-
-
Notifications
You must be signed in to change notification settings - Fork 32.4k
/
Copy pathDemo.js
772 lines (720 loc) · 25.3 KB
/
Demo.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
import * as React from 'react';
import PropTypes from 'prop-types';
import copy from 'clipboard-copy';
import { useRouter } from 'next/router';
import { debounce } from '@mui/material/utils';
import { alpha, styled } from '@mui/material/styles';
import { styled as joyStyled } from '@mui/joy/styles';
import { Tabs } from '@mui/base/Tabs';
import { TabPanel } from '@mui/base/TabPanel';
import { unstable_useId as useId } from '@mui/utils';
import IconButton from '@mui/material/IconButton';
import Box from '@mui/material/Box';
import Collapse from '@mui/material/Collapse';
import NoSsr from '@mui/material/NoSsr';
import { HighlightedCode } from '@mui/docs/HighlightedCode';
import { CodeTab, CodeTabList } from '@mui/docs/HighlightedCodeWithTabs';
import ContentCopyRoundedIcon from '@mui/icons-material/ContentCopyRounded';
import LibraryAddCheckRoundedIcon from '@mui/icons-material/LibraryAddCheckRounded';
import DemoSandbox from 'docs/src/modules/components/DemoSandbox';
import ReactRunner from 'docs/src/modules/components/ReactRunner';
import DemoEditor from 'docs/src/modules/components/DemoEditor';
import DemoEditorError from 'docs/src/modules/components/DemoEditorError';
import { pathnameToLanguage } from 'docs/src/modules/utils/helpers';
import { useCodeVariant } from 'docs/src/modules/utils/codeVariant';
import { useCodeStyling } from 'docs/src/modules/utils/codeStylingSolution';
import { CODE_VARIANTS, CODE_STYLING } from 'docs/src/modules/constants';
import { useUserLanguage, useTranslate } from '@mui/docs/i18n';
import stylingSolutionMapping from 'docs/src/modules/utils/stylingSolutionMapping';
import DemoToolbarRoot from 'docs/src/modules/components/DemoToolbarRoot';
import { AdCarbonInline } from '@mui/docs/Ad';
import { BrandingProvider, blue, blueDark, grey } from '@mui/docs/branding';
/**
* Removes leading spaces (indentation) present in the `.tsx` previews
* to be able to replace the existing code with the incoming dynamic code
* @param {string} input
*/
function trimLeadingSpaces(input = '') {
return input.replace(/^\s+/gm, '');
}
const DemoToolbar = React.lazy(() => import('./DemoToolbar'));
function DemoToolbarFallback() {
const t = useTranslate();
// Sync with styles from DemoToolbar, we can't import the styles
return <Box sx={{ height: 42 }} aria-busy aria-label={t('demoToolbarLabel')} role="toolbar" />;
}
function getDemoName(location) {
return location.endsWith('.js') || location.endsWith('.tsx')
? location.replace(/(.+?)(\w+)\.\w+$$/, '$2')
: // the demos with multiple styling solution point to directory
location.split('/').pop();
}
function useDemoData(codeVariant, demo, githubLocation, codeStyling) {
const userLanguage = useUserLanguage();
const router = useRouter();
const { canonicalAs } = pathnameToLanguage(router.asPath);
return React.useMemo(() => {
let productId;
let name = 'Material UI';
if (canonicalAs.startsWith('/joy-ui/')) {
productId = 'joy-ui';
name = 'Joy UI';
} else if (canonicalAs.startsWith('/base-ui/')) {
productId = 'base-ui';
name = 'Base UI';
} else if (canonicalAs.startsWith('/x/')) {
name = 'MUI X';
}
let codeOptions = {};
if (codeStyling === CODE_STYLING.SYSTEM) {
if (codeVariant === CODE_VARIANTS.TS && demo.rawTS) {
codeOptions = {
codeVariant: CODE_VARIANTS.TS,
githubLocation: githubLocation.replace(/\.js$/, '.tsx'),
raw: demo.rawTS,
module: demo.moduleTS,
Component: demo.tsx ?? null,
sourceLanguage: 'tsx',
};
if (demo.relativeModules) {
codeOptions.relativeModules = demo.relativeModules[CODE_VARIANTS.TS];
}
} else {
codeOptions = {
codeVariant: CODE_VARIANTS.JS,
githubLocation,
raw: demo.raw,
module: demo.module,
Component: demo.js,
sourceLanguage: 'jsx',
};
if (demo.relativeModules) {
codeOptions.relativeModules = demo.relativeModules[CODE_VARIANTS.JS];
}
}
} else if (codeStyling === CODE_STYLING.TAILWIND) {
if (codeVariant === CODE_VARIANTS.TS && demo.rawTailwindTS) {
codeOptions = {
codeVariant: CODE_VARIANTS.TS,
githubLocation: githubLocation.replace(/\/system\/index\.js$/, '/tailwind/index.tsx'),
raw: demo.rawTailwindTS,
module: demo.moduleTS,
Component: demo.tsxTailwind,
sourceLanguage: 'tsx',
};
} else {
codeOptions = {
codeVariant: CODE_VARIANTS.JS,
githubLocation: githubLocation.replace(/\/system\/index\.js$/, '/tailwind/index.js'),
raw: demo.rawTailwind ?? demo.raw,
module: demo.module,
Component: demo.jsTailwind ?? demo.js,
sourceLanguage: 'jsx',
};
}
} else if (codeStyling === CODE_STYLING.CSS) {
if (codeVariant === CODE_VARIANTS.TS && demo.rawCSSTS) {
codeOptions = {
codeVariant: CODE_VARIANTS.TS,
githubLocation: githubLocation.replace(/\/system\/index\.js$/, '/css/index.tsx'),
raw: demo.rawCSSTS,
module: demo.moduleTS,
Component: demo.tsxCSS,
sourceLanguage: 'tsx',
};
} else {
codeOptions = {
codeVariant: CODE_VARIANTS.JS,
githubLocation: githubLocation.replace(/\/system\/index\.js$/, '/css/index.js'),
raw: demo.rawCSS ?? demo.raw,
module: demo.module,
Component: demo.jsCSS ?? demo.js,
sourceLanguage: 'jsx',
};
}
}
let jsxPreview = demo.jsxPreview;
if (codeStyling === CODE_STYLING.TAILWIND && demo.tailwindJsxPreview) {
jsxPreview = demo.tailwindJsxPreview;
} else if (codeStyling === CODE_STYLING.CSS && demo.cssJsxPreview) {
jsxPreview = demo.cssJsxPreview;
}
return {
scope: demo.scope,
jsxPreview,
...codeOptions,
title: `${getDemoName(githubLocation)} demo — ${name}`,
productId,
language: userLanguage,
codeStyling,
};
}, [canonicalAs, codeVariant, demo, githubLocation, userLanguage, codeStyling]);
}
function useDemoElement({ demoData, editorCode, setDebouncedError, liveDemoActive }) {
const debouncedSetError = React.useMemo(
() => debounce(setDebouncedError, 300),
[setDebouncedError],
);
React.useEffect(() => {
return () => {
debouncedSetError.clear();
};
}, [debouncedSetError]);
// Memoize to avoid rendering the demo more than it needs to be.
// For example, avoid a render when the demo is hovered.
const BundledComponent = React.useMemo(() => <demoData.Component />, [demoData]);
const LiveComponent = React.useMemo(
() => (
<ReactRunner
scope={demoData.scope}
onError={debouncedSetError}
code={
editorCode.isPreview
? trimLeadingSpaces(demoData.raw).replace(
trimLeadingSpaces(demoData.jsxPreview),
editorCode.value,
)
: editorCode.value
}
/>
),
[demoData, debouncedSetError, editorCode.isPreview, editorCode.value],
);
// No need for a live environment if the code matches with the component rendered server-side.
return editorCode.value === editorCode.initialEditorCode && liveDemoActive === false
? BundledComponent
: LiveComponent;
}
const Root = styled('div')(({ theme }) => ({
marginBottom: 24,
marginLeft: theme.spacing(-2),
marginRight: theme.spacing(-2),
[theme.breakpoints.up('sm')]: {
marginLeft: 0,
marginRight: 0,
},
}));
const DemoRootMaterial = styled('div', {
shouldForwardProp: (prop) => prop !== 'hideToolbar' && prop !== 'bg',
})(({ theme }) => ({
position: 'relative',
margin: 'auto',
display: 'flex',
justifyContent: 'center',
variants: [
{
props: ({ hideToolbar }) => hideToolbar,
style: {
[theme.breakpoints.up('sm')]: {
borderRadius: 12,
},
},
},
{
props: ({ hideToolbar }) => !hideToolbar,
style: {
[theme.breakpoints.up('sm')]: {
borderRadius: '12px 12px 0 0',
},
},
},
{
props: {
bg: 'outlined',
},
style: {
[theme.breakpoints.up('sm')]: {
borderLeftWidth: 1,
borderRightWidth: 1,
},
},
},
{
props: {
bg: 'inline',
},
style: {
[theme.breakpoints.up('sm')]: {
padding: theme.spacing(0),
},
},
},
{
props: {
bg: 'gradient',
},
style: {
[theme.breakpoints.up('sm')]: {
padding: theme.spacing(12, 8),
borderLeftWidth: 1,
borderRightWidth: 1,
},
},
},
{
props: {
bg: 'outlined',
},
style: {
padding: theme.spacing(3),
backgroundColor: (theme.vars || theme).palette.background.paper,
border: `1px solid ${(theme.vars || theme).palette.divider}`,
borderLeftWidth: 0,
borderRightWidth: 0,
...theme.applyDarkStyles({
backgroundColor: alpha(theme.palette.primaryDark[700], 0.1),
}),
},
},
{
props: {
bg: 'playground',
},
style: {
backgroundColor: (theme.vars || theme).palette.background.paper,
border: `1px solid ${(theme.vars || theme).palette.divider}`,
overflow: 'auto',
},
},
{
props: {
bg: true,
},
style: {
padding: theme.spacing(3),
backgroundColor: alpha(theme.palette.grey[50], 0.5),
border: `1px solid ${(theme.vars || theme).palette.divider}`,
...theme.applyDarkStyles({
backgroundColor: alpha(theme.palette.primaryDark[700], 0.4),
}),
},
},
{
props: {
bg: 'gradient',
},
style: {
overflow: 'auto',
padding: theme.spacing(4, 2),
border: `1px solid ${(theme.vars || theme).palette.divider}`,
borderLeftWidth: 0,
borderRightWidth: 0,
backgroundClip: 'padding-box',
backgroundColor: alpha(theme.palette.primary[50], 0.2),
backgroundImage: `radial-gradient(120% 140% at 50% 10%, transparent 40%, ${alpha(theme.palette.primary[100], 0.2)} 70%)`,
...theme.applyDarkStyles({
backgroundColor: (theme.vars || theme).palette.primaryDark[900],
backgroundImage: `radial-gradient(120% 140% at 50% 10%, transparent 30%, ${alpha(theme.palette.primary[900], 0.3)} 80%)`,
}),
},
},
],
}));
const DemoRootJoy = joyStyled('div', {
shouldForwardProp: (prop) => prop !== 'hideToolbar' && prop !== 'bg',
})(({ theme, hideToolbar, bg }) => ({
position: 'relative',
margin: 'auto',
display: 'flex',
justifyContent: 'center',
[theme.breakpoints.up('sm')]: {
borderRadius: hideToolbar ? 12 : '12px 12px 0 0',
...(bg === 'outlined' && {
borderLeftWidth: 1,
borderRightWidth: 1,
}),
/* Make no difference between the demo and the markdown. */
...(bg === 'inline' && {
padding: theme.spacing(0),
}),
},
/* Isolate the demo with an outline. */
...(bg === 'outlined' && {
padding: theme.spacing(3),
border: `1px solid`,
borderColor: grey[100],
borderLeftWidth: 0,
borderRightWidth: 0,
backgroundColor: 'transparent',
...theme.applyDarkStyles({
borderColor: alpha(blueDark[500], 0.3),
backgroundColor: alpha(theme.palette.neutral[900], 0.8),
}),
}),
/* Prepare the background to display an inner elevation. */
...(bg === true && {
padding: theme.spacing(3),
backgroundColor: theme.vars.palette.background.level2,
}),
/* Mostly meant for introduction demos. */
...(bg === 'gradient' && {
[theme.breakpoints.up('sm')]: {
borderRadius: 12,
},
borderRadius: 0,
padding: theme.spacing(0),
overflow: 'auto',
backgroundColor: alpha(blue[50], 0.5),
border: `1px solid`,
borderColor: grey[100],
backgroundImage: `radial-gradient(at 51% 52%, ${alpha(blue[50], 0.5)} 0px, transparent 50%),
radial-gradient(at 80% 0%, #FFFFFF 0px, transparent 20%),
radial-gradient(at 0% 95%, ${alpha(blue[100], 0.3)}, transparent 40%),
radial-gradient(at 0% 20%, ${blue[50]} 0px, transparent 50%),
radial-gradient(at 93% 85%, ${alpha(blue[100], 0.2)} 0px, transparent 50%);`,
...theme.applyDarkStyles({
backgroundColor: alpha(blue[900], 0.1),
borderColor: alpha(blueDark[700], 1),
backgroundImage: `radial-gradient(at 51% 52%, ${alpha(
blueDark[700],
0.5,
)} 0px, transparent 50%),
radial-gradient(at 80% 0%, ${alpha(blue[900], 0.3)} 0px, transparent 50%),
radial-gradient(at 0% 95%, ${alpha(blue[900], 0.5)} 0px, transparent 50%),
radial-gradient(at 0% 5%, ${alpha(blue[900], 0.5)} 0px, transparent 35%),
radial-gradient(at 93% 85%, ${alpha(blue[900], 0.3)} 0px, transparent 50%);`,
}),
}),
}));
const DemoCodeViewer = styled(HighlightedCode)(() => ({
'& pre': {
margin: 0,
marginTop: -1,
maxHeight: 'min(68vh, 1000px)',
maxWidth: 'initial',
borderRadius: 0,
borderBottomLeftRadius: 12,
borderBottomRightRadius: 12,
},
}));
const AnchorLink = styled('div')({
marginTop: -64, // height of toolbar
position: 'absolute',
});
const InitialFocus = styled(IconButton)(({ theme }) => ({
position: 'absolute',
top: 0,
left: 0,
width: theme.spacing(4),
height: theme.spacing(4),
pointerEvents: 'none',
}));
const selectionOverride = (theme) => ({
cursor: 'pointer',
'&.base--selected': {
color: (theme.vars || theme).palette.primary[700],
backgroundColor: (theme.vars || theme).palette.primary[50],
borderColor: (theme.vars || theme).palette.primary[200],
...theme.applyDarkStyles({
color: (theme.vars || theme).palette.primary[200],
backgroundColor: alpha(theme.palette.primary[900], 0.4),
borderColor: (theme.vars || theme).palette.primary[800],
}),
},
});
export default function Demo(props) {
const { demo, demoOptions, disableAd, githubLocation, mode } = props;
if (process.env.NODE_ENV !== 'production') {
if (demoOptions.hideToolbar === false) {
throw new Error(
[
'"hideToolbar": false is already the default.',
`Please remove the property in {{"demo": "${demoOptions.demo}", …}}.`,
].join('\n'),
);
}
if (demoOptions.hideToolbar === true && demoOptions.defaultCodeOpen === true) {
throw new Error(
[
'"hideToolbar": true, "defaultCodeOpen": true combination is invalid.',
`Please remove one of the properties in {{"demo": "${demoOptions.demo}", …}}.`,
].join('\n'),
);
}
if (demoOptions.hideToolbar === true && demoOptions.disableAd === true) {
throw new Error(
[
'"hideToolbar": true, "disableAd": true combination is invalid.',
`Please remove one of the properties in {{"demo": "${demoOptions.demo}", …}}.`,
].join('\n'),
);
}
}
if (
(demoOptions.demo.endsWith('.ts') || demoOptions.demo.endsWith('.tsx')) &&
demoOptions.hideToolbar !== true
) {
throw new Error(
[
`The following demos use TS directly: ${demoOptions.demo}.`,
'',
'Please run "pnpm docs:typescript:formatted" to generate a JS version and reference it:',
// This regex intentionally excludes the dot character in the Kleene star to prevent ReDoS
// See https://github.com/mui/material-ui/issues/44078
`{{"demo": "${demoOptions.demo.replace(/\.([^.]*)$/, '.js')}", …}}.`,
'',
"Otherwise, if it's not a code demo hide the toolbar:",
`{{"demo": "${demoOptions.demo}", "hideToolbar": true, …}}.`,
].join('\n'),
);
}
const t = useTranslate();
const codeVariant = useCodeVariant();
const styleSolution = useCodeStyling();
const demoData = useDemoData(codeVariant, demo, githubLocation, styleSolution);
const hasNonSystemDemos = demo.rawTailwind || demo.rawTailwindTS || demo.rawCSS || demo.rawCSSTs;
const demoName = getDemoName(demoData.githubLocation);
const demoSandboxedStyle = React.useMemo(
() => ({
maxWidth: demoOptions.maxWidth,
height: demoOptions.height,
}),
[demoOptions.height, demoOptions.maxWidth],
);
if (demoOptions.bg == null) {
demoOptions.bg = 'outlined';
if (demoOptions.iframe) {
demoOptions.bg = true;
}
}
const [codeOpen, setCodeOpen] = React.useState(demoOptions.defaultCodeOpen || false);
const shownOnce = React.useRef(false);
if (codeOpen) {
shownOnce.current = true;
}
React.useEffect(() => {
const navigatedDemoName = getDemoName(window.location.hash);
if (navigatedDemoName && demoName === navigatedDemoName) {
setCodeOpen(true);
}
}, [demoName]);
const showPreview =
!demoOptions.hideToolbar &&
demoOptions.defaultCodeOpen !== false &&
Boolean(demoData.jsxPreview);
const [demoKey, setDemoKey] = React.useReducer((key) => key + 1, 0);
const demoId = `demo-${useId()}`;
const demoSourceId = `demoSource-${useId()}`;
const openDemoSource = codeOpen || showPreview;
const initialFocusRef = React.useRef(null);
const [showAd, setShowAd] = React.useState(false);
const adVisibility = showAd && !disableAd && !demoOptions.disableAd;
const DemoRoot = demoData.productId === 'joy-ui' ? DemoRootJoy : DemoRootMaterial;
const Wrapper = demoData.productId === 'joy-ui' ? BrandingProvider : React.Fragment;
const isPreview = !codeOpen && showPreview;
const initialEditorCode = isPreview
? demoData.jsxPreview
: // Prettier remove all the leading lines except for the last one, remove it as we don't
// need it in the live edit view.
demoData.raw.replace(/\n$/, '');
const [editorCode, setEditorCode] = React.useState({
value: initialEditorCode,
isPreview,
initialEditorCode,
});
const resetDemo = React.useMemo(
() => () => {
setEditorCode({
value: initialEditorCode,
isPreview,
initialEditorCode,
});
setDemoKey();
},
[setEditorCode, setDemoKey, initialEditorCode, isPreview],
);
React.useEffect(() => {
setEditorCode({
value: initialEditorCode,
isPreview,
initialEditorCode,
});
}, [initialEditorCode, isPreview]);
const [debouncedError, setDebouncedError] = React.useState(null);
const [liveDemoActive, setLiveDemoActive] = React.useState(false);
const demoElement = useDemoElement({
demoData,
editorCode,
setDebouncedError,
liveDemoActive,
});
const [activeTab, setActiveTab] = React.useState(0);
const handleTabChange = (event, newValue) => {
setActiveTab(newValue);
};
const ownerState = { mounted: true, contained: true };
const tabs = React.useMemo(() => {
if (!demoData.relativeModules) {
return [{ module: demoData.module, raw: demoData.raw }];
}
let demoModule = demoData.module;
if (codeVariant === CODE_VARIANTS.TS && demo.moduleTS) {
demoModule =
demo.moduleTS === demo.module ? demoData.module.replace(/\.js$/, '.tsx') : demo.moduleTS;
}
return [{ module: demoModule, raw: demoData.raw }, ...demoData.relativeModules];
}, [
codeVariant,
demo.moduleTS,
demo.module,
demoData.module,
demoData.raw,
demoData.relativeModules,
]);
const [copiedContent, setCopiedContent] = React.useState(false);
const handleCopyClick = async () => {
try {
const activeTabData = tabs[activeTab];
await copy(activeTabData.raw);
setCopiedContent(true);
setTimeout(() => {
setCopiedContent(false);
}, 1000);
} catch (error) {
console.error('Code content not copied', error);
}
};
return (
<Root>
<AnchorLink id={demoName} />
<DemoRoot hideToolbar={demoOptions.hideToolbar} bg={demoOptions.bg} id={demoId}>
<Wrapper {...(demoData.productId === 'joy-ui' && { mode })}>
<InitialFocus
aria-label={t('initialFocusLabel')}
action={initialFocusRef}
tabIndex={-1}
/>
</Wrapper>
<DemoSandbox
key={demoKey}
style={demoSandboxedStyle}
iframe={demoOptions.iframe}
usesCssVarsTheme={demoData.productId === 'joy-ui'}
name={demoName}
onResetDemoClick={resetDemo}
>
{demoElement}
</DemoSandbox>
</DemoRoot>
{/* TODO: Wrapper shouldn't be needed, it should already be at the top of the docs page */}
{demoOptions.hideToolbar ? null : (
<Wrapper {...(demoData.productId === 'joy-ui' ? { mode } : {})}>
{Object.keys(stylingSolutionMapping).map((key) => (
<React.Fragment key={key}>
<AnchorLink id={`${stylingSolutionMapping[key]}-${demoName}.js`} />
<AnchorLink id={`${stylingSolutionMapping[key]}-${demoName}.tsx`} />
</React.Fragment>
))}
<AnchorLink id={`${demoName}.js`} />
<AnchorLink id={`${demoName}.tsx`} />
<DemoToolbarRoot demoOptions={demoOptions} openDemoSource={openDemoSource}>
<NoSsr fallback={<DemoToolbarFallback />}>
<React.Suspense fallback={<DemoToolbarFallback />}>
<DemoToolbar
codeOpen={codeOpen}
codeVariant={codeVariant}
copyIcon={
copiedContent ? <LibraryAddCheckRoundedIcon /> : <ContentCopyRoundedIcon />
}
copyButtonOnClick={handleCopyClick}
hasNonSystemDemos={hasNonSystemDemos}
demo={demo}
demoData={demoData}
demoId={demoId}
demoName={demoName}
demoOptions={demoOptions}
demoSourceId={demoSourceId}
initialFocusRef={initialFocusRef}
onCodeOpenChange={() => {
setCodeOpen((open) => !open);
setShowAd(true);
}}
onResetDemoClick={resetDemo}
openDemoSource={openDemoSource}
showPreview={showPreview}
/>
</React.Suspense>
</NoSsr>
</DemoToolbarRoot>
<Tabs value={activeTab} onChange={handleTabChange}>
{demoData.relativeModules && openDemoSource && !editorCode.isPreview ? (
<CodeTabList ownerState={ownerState}>
{tabs.map((tab, index) => (
<CodeTab
sx={selectionOverride}
ownerState={ownerState}
key={tab.module}
value={index}
>
{tab.module}
</CodeTab>
))}
</CodeTabList>
) : null}
<Collapse in={openDemoSource} unmountOnExit timeout={150}>
{/* A limitation from https://github.com/nihgwu/react-runner,
we can't inject the `window` of the iframe so we need a disableLiveEdit option. */}
{tabs.map((tab, index) => (
<TabPanel value={index} index={index} key={index}>
{demoOptions.disableLiveEdit || index > 0 ? (
<DemoCodeViewer
key={index}
code={tab.raw}
id={demoSourceId}
language={demoData.sourceLanguage}
copyButtonProps={{
'data-ga-event-category': codeOpen ? 'demo-expand' : 'demo',
'data-ga-event-label': demo.gaLabel,
'data-ga-event-action': 'copy-click',
}}
sx={{
'& .MuiCode-copy': {
display: 'none',
},
}}
/>
) : (
<DemoEditor
// Mount a new text editor when the preview mode change to reset the undo/redo history.
key={editorCode.isPreview}
value={editorCode.value}
onChange={(value) => {
setEditorCode({
...editorCode,
value,
});
}}
onFocus={() => {
setLiveDemoActive(true);
}}
id={demoSourceId}
language={demoData.sourceLanguage}
copyButtonProps={{
'data-ga-event-category': codeOpen ? 'demo-expand' : 'demo',
'data-ga-event-label': demo.gaLabel,
'data-ga-event-action': 'copy-click',
}}
>
<DemoEditorError>{debouncedError}</DemoEditorError>
</DemoEditor>
)}
</TabPanel>
))}
</Collapse>
</Tabs>
{adVisibility ? <AdCarbonInline /> : null}
</Wrapper>
)}
</Root>
);
}
Demo.propTypes = {
demo: PropTypes.object.isRequired,
/**
* The options provided with: {{"demo": "Name.js", …demoOptions}}
*/
demoOptions: PropTypes.object.isRequired,
disableAd: PropTypes.bool.isRequired,
githubLocation: PropTypes.string.isRequired,
mode: PropTypes.string, // temporary, just to make Joy docs work.
};