Skip to content

Commit a152f7a

Browse files
authored
[docs-infra] Fix migrated demo integration
Fix core-docs integration for demos using `@mui/internal-docs-infra`. - Preserve sandbox dependency/import hooks and demo metadata - Render toolbar controls in SSR; retain previews while controls load - Share nested frame ownership and defer editing engines until interaction - Omit hidden language buttons; measure navigation only when visible - Mount menus/copy feedback on first use; retain closing/focus behavior - Remove unused legacy rendering and document Next transpilation - Prebundle browser-test dependencies to prevent optimizer reloads Use published docs-infra `0.13.1-canary.33` from mui/mui-public#2052. No package patch or path alias. Pre-rebase validation: all 20 CI checks passed at `4c22b160b6`, including browser, legacy browser, website, types, lint and docs deployment. Local core-docs suites pass (112 Node, 110 Chromium), with real Button/Charts menu, copy, editor/reset and preview-retention checks. Dependency checks and 348 Autocomplete tests pass after merging master `fe03845dd1`. November 13 deployed Button comparison (measured revisions retained below): ten accepted alternating mobile Lighthouse pairs, Chrome 156/Lighthouse 13.4.1, 4× simulated CPU. Master `212e2e351f` versus preview `4c22b160b6`: | Metric | Master median | Preview median | |---|---:|---:| | Performance | 80.5 | 81.5 | | LCP | 2,748ms | 2,729ms | | TBT | 603ms | 510ms | | Main-thread work | 3,162ms | 2,810ms | | CLS | 0 | 0 | TBT and main-thread work improve in all ten pairs; median paired reductions are 91ms and 331ms. LCP improves in six pairs and remains variable. HTML shrinks 17.9KB (994B gzip). Rebased onto master `93eb0653d4`; head `02097fb7f8`. Existing runtime patches are unchanged. Master already includes docs-infra canary.33, so two superseded dependency-pin commits were dropped. Frozen install, dedupe, types, lint, 7,019 Node tests and 6,789 browser tests pass. Browser tests use the repository CI flags (`--no-isolate --no-file-parallelism`); the default parallel run hit the previously seen setup-import failure in five suites. CI and deployment must rerun after pushing. Merge preparation: combine master’s React 17 test exclusion with the docs-infra prebundle. Fix navigation scroll-test queries for CSS-hidden jsdom fixtures while retaining measurement and restoration assertions. Runtime behavior is unchanged. Local checks pass: 7,027 Node tests, 110 core-docs browser tests, focused ESLint and formatting. Admin merge and internal-package publication requested.
1 parent 422ac96 commit a152f7a

21 files changed

Lines changed: 1276 additions & 465 deletions

‎packages-internal/core-docs/README.md‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,13 @@ npm install @mui/material@next
2323

2424
## Documentation
2525

26-
We have no documentation for these components.
26+
### Next.js consumers
27+
28+
Transpile core-docs for its Next.js module imports.
29+
DocSearch also needs transpilation for its CommonJS autocomplete dependency during SSR.
30+
31+
```js
32+
export default {
33+
transpilePackages: ['@mui/internal-core-docs', '@docsearch/react'],
34+
};
35+
```

‎packages-internal/core-docs/package.json‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,8 @@
8484
},
8585
"exports": {
8686
"./*": "./src/*/index.ts",
87-
"./ApiPage/private": "./src/ApiPage/private.ts"
87+
"./ApiPage/private": "./src/ApiPage/private.ts",
88+
"./utils/createDemo": "./src/utils/createDemo.tsx",
89+
"./utils/createDemoClient": "./src/utils/createDemoClient.ts"
8890
}
8991
}
Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2+
import * as React from 'react';
3+
import { createRenderer, isJsdom, screen } from '@mui/internal-test-utils';
4+
import { ThemeProvider } from '@mui/material/styles';
5+
import PageContext from '../../PageContext';
6+
import type { MuiPageContext } from '../../PageContext';
7+
import { brandingLightTheme } from '../../branding';
8+
import { UserLanguageProvider } from '../../i18n';
9+
import { AppNavDrawer } from './AppNavDrawer';
10+
11+
vi.hoisted(() => vi.resetModules());
12+
vi.mock('next/router', () => ({
13+
useRouter: () => ({ pathname: '/example/', asPath: '/example/' }),
14+
}));
15+
16+
const noop = () => {};
17+
const MOBILE_WIDTH = 412;
18+
const DESKTOP_WIDTH = 1280;
19+
const SAVED_SCROLL_TOP = 64;
20+
const desktopQuery = brandingLightTheme.breakpoints.up('lg').replace('@media ', '');
21+
const mobileQuery = brandingLightTheme.breakpoints.down('lg').replace('@media ', '');
22+
const activePage = { pathname: '/example/', title: 'Example' };
23+
const pageContext: MuiPageContext = {
24+
activePage,
25+
activePageParents: [activePage],
26+
pages: [activePage],
27+
productId: 'material-ui',
28+
productCategoryId: 'core',
29+
productIdentifier: { name: 'Material UI', metadata: '', versions: [] },
30+
};
31+
const scrollDescriptor = Object.getOwnPropertyDescriptor(Element.prototype, 'scrollIntoView');
32+
const measure = vi.fn();
33+
const scroll = vi.fn();
34+
let viewportWidth = MOBILE_WIDTH;
35+
36+
function LayoutProbe({ onLayout }: { onLayout?: () => void }) {
37+
React.useLayoutEffect(() => {
38+
onLayout?.();
39+
}, [onLayout]);
40+
return null;
41+
}
42+
43+
function drawer(open: 'closed' | 'open' = 'closed', onLayout?: () => void) {
44+
return (
45+
<UserLanguageProvider defaultUserLanguage="en">
46+
<ThemeProvider theme={brandingLightTheme}>
47+
<PageContext.Provider value={pageContext}>
48+
<AppNavDrawer
49+
disablePermanent={false}
50+
mobileOpen={open === 'open'}
51+
onClose={noop}
52+
onOpen={noop}
53+
/>
54+
<LayoutProbe onLayout={onLayout} />
55+
</PageContext.Provider>
56+
</ThemeProvider>
57+
</UserLanguageProvider>
58+
);
59+
}
60+
61+
beforeEach(() => {
62+
const queries = new Map<string, MediaQueryList>();
63+
vi.stubGlobal('matchMedia', (query: string) => {
64+
if (!queries.has(query)) {
65+
queries.set(query, {
66+
matches:
67+
query === desktopQuery
68+
? viewportWidth >= brandingLightTheme.breakpoints.values.lg
69+
: query === mobileQuery && viewportWidth < brandingLightTheme.breakpoints.values.lg,
70+
media: query,
71+
onchange: null,
72+
addEventListener: noop,
73+
removeEventListener: noop,
74+
addListener: noop,
75+
removeListener: noop,
76+
dispatchEvent: () => true,
77+
});
78+
}
79+
return queries.get(query);
80+
});
81+
const getRect = Element.prototype.getBoundingClientRect;
82+
vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function getRectMock(
83+
this: Element,
84+
) {
85+
if (this.classList.contains('app-drawer-active')) {
86+
measure();
87+
return {
88+
x: 0,
89+
y: -20,
90+
top: -20,
91+
bottom: 0,
92+
left: 0,
93+
right: 20,
94+
width: 20,
95+
height: 20,
96+
toJSON: noop,
97+
};
98+
}
99+
return getRect.call(this);
100+
});
101+
Object.defineProperty(Element.prototype, 'scrollIntoView', {
102+
configurable: true,
103+
value(this: Element) {
104+
if (this.classList.contains('app-drawer-active')) {
105+
scroll();
106+
}
107+
},
108+
});
109+
});
110+
111+
afterEach(() => {
112+
vi.restoreAllMocks();
113+
vi.unstubAllGlobals();
114+
measure.mockClear();
115+
scroll.mockClear();
116+
if (scrollDescriptor) {
117+
Object.defineProperty(Element.prototype, 'scrollIntoView', scrollDescriptor);
118+
} else {
119+
Reflect.deleteProperty(Element.prototype, 'scrollIntoView');
120+
}
121+
});
122+
afterAll(() => vi.resetModules());
123+
124+
describe.skipIf(!isJsdom())('AppNavDrawer scroll restoration', () => {
125+
const { render, renderToString } = createRenderer();
126+
127+
it('waits until a closed mobile drawer opens before measuring the active link', () => {
128+
viewportWidth = MOBILE_WIDTH;
129+
const { hydrate } = renderToString(drawer());
130+
const { rerender } = hydrate();
131+
132+
expect(measure).not.toHaveBeenCalled();
133+
expect(scroll).not.toHaveBeenCalled();
134+
135+
rerender(drawer('open'));
136+
137+
expect(measure).toHaveBeenCalled();
138+
expect(scroll).toHaveBeenCalled();
139+
});
140+
141+
it('restores desktop scrolling and keeps the active link visible', () => {
142+
viewportWidth = DESKTOP_WIDTH;
143+
const layoutReads = vi.fn();
144+
const matchMedia = window.matchMedia;
145+
vi.stubGlobal('matchMedia', undefined);
146+
const { hydrate } = renderToString(
147+
drawer('closed', () => layoutReads(measure.mock.calls.length)),
148+
);
149+
vi.stubGlobal('matchMedia', matchMedia);
150+
const { unmount } = hydrate();
151+
152+
expect(layoutReads.mock.calls[0][0]).toBeGreaterThan(0);
153+
154+
const link = screen.getByRole('link', { name: 'Example', hidden: true });
155+
const scroller = link.closest('ul')!.parentElement!.parentElement!;
156+
scroller.scrollTop = SAVED_SCROLL_TOP;
157+
unmount();
158+
measure.mockClear();
159+
scroll.mockClear();
160+
161+
render(drawer());
162+
163+
const restored = screen.getByRole('link', { name: 'Example', hidden: true }).closest('ul')!
164+
.parentElement!.parentElement!;
165+
expect(restored.scrollTop).toBe(SAVED_SCROLL_TOP);
166+
expect(measure).toHaveBeenCalled();
167+
expect(scroll).toHaveBeenCalled();
168+
});
169+
});

‎packages-internal/core-docs/src/AppLayout/navigation/AppNavDrawer.tsx‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -184,10 +184,14 @@ function PersistScroll(props: PersistScrollProps) {
184184
const rootRef = React.useRef<HTMLDivElement>(null);
185185

186186
useEnhancedEffect(() => {
187+
if (!enabled) {
188+
return undefined;
189+
}
190+
187191
const scrollContainer = rootRef.current ? rootRef.current.parentElement : null;
188192
const activeDrawerLink = scrollContainer?.querySelector('.app-drawer-active');
189193

190-
if (!enabled || !scrollContainer || !activeDrawerLink || !activeDrawerLink.scrollIntoView) {
194+
if (!scrollContainer || !activeDrawerLink || !activeDrawerLink.scrollIntoView) {
191195
return undefined;
192196
}
193197

@@ -369,7 +373,9 @@ export function AppNavDrawer(props: AppNavDrawerProps) {
369373
const [anchorEl, setAnchorEl] = React.useState<HTMLButtonElement | null>(null);
370374
const t = useTranslate();
371375
const mobile = useMediaQuery((theme) => theme.breakpoints.down('lg'));
376+
const desktop = useMediaQuery((theme) => theme.breakpoints.up('lg'), { noSsr: true });
372377
const swipeableDrawer = disablePermanent || mobile;
378+
const scrollEnabled = swipeableDrawer ? mobileOpen : desktop;
373379

374380
const drawer = React.useMemo(() => {
375381
const navItems = renderNavItems({ onClose, pages, activePageParents, depth: 0, t });
@@ -474,14 +480,23 @@ export function AppNavDrawer(props: AppNavDrawerProps) {
474480
scrollbarWidth: 'thin',
475481
}}
476482
>
477-
<PersistScroll slot="side" enabled>
483+
<PersistScroll slot="side" enabled={scrollEnabled}>
478484
{navItems}
479485
</PersistScroll>
480486
</Box>
481487
</Box>
482488
</React.Fragment>
483489
);
484-
}, [onClose, pages, activePageParents, t, productIdentifier, anchorEl, swipeableDrawer]);
490+
}, [
491+
onClose,
492+
pages,
493+
activePageParents,
494+
t,
495+
productIdentifier,
496+
anchorEl,
497+
swipeableDrawer,
498+
scrollEnabled,
499+
]);
485500

486501
// Guard with NEXT_RUNTIME so this check is dead-code-eliminated from client bundles.
487502
if (process.env.NEXT_RUNTIME) {

‎packages-internal/core-docs/src/DemoContent/DemoContainer.test.tsx‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,32 @@ function StatefulDemo() {
3333
describe('DemoContainer', () => {
3434
const { render } = createRenderer();
3535

36+
it('does not rerender an isolated preview when its toolbar changes', () => {
37+
let calls = 0;
38+
function Demo() {
39+
calls += 1;
40+
return <span>Preview</span>;
41+
}
42+
const preview = <Demo />;
43+
44+
function view(label: string) {
45+
return (
46+
<UserLanguageProvider defaultUserLanguage="en">
47+
<ThemeProvider theme={brandingLightTheme}>
48+
<DemoContainer isolated preview={preview} toolbar={<span>{label}</span>} />
49+
</ThemeProvider>
50+
</UserLanguageProvider>
51+
);
52+
}
53+
54+
const { rerender } = render(view('First'));
55+
const initialCalls = calls;
56+
rerender(view('Second'));
57+
58+
expect(screen.getByText('Second')).not.to.equal(null);
59+
expect(calls).to.equal(initialCalls);
60+
});
61+
3662
// Regression: the error boundary used to sit between `DemoComponentTheme` and
3763
// the demo, so the `cloneElement` that injects the isolation props targeted the
3864
// error boundary (which renders `children` verbatim) and the demo never saw

‎packages-internal/core-docs/src/DemoContent/DemoContainer.tsx‎

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -615,17 +615,20 @@ export function DemoContainer(props: DemoContainerProps) {
615615
// demo element directly, while the live `DemoContent` and the SSR
616616
// `DemoContentLoading` skeleton still share the exact same theming.
617617
const themedName = name ?? 'demo';
618-
const themedPreview = (
619-
<DemoErrorBoundary key={previewEpoch} name={themedName} onReset={onReset}>
620-
<DemoComponentTheme
621-
isolated={isolated}
622-
iframe={iframe}
623-
iframeStyle={iframe ? previewStyle : undefined}
624-
name={themedName}
625-
>
626-
{preview}
627-
</DemoComponentTheme>
628-
</DemoErrorBoundary>
618+
const themedPreview = React.useMemo(
619+
() => (
620+
<DemoErrorBoundary key={previewEpoch} name={themedName} onReset={onReset}>
621+
<DemoComponentTheme
622+
isolated={isolated}
623+
iframe={iframe}
624+
iframeStyle={iframe ? previewStyle : undefined}
625+
name={themedName}
626+
>
627+
{preview}
628+
</DemoComponentTheme>
629+
</DemoErrorBoundary>
630+
),
631+
[previewEpoch, themedName, onReset, isolated, iframe, previewStyle, preview],
629632
);
630633

631634
const tabsAndCode = (

0 commit comments

Comments
 (0)