@unpunnyfuns/swatchbook-addon 0.55.0 → 0.57.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.
@@ -1,6 +1,7 @@
1
1
  import { buildResolveAt } from "@unpunnyfuns/swatchbook-core/resolve-at";
2
2
  import { axes, cells, cssVarPrefix, defaultTuple, jointOverrides } from "virtual:swatchbook/tokens";
3
3
  import { useActiveAxes, useOptionalSwatchbookData } from "@unpunnyfuns/swatchbook-blocks";
4
+ import { makeCssVar } from "@unpunnyfuns/swatchbook-core/css-var";
4
5
  //#region src/hooks/use-token.ts
5
6
  /**
6
7
  * Module-scope `resolveAt` for the no-provider fallback path. Built
@@ -9,11 +10,7 @@ import { useActiveAxes, useOptionalSwatchbookData } from "@unpunnyfuns/swatchboo
9
10
  * file so the hook can be called outside the addon's preview wrapper
10
11
  * (autodocs / MDX renders).
11
12
  */
12
- const fallbackResolveAt = buildResolveAt(axes, cells, new Map(jointOverrides), defaultTuple);
13
- function makeCssVar(path, prefix) {
14
- const tail = path.replaceAll(".", "-");
15
- return prefix ? `var(--${prefix}-${tail})` : `var(--${tail})`;
16
- }
13
+ const fallbackResolveAt = buildResolveAt(axes, cells, jointOverrides, defaultTuple);
17
14
  /**
18
15
  * Read a DTCG token for the currently active theme. Re-reads on theme
19
16
  * switch via the addon's `SwatchbookContext`. Returns `{ value, cssVar,
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["virtualAxes","virtualCells","virtualJointOverrides","virtualDefaultTuple","virtualCssVarPrefix"],"sources":["../../src/hooks/use-token.ts"],"sourcesContent":["import {\n axes as virtualAxes,\n cells as virtualCells,\n cssVarPrefix as virtualCssVarPrefix,\n defaultTuple as virtualDefaultTuple,\n jointOverrides as virtualJointOverrides,\n} from 'virtual:swatchbook/tokens';\nimport { buildResolveAt } from '@unpunnyfuns/swatchbook-core/resolve-at';\nimport type {\n Axis as CoreAxis,\n Cells as CoreCells,\n JointOverride,\n JointOverrides,\n} from '@unpunnyfuns/swatchbook-core';\nimport { useActiveAxes, useOptionalSwatchbookData } from '@unpunnyfuns/swatchbook-blocks';\n\n/**\n * Module-scope `resolveAt` for the no-provider fallback path. Built\n * once from the stable virtual-module exports — mirrors what the\n * preview decorator does for its `previewResolveAt` but lives in this\n * file so the hook can be called outside the addon's preview wrapper\n * (autodocs / MDX renders).\n */\nconst fallbackResolveAt = buildResolveAt(\n virtualAxes as readonly CoreAxis[],\n virtualCells as CoreCells,\n new Map(virtualJointOverrides as readonly (readonly [string, JointOverride])[]) as JointOverrides,\n virtualDefaultTuple,\n);\n\n/**\n * Consumers augment this interface (via the addon's generated\n * `.swatchbook/tokens.d.ts`) to narrow {@link useToken}'s first parameter\n * to their project's actual token paths. Without augmentation it's empty\n * and {@link TokenPath} falls back to `string`.\n */\nexport interface SwatchbookTokenMap {}\n\ntype KnownPath = keyof SwatchbookTokenMap;\n\n/** Union of known token paths, or `string` when the addon codegen hasn't run. */\nexport type TokenPath = [KnownPath] extends [never] ? string : KnownPath;\n\nexport interface TokenInfo {\n /** The resolved DTCG `$value`. Shape varies by `$type`. */\n value: unknown;\n /** `var(--prefix-token-path)` reference, ready to drop into any CSS value. */\n cssVar: string;\n /** DTCG `$type` of the token, if known. */\n type?: string;\n /** Optional DTCG `$description`. */\n description?: string;\n}\n\nfunction makeCssVar(path: string, prefix: string): string {\n const tail = path.replaceAll('.', '-');\n return prefix ? `var(--${prefix}-${tail})` : `var(--${tail})`;\n}\n\n/**\n * Read a DTCG token for the currently active theme. Re-reads on theme\n * switch via the addon's `SwatchbookContext`. Returns `{ value, cssVar,\n * type, description }`.\n *\n * Typed paths appear automatically once `.swatchbook/tokens.d.ts` is\n * generated (happens on first storybook start/build). Until then\n * `TokenPath` is `string`.\n *\n * Safe to call in autodocs / MDX renders — uses plain React context, not\n * Storybook's preview-only hooks. Reads from the addon-provided\n * `SwatchbookContext` when present (preferred — uses the lifted\n * `resolveAt` accessor and the live active tuple); falls back to the\n * virtual module's eager `permutationsResolved` lookup keyed by the\n * default permutation name when no provider is mounted.\n */\nexport function useToken(path: TokenPath): TokenInfo {\n const snapshot = useOptionalSwatchbookData();\n const contextAxes = useActiveAxes();\n const hasContextAxes = Object.keys(contextAxes).length > 0;\n\n const prefix = snapshot?.cssVarPrefix ?? virtualCssVarPrefix;\n const resolver = snapshot?.resolveAt ?? fallbackResolveAt;\n const tuple = hasContextAxes\n ? (contextAxes as Record<string, string>)\n : (snapshot?.defaultTuple ?? virtualDefaultTuple);\n const token = resolver(tuple)[path] as\n | { $value?: unknown; $type?: string; $description?: string }\n | undefined;\n\n const info: TokenInfo = {\n value: token?.$value,\n cssVar: makeCssVar(path, prefix),\n };\n if (token?.$type) info.type = token.$type;\n if (token?.$description) info.description = token.$description;\n return info;\n}\n"],"mappings":";;;;;;;;;;;AAuBA,MAAM,oBAAoB,eACxBA,MACAC,OACA,IAAI,IAAIC,eAAuE,EAC/EC,aACD;AA0BD,SAAS,WAAW,MAAc,QAAwB;CACxD,MAAM,OAAO,KAAK,WAAW,KAAK,IAAI;AACtC,QAAO,SAAS,SAAS,OAAO,GAAG,KAAK,KAAK,SAAS,KAAK;;;;;;;;;;;;;;;;;;AAmB7D,SAAgB,SAAS,MAA4B;CACnD,MAAM,WAAW,2BAA2B;CAC5C,MAAM,cAAc,eAAe;CACnC,MAAM,iBAAiB,OAAO,KAAK,YAAY,CAAC,SAAS;CAEzD,MAAM,SAAS,UAAU,gBAAgBC;CAKzC,MAAM,SAJW,UAAU,aAAa,mBAC1B,iBACT,cACA,UAAU,gBAAgBD,aACF,CAAC;CAI9B,MAAM,OAAkB;EACtB,OAAO,OAAO;EACd,QAAQ,WAAW,MAAM,OAAO;EACjC;AACD,KAAI,OAAO,MAAO,MAAK,OAAO,MAAM;AACpC,KAAI,OAAO,aAAc,MAAK,cAAc,MAAM;AAClD,QAAO"}
1
+ {"version":3,"file":"index.mjs","names":["virtualAxes","virtualCells","virtualJointOverrides","virtualDefaultTuple","virtualCssVarPrefix"],"sources":["../../src/hooks/use-token.ts"],"sourcesContent":["import {\n axes as virtualAxes,\n cells as virtualCells,\n cssVarPrefix as virtualCssVarPrefix,\n defaultTuple as virtualDefaultTuple,\n jointOverrides as virtualJointOverrides,\n} from 'virtual:swatchbook/tokens';\nimport { buildResolveAt } from '@unpunnyfuns/swatchbook-core/resolve-at';\nimport { makeCssVar } from '@unpunnyfuns/swatchbook-core/css-var';\nimport type {\n Axis as CoreAxis,\n Cells as CoreCells,\n JointOverrides,\n} from '@unpunnyfuns/swatchbook-core';\nimport { useActiveAxes, useOptionalSwatchbookData } from '@unpunnyfuns/swatchbook-blocks';\n\n/**\n * Module-scope `resolveAt` for the no-provider fallback path. Built\n * once from the stable virtual-module exports — mirrors what the\n * preview decorator does for its `previewResolveAt` but lives in this\n * file so the hook can be called outside the addon's preview wrapper\n * (autodocs / MDX renders).\n */\nconst fallbackResolveAt = buildResolveAt(\n virtualAxes as readonly CoreAxis[],\n virtualCells as CoreCells,\n virtualJointOverrides as JointOverrides,\n virtualDefaultTuple,\n);\n\n/**\n * Consumers augment this interface (via the addon's generated\n * `.swatchbook/tokens.d.ts`) to narrow {@link useToken}'s first parameter\n * to their project's actual token paths. Without augmentation it's empty\n * and {@link TokenPath} falls back to `string`.\n */\nexport interface SwatchbookTokenMap {}\n\ntype KnownPath = keyof SwatchbookTokenMap;\n\n/** Union of known token paths, or `string` when the addon codegen hasn't run. */\nexport type TokenPath = [KnownPath] extends [never] ? string : KnownPath;\n\nexport interface TokenInfo {\n /** The resolved DTCG `$value`. Shape varies by `$type`. */\n value: unknown;\n /** `var(--prefix-token-path)` reference, ready to drop into any CSS value. */\n cssVar: string;\n /** DTCG `$type` of the token, if known. */\n type?: string;\n /** Optional DTCG `$description`. */\n description?: string;\n}\n\n/**\n * Read a DTCG token for the currently active theme. Re-reads on theme\n * switch via the addon's `SwatchbookContext`. Returns `{ value, cssVar,\n * type, description }`.\n *\n * Typed paths appear automatically once `.swatchbook/tokens.d.ts` is\n * generated (happens on first storybook start/build). Until then\n * `TokenPath` is `string`.\n *\n * Safe to call in autodocs / MDX renders — uses plain React context, not\n * Storybook's preview-only hooks. Reads from the addon-provided\n * `SwatchbookContext` when present (preferred — uses the lifted\n * `resolveAt` accessor and the live active tuple); falls back to the\n * virtual module's eager `permutationsResolved` lookup keyed by the\n * default permutation name when no provider is mounted.\n */\nexport function useToken(path: TokenPath): TokenInfo {\n const snapshot = useOptionalSwatchbookData();\n const contextAxes = useActiveAxes();\n const hasContextAxes = Object.keys(contextAxes).length > 0;\n\n const prefix = snapshot?.cssVarPrefix ?? virtualCssVarPrefix;\n const resolver = snapshot?.resolveAt ?? fallbackResolveAt;\n const tuple = hasContextAxes\n ? (contextAxes as Record<string, string>)\n : (snapshot?.defaultTuple ?? virtualDefaultTuple);\n const token = resolver(tuple)[path] as\n | { $value?: unknown; $type?: string; $description?: string }\n | undefined;\n\n const info: TokenInfo = {\n value: token?.$value,\n cssVar: makeCssVar(path, prefix),\n };\n if (token?.$type) info.type = token.$type;\n if (token?.$description) info.description = token.$description;\n return info;\n}\n"],"mappings":";;;;;;;;;;;;AAuBA,MAAM,oBAAoB,eACxBA,MACAC,OACAC,gBACAC,aACD;;;;;;;;;;;;;;;;;AA0CD,SAAgB,SAAS,MAA4B;CACnD,MAAM,WAAW,2BAA2B;CAC5C,MAAM,cAAc,eAAe;CACnC,MAAM,iBAAiB,OAAO,KAAK,YAAY,CAAC,SAAS;CAEzD,MAAM,SAAS,UAAU,gBAAgBC;CAKzC,MAAM,SAJW,UAAU,aAAa,mBAC1B,iBACT,cACA,UAAU,gBAAgBD,aACF,CAAC;CAI9B,MAAM,OAAkB;EACtB,OAAO,OAAO;EACd,QAAQ,WAAW,MAAM,OAAO;EACjC;AACD,KAAI,OAAO,MAAO,MAAK,OAAO,MAAM;AACpC,KAAI,OAAO,aAAc,MAAK,cAAc,MAAM;AAClD,QAAO"}
package/dist/index.d.mts CHANGED
@@ -5,9 +5,12 @@ export * from "@unpunnyfuns/swatchbook-switcher";
5
5
 
6
6
  //#region src/constants.d.ts
7
7
  declare const ADDON_ID = "swatchbook";
8
+ declare const TOOL_ID = "swatchbook/theme-switcher";
8
9
  declare const PARAM_KEY = "swatchbook";
9
10
  /** Canonical active-permutation tuple: `Record<axisName, contextName>`. Read by toolbar, panel, blocks. */
10
11
  declare const AXES_GLOBAL_KEY = "swatchbookAxes";
12
+ /** Display-only color format for blocks (`hex` | `rgb` | `hsl` | `oklch` | `raw`). Emitted CSS is unaffected. */
13
+ declare const COLOR_FORMAT_GLOBAL_KEY = "swatchbookColorFormat";
11
14
  declare const VIRTUAL_MODULE_ID = "virtual:swatchbook/tokens";
12
15
  //#endregion
13
16
  //#region src/index.d.ts
@@ -18,5 +21,5 @@ declare const VIRTUAL_MODULE_ID = "virtual:swatchbook/tokens";
18
21
  */
19
22
  declare function swatchbookAddon(): ReturnType<typeof definePreviewAddon>;
20
23
  //#endregion
21
- export { ADDON_ID, AXES_GLOBAL_KEY, type AddonOptions, PARAM_KEY, VIRTUAL_MODULE_ID, swatchbookAddon as default };
24
+ export { ADDON_ID, AXES_GLOBAL_KEY, type AddonOptions, COLOR_FORMAT_GLOBAL_KEY, PARAM_KEY, TOOL_ID, VIRTUAL_MODULE_ID, swatchbookAddon as default };
22
25
  //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { i as preview_exports } from "./preview-DvtUsEMq.mjs";
2
- import { c as PARAM_KEY, h as VIRTUAL_MODULE_ID, n as AXES_GLOBAL_KEY, t as ADDON_ID } from "./constants-B31xFInv.mjs";
1
+ import { i as preview_exports } from "./preview-661N0-BM.mjs";
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";
5
5
  export * from "@unpunnyfuns/swatchbook-switcher";
@@ -13,6 +13,6 @@ function swatchbookAddon() {
13
13
  return definePreviewAddon(preview_exports);
14
14
  }
15
15
  //#endregion
16
- export { ADDON_ID, AXES_GLOBAL_KEY, PARAM_KEY, VIRTUAL_MODULE_ID, swatchbookAddon as default };
16
+ export { ADDON_ID, AXES_GLOBAL_KEY, COLOR_FORMAT_GLOBAL_KEY, PARAM_KEY, TOOL_ID, VIRTUAL_MODULE_ID, swatchbookAddon as default };
17
17
 
18
18
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["previewExports"],"sources":["../src/index.ts"],"sourcesContent":["import { definePreviewAddon } from 'storybook/internal/csf';\nimport * as previewExports from '#/preview.tsx';\n\nexport { ADDON_ID, AXES_GLOBAL_KEY, PARAM_KEY, VIRTUAL_MODULE_ID } from '#/constants.ts';\nexport type { AddonOptions } from '#/options.ts';\n\n/**\n * Re-export the full user-facing surface from `@unpunnyfuns/swatchbook-blocks`\n * and `@unpunnyfuns/swatchbook-switcher` so consumers can\n * `import { TokenTable, ThemeSwitcher, useToken } from '@unpunnyfuns/swatchbook-addon'`\n * without adding the sibling packages to their own package.json. Both are\n * declared as regular dependencies of the addon, so they come along for the\n * ride. Subpath entries (`./preset`, `./manager`, `./preview`, `./hooks`)\n * still exist for Storybook's preset loader — this meta re-export is just\n * for the React / MDX consumer path.\n */\nexport * from '@unpunnyfuns/swatchbook-blocks';\nexport * from '@unpunnyfuns/swatchbook-switcher';\n\n/**\n * CSF Next factory. Consumers call this inside\n * `definePreview({ addons: [swatchbookAddon()] })` so the preview annotations\n * (decorator, globalTypes, initialGlobals) are added to the preview bundle.\n */\nexport default function swatchbookAddon(): ReturnType<typeof definePreviewAddon> {\n return definePreviewAddon(previewExports);\n}\n"],"mappings":";;;;;;;;;;;AAwBA,SAAwB,kBAAyD;AAC/E,QAAO,mBAAmBA,gBAAe"}
1
+ {"version":3,"file":"index.mjs","names":["previewExports"],"sources":["../src/index.ts"],"sourcesContent":["import { definePreviewAddon } from 'storybook/internal/csf';\nimport * as previewExports from '#/preview.tsx';\n\nexport type { AddonOptions } from '#/options.ts';\n\n/**\n * Public namespace constants — addon ID, parameter / global keys, the\n * canonical virtual module ID. Useful for consumer code that needs to\n * reach into the addon's namespace (custom toolbar registrations,\n * channel events, manager hooks that need a stable handle on these keys).\n */\nexport {\n ADDON_ID,\n AXES_GLOBAL_KEY,\n COLOR_FORMAT_GLOBAL_KEY,\n PARAM_KEY,\n TOOL_ID,\n VIRTUAL_MODULE_ID,\n} from '#/constants.ts';\n\n/**\n * Re-export the full user-facing surface from `@unpunnyfuns/swatchbook-blocks`\n * and `@unpunnyfuns/swatchbook-switcher` so consumers can\n * `import { TokenTable, ThemeSwitcher, useToken } from '@unpunnyfuns/swatchbook-addon'`\n * without adding the sibling packages to their own package.json. Both are\n * declared as regular dependencies of the addon, so they come along for the\n * ride. Subpath entries (`./preset`, `./manager`, `./preview`, `./hooks`)\n * still exist for Storybook's preset loader — this meta re-export is just\n * for the React / MDX consumer path.\n */\nexport * from '@unpunnyfuns/swatchbook-blocks';\nexport * from '@unpunnyfuns/swatchbook-switcher';\n\n/**\n * CSF Next factory. Consumers call this inside\n * `definePreview({ addons: [swatchbookAddon()] })` so the preview annotations\n * (decorator, globalTypes, initialGlobals) are added to the preview bundle.\n */\nexport default function swatchbookAddon(): ReturnType<typeof definePreviewAddon> {\n return definePreviewAddon(previewExports);\n}\n"],"mappings":";;;;;;;;;;;AAsCA,SAAwB,kBAAyD;AAC/E,QAAO,mBAAmBA,gBAAe"}
package/dist/manager.mjs CHANGED
@@ -1,9 +1,39 @@
1
1
  import { a as INIT_EVENT, l as PREVIEW_MOUSEDOWN_EVENT, m as TOOL_ID, n as AXES_GLOBAL_KEY, o as INIT_REQUEST_EVENT, r as COLOR_FORMAT_GLOBAL_KEY, t as ADDON_ID } from "./constants-B31xFInv.mjs";
2
2
  import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
3
- import { ThemeSwitcher } from "@unpunnyfuns/swatchbook-switcher";
4
- import { IconButton, WithTooltipPure } from "storybook/internal/components";
3
+ import { ThemeSwitcher, presetTuple } from "@unpunnyfuns/swatchbook-switcher";
4
+ import { Button, ToggleButton, WithTooltip } from "storybook/internal/components";
5
5
  import { addons, types, useGlobals, useStorybookApi } from "storybook/manager-api";
6
6
  //#region src/ColorFormatSelector.tsx
7
+ /**
8
+ * Storybook-addon-specific pill row for picking how color sub-values
9
+ * render in swatchbook blocks (hex / rgb / hsl / oklch / raw). Lives in
10
+ * the addon rather than the shared switcher because color format is a
11
+ * blocks-rendering concern, not a theming one — the docs-site navbar
12
+ * switcher has no consumer for it.
13
+ *
14
+ * Reuses the `sb-switcher__*` class names so styling stays consistent
15
+ * with the rest of the toolbar popover. The switcher's CSS is already
16
+ * loaded on the page because this selector only renders inside
17
+ * `<ThemeSwitcher>`'s `footer` prop.
18
+ *
19
+ * Uses `React.createElement` (via `h`) to survive embedding in Storybook's
20
+ * manager bundle, which doesn't expose `react/jsx-runtime`.
21
+ */
22
+ /**
23
+ * Runtime list of valid color formats. Declared here (alongside
24
+ * `COLOR_FORMAT_OPTIONS`) rather than imported from blocks because the
25
+ * manager bundle can't pull from `@unpunnyfuns/swatchbook-blocks` — that
26
+ * package's barrel has a top-level `import 'virtual:swatchbook/tokens'`
27
+ * which the manager has no resolver for. The `ColorFormat` type above
28
+ * stays imported (type-only erases at compile time).
29
+ */
30
+ const COLOR_FORMATS = [
31
+ "hex",
32
+ "rgb",
33
+ "hsl",
34
+ "oklch",
35
+ "raw"
36
+ ];
7
37
  const COLOR_FORMAT_OPTIONS = [
8
38
  {
9
39
  id: "hex",
@@ -80,20 +110,6 @@ function defaultTupleFor(axes) {
80
110
  for (const axis of axes) out[axis.name] = axis.default;
81
111
  return out;
82
112
  }
83
- /**
84
- * Compose a preset's sanitized partial tuple with the axis defaults, so
85
- * applying a preset that only names some axes leaves the omitted ones at
86
- * their defaults (not blank). Mirrors the preview decorator's own fallback
87
- * logic so what the toolbar sends out is what the decorator honors.
88
- */
89
- function presetTuple(preset, axes, defaults) {
90
- const out = { ...defaults };
91
- for (const axis of axes) {
92
- const candidate = preset.axes[axis.name];
93
- if (candidate !== void 0 && axis.contexts.includes(candidate)) out[axis.name] = candidate;
94
- }
95
- return out;
96
- }
97
113
  function AxesToolbar() {
98
114
  const [globals, updateGlobals] = useGlobals();
99
115
  const api = useStorybookApi();
@@ -119,8 +135,10 @@ function AxesToolbar() {
119
135
  const presets = payload?.presets ?? EMPTY_PRESETS;
120
136
  const defaults = useMemo(() => defaultTupleFor(axes), [axes]);
121
137
  const [lastApplied, setLastApplied] = useState(null);
122
- const globalTuple = globals[AXES_GLOBAL_KEY];
123
- const activeColorFormat = globals["swatchbookColorFormat"] ?? "hex";
138
+ const rawTuple = globals[AXES_GLOBAL_KEY];
139
+ const globalTuple = rawTuple && typeof rawTuple === "object" ? rawTuple : void 0;
140
+ const rawColorFormat = globals[COLOR_FORMAT_GLOBAL_KEY];
141
+ const activeColorFormat = typeof rawColorFormat === "string" && COLOR_FORMATS.includes(rawColorFormat) ? rawColorFormat : "hex";
124
142
  const activeTuple = useMemo(() => {
125
143
  const out = { ...defaults };
126
144
  if (globalTuple) for (const axis of axes) {
@@ -191,7 +209,7 @@ function AxesToolbar() {
191
209
  return () => document.removeEventListener("keydown", onDocKey);
192
210
  }, [open]);
193
211
  /**
194
- * `WithTooltipPure`'s built-in `closeOnOutsideClick` misses some cases
212
+ * `WithTooltip`'s built-in `closeOnOutsideClick` misses some cases
195
213
  * (portaled popover + manager iframe boundaries). Belt-and-suspenders:
196
214
  * close when the user mouses down anywhere that isn't the trigger wrapper
197
215
  * or the popover body.
@@ -220,15 +238,18 @@ function AxesToolbar() {
220
238
  channel.off(PREVIEW_MOUSEDOWN_EVENT, onPreviewMouseDown);
221
239
  };
222
240
  }, [open]);
223
- if (axes.length === 0) return h(IconButton, {
241
+ if (axes.length === 0) return h(Button, {
224
242
  key: TOOL_ID,
225
- title: "Swatchbook theme (loading…)",
243
+ ariaLabel: "Swatchbook theme (loading…)",
244
+ tooltip: "Swatchbook theme (loading…)",
226
245
  disabled: true
227
246
  }, h(SwatchbookIcon));
228
- const button = h(IconButton, {
247
+ const label = `Swatchbook · ${axes.map((a) => activeTuple[a.name] ?? a.default).join(" · ")}`;
248
+ const button = h(ToggleButton, {
229
249
  key: TOOL_ID,
230
- title: `Swatchbook · ${axes.map((a) => activeTuple[a.name] ?? a.default).join(" · ")}`,
231
- active: open,
250
+ ariaLabel: label,
251
+ tooltip: label,
252
+ pressed: open,
232
253
  onClick: () => setOpen((prev) => !prev),
233
254
  "aria-haspopup": "dialog",
234
255
  "aria-expanded": open
@@ -253,7 +274,7 @@ function AxesToolbar() {
253
274
  display: "inline-flex",
254
275
  alignItems: "center"
255
276
  }
256
- }, h(WithTooltipPure, {
277
+ }, h(WithTooltip, {
257
278
  placement: "bottom",
258
279
  trigger: "click",
259
280
  visible: open,
@@ -1 +1 @@
1
- {"version":3,"file":"manager.mjs","names":["h"],"sources":["../src/ColorFormatSelector.tsx","../src/manager.tsx"],"sourcesContent":["import React, { type ReactElement } from 'react';\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\nexport type 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 { ThemeSwitcher } from '@unpunnyfuns/swatchbook-switcher';\nimport { type ColorFormat, ColorFormatSelector } from '#/ColorFormatSelector.tsx';\nimport React, { useCallback, useEffect, useMemo, useRef, useState, type ReactElement } from 'react';\nimport { IconButton, WithTooltipPure } from 'storybook/internal/components';\nimport { addons, types, useGlobals, useStorybookApi } from 'storybook/manager-api';\nimport {\n type InitPayload,\n type VirtualAxis as AxisEntry,\n type 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\n/**\n * Compose a preset's sanitized partial tuple with the axis defaults, so\n * applying a preset that only names some axes leaves the omitted ones at\n * their defaults (not blank). Mirrors the preview decorator's own fallback\n * logic so what the toolbar sends out is what the decorator honors.\n */\nfunction presetTuple(\n preset: PresetEntry,\n axes: readonly AxisEntry[],\n defaults: Readonly<Record<string, string>>,\n): Record<string, string> {\n const out: Record<string, string> = { ...defaults };\n for (const axis of axes) {\n const candidate = preset.axes[axis.name];\n if (candidate !== undefined && axis.contexts.includes(candidate)) {\n out[axis.name] = candidate;\n }\n }\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 globalTuple = globals[AXES_GLOBAL_KEY] as Record<string, string> | undefined;\n const activeColorFormat = ((globals[COLOR_FORMAT_GLOBAL_KEY] as string | undefined) ??\n 'hex') as ColorFormat;\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 * `WithTooltipPure`'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 IconButton,\n { key: TOOL_ID, title: 'Swatchbook theme (loading…)', disabled: true },\n h(SwatchbookIcon),\n );\n }\n\n const summary = axes.map((a) => activeTuple[a.name] ?? a.default).join(' · ');\n const title = `Swatchbook · ${summary}`;\n\n const button = h(\n IconButton,\n {\n key: TOOL_ID,\n title,\n active: open,\n onClick: () => setOpen((prev) => !prev),\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 `WithTooltipPure` 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 '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(WithTooltipPure, {\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":";;;;;;AAoBA,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,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,SAAS,EACb,YACA;EACE,KAAK;EACL,OANU,gBADE,KAAK,KAAK,MAAM,YAAY,EAAE,SAAS,EAAE,QAAQ,CAAC,KAAK,MAAM;EAQzE,QAAQ;EACR,eAAe,SAAS,SAAS,CAAC,KAAK;EAMvC,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,iBAAiB;EACjB,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('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 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,IAAE,OAAO,EAAE,WAAW,8BAA8B,EAAE,eAAe,EACrEA,IACE,OACA,EAAE,WAAW,6BAA6B,EAC1C,GAAG,qBAAqB,KAAK,QAC3BA,IACE,UACA;EACE,KAAK,gBAAgB,IAAI;EACzB,MAAM;EACN,eAAe,SAAS,IAAI,GAAG;EAC/B,cAAc,UAA4B,MAAM,gBAAgB;EAChE,WACE,IAAI,OAAO,SACP,gDACA;EACP,EACD,IAAI,MACL,CACF,CACF,CACF;;;;;;;;;;;;;;;;ACtCH,MAAM,IAAI,MAAM;AAEhB,MAAM,aAAmC,EAAE;AAC3C,MAAM,gBAAwC,EAAE;;;;;;AAOhD,SAAS,iBAA+B;AACtC,QAAO,EACL,OACA;EAAE,OAAO;EAAI,QAAQ;EAAI,SAAS;EAAa,eAAe;EAAM,EACpE,EAAE,UAAU;EAAE,IAAI;EAAG,IAAI;EAAG,GAAG;EAAG,MAAM;EAAgB,SAAS;EAAM,CAAC,EACxE,EAAE,QAA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EACF"}
package/dist/preset.mjs CHANGED
@@ -1,9 +1,11 @@
1
1
  import { d as RESOLVED_VIRTUAL_MODULE_ID, i as HMR_EVENT, u as RESOLVED_INTEGRATION_SIDE_EFFECTS_VIRTUAL_ID } from "./constants-B31xFInv.mjs";
2
+ import { enumerateThemes } from "@unpunnyfuns/swatchbook-core/themes";
2
3
  import { mkdir, writeFile } from "node:fs/promises";
3
4
  import { basename, dirname, isAbsolute, resolve } from "node:path";
4
5
  import { fileURLToPath, pathToFileURL } from "node:url";
5
6
  import { emitAxisProjectedCss, loadProject } from "@unpunnyfuns/swatchbook-core";
6
7
  import { createJiti } from "jiti";
8
+ import { snapshotForWire } from "@unpunnyfuns/swatchbook-core/snapshot-for-wire";
7
9
  import { watch } from "node:fs";
8
10
  import "picomatch";
9
11
  //#region src/virtual/plugin.ts
@@ -17,9 +19,9 @@ function resolvedId(virtualId) {
17
19
  * and diagnostics. Watches the token files + resolver for changes and
18
20
  * invalidates the module so HMR reloads the preview with fresh data.
19
21
  */
20
- function swatchbookTokensPlugin({ config, cwd, integrations = [] }) {
21
- let project;
22
- let css = "";
22
+ function swatchbookTokensPlugin({ config, cwd, integrations = [], initialProject }) {
23
+ let project = initialProject;
24
+ let css = project ? emitAxisProjectedCss(project) : "";
23
25
  async function refresh() {
24
26
  project = await loadProject(config, cwd);
25
27
  css = emitAxisProjectedCss(project);
@@ -38,6 +40,7 @@ function swatchbookTokensPlugin({ config, cwd, integrations = [] }) {
38
40
  name: "swatchbook:virtual-tokens",
39
41
  enforce: "pre",
40
42
  async buildStart() {
43
+ if (project) return;
41
44
  await refresh();
42
45
  },
43
46
  resolveId(id) {
@@ -55,21 +58,20 @@ function swatchbookTokensPlugin({ config, cwd, integrations = [] }) {
55
58
  }
56
59
  if (id !== RESOLVED_VIRTUAL_MODULE_ID) return null;
57
60
  if (!project) return "export default null;";
58
- const jointOverridesArr = [...project.jointOverrides.entries()];
59
- const varianceByPathObj = Object.fromEntries(project.varianceByPath.entries());
61
+ const snap = snapshotForWire(project, css);
60
62
  return [
61
63
  `/* swatchbook virtual module — generated */`,
62
- `export const axes = ${JSON.stringify(project.axes)};`,
63
- `export const presets = ${JSON.stringify(project.presets)};`,
64
- `export const disabledAxes = ${JSON.stringify(project.disabledAxes)};`,
65
- `export const diagnostics = ${JSON.stringify(project.diagnostics)};`,
66
- `export const css = ${JSON.stringify(css)};`,
67
- `export const cssVarPrefix = ${JSON.stringify(config.cssVarPrefix ?? "")};`,
68
- `export const listing = ${JSON.stringify(slimListing(project.listing))};`,
69
- `export const cells = ${JSON.stringify(project.cells)};`,
70
- `export const jointOverrides = ${JSON.stringify(jointOverridesArr)};`,
71
- `export const varianceByPath = ${JSON.stringify(varianceByPathObj)};`,
72
- `export const defaultTuple = ${JSON.stringify(project.defaultTuple)};`
64
+ `export const axes = ${JSON.stringify(snap.axes)};`,
65
+ `export const presets = ${JSON.stringify(snap.presets)};`,
66
+ `export const disabledAxes = ${JSON.stringify(snap.disabledAxes)};`,
67
+ `export const diagnostics = ${JSON.stringify(snap.diagnostics)};`,
68
+ `export const css = ${JSON.stringify(snap.css)};`,
69
+ `export const cssVarPrefix = ${JSON.stringify(snap.cssVarPrefix)};`,
70
+ `export const listing = ${JSON.stringify(snap.listing)};`,
71
+ `export const cells = ${JSON.stringify(snap.cells)};`,
72
+ `export const jointOverrides = ${JSON.stringify(snap.jointOverrides)};`,
73
+ `export const varianceByPath = ${JSON.stringify(snap.varianceByPath)};`,
74
+ `export const defaultTuple = ${JSON.stringify(snap.defaultTuple)};`
73
75
  ].join("\n");
74
76
  },
75
77
  async configureServer(server) {
@@ -111,19 +113,7 @@ function swatchbookTokensPlugin({ config, cwd, integrations = [] }) {
111
113
  server.ws.send({
112
114
  type: "custom",
113
115
  event: HMR_EVENT,
114
- data: {
115
- axes: project.axes,
116
- disabledAxes: project.disabledAxes,
117
- presets: project.presets,
118
- diagnostics: project.diagnostics,
119
- css,
120
- cssVarPrefix: config.cssVarPrefix ?? "",
121
- listing: slimListing(project.listing),
122
- cells: project.cells,
123
- jointOverrides: [...project.jointOverrides.entries()],
124
- varianceByPath: Object.fromEntries(project.varianceByPath.entries()),
125
- defaultTuple: project.defaultTuple
126
- }
116
+ data: snapshotForWire(project, css)
127
117
  });
128
118
  })();
129
119
  }, 100);
@@ -162,24 +152,6 @@ function swatchbookTokensPlugin({ config, cwd, integrations = [] }) {
162
152
  }
163
153
  };
164
154
  }
165
- /**
166
- * Reduce the full Token Listing surface down to the fields blocks read.
167
- * Drops `originalValue` (large, not needed for display), `$value`, `$type`,
168
- * `mode`, `subtype` for now — the blocks don't consume them yet. Keeps the
169
- * virtual module payload lean, especially for large projects where each
170
- * token's raw listing entry can weigh a few KB.
171
- */
172
- function slimListing(listing) {
173
- const out = {};
174
- for (const [path, entry] of Object.entries(listing)) {
175
- const ext = entry.$extensions["app.terrazzo.listing"];
176
- const slim = { names: ext.names };
177
- if (ext.previewValue !== void 0) slim.previewValue = ext.previewValue;
178
- if (ext.source !== void 0) slim.source = ext.source;
179
- out[path] = slim;
180
- }
181
- return out;
182
- }
183
155
  //#endregion
184
156
  //#region src/preset.ts
185
157
  /**
@@ -190,11 +162,13 @@ function slimListing(listing) {
190
162
  */
191
163
  async function viteFinal(viteConfig, options) {
192
164
  const { config, cwd } = await resolveConfig(options);
193
- await writeTokenCodegen(config, cwd, options);
165
+ const project = await loadProject(config, cwd);
166
+ await writeTokenCodegen(project, options);
194
167
  const plugins = Array.isArray(viteConfig.plugins) ? [...viteConfig.plugins] : [];
195
168
  plugins.push(swatchbookTokensPlugin({
196
169
  config,
197
170
  cwd,
171
+ initialProject: project,
198
172
  ...options.integrations !== void 0 && { integrations: options.integrations }
199
173
  }));
200
174
  return {
@@ -223,24 +197,17 @@ async function resolveConfig(options) {
223
197
  cwd: dirname(absolute)
224
198
  };
225
199
  }
226
- async function writeTokenCodegen(config, cwd, options) {
227
- const project = await loadProject(config, cwd);
228
- const outDir = resolve(resolve(options.configDir, ".."), config.outDir ?? ".swatchbook");
200
+ async function writeTokenCodegen(project, options) {
201
+ const outDir = resolve(resolve(options.configDir, ".."), project.config.outDir ?? ".swatchbook");
229
202
  await mkdir(outDir, { recursive: true });
230
203
  const content = renderTokenTypes(project);
231
204
  await writeFile(resolve(outDir, "tokens.d.ts"), content);
232
205
  }
233
206
  /** @internal Exported for tests; not part of the public API. */
234
207
  function renderTokenTypes(project) {
235
- const paths = /* @__PURE__ */ new Set();
236
- if (project.varianceByPath && project.varianceByPath.size > 0) for (const p of project.varianceByPath.keys()) paths.add(p);
237
- else for (const theme of project.permutations) {
238
- const tokens = project.permutationsResolved[theme.name];
239
- if (!tokens) continue;
240
- for (const path of Object.keys(tokens)) paths.add(path);
241
- }
242
- const tokenEntries = [...paths].toSorted().map((p) => ` ${JSON.stringify(p)}: string;`);
243
- const themeUnion = project.permutations.map((t) => JSON.stringify(t.name)).join(" | ") || "string";
208
+ const tokenEntries = [...project.varianceByPath.keys()].toSorted().map((p) => ` ${JSON.stringify(p)}: string;`);
209
+ const themeNames = project.axes.length === 0 ? [] : enumerateThemes(project).map((t) => t.name);
210
+ const themeUnion = themeNames.length > 0 ? themeNames.map((n) => JSON.stringify(n)).join(" | ") : "string";
244
211
  return [
245
212
  "// Generated by @unpunnyfuns/swatchbook-addon. Do not edit.",
246
213
  "declare module '@unpunnyfuns/swatchbook-addon/hooks' {",
@@ -1 +1 @@
1
- {"version":3,"file":"preset.mjs","names":["fsWatch"],"sources":["../src/virtual/plugin.ts","../src/preset.ts"],"sourcesContent":["import type {\n Config,\n ListedToken,\n Project,\n SwatchbookIntegration,\n TokenListingByPath,\n} from '@unpunnyfuns/swatchbook-core';\nimport { emitAxisProjectedCss, loadProject } from '@unpunnyfuns/swatchbook-core';\nimport { type FSWatcher, watch as fsWatch } from 'node:fs';\nimport { basename, dirname, isAbsolute, resolve as resolvePath } from 'node:path';\nimport picomatch from 'picomatch';\nimport type { Plugin } from 'vite';\nimport {\n HMR_EVENT,\n INTEGRATION_SIDE_EFFECTS_VIRTUAL_ID,\n RESOLVED_INTEGRATION_SIDE_EFFECTS_VIRTUAL_ID,\n RESOLVED_VIRTUAL_MODULE_ID,\n VIRTUAL_MODULE_ID,\n} from '#/constants.ts';\n\nexport interface SwatchbookPluginOptions {\n config: Config;\n cwd: string;\n /** Display-side integrations — each may contribute a virtual module the preview imports. */\n integrations?: readonly SwatchbookIntegration[];\n}\n\n/** `\\0<virtualId>` — Vite convention for resolved virtual module IDs. */\nfunction resolvedId(virtualId: string): string {\n return `\\0${virtualId}`;\n}\n\n/**\n * Vite plugin that serves the virtual `virtual:swatchbook/tokens` module —\n * a single source of truth for permutations, resolved token maps, per-theme CSS,\n * and diagnostics. Watches the token files + resolver for changes and\n * invalidates the module so HMR reloads the preview with fresh data.\n */\nexport function swatchbookTokensPlugin({\n config,\n cwd,\n integrations = [],\n}: SwatchbookPluginOptions): Plugin {\n let project: Project | undefined;\n let css = '';\n\n async function refresh(): Promise<void> {\n project = await loadProject(config, cwd);\n css = emitAxisProjectedCss(project);\n }\n\n /** Map of resolvedId → integration, indexed once. */\n const integrationById = new Map<string, SwatchbookIntegration>();\n /** Virtual IDs the preview auto-imports as side effects (global CSS). */\n const autoInjectIds: string[] = [];\n for (const integration of integrations) {\n const vm = integration.virtualModule;\n if (!vm) continue;\n integrationById.set(resolvedId(vm.virtualId), integration);\n if (vm.autoInject) autoInjectIds.push(vm.virtualId);\n }\n\n return {\n name: 'swatchbook:virtual-tokens',\n enforce: 'pre',\n\n async buildStart() {\n await refresh();\n },\n\n resolveId(id) {\n if (id === VIRTUAL_MODULE_ID) return RESOLVED_VIRTUAL_MODULE_ID;\n if (id === INTEGRATION_SIDE_EFFECTS_VIRTUAL_ID) {\n return RESOLVED_INTEGRATION_SIDE_EFFECTS_VIRTUAL_ID;\n }\n for (const integration of integrations) {\n if (integration.virtualModule?.virtualId === id) {\n return resolvedId(integration.virtualModule.virtualId);\n }\n }\n return null;\n },\n\n load(id) {\n if (id === RESOLVED_INTEGRATION_SIDE_EFFECTS_VIRTUAL_ID) {\n // Aggregate side-effect imports. Empty when no integration\n // opted in — still a valid ESM module, just a no-op.\n return autoInjectIds.map((vid) => `import ${JSON.stringify(vid)};`).join('\\n');\n }\n const integration = integrationById.get(id);\n if (integration?.virtualModule) {\n if (!project) return '';\n return integration.virtualModule.render(project);\n }\n if (id !== RESOLVED_VIRTUAL_MODULE_ID) return null;\n if (!project) return 'export default null;';\n // Emit a typed ESM module. Values are JSON-stringified for stability.\n // `jointOverrides` ships as an array of `[key, entry]` pairs because\n // `Map` doesn't survive `JSON.stringify`; the block side reconstructs\n // the Map (or just reads the array, depending on the consumer).\n const jointOverridesArr = [...project.jointOverrides.entries()];\n const varianceByPathObj = Object.fromEntries(project.varianceByPath.entries());\n return [\n `/* swatchbook virtual module — generated */`,\n `export const axes = ${JSON.stringify(project.axes)};`,\n `export const presets = ${JSON.stringify(project.presets)};`,\n `export const disabledAxes = ${JSON.stringify(project.disabledAxes)};`,\n `export const diagnostics = ${JSON.stringify(project.diagnostics)};`,\n `export const css = ${JSON.stringify(css)};`,\n `export const cssVarPrefix = ${JSON.stringify(config.cssVarPrefix ?? '')};`,\n `export const listing = ${JSON.stringify(slimListing(project.listing))};`,\n `export const cells = ${JSON.stringify(project.cells)};`,\n `export const jointOverrides = ${JSON.stringify(jointOverridesArr)};`,\n `export const varianceByPath = ${JSON.stringify(varianceByPathObj)};`,\n `export const defaultTuple = ${JSON.stringify(project.defaultTuple)};`,\n ].join('\\n');\n },\n\n async configureServer(server) {\n // `configureServer` fires before `buildStart` in Vite's plugin\n // lifecycle, so `project` is still undefined when consumers only\n // set `config.resolver` (no `tokens` glob). Force an initial load\n // here so the watcher setup below sees a populated `sourceFiles`\n // list — otherwise only the resolver file itself gets watched,\n // and saves to any `$ref` target silently drop.\n if (!project) await refresh();\n\n /**\n * Editors typically emit two or three filesystem events per save\n * (atomic rename + rewrite + metadata). A 100 ms trailing debounce\n * coalesces those into a single reload while staying well under\n * user-perceptible latency.\n */\n let pending: ReturnType<typeof setTimeout> | null = null;\n const invalidate = (): void => {\n if (pending) clearTimeout(pending);\n pending = setTimeout(() => {\n pending = null;\n void (async () => {\n await refresh();\n if (!project) return;\n const tokenCount = project.varianceByPath.size;\n const diagCount = project.diagnostics.length;\n server.config.logger.info(\n `\\x1b[36m[swatchbook]\\x1b[0m tokens reloaded — ${tokenCount} tokens, ${diagCount} diagnostic${diagCount === 1 ? '' : 's'}`,\n { clear: false, timestamp: true },\n );\n const mod = server.moduleGraph.getModuleById(RESOLVED_VIRTUAL_MODULE_ID);\n if (mod) server.moduleGraph.invalidateModule(mod);\n // Invalidate every integration-contributed virtual module so\n // its body re-renders against the fresh project on the next\n // request.\n for (const resolvedIntegrationId of integrationById.keys()) {\n const m = server.moduleGraph.getModuleById(resolvedIntegrationId);\n if (m) server.moduleGraph.invalidateModule(m);\n }\n /**\n * Send the fresh snapshot as a custom HMR event instead of a\n * full-reload. The preview subscribes and re-broadcasts to\n * blocks via the Storybook channel so the React tree\n * re-renders in place without losing toolbar / args / scroll\n * state. Field shape matches the INIT_EVENT payload so the\n * preview can hand it straight through.\n */\n server.ws.send({\n type: 'custom',\n event: HMR_EVENT,\n data: {\n axes: project.axes,\n disabledAxes: project.disabledAxes,\n presets: project.presets,\n diagnostics: project.diagnostics,\n css,\n cssVarPrefix: config.cssVarPrefix ?? '',\n listing: slimListing(project.listing),\n cells: project.cells,\n jointOverrides: [...project.jointOverrides.entries()],\n varianceByPath: Object.fromEntries(project.varianceByPath.entries()),\n defaultTuple: project.defaultTuple,\n },\n });\n })();\n }, 100);\n };\n\n /**\n * Watch each source file's *parent directory* rather than the file\n * itself. File-level `fs.watch` is fragile: atomic-save editors\n * unlink the old inode and write a new one, so the original\n * watcher either fires a one-shot 'rename' and goes deaf, or on\n * some platforms loops on ghost events for the old inode. Watching\n * the dir sidesteps both — the dir inode is stable across the\n * rename dance — and filename filtering keeps event volume low.\n *\n * Vite's `server.watcher` still wouldn't carry these events across\n * pnpm symlink boundaries, so we keep running our own watchers.\n */\n const byDir = new Map<string, Set<string>>();\n for (const file of project?.sourceFiles ?? []) {\n const dir = dirname(file);\n const set = byDir.get(dir) ?? new Set<string>();\n set.add(basename(file));\n byDir.set(dir, set);\n }\n\n const fileWatchers: FSWatcher[] = [];\n for (const [dir, names] of byDir) {\n try {\n const w = fsWatch(dir, { persistent: false }, (eventType, filename) => {\n if (!filename) return;\n if (!names.has(filename)) return;\n if (eventType === 'change' || eventType === 'rename') invalidate();\n });\n fileWatchers.push(w);\n } catch {\n // unwatchable dir — skip. Next loadProject pass will report it.\n }\n }\n server.httpServer?.once('close', () => {\n for (const w of fileWatchers) w.close();\n });\n },\n };\n}\n\n/**\n * Collect the set of filesystem paths the dev server should watch for\n * HMR. When `config.tokens` is set, use its globs (stripped to their\n * base directories) — users opt in to broader watching this way. When\n * absent, use the resolver file + every `$ref` target it pulled in, as\n * tracked on `project.sourceFiles` — which stays correct as the resolver\n * evolves without requiring a parallel `tokens` glob.\n */\n/** @internal Exported for tests; not part of the public API. */\nexport function collectWatchPaths(\n config: Config,\n project: Project | undefined,\n cwd: string,\n): string[] {\n const paths: string[] = [];\n if (config.tokens && config.tokens.length > 0) {\n for (const glob of config.tokens) {\n // `picomatch.scan` yields the longest literal prefix before any glob\n // metachar, so it handles brace expansion, nested globstars, and the\n // other shapes the hand-rolled regex missed.\n const { base } = picomatch.scan(glob);\n paths.push(resolveFromCwd(base || '.', cwd));\n }\n } else if (project?.sourceFiles) {\n for (const file of project.sourceFiles) paths.push(dirname(file));\n }\n if (config.resolver) paths.push(resolveFromCwd(config.resolver, cwd));\n return [...new Set(paths)];\n}\n\nfunction resolveFromCwd(p: string, cwd: string): string {\n if (isAbsolute(p)) return p;\n return resolvePath(cwd, p);\n}\n\n/** @internal Tests use this so they don't have to spin up Vite. */\nexport function composeProjectCss(project: Project): string {\n return emitAxisProjectedCss(project);\n}\n\ntype SlimListedToken = Pick<\n ListedToken['$extensions']['app.terrazzo.listing'],\n 'names' | 'previewValue' | 'source'\n>;\n\n/**\n * Reduce the full Token Listing surface down to the fields blocks read.\n * Drops `originalValue` (large, not needed for display), `$value`, `$type`,\n * `mode`, `subtype` for now — the blocks don't consume them yet. Keeps the\n * virtual module payload lean, especially for large projects where each\n * token's raw listing entry can weigh a few KB.\n */\nfunction slimListing(listing: TokenListingByPath): Record<string, SlimListedToken> {\n const out: Record<string, SlimListedToken> = {};\n for (const [path, entry] of Object.entries(listing)) {\n const ext = entry.$extensions['app.terrazzo.listing'];\n const slim: SlimListedToken = { names: ext.names };\n if (ext.previewValue !== undefined) slim.previewValue = ext.previewValue;\n if (ext.source !== undefined) slim.source = ext.source;\n out[path] = slim;\n }\n return out;\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, isAbsolute, resolve } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport type { Config, Project } from '@unpunnyfuns/swatchbook-core';\nimport { loadProject } from '@unpunnyfuns/swatchbook-core';\nimport { createJiti } from 'jiti';\nimport type { InlineConfig } from 'vite';\nimport type { AddonOptions } from '#/options.ts';\nimport { swatchbookTokensPlugin } from '#/virtual/plugin.ts';\n\ninterface PresetOptions extends AddonOptions {\n /** Storybook injects this — the `.storybook` directory absolute path. */\n configDir: string;\n}\n\n/**\n * Storybook preset entry. Called by Storybook at config time; extends Vite's\n * plugin list with our virtual-module plugin so the preview can import\n * `virtual:swatchbook/tokens`. Also writes the typed token-path codegen so\n * `useToken()` autocompletes against the loaded project.\n */\nexport async function viteFinal(\n viteConfig: InlineConfig,\n options: PresetOptions,\n): Promise<InlineConfig> {\n const { config, cwd } = await resolveConfig(options);\n\n // Codegen runs once at Vite startup. The virtual module plugin still\n // owns the live reload path via its HMR watcher; this file just gives\n // TS autocomplete for `useToken('…')` in consumer stories.\n await writeTokenCodegen(config, cwd, options);\n\n const plugins = Array.isArray(viteConfig.plugins) ? [...viteConfig.plugins] : [];\n plugins.push(\n swatchbookTokensPlugin({\n config,\n cwd,\n ...(options.integrations !== undefined && { integrations: options.integrations }),\n }),\n );\n\n return { ...viteConfig, plugins };\n}\n\n/** Storybook appends this module into the manager bundle so our toolbar tool registers. */\nexport function managerEntries(entry: string[] = []): string[] {\n const managerUrl = import.meta.resolve('@unpunnyfuns/swatchbook-addon/manager');\n return [...entry, fileURLToPath(managerUrl)];\n}\n\nasync function resolveConfig(options: PresetOptions): Promise<{ config: Config; cwd: string }> {\n const projectRoot = resolve(options.configDir, '..');\n\n if (options.config) {\n return { config: options.config, cwd: projectRoot };\n }\n\n const path = options.configPath ?? 'swatchbook.config.ts';\n const absolute = isAbsolute(path) ? path : resolve(options.configDir, path);\n\n const jiti = createJiti(pathToFileURL(options.configDir).href, {\n interopDefault: true,\n moduleCache: false,\n });\n const loaded = (await jiti.import(absolute, { default: true })) as Config;\n\n // If the config file isn't at projectRoot, still resolve globs from its dir.\n const cwd = dirname(absolute);\n return { config: loaded, cwd };\n}\n\nasync function writeTokenCodegen(\n config: Config,\n cwd: string,\n options: PresetOptions,\n): Promise<void> {\n const project = await loadProject(config, cwd);\n const projectRoot = resolve(options.configDir, '..');\n const outDir = resolve(projectRoot, config.outDir ?? '.swatchbook');\n await mkdir(outDir, { recursive: true });\n const content = renderTokenTypes(project);\n await writeFile(resolve(outDir, 'tokens.d.ts'), content);\n}\n\n/** @internal Exported for tests; not part of the public API. */\nexport function renderTokenTypes(project: Project): string {\n // `varianceByPath` covers every path that appears in any\n // permutation's resolved map (by construction in\n // `buildVarianceByPath`), so it's the right source for the token\n // path union — independent of the cartesian materialization the\n // chain is in the process of dropping. Hand-built test fixtures\n // that don't populate `varianceByPath` fall through to the\n // legacy per-permutation scan.\n const paths = new Set<string>();\n if (project.varianceByPath && project.varianceByPath.size > 0) {\n for (const p of project.varianceByPath.keys()) paths.add(p);\n } else {\n for (const theme of project.permutations) {\n const tokens = project.permutationsResolved[theme.name];\n if (!tokens) continue;\n for (const path of Object.keys(tokens)) paths.add(path);\n }\n }\n const sorted = [...paths].toSorted();\n const tokenEntries = sorted.map((p) => ` ${JSON.stringify(p)}: string;`);\n const themeUnion =\n project.permutations.map((t) => JSON.stringify(t.name)).join(' | ') || 'string';\n\n return [\n '// Generated by @unpunnyfuns/swatchbook-addon. Do not edit.',\n \"declare module '@unpunnyfuns/swatchbook-addon/hooks' {\",\n ' interface SwatchbookTokenMap {',\n ...tokenEntries,\n ' }',\n '',\n ` export type SwatchbookPermutationName = ${themeUnion};`,\n '}',\n '',\n ].join('\\n');\n}\n"],"mappings":";;;;;;;;;;AA4BA,SAAS,WAAW,WAA2B;AAC7C,QAAO,KAAK;;;;;;;;AASd,SAAgB,uBAAuB,EACrC,QACA,KACA,eAAe,EAAE,IACiB;CAClC,IAAI;CACJ,IAAI,MAAM;CAEV,eAAe,UAAyB;AACtC,YAAU,MAAM,YAAY,QAAQ,IAAI;AACxC,QAAM,qBAAqB,QAAQ;;;CAIrC,MAAM,kCAAkB,IAAI,KAAoC;;CAEhE,MAAM,gBAA0B,EAAE;AAClC,MAAK,MAAM,eAAe,cAAc;EACtC,MAAM,KAAK,YAAY;AACvB,MAAI,CAAC,GAAI;AACT,kBAAgB,IAAI,WAAW,GAAG,UAAU,EAAE,YAAY;AAC1D,MAAI,GAAG,WAAY,eAAc,KAAK,GAAG,UAAU;;AAGrD,QAAO;EACL,MAAM;EACN,SAAS;EAET,MAAM,aAAa;AACjB,SAAM,SAAS;;EAGjB,UAAU,IAAI;AACZ,OAAI,OAAA,4BAA0B,QAAO;AACrC,OAAI,OAAA,8CACF,QAAO;AAET,QAAK,MAAM,eAAe,aACxB,KAAI,YAAY,eAAe,cAAc,GAC3C,QAAO,WAAW,YAAY,cAAc,UAAU;AAG1D,UAAO;;EAGT,KAAK,IAAI;AACP,OAAI,OAAO,6CAGT,QAAO,cAAc,KAAK,QAAQ,UAAU,KAAK,UAAU,IAAI,CAAC,GAAG,CAAC,KAAK,KAAK;GAEhF,MAAM,cAAc,gBAAgB,IAAI,GAAG;AAC3C,OAAI,aAAa,eAAe;AAC9B,QAAI,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AAC;EAIrC,KADb,QAAQ,SAAS;EACC;;AAGhC,eAAe,kBACb,QACA,KACA,SACe;CACf,MAAM,UAAU,MAAM,YAAY,QAAQ,IAAI;CAE9C,MAAM,SAAS,QADK,QAAQ,QAAQ,WAAW,KAAK,EAChB,OAAO,UAAU,cAAc;AACnE,OAAM,MAAM,QAAQ,EAAE,WAAW,MAAM,CAAC;CACxC,MAAM,UAAU,iBAAiB,QAAQ;AACzC,OAAM,UAAU,QAAQ,QAAQ,cAAc,EAAE,QAAQ;;;AAI1D,SAAgB,iBAAiB,SAA0B;CAQzD,MAAM,wBAAQ,IAAI,KAAa;AAC/B,KAAI,QAAQ,kBAAkB,QAAQ,eAAe,OAAO,EAC1D,MAAK,MAAM,KAAK,QAAQ,eAAe,MAAM,CAAE,OAAM,IAAI,EAAE;KAE3D,MAAK,MAAM,SAAS,QAAQ,cAAc;EACxC,MAAM,SAAS,QAAQ,qBAAqB,MAAM;AAClD,MAAI,CAAC,OAAQ;AACb,OAAK,MAAM,QAAQ,OAAO,KAAK,OAAO,CAAE,OAAM,IAAI,KAAK;;CAI3D,MAAM,eADS,CAAC,GAAG,MAAM,CAAC,UAAU,CACR,KAAK,MAAM,OAAO,KAAK,UAAU,EAAE,CAAC,WAAW;CAC3E,MAAM,aACJ,QAAQ,aAAa,KAAK,MAAM,KAAK,UAAU,EAAE,KAAK,CAAC,CAAC,KAAK,MAAM,IAAI;AAEzE,QAAO;EACL;EACA;EACA;EACA,GAAG;EACH;EACA;EACA,6CAA6C,WAAW;EACxD;EACA;EACD,CAAC,KAAK,KAAK"}
1
+ {"version":3,"file":"preset.mjs","names":["fsWatch"],"sources":["../src/virtual/plugin.ts","../src/preset.ts"],"sourcesContent":["import type { Config, Project, SwatchbookIntegration } from '@unpunnyfuns/swatchbook-core';\nimport { emitAxisProjectedCss, loadProject } from '@unpunnyfuns/swatchbook-core';\nimport { snapshotForWire } from '@unpunnyfuns/swatchbook-core/snapshot-for-wire';\nimport { watch as fsWatch } from 'node:fs';\nimport type { FSWatcher } from 'node:fs';\nimport { basename, dirname, isAbsolute, resolve as resolvePath } from 'node:path';\nimport picomatch from 'picomatch';\nimport type { Plugin } from 'vite';\nimport {\n HMR_EVENT,\n INTEGRATION_SIDE_EFFECTS_VIRTUAL_ID,\n RESOLVED_INTEGRATION_SIDE_EFFECTS_VIRTUAL_ID,\n RESOLVED_VIRTUAL_MODULE_ID,\n VIRTUAL_MODULE_ID,\n} from '#/constants.ts';\n\nexport interface SwatchbookPluginOptions {\n config: Config;\n cwd: string;\n /** Display-side integrations — each may contribute a virtual module the preview imports. */\n integrations?: readonly SwatchbookIntegration[];\n /**\n * Pre-loaded project to use for the first `buildStart` instead of\n * calling `loadProject` again. Lets `preset.viteFinal` share its\n * single `loadProject` call (originally needed for codegen) with the\n * plugin, eliminating a redundant parse pass at Storybook startup.\n * HMR-triggered reloads still call `loadProject` directly.\n */\n initialProject?: Project;\n}\n\n/** `\\0<virtualId>` — Vite convention for resolved virtual module IDs. */\nfunction resolvedId(virtualId: string): string {\n return `\\0${virtualId}`;\n}\n\n/**\n * Vite plugin that serves the virtual `virtual:swatchbook/tokens` module —\n * a single source of truth for permutations, resolved token maps, per-theme CSS,\n * and diagnostics. Watches the token files + resolver for changes and\n * invalidates the module so HMR reloads the preview with fresh data.\n */\nexport function swatchbookTokensPlugin({\n config,\n cwd,\n integrations = [],\n initialProject,\n}: SwatchbookPluginOptions): Plugin {\n let project: Project | undefined = initialProject;\n let css = project ? emitAxisProjectedCss(project) : '';\n\n async function refresh(): Promise<void> {\n project = await loadProject(config, cwd);\n css = emitAxisProjectedCss(project);\n }\n\n /** Map of resolvedId → integration, indexed once. */\n const integrationById = new Map<string, SwatchbookIntegration>();\n /** Virtual IDs the preview auto-imports as side effects (global CSS). */\n const autoInjectIds: string[] = [];\n for (const integration of integrations) {\n const vm = integration.virtualModule;\n if (!vm) continue;\n integrationById.set(resolvedId(vm.virtualId), integration);\n if (vm.autoInject) autoInjectIds.push(vm.virtualId);\n }\n\n return {\n name: 'swatchbook:virtual-tokens',\n enforce: 'pre',\n\n async buildStart() {\n // Skip the redundant load when preset.viteFinal already supplied\n // a freshly-loaded project via `initialProject`. The first HMR\n // reload (or a manual `refresh()`) calls `loadProject` as usual.\n if (project) return;\n await refresh();\n },\n\n resolveId(id) {\n if (id === VIRTUAL_MODULE_ID) return RESOLVED_VIRTUAL_MODULE_ID;\n if (id === INTEGRATION_SIDE_EFFECTS_VIRTUAL_ID) {\n return RESOLVED_INTEGRATION_SIDE_EFFECTS_VIRTUAL_ID;\n }\n for (const integration of integrations) {\n if (integration.virtualModule?.virtualId === id) {\n return resolvedId(integration.virtualModule.virtualId);\n }\n }\n return null;\n },\n\n load(id) {\n if (id === RESOLVED_INTEGRATION_SIDE_EFFECTS_VIRTUAL_ID) {\n // Aggregate side-effect imports. Empty when no integration\n // opted in — still a valid ESM module, just a no-op.\n return autoInjectIds.map((vid) => `import ${JSON.stringify(vid)};`).join('\\n');\n }\n const integration = integrationById.get(id);\n if (integration?.virtualModule) {\n if (!project) return '';\n return integration.virtualModule.render(project);\n }\n if (id !== RESOLVED_VIRTUAL_MODULE_ID) return null;\n if (!project) return 'export default null;';\n // Emit a typed ESM module. `snapshotForWire` does the field set +\n // Map-to-Object conversion in one place; we destructure here and\n // JSON-stringify each field for ESM export.\n const snap = snapshotForWire(project, css);\n return [\n `/* swatchbook virtual module — generated */`,\n `export const axes = ${JSON.stringify(snap.axes)};`,\n `export const presets = ${JSON.stringify(snap.presets)};`,\n `export const disabledAxes = ${JSON.stringify(snap.disabledAxes)};`,\n `export const diagnostics = ${JSON.stringify(snap.diagnostics)};`,\n `export const css = ${JSON.stringify(snap.css)};`,\n `export const cssVarPrefix = ${JSON.stringify(snap.cssVarPrefix)};`,\n `export const listing = ${JSON.stringify(snap.listing)};`,\n `export const cells = ${JSON.stringify(snap.cells)};`,\n `export const jointOverrides = ${JSON.stringify(snap.jointOverrides)};`,\n `export const varianceByPath = ${JSON.stringify(snap.varianceByPath)};`,\n `export const defaultTuple = ${JSON.stringify(snap.defaultTuple)};`,\n ].join('\\n');\n },\n\n async configureServer(server) {\n // `configureServer` fires before `buildStart` in Vite's plugin\n // lifecycle, so `project` is still undefined when consumers only\n // set `config.resolver` (no `tokens` glob). Force an initial load\n // here so the watcher setup below sees a populated `sourceFiles`\n // list — otherwise only the resolver file itself gets watched,\n // and saves to any `$ref` target silently drop.\n if (!project) await refresh();\n\n /**\n * Editors typically emit two or three filesystem events per save\n * (atomic rename + rewrite + metadata). A 100 ms trailing debounce\n * coalesces those into a single reload while staying well under\n * user-perceptible latency.\n */\n let pending: ReturnType<typeof setTimeout> | null = null;\n const invalidate = (): void => {\n if (pending) clearTimeout(pending);\n pending = setTimeout(() => {\n pending = null;\n void (async () => {\n await refresh();\n if (!project) return;\n const tokenCount = project.varianceByPath.size;\n const diagCount = project.diagnostics.length;\n server.config.logger.info(\n `\\x1b[36m[swatchbook]\\x1b[0m tokens reloaded — ${tokenCount} tokens, ${diagCount} diagnostic${diagCount === 1 ? '' : 's'}`,\n { clear: false, timestamp: true },\n );\n const mod = server.moduleGraph.getModuleById(RESOLVED_VIRTUAL_MODULE_ID);\n if (mod) server.moduleGraph.invalidateModule(mod);\n // Invalidate every integration-contributed virtual module so\n // its body re-renders against the fresh project on the next\n // request.\n for (const resolvedIntegrationId of integrationById.keys()) {\n const m = server.moduleGraph.getModuleById(resolvedIntegrationId);\n if (m) server.moduleGraph.invalidateModule(m);\n }\n /**\n * Send the fresh snapshot as a custom HMR event instead of a\n * full-reload. The preview subscribes and re-broadcasts to\n * blocks via the Storybook channel so the React tree\n * re-renders in place without losing toolbar / args / scroll\n * state. Field shape matches the INIT_EVENT payload so the\n * preview can hand it straight through.\n */\n server.ws.send({\n type: 'custom',\n event: HMR_EVENT,\n data: snapshotForWire(project, css),\n });\n })();\n }, 100);\n };\n\n /**\n * Watch each source file's *parent directory* rather than the file\n * itself. File-level `fs.watch` is fragile: atomic-save editors\n * unlink the old inode and write a new one, so the original\n * watcher either fires a one-shot 'rename' and goes deaf, or on\n * some platforms loops on ghost events for the old inode. Watching\n * the dir sidesteps both — the dir inode is stable across the\n * rename dance — and filename filtering keeps event volume low.\n *\n * Vite's `server.watcher` still wouldn't carry these events across\n * pnpm symlink boundaries, so we keep running our own watchers.\n */\n const byDir = new Map<string, Set<string>>();\n for (const file of project?.sourceFiles ?? []) {\n const dir = dirname(file);\n const set = byDir.get(dir) ?? new Set<string>();\n set.add(basename(file));\n byDir.set(dir, set);\n }\n\n const fileWatchers: FSWatcher[] = [];\n for (const [dir, names] of byDir) {\n try {\n const w = fsWatch(dir, { persistent: false }, (eventType, filename) => {\n if (!filename) return;\n if (!names.has(filename)) return;\n if (eventType === 'change' || eventType === 'rename') invalidate();\n });\n fileWatchers.push(w);\n } catch {\n // unwatchable dir — skip. Next loadProject pass will report it.\n }\n }\n server.httpServer?.once('close', () => {\n for (const w of fileWatchers) w.close();\n });\n },\n };\n}\n\n/**\n * Collect the set of filesystem paths the dev server should watch for\n * HMR. When `config.tokens` is set, use its globs (stripped to their\n * base directories) — users opt in to broader watching this way. When\n * absent, use the resolver file + every `$ref` target it pulled in, as\n * tracked on `project.sourceFiles` — which stays correct as the resolver\n * evolves without requiring a parallel `tokens` glob.\n */\n/** @internal Exported for tests; not part of the public API. */\nexport function collectWatchPaths(\n config: Config,\n project: Project | undefined,\n cwd: string,\n): string[] {\n const paths: string[] = [];\n if (config.tokens && config.tokens.length > 0) {\n for (const glob of config.tokens) {\n // `picomatch.scan` yields the longest literal prefix before any glob\n // metachar, so it handles brace expansion, nested globstars, and the\n // other shapes the hand-rolled regex missed.\n const { base } = picomatch.scan(glob);\n paths.push(resolveFromCwd(base || '.', cwd));\n }\n } else if (project?.sourceFiles) {\n for (const file of project.sourceFiles) paths.push(dirname(file));\n }\n if (config.resolver) paths.push(resolveFromCwd(config.resolver, cwd));\n return [...new Set(paths)];\n}\n\nfunction resolveFromCwd(p: string, cwd: string): string {\n if (isAbsolute(p)) return p;\n return resolvePath(cwd, p);\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, isAbsolute, resolve } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport type { Config, Project } from '@unpunnyfuns/swatchbook-core';\nimport { loadProject } from '@unpunnyfuns/swatchbook-core';\nimport { enumerateThemes } from '@unpunnyfuns/swatchbook-core/themes';\nimport { createJiti } from 'jiti';\nimport type { InlineConfig } from 'vite';\nimport type { AddonOptions } from '#/options.ts';\nimport { swatchbookTokensPlugin } from '#/virtual/plugin.ts';\n\ninterface PresetOptions extends AddonOptions {\n /** Storybook injects this — the `.storybook` directory absolute path. */\n configDir: string;\n}\n\n/**\n * Storybook preset entry. Called by Storybook at config time; extends Vite's\n * plugin list with our virtual-module plugin so the preview can import\n * `virtual:swatchbook/tokens`. Also writes the typed token-path codegen so\n * `useToken()` autocompletes against the loaded project.\n */\nexport async function viteFinal(\n viteConfig: InlineConfig,\n options: PresetOptions,\n): Promise<InlineConfig> {\n const { config, cwd } = await resolveConfig(options);\n\n // One `loadProject` call shared between codegen (needs the resolved\n // shape to render typed token paths) and the Vite plugin (uses it\n // for its first virtual-module render). Without sharing, the addon\n // calls `loadProject` twice at Storybook startup — once here for\n // codegen, once again inside the plugin's `buildStart`.\n const project = await loadProject(config, cwd);\n await writeTokenCodegen(project, options);\n\n const plugins = Array.isArray(viteConfig.plugins) ? [...viteConfig.plugins] : [];\n plugins.push(\n swatchbookTokensPlugin({\n config,\n cwd,\n initialProject: project,\n ...(options.integrations !== undefined && { integrations: options.integrations }),\n }),\n );\n\n return { ...viteConfig, plugins };\n}\n\n/** Storybook appends this module into the manager bundle so our toolbar tool registers. */\nexport function managerEntries(entry: string[] = []): string[] {\n const managerUrl = import.meta.resolve('@unpunnyfuns/swatchbook-addon/manager');\n return [...entry, fileURLToPath(managerUrl)];\n}\n\nasync function resolveConfig(options: PresetOptions): Promise<{ config: Config; cwd: string }> {\n const projectRoot = resolve(options.configDir, '..');\n\n if (options.config) {\n return { config: options.config, cwd: projectRoot };\n }\n\n const path = options.configPath ?? 'swatchbook.config.ts';\n const absolute = isAbsolute(path) ? path : resolve(options.configDir, path);\n\n const jiti = createJiti(pathToFileURL(options.configDir).href, {\n interopDefault: true,\n moduleCache: false,\n });\n const loaded = (await jiti.import(absolute, { default: true })) as Config;\n\n // If the config file isn't at projectRoot, still resolve globs from its dir.\n const cwd = dirname(absolute);\n return { config: loaded, cwd };\n}\n\nasync function writeTokenCodegen(project: Project, options: PresetOptions): Promise<void> {\n const projectRoot = resolve(options.configDir, '..');\n const outDir = resolve(projectRoot, project.config.outDir ?? '.swatchbook');\n await mkdir(outDir, { recursive: true });\n const content = renderTokenTypes(project);\n await writeFile(resolve(outDir, 'tokens.d.ts'), content);\n}\n\n/** @internal Exported for tests; not part of the public API. */\nexport function renderTokenTypes(project: Project): string {\n const sorted = [...project.varianceByPath.keys()].toSorted();\n const tokenEntries = sorted.map((p) => ` ${JSON.stringify(p)}: string;`);\n const themeNames = project.axes.length === 0 ? [] : enumerateThemes(project).map((t) => t.name);\n const themeUnion =\n themeNames.length > 0 ? themeNames.map((n) => JSON.stringify(n)).join(' | ') : 'string';\n\n return [\n '// Generated by @unpunnyfuns/swatchbook-addon. Do not edit.',\n \"declare module '@unpunnyfuns/swatchbook-addon/hooks' {\",\n ' interface SwatchbookTokenMap {',\n ...tokenEntries,\n ' }',\n '',\n ` export type SwatchbookPermutationName = ${themeUnion};`,\n '}',\n '',\n ].join('\\n');\n}\n"],"mappings":";;;;;;;;;;;;AAgCA,SAAS,WAAW,WAA2B;AAC7C,QAAO,KAAK;;;;;;;;AASd,SAAgB,uBAAuB,EACrC,QACA,KACA,eAAe,EAAE,EACjB,kBACkC;CAClC,IAAI,UAA+B;CACnC,IAAI,MAAM,UAAU,qBAAqB,QAAQ,GAAG;CAEpD,eAAe,UAAyB;AACtC,YAAU,MAAM,YAAY,QAAQ,IAAI;AACxC,QAAM,qBAAqB,QAAQ;;;CAIrC,MAAM,kCA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;GACd,CAAC,CACyB,OAAO,UAAU,EAAE,SAAS,MAAM,CAAC;EAIrC,KADb,QAAQ,SAAS;EACC;;AAGhC,eAAe,kBAAkB,SAAkB,SAAuC;CAExF,MAAM,SAAS,QADK,QAAQ,QAAQ,WAAW,KAAK,EAChB,QAAQ,OAAO,UAAU,cAAc;AAC3E,OAAM,MAAM,QAAQ,EAAE,WAAW,MAAM,CAAC;CACxC,MAAM,UAAU,iBAAiB,QAAQ;AACzC,OAAM,UAAU,QAAQ,QAAQ,cAAc,EAAE,QAAQ;;;AAI1D,SAAgB,iBAAiB,SAA0B;CAEzD,MAAM,eADS,CAAC,GAAG,QAAQ,eAAe,MAAM,CAAC,CAAC,UAAU,CAChC,KAAK,MAAM,OAAO,KAAK,UAAU,EAAE,CAAC,WAAW;CAC3E,MAAM,aAAa,QAAQ,KAAK,WAAW,IAAI,EAAE,GAAG,gBAAgB,QAAQ,CAAC,KAAK,MAAM,EAAE,KAAK;CAC/F,MAAM,aACJ,WAAW,SAAS,IAAI,WAAW,KAAK,MAAM,KAAK,UAAU,EAAE,CAAC,CAAC,KAAK,MAAM,GAAG;AAEjF,QAAO;EACL;EACA;EACA;EACA,GAAG;EACH;EACA;EACA,6CAA6C,WAAW;EACxD;EACA;EACD,CAAC,KAAK,KAAK"}
@@ -2,9 +2,12 @@ import { a as INIT_EVENT, f as STYLE_ELEMENT_ID, i as HMR_EVENT, l as PREVIEW_MO
2
2
  import { buildResolveAt } from "@unpunnyfuns/swatchbook-core/resolve-at";
3
3
  import { useEffect, useMemo } from "react";
4
4
  import { addons } from "storybook/preview-api";
5
+ import { dataAttr } from "@unpunnyfuns/swatchbook-core/data-attr";
6
+ import { ensureStyleElement } from "@unpunnyfuns/swatchbook-core/style-element";
7
+ import { tupleToName } from "@unpunnyfuns/swatchbook-core/themes";
5
8
  import "virtual:swatchbook/integration-side-effects";
6
9
  import { axes, cells, css, cssVarPrefix, defaultTuple, diagnostics, disabledAxes, jointOverrides, listing, presets, varianceByPath } from "virtual:swatchbook/tokens";
7
- import { AxesContext, COLOR_FORMATS, ColorFormatContext, PermutationContext, SwatchbookContext } from "@unpunnyfuns/swatchbook-blocks";
10
+ import { AxesContext, COLOR_FORMATS, ColorFormatContext, SwatchbookContext, ThemeContext } from "@unpunnyfuns/swatchbook-blocks";
8
11
  import { jsx } from "react/jsx-runtime";
9
12
  //#region \0rolldown/runtime.js
10
13
  var __defProp = Object.defineProperty;
@@ -18,49 +21,34 @@ var __exportAll = (all, no_symbols) => {
18
21
  return target;
19
22
  };
20
23
  //#endregion
21
- //#region src/data-attr.ts
22
- /**
23
- * Produce a prefixed `data-*` attribute name when `prefix` is set, bare
24
- * `data-<key>` otherwise. Duplicated from `@unpunnyfuns/swatchbook-core`'s
25
- * `dataAttr` so the preview bundle doesn't have to import from core —
26
- * core's top-level entry pulls in Node-only modules (`node:fs/promises`
27
- * via the loader) that throw when evaluated in the browser.
28
- */
29
- function dataAttr(prefix, key) {
30
- return prefix ? `data-${prefix}-${key}` : `data-${key}`;
31
- }
32
- //#endregion
33
24
  //#region src/preview.tsx
34
25
  var preview_exports = /* @__PURE__ */ __exportAll({
35
26
  decorators: () => decorators,
36
27
  globalTypes: () => globalTypes,
37
28
  initialGlobals: () => initialGlobals
38
29
  });
39
- /** CSS var name with the active prefix applied. */
40
- function v(name) {
41
- return cssVarPrefix ? `--${cssVarPrefix}-${name}` : `--${name}`;
42
- }
43
30
  /**
44
- * Inject the per-theme stylesheet plus a tiny `html, body { ... }` block so
45
- * the iframe's own chrome (outside any decorator wrapper — Docs mode,
46
- * autodocs, empty gutters) also picks up the active theme.
31
+ * The `html, body { ... }` rules that paint the iframe's own chrome
32
+ * (outside any decorator wrapper — Docs mode, autodocs, empty gutters)
33
+ * with the active theme's surface + text vars. Composed alongside the
34
+ * emitted token CSS so both load through the same `<style>` element.
47
35
  */
48
- function ensureStylesheet() {
49
- if (typeof document === "undefined") return;
50
- const text = `${css}\n${`
36
+ function iframeChromeRules(prefix) {
37
+ return `
51
38
  html, body {
52
- background: var(${v("color-surface-default")}, Canvas);
53
- color: var(${v("color-text-default")}, CanvasText);
39
+ background: var(${prefix ? `--${prefix}-color-surface-default` : "--color-surface-default"}, Canvas);
40
+ color: var(${prefix ? `--${prefix}-color-text-default` : "--color-text-default"}, CanvasText);
54
41
  margin: 0;
55
42
  }
56
- `}`;
57
- let style = document.getElementById(STYLE_ELEMENT_ID);
58
- if (!style) {
59
- style = document.createElement("style");
60
- style.id = STYLE_ELEMENT_ID;
61
- document.head.appendChild(style);
62
- }
63
- if (style.textContent !== text) style.textContent = text;
43
+ `;
44
+ }
45
+ /**
46
+ * Inject the per-theme stylesheet plus the iframe-chrome block. Shared
47
+ * with the HMR re-emit path below so a token refresh updates the
48
+ * iframe's chrome rules from the same source.
49
+ */
50
+ function ensureStylesheet(cssText, prefix) {
51
+ ensureStyleElement(STYLE_ELEMENT_ID, `${cssText}\n${iframeChromeRules(prefix)}`);
64
52
  }
65
53
  /**
66
54
  * Apply `cb(axisName, value)` for every pinned (disabled) axis whose
@@ -77,15 +65,14 @@ function forEachPinnedAxis(cb) {
77
65
  }
78
66
  }
79
67
  /**
80
- * Compose a stable theme name from a tuple — the same `Light · Brand A
81
- * · Normal` form `permutationID` produced server-side. Used for the
82
- * `data-<prefix>-theme` attribute and the `swatchbook/theme` channel
83
- * signal. Returns empty string when there are no axes (no name to
84
- * write).
68
+ * Compose a stable theme name from a tuple — `axisValues.join(' · ')`
69
+ * in axis order. Used for the `data-<prefix>-theme` attribute and the
70
+ * `swatchbook/theme` channel signal. Returns empty string when there
71
+ * are no axes (no name to write).
85
72
  */
86
- function matchPermutationName(tuple) {
73
+ function matchThemeName(tuple) {
87
74
  if (axes.length === 0) return "";
88
- return axes.map((axis) => tuple[axis.name] ?? axis.default).join(" · ");
75
+ return tupleToName(axes, tuple);
89
76
  }
90
77
  /**
91
78
  * Write the composed permutation ID to `data-<prefix>-theme` plus one
@@ -109,13 +96,26 @@ function setRootAxes(themeName, tuple) {
109
96
  root.setAttribute(dataAttr(cssVarPrefix, name), value);
110
97
  });
111
98
  }
99
+ function pickInitFields(source) {
100
+ return {
101
+ axes: source.axes,
102
+ disabledAxes: source.disabledAxes,
103
+ presets: source.presets,
104
+ diagnostics: source.diagnostics,
105
+ cssVarPrefix: source.cssVarPrefix,
106
+ cells: source.cells,
107
+ jointOverrides: source.jointOverrides,
108
+ varianceByPath: source.varianceByPath,
109
+ defaultTuple: source.defaultTuple
110
+ };
111
+ }
112
112
  /**
113
113
  * Emit the full virtual-module payload to the manager over Storybook's
114
114
  * channel so the toolbar + panel (which run in the manager bundle and
115
115
  * can't import our virtual module) can render from it.
116
116
  */
117
117
  function broadcastInit() {
118
- addons.getChannel().emit(INIT_EVENT, {
118
+ addons.getChannel().emit(INIT_EVENT, pickInitFields({
119
119
  axes,
120
120
  disabledAxes,
121
121
  presets,
@@ -125,7 +125,7 @@ function broadcastInit() {
125
125
  jointOverrides,
126
126
  varianceByPath,
127
127
  defaultTuple
128
- });
128
+ }));
129
129
  }
130
130
  /** Axis-default tuple, used as the baseline before overrides. */
131
131
  function defaultTuple$1() {
@@ -136,7 +136,7 @@ function defaultTuple$1() {
136
136
  /**
137
137
  * Reverse-engineer a tuple from a `Light · Brand A · Normal`-shape
138
138
  * theme name. Splits on ` · ` and zips with `virtualAxes` in declared
139
- * order — matches `matchPermutationName`'s production direction so a
139
+ * order — matches `matchThemeName`'s production direction so a
140
140
  * round-trip is lossless. Returns `undefined` when the segment count
141
141
  * doesn't match the axis count.
142
142
  */
@@ -197,19 +197,16 @@ function resolveColorFormat(globals) {
197
197
  * never needs to rebuild; downstream `ProjectSnapshot` consumers can
198
198
  * key memos on the snapshot wrapper without worrying about
199
199
  * `resolveAt` churning when Storybook recreates `context.globals`.
200
- *
201
- * Replaces the per-render `useMemo(makeResolveAt(...))` dance the
202
- * blocks side used to do in `useProject`.
203
200
  */
204
- const previewResolveAt = buildResolveAt(axes, cells, new Map(jointOverrides), defaultTuple);
201
+ const previewResolveAt = buildResolveAt(axes, cells, jointOverrides, defaultTuple);
205
202
  const themedDecorator = (Story, context) => {
206
203
  const globals = context.globals;
207
204
  const parameters = context.parameters;
208
205
  const tuple = useMemo(() => resolveTuple(globals, parameters), [globals, parameters]);
209
206
  const colorFormat = useMemo(() => resolveColorFormat(globals), [globals]);
210
- const themeName = useMemo(() => matchPermutationName(tuple), [tuple]);
207
+ const themeName = useMemo(() => matchThemeName(tuple), [tuple]);
211
208
  useEffect(() => {
212
- ensureStylesheet();
209
+ ensureStylesheet(css, cssVarPrefix);
213
210
  broadcastInit();
214
211
  }, []);
215
212
  useEffect(() => {
@@ -228,7 +225,7 @@ const themedDecorator = (Story, context) => {
228
225
  axes,
229
226
  disabledAxes,
230
227
  presets,
231
- activePermutation: themeName,
228
+ activeTheme: themeName,
232
229
  activeAxes: tuple,
233
230
  cssVarPrefix,
234
231
  diagnostics,
@@ -242,7 +239,7 @@ const themedDecorator = (Story, context) => {
242
239
  }), [themeName, tuple]);
243
240
  return /* @__PURE__ */ jsx(SwatchbookContext.Provider, {
244
241
  value: snapshot,
245
- children: /* @__PURE__ */ jsx(PermutationContext.Provider, {
242
+ children: /* @__PURE__ */ jsx(ThemeContext.Provider, {
246
243
  value: themeName,
247
244
  children: /* @__PURE__ */ jsx(AxesContext.Provider, {
248
245
  value: tuple,
@@ -306,7 +303,7 @@ function installGlobalAxisApplier() {
306
303
  * story/decorator ever runs (bare MDX docs pages). Without these, the
307
304
  * toolbar sits in its disabled "loading…" state and nothing is styled.
308
305
  */
309
- ensureStylesheet();
306
+ ensureStylesheet(css, cssVarPrefix);
310
307
  broadcastInit();
311
308
  /**
312
309
  * If the manager subscribes to INIT_EVENT after our initial broadcast,
@@ -316,12 +313,17 @@ function installGlobalAxisApplier() {
316
313
  */
317
314
  channel.on(INIT_REQUEST_EVENT, broadcastInit);
318
315
  const apply = (globals) => {
319
- ensureStylesheet();
316
+ ensureStylesheet(css, cssVarPrefix);
320
317
  const tuple = resolveTuple(globals, {});
321
- setRootAxes(matchPermutationName(tuple), tuple);
318
+ setRootAxes(matchThemeName(tuple), tuple);
322
319
  };
320
+ let lastApplied = "";
323
321
  const onGlobals = (payload) => {
324
- if (payload.globals) apply(payload.globals);
322
+ if (!payload.globals) return;
323
+ const fingerprint = matchThemeName(resolveTuple(payload.globals, {}));
324
+ if (fingerprint === lastApplied) return;
325
+ lastApplied = fingerprint;
326
+ apply(payload.globals);
325
327
  };
326
328
  channel.on("globalsUpdated", onGlobals);
327
329
  channel.on("setGlobals", onGlobals);
@@ -344,38 +346,12 @@ function installPreviewMouseDownBridge() {
344
346
  }
345
347
  installPreviewMouseDownBridge();
346
348
  if (import.meta.hot) import.meta.hot.on(HMR_EVENT, (payload) => {
347
- if (typeof document !== "undefined") {
348
- const bodyRules = `
349
- html, body {
350
- background: var(${payload.cssVarPrefix ? `--${payload.cssVarPrefix}-` : "--"}color-surface-default, Canvas);
351
- color: var(${payload.cssVarPrefix ? `--${payload.cssVarPrefix}-` : "--"}color-text-default, CanvasText);
352
- margin: 0;
353
- }
354
- `;
355
- const text = `${payload.css}\n${bodyRules}`;
356
- let style = document.getElementById(STYLE_ELEMENT_ID);
357
- if (!style) {
358
- style = document.createElement("style");
359
- style.id = STYLE_ELEMENT_ID;
360
- document.head.appendChild(style);
361
- }
362
- if (style.textContent !== text) style.textContent = text;
363
- }
349
+ ensureStylesheet(payload.css, payload.cssVarPrefix);
364
350
  const channel = addons.getChannel();
365
- channel.emit(INIT_EVENT, {
366
- axes: payload.axes,
367
- disabledAxes: payload.disabledAxes,
368
- presets: payload.presets,
369
- diagnostics: payload.diagnostics,
370
- cssVarPrefix: payload.cssVarPrefix,
371
- cells: payload.cells,
372
- jointOverrides: payload.jointOverrides,
373
- varianceByPath: payload.varianceByPath,
374
- defaultTuple: payload.defaultTuple
375
- });
351
+ channel.emit(INIT_EVENT, pickInitFields(payload));
376
352
  channel.emit(TOKENS_UPDATED_EVENT, payload);
377
353
  });
378
354
  //#endregion
379
355
  export { preview_exports as i, globalTypes as n, initialGlobals as r, decorators as t };
380
356
 
381
- //# sourceMappingURL=preview-DvtUsEMq.mjs.map
357
+ //# sourceMappingURL=preview-661N0-BM.mjs.map
@@ -0,0 +1 @@
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;;;;;;;;;;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,MAA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C5B;;;;;;;;;;;;;AAcD,SAAS,2BAAiC;AACxC,KAAI,OAAO,aAAa,YAAa;CACrC,MAAM,UAAU,OAAO,YAAY;;;;;;;AAOnC,kBAAiB,KAAK,aAAa;AACnC,gBAAe;;;;;;;AAOf,SAAQ,GAAG,oBAAoB,cAAc;CAC7C,MAAM,SAAS,YAAqC;AAClD,mBAAiB,KAAK,aAAa;EACnC,MAAM,QAAQ,aAAa,SAAS,EAAE,CAAC;AACvC,cAAY,eAAe,MAAM,EAAE,MAAM;;CAW3C,IAAI,cAAc;CAClB,MAAM,aAAa,YAAmD;AACpE,MAAI,CAAC,QAAQ,QAAS;EAEtB,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-DvtUsEMq.mjs";
1
+ import { n as globalTypes, r as initialGlobals, t as decorators } from "./preview-661N0-BM.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.55.0",
3
+ "version": "0.57.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.55.0",
79
- "@unpunnyfuns/swatchbook-core": "0.55.0",
80
- "@unpunnyfuns/swatchbook-switcher": "0.55.0"
78
+ "@unpunnyfuns/swatchbook-blocks": "0.57.0",
79
+ "@unpunnyfuns/swatchbook-core": "0.57.0",
80
+ "@unpunnyfuns/swatchbook-switcher": "0.57.0"
81
81
  },
82
82
  "peerDependencies": {
83
83
  "@storybook/react-vite": "^10.3.5",
@@ -1 +0,0 @@
1
- {"version":3,"file":"preview-DvtUsEMq.mjs","names":["virtualDisabledAxes","virtualDefaultTuple","virtualAxes","virtualPresets","virtualCells","virtualJointOverrides","virtualVarianceByPath","defaultTuple","virtualListing"],"sources":["../src/data-attr.ts","../src/preview.tsx"],"sourcesContent":["/**\n * Produce a prefixed `data-*` attribute name when `prefix` is set, bare\n * `data-<key>` otherwise. Duplicated from `@unpunnyfuns/swatchbook-core`'s\n * `dataAttr` so the preview bundle doesn't have to import from core —\n * core's top-level entry pulls in Node-only modules (`node:fs/promises`\n * via the loader) that throw when evaluated in the browser.\n */\nexport function dataAttr(prefix: string, key: string): string {\n return prefix ? `data-${prefix}-${key}` : `data-${key}`;\n}\n","/// <reference types=\"vite/client\" />\nimport { buildResolveAt } from '@unpunnyfuns/swatchbook-core/resolve-at';\nimport type {\n Axis as CoreAxis,\n Cells as CoreCells,\n JointOverride,\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 '#/data-attr.ts';\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 type ColorFormat,\n ColorFormatContext,\n type ProjectSnapshot,\n SwatchbookContext,\n PermutationContext,\n} 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/** CSS var name with the active prefix applied. */\nfunction v(name: string): string {\n return cssVarPrefix ? `--${cssVarPrefix}-${name}` : `--${name}`;\n}\n\n/**\n * Inject the per-theme stylesheet plus a tiny `html, body { ... }` block so\n * the iframe's own chrome (outside any decorator wrapper — Docs mode,\n * autodocs, empty gutters) also picks up the active theme.\n */\nfunction ensureStylesheet(): void {\n if (typeof document === 'undefined') return;\n const bodyRules = `\nhtml, body {\n background: var(${v('color-surface-default')}, Canvas);\n color: var(${v('color-text-default')}, CanvasText);\n margin: 0;\n}\n`;\n const text = `${css}\\n${bodyRules}`;\n let style = document.getElementById(STYLE_ELEMENT_ID) as HTMLStyleElement | null;\n if (!style) {\n style = document.createElement('style');\n style.id = STYLE_ELEMENT_ID;\n document.head.appendChild(style);\n }\n if (style.textContent !== text) style.textContent = text;\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 — the same `Light · Brand A\n * · Normal` form `permutationID` produced server-side. Used for the\n * `data-<prefix>-theme` attribute and the `swatchbook/theme` channel\n * signal. Returns empty string when there are no axes (no name to\n * write).\n */\nfunction matchPermutationName(tuple: Readonly<Record<string, string>>): string {\n if (virtualAxes.length === 0) return '';\n return virtualAxes.map((axis) => tuple[axis.name] ?? axis.default).join(' · ');\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 * 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(INIT_EVENT, {\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/** 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 `matchPermutationName`'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 *\n * Replaces the per-render `useMemo(makeResolveAt(...))` dance the\n * blocks side used to do in `useProject`.\n */\nconst previewResolveAt = buildResolveAt(\n virtualAxes as readonly CoreAxis[],\n virtualCells as CoreCells,\n new Map(virtualJointOverrides as readonly (readonly [string, JointOverride])[]) 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(() => matchPermutationName(tuple), [tuple]);\n\n useEffect(() => {\n ensureStylesheet();\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 activePermutation: 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 // Cast: `buildResolveAt` returns `TokenMap` (Terrazzo's\n // `TokenNormalized`), while the block-side snapshot type uses\n // its own narrower `VirtualTokenShape`. The shapes are\n // structurally a subset; the cast covers the\n // `exactOptionalPropertyTypes` mismatch between\n // `string | undefined` and `string`.\n resolveAt: previewResolveAt as unknown as NonNullable<ProjectSnapshot['resolveAt']>,\n }),\n [themeName, tuple],\n );\n\n return (\n <SwatchbookContext.Provider value={snapshot}>\n <PermutationContext.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 </PermutationContext.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();\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();\n const tuple = resolveTuple(globals, {});\n setRootAxes(matchPermutationName(tuple), tuple);\n };\n const onGlobals = (payload: { globals?: SwatchbookGlobals }): void => {\n if (payload.globals) 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 if (typeof document !== 'undefined') {\n const bodyRules = `\nhtml, body {\n background: var(${payload.cssVarPrefix ? `--${payload.cssVarPrefix}-` : '--'}color-surface-default, Canvas);\n color: var(${payload.cssVarPrefix ? `--${payload.cssVarPrefix}-` : '--'}color-text-default, CanvasText);\n margin: 0;\n}\n`;\n const text = `${payload.css}\\n${bodyRules}`;\n let style = document.getElementById(STYLE_ELEMENT_ID) as HTMLStyleElement | null;\n if (!style) {\n style = document.createElement('style');\n style.id = STYLE_ELEMENT_ID;\n document.head.appendChild(style);\n }\n if (style.textContent !== text) style.textContent = text;\n }\n const channel = addons.getChannel();\n channel.emit(INIT_EVENT, {\n axes: payload.axes,\n disabledAxes: payload.disabledAxes,\n presets: payload.presets,\n diagnostics: payload.diagnostics,\n cssVarPrefix: payload.cssVarPrefix,\n cells: payload.cells,\n jointOverrides: payload.jointOverrides,\n varianceByPath: payload.varianceByPath,\n defaultTuple: payload.defaultTuple,\n });\n channel.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