-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathpreview.js
More file actions
491 lines (420 loc) · 13.7 KB
/
Copy pathpreview.js
File metadata and controls
491 lines (420 loc) · 13.7 KB
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
import React from 'react';
import { buildArgsParam } from 'storybook/internal/router';
import { useArgs, useGlobals } from 'storybook/preview-api';
import '../src/assets/styles/entry-styles';
import themeCFPB from './themeCFPB';
const responsivePreviewQueryParameter = 'responsivePreview';
/** Query key read by `.storybook/preview-head.html` inside nested “All viewports” iframes. */
const nestedCanvasPaddingQueryParameter = 'sbNestedCanvasPadding';
/**
* Nested All-viewports iframes use `responsivePreview=off`. Padding on `#storybook-root` keeps
* `:focus-visible` rings visible. Full-bleed stories set `parameters.sbNestedCanvasPadding: 'flush'`.
*
* @param {Record<string, unknown> | undefined} parameters
* @returns {'focus' | 'flush'}
*/
const getNestedCanvasPaddingMode = (parameters) =>
parameters?.sbNestedCanvasPadding === 'flush' ? 'flush' : 'focus';
// Match CFPB design-system breakpoints (16px root): large layout from 63.8125em (~1021px).
// Hero `.m-hero__wrapper` uses min-height + em padding there; 1230px aligns with typical
// max-width + gutters. Storybook also accepts ad-hoc sizes via globals.viewport.value like
// `1230-900` (width-height, px by default) without adding an entry here.
const viewportOptions = {
desktop: {
name: 'Desktop (901px and above)',
styles: {
// Match design width; iframe uses content-box so border does not shrink the inner viewport.
width: '1230px',
height: '900px',
},
type: 'desktop',
},
tablet: {
name: 'Tablet (601-900px)',
styles: {
width: '900px',
height: '1024px',
},
type: 'tablet',
},
phone: {
name: 'Phone (600px and below)',
styles: {
width: '600px',
height: '844px',
},
type: 'mobile',
},
};
const responsivePreviewOptions = Object.entries(viewportOptions);
/** Extra height on nested All-viewports iframes so :focus-visible rings are not clipped (outline
* does not affect layout / scrollHeight). Covers checkbox, large target, fieldset, select, etc. */
const RESPONSIVE_PREVIEW_FOCUS_VERTICAL_BUFFER_PX = 40;
const shouldRenderSinglePreview = (context) => {
const searchParameters = new URLSearchParams(globalThis.location.search);
return (
context.viewMode !== 'story' ||
context.globals.responsivePreview !== 'all' ||
searchParameters.get(responsivePreviewQueryParameter) === 'off'
);
};
/**
* Build `args` / `globals` query strings for nested iframes (same encoding as Storybook manager).
*
* @param {Record<string, unknown>} initialValues
* @param {Record<string, unknown>} currentValues
* @returns {string}
*/
const buildNestedQueryParam = (initialValues, currentValues) =>
buildArgsParam(initialValues ?? {}, currentValues ?? {});
/**
* @param {string} storyId
* @param {'focus' | 'flush'} nestedCanvasPaddingMode
* @param {{ argsParam: string, globalsParam: string }} queryParams
* @returns {string}
*/
const getPreviewSource = (storyId, nestedCanvasPaddingMode, queryParams) => {
const url = new URL(globalThis.location.href);
url.search = '';
url.searchParams.set('id', storyId);
url.searchParams.set('viewMode', 'story');
url.searchParams.set(responsivePreviewQueryParameter, 'off');
if (nestedCanvasPaddingMode === 'flush') {
url.searchParams.set(nestedCanvasPaddingQueryParameter, 'flush');
}
if (queryParams.argsParam) {
url.searchParams.set('args', queryParams.argsParam);
}
if (queryParams.globalsParam) {
url.searchParams.set('globals', queryParams.globalsParam);
}
return url.toString();
};
const getFrameHeight = (frame) => {
const frameDocument = frame.contentDocument;
if (!frameDocument) return 0;
const { body, documentElement } = frameDocument;
const storyRoot = frameDocument.getElementById('storybook-root');
if (storyRoot && body) {
const win = frame.contentWindow;
const bodyStyle = win?.getComputedStyle(body);
const bodyVerticalPadding =
parseFloat(bodyStyle?.paddingTop ?? '0') +
parseFloat(bodyStyle?.paddingBottom ?? '0');
// Prefer #storybook-root box for content height. `body.scrollHeight` alone often tracks the
// iframe’s current height (min-height / 100% chains). Add body vertical padding when the body
// has inset (single canvas). Do not add #storybook-root padding again — offsetHeight /
// scrollHeight already include it when `box-sizing: border-box` (nested All viewports).
const fromRoot = Math.max(
storyRoot.scrollHeight,
storyRoot.offsetHeight,
storyRoot.getBoundingClientRect().height,
);
if (fromRoot > 0) {
return Math.ceil(fromRoot + bodyVerticalPadding);
}
}
return Math.max(
body?.scrollHeight ?? 0,
body?.offsetHeight ?? 0,
documentElement?.scrollHeight ?? 0,
documentElement?.offsetHeight ?? 0,
);
};
const ResponsivePreviewFrame = ({ previewSrc, viewport }) => {
const [height, setHeight] = React.useState(64);
const updateHeight = React.useCallback((frame) => {
const measuredHeight = getFrameHeight(frame);
const padded = measuredHeight + RESPONSIVE_PREVIEW_FOCUS_VERTICAL_BUFFER_PX;
// Floor avoids 0 during load; buffer leaves room for focus outlines outside the layout box.
setHeight(Math.max(Math.ceil(padded), 1));
}, []);
return React.createElement('iframe', {
onLoad: (event) => {
const frame = event.currentTarget;
const frameWindow = frame.contentWindow;
const frameDocument = frame.contentDocument;
updateHeight(frame);
frameWindow?.requestAnimationFrame(() => updateHeight(frame));
frameWindow?.setTimeout(() => updateHeight(frame), 250);
frameWindow?.addEventListener('resize', () => updateHeight(frame));
if (frameWindow?.ResizeObserver && frameDocument) {
const observer = new frameWindow.ResizeObserver(() =>
updateHeight(frame),
);
const storyRoot = frameDocument.getElementById('storybook-root');
observer.observe(frameDocument.documentElement);
observer.observe(frameDocument.body);
if (storyRoot) observer.observe(storyRoot);
}
},
src: previewSrc,
title: `${viewport.name} preview`,
style: {
background: 'white',
// set border around the iframe
border: 'none',
// border-box would make width include the border, so a 900px frame only has ~898px for
// the document — content-box keeps viewport.styles.width as the iframe layout width.
boxSizing: 'content-box',
display: 'block',
height,
width: viewport.styles.width,
},
});
};
/**
* All-viewports grid: nested iframes are separate documents; args/globals come from the decorator
* (`useArgs` / `useGlobals` must run there, not in this child component).
*
* @param {{ context: import('storybook/internal/types').StoryContext, nestedCanvasPaddingMode: 'focus' | 'flush', args: Record<string, unknown>, globals: Record<string, unknown> }} props
*/
const AllViewportsPreviews = ({
context,
nestedCanvasPaddingMode,
args,
globals,
}) => {
const argsParam = buildNestedQueryParam(context.initialArgs, args);
const globalsParam = buildNestedQueryParam(context.initialGlobals, globals);
const previewSrc = getPreviewSource(context.id, nestedCanvasPaddingMode, {
argsParam,
globalsParam,
});
const iframeCacheKey = `${argsParam}|${globalsParam}`;
return React.createElement(
'div',
{
style: {
boxSizing: 'border-box',
display: 'grid',
gap: '45px',
overflowX: 'auto',
padding: '0px',
},
},
responsivePreviewOptions.map(([key, viewport]) =>
React.createElement(
'section',
{
key,
style: {
display: 'grid',
justifyItems: 'start',
},
},
React.createElement(
'p',
{
style: {
color: '#43484e',
fontWeight: 500,
},
},
`${viewport.name}`,
),
React.createElement(ResponsivePreviewFrame, {
key: `${key}-${iframeCacheKey}`,
previewSrc,
viewport,
}),
),
),
);
};
const renderResponsivePreviews = (Story, context) => {
const [args] = useArgs();
const [globals] = useGlobals();
if (shouldRenderSinglePreview(context)) {
return React.createElement(Story);
}
const nestedCanvasPaddingMode = getNestedCanvasPaddingMode(
context.parameters,
);
return React.createElement(AllViewportsPreviews, {
context,
nestedCanvasPaddingMode,
args,
globals,
});
};
/** Storybook body classes applied by `parameters.layout` (see prepareForStory / WebView). */
const STORYBOOK_LAYOUT_BODY_CLASSES = [
'sb-main-padded',
'sb-main-centered',
'sb-main-fullscreen',
];
/**
* Only force `sb-main-fullscreen` when a story opts in with `parameters.layout: 'fullscreen'`.
* Global `layout: 'fullscreen'` in preview was removed because it merges into docs `<Canvas>`.
*
* For the default (undefined / `padded`), Storybook already applies `sb-main-padded` — the same
* ~1rem inset as Overview / autodocs previews. Do not override that here.
*
* @type {(Story: any, context: any) => import('react').ReactElement}
*/
const withExplicitFullscreenStoryCanvas = (Story, context) => {
React.useLayoutEffect(() => {
if (context.viewMode !== 'story') {
return undefined;
}
if (context.parameters?.layout !== 'fullscreen') {
return undefined;
}
const { body } = document;
for (const className of STORYBOOK_LAYOUT_BODY_CLASSES) {
body.classList.remove(className);
}
body.classList.add('sb-main-fullscreen');
return undefined;
}, [context.viewMode, context.id, context.parameters?.layout]);
return React.createElement(Story);
};
const shouldBlockStorybookLinkNavigation = (anchor) => {
const href = anchor.getAttribute('href');
if (!href) {
return false;
}
if (
href.startsWith('#') ||
href.startsWith('mailto:') ||
href.startsWith('tel:')
) {
return false;
}
return true;
};
/**
* Prevent links rendered inside stories from navigating away from Storybook.
*
* @type {(Story: any, context: any) => import('react').ReactElement}
*/
const withStorybookLinkNavigationGuard = (Story, context) => {
React.useEffect(() => {
if (context.viewMode !== 'story' && context.viewMode !== 'docs') {
return undefined;
}
// Only guard the rendered component. Listening on document would also stop
// Storybook's own chrome, so the docs page links would go dead too.
const root = context.canvasElement;
if (!(root instanceof Element)) {
return undefined;
}
const handleAnchorClick = (event) => {
if (
event.defaultPrevented ||
event.button !== 0 ||
event.metaKey ||
event.ctrlKey ||
event.shiftKey ||
event.altKey
) {
return;
}
const target = event.target;
if (!(target instanceof Element)) {
return;
}
const anchor = target.closest('a[href]');
if (!(anchor instanceof HTMLAnchorElement)) {
return;
}
if (!shouldBlockStorybookLinkNavigation(anchor)) {
return;
}
event.preventDefault();
};
root.addEventListener('click', handleAnchorClick, true);
return () => {
root.removeEventListener('click', handleAnchorClick, true);
};
}, [context.id, context.viewMode]);
return React.createElement(Story);
};
export const globalTypes = {
responsivePreview: {
name: 'Responsive preview',
description: 'Preview the current story at every configured viewport',
toolbar: {
icon: 'browser',
items: [
{ value: 'single', title: 'Single viewport' },
{ value: 'all', title: 'All viewports' },
],
},
},
};
export const initialGlobals = {
responsivePreview: 'single',
// Omit `globals.viewport` so the toolbar defaults to "Reset viewport" (full canvas).
// Setting `value: 'desktop'` (or any named key) forces that preset for every story.
};
export const decorators = [
renderResponsivePreviews,
withExplicitFullscreenStoryCanvas,
withStorybookLinkNavigationGuard,
];
export const preview = {
globalTypes,
initialGlobals,
parameters: {
// Default canvas padding matches Overview `<Canvas>` (`sb-main-padded`, 1rem). Stories that
// need edge-to-edge can set `parameters.layout: 'fullscreen'` (see
// `withExplicitFullscreenStoryCanvas`).
// https://storybook.js.org/docs/configure/story-layout
viewport: {
options: viewportOptions,
},
options: {
// Determines the display order of Stories in the sidebar
storySort: {
method: 'alphabetical',
order: [
'Guides',
'Components (Verified)',
[
'Banner (US gov)',
'Buttons',
'Checkboxes',
['Overview', '*'], // Display the custom Overview page first
'Expandables',
'Fieldsets',
'Headings',
'Labels',
'Links',
'Pagination',
'Paragraphs',
'Radio buttons',
'Tables',
'Taglines',
'Text inputs',
['Overview', '*'], // Display the custom Overview page first
'Text introductions',
'Wells',
],
'Components (Draft)',
'*',
],
},
},
actions: {},
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
docs: {
theme: themeCFPB,
},
a11y: {
// 'todo' - show a11y violations in the test UI only
// 'error' - fail CI on a11y violations
// 'off' - skip a11y checks entirely
test: 'todo',
},
},
tags: ['autodocs'],
decorators,
};
export default preview;