|
1 |
| -export const withDownStateDimensionCapture = (selector) => (Story, context) => { |
2 |
| - const captureDownStateDimensions = () => { |
3 |
| - const components = document.querySelectorAll(selector); |
4 |
| - components.forEach((component) => { |
5 |
| - const { width, height } = component.getBoundingClientRect(); |
6 |
| - component.style.setProperty('--spectrum-downstate-width', `${width}px`); |
7 |
| - component.style.setProperty('--spectrum-downstate-height', `${height}px`); |
8 |
| - }); |
9 |
| - }; |
| 1 | +import { makeDecorator, useEffect } from "@storybook/preview-api"; |
| 2 | +import { fetchContainers } from "./helpers.js"; |
10 | 3 |
|
11 |
| - document.addEventListener("DOMContentLoaded", () => { |
12 |
| - // Wait to make sure the story is fully rendered (otherwise width/height can be wrong) |
13 |
| - setTimeout(() => { |
14 |
| - captureDownStateDimensions(); |
15 |
| - }, 100); |
16 |
| - }); |
| 4 | +export const withDownStateDimensionCapture = makeDecorator({ |
| 5 | + name: "withDownStateDimensionCapture", |
| 6 | + parameterName: "downState", |
| 7 | + wrapper: (StoryFn, context) => { |
| 8 | + const { args = {}, parameters = {}, viewMode, id } = context; |
| 9 | + |
| 10 | + /* Selectors are defined in the downState parameter */ |
| 11 | + const { |
| 12 | + // Fall back to the rootClass if no selectors are provided |
| 13 | + selectors = args.rootClass ? [ args.rootClass ] : [] |
| 14 | + } = parameters.downState ?? {}; |
17 | 15 |
|
18 |
| - return Story(context); |
19 |
| -}; |
| 16 | + /** |
| 17 | + * This effect will run after the component is rendered and will capture the dimensions of the |
| 18 | + * components that are specified in the selectors array. It will then set the custom properties |
| 19 | + * --spectrum-downstate-width and --spectrum-downstate-height on the component to the width and |
| 20 | + * height of the component respectively. This will allow the downstate to be calculated correctly |
| 21 | + * in the CSS. |
| 22 | + */ |
| 23 | + useEffect(() => { |
| 24 | + if (selectors.length === 0) return; |
| 25 | + |
| 26 | + for (const container of fetchContainers(id, viewMode === "docs")) { |
| 27 | + for (const selector of selectors) { |
| 28 | + const components = [...container.querySelectorAll(selector)]; |
| 29 | + for (const component of components) { |
| 30 | + const { width, height } = component.getBoundingClientRect(); |
| 31 | + component.style.setProperty("--spectrum-downstate-width", `${width}px`); |
| 32 | + component.style.setProperty("--spectrum-downstate-height", `${height}px`); |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + }, [selectors]); |
| 37 | + |
| 38 | + return StoryFn(context); |
| 39 | + }, |
| 40 | +}); |
0 commit comments