@unpunnyfuns/swatchbook-addon 0.57.1 → 0.58.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +1 -1
- package/dist/manager.mjs +19 -8
- package/dist/manager.mjs.map +1 -1
- package/dist/{preview-661N0-BM.mjs → preview-NOHYIleu.mjs} +13 -17
- package/dist/preview-NOHYIleu.mjs.map +1 -0
- package/dist/preview.mjs +1 -1
- package/package.json +4 -4
- package/dist/preview-661N0-BM.mjs.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as preview_exports } from "./preview-
|
|
1
|
+
import { i as preview_exports } from "./preview-NOHYIleu.mjs";
|
|
2
2
|
import { c as PARAM_KEY, h as VIRTUAL_MODULE_ID, m as TOOL_ID, n as AXES_GLOBAL_KEY, r as COLOR_FORMAT_GLOBAL_KEY, t as ADDON_ID } from "./constants-B31xFInv.mjs";
|
|
3
3
|
import { definePreviewAddon } from "storybook/internal/csf";
|
|
4
4
|
export * from "@unpunnyfuns/swatchbook-blocks";
|
package/dist/manager.mjs
CHANGED
|
@@ -58,13 +58,24 @@ const COLOR_FORMAT_OPTIONS = [
|
|
|
58
58
|
];
|
|
59
59
|
const h$1 = React.createElement;
|
|
60
60
|
function ColorFormatSelector({ active, onSelect }) {
|
|
61
|
-
return h$1("div", null, h$1("div", {
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
61
|
+
return h$1("div", null, h$1("div", {
|
|
62
|
+
className: "sb-switcher__section-label",
|
|
63
|
+
id: "sb-color-format-label"
|
|
64
|
+
}, "Color format"), h$1("div", {
|
|
65
|
+
className: "sb-switcher__section-body",
|
|
66
|
+
role: "group",
|
|
67
|
+
"aria-labelledby": "sb-color-format-label"
|
|
68
|
+
}, ...COLOR_FORMAT_OPTIONS.map((opt) => {
|
|
69
|
+
const isActive = opt.id === active;
|
|
70
|
+
return h$1("button", {
|
|
71
|
+
key: `color-format/${opt.id}`,
|
|
72
|
+
type: "button",
|
|
73
|
+
"aria-pressed": isActive,
|
|
74
|
+
"aria-label": `${opt.label} color format`,
|
|
75
|
+
onClick: () => onSelect(opt.id),
|
|
76
|
+
className: isActive ? "sb-switcher__pill sb-switcher__pill--active" : "sb-switcher__pill"
|
|
77
|
+
}, opt.label);
|
|
78
|
+
})));
|
|
68
79
|
}
|
|
69
80
|
//#endregion
|
|
70
81
|
//#region src/manager.tsx
|
|
@@ -251,7 +262,7 @@ function AxesToolbar() {
|
|
|
251
262
|
tooltip: label,
|
|
252
263
|
pressed: open,
|
|
253
264
|
onClick: () => setOpen((prev) => !prev),
|
|
254
|
-
"aria-haspopup":
|
|
265
|
+
"aria-haspopup": true,
|
|
255
266
|
"aria-expanded": open
|
|
256
267
|
}, h(SwatchbookIcon));
|
|
257
268
|
const tooltipBody = h(ThemeSwitcher, {
|
package/dist/manager.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manager.mjs","names":["h"],"sources":["../src/ColorFormatSelector.tsx","../src/manager.tsx"],"sourcesContent":["import type { ColorFormat } from '@unpunnyfuns/swatchbook-blocks';\nimport React from 'react';\nimport type { ReactElement } from 'react';\n\nexport type { ColorFormat };\n\n/**\n * Storybook-addon-specific pill row for picking how color sub-values\n * render in swatchbook blocks (hex / rgb / hsl / oklch / raw). Lives in\n * the addon rather than the shared switcher because color format is a\n * blocks-rendering concern, not a theming one — the docs-site navbar\n * switcher has no consumer for it.\n *\n * Reuses the `sb-switcher__*` class names so styling stays consistent\n * with the rest of the toolbar popover. The switcher's CSS is already\n * loaded on the page because this selector only renders inside\n * `<ThemeSwitcher>`'s `footer` prop.\n *\n * Uses `React.createElement` (via `h`) to survive embedding in Storybook's\n * manager bundle, which doesn't expose `react/jsx-runtime`.\n */\n\n/**\n * Runtime list of valid color formats. Declared here (alongside\n * `COLOR_FORMAT_OPTIONS`) rather than imported from blocks because the\n * manager bundle can't pull from `@unpunnyfuns/swatchbook-blocks` — that\n * package's barrel has a top-level `import 'virtual:swatchbook/tokens'`\n * which the manager has no resolver for. The `ColorFormat` type above\n * stays imported (type-only erases at compile time).\n */\nexport const COLOR_FORMATS: readonly ColorFormat[] = ['hex', 'rgb', 'hsl', 'oklch', 'raw'];\n\nconst COLOR_FORMAT_OPTIONS: readonly { id: ColorFormat; label: string }[] = [\n { id: 'hex', label: 'Hex' },\n { id: 'rgb', label: 'RGB' },\n { id: 'hsl', label: 'HSL' },\n { id: 'oklch', label: 'OKLCH' },\n { id: 'raw', label: 'Raw (JSON)' },\n];\n\nconst h = React.createElement;\n\nexport interface ColorFormatSelectorProps {\n active: ColorFormat;\n onSelect(next: ColorFormat): void;\n}\n\nexport function ColorFormatSelector({ active, onSelect }: ColorFormatSelectorProps): ReactElement {\n return h(\n 'div',\n null,\n h('div', { className: 'sb-switcher__section-label' }, 'Color format'),\n h(\n 'div',\n { className: 'sb-switcher__section-body' },\n ...COLOR_FORMAT_OPTIONS.map((opt) =>\n h(\n 'button',\n {\n key: `color-format/${opt.id}`,\n type: 'button',\n onClick: () => onSelect(opt.id),\n onMouseDown: (event: React.MouseEvent) => event.preventDefault(),\n className:\n opt.id === active\n ? 'sb-switcher__pill sb-switcher__pill--active'\n : 'sb-switcher__pill',\n },\n opt.label,\n ),\n ),\n ),\n );\n}\n","import { presetTuple, ThemeSwitcher } from '@unpunnyfuns/swatchbook-switcher';\nimport { COLOR_FORMATS, ColorFormatSelector } from '#/ColorFormatSelector.tsx';\nimport type { ColorFormat } from '#/ColorFormatSelector.tsx';\nimport React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport type { ReactElement } from 'react';\nimport { Button, ToggleButton, WithTooltip } from 'storybook/internal/components';\nimport { addons, types, useGlobals, useStorybookApi } from 'storybook/manager-api';\nimport type {\n InitPayload,\n VirtualAxis as AxisEntry,\n VirtualPreset as PresetEntry,\n} from '#/channel-types.ts';\nimport {\n ADDON_ID,\n AXES_GLOBAL_KEY,\n COLOR_FORMAT_GLOBAL_KEY,\n INIT_EVENT,\n INIT_REQUEST_EVENT,\n PREVIEW_MOUSEDOWN_EVENT,\n TOOL_ID,\n} from '#/constants.ts';\n\n/**\n * Use explicit `React.createElement` rather than JSX so the manager bundle\n * doesn't take a hard dependency on `react/jsx-runtime`. Storybook's manager\n * page injects its own React as a runtime global; `react/jsx-runtime` isn't\n * always part of that exposure, which breaks JSX with\n * \"Cannot read properties of undefined (reading 'recentlyCreatedOwnerStacks')\".\n * Mirrors the pattern `@storybook/addon-a11y` uses in its manager.\n *\n * The imported `<ThemeSwitcher>` from `@unpunnyfuns/swatchbook-switcher`\n * compiles with classic JSX (`React.createElement`) specifically so it\n * survives embedding in the manager bundle the same way.\n */\nconst h = React.createElement;\n\nconst EMPTY_AXES: readonly AxisEntry[] = [];\nconst EMPTY_PRESETS: readonly PresetEntry[] = [];\n\n/**\n * Root toolbar glyph — a split-circle (\"yinyang\") mark: a faint filled\n * disc for the full-swatch silhouette, with a darker half-and-inset-disc\n * path reading as a pair of theme variants swapped in place.\n */\nfunction SwatchbookIcon(): ReactElement {\n return h(\n 'svg',\n { width: 14, height: 14, viewBox: '0 0 14 14', 'aria-hidden': true },\n h('circle', { cx: 7, cy: 7, r: 6, fill: 'currentColor', opacity: 0.15 }),\n h('path', {\n d: 'M7 1a6 6 0 0 0 0 12 3 3 0 0 0 0-6 3 3 0 0 1 0-6Z',\n fill: 'currentColor',\n }),\n );\n}\n\nfunction defaultTupleFor(axes: readonly AxisEntry[]): Record<string, string> {\n const out: Record<string, string> = {};\n for (const axis of axes) out[axis.name] = axis.default;\n return out;\n}\n\nfunction AxesToolbar(): ReactElement {\n const [globals, updateGlobals] = useGlobals();\n const api = useStorybookApi();\n const [payload, setPayload] = useState<InitPayload | null>(null);\n const [open, setOpen] = useState(false);\n const bodyRef = useRef<HTMLDivElement | null>(null);\n\n useEffect(() => {\n const channel = addons.getChannel();\n const onInit = (next: InitPayload): void => setPayload(next);\n channel.on(INIT_EVENT, onInit);\n /**\n * Ask the preview to (re-)emit INIT_EVENT in case it already broadcast\n * before this effect subscribed. Without this request, a late-mounting\n * manager (story navigation, docs reload) can stay in \"loading…\" until\n * the user triggers a globals change.\n */\n channel.emit(INIT_REQUEST_EVENT);\n return () => {\n channel.off(INIT_EVENT, onInit);\n };\n }, []);\n\n const axes = payload?.axes ?? EMPTY_AXES;\n const presets = payload?.presets ?? EMPTY_PRESETS;\n const defaults = useMemo(() => defaultTupleFor(axes), [axes]);\n const [lastApplied, setLastApplied] = useState<string | null>(null);\n const rawTuple = globals[AXES_GLOBAL_KEY];\n const globalTuple =\n rawTuple && typeof rawTuple === 'object' ? (rawTuple as Record<string, string>) : undefined;\n const rawColorFormat = globals[COLOR_FORMAT_GLOBAL_KEY];\n const activeColorFormat: ColorFormat =\n typeof rawColorFormat === 'string' &&\n (COLOR_FORMATS as readonly string[]).includes(rawColorFormat)\n ? (rawColorFormat as ColorFormat)\n : 'hex';\n\n const activeTuple = useMemo<Record<string, string>>(() => {\n const out: Record<string, string> = { ...defaults };\n if (globalTuple) {\n for (const axis of axes) {\n const candidate = globalTuple[axis.name];\n if (candidate !== undefined && axis.contexts.includes(candidate)) {\n out[axis.name] = candidate;\n }\n }\n }\n return out;\n }, [axes, defaults, globalTuple]);\n\n const setAxis = useCallback(\n (axisName: string, next: string): void => {\n const tuple: Record<string, string> = { ...activeTuple, [axisName]: next };\n updateGlobals({ [AXES_GLOBAL_KEY]: tuple });\n },\n [activeTuple, updateGlobals],\n );\n\n const applyPreset = useCallback(\n (preset: PresetEntry): void => {\n const tuple = presetTuple(preset, axes, defaults);\n updateGlobals({ [AXES_GLOBAL_KEY]: tuple });\n setLastApplied(preset.name);\n },\n [axes, defaults, updateGlobals],\n );\n\n useEffect(() => {\n if (presets.length === 0) return;\n // `alt+shift+C` rather than `alt+T` — the latter conflicts with\n // Storybook's built-in \"toggle addon panel\" binding on some\n // platforms. Rebindable from Storybook's keyboard-shortcuts panel.\n api.setAddonShortcut(ADDON_ID, {\n label: `Cycle swatchbook presets (${presets.length})`,\n defaultShortcut: ['alt', 'shift', 'C'],\n actionName: 'cyclePreset',\n showInMenu: true,\n action: () => {\n const currentIdx = lastApplied\n ? presets.findIndex((preset) => preset.name === lastApplied)\n : -1;\n const next = presets[(currentIdx + 1) % presets.length];\n if (next) applyPreset(next);\n },\n });\n }, [api, presets, lastApplied, applyPreset]);\n\n const handleKeyDown = useCallback((event: React.KeyboardEvent<HTMLDivElement>): void => {\n if (event.key === 'Escape') {\n event.stopPropagation();\n setOpen(false);\n }\n }, []);\n\n /**\n * Escape closes even when focus hasn't entered the popover yet (e.g. the\n * user opened it via click and the mouse is still over the canvas). We\n * attach a document-level listener when open.\n */\n useEffect(() => {\n if (!open) return;\n const onDocKey = (e: KeyboardEvent): void => {\n if (e.key === 'Escape') setOpen(false);\n };\n document.addEventListener('keydown', onDocKey);\n return () => document.removeEventListener('keydown', onDocKey);\n }, [open]);\n\n /**\n * `WithTooltip`'s built-in `closeOnOutsideClick` misses some cases\n * (portaled popover + manager iframe boundaries). Belt-and-suspenders:\n * close when the user mouses down anywhere that isn't the trigger wrapper\n * or the popover body.\n */\n useEffect(() => {\n if (!open) return;\n const onDocMouseDown = (e: MouseEvent): void => {\n const target = e.target;\n if (!(target instanceof Element)) return;\n if (bodyRef.current?.contains(target)) return;\n if (target.closest('[data-testid=\"swatchbook-switcher\"]')) return;\n setOpen(false);\n };\n /**\n * The manager's document-level listener above can't see mousedowns\n * inside the preview iframe. Preview emits PREVIEW_MOUSEDOWN_EVENT on\n * every mousedown over its own document; listen for it here so\n * clicking the canvas / docs page also closes the popover.\n */\n const channel = addons.getChannel();\n const onPreviewMouseDown = (): void => setOpen(false);\n document.addEventListener('mousedown', onDocMouseDown);\n channel.on(PREVIEW_MOUSEDOWN_EVENT, onPreviewMouseDown);\n return () => {\n document.removeEventListener('mousedown', onDocMouseDown);\n channel.off(PREVIEW_MOUSEDOWN_EVENT, onPreviewMouseDown);\n };\n }, [open]);\n\n if (axes.length === 0) {\n return h(\n Button,\n {\n key: TOOL_ID,\n ariaLabel: 'Swatchbook theme (loading…)',\n tooltip: 'Swatchbook theme (loading…)',\n disabled: true,\n },\n h(SwatchbookIcon),\n );\n }\n\n const summary = axes.map((a) => activeTuple[a.name] ?? a.default).join(' · ');\n const label = `Swatchbook · ${summary}`;\n\n const button = h(\n ToggleButton,\n {\n key: TOOL_ID,\n ariaLabel: label,\n tooltip: label,\n pressed: open,\n onClick: () => setOpen((prev) => !prev),\n /**\n * Screen-reader disclosure semantics for the popover trigger. We\n * don't set `aria-controls` because the popover is portaled by\n * Storybook's `WithTooltip` with a dynamically-generated id we\n * don't have a stable handle on; `aria-haspopup` + `aria-expanded`\n * is the practical subset of the disclosure pattern.\n */\n 'aria-haspopup': 'dialog' as const,\n 'aria-expanded': open,\n },\n h(SwatchbookIcon),\n );\n\n const tooltipBody = h(ThemeSwitcher, {\n axes,\n presets,\n activeTuple,\n defaults,\n lastApplied,\n onAxisChange: setAxis,\n onPresetApply: applyPreset,\n onKeyDown: handleKeyDown,\n /**\n * Color format is addon-local chrome — drives how swatchbook blocks\n * stringify colors inside stories and docs. Slotted through the\n * switcher's `footer` escape hatch so shared theming UI stays free\n * of this concern.\n */\n footer: h(ColorFormatSelector, {\n active: activeColorFormat,\n onSelect: (next: ColorFormat) => updateGlobals({ [COLOR_FORMAT_GLOBAL_KEY]: next }),\n }),\n });\n\n return h(\n 'span',\n { ref: bodyRef, style: { display: 'inline-flex', alignItems: 'center' } },\n h(WithTooltip, {\n placement: 'bottom',\n trigger: 'click',\n visible: open,\n onVisibleChange: (next: boolean) => setOpen(next),\n closeOnOutsideClick: true,\n tooltip: tooltipBody,\n children: button,\n }),\n );\n}\n\naddons.register(ADDON_ID, () => {\n addons.add(TOOL_ID, {\n type: types.TOOL,\n title: 'Swatchbook theme',\n match: ({ viewMode, tabId }) => !tabId && (viewMode === 'story' || viewMode === 'docs'),\n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AAe;AACzD,WAAQ,IAAI,yBAAyB,mBAAmB;;IAEzD,CAAC,KAAK,CAAC;AAEV,KAAI,KAAK,WAAW,EAClB,QAAO,EACL,QACA;EACE,KAAK;EACL,WAAW;EACX,SAAS;EACT,UAAU;EACX,EACD,EAAE,eAAe,CAClB;CAIH,MAAM,QAAQ,gBADE,KAAK,KAAK,MAAM,YAAY,EAAE,SAAS,EAAE,QAAQ,CAAC,KAAK,MAAM;CAG7E,MAAM,SAAS,EACb,cACA;EACE,KAAK;EACL,WAAW;EACX,SAAS;EACT,SAAS;EACT,eAAe,SAAS,SAAS,CAAC,KAAK;EAQvC,iBAAiB;EACjB,iBAAiB;EAClB,EACD,EAAE,eAAe,CAClB;CAED,MAAM,cAAc,EAAE,eAAe;EACnC;EACA;EACA;EACA;EACA;EACA,cAAc;EACd,eAAe;EACf,WAAW;EAOX,QAAQ,EAAE,qBAAqB;GAC7B,QAAQ;GACR,WAAW,SAAsB,cAAc,GAAG,0BAA0B,MAAM,CAAC;GACpF,CAAC;EACH,CAAC;AAEF,QAAO,EACL,QACA;EAAE,KAAK;EAAS,OAAO;GAAE,SAAS;GAAe,YAAY;GAAU;EAAE,EACzE,EAAE,aAAa;EACb,WAAW;EACX,SAAS;EACT,SAAS;EACT,kBAAkB,SAAkB,QAAQ,KAAK;EACjD,qBAAqB;EACrB,SAAS;EACT,UAAU;EACX,CAAC,CACH;;AAGH,OAAO,SAAS,gBAAgB;AAC9B,QAAO,IAAI,SAAS;EAClB,MAAM,MAAM;EACZ,OAAO;EACP,QAAQ,EAAE,UAAU,YAAY,CAAC,UAAU,aAAa,WAAW,aAAa;EAChF,cAAc,EAAE,YAAY;EAC7B,CAAC;EACF"}
|
|
1
|
+
{"version":3,"file":"manager.mjs","names":["h"],"sources":["../src/ColorFormatSelector.tsx","../src/manager.tsx"],"sourcesContent":["import type { ColorFormat } from '@unpunnyfuns/swatchbook-blocks';\nimport React from 'react';\nimport type { ReactElement } from 'react';\n\nexport type { ColorFormat };\n\n/**\n * Storybook-addon-specific pill row for picking how color sub-values\n * render in swatchbook blocks (hex / rgb / hsl / oklch / raw). Lives in\n * the addon rather than the shared switcher because color format is a\n * blocks-rendering concern, not a theming one — the docs-site navbar\n * switcher has no consumer for it.\n *\n * Reuses the `sb-switcher__*` class names so styling stays consistent\n * with the rest of the toolbar popover. The switcher's CSS is already\n * loaded on the page because this selector only renders inside\n * `<ThemeSwitcher>`'s `footer` prop.\n *\n * Uses `React.createElement` (via `h`) to survive embedding in Storybook's\n * manager bundle, which doesn't expose `react/jsx-runtime`.\n */\n\n/**\n * Runtime list of valid color formats. Declared here (alongside\n * `COLOR_FORMAT_OPTIONS`) rather than imported from blocks because the\n * manager bundle can't pull from `@unpunnyfuns/swatchbook-blocks` — that\n * package's barrel has a top-level `import 'virtual:swatchbook/tokens'`\n * which the manager has no resolver for. The `ColorFormat` type above\n * stays imported (type-only erases at compile time).\n */\nexport const COLOR_FORMATS: readonly ColorFormat[] = ['hex', 'rgb', 'hsl', 'oklch', 'raw'];\n\nconst COLOR_FORMAT_OPTIONS: readonly { id: ColorFormat; label: string }[] = [\n { id: 'hex', label: 'Hex' },\n { id: 'rgb', label: 'RGB' },\n { id: 'hsl', label: 'HSL' },\n { id: 'oklch', label: 'OKLCH' },\n { id: 'raw', label: 'Raw (JSON)' },\n];\n\nconst h = React.createElement;\n\nexport interface ColorFormatSelectorProps {\n active: ColorFormat;\n onSelect(next: ColorFormat): void;\n}\n\nexport function ColorFormatSelector({ active, onSelect }: ColorFormatSelectorProps): ReactElement {\n return h(\n 'div',\n null,\n h(\n 'div',\n { className: 'sb-switcher__section-label', id: 'sb-color-format-label' },\n 'Color format',\n ),\n h(\n 'div',\n {\n className: 'sb-switcher__section-body',\n role: 'group',\n 'aria-labelledby': 'sb-color-format-label',\n },\n ...COLOR_FORMAT_OPTIONS.map((opt) => {\n const isActive = opt.id === active;\n return h(\n 'button',\n {\n key: `color-format/${opt.id}`,\n type: 'button',\n 'aria-pressed': isActive,\n 'aria-label': `${opt.label} color format`,\n onClick: () => onSelect(opt.id),\n className: isActive\n ? 'sb-switcher__pill sb-switcher__pill--active'\n : 'sb-switcher__pill',\n },\n opt.label,\n );\n }),\n ),\n );\n}\n","import { presetTuple, ThemeSwitcher } from '@unpunnyfuns/swatchbook-switcher';\nimport { COLOR_FORMATS, ColorFormatSelector } from '#/ColorFormatSelector.tsx';\nimport type { ColorFormat } from '#/ColorFormatSelector.tsx';\nimport React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport type { ReactElement } from 'react';\nimport { Button, ToggleButton, WithTooltip } from 'storybook/internal/components';\nimport { addons, types, useGlobals, useStorybookApi } from 'storybook/manager-api';\nimport type {\n InitPayload,\n VirtualAxis as AxisEntry,\n VirtualPreset as PresetEntry,\n} from '#/channel-types.ts';\nimport {\n ADDON_ID,\n AXES_GLOBAL_KEY,\n COLOR_FORMAT_GLOBAL_KEY,\n INIT_EVENT,\n INIT_REQUEST_EVENT,\n PREVIEW_MOUSEDOWN_EVENT,\n TOOL_ID,\n} from '#/constants.ts';\n\n/**\n * Use explicit `React.createElement` rather than JSX so the manager bundle\n * doesn't take a hard dependency on `react/jsx-runtime`. Storybook's manager\n * page injects its own React as a runtime global; `react/jsx-runtime` isn't\n * always part of that exposure, which breaks JSX with\n * \"Cannot read properties of undefined (reading 'recentlyCreatedOwnerStacks')\".\n * Mirrors the pattern `@storybook/addon-a11y` uses in its manager.\n *\n * The imported `<ThemeSwitcher>` from `@unpunnyfuns/swatchbook-switcher`\n * compiles with classic JSX (`React.createElement`) specifically so it\n * survives embedding in the manager bundle the same way.\n */\nconst h = React.createElement;\n\nconst EMPTY_AXES: readonly AxisEntry[] = [];\nconst EMPTY_PRESETS: readonly PresetEntry[] = [];\n\n/**\n * Root toolbar glyph — a split-circle (\"yinyang\") mark: a faint filled\n * disc for the full-swatch silhouette, with a darker half-and-inset-disc\n * path reading as a pair of theme variants swapped in place.\n */\nfunction SwatchbookIcon(): ReactElement {\n return h(\n 'svg',\n { width: 14, height: 14, viewBox: '0 0 14 14', 'aria-hidden': true },\n h('circle', { cx: 7, cy: 7, r: 6, fill: 'currentColor', opacity: 0.15 }),\n h('path', {\n d: 'M7 1a6 6 0 0 0 0 12 3 3 0 0 0 0-6 3 3 0 0 1 0-6Z',\n fill: 'currentColor',\n }),\n );\n}\n\nfunction defaultTupleFor(axes: readonly AxisEntry[]): Record<string, string> {\n const out: Record<string, string> = {};\n for (const axis of axes) out[axis.name] = axis.default;\n return out;\n}\n\nfunction AxesToolbar(): ReactElement {\n const [globals, updateGlobals] = useGlobals();\n const api = useStorybookApi();\n const [payload, setPayload] = useState<InitPayload | null>(null);\n const [open, setOpen] = useState(false);\n const bodyRef = useRef<HTMLDivElement | null>(null);\n\n useEffect(() => {\n const channel = addons.getChannel();\n const onInit = (next: InitPayload): void => setPayload(next);\n channel.on(INIT_EVENT, onInit);\n /**\n * Ask the preview to (re-)emit INIT_EVENT in case it already broadcast\n * before this effect subscribed. Without this request, a late-mounting\n * manager (story navigation, docs reload) can stay in \"loading…\" until\n * the user triggers a globals change.\n */\n channel.emit(INIT_REQUEST_EVENT);\n return () => {\n channel.off(INIT_EVENT, onInit);\n };\n }, []);\n\n const axes = payload?.axes ?? EMPTY_AXES;\n const presets = payload?.presets ?? EMPTY_PRESETS;\n const defaults = useMemo(() => defaultTupleFor(axes), [axes]);\n const [lastApplied, setLastApplied] = useState<string | null>(null);\n const rawTuple = globals[AXES_GLOBAL_KEY];\n const globalTuple =\n rawTuple && typeof rawTuple === 'object' ? (rawTuple as Record<string, string>) : undefined;\n const rawColorFormat = globals[COLOR_FORMAT_GLOBAL_KEY];\n const activeColorFormat: ColorFormat =\n typeof rawColorFormat === 'string' &&\n (COLOR_FORMATS as readonly string[]).includes(rawColorFormat)\n ? (rawColorFormat as ColorFormat)\n : 'hex';\n\n const activeTuple = useMemo<Record<string, string>>(() => {\n const out: Record<string, string> = { ...defaults };\n if (globalTuple) {\n for (const axis of axes) {\n const candidate = globalTuple[axis.name];\n if (candidate !== undefined && axis.contexts.includes(candidate)) {\n out[axis.name] = candidate;\n }\n }\n }\n return out;\n }, [axes, defaults, globalTuple]);\n\n const setAxis = useCallback(\n (axisName: string, next: string): void => {\n const tuple: Record<string, string> = { ...activeTuple, [axisName]: next };\n updateGlobals({ [AXES_GLOBAL_KEY]: tuple });\n },\n [activeTuple, updateGlobals],\n );\n\n const applyPreset = useCallback(\n (preset: PresetEntry): void => {\n const tuple = presetTuple(preset, axes, defaults);\n updateGlobals({ [AXES_GLOBAL_KEY]: tuple });\n setLastApplied(preset.name);\n },\n [axes, defaults, updateGlobals],\n );\n\n useEffect(() => {\n if (presets.length === 0) return;\n // `alt+shift+C` rather than `alt+T` — the latter conflicts with\n // Storybook's built-in \"toggle addon panel\" binding on some\n // platforms. Rebindable from Storybook's keyboard-shortcuts panel.\n api.setAddonShortcut(ADDON_ID, {\n label: `Cycle swatchbook presets (${presets.length})`,\n defaultShortcut: ['alt', 'shift', 'C'],\n actionName: 'cyclePreset',\n showInMenu: true,\n action: () => {\n const currentIdx = lastApplied\n ? presets.findIndex((preset) => preset.name === lastApplied)\n : -1;\n const next = presets[(currentIdx + 1) % presets.length];\n if (next) applyPreset(next);\n },\n });\n }, [api, presets, lastApplied, applyPreset]);\n\n const handleKeyDown = useCallback((event: React.KeyboardEvent<HTMLDivElement>): void => {\n if (event.key === 'Escape') {\n event.stopPropagation();\n setOpen(false);\n }\n }, []);\n\n /**\n * Escape closes even when focus hasn't entered the popover yet (e.g. the\n * user opened it via click and the mouse is still over the canvas). We\n * attach a document-level listener when open.\n */\n useEffect(() => {\n if (!open) return;\n const onDocKey = (e: KeyboardEvent): void => {\n if (e.key === 'Escape') setOpen(false);\n };\n document.addEventListener('keydown', onDocKey);\n return () => document.removeEventListener('keydown', onDocKey);\n }, [open]);\n\n /**\n * `WithTooltip`'s built-in `closeOnOutsideClick` misses some cases\n * (portaled popover + manager iframe boundaries). Belt-and-suspenders:\n * close when the user mouses down anywhere that isn't the trigger wrapper\n * or the popover body.\n */\n useEffect(() => {\n if (!open) return;\n const onDocMouseDown = (e: MouseEvent): void => {\n const target = e.target;\n if (!(target instanceof Element)) return;\n if (bodyRef.current?.contains(target)) return;\n if (target.closest('[data-testid=\"swatchbook-switcher\"]')) return;\n setOpen(false);\n };\n /**\n * The manager's document-level listener above can't see mousedowns\n * inside the preview iframe. Preview emits PREVIEW_MOUSEDOWN_EVENT on\n * every mousedown over its own document; listen for it here so\n * clicking the canvas / docs page also closes the popover.\n */\n const channel = addons.getChannel();\n const onPreviewMouseDown = (): void => setOpen(false);\n document.addEventListener('mousedown', onDocMouseDown);\n channel.on(PREVIEW_MOUSEDOWN_EVENT, onPreviewMouseDown);\n return () => {\n document.removeEventListener('mousedown', onDocMouseDown);\n channel.off(PREVIEW_MOUSEDOWN_EVENT, onPreviewMouseDown);\n };\n }, [open]);\n\n if (axes.length === 0) {\n return h(\n Button,\n {\n key: TOOL_ID,\n ariaLabel: 'Swatchbook theme (loading…)',\n tooltip: 'Swatchbook theme (loading…)',\n disabled: true,\n },\n h(SwatchbookIcon),\n );\n }\n\n const summary = axes.map((a) => activeTuple[a.name] ?? a.default).join(' · ');\n const label = `Swatchbook · ${summary}`;\n\n const button = h(\n ToggleButton,\n {\n key: TOOL_ID,\n ariaLabel: label,\n tooltip: label,\n pressed: open,\n onClick: () => setOpen((prev) => !prev),\n /**\n * Screen-reader disclosure semantics for the popover trigger. We\n * don't set `aria-controls` because the popover is portaled by\n * Storybook's `WithTooltip` with a dynamically-generated id we\n * don't have a stable handle on; `aria-haspopup` + `aria-expanded`\n * is the practical subset of the disclosure pattern.\n *\n * `aria-haspopup=\"true\"` (generic) rather than `\"dialog\"`: the\n * switcher body is `role=\"group\"` (it's a settings panel of\n * independent controls, not a modal dialog), so promising\n * `\"dialog\"` would misalign the trigger with what AT finds when\n * focus enters the popover.\n */\n 'aria-haspopup': true as const,\n 'aria-expanded': open,\n },\n h(SwatchbookIcon),\n );\n\n const tooltipBody = h(ThemeSwitcher, {\n axes,\n presets,\n activeTuple,\n defaults,\n lastApplied,\n onAxisChange: setAxis,\n onPresetApply: applyPreset,\n onKeyDown: handleKeyDown,\n /**\n * Color format is addon-local chrome — drives how swatchbook blocks\n * stringify colors inside stories and docs. Slotted through the\n * switcher's `footer` escape hatch so shared theming UI stays free\n * of this concern.\n */\n footer: h(ColorFormatSelector, {\n active: activeColorFormat,\n onSelect: (next: ColorFormat) => updateGlobals({ [COLOR_FORMAT_GLOBAL_KEY]: next }),\n }),\n });\n\n return h(\n 'span',\n { ref: bodyRef, style: { display: 'inline-flex', alignItems: 'center' } },\n h(WithTooltip, {\n placement: 'bottom',\n trigger: 'click',\n visible: open,\n onVisibleChange: (next: boolean) => setOpen(next),\n closeOnOutsideClick: true,\n tooltip: tooltipBody,\n children: button,\n }),\n );\n}\n\naddons.register(ADDON_ID, () => {\n addons.add(TOOL_ID, {\n type: types.TOOL,\n title: 'Swatchbook theme',\n match: ({ viewMode, tabId }) => !tabId && (viewMode === 'story' || viewMode === 'docs'),\n render: () => h(AxesToolbar),\n });\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAa,gBAAwC;CAAC;CAAO;CAAO;CAAO;CAAS;CAAM;AAE1F,MAAM,uBAAsE;CAC1E;EAAE,IAAI;EAAO,OAAO;EAAO;CAC3B;EAAE,IAAI;EAAO,OAAO;EAAO;CAC3B;EAAE,IAAI;EAAO,OAAO;EAAO;CAC3B;EAAE,IAAI;EAAS,OAAO;EAAS;CAC/B;EAAE,IAAI;EAAO,OAAO;EAAc;CACnC;AAED,MAAMA,MAAI,MAAM;AAOhB,SAAgB,oBAAoB,EAAE,QAAQ,YAAoD;AAChG,QAAOA,IACL,OACA,MACAA,IACE,OACA;EAAE,WAAW;EAA8B,IAAI;EAAyB,EACxE,eACD,EACDA,IACE,OACA;EACE,WAAW;EACX,MAAM;EACN,mBAAmB;EACpB,EACD,GAAG,qBAAqB,KAAK,QAAQ;EACnC,MAAM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f,WAAW;EAOX,QAAQ,EAAE,qBAAqB;GAC7B,QAAQ;GACR,WAAW,SAAsB,cAAc,GAAG,0BAA0B,MAAM,CAAC;GACpF,CAAC;EACH,CAAC;AAEF,QAAO,EACL,QACA;EAAE,KAAK;EAAS,OAAO;GAAE,SAAS;GAAe,YAAY;GAAU;EAAE,EACzE,EAAE,aAAa;EACb,WAAW;EACX,SAAS;EACT,SAAS;EACT,kBAAkB,SAAkB,QAAQ,KAAK;EACjD,qBAAqB;EACrB,SAAS;EACT,UAAU;EACX,CAAC,CACH;;AAGH,OAAO,SAAS,gBAAgB;AAC9B,QAAO,IAAI,SAAS;EAClB,MAAM,MAAM;EACZ,OAAO;EACP,QAAQ,EAAE,UAAU,YAAY,CAAC,UAAU,aAAa,WAAW,aAAa;EAChF,cAAc,EAAE,YAAY;EAC7B,CAAC;EACF"}
|
|
@@ -66,26 +66,24 @@ function forEachPinnedAxis(cb) {
|
|
|
66
66
|
}
|
|
67
67
|
/**
|
|
68
68
|
* Compose a stable theme name from a tuple — `axisValues.join(' · ')`
|
|
69
|
-
* in axis order. Used for the `
|
|
70
|
-
*
|
|
71
|
-
* are no axes (no name to write).
|
|
69
|
+
* in axis order. Used for the `ThemeContext` value the blocks read and
|
|
70
|
+
* the addon-channel signals downstream consumers subscribe to. Returns
|
|
71
|
+
* empty string when there are no axes (no name to write).
|
|
72
72
|
*/
|
|
73
73
|
function matchThemeName(tuple) {
|
|
74
74
|
if (axes.length === 0) return "";
|
|
75
75
|
return tupleToName(axes, tuple);
|
|
76
76
|
}
|
|
77
77
|
/**
|
|
78
|
-
* Write
|
|
79
|
-
*
|
|
80
|
-
*
|
|
81
|
-
*
|
|
78
|
+
* Write one `data-<prefix>-<axis>=<context>` per axis on `<html>`.
|
|
79
|
+
* The smart CSS emitter targets these single-axis selectors (and
|
|
80
|
+
* joint compounds across multiple) — that's the actual scoping
|
|
81
|
+
* surface the cascade resolves through. Prefix follows `cssVarPrefix`
|
|
82
|
+
* so attr namespace and emitted selectors stay in lockstep.
|
|
82
83
|
*/
|
|
83
|
-
function setRootAxes(
|
|
84
|
+
function setRootAxes(tuple) {
|
|
84
85
|
if (typeof document === "undefined") return;
|
|
85
86
|
const root = document.documentElement;
|
|
86
|
-
const themeAttr = dataAttr(cssVarPrefix, "theme");
|
|
87
|
-
if (themeName) root.setAttribute(themeAttr, themeName);
|
|
88
|
-
else root.removeAttribute(themeAttr);
|
|
89
87
|
for (const axis of axes) {
|
|
90
88
|
const attr = dataAttr(cssVarPrefix, axis.name);
|
|
91
89
|
const value = tuple[axis.name];
|
|
@@ -210,10 +208,9 @@ const themedDecorator = (Story, context) => {
|
|
|
210
208
|
broadcastInit();
|
|
211
209
|
}, []);
|
|
212
210
|
useEffect(() => {
|
|
213
|
-
setRootAxes(
|
|
214
|
-
}, [
|
|
211
|
+
setRootAxes(tuple);
|
|
212
|
+
}, [tuple]);
|
|
215
213
|
const wrapperAttrs = {};
|
|
216
|
-
if (themeName) wrapperAttrs[dataAttr(cssVarPrefix, "theme")] = themeName;
|
|
217
214
|
for (const axis of axes) {
|
|
218
215
|
const value = tuple[axis.name];
|
|
219
216
|
if (value !== void 0) wrapperAttrs[dataAttr(cssVarPrefix, axis.name)] = value;
|
|
@@ -314,8 +311,7 @@ function installGlobalAxisApplier() {
|
|
|
314
311
|
channel.on(INIT_REQUEST_EVENT, broadcastInit);
|
|
315
312
|
const apply = (globals) => {
|
|
316
313
|
ensureStylesheet(css, cssVarPrefix);
|
|
317
|
-
|
|
318
|
-
setRootAxes(matchThemeName(tuple), tuple);
|
|
314
|
+
setRootAxes(resolveTuple(globals, {}));
|
|
319
315
|
};
|
|
320
316
|
let lastApplied = "";
|
|
321
317
|
const onGlobals = (payload) => {
|
|
@@ -354,4 +350,4 @@ if (import.meta.hot) import.meta.hot.on(HMR_EVENT, (payload) => {
|
|
|
354
350
|
//#endregion
|
|
355
351
|
export { preview_exports as i, globalTypes as n, initialGlobals as r, decorators as t };
|
|
356
352
|
|
|
357
|
-
//# sourceMappingURL=preview-
|
|
353
|
+
//# sourceMappingURL=preview-NOHYIleu.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"preview-NOHYIleu.mjs","names":["virtualDisabledAxes","virtualDefaultTuple","virtualAxes","virtualPresets","virtualCells","virtualJointOverrides","virtualVarianceByPath","defaultTuple","virtualListing"],"sources":["../src/preview.tsx"],"sourcesContent":["/// <reference types=\"vite/client\" />\nimport { buildResolveAt } from '@unpunnyfuns/swatchbook-core/resolve-at';\nimport type {\n Axis as CoreAxis,\n Cells as CoreCells,\n JointOverrides,\n} from '@unpunnyfuns/swatchbook-core';\nimport type { Decorator, Preview } from '@storybook/react-vite';\nimport { useEffect, useMemo } from 'react';\nimport { addons } from 'storybook/preview-api';\nimport { dataAttr } from '@unpunnyfuns/swatchbook-core/data-attr';\nimport { ensureStyleElement } from '@unpunnyfuns/swatchbook-core/style-element';\nimport { tupleToName } from '@unpunnyfuns/swatchbook-core/themes';\n// Side-effect import for integrations that opted into `autoInject`\n// (e.g. Tailwind's `@theme` block). When no integration opts in, the\n// virtual module body is empty — still a valid no-op.\nimport 'virtual:swatchbook/integration-side-effects';\nimport {\n axes as virtualAxes,\n cells as virtualCells,\n css,\n cssVarPrefix,\n defaultTuple as virtualDefaultTuple,\n diagnostics,\n disabledAxes as virtualDisabledAxes,\n jointOverrides as virtualJointOverrides,\n listing as virtualListing,\n presets as virtualPresets,\n varianceByPath as virtualVarianceByPath,\n} from 'virtual:swatchbook/tokens';\nimport {\n AxesContext,\n COLOR_FORMATS,\n ColorFormatContext,\n SwatchbookContext,\n ThemeContext,\n} from '@unpunnyfuns/swatchbook-blocks';\nimport type { ColorFormat, ProjectSnapshot } from '@unpunnyfuns/swatchbook-blocks';\nimport {\n AXES_GLOBAL_KEY,\n COLOR_FORMAT_GLOBAL_KEY,\n HMR_EVENT,\n INIT_EVENT,\n INIT_REQUEST_EVENT,\n PREVIEW_MOUSEDOWN_EVENT,\n STYLE_ELEMENT_ID,\n TOKENS_UPDATED_EVENT,\n} from '#/constants.ts';\nimport type { StoryParameters, SwatchbookGlobals } from '#/globals.ts';\n\n/**\n * The `html, body { ... }` rules that paint the iframe's own chrome\n * (outside any decorator wrapper — Docs mode, autodocs, empty gutters)\n * with the active theme's surface + text vars. Composed alongside the\n * emitted token CSS so both load through the same `<style>` element.\n */\nfunction iframeChromeRules(prefix: string): string {\n const surface = prefix ? `--${prefix}-color-surface-default` : '--color-surface-default';\n const text = prefix ? `--${prefix}-color-text-default` : '--color-text-default';\n return `\nhtml, body {\n background: var(${surface}, Canvas);\n color: var(${text}, CanvasText);\n margin: 0;\n}\n`;\n}\n\n/**\n * Inject the per-theme stylesheet plus the iframe-chrome block. Shared\n * with the HMR re-emit path below so a token refresh updates the\n * iframe's chrome rules from the same source.\n */\nfunction ensureStylesheet(cssText: string, prefix: string): void {\n ensureStyleElement(STYLE_ELEMENT_ID, `${cssText}\\n${iframeChromeRules(prefix)}`);\n}\n\n/**\n * Apply `cb(axisName, value)` for every pinned (disabled) axis whose\n * default-tuple value is set. `virtualDefaultTuple` carries the\n * post-filter axis defaults; disabled axes don't appear in\n * `virtualAxes` but their pinned context value still lives here, so\n * sampling it gives the same result the old \"first permutation's\n * input\" lookup did.\n */\nfunction forEachPinnedAxis(cb: (name: string, value: string) => void): void {\n for (const name of virtualDisabledAxes) {\n const value = virtualDefaultTuple[name];\n if (value !== undefined) cb(name, value);\n }\n}\n\n/**\n * Compose a stable theme name from a tuple — `axisValues.join(' · ')`\n * in axis order. Used for the `ThemeContext` value the blocks read and\n * the addon-channel signals downstream consumers subscribe to. Returns\n * empty string when there are no axes (no name to write).\n */\nfunction matchThemeName(tuple: Readonly<Record<string, string>>): string {\n if (virtualAxes.length === 0) return '';\n return tupleToName(virtualAxes, tuple);\n}\n\n/**\n * Write one `data-<prefix>-<axis>=<context>` per axis on `<html>`.\n * The smart CSS emitter targets these single-axis selectors (and\n * joint compounds across multiple) — that's the actual scoping\n * surface the cascade resolves through. Prefix follows `cssVarPrefix`\n * so attr namespace and emitted selectors stay in lockstep.\n */\nfunction setRootAxes(tuple: Readonly<Record<string, string>>): void {\n if (typeof document === 'undefined') return;\n const root = document.documentElement;\n for (const axis of virtualAxes) {\n const attr = dataAttr(cssVarPrefix, axis.name);\n const value = tuple[axis.name];\n if (value === undefined) {\n root.removeAttribute(attr);\n } else {\n root.setAttribute(attr, value);\n }\n }\n forEachPinnedAxis((name, value) => {\n root.setAttribute(dataAttr(cssVarPrefix, name), value);\n });\n}\n\n/**\n * Subset of an INIT_EVENT-shaped object the manager bundle needs. The 9\n * fields are the union of what the toolbar and panel read; named so\n * `broadcastInit` (module-level virtual exports) and the HMR re-emit\n * (`payload`-shaped) compose the same payload from the same shape.\n */\ninterface InitFieldsSource {\n axes: typeof virtualAxes;\n disabledAxes: typeof virtualDisabledAxes;\n presets: typeof virtualPresets;\n diagnostics: typeof diagnostics;\n cssVarPrefix: string;\n cells: typeof virtualCells;\n jointOverrides: typeof virtualJointOverrides;\n varianceByPath: typeof virtualVarianceByPath;\n defaultTuple: typeof virtualDefaultTuple;\n}\n\nfunction pickInitFields(source: InitFieldsSource): InitFieldsSource {\n return {\n axes: source.axes,\n disabledAxes: source.disabledAxes,\n presets: source.presets,\n diagnostics: source.diagnostics,\n cssVarPrefix: source.cssVarPrefix,\n cells: source.cells,\n jointOverrides: source.jointOverrides,\n varianceByPath: source.varianceByPath,\n defaultTuple: source.defaultTuple,\n };\n}\n\n/**\n * Emit the full virtual-module payload to the manager over Storybook's\n * channel so the toolbar + panel (which run in the manager bundle and\n * can't import our virtual module) can render from it.\n */\nfunction broadcastInit(): void {\n const channel = addons.getChannel();\n channel.emit(\n INIT_EVENT,\n pickInitFields({\n axes: virtualAxes,\n disabledAxes: virtualDisabledAxes,\n presets: virtualPresets,\n diagnostics,\n cssVarPrefix,\n cells: virtualCells,\n jointOverrides: virtualJointOverrides,\n varianceByPath: virtualVarianceByPath,\n defaultTuple: virtualDefaultTuple,\n }),\n );\n}\n\n/** Axis-default tuple, used as the baseline before overrides. */\nfunction defaultTuple(): Record<string, string> {\n const out: Record<string, string> = {};\n for (const axis of virtualAxes) out[axis.name] = axis.default;\n return out;\n}\n\n/**\n * Reverse-engineer a tuple from a `Light · Brand A · Normal`-shape\n * theme name. Splits on ` · ` and zips with `virtualAxes` in declared\n * order — matches `matchThemeName`'s production direction so a\n * round-trip is lossless. Returns `undefined` when the segment count\n * doesn't match the axis count.\n */\nfunction tupleForName(name: string): Record<string, string> | undefined {\n if (!name) return undefined;\n const parts = name.split(' · ');\n if (parts.length !== virtualAxes.length) return undefined;\n const out: Record<string, string> = {};\n for (let i = 0; i < virtualAxes.length; i++) {\n const axis = virtualAxes[i] as (typeof virtualAxes)[number];\n const value = parts[i];\n if (value === undefined) return undefined;\n out[axis.name] = value;\n }\n return out;\n}\n\n/**\n * Merge a partial tuple onto the axis defaults, dropping keys for axes that\n * don't exist and silently falling back to the default for contexts that\n * aren't listed on the axis.\n */\nfunction normalizeTuple(partial: Readonly<Record<string, string>>): Record<string, string> {\n const out = defaultTuple();\n for (const axis of virtualAxes) {\n const candidate = partial[axis.name];\n if (candidate !== undefined && axis.contexts.includes(candidate)) {\n out[axis.name] = candidate;\n }\n }\n return out;\n}\n\n/**\n * Resolve the active tuple from all input channels, in priority order:\n * 1. `parameters.swatchbook.axes` — per-story tuple.\n * 2. `parameters.swatchbook.permutation` — per-story composed name.\n * 3. `globals.swatchbookAxes` — toolbar-set tuple.\n * 4. virtual module default.\n */\nfunction resolveTuple(\n globals: SwatchbookGlobals,\n parameters: StoryParameters,\n): Record<string, string> {\n const param = parameters.swatchbook;\n const paramAxes = param?.axes;\n if (paramAxes) {\n return normalizeTuple(paramAxes);\n }\n if (param?.permutation) {\n const hit = tupleForName(param.permutation);\n if (hit) return normalizeTuple(hit);\n }\n const globalAxes = globals[AXES_GLOBAL_KEY];\n if (globalAxes && typeof globalAxes === 'object') {\n return normalizeTuple(globalAxes as Record<string, string>);\n }\n return defaultTuple();\n}\n\nfunction resolveColorFormat(globals: SwatchbookGlobals): ColorFormat {\n const raw = globals[COLOR_FORMAT_GLOBAL_KEY];\n if (typeof raw === 'string' && (COLOR_FORMATS as readonly string[]).includes(raw)) {\n return raw as ColorFormat;\n }\n return 'hex';\n}\n\n/**\n * Single shared `resolveAt` instance for the lifetime of the preview\n * iframe. The inputs (`virtualAxes`, `virtualCells`, …) are all\n * module-level virtual-module exports with stable identity, so this\n * never needs to rebuild; downstream `ProjectSnapshot` consumers can\n * key memos on the snapshot wrapper without worrying about\n * `resolveAt` churning when Storybook recreates `context.globals`.\n */\nconst previewResolveAt = buildResolveAt(\n virtualAxes as readonly CoreAxis[],\n virtualCells as CoreCells,\n virtualJointOverrides as JointOverrides,\n virtualDefaultTuple,\n);\n\nconst themedDecorator: Decorator = (Story, context) => {\n const globals = context.globals as SwatchbookGlobals;\n const parameters = context.parameters as StoryParameters;\n const tuple = useMemo(() => resolveTuple(globals, parameters), [globals, parameters]);\n const colorFormat = useMemo(() => resolveColorFormat(globals), [globals]);\n const themeName = useMemo(() => matchThemeName(tuple), [tuple]);\n\n useEffect(() => {\n ensureStylesheet(css, cssVarPrefix);\n broadcastInit();\n }, []);\n\n useEffect(() => {\n setRootAxes(tuple);\n }, [tuple]);\n\n const wrapperAttrs: Record<string, string> = {};\n for (const axis of virtualAxes) {\n const value = tuple[axis.name];\n if (value !== undefined) wrapperAttrs[dataAttr(cssVarPrefix, axis.name)] = value;\n }\n forEachPinnedAxis((name, value) => {\n wrapperAttrs[dataAttr(cssVarPrefix, name)] = value;\n });\n\n const snapshot = useMemo<ProjectSnapshot>(\n () => ({\n axes: virtualAxes,\n disabledAxes: virtualDisabledAxes,\n presets: virtualPresets,\n activeTheme: themeName,\n activeAxes: tuple,\n cssVarPrefix,\n diagnostics,\n css,\n listing: virtualListing,\n cells: virtualCells,\n jointOverrides: virtualJointOverrides,\n varianceByPath: virtualVarianceByPath,\n defaultTuple: virtualDefaultTuple,\n resolveAt: previewResolveAt,\n }),\n [themeName, tuple],\n );\n\n return (\n <SwatchbookContext.Provider value={snapshot}>\n <ThemeContext.Provider value={themeName}>\n <AxesContext.Provider value={tuple}>\n <ColorFormatContext.Provider value={colorFormat}>\n <div\n {...wrapperAttrs}\n style={{\n padding: '1rem',\n minHeight: '100%',\n }}\n >\n <Story />\n </div>\n </ColorFormatContext.Provider>\n </AxesContext.Provider>\n </ThemeContext.Provider>\n </SwatchbookContext.Provider>\n );\n};\n\n/**\n * Named exports consumed by `definePreviewAddon(previewExports)` in the\n * addon's CSF Next factory (`src/index.ts`).\n */\nexport const decorators: NonNullable<Preview['decorators']> = [themedDecorator];\n\nexport const globalTypes: NonNullable<Preview['globalTypes']> = {\n [AXES_GLOBAL_KEY]: {\n name: 'Axes',\n description: 'Per-axis context selection — the active permutation tuple.',\n },\n [COLOR_FORMAT_GLOBAL_KEY]: {\n name: 'Color format',\n description: 'Display format for color tokens in blocks. Emitted CSS is unaffected.',\n },\n};\n\nfunction buildInitialAxes(): Record<string, string> {\n const out: Record<string, string> = {};\n for (const axis of virtualAxes) out[axis.name] = axis.default;\n return out;\n}\n\nexport const initialGlobals: NonNullable<Preview['initialGlobals']> = {\n [AXES_GLOBAL_KEY]: buildInitialAxes(),\n [COLOR_FORMAT_GLOBAL_KEY]: 'hex',\n};\n\n/**\n * Module-level channel subscription: writes the active tuple's attributes\n * onto `<html>` regardless of whether a story decorator is rendering.\n *\n * The {@link themedDecorator} already sets these inside story renders, but\n * it never runs on MDX docs pages that embed blocks without `<Story />`.\n * Without attrs on an ancestor, the per-tuple CSS selectors\n * (`[data-mode=\"Dark\"][data-brand=\"…\"]`) don't match and everything falls\n * back to the `:root` default tuple — so colors stay defaults even after\n * the toolbar switches axes. Subscribing globally fixes MDX docs at the\n * cost of one idempotent redundant write per story render.\n */\nfunction installGlobalAxisApplier(): void {\n if (typeof document === 'undefined') return;\n const channel = addons.getChannel();\n /**\n * Inject the stylesheet and emit the init payload once on module load so\n * the manager's toolbar populates and CSS vars are available even when no\n * story/decorator ever runs (bare MDX docs pages). Without these, the\n * toolbar sits in its disabled \"loading…\" state and nothing is styled.\n */\n ensureStylesheet(css, cssVarPrefix);\n broadcastInit();\n /**\n * If the manager subscribes to INIT_EVENT after our initial broadcast,\n * it misses the payload and the toolbar stays in its \"loading…\" state\n * until something else re-fires it. Honor an explicit request event so\n * a late-mounting manager can ask for the payload.\n */\n channel.on(INIT_REQUEST_EVENT, broadcastInit);\n const apply = (globals: SwatchbookGlobals): void => {\n ensureStylesheet(css, cssVarPrefix);\n const tuple = resolveTuple(globals, {});\n setRootAxes(tuple);\n };\n // Storybook fires `globalsUpdated`, `setGlobals`, and `updateGlobals`\n // for the same logical change (preview init + every toolbar tick).\n // Subscribing to all three is intentional — `setGlobals` carries the\n // initial URL-persisted globals; `updateGlobals` is the toolbar\n // signal; `globalsUpdated` is the cross-frame echo. Apply the same\n // handler to all three but dedupe via a stringified-tuple guard so\n // downstream `setRootAxes` + `useSyncExternalStore` consumers\n // re-render at most once per real change instead of three times per\n // tick.\n let lastApplied = '';\n const onGlobals = (payload: { globals?: SwatchbookGlobals }): void => {\n if (!payload.globals) return;\n const tuple = resolveTuple(payload.globals, {});\n const fingerprint = matchThemeName(tuple);\n if (fingerprint === lastApplied) return;\n lastApplied = fingerprint;\n apply(payload.globals);\n };\n channel.on('globalsUpdated', onGlobals);\n channel.on('setGlobals', onGlobals);\n channel.on('updateGlobals', onGlobals);\n}\n\ninstallGlobalAxisApplier();\n\n/**\n * Bridge `mousedown` inside the preview iframe to the manager via a\n * dedicated channel event. The toolbar popover's outside-click listener\n * runs on the manager's document, which can't observe mousedowns inside\n * the preview; without this bridge, clicking the canvas leaves the\n * popover open. Idempotent: fires at most once per real mousedown.\n */\nfunction installPreviewMouseDownBridge(): void {\n if (typeof document === 'undefined') return;\n const channel = addons.getChannel();\n document.addEventListener('mousedown', () => {\n channel.emit(PREVIEW_MOUSEDOWN_EVENT);\n });\n}\n\ninstallPreviewMouseDownBridge();\n\n/**\n * Wire the dev-time token-refresh HMR path. The plugin emits `HMR_EVENT`\n * with the fresh virtual-module payload whenever a watched source file\n * changes; we re-inject the stylesheet and forward to the Storybook\n * channel so the toolbar re-renders and blocks can re-subscribe with\n * the new snapshot — no full preview reload, so args / scroll / open\n * overlays survive the refresh. No-ops in production where\n * `import.meta.hot` is undefined.\n */\ninterface HmrSnapshot {\n axes: typeof virtualAxes;\n disabledAxes: typeof virtualDisabledAxes;\n presets: typeof virtualPresets;\n diagnostics: typeof diagnostics;\n css: string;\n cssVarPrefix: string;\n listing: typeof virtualListing;\n cells: typeof virtualCells;\n jointOverrides: typeof virtualJointOverrides;\n varianceByPath: typeof virtualVarianceByPath;\n defaultTuple: typeof virtualDefaultTuple;\n}\nif (import.meta.hot) {\n import.meta.hot.on(HMR_EVENT, (payload: HmrSnapshot) => {\n ensureStylesheet(payload.css, payload.cssVarPrefix);\n const channel = addons.getChannel();\n channel.emit(INIT_EVENT, pickInitFields(payload));\n channel.emit(TOKENS_UPDATED_EVENT, payload);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,SAAS,kBAAkB,QAAwB;AAGjD,QAAO;;oBAFS,SAAS,KAAK,OAAO,0BAA0B,0BAIrC;eAHb,SAAS,KAAK,OAAO,uBAAuB,uBAIvC;;;;;;;;;;AAWpB,SAAS,iBAAiB,SAAiB,QAAsB;AAC/D,oBAAmB,kBAAkB,GAAG,QAAQ,IAAI,kBAAkB,OAAO,GAAG;;;;;;;;;;AAWlF,SAAS,kBAAkB,IAAiD;AAC1E,MAAK,MAAM,QAAQA,cAAqB;EACtC,MAAM,QAAQC,aAAoB;AAClC,MAAI,UAAU,KAAA,EAAW,IAAG,MAAM,MAAM;;;;;;;;;AAU5C,SAAS,eAAe,OAAiD;AACvE,KAAIC,KAAY,WAAW,EAAG,QAAO;AACrC,QAAO,YAAYA,MAAa,MAAM;;;;;;;;;AAUxC,SAAS,YAAY,OAA+C;AAClE,KA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EtB,MAAM,cAAc,eADN,aAAa,QAAQ,SAAS,EAAE,CAAC,CACN;AACzC,MAAI,gBAAgB,YAAa;AACjC,gBAAc;AACd,QAAM,QAAQ,QAAQ;;AAExB,SAAQ,GAAG,kBAAkB,UAAU;AACvC,SAAQ,GAAG,cAAc,UAAU;AACnC,SAAQ,GAAG,iBAAiB,UAAU;;AAGxC,0BAA0B;;;;;;;;AAS1B,SAAS,gCAAsC;AAC7C,KAAI,OAAO,aAAa,YAAa;CACrC,MAAM,UAAU,OAAO,YAAY;AACnC,UAAS,iBAAiB,mBAAmB;AAC3C,UAAQ,KAAK,wBAAwB;GACrC;;AAGJ,+BAA+B;AAwB/B,IAAI,OAAO,KAAK,IACd,QAAO,KAAK,IAAI,GAAG,YAAY,YAAyB;AACtD,kBAAiB,QAAQ,KAAK,QAAQ,aAAa;CACnD,MAAM,UAAU,OAAO,YAAY;AACnC,SAAQ,KAAK,YAAY,eAAe,QAAQ,CAAC;AACjD,SAAQ,KAAK,sBAAsB,QAAQ;EAC3C"}
|
package/dist/preview.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as globalTypes, r as initialGlobals, t as decorators } from "./preview-
|
|
1
|
+
import { n as globalTypes, r as initialGlobals, t as decorators } from "./preview-NOHYIleu.mjs";
|
|
2
2
|
export { decorators, globalTypes, initialGlobals };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@unpunnyfuns/swatchbook-addon",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.58.0",
|
|
4
4
|
"description": "Storybook addon for DTCG design tokens — toolbar, panel, and useToken hook.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "unpunnyfuns <unpunnyfuns@gmail.com>",
|
|
@@ -75,9 +75,9 @@
|
|
|
75
75
|
"dependencies": {
|
|
76
76
|
"jiti": "^2.4.0",
|
|
77
77
|
"picomatch": "^4.0.4",
|
|
78
|
-
"@unpunnyfuns/swatchbook-blocks": "0.
|
|
79
|
-
"@unpunnyfuns/swatchbook-core": "0.
|
|
80
|
-
"@unpunnyfuns/swatchbook-switcher": "0.
|
|
78
|
+
"@unpunnyfuns/swatchbook-blocks": "0.58.0",
|
|
79
|
+
"@unpunnyfuns/swatchbook-core": "0.58.0",
|
|
80
|
+
"@unpunnyfuns/swatchbook-switcher": "0.58.0"
|
|
81
81
|
},
|
|
82
82
|
"peerDependencies": {
|
|
83
83
|
"@storybook/react-vite": "^10.3.5",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"preview-661N0-BM.mjs","names":["virtualDisabledAxes","virtualDefaultTuple","virtualAxes","virtualPresets","virtualCells","virtualJointOverrides","virtualVarianceByPath","defaultTuple","virtualListing"],"sources":["../src/preview.tsx"],"sourcesContent":["/// <reference types=\"vite/client\" />\nimport { buildResolveAt } from '@unpunnyfuns/swatchbook-core/resolve-at';\nimport type {\n Axis as CoreAxis,\n Cells as CoreCells,\n JointOverrides,\n} from '@unpunnyfuns/swatchbook-core';\nimport type { Decorator, Preview } from '@storybook/react-vite';\nimport { useEffect, useMemo } from 'react';\nimport { addons } from 'storybook/preview-api';\nimport { dataAttr } from '@unpunnyfuns/swatchbook-core/data-attr';\nimport { ensureStyleElement } from '@unpunnyfuns/swatchbook-core/style-element';\nimport { tupleToName } from '@unpunnyfuns/swatchbook-core/themes';\n// Side-effect import for integrations that opted into `autoInject`\n// (e.g. Tailwind's `@theme` block). When no integration opts in, the\n// virtual module body is empty — still a valid no-op.\nimport 'virtual:swatchbook/integration-side-effects';\nimport {\n axes as virtualAxes,\n cells as virtualCells,\n css,\n cssVarPrefix,\n defaultTuple as virtualDefaultTuple,\n diagnostics,\n disabledAxes as virtualDisabledAxes,\n jointOverrides as virtualJointOverrides,\n listing as virtualListing,\n presets as virtualPresets,\n varianceByPath as virtualVarianceByPath,\n} from 'virtual:swatchbook/tokens';\nimport {\n AxesContext,\n COLOR_FORMATS,\n ColorFormatContext,\n SwatchbookContext,\n ThemeContext,\n} from '@unpunnyfuns/swatchbook-blocks';\nimport type { ColorFormat, ProjectSnapshot } from '@unpunnyfuns/swatchbook-blocks';\nimport {\n AXES_GLOBAL_KEY,\n COLOR_FORMAT_GLOBAL_KEY,\n HMR_EVENT,\n INIT_EVENT,\n INIT_REQUEST_EVENT,\n PREVIEW_MOUSEDOWN_EVENT,\n STYLE_ELEMENT_ID,\n TOKENS_UPDATED_EVENT,\n} from '#/constants.ts';\nimport type { StoryParameters, SwatchbookGlobals } from '#/globals.ts';\n\n/**\n * The `html, body { ... }` rules that paint the iframe's own chrome\n * (outside any decorator wrapper — Docs mode, autodocs, empty gutters)\n * with the active theme's surface + text vars. Composed alongside the\n * emitted token CSS so both load through the same `<style>` element.\n */\nfunction iframeChromeRules(prefix: string): string {\n const surface = prefix ? `--${prefix}-color-surface-default` : '--color-surface-default';\n const text = prefix ? `--${prefix}-color-text-default` : '--color-text-default';\n return `\nhtml, body {\n background: var(${surface}, Canvas);\n color: var(${text}, CanvasText);\n margin: 0;\n}\n`;\n}\n\n/**\n * Inject the per-theme stylesheet plus the iframe-chrome block. Shared\n * with the HMR re-emit path below so a token refresh updates the\n * iframe's chrome rules from the same source.\n */\nfunction ensureStylesheet(cssText: string, prefix: string): void {\n ensureStyleElement(STYLE_ELEMENT_ID, `${cssText}\\n${iframeChromeRules(prefix)}`);\n}\n\n/**\n * Apply `cb(axisName, value)` for every pinned (disabled) axis whose\n * default-tuple value is set. `virtualDefaultTuple` carries the\n * post-filter axis defaults; disabled axes don't appear in\n * `virtualAxes` but their pinned context value still lives here, so\n * sampling it gives the same result the old \"first permutation's\n * input\" lookup did.\n */\nfunction forEachPinnedAxis(cb: (name: string, value: string) => void): void {\n for (const name of virtualDisabledAxes) {\n const value = virtualDefaultTuple[name];\n if (value !== undefined) cb(name, value);\n }\n}\n\n/**\n * Compose a stable theme name from a tuple — `axisValues.join(' · ')`\n * in axis order. Used for the `data-<prefix>-theme` attribute and the\n * `swatchbook/theme` channel signal. Returns empty string when there\n * are no axes (no name to write).\n */\nfunction matchThemeName(tuple: Readonly<Record<string, string>>): string {\n if (virtualAxes.length === 0) return '';\n return tupleToName(virtualAxes, tuple);\n}\n\n/**\n * Write the composed permutation ID to `data-<prefix>-theme` plus one\n * `data-<prefix>-<axis>=<context>` per axis. Prefix follows `cssVarPrefix`\n * so the attr namespace and the emitted-CSS selectors stay in lockstep;\n * empty prefix keeps the bare `data-theme` form.\n */\nfunction setRootAxes(themeName: string, tuple: Readonly<Record<string, string>>): void {\n if (typeof document === 'undefined') return;\n const root = document.documentElement;\n const themeAttr = dataAttr(cssVarPrefix, 'theme');\n if (themeName) root.setAttribute(themeAttr, themeName);\n else root.removeAttribute(themeAttr);\n for (const axis of virtualAxes) {\n const attr = dataAttr(cssVarPrefix, axis.name);\n const value = tuple[axis.name];\n if (value === undefined) {\n root.removeAttribute(attr);\n } else {\n root.setAttribute(attr, value);\n }\n }\n forEachPinnedAxis((name, value) => {\n root.setAttribute(dataAttr(cssVarPrefix, name), value);\n });\n}\n\n/**\n * Subset of an INIT_EVENT-shaped object the manager bundle needs. The 9\n * fields are the union of what the toolbar and panel read; named so\n * `broadcastInit` (module-level virtual exports) and the HMR re-emit\n * (`payload`-shaped) compose the same payload from the same shape.\n */\ninterface InitFieldsSource {\n axes: typeof virtualAxes;\n disabledAxes: typeof virtualDisabledAxes;\n presets: typeof virtualPresets;\n diagnostics: typeof diagnostics;\n cssVarPrefix: string;\n cells: typeof virtualCells;\n jointOverrides: typeof virtualJointOverrides;\n varianceByPath: typeof virtualVarianceByPath;\n defaultTuple: typeof virtualDefaultTuple;\n}\n\nfunction pickInitFields(source: InitFieldsSource): InitFieldsSource {\n return {\n axes: source.axes,\n disabledAxes: source.disabledAxes,\n presets: source.presets,\n diagnostics: source.diagnostics,\n cssVarPrefix: source.cssVarPrefix,\n cells: source.cells,\n jointOverrides: source.jointOverrides,\n varianceByPath: source.varianceByPath,\n defaultTuple: source.defaultTuple,\n };\n}\n\n/**\n * Emit the full virtual-module payload to the manager over Storybook's\n * channel so the toolbar + panel (which run in the manager bundle and\n * can't import our virtual module) can render from it.\n */\nfunction broadcastInit(): void {\n const channel = addons.getChannel();\n channel.emit(\n INIT_EVENT,\n pickInitFields({\n axes: virtualAxes,\n disabledAxes: virtualDisabledAxes,\n presets: virtualPresets,\n diagnostics,\n cssVarPrefix,\n cells: virtualCells,\n jointOverrides: virtualJointOverrides,\n varianceByPath: virtualVarianceByPath,\n defaultTuple: virtualDefaultTuple,\n }),\n );\n}\n\n/** Axis-default tuple, used as the baseline before overrides. */\nfunction defaultTuple(): Record<string, string> {\n const out: Record<string, string> = {};\n for (const axis of virtualAxes) out[axis.name] = axis.default;\n return out;\n}\n\n/**\n * Reverse-engineer a tuple from a `Light · Brand A · Normal`-shape\n * theme name. Splits on ` · ` and zips with `virtualAxes` in declared\n * order — matches `matchThemeName`'s production direction so a\n * round-trip is lossless. Returns `undefined` when the segment count\n * doesn't match the axis count.\n */\nfunction tupleForName(name: string): Record<string, string> | undefined {\n if (!name) return undefined;\n const parts = name.split(' · ');\n if (parts.length !== virtualAxes.length) return undefined;\n const out: Record<string, string> = {};\n for (let i = 0; i < virtualAxes.length; i++) {\n const axis = virtualAxes[i] as (typeof virtualAxes)[number];\n const value = parts[i];\n if (value === undefined) return undefined;\n out[axis.name] = value;\n }\n return out;\n}\n\n/**\n * Merge a partial tuple onto the axis defaults, dropping keys for axes that\n * don't exist and silently falling back to the default for contexts that\n * aren't listed on the axis.\n */\nfunction normalizeTuple(partial: Readonly<Record<string, string>>): Record<string, string> {\n const out = defaultTuple();\n for (const axis of virtualAxes) {\n const candidate = partial[axis.name];\n if (candidate !== undefined && axis.contexts.includes(candidate)) {\n out[axis.name] = candidate;\n }\n }\n return out;\n}\n\n/**\n * Resolve the active tuple from all input channels, in priority order:\n * 1. `parameters.swatchbook.axes` — per-story tuple.\n * 2. `parameters.swatchbook.permutation` — per-story composed name.\n * 3. `globals.swatchbookAxes` — toolbar-set tuple.\n * 4. virtual module default.\n */\nfunction resolveTuple(\n globals: SwatchbookGlobals,\n parameters: StoryParameters,\n): Record<string, string> {\n const param = parameters.swatchbook;\n const paramAxes = param?.axes;\n if (paramAxes) {\n return normalizeTuple(paramAxes);\n }\n if (param?.permutation) {\n const hit = tupleForName(param.permutation);\n if (hit) return normalizeTuple(hit);\n }\n const globalAxes = globals[AXES_GLOBAL_KEY];\n if (globalAxes && typeof globalAxes === 'object') {\n return normalizeTuple(globalAxes as Record<string, string>);\n }\n return defaultTuple();\n}\n\nfunction resolveColorFormat(globals: SwatchbookGlobals): ColorFormat {\n const raw = globals[COLOR_FORMAT_GLOBAL_KEY];\n if (typeof raw === 'string' && (COLOR_FORMATS as readonly string[]).includes(raw)) {\n return raw as ColorFormat;\n }\n return 'hex';\n}\n\n/**\n * Single shared `resolveAt` instance for the lifetime of the preview\n * iframe. The inputs (`virtualAxes`, `virtualCells`, …) are all\n * module-level virtual-module exports with stable identity, so this\n * never needs to rebuild; downstream `ProjectSnapshot` consumers can\n * key memos on the snapshot wrapper without worrying about\n * `resolveAt` churning when Storybook recreates `context.globals`.\n */\nconst previewResolveAt = buildResolveAt(\n virtualAxes as readonly CoreAxis[],\n virtualCells as CoreCells,\n virtualJointOverrides as JointOverrides,\n virtualDefaultTuple,\n);\n\nconst themedDecorator: Decorator = (Story, context) => {\n const globals = context.globals as SwatchbookGlobals;\n const parameters = context.parameters as StoryParameters;\n const tuple = useMemo(() => resolveTuple(globals, parameters), [globals, parameters]);\n const colorFormat = useMemo(() => resolveColorFormat(globals), [globals]);\n const themeName = useMemo(() => matchThemeName(tuple), [tuple]);\n\n useEffect(() => {\n ensureStylesheet(css, cssVarPrefix);\n broadcastInit();\n }, []);\n\n useEffect(() => {\n setRootAxes(themeName, tuple);\n }, [themeName, tuple]);\n\n const wrapperAttrs: Record<string, string> = {};\n if (themeName) wrapperAttrs[dataAttr(cssVarPrefix, 'theme')] = themeName;\n for (const axis of virtualAxes) {\n const value = tuple[axis.name];\n if (value !== undefined) wrapperAttrs[dataAttr(cssVarPrefix, axis.name)] = value;\n }\n forEachPinnedAxis((name, value) => {\n wrapperAttrs[dataAttr(cssVarPrefix, name)] = value;\n });\n\n const snapshot = useMemo<ProjectSnapshot>(\n () => ({\n axes: virtualAxes,\n disabledAxes: virtualDisabledAxes,\n presets: virtualPresets,\n activeTheme: themeName,\n activeAxes: tuple,\n cssVarPrefix,\n diagnostics,\n css,\n listing: virtualListing,\n cells: virtualCells,\n jointOverrides: virtualJointOverrides,\n varianceByPath: virtualVarianceByPath,\n defaultTuple: virtualDefaultTuple,\n resolveAt: previewResolveAt,\n }),\n [themeName, tuple],\n );\n\n return (\n <SwatchbookContext.Provider value={snapshot}>\n <ThemeContext.Provider value={themeName}>\n <AxesContext.Provider value={tuple}>\n <ColorFormatContext.Provider value={colorFormat}>\n <div\n {...wrapperAttrs}\n style={{\n padding: '1rem',\n minHeight: '100%',\n }}\n >\n <Story />\n </div>\n </ColorFormatContext.Provider>\n </AxesContext.Provider>\n </ThemeContext.Provider>\n </SwatchbookContext.Provider>\n );\n};\n\n/**\n * Named exports consumed by `definePreviewAddon(previewExports)` in the\n * addon's CSF Next factory (`src/index.ts`).\n */\nexport const decorators: NonNullable<Preview['decorators']> = [themedDecorator];\n\nexport const globalTypes: NonNullable<Preview['globalTypes']> = {\n [AXES_GLOBAL_KEY]: {\n name: 'Axes',\n description: 'Per-axis context selection — the active permutation tuple.',\n },\n [COLOR_FORMAT_GLOBAL_KEY]: {\n name: 'Color format',\n description: 'Display format for color tokens in blocks. Emitted CSS is unaffected.',\n },\n};\n\nfunction buildInitialAxes(): Record<string, string> {\n const out: Record<string, string> = {};\n for (const axis of virtualAxes) out[axis.name] = axis.default;\n return out;\n}\n\nexport const initialGlobals: NonNullable<Preview['initialGlobals']> = {\n [AXES_GLOBAL_KEY]: buildInitialAxes(),\n [COLOR_FORMAT_GLOBAL_KEY]: 'hex',\n};\n\n/**\n * Module-level channel subscription: writes the active tuple's attributes\n * onto `<html>` regardless of whether a story decorator is rendering.\n *\n * The {@link themedDecorator} already sets these inside story renders, but\n * it never runs on MDX docs pages that embed blocks without `<Story />`.\n * Without attrs on an ancestor, the per-tuple CSS selectors\n * (`[data-mode=\"Dark\"][data-brand=\"…\"]`) don't match and everything falls\n * back to the `:root` default tuple — so colors stay defaults even after\n * the toolbar switches axes. Subscribing globally fixes MDX docs at the\n * cost of one idempotent redundant write per story render.\n */\nfunction installGlobalAxisApplier(): void {\n if (typeof document === 'undefined') return;\n const channel = addons.getChannel();\n /**\n * Inject the stylesheet and emit the init payload once on module load so\n * the manager's toolbar populates and CSS vars are available even when no\n * story/decorator ever runs (bare MDX docs pages). Without these, the\n * toolbar sits in its disabled \"loading…\" state and nothing is styled.\n */\n ensureStylesheet(css, cssVarPrefix);\n broadcastInit();\n /**\n * If the manager subscribes to INIT_EVENT after our initial broadcast,\n * it misses the payload and the toolbar stays in its \"loading…\" state\n * until something else re-fires it. Honor an explicit request event so\n * a late-mounting manager can ask for the payload.\n */\n channel.on(INIT_REQUEST_EVENT, broadcastInit);\n const apply = (globals: SwatchbookGlobals): void => {\n ensureStylesheet(css, cssVarPrefix);\n const tuple = resolveTuple(globals, {});\n setRootAxes(matchThemeName(tuple), tuple);\n };\n // Storybook fires `globalsUpdated`, `setGlobals`, and `updateGlobals`\n // for the same logical change (preview init + every toolbar tick).\n // Subscribing to all three is intentional — `setGlobals` carries the\n // initial URL-persisted globals; `updateGlobals` is the toolbar\n // signal; `globalsUpdated` is the cross-frame echo. Apply the same\n // handler to all three but dedupe via a stringified-tuple guard so\n // downstream `setRootAxes` + `useSyncExternalStore` consumers\n // re-render at most once per real change instead of three times per\n // tick.\n let lastApplied = '';\n const onGlobals = (payload: { globals?: SwatchbookGlobals }): void => {\n if (!payload.globals) return;\n const tuple = resolveTuple(payload.globals, {});\n const fingerprint = matchThemeName(tuple);\n if (fingerprint === lastApplied) return;\n lastApplied = fingerprint;\n apply(payload.globals);\n };\n channel.on('globalsUpdated', onGlobals);\n channel.on('setGlobals', onGlobals);\n channel.on('updateGlobals', onGlobals);\n}\n\ninstallGlobalAxisApplier();\n\n/**\n * Bridge `mousedown` inside the preview iframe to the manager via a\n * dedicated channel event. The toolbar popover's outside-click listener\n * runs on the manager's document, which can't observe mousedowns inside\n * the preview; without this bridge, clicking the canvas leaves the\n * popover open. Idempotent: fires at most once per real mousedown.\n */\nfunction installPreviewMouseDownBridge(): void {\n if (typeof document === 'undefined') return;\n const channel = addons.getChannel();\n document.addEventListener('mousedown', () => {\n channel.emit(PREVIEW_MOUSEDOWN_EVENT);\n });\n}\n\ninstallPreviewMouseDownBridge();\n\n/**\n * Wire the dev-time token-refresh HMR path. The plugin emits `HMR_EVENT`\n * with the fresh virtual-module payload whenever a watched source file\n * changes; we re-inject the stylesheet and forward to the Storybook\n * channel so the toolbar re-renders and blocks can re-subscribe with\n * the new snapshot — no full preview reload, so args / scroll / open\n * overlays survive the refresh. No-ops in production where\n * `import.meta.hot` is undefined.\n */\ninterface HmrSnapshot {\n axes: typeof virtualAxes;\n disabledAxes: typeof virtualDisabledAxes;\n presets: typeof virtualPresets;\n diagnostics: typeof diagnostics;\n css: string;\n cssVarPrefix: string;\n listing: typeof virtualListing;\n cells: typeof virtualCells;\n jointOverrides: typeof virtualJointOverrides;\n varianceByPath: typeof virtualVarianceByPath;\n defaultTuple: typeof virtualDefaultTuple;\n}\nif (import.meta.hot) {\n import.meta.hot.on(HMR_EVENT, (payload: HmrSnapshot) => {\n ensureStylesheet(payload.css, payload.cssVarPrefix);\n const channel = addons.getChannel();\n channel.emit(INIT_EVENT, pickInitFields(payload));\n channel.emit(TOKENS_UPDATED_EVENT, payload);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,SAAS,kBAAkB,QAAwB;AAGjD,QAAO;;oBAFS,SAAS,KAAK,OAAO,0BAA0B,0BAIrC;eAHb,SAAS,KAAK,OAAO,uBAAuB,uBAIvC;;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