@weasel-js/forge 1.10.1 → 1.11.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.
Files changed (36) hide show
  1. package/dist/{FrameController-UeTY7ubF.d.ts → FrameController-BRhShqut.d.ts} +5 -0
  2. package/dist/{chunk-FL2MUPUL.js → chunk-2OJAV522.js} +2 -2
  3. package/dist/chunk-2OJAV522.js.map +1 -0
  4. package/dist/{chunk-DFKCLZKS.js → chunk-7BQPHMA2.js} +2 -2
  5. package/dist/chunk-7BQPHMA2.js.map +1 -0
  6. package/dist/{chunk-DKWHGSBZ.js → chunk-DPTECNYC.js} +3 -3
  7. package/dist/{chunk-DKWHGSBZ.js.map → chunk-DPTECNYC.js.map} +1 -1
  8. package/dist/{chunk-E2FHBDNQ.js → chunk-J3GYSNCK.js} +4 -4
  9. package/dist/{chunk-E2FHBDNQ.js.map → chunk-J3GYSNCK.js.map} +1 -1
  10. package/dist/{chunk-AP3DRQLI.js → chunk-NVNTQ4AT.js} +87 -9
  11. package/dist/chunk-NVNTQ4AT.js.map +1 -0
  12. package/dist/{chunk-BIAEGWGJ.js → chunk-R5F44ECM.js} +17 -7
  13. package/dist/chunk-R5F44ECM.js.map +1 -0
  14. package/dist/{chunk-GB6PRJET.js → chunk-SQ4KCIEH.js} +3 -3
  15. package/dist/{chunk-GB6PRJET.js.map → chunk-SQ4KCIEH.js.map} +1 -1
  16. package/dist/{config-Cz7ZyGF-.d.ts → config-BwScQukB.d.ts} +5 -4
  17. package/dist/csf/preview-api.js +2 -2
  18. package/dist/frame/index.d.ts +3 -2
  19. package/dist/frame/index.js +7 -8
  20. package/dist/frame/index.js.map +1 -1
  21. package/dist/index.d.ts +5 -4
  22. package/dist/index.js +3 -3
  23. package/dist/shell/index.css +3 -0
  24. package/dist/shell/index.css.map +1 -1
  25. package/dist/shell/index.d.ts +4 -3
  26. package/dist/shell/index.js +140 -69
  27. package/dist/shell/index.js.map +1 -1
  28. package/dist/test/index.d.ts +2 -1
  29. package/dist/test/index.js +5 -5
  30. package/dist/vite/index.d.ts +1 -1
  31. package/dist/vite/index.js.map +1 -1
  32. package/package.json +8 -6
  33. package/dist/chunk-AP3DRQLI.js.map +0 -1
  34. package/dist/chunk-BIAEGWGJ.js.map +0 -1
  35. package/dist/chunk-DFKCLZKS.js.map +0 -1
  36. package/dist/chunk-FL2MUPUL.js.map +0 -1
@@ -1,3 +1,4 @@
1
+ import { IconTable } from '@weasel-js/icons';
1
2
  import { BranchAnnotations, Annotations, ConfigSchema } from '@weasel-js/labkit/config';
2
3
  import { ReactNode, ComponentType } from 'react';
3
4
 
@@ -57,6 +58,8 @@ interface CssVarReport {
57
58
  value: string;
58
59
  /** Whether a `vars.set` override is in force on it. */
59
60
  overridden: boolean;
61
+ /** Whether the story reads it, directly or through another property it reads. */
62
+ used: boolean;
60
63
  }
61
64
  /** Visibility and validation answers, keyed by the config they were computed for. */
62
65
  interface ConfigAnswers {
@@ -370,6 +373,8 @@ interface FrameSetup {
370
373
  * need, so the rest never load it.
371
374
  */
372
375
  prepare?: (story: LoadedStory) => void | Promise<void>;
376
+ /** Icon tables registered beside the kit's in every frame: an app's own, for its stories' glyphs. */
377
+ icons?: readonly IconTable[];
373
378
  }
374
379
  /** Inputs to `startFrame`: the story, the channel to the shell, and the element to render into. */
375
380
  interface StartFrameOptions {
@@ -6,5 +6,5 @@ var PORT_HANDOFF = "weaselforge:port";
6
6
  var FRAME_HELLO = "weaselforge:hello";
7
7
 
8
8
  export { FRAME_HELLO, PORT_HANDOFF, PROTOCOL_VERSION };
9
- //# sourceMappingURL=chunk-FL2MUPUL.js.map
10
- //# sourceMappingURL=chunk-FL2MUPUL.js.map
9
+ //# sourceMappingURL=chunk-2OJAV522.js.map
10
+ //# sourceMappingURL=chunk-2OJAV522.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/protocol/messages.ts"],"names":[],"mappings":";;;AAEO,IAAM,gBAAA,GAAmB;AA2FzB,IAAM,YAAA,GAAe;AASrB,IAAM,WAAA,GAAc","file":"chunk-2OJAV522.js","sourcesContent":["import type { SchemaDescription } from './schema.ts';\n\nexport const PROTOCOL_VERSION = 1;\n\n/** The workshop's toolbar globals as a story reads them, by name. */\nexport type Globals = Readonly<Record<string, unknown>>;\n/** How a story sits in its frame. */\nexport type Layout = 'centered' | 'padded' | 'fullscreen';\n/** A frame size a story asks for, in CSS pixels. */\nexport interface Viewport {\n width: number;\n height: number;\n}\n/** Where a frame's fault happened: loading the story, rendering it, or reading a message. */\nexport type FaultPhase = 'import' | 'render' | 'protocol';\n\n/** One custom property as the frame found it. */\nexport interface CssVarReport {\n name: string;\n value: string;\n /** Whether a `vars.set` override is in force on it. */\n overridden: boolean;\n /** Whether the story reads it, directly or through another property it reads. */\n used: boolean;\n}\n\n/** Visibility and validation answers, keyed by the config they were computed for. */\nexport interface ConfigAnswers {\n /** `stableStringify(config)` of the config the frame evaluated. */\n configKey: string;\n hidden: string[];\n errors: Record<string, string[]>;\n}\n\n/** One element axe faulted on, inside the frame's own document. */\nexport interface A11yNode {\n /** The CSS selectors, outermost first, that reach the element in the frame. */\n target: readonly string[];\n html: string;\n failureSummary?: string;\n}\n\n/** One axe rule's outcome on the story, with the elements it names. */\nexport interface A11yFinding {\n id: string;\n impact: 'minor' | 'moderate' | 'serious' | 'critical' | null;\n help: string;\n helpUrl: string;\n description: string;\n nodes: readonly A11yNode[];\n}\n\n/** What axe found on one story: the rules it failed, and the ones it could not decide. */\nexport interface A11yReport {\n violations: readonly A11yFinding[];\n incomplete: readonly A11yFinding[];\n /** Rules that passed, and rules no element on the page could be judged by. */\n passes: number;\n inapplicable: number;\n}\n\n/** A message the workshop sends a story's frame. */\nexport type ToFrame =\n | { type: 'init'; config: unknown; state: unknown; globals: Globals }\n | { type: 'config'; config: unknown }\n | { type: 'state'; state: unknown }\n | { type: 'globals'; globals: Globals }\n | { type: 'vars.set'; name: string; value: string | null }\n /** Run axe over the story's own subtree. Answered by `a11y` carrying the same `id`. */\n | { type: 'a11y.run'; id: string };\n\n/** A message a story's frame sends the workshop. */\nexport type FromFrame =\n | { type: 'ready'; schema: SchemaDescription; layout: Layout; viewport: Viewport | null }\n /** Sent once, when the story's first render after `init` has committed. */\n | { type: 'rendered' }\n | { type: 'answers'; answers: ConfigAnswers }\n | { type: 'setConfig'; path: string; value: unknown }\n | { type: 'setState'; state: unknown }\n | { type: 'vars'; vars: CssVarReport[] }\n /** Asks the shell to show story `id` in this frame's trial in place of what it shows now. */\n | { type: 'open'; id: string }\n | { type: 'a11y'; id: string; ok: true; report: A11yReport }\n | { type: 'a11y'; id: string; ok: false; message: string }\n /** `seq`, on a render fault only: how many `init`/`config`/`state`/`globals` messages the frame had received. */\n | { type: 'fault'; phase: FaultPhase; message: string; stack?: string; seq?: number };\n\nexport interface Envelope<M> {\n v: number;\n msg: M;\n}\n\n/** Posted on the frame's window with the port transferred alongside it, as a `PortHandoff`. */\nexport const PORT_HANDOFF = 'weaselforge:port';\n\n/** What the shell posts with the port: `id` names what the frame shows, a story or an index. */\nexport interface PortHandoff {\n type: typeof PORT_HANDOFF;\n id: string;\n}\n\n/** Posted by a frame document to its parent as soon as its entry runs, asking for a port. */\nexport const FRAME_HELLO = 'weaselforge:hello';\n\nexport { stableStringify } from '@weasel-js/core';\n"]}
@@ -77,5 +77,5 @@ function withGlobals(schema, declarations) {
77
77
  }
78
78
 
79
79
  export { FOLLOW_APP, GLOBALS_KEY, PLAYHEAD_KEY, effectiveGlobals, followApp, isForgePath, isGlobalsPath, labGlobals, labOptions, storyConfig, withGlobals };
80
- //# sourceMappingURL=chunk-DFKCLZKS.js.map
81
- //# sourceMappingURL=chunk-DFKCLZKS.js.map
80
+ //# sourceMappingURL=chunk-7BQPHMA2.js.map
81
+ //# sourceMappingURL=chunk-7BQPHMA2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/shell/globals.ts"],"names":["from"],"mappings":";;;;AAqCO,IAAM,WAAA,GAAc;AAEpB,IAA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H,EAAA,OAAO,CAAA,CAAE,MAAA,CAAO,EAAE,GAAG,MAAA,CAAO,OAAO,CAAC,WAAW,GAAG,KAAA,EAAO,CAAA;AAC3D","file":"chunk-7BQPHMA2.js","sourcesContent":["import { isPlainObject } from '@weasel-js/core';\nimport type { IconRef } from '@weasel-js/icons';\nimport type { LabMode } from '@weasel-js/labkit';\nimport { type ConfigSchema, f } from '@weasel-js/labkit/config';\nimport type { Globals } from '../protocol/messages';\n\n/** One global the workshop's toolbar sets for every story, and a trial may pin for its own. */\nexport interface GlobalDeclaration {\n label: string;\n options: readonly { value: string; label: string }[];\n default: string;\n /** Another global's key: the toolbar shows this one in a popover beside that one rather than in the bar itself. */\n under?: string;\n /** The glyph on the button opening the globals declared `under` this one. Default `core:tune`. */\n icon?: IconRef;\n /**\n * Whether the toolbar offers `value` given the lab's other values; every option shows when absent. `globals` is\n * resolved without any declaration's `shows`, so one `shows` cannot depend on another's outcome.\n */\n shows?: (value: string, globals: Globals) => boolean;\n /**\n * What this global reads from the lab's own chrome. Given, the lab's value may be `App` (`FOLLOW_APP`), offered\n * first, and while it is the global follows that chrome control, as the header's mode switch sets it. A trial's\n * pin follows the lab or names a value; it cannot follow the app on its own.\n */\n follows?: (chrome: LabChrome) => string;\n}\n\n/** The lab chrome's own settings a global can follow. */\nexport interface LabChrome {\n mode: LabMode;\n}\n\n/** The shell config's `globals`: each declaration by the key stories read it under. */\nexport type GlobalDeclarations = Readonly<Record<string, GlobalDeclaration>>;\n\n/** The config group every story schema gains, holding the trial's pins. A story never sees it. */\nexport const GLOBALS_KEY = '$globals';\n/** A pin's value when the trial follows the lab. */\nexport const FOLLOW_LAB = 'lab';\n/** A lab value, for a declaration that `follows` the app, meaning whatever the app's chrome is set to. */\nexport const FOLLOW_APP = 'app';\n\nconst APP_OPTION = { value: FOLLOW_APP, label: 'App' } as const;\n\nconst isRecord = isPlainObject;\n\nexport const isGlobalsPath = (path: string): boolean => path === GLOBALS_KEY || path.startsWith(`${GLOBALS_KEY}.`);\n\n/** The config key a timeline story's paused playhead is kept under, so labkit persists and snapshots it. */\nexport const PLAYHEAD_KEY = '$playhead';\n\n/** Config keys forge owns: a story neither sees nor writes them. */\nconst FORGE_KEYS: ReadonlySet<string> = new Set([GLOBALS_KEY, PLAYHEAD_KEY]);\n\n/** Whether a config path lies under a key forge owns. */\nexport const isForgePath = (path: string): boolean => FORGE_KEYS.has(path.split('.')[0]!);\n\n/** The options the toolbar offers for `declaration` at `globals`. */\nexport function shownOptions(declaration: GlobalDeclaration, globals: Globals): GlobalDeclaration['options'] {\n const { shows } = declaration;\n return shows ? declaration.options.filter((option) => shows(option.value, globals)) : declaration.options;\n}\n\n/** The options the lab's own control offers: `shownOptions`, after `App` where the declaration follows the app. */\nexport function labOptions(declaration: GlobalDeclaration, globals: Globals): GlobalDeclaration['options'] {\n const shown = shownOptions(declaration, globals);\n return declaration.follows ? [APP_OPTION, ...shown] : shown;\n}\n\n/** `values` with each `App` replaced by what its declaration reads from `chrome`; `values` itself when none is. */\nexport function followApp(declarations: GlobalDeclarations, values: Globals, chrome: LabChrome): Globals {\n const followed = Object.entries(declarations).flatMap(([key, { follows }]) =>\n follows && values[key] === FOLLOW_APP ? [[key, follows(chrome)] as const] : [],\n );\n return followed.length === 0 ? values : { ...values, ...Object.fromEntries(followed) };\n}\n\n/**\n * The lab's values from what was stored: declared keys only. A value no option offers falls back to the default, and\n * one its declaration's `shows` hides falls back to the shown option nearest it in `options`, the earlier on a tie.\n */\nexport function labGlobals(declarations: GlobalDeclarations, stored: unknown): Globals {\n const from = isRecord(stored) ? stored : {};\n const offered: Globals = Object.fromEntries(\n Object.entries(declarations).map(([key, declaration]) => {\n const value = from[key];\n const known =\n declaration.options.some((option) => option.value === value) || (declaration.follows && value === FOLLOW_APP);\n return [key, known ? value : declaration.default];\n }),\n );\n return Object.fromEntries(\n Object.entries(declarations).map(([key, declaration]) => {\n const shown = shownOptions(declaration, offered);\n const value = offered[key];\n if (value === FOLLOW_APP && declaration.follows) return [key, value];\n if (!declaration.shows || shown.length === 0 || shown.some((option) => option.value === value)) return [key, value];\n const at = (v: unknown) => declaration.options.findIndex((option) => option.value === v);\n const from = at(value);\n const nearest = shown.reduce((best, option) =>\n Math.abs(at(option.value) - from) < Math.abs(at(best.value) - from) ? option : best,\n );\n return [key, nearest.value];\n }),\n );\n}\n\n/** The lab's values, overridden by the pins in a trial's config that do not follow the lab. */\nexport function effectiveGlobals(lab: Globals, pins: unknown): Globals {\n if (!isRecord(pins)) return lab;\n const pinned = Object.entries(pins).filter(([key, value]) => key in lab && value !== FOLLOW_LAB);\n return pinned.length === 0 ? lab : { ...lab, ...Object.fromEntries(pinned) };\n}\n\n/**\n * The config a story receives: the trial's, without the keys forge owns. Returns `previous` when every other entry is\n * the same, so a change to a pin or the playhead alone is not a change to the story's config.\n */\nexport function storyConfig(config: unknown, previous?: unknown): unknown {\n if (!isRecord(config) || !Object.keys(config).some((key) => FORGE_KEYS.has(key))) return config;\n const rest = Object.fromEntries(Object.entries(config).filter(([key]) => !FORGE_KEYS.has(key)));\n if (isRecord(previous)) {\n const keys = Object.keys(rest);\n if (keys.length === Object.keys(previous).length && keys.every((key) => rest[key] === previous[key])) return previous;\n }\n return rest;\n}\n\n/** `schema` with a `$globals` group appended: one leaf per declaration, following the lab until pinned. */\nexport function withGlobals(schema: ConfigSchema<unknown>, declarations: GlobalDeclarations): ConfigSchema<unknown> {\n const entries = Object.entries(declarations);\n if (entries.length === 0) return schema;\n const leaves = Object.fromEntries(\n entries.map(([key, declaration]) => [\n key,\n f.enum(FOLLOW_LAB, [{ value: FOLLOW_LAB, label: 'Lab' }, ...declaration.options]).label(declaration.label),\n ]),\n );\n // An empty group name contributes rows without a heading of its own, under the section's.\n const group = f.group(leaves).label('').section('Globals', { layout: 'inline', pack: 'pairs', className: 'fg-globals-pins' });\n return f.schema({ ...schema.nodes, [GLOBALS_KEY]: group }) as ConfigSchema<unknown>;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { stableStringify } from './chunk-FL2MUPUL.js';
1
+ import { stableStringify } from './chunk-2OJAV522.js';
2
2
  import { valueAtPath, isConfigBranch } from '@weasel-js/labkit/config';
3
3
  import { isPlainObject } from '@weasel-js/core';
4
4
 
@@ -148,5 +148,5 @@ function storyHref(story, knobs = {}, params = {}) {
148
148
  }
149
149
 
150
150
  export { PLAYHEAD_PARAM, RESERVED_PARAMS, decodeKnob, encodeKnob, formatRoute, knobParams, knobPaths, knobsToParams, paramsToKnobs, parseRoute, reservedParams, sameKnob, storyHref };
151
- //# sourceMappingURL=chunk-DKWHGSBZ.js.map
152
- //# sourceMappingURL=chunk-DKWHGSBZ.js.map
151
+ //# sourceMappingURL=chunk-DPTECNYC.js.map
152
+ //# sourceMappingURL=chunk-DPTECNYC.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/route/url.ts"],"names":[],"mappings":";;;;AAWO,IAAM,cAAA,GAAiB;AAGvB,IAAM,eAAA,mBAAuC,IAAI,GAAA,CAAI,CAAC,cAAc,CAAC;AAG5E,IAAM,eAAA,GAAkB,GAAA;AASjB,SAAS,WAAW,IAAA,EAA0B;AACnD,EAAA,MAAM,IAAA,GAAO,KAAK,UAAA,CAAW,GAAG,IAAI,IAAA,CAAK,KAAA,CAAM,CAAC,CAAA,GAAI,IAAA;AACpD,EAAA,IAAI,CAAC,IAAA,CAAK,UAAA,CAAW,GAAG,CAAA,EAAG,OAAO,EAAE,KAAA,EAAO,IAAA,EAAM,MAAA,EAAQ,EAAC,EAAE;AAC5D,EAAA,MAAM,EAAA,GAAK,IAAA,CAAK,OAAA,CAAQ,GAAG,CAAA;AAC3B,EAAA,MAAM,IAAA,GAAO,EAAA,KAAO,EAAA,GAAK,IAAA,CAAK,KAAA,CAAM,CAAC,CAAA,GAAI,IAAA,CAAK,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA;AACzD,EAAA,IAAI,KAAA;AACJ,EAAA,IAAI;AACF,IAAA,KAAA,GAAQ,kBAAA,CAAmB,IAAI,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CAAA;AAC5B,IAAA,IAAI,QAAQ,MAAA,IAAa,WAAA,CAAY,IAAI,CAAA,EAAG,OAAA,CAAQ,IAAI,CAAA,GAAI,GAAA;AAAA,EAC9D;AACA,EAAA,OAAO,WAAA,CAAY,EAAE,KAAA,EAAO,MAAA,EAAQ,EAAE,GAAG,OAAA,EAAS,GAAG,cAAA,CAAe,MAAM,CAAA,EAAE,EAAG,CAAA;AACjF","file":"chunk-DKWHGSBZ.js","sourcesContent":["import { type ConfigSchema, type ConfigShape, isConfigBranch, valueAtPath } from '@weasel-js/labkit/config';\nimport { isPlainObject } from '@weasel-js/core';\nimport { stableStringify } from '../protocol/messages';\n\n/**\n * Forge's URL, as pure functions: `#/<story id>?<params>`. The story and its params share the hash, so the page's\n * own query string stays the host's. A param is a knob — a story arg, addressed by its dotted config path\n * (`look.px`) — unless its name is reserved for the workshop itself.\n */\n\n/** The param a paused playhead is held in, in seconds. */\nexport const PLAYHEAD_PARAM = 't';\n\n/** Param names that are never knobs. */\nexport const RESERVED_PARAMS: ReadonlySet<string> = new Set([PLAYHEAD_PARAM]);\n\n/** Config keys forge keeps for itself, such as the `$globals` pins, start with this and never reach the URL. */\nconst INTERNAL_PREFIX = '$';\n\n/** What a forge hash holds: the story it names, and every param after it, knobs and reserved alike, in order. */\nexport interface ForgeRoute {\n story: string | null;\n params: Readonly<Record<string, string>>;\n}\n\n/** Reads a hash (`location.hash`, with or without its `#`). Anything not in the `#/<id>` form names no story. */\nexport function parseRoute(hash: string): ForgeRoute {\n const body = hash.startsWith('#') ? hash.slice(1) : hash;\n if (!body.startsWith('/')) return { story: null, params: {} };\n const at = body.indexOf('?');\n const path = at === -1 ? body.slice(1) : body.slice(1, at);\n let story: string | null;\n try {\n story = decodeURIComponent(path) || null;\n } catch {\n story = null;\n }\n const params: Record<string, string> = {};\n if (at !== -1) for (const [key, value] of new URLSearchParams(body.slice(at + 1))) params[key] = value;\n return { story, params };\n}\n\n/** The hash for `route`, with its leading `#`. The inverse of `parseRoute`. */\nexport function formatRoute(route: ForgeRoute): string {\n const query = new URLSearchParams(Object.entries(route.params)).toString();\n return `#/${encodeURIComponent(route.story ?? '')}${query ? `?${query}` : ''}`;\n}\n\n/** Whether a param name can be a knob: not reserved and not one of forge's own config keys. */\nexport function isKnobParam(name: string): boolean {\n return name !== '' && !RESERVED_PARAMS.has(name) && !name.startsWith(INTERNAL_PREFIX);\n}\n\n/** The params that are knobs, with the reserved ones left out. */\nexport function knobParams(params: Readonly<Record<string, string>>): Record<string, string> {\n return Object.fromEntries(Object.entries(params).filter(([name]) => isKnobParam(name)));\n}\n\n/** The params that are not knobs. Kept as they are when the knobs are rewritten. */\nexport function reservedParams(params: Readonly<Record<string, string>>): Record<string, string> {\n return Object.fromEntries(Object.entries(params).filter(([name]) => !isKnobParam(name)));\n}\n\n/** What a knob's value is decoded against: its schema leaf's declared kind, its default, and its choices. */\nexport interface KnobLeaf {\n kind: string | null;\n default: unknown;\n annotations?: { options?: readonly { value: string }[] };\n}\n\ntype Codec = 'number' | 'boolean' | 'string' | 'enum' | 'json';\n\n/** How a leaf's value travels: by its declared kind first, then by the type of its default. */\nfunction codecOf(leaf: KnobLeaf): Codec | null {\n switch (leaf.kind) {\n case 'number':\n case 'boolean':\n case 'string':\n case 'enum':\n return leaf.kind;\n case 'color':\n return 'string';\n case 'list':\n case 'json':\n return 'json';\n }\n const d = leaf.default;\n if (typeof d === 'number' || typeof d === 'boolean' || typeof d === 'string') return typeof d as Codec;\n return Array.isArray(d) || isPlainObject(d) ? 'json' : null;\n}\n\n/** A value as one param. Undefined for a value no param can carry, such as a function. */\nexport function encodeKnob(value: unknown): string | undefined {\n switch (typeof value) {\n case 'string':\n return value;\n case 'number':\n case 'boolean':\n return String(value);\n case 'object':\n return value !== null && (Array.isArray(value) || isPlainObject(value)) ? JSON.stringify(value) : undefined;\n default:\n return undefined;\n }\n}\n\n/** Whether `value` is something a leaf of codec `codec` could hold, so a well-formed param of the wrong type is refused. */\nfunction fits(codec: Codec, value: unknown, leaf: KnobLeaf): boolean {\n if (codec !== 'json') return true;\n const d = leaf.default;\n if (Array.isArray(d)) {\n if (!Array.isArray(value)) return false;\n return leaf.kind !== 'list' || value.every((item) => typeof item === 'string');\n }\n if (isPlainObject(d)) return isPlainObject(value);\n return true;\n}\n\n/**\n * One param read as `leaf`'s type: `{ value }`, or undefined for a param that does not parse as one — a number that\n * is not a number, an option the enum does not list, malformed JSON. A bare boolean param (`?dark`) reads as true.\n */\nexport function decodeKnob(raw: string, leaf: KnobLeaf): { value: unknown } | undefined {\n const codec = codecOf(leaf);\n switch (codec) {\n case 'number': {\n const n = raw.trim() === '' ? Number.NaN : Number(raw);\n return Number.isNaN(n) ? undefined : { value: n };\n }\n case 'boolean':\n if (raw === '' || raw === 'true' || raw === '1') return { value: true };\n if (raw === 'false' || raw === '0') return { value: false };\n return undefined;\n case 'string':\n return { value: raw };\n case 'enum': {\n const options = leaf.annotations?.options;\n return !options || options.some((o) => o.value === raw) ? { value: raw } : undefined;\n }\n case 'json': {\n try {\n const value: unknown = JSON.parse(raw);\n return fits(codec, value, leaf) ? { value } : undefined;\n } catch {\n return undefined;\n }\n }\n default:\n return undefined;\n }\n}\n\n/** One leaf a URL can address: its dotted path, and what its value decodes against. */\nexport interface KnobPath {\n path: string;\n leaf: KnobLeaf;\n}\n\n/** Every leaf of `schema` a param can carry, in schema order, with branches flattened into dotted paths. */\nexport function knobPaths(schema: Pick<ConfigSchema<unknown>, 'nodes'>): KnobPath[] {\n const out: KnobPath[] = [];\n const walk = (shape: ConfigShape, at: string): void => {\n for (const [key, entry] of Object.entries(shape)) {\n if (key.startsWith(INTERNAL_PREFIX) || key.includes('.')) continue;\n const path = at === '' ? key : `${at}.${key}`;\n if (isConfigBranch(entry)) walk(entry.children, path);\n else if (codecOf(entry) !== null) out.push({ path, leaf: entry });\n }\n };\n walk(schema.nodes, '');\n return out;\n}\n\n/** Whether two knob values are the same value, compared as data. */\nexport function sameKnob(a: unknown, b: unknown): boolean {\n return Object.is(a, b) || stableStringify(a) === stableStringify(b);\n}\n\n/**\n * The knob params for `config`: one per leaf whose value differs from its default, keyed by dotted path, in schema\n * order. A leaf absent from `config` is at its default.\n */\nexport function knobsToParams(schema: Pick<ConfigSchema<unknown>, 'nodes'>, config: unknown): Record<string, string> {\n const params: Record<string, string> = {};\n for (const { path, leaf } of knobPaths(schema)) {\n const value = valueAtPath(config, path);\n if (value === undefined || sameKnob(value, leaf.default)) continue;\n const encoded = encodeKnob(value);\n if (encoded !== undefined) params[path] = encoded;\n }\n return params;\n}\n\n/**\n * The knob values `params` sets, by dotted path, each coerced to its leaf's type. A param naming no leaf, a reserved\n * param, and one that does not parse as its leaf's type are left out rather than failing the rest.\n */\nexport function paramsToKnobs(\n schema: Pick<ConfigSchema<unknown>, 'nodes'>,\n params: Readonly<Record<string, string>>,\n): Record<string, unknown> {\n const knobs: Record<string, unknown> = {};\n for (const { path, leaf } of knobPaths(schema)) {\n const raw = params[path];\n if (raw === undefined || !isKnobParam(path)) continue;\n const decoded = decodeKnob(raw, leaf);\n if (decoded) knobs[path] = decoded.value;\n }\n return knobs;\n}\n\n/**\n * A link to a story at a given state, for a host that has no schema to hand: each knob is a dotted path and a value,\n * encoded by its own type. `params` adds workshop params, such as `t`.\n */\nexport function storyHref(\n story: string,\n knobs: Readonly<Record<string, unknown>> = {},\n params: Readonly<Record<string, string>> = {},\n): string {\n const encoded: Record<string, string> = {};\n for (const [path, value] of Object.entries(knobs)) {\n const raw = encodeKnob(value);\n if (raw !== undefined && isKnobParam(path)) encoded[path] = raw;\n }\n return formatRoute({ story, params: { ...encoded, ...reservedParams(params) } });\n}\n"]}
1
+ {"version":3,"sources":["../src/route/url.ts"],"names":[],"mappings":";;;;AAWO,IAAM,cAAA,GAAiB;AAGvB,IAAM,eAAA,mBAAuC,IAAI,GAAA,CAAI,CAAC,cAAc,CAAC;AAG5E,IAAM,eAAA,GAAkB,GAAA;AASjB,SAAS,WAAW,IAAA,EAA0B;AACnD,EAAA,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AI,CAAA;AACvB,IAAA,IAAI,GAAA,KAAQ,MAAA,IAAa,CAAC,WAAA,CAAY,IAAI,CAAA,EAAG;AAC7C,IAAA,MAAM,OAAA,GAAU,UAAA,CAAW,GAAA,EAAK,IAAI,CAAA;AACpC,IAAA,IAAI,OAAA,EAAS,KAAA,CAAM,IAAI,CAAA,GAAI,OAAA,CAAQ,KAAA;AAAA,EACrC;AACA,EAAA,OAAO,KAAA;AACT;AAMO,SAAS,UACd,KAAA,EACA,KAAA,GAA2C,EAAC,EAC5C,MAAA,GAA2C,EAAC,EACpC;AACR,EAAA,MAAM,UAAkC,EAAC;AACzC,EAAA,KAAA,MAAW,CAAC,IAAA,EAAM,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAA,EAAG;AACjD,IAAA,MAAM,GAAA,GAAM,WAAW,KAAK,CAAA;AAC5B,IAAA,IAAI,QAAQ,MAAA,IAAa,WAAA,CAAY,IAAI,CAAA,EAAG,OAAA,CAAQ,IAAI,CAAA,GAAI,GAAA;AAAA,EAC9D;AACA,EAAA,OAAO,WAAA,CAAY,EAAE,KAAA,EAAO,MAAA,EAAQ,EAAE,GAAG,OAAA,EAAS,GAAG,cAAA,CAAe,MAAM,CAAA,EAAE,EAAG,CAAA;AACjF","file":"chunk-DPTECNYC.js","sourcesContent":["import { type ConfigSchema, type ConfigShape, isConfigBranch, valueAtPath } from '@weasel-js/labkit/config';\nimport { isPlainObject } from '@weasel-js/core';\nimport { stableStringify } from '../protocol/messages';\n\n/**\n * Forge's URL, as pure functions: `#/<story id>?<params>`. The story and its params share the hash, so the page's\n * own query string stays the host's. A param is a knob — a story arg, addressed by its dotted config path\n * (`look.px`) — unless its name is reserved for the workshop itself.\n */\n\n/** The param a paused playhead is held in, in seconds. */\nexport const PLAYHEAD_PARAM = 't';\n\n/** Param names that are never knobs. */\nexport const RESERVED_PARAMS: ReadonlySet<string> = new Set([PLAYHEAD_PARAM]);\n\n/** Config keys forge keeps for itself, such as the `$globals` pins, start with this and never reach the URL. */\nconst INTERNAL_PREFIX = '$';\n\n/** What a forge hash holds: the story it names, and every param after it, knobs and reserved alike, in order. */\nexport interface ForgeRoute {\n story: string | null;\n params: Readonly<Record<string, string>>;\n}\n\n/** Reads a hash (`location.hash`, with or without its `#`). Anything not in the `#/<id>` form names no story. */\nexport function parseRoute(hash: string): ForgeRoute {\n const body = hash.startsWith('#') ? hash.slice(1) : hash;\n if (!body.startsWith('/')) return { story: null, params: {} };\n const at = body.indexOf('?');\n const path = at === -1 ? body.slice(1) : body.slice(1, at);\n let story: string | null;\n try {\n story = decodeURIComponent(path) || null;\n } catch {\n story = null;\n }\n const params: Record<string, string> = {};\n if (at !== -1) for (const [key, value] of new URLSearchParams(body.slice(at + 1))) params[key] = value;\n return { story, params };\n}\n\n/** The hash for `route`, with its leading `#`. The inverse of `parseRoute`. */\nexport function formatRoute(route: ForgeRoute): string {\n const query = new URLSearchParams(Object.entries(route.params)).toString();\n return `#/${encodeURIComponent(route.story ?? '')}${query ? `?${query}` : ''}`;\n}\n\n/** Whether a param name can be a knob: not reserved and not one of forge's own config keys. */\nexport function isKnobParam(name: string): boolean {\n return name !== '' && !RESERVED_PARAMS.has(name) && !name.startsWith(INTERNAL_PREFIX);\n}\n\n/** The params that are knobs, with the reserved ones left out. */\nexport function knobParams(params: Readonly<Record<string, string>>): Record<string, string> {\n return Object.fromEntries(Object.entries(params).filter(([name]) => isKnobParam(name)));\n}\n\n/** The params that are not knobs. Kept as they are when the knobs are rewritten. */\nexport function reservedParams(params: Readonly<Record<string, string>>): Record<string, string> {\n return Object.fromEntries(Object.entries(params).filter(([name]) => !isKnobParam(name)));\n}\n\n/** What a knob's value is decoded against: its schema leaf's declared kind, its default, and its choices. */\nexport interface KnobLeaf {\n kind: string | null;\n default: unknown;\n annotations?: { options?: readonly { value: string }[] };\n}\n\ntype Codec = 'number' | 'boolean' | 'string' | 'enum' | 'json';\n\n/** How a leaf's value travels: by its declared kind first, then by the type of its default. */\nfunction codecOf(leaf: KnobLeaf): Codec | null {\n switch (leaf.kind) {\n case 'number':\n case 'boolean':\n case 'string':\n case 'enum':\n return leaf.kind;\n case 'color':\n return 'string';\n case 'list':\n case 'json':\n return 'json';\n }\n const d = leaf.default;\n if (typeof d === 'number' || typeof d === 'boolean' || typeof d === 'string') return typeof d as Codec;\n return Array.isArray(d) || isPlainObject(d) ? 'json' : null;\n}\n\n/** A value as one param. Undefined for a value no param can carry, such as a function. */\nexport function encodeKnob(value: unknown): string | undefined {\n switch (typeof value) {\n case 'string':\n return value;\n case 'number':\n case 'boolean':\n return String(value);\n case 'object':\n return value !== null && (Array.isArray(value) || isPlainObject(value)) ? JSON.stringify(value) : undefined;\n default:\n return undefined;\n }\n}\n\n/** Whether `value` is something a leaf of codec `codec` could hold, so a well-formed param of the wrong type is refused. */\nfunction fits(codec: Codec, value: unknown, leaf: KnobLeaf): boolean {\n if (codec !== 'json') return true;\n const d = leaf.default;\n if (Array.isArray(d)) {\n if (!Array.isArray(value)) return false;\n return leaf.kind !== 'list' || value.every((item) => typeof item === 'string');\n }\n if (isPlainObject(d)) return isPlainObject(value);\n return true;\n}\n\n/**\n * One param read as `leaf`'s type: `{ value }`, or undefined for a param that does not parse as one — a number that\n * is not a number, an option the enum does not list, malformed JSON. A bare boolean param (`?dark`) reads as true.\n */\nexport function decodeKnob(raw: string, leaf: KnobLeaf): { value: unknown } | undefined {\n const codec = codecOf(leaf);\n switch (codec) {\n case 'number': {\n const n = raw.trim() === '' ? Number.NaN : Number(raw);\n return Number.isNaN(n) ? undefined : { value: n };\n }\n case 'boolean':\n if (raw === '' || raw === 'true' || raw === '1') return { value: true };\n if (raw === 'false' || raw === '0') return { value: false };\n return undefined;\n case 'string':\n return { value: raw };\n case 'enum': {\n const options = leaf.annotations?.options;\n return !options || options.some((o) => o.value === raw) ? { value: raw } : undefined;\n }\n case 'json': {\n try {\n const value: unknown = JSON.parse(raw);\n return fits(codec, value, leaf) ? { value } : undefined;\n } catch {\n return undefined;\n }\n }\n default:\n return undefined;\n }\n}\n\n/** One leaf a URL can address: its dotted path, and what its value decodes against. */\nexport interface KnobPath {\n path: string;\n leaf: KnobLeaf;\n}\n\n/** Every leaf of `schema` a param can carry, in schema order, with branches flattened into dotted paths. */\nexport function knobPaths(schema: Pick<ConfigSchema<unknown>, 'nodes'>): KnobPath[] {\n const out: KnobPath[] = [];\n const walk = (shape: ConfigShape, at: string): void => {\n for (const [key, entry] of Object.entries(shape)) {\n if (key.startsWith(INTERNAL_PREFIX) || key.includes('.')) continue;\n const path = at === '' ? key : `${at}.${key}`;\n if (isConfigBranch(entry)) walk(entry.children, path);\n else if (codecOf(entry) !== null) out.push({ path, leaf: entry });\n }\n };\n walk(schema.nodes, '');\n return out;\n}\n\n/** Whether two knob values are the same value, compared as data. */\nexport function sameKnob(a: unknown, b: unknown): boolean {\n return Object.is(a, b) || stableStringify(a) === stableStringify(b);\n}\n\n/**\n * The knob params for `config`: one per leaf whose value differs from its default, keyed by dotted path, in schema\n * order. A leaf absent from `config` is at its default.\n */\nexport function knobsToParams(schema: Pick<ConfigSchema<unknown>, 'nodes'>, config: unknown): Record<string, string> {\n const params: Record<string, string> = {};\n for (const { path, leaf } of knobPaths(schema)) {\n const value = valueAtPath(config, path);\n if (value === undefined || sameKnob(value, leaf.default)) continue;\n const encoded = encodeKnob(value);\n if (encoded !== undefined) params[path] = encoded;\n }\n return params;\n}\n\n/**\n * The knob values `params` sets, by dotted path, each coerced to its leaf's type. A param naming no leaf, a reserved\n * param, and one that does not parse as its leaf's type are left out rather than failing the rest.\n */\nexport function paramsToKnobs(\n schema: Pick<ConfigSchema<unknown>, 'nodes'>,\n params: Readonly<Record<string, string>>,\n): Record<string, unknown> {\n const knobs: Record<string, unknown> = {};\n for (const { path, leaf } of knobPaths(schema)) {\n const raw = params[path];\n if (raw === undefined || !isKnobParam(path)) continue;\n const decoded = decodeKnob(raw, leaf);\n if (decoded) knobs[path] = decoded.value;\n }\n return knobs;\n}\n\n/**\n * A link to a story at a given state, for a host that has no schema to hand: each knob is a dotted path and a value,\n * encoded by its own type. `params` adds workshop params, such as `t`.\n */\nexport function storyHref(\n story: string,\n knobs: Readonly<Record<string, unknown>> = {},\n params: Readonly<Record<string, string>> = {},\n): string {\n const encoded: Record<string, string> = {};\n for (const [path, value] of Object.entries(knobs)) {\n const raw = encodeKnob(value);\n if (raw !== undefined && isKnobParam(path)) encoded[path] = raw;\n }\n return formatRoute({ story, params: { ...encoded, ...reservedParams(params) } });\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { GLOBALS_KEY, effectiveGlobals, storyConfig, isForgePath, PLAYHEAD_KEY } from './chunk-DFKCLZKS.js';
2
- import { StoryHost, useNearViewport, IN_VIEW_MARGIN, createOverrides, createGlobalsTarget, useStoryClock, useClockLoop, scanCssVars, runAxe } from './chunk-AP3DRQLI.js';
1
+ import { GLOBALS_KEY, effectiveGlobals, storyConfig, isForgePath, PLAYHEAD_KEY } from './chunk-7BQPHMA2.js';
2
+ import { StoryHost, useNearViewport, IN_VIEW_MARGIN, createOverrides, createGlobalsTarget, useStoryClock, useClockLoop, scanCssVars, runAxe } from './chunk-NVNTQ4AT.js';
3
3
  import { ClockContext } from './chunk-L5XM5VKB.js';
4
4
  import { createEmitter } from '@weasel-js/registry';
5
5
  import { createContext, memo, useContext, useCallback, useSyncExternalStore, useMemo, useId, useState, useRef, useLayoutEffect, useEffect } from 'react';
@@ -281,5 +281,5 @@ function StoryTrial({ story, setup, ctx, hostRef, onRendered, onError }) {
281
281
  }
282
282
 
283
283
  export { StoryGlobalsContext, StoryTrial, TrialClocksContext, TrialFramesContext, TrialHost, createTrialClocks, createTrialFrames, useCssOverrides, useTrialClock, useTrialFrame };
284
- //# sourceMappingURL=chunk-E2FHBDNQ.js.map
285
- //# sourceMappingURL=chunk-E2FHBDNQ.js.map
284
+ //# sourceMappingURL=chunk-J3GYSNCK.js.map
285
+ //# sourceMappingURL=chunk-J3GYSNCK.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/shell/trialFrames.ts","../src/shell/StoryGlobalsContext.ts","../src/shell/cssVars/overrides.ts","../src/shell/TrialHost.tsx","../src/timeline/trialClocks.ts","../src/timeline/usePersistedPlayhead.ts","../src/shell/StoryTrial.tsx"],"names":["createContext","useContext","createEmitter","NONE","useSyncExternalStore","useRef","useLatest","useEffect","StoryBody","jsx","useState","useCallback","TrialIdContext"],"mappings":";;;;;;;;;;AAmCA,IAAM,QAAA,GAAuB,EAAE,IAAA,EAAM,IAAA,EAAM,IAAA,EAAM,EAAC,EAAG,KAAA,EAAO,IAAA,EAAM,IAAA,EAAM,IAAA,EAAK;AAEtE,SAAS,iBAAA,GAAiC;AAC/C,EAAA,MAAM,MAAA,uBAAa,GAAA,EAAwB;AAC3C,EAAA,MAAM,UAAU,aAAA,EAAc;AAC9B,EAAA,MAAM,UAAU,OAAA,CAAQ,IAAA;AACxB,EAAA,MAAM,KAAA,GAAQ,CAAC,OAAA,EAAiB,IAAA,KAA8B;AAC5D,IAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,GAAA,CAAI,OAAO,CAAA;AAChC,IAAA,IAAI,CAAC,KAAA,EAAO;AACZ,IAAA,MAAA,CAAO,IAAI,OAAA,EAAS,EAAE,GAAG,KAAA,EAAO,GAAG,MAAM,CAAA;AACzC,IAAA,OAAA,EAAQ;AAAA,EACV,CAAA;AACA,EAAA,OAAO;AAAA,IACL,OAAA,CAAQ,SAAS,KAAA,EAAO;AACtB,MAAA,MAAA,CAAO,GAAA,CAAI,OAAA,EAAS,EAAE,IAAA,EAAM,MAAM,IAAA,EAAM,IAAA,EAAM,EAAC,EAAG,KAAA,EAAO,KAAA,CAAM,KAAA,EAAO,IAAA,EAAM,MAAM,CAAA;AAClF,MAAA,OAAA,EAAQ;AACR,MAAA,OAAO,MAAM;AACX,QAAA,IAAI,OAAO,GAAA,CAAI,OAAO,CAAA,EAAG,IAAA,KAAS,MAAM,IAAA,EAAM;AAC9C,QAAA,MAAA,CAAO,OAAO,OAAO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AAA,GAAcD,UAAU,OAAO,CAAA;AACrC,EAAA,MAAM,WAAA,GAAcK,WAAAA,CAAY,CAAC,KAAA,KAAmB,WAAA,CAAY,UAAU,KAAK,CAAA,EAAG,CAAC,WAAW,CAAC,CAAA;AAC/F,EAAA,MAAM,MAAA,GAAS,CAAC,OAAA,qBACdF,GAAAA,CAAC,aAAa,QAAA,EAAb,EAAsB,KAAA,EAAO,KAAA,EAC5B,QAAA,kBAAAA,GAAAA;AAAA,IAAC,SAAA;AAAA,IAAA;AAAA,MACC,KAAA;AAAA,MACA,MAAA;AAAA,MACA,SAAA;AAAA,MACA,OAAO,GAAA,CAAI,KAAA;AAAA,MACX,QAAA;AAAA,MACA,OAAA;AAAA,MACA,UAAA;AAAA,MACA,QAAA;AAAA,MACA,OAAA,EAAS;AAAA;AAAA,GACX,EACF,CAAA;AAGF,EAAA,uBACEA,GAAAA;AAAA,IAAC,SAAA;AAAA,IAAA;AAAA,MACC,QAAQ,KAAA,CAAM,MAAA;AAAA,MACd,KAAA;AAAA,MACA,QAAQ,GAAA,CAAI,MAAA;AAAA,MACZ,OAAA,EAAS,IAAA;AAAA,MACR,GAAI,UAAA,GAAa,EAAE,UAAA,KAAe,EAAC;AAAA,MAEnC,QAAA,EAAA;AAAA;AAAA,GACH;AAEJ","file":"chunk-E2FHBDNQ.js","sourcesContent":["import { createEmitter } from '@weasel-js/registry';\nimport { createContext, useCallback, useContext, useSyncExternalStore } from 'react';\nimport type { A11yReport, CssVarReport, ToFrame } from '../protocol/messages';\n\n/** What an axe run in the frame came back with. */\nexport type A11yOutcome = { ok: true; report: A11yReport } | { ok: false; message: string };\n\n/** The half of a trial's frame that answers a request: each call is one round trip over the frame's channel. */\nexport interface TrialFrameCalls {\n send: (msg: ToFrame) => void;\n audit: () => Promise<A11yOutcome>;\n}\n\n/** What trial chrome can reach of the frame its trial shows. */\nexport interface TrialFrame {\n /** Null while no frame is connected. */\n send: ((msg: ToFrame) => void) | null;\n /** The frame's latest `vars` report. */\n vars: readonly CssVarReport[];\n /** Runs axe over the story and records the answer as `a11y`. Null while no frame is connected. */\n audit: (() => Promise<A11yOutcome>) | null;\n /** What the last audit found; null until one has run against the connected frame. */\n a11y: A11yOutcome | null;\n}\n\n/** Each trial's frame, keyed by trial id: `FrameView` connects and reports, trial chrome reads. */\nexport interface TrialFrames {\n /** Returns a disconnect that does nothing once a newer connection replaced this one. */\n connect(trialId: string, calls: TrialFrameCalls): () => void;\n report(trialId: string, vars: readonly CssVarReport[]): void;\n reportA11y(trialId: string, outcome: A11yOutcome): void;\n get(trialId: string): TrialFrame;\n subscribe(listener: () => void): () => void;\n}\n\nconst NO_FRAME: TrialFrame = { send: null, vars: [], audit: null, a11y: null };\n\nexport function createTrialFrames(): TrialFrames {\n const frames = new Map<string, TrialFrame>();\n const changes = createEmitter();\n const changed = changes.emit;\n const patch = (trialId: string, next: Partial<TrialFrame>) => {\n const frame = frames.get(trialId);\n if (!frame) return;\n frames.set(trialId, { ...frame, ...next });\n changed();\n };\n return {\n connect(trialId, calls) {\n frames.set(trialId, { send: calls.send, vars: [], audit: calls.audit, a11y: null });\n changed();\n return () => {\n if (frames.get(trialId)?.send !== calls.send) return;\n frames.delete(trialId);\n changed();\n };\n },\n report: (trialId, vars) => patch(trialId, { vars }),\n reportA11y: (trialId, a11y) => patch(trialId, { a11y }),\n get: (trialId) => frames.get(trialId) ?? NO_FRAME,\n subscribe: changes.subscribe,\n };\n}\n\n/** The workshop's `TrialFrames`; `null` outside a `Workshop`. */\nexport const TrialFramesContext = createContext<TrialFrames | null>(null);\n\n/** The frame of the trial `trialId` names, re-read when it connects or reports. */\nexport function useTrialFrame(trialId: string): TrialFrame {\n const frames = useContext(TrialFramesContext);\n const subscribe = useCallback((listener: () => void) => frames?.subscribe(listener) ?? (() => {}), [frames]);\n const read = () => frames?.get(trialId) ?? NO_FRAME;\n return useSyncExternalStore(subscribe, read, read);\n}\n","import { createContext } from 'react';\nimport type { Globals } from '../protocol/messages';\n\n/** The lab's global values, which a trial's pins override. A change reaches open frames without replacing instruments. */\nexport const StoryGlobalsContext = createContext<Globals>({});\n","import { usePersistedState } from '@weasel-js/labkit';\n\nexport type CssOverrides = Readonly<Record<string, string>>;\n\nconst NONE: CssOverrides = {};\n\n/** The CSS variable overrides of the trial this is rendered inside, persisted with it. */\nexport function useCssOverrides() {\n return usePersistedState<CssOverrides>('fg-css-overrides', NONE, { scope: 'trial' });\n}\n","import { useLatest } from '@weasel-js/core';\nimport { LabBoundary, TrialIdContext } from '@weasel-js/labkit';\nimport { OverlayPortalProvider } from '@weasel-js/ui';\nimport {\n type ReactNode,\n type RefObject,\n useContext,\n useEffect,\n useId,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { runAxe } from '../frame/a11y';\nimport { createOverrides, type Overrides, scanCssVars } from '../frame/cssVars';\nimport type { FrameSetup } from '../frame/FrameController';\nimport { IN_VIEW_MARGIN, useNearViewport } from '../frame/useNearViewport';\nimport { createGlobalsTarget } from '../frame/globalsTarget';\nimport type { CssVarReport, Globals, Layout, ToFrame } from '../protocol/messages';\nimport { useCssOverrides } from './cssVars/overrides';\nimport { effectiveGlobals, GLOBALS_KEY } from './globals';\nimport { StoryGlobalsContext } from './StoryGlobalsContext';\nimport { type A11yOutcome, TrialFramesContext } from './trialFrames';\n\n/** Props for `TrialHost`. */\nexport interface TrialHostProps {\n layout: Layout;\n setup: FrameSetup;\n /** The trial's config, read for its `$globals` pins. */\n config: unknown;\n /** Rendered once the host element exists, with the globals in force on it. */\n children: (globals: Globals) => ReactNode;\n /** Receives the host element, for a caller with no trial to reach it through. */\n hostRef?: RefObject<HTMLElement | null>;\n /** Called once the children's first commit has painted. */\n onRendered?: () => void;\n}\n\nconst VARS_SETTLE_MS = 100;\n\n/** A selector matching only the element carrying `id`. */\nconst scopeOf = (id: string) => `[data-fg-host=\"${id}\"]`;\n\n/**\n * One story's box in the workshop document: what a frame document was, as an element. It applies the globals to\n * itself, keeps its CSS variable overrides on itself, contains fixed-position descendants and portals, reports its\n * vars and audits to the trial's frame registry, and unmounts its content while out of view.\n */\nexport function TrialHost({ layout, setup, config, children, hostRef, onRendered }: TrialHostProps) {\n const trialId = useContext(TrialIdContext);\n const frames = useContext(TrialFramesContext);\n const labGlobals = useContext(StoryGlobalsContext);\n const pins = (config as Record<string, unknown> | null | undefined)?.[GLOBALS_KEY];\n const globals = useMemo(() => effectiveGlobals(labGlobals, pins), [labGlobals, pins]);\n const [persisted] = useCssOverrides();\n const reactId = useId();\n const hostId = trialId ?? reactId;\n const [host, setHost] = useState<HTMLDivElement | null>(null);\n const elementRef = useRef<HTMLDivElement | null>(null);\n const inView = useNearViewport(elementRef, IN_VIEW_MARGIN);\n const [pending, setPending] = useState(true);\n const overridesRef = useRef<Overrides | null>(null);\n const latest = useLatest({ setup, onRendered });\n\n // Everything the host owns for its lifetime: the globals target, the overrides rule, the registry connection.\n useLayoutEffect(() => {\n if (!host) return;\n const doc = host.ownerDocument;\n const scope = scopeOf(hostId);\n const { cssVarsScope } = latest.current.setup;\n const overrides = createOverrides(doc, cssVarsScope ? `${scope}, ${scope} :is(${cssVarsScope})` : scope);\n overridesRef.current = overrides;\n let lastVars: CssVarReport[] | null = null;\n let reported: string | null = null;\n const publish = (vars: CssVarReport[]) => {\n lastVars = vars;\n const key = JSON.stringify(vars);\n if (key === reported) return;\n reported = key;\n if (trialId) frames?.report(trialId, vars);\n };\n const scan = () => publish(scanCssVars(doc, overrides.has, host));\n let settleTimer: ReturnType<typeof setTimeout> | undefined;\n const ownMutation = (record: MutationRecord) =>\n overrides.owns(record.target) ||\n (record.type === 'childList' &&\n [...record.addedNodes, ...record.removedNodes].length > 0 &&\n [...record.addedNodes, ...record.removedNodes].every(overrides.owns));\n const mutations =\n typeof MutationObserver === 'undefined'\n ? null\n : new MutationObserver((records) => {\n if (records.every(ownMutation)) return;\n clearTimeout(settleTimer);\n settleTimer = setTimeout(scan, VARS_SETTLE_MS);\n });\n mutations?.observe(host, { subtree: true, childList: true, characterData: true, attributes: true });\n\n const send = (msg: ToFrame) => {\n if (msg.type !== 'vars.set') return;\n overrides.set(msg.name, msg.value);\n if (lastVars?.some((v) => v.name === msg.name)) scan();\n };\n const audit = async (): Promise<A11yOutcome> => {\n let outcome: A11yOutcome;\n try {\n outcome = { ok: true, report: await runAxe(host, { page: false }) };\n } catch (error) {\n outcome = { ok: false, message: error instanceof Error ? error.message : String(error) };\n }\n if (trialId) frames?.reportA11y(trialId, outcome);\n return outcome;\n };\n const disconnect = frames && trialId ? frames.connect(trialId, { send, audit }) : () => {};\n\n return () => {\n disconnect();\n mutations?.disconnect();\n clearTimeout(settleTimer);\n overrides.dispose();\n overridesRef.current = null;\n };\n }, [host, hostId, trialId, frames, latest]);\n\n // The overrides the trial persisted, put back on every mount and kept in step with the panel's edits.\n const applied = useRef<Record<string, string>>({});\n useLayoutEffect(() => {\n const overrides = overridesRef.current;\n if (!overrides) return;\n for (const name of Object.keys(applied.current)) if (!(name in persisted)) overrides.set(name, null);\n for (const [name, value] of Object.entries(persisted)) overrides.set(name, value);\n applied.current = { ...persisted };\n }, [host, persisted]);\n\n useLayoutEffect(() => {\n if (!host) return;\n const target = createGlobalsTarget(host, scopeOf(hostId));\n latest.current.setup.applyGlobals?.(globals, target);\n return () => target.dispose();\n }, [host, hostId, globals, latest]);\n\n // The host is hidden until its first commit has painted with its fonts, so a new trial never shows a jump.\n const announced = useRef(false);\n useEffect(() => {\n if (!host || !inView || announced.current) return;\n let canceled = false;\n const done = () => {\n if (canceled) return;\n announced.current = true;\n setPending(false);\n latest.current.onRendered?.();\n };\n const { fonts } = host.ownerDocument;\n if (!fonts) {\n done();\n return;\n }\n const afterPaint = () => requestAnimationFrame(done);\n void fonts.ready.then(afterPaint, afterPaint);\n return () => {\n canceled = true;\n };\n }, [host, inView, latest]);\n\n return (\n <div\n ref={(el) => {\n elementRef.current = el;\n if (hostRef) hostRef.current = el;\n setHost(el);\n }}\n className=\"fg-story\"\n data-fg-host={hostId}\n data-fg-layout={layout}\n data-pending={pending || undefined}\n >\n {host && inView ? (\n // The workshop is itself a lab; below the boundary a story sees no lab, trial or theme above it, as in a\n // document of its own.\n <LabBoundary>\n <OverlayPortalProvider container={host}>{children(globals)}</OverlayPortalProvider>\n </LabBoundary>\n ) : null}\n </div>\n );\n}\n","import { createEmitter } from '@weasel-js/registry';\nimport { createContext, useContext, useSyncExternalStore } from 'react';\nimport type { Clock } from './clock';\n\n/** Each trial's story clock, by trial id: the story's trial publishes it, and the trial's transport reads it. */\nexport interface TrialClocks {\n /** Publishes `clock` as `trialId`'s; the returned function withdraws it. */\n publish(trialId: string, clock: Clock): () => void;\n get(trialId: string): Clock | null;\n subscribe(listener: () => void): () => void;\n}\n\nexport function createTrialClocks(): TrialClocks {\n const clocks = new Map<string, Clock>();\n const changed = createEmitter();\n const notify = changed.emit;\n return {\n publish(trialId, clock) {\n clocks.set(trialId, clock);\n notify();\n return () => {\n if (clocks.get(trialId) !== clock) return;\n clocks.delete(trialId);\n notify();\n };\n },\n get: (trialId) => clocks.get(trialId) ?? null,\n subscribe: changed.subscribe,\n };\n}\n\nexport const TrialClocksContext = createContext<TrialClocks | null>(null);\n\nconst NEVER = () => () => {};\nconst NONE = () => null;\n\n/** The clock trial `trialId`'s story published, or null. */\nexport function useTrialClock(trialId: string): Clock | null {\n const clocks = useContext(TrialClocksContext);\n return useSyncExternalStore(clocks?.subscribe ?? NEVER, clocks ? () => clocks.get(trialId) : NONE);\n}\n","import { useLatest } from '@weasel-js/core';\nimport { useEffect, useRef } from 'react';\nimport type { Clock } from './clock';\n\n/**\n * Keeps `clock`'s paused time in the trial, through `write`, so a reload or a snapshot brings the story back there.\n * It writes when the clock stops or moves while stopped, never on a playing frame. A `persisted` value arriving from\n * outside — a snapshot loaded, a Reset — is requested of the clock, so a span set later can still hold it; null\n * stands for the span's start. Nothing is written while a request waits on a span.\n */\nexport function usePersistedPlayhead(clock: Clock | null, persisted: number | null, write: (time: number) => void): void {\n const written = useRef(persisted);\n const latestWrite = useLatest(write);\n\n useEffect(() => {\n if (!clock || persisted === written.current) return;\n written.current = persisted;\n clock.request(persisted);\n }, [clock, persisted]);\n\n useEffect(() => {\n if (!clock) return;\n return clock.subscribe(() => {\n const { playing, time } = clock.get();\n if (playing || clock.pending() !== null || time === written.current) return;\n written.current = time;\n latestWrite.current(time);\n });\n }, [clock, latestWrite]);\n}\n","import { type RenderContext, TrialIdContext } from '@weasel-js/labkit';\nimport { useLatest } from '@weasel-js/core';\nimport { memo, type RefObject, useCallback, useContext, useEffect, useRef, useState } from 'react';\nimport type { FrameSetup } from '../frame/FrameController';\nimport { StoryHost } from '../frame/StoryHost';\nimport type { Globals } from '../protocol/messages';\nimport type { Decorator, LoadedStory, StoryContext } from '../story/types';\nimport { ClockContext } from '../timeline/context';\nimport { useStoryClock } from '../timeline/StoryClock';\nimport { TrialClocksContext } from '../timeline/trialClocks';\nimport { useClockLoop } from '../timeline/useClockLoop';\nimport { usePersistedPlayhead } from '../timeline/usePersistedPlayhead';\nimport { isForgePath, PLAYHEAD_KEY, storyConfig } from './globals';\nimport { TrialHost } from './TrialHost';\n\n/** Props for `StoryTrial`. */\nexport interface StoryTrialProps {\n story: LoadedStory;\n setup: FrameSetup;\n /** The trial's config and state; the story reads and writes them through its `StoryContext`. */\n ctx: Pick<RenderContext<unknown, unknown>, 'config' | 'state' | 'setConfig' | 'setState'>;\n hostRef?: RefObject<HTMLElement | null>;\n onRendered?: () => void;\n /** A render throw, after the boundary has shown it. */\n onError?: (error: unknown) => void;\n}\n\nconst NO_DECORATORS: readonly Decorator[] = [];\n\ninterface StoryBodyProps {\n story: LoadedStory;\n config: StoryContext['config'];\n setConfig: StoryContext['setConfig'];\n state: unknown;\n setState: StoryContext['setState'];\n globals: Globals;\n decorators: readonly Decorator[];\n resetKey: number;\n onError: (error: unknown) => void;\n}\n\n/** Calls `render` only when its inputs change, as Storybook does: the lab re-renders a trial for its own reasons, and a\n * story declaring a component inside `render` remounts it on every extra call. */\nconst StoryBody = memo(function StoryBody({ story, config, setConfig, state, setState, globals, decorators, resetKey, onError }: StoryBodyProps) {\n const storyCtx: StoryContext = { config, setConfig, state, setState, globals, title: story.title, name: story.name };\n return <StoryHost story={story} ctx={storyCtx} decorators={decorators} resetKey={resetKey} onError={onError} />;\n});\n\n/** A story rendered in the workshop document, inside a `TrialHost`, from the trial's own config and state. */\nexport function StoryTrial({ story, setup, ctx, hostRef, onRendered, onError }: StoryTrialProps) {\n const latestRef = useLatest(ctx);\n // Kept across a write to a key forge owns, so moving the playhead or a pin does not re-render the story.\n const [heldConfig, setHeldConfig] = useState(() => storyConfig(ctx.config));\n const config = storyConfig(ctx.config, heldConfig);\n if (config !== heldConfig) setHeldConfig(config);\n\n // A trial opened on the provisional instrument starts at `null`; the story's own initial state fills it once.\n const seeded = useRef(false);\n useEffect(() => {\n if (seeded.current || ctx.state !== null || !story.initialState) return;\n seeded.current = true;\n ctx.setState(story.initialState(config));\n }, [ctx, story, config]);\n\n // Each new input retries a render the boundary caught, as the frame did on each message.\n // State, not a ref: a render React throws away takes its bump with it.\n const [input, setInput] = useState({ config, state: ctx.state, key: 0 });\n let resetKey = input.key;\n if (input.config !== config || input.state !== ctx.state) {\n resetKey = input.key + 1;\n setInput({ config, state: ctx.state, key: resetKey });\n }\n\n // Stable, as the frame's were: a story may list them as effect dependencies.\n // The pins belong to the trial; a story cannot see them, so it cannot set them either.\n const setConfig = useCallback((path: string, value: unknown) => {\n if (!isForgePath(path)) latestRef.current.setConfig(path, value);\n }, [latestRef]);\n const setState = useCallback((next: unknown) => latestRef.current.setState(next), [latestRef]);\n\n // The story's clock lives with its trial: the trial's transport reads it from the registry, the story from context.\n const trialId = useContext(TrialIdContext);\n const clocks = useContext(TrialClocksContext);\n const ownHost = useRef<HTMLElement | null>(null);\n const host = hostRef ?? ownHost;\n const kept = (ctx.config as Record<string, unknown> | null)?.[PLAYHEAD_KEY];\n const persisted = typeof kept === 'number' && Number.isFinite(kept) ? kept : null;\n const clock = useStoryClock(story.timeline?.(config) ?? null, () => persisted);\n useClockLoop(clock, host);\n usePersistedPlayhead(clock, persisted, (time) => latestRef.current.setConfig(PLAYHEAD_KEY, time));\n useEffect(() => (clock && clocks && trialId ? clocks.publish(trialId, clock) : undefined), [clock, clocks, trialId]);\n\n const decorators = setup.decorators ?? NO_DECORATORS;\n const latestError = useLatest(onError);\n const reportError = useCallback((error: unknown) => latestError.current?.(error), [latestError]);\n const render = (globals: Globals) => (\n <ClockContext.Provider value={clock}>\n <StoryBody\n story={story}\n config={config}\n setConfig={setConfig}\n state={ctx.state}\n setState={setState}\n globals={globals}\n decorators={decorators}\n resetKey={resetKey}\n onError={reportError}\n />\n </ClockContext.Provider>\n );\n\n return (\n <TrialHost\n layout={story.layout}\n setup={setup}\n config={ctx.config}\n hostRef={host}\n {...(onRendered ? { onRendered } : {})}\n >\n {render}\n </TrialHost>\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/shell/trialFrames.ts","../src/shell/StoryGlobalsContext.ts","../src/shell/cssVars/overrides.ts","../src/shell/TrialHost.tsx","../src/timeline/trialClocks.ts","../src/timeline/usePersistedPlayhead.ts","../src/shell/StoryTrial.tsx"],"names":["createContext","useContext","createEmitter","NONE","useSyncExternalStore","useRef","useLatest","useEffect","StoryBody","jsx","useState","useCallback","TrialIdContext"],"mappings":";;;;;;;;;;AAmCA,IAAM,QAAA,GAAuB,EAAE,IAAA,EAAM,IAAA,EAAM,IAAA,EAAM,EAAC,EAAG,KAAA,EAAO,IAAA,EAAM,IAAA,EAAM,IAAA,EAAK;AAEtE,SAAS,iBAAA,GAAiC;AAC/C,EAAA,MAAM,MAAA,uBAAa,GAAA,EAAwB;AAC3C,EAAA,MAAM,UAAU,aAAA,EAAc;AAC9B,EAAA,MAAM,UAAU,OAAA,CAAQ,IAAA;AACxB,EAAA,MAAM,KAAA,GAAQ,CAAC,OAAA,EAAiB,IAAA,KAA8B;AAC5D,IAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,GAAA,CAA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I,MAAA;AAAA,MACZ,OAAA,EAAS,IAAA;AAAA,MACR,GAAI,UAAA,GAAa,EAAE,UAAA,KAAe,EAAC;AAAA,MAEnC,QAAA,EAAA;AAAA;AAAA,GACH;AAEJ","file":"chunk-J3GYSNCK.js","sourcesContent":["import { createEmitter } from '@weasel-js/registry';\nimport { createContext, useCallback, useContext, useSyncExternalStore } from 'react';\nimport type { A11yReport, CssVarReport, ToFrame } from '../protocol/messages';\n\n/** What an axe run in the frame came back with. */\nexport type A11yOutcome = { ok: true; report: A11yReport } | { ok: false; message: string };\n\n/** The half of a trial's frame that answers a request: each call is one round trip over the frame's channel. */\nexport interface TrialFrameCalls {\n send: (msg: ToFrame) => void;\n audit: () => Promise<A11yOutcome>;\n}\n\n/** What trial chrome can reach of the frame its trial shows. */\nexport interface TrialFrame {\n /** Null while no frame is connected. */\n send: ((msg: ToFrame) => void) | null;\n /** The frame's latest `vars` report. */\n vars: readonly CssVarReport[];\n /** Runs axe over the story and records the answer as `a11y`. Null while no frame is connected. */\n audit: (() => Promise<A11yOutcome>) | null;\n /** What the last audit found; null until one has run against the connected frame. */\n a11y: A11yOutcome | null;\n}\n\n/** Each trial's frame, keyed by trial id: `FrameView` connects and reports, trial chrome reads. */\nexport interface TrialFrames {\n /** Returns a disconnect that does nothing once a newer connection replaced this one. */\n connect(trialId: string, calls: TrialFrameCalls): () => void;\n report(trialId: string, vars: readonly CssVarReport[]): void;\n reportA11y(trialId: string, outcome: A11yOutcome): void;\n get(trialId: string): TrialFrame;\n subscribe(listener: () => void): () => void;\n}\n\nconst NO_FRAME: TrialFrame = { send: null, vars: [], audit: null, a11y: null };\n\nexport function createTrialFrames(): TrialFrames {\n const frames = new Map<string, TrialFrame>();\n const changes = createEmitter();\n const changed = changes.emit;\n const patch = (trialId: string, next: Partial<TrialFrame>) => {\n const frame = frames.get(trialId);\n if (!frame) return;\n frames.set(trialId, { ...frame, ...next });\n changed();\n };\n return {\n connect(trialId, calls) {\n frames.set(trialId, { send: calls.send, vars: [], audit: calls.audit, a11y: null });\n changed();\n return () => {\n if (frames.get(trialId)?.send !== calls.send) return;\n frames.delete(trialId);\n changed();\n };\n },\n report: (trialId, vars) => patch(trialId, { vars }),\n reportA11y: (trialId, a11y) => patch(trialId, { a11y }),\n get: (trialId) => frames.get(trialId) ?? NO_FRAME,\n subscribe: changes.subscribe,\n };\n}\n\n/** The workshop's `TrialFrames`; `null` outside a `Workshop`. */\nexport const TrialFramesContext = createContext<TrialFrames | null>(null);\n\n/** The frame of the trial `trialId` names, re-read when it connects or reports. */\nexport function useTrialFrame(trialId: string): TrialFrame {\n const frames = useContext(TrialFramesContext);\n const subscribe = useCallback((listener: () => void) => frames?.subscribe(listener) ?? (() => {}), [frames]);\n const read = () => frames?.get(trialId) ?? NO_FRAME;\n return useSyncExternalStore(subscribe, read, read);\n}\n","import { createContext } from 'react';\nimport type { Globals } from '../protocol/messages';\n\n/** The lab's global values, which a trial's pins override. A change reaches open frames without replacing instruments. */\nexport const StoryGlobalsContext = createContext<Globals>({});\n","import { usePersistedState } from '@weasel-js/labkit';\n\nexport type CssOverrides = Readonly<Record<string, string>>;\n\nconst NONE: CssOverrides = {};\n\n/** The CSS variable overrides of the trial this is rendered inside, persisted with it. */\nexport function useCssOverrides() {\n return usePersistedState<CssOverrides>('fg-css-overrides', NONE, { scope: 'trial' });\n}\n","import { useLatest } from '@weasel-js/core';\nimport { LabBoundary, TrialIdContext } from '@weasel-js/labkit';\nimport { OverlayPortalProvider } from '@weasel-js/ui';\nimport {\n type ReactNode,\n type RefObject,\n useContext,\n useEffect,\n useId,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { runAxe } from '../frame/a11y';\nimport { createOverrides, type Overrides, scanCssVars } from '../frame/cssVars';\nimport type { FrameSetup } from '../frame/FrameController';\nimport { IN_VIEW_MARGIN, useNearViewport } from '../frame/useNearViewport';\nimport { createGlobalsTarget } from '../frame/globalsTarget';\nimport type { CssVarReport, Globals, Layout, ToFrame } from '../protocol/messages';\nimport { useCssOverrides } from './cssVars/overrides';\nimport { effectiveGlobals, GLOBALS_KEY } from './globals';\nimport { StoryGlobalsContext } from './StoryGlobalsContext';\nimport { type A11yOutcome, TrialFramesContext } from './trialFrames';\n\n/** Props for `TrialHost`. */\nexport interface TrialHostProps {\n layout: Layout;\n setup: FrameSetup;\n /** The trial's config, read for its `$globals` pins. */\n config: unknown;\n /** Rendered once the host element exists, with the globals in force on it. */\n children: (globals: Globals) => ReactNode;\n /** Receives the host element, for a caller with no trial to reach it through. */\n hostRef?: RefObject<HTMLElement | null>;\n /** Called once the children's first commit has painted. */\n onRendered?: () => void;\n}\n\nconst VARS_SETTLE_MS = 100;\n\n/** A selector matching only the element carrying `id`. */\nconst scopeOf = (id: string) => `[data-fg-host=\"${id}\"]`;\n\n/**\n * One story's box in the workshop document: what a frame document was, as an element. It applies the globals to\n * itself, keeps its CSS variable overrides on itself, contains fixed-position descendants and portals, reports its\n * vars and audits to the trial's frame registry, and unmounts its content while out of view.\n */\nexport function TrialHost({ layout, setup, config, children, hostRef, onRendered }: TrialHostProps) {\n const trialId = useContext(TrialIdContext);\n const frames = useContext(TrialFramesContext);\n const labGlobals = useContext(StoryGlobalsContext);\n const pins = (config as Record<string, unknown> | null | undefined)?.[GLOBALS_KEY];\n const globals = useMemo(() => effectiveGlobals(labGlobals, pins), [labGlobals, pins]);\n const [persisted] = useCssOverrides();\n const reactId = useId();\n const hostId = trialId ?? reactId;\n const [host, setHost] = useState<HTMLDivElement | null>(null);\n const elementRef = useRef<HTMLDivElement | null>(null);\n const inView = useNearViewport(elementRef, IN_VIEW_MARGIN);\n const [pending, setPending] = useState(true);\n const overridesRef = useRef<Overrides | null>(null);\n const latest = useLatest({ setup, onRendered });\n\n // Everything the host owns for its lifetime: the globals target, the overrides rule, the registry connection.\n useLayoutEffect(() => {\n if (!host) return;\n const doc = host.ownerDocument;\n const scope = scopeOf(hostId);\n const { cssVarsScope } = latest.current.setup;\n const overrides = createOverrides(doc, cssVarsScope ? `${scope}, ${scope} :is(${cssVarsScope})` : scope);\n overridesRef.current = overrides;\n let lastVars: CssVarReport[] | null = null;\n let reported: string | null = null;\n const publish = (vars: CssVarReport[]) => {\n lastVars = vars;\n const key = JSON.stringify(vars);\n if (key === reported) return;\n reported = key;\n if (trialId) frames?.report(trialId, vars);\n };\n const scan = () => publish(scanCssVars(doc, overrides.has, host));\n let settleTimer: ReturnType<typeof setTimeout> | undefined;\n const ownMutation = (record: MutationRecord) =>\n overrides.owns(record.target) ||\n (record.type === 'childList' &&\n [...record.addedNodes, ...record.removedNodes].length > 0 &&\n [...record.addedNodes, ...record.removedNodes].every(overrides.owns));\n const mutations =\n typeof MutationObserver === 'undefined'\n ? null\n : new MutationObserver((records) => {\n if (records.every(ownMutation)) return;\n clearTimeout(settleTimer);\n settleTimer = setTimeout(scan, VARS_SETTLE_MS);\n });\n mutations?.observe(host, { subtree: true, childList: true, characterData: true, attributes: true });\n\n const send = (msg: ToFrame) => {\n if (msg.type !== 'vars.set') return;\n overrides.set(msg.name, msg.value);\n if (lastVars?.some((v) => v.name === msg.name)) scan();\n };\n const audit = async (): Promise<A11yOutcome> => {\n let outcome: A11yOutcome;\n try {\n outcome = { ok: true, report: await runAxe(host, { page: false }) };\n } catch (error) {\n outcome = { ok: false, message: error instanceof Error ? error.message : String(error) };\n }\n if (trialId) frames?.reportA11y(trialId, outcome);\n return outcome;\n };\n const disconnect = frames && trialId ? frames.connect(trialId, { send, audit }) : () => {};\n\n return () => {\n disconnect();\n mutations?.disconnect();\n clearTimeout(settleTimer);\n overrides.dispose();\n overridesRef.current = null;\n };\n }, [host, hostId, trialId, frames, latest]);\n\n // The overrides the trial persisted, put back on every mount and kept in step with the panel's edits.\n const applied = useRef<Record<string, string>>({});\n useLayoutEffect(() => {\n const overrides = overridesRef.current;\n if (!overrides) return;\n for (const name of Object.keys(applied.current)) if (!(name in persisted)) overrides.set(name, null);\n for (const [name, value] of Object.entries(persisted)) overrides.set(name, value);\n applied.current = { ...persisted };\n }, [host, persisted]);\n\n useLayoutEffect(() => {\n if (!host) return;\n const target = createGlobalsTarget(host, scopeOf(hostId));\n latest.current.setup.applyGlobals?.(globals, target);\n return () => target.dispose();\n }, [host, hostId, globals, latest]);\n\n // The host is hidden until its first commit has painted with its fonts, so a new trial never shows a jump.\n const announced = useRef(false);\n useEffect(() => {\n if (!host || !inView || announced.current) return;\n let canceled = false;\n const done = () => {\n if (canceled) return;\n announced.current = true;\n setPending(false);\n latest.current.onRendered?.();\n };\n const { fonts } = host.ownerDocument;\n if (!fonts) {\n done();\n return;\n }\n const afterPaint = () => requestAnimationFrame(done);\n void fonts.ready.then(afterPaint, afterPaint);\n return () => {\n canceled = true;\n };\n }, [host, inView, latest]);\n\n return (\n <div\n ref={(el) => {\n elementRef.current = el;\n if (hostRef) hostRef.current = el;\n setHost(el);\n }}\n className=\"fg-story\"\n data-fg-host={hostId}\n data-fg-layout={layout}\n data-pending={pending || undefined}\n >\n {host && inView ? (\n // The workshop is itself a lab; below the boundary a story sees no lab, trial or theme above it, as in a\n // document of its own.\n <LabBoundary>\n <OverlayPortalProvider container={host}>{children(globals)}</OverlayPortalProvider>\n </LabBoundary>\n ) : null}\n </div>\n );\n}\n","import { createEmitter } from '@weasel-js/registry';\nimport { createContext, useContext, useSyncExternalStore } from 'react';\nimport type { Clock } from './clock';\n\n/** Each trial's story clock, by trial id: the story's trial publishes it, and the trial's transport reads it. */\nexport interface TrialClocks {\n /** Publishes `clock` as `trialId`'s; the returned function withdraws it. */\n publish(trialId: string, clock: Clock): () => void;\n get(trialId: string): Clock | null;\n subscribe(listener: () => void): () => void;\n}\n\nexport function createTrialClocks(): TrialClocks {\n const clocks = new Map<string, Clock>();\n const changed = createEmitter();\n const notify = changed.emit;\n return {\n publish(trialId, clock) {\n clocks.set(trialId, clock);\n notify();\n return () => {\n if (clocks.get(trialId) !== clock) return;\n clocks.delete(trialId);\n notify();\n };\n },\n get: (trialId) => clocks.get(trialId) ?? null,\n subscribe: changed.subscribe,\n };\n}\n\nexport const TrialClocksContext = createContext<TrialClocks | null>(null);\n\nconst NEVER = () => () => {};\nconst NONE = () => null;\n\n/** The clock trial `trialId`'s story published, or null. */\nexport function useTrialClock(trialId: string): Clock | null {\n const clocks = useContext(TrialClocksContext);\n return useSyncExternalStore(clocks?.subscribe ?? NEVER, clocks ? () => clocks.get(trialId) : NONE);\n}\n","import { useLatest } from '@weasel-js/core';\nimport { useEffect, useRef } from 'react';\nimport type { Clock } from './clock';\n\n/**\n * Keeps `clock`'s paused time in the trial, through `write`, so a reload or a snapshot brings the story back there.\n * It writes when the clock stops or moves while stopped, never on a playing frame. A `persisted` value arriving from\n * outside — a snapshot loaded, a Reset — is requested of the clock, so a span set later can still hold it; null\n * stands for the span's start. Nothing is written while a request waits on a span.\n */\nexport function usePersistedPlayhead(clock: Clock | null, persisted: number | null, write: (time: number) => void): void {\n const written = useRef(persisted);\n const latestWrite = useLatest(write);\n\n useEffect(() => {\n if (!clock || persisted === written.current) return;\n written.current = persisted;\n clock.request(persisted);\n }, [clock, persisted]);\n\n useEffect(() => {\n if (!clock) return;\n return clock.subscribe(() => {\n const { playing, time } = clock.get();\n if (playing || clock.pending() !== null || time === written.current) return;\n written.current = time;\n latestWrite.current(time);\n });\n }, [clock, latestWrite]);\n}\n","import { type RenderContext, TrialIdContext } from '@weasel-js/labkit';\nimport { useLatest } from '@weasel-js/core';\nimport { memo, type RefObject, useCallback, useContext, useEffect, useRef, useState } from 'react';\nimport type { FrameSetup } from '../frame/FrameController';\nimport { StoryHost } from '../frame/StoryHost';\nimport type { Globals } from '../protocol/messages';\nimport type { Decorator, LoadedStory, StoryContext } from '../story/types';\nimport { ClockContext } from '../timeline/context';\nimport { useStoryClock } from '../timeline/StoryClock';\nimport { TrialClocksContext } from '../timeline/trialClocks';\nimport { useClockLoop } from '../timeline/useClockLoop';\nimport { usePersistedPlayhead } from '../timeline/usePersistedPlayhead';\nimport { isForgePath, PLAYHEAD_KEY, storyConfig } from './globals';\nimport { TrialHost } from './TrialHost';\n\n/** Props for `StoryTrial`. */\nexport interface StoryTrialProps {\n story: LoadedStory;\n setup: FrameSetup;\n /** The trial's config and state; the story reads and writes them through its `StoryContext`. */\n ctx: Pick<RenderContext<unknown, unknown>, 'config' | 'state' | 'setConfig' | 'setState'>;\n hostRef?: RefObject<HTMLElement | null>;\n onRendered?: () => void;\n /** A render throw, after the boundary has shown it. */\n onError?: (error: unknown) => void;\n}\n\nconst NO_DECORATORS: readonly Decorator[] = [];\n\ninterface StoryBodyProps {\n story: LoadedStory;\n config: StoryContext['config'];\n setConfig: StoryContext['setConfig'];\n state: unknown;\n setState: StoryContext['setState'];\n globals: Globals;\n decorators: readonly Decorator[];\n resetKey: number;\n onError: (error: unknown) => void;\n}\n\n/** Calls `render` only when its inputs change, as Storybook does: the lab re-renders a trial for its own reasons, and a\n * story declaring a component inside `render` remounts it on every extra call. */\nconst StoryBody = memo(function StoryBody({ story, config, setConfig, state, setState, globals, decorators, resetKey, onError }: StoryBodyProps) {\n const storyCtx: StoryContext = { config, setConfig, state, setState, globals, title: story.title, name: story.name };\n return <StoryHost story={story} ctx={storyCtx} decorators={decorators} resetKey={resetKey} onError={onError} />;\n});\n\n/** A story rendered in the workshop document, inside a `TrialHost`, from the trial's own config and state. */\nexport function StoryTrial({ story, setup, ctx, hostRef, onRendered, onError }: StoryTrialProps) {\n const latestRef = useLatest(ctx);\n // Kept across a write to a key forge owns, so moving the playhead or a pin does not re-render the story.\n const [heldConfig, setHeldConfig] = useState(() => storyConfig(ctx.config));\n const config = storyConfig(ctx.config, heldConfig);\n if (config !== heldConfig) setHeldConfig(config);\n\n // A trial opened on the provisional instrument starts at `null`; the story's own initial state fills it once.\n const seeded = useRef(false);\n useEffect(() => {\n if (seeded.current || ctx.state !== null || !story.initialState) return;\n seeded.current = true;\n ctx.setState(story.initialState(config));\n }, [ctx, story, config]);\n\n // Each new input retries a render the boundary caught, as the frame did on each message.\n // State, not a ref: a render React throws away takes its bump with it.\n const [input, setInput] = useState({ config, state: ctx.state, key: 0 });\n let resetKey = input.key;\n if (input.config !== config || input.state !== ctx.state) {\n resetKey = input.key + 1;\n setInput({ config, state: ctx.state, key: resetKey });\n }\n\n // Stable, as the frame's were: a story may list them as effect dependencies.\n // The pins belong to the trial; a story cannot see them, so it cannot set them either.\n const setConfig = useCallback((path: string, value: unknown) => {\n if (!isForgePath(path)) latestRef.current.setConfig(path, value);\n }, [latestRef]);\n const setState = useCallback((next: unknown) => latestRef.current.setState(next), [latestRef]);\n\n // The story's clock lives with its trial: the trial's transport reads it from the registry, the story from context.\n const trialId = useContext(TrialIdContext);\n const clocks = useContext(TrialClocksContext);\n const ownHost = useRef<HTMLElement | null>(null);\n const host = hostRef ?? ownHost;\n const kept = (ctx.config as Record<string, unknown> | null)?.[PLAYHEAD_KEY];\n const persisted = typeof kept === 'number' && Number.isFinite(kept) ? kept : null;\n const clock = useStoryClock(story.timeline?.(config) ?? null, () => persisted);\n useClockLoop(clock, host);\n usePersistedPlayhead(clock, persisted, (time) => latestRef.current.setConfig(PLAYHEAD_KEY, time));\n useEffect(() => (clock && clocks && trialId ? clocks.publish(trialId, clock) : undefined), [clock, clocks, trialId]);\n\n const decorators = setup.decorators ?? NO_DECORATORS;\n const latestError = useLatest(onError);\n const reportError = useCallback((error: unknown) => latestError.current?.(error), [latestError]);\n const render = (globals: Globals) => (\n <ClockContext.Provider value={clock}>\n <StoryBody\n story={story}\n config={config}\n setConfig={setConfig}\n state={ctx.state}\n setState={setState}\n globals={globals}\n decorators={decorators}\n resetKey={resetKey}\n onError={reportError}\n />\n </ClockContext.Provider>\n );\n\n return (\n <TrialHost\n layout={story.layout}\n setup={setup}\n config={ctx.config}\n hostRef={host}\n {...(onRendered ? { onRendered } : {})}\n >\n {render}\n </TrialHost>\n );\n}\n"]}
@@ -1,11 +1,12 @@
1
1
  import { isNative, ClockContext } from './chunk-L5XM5VKB.js';
2
2
  import { storyNameFromExport, storyId, PROP_ARG_TYPES_EXPORT } from './chunk-ZAWXMUGZ.js';
3
- import { portSafePart, appliedLocal, withUnsent, coverOf, ArgsContext } from './chunk-GB6PRJET.js';
3
+ import { portSafePart, appliedLocal, withUnsent, coverOf, ArgsContext } from './chunk-SQ4KCIEH.js';
4
4
  import { useVisibleRaf, useLatest, isPlainObject } from '@weasel-js/core';
5
5
  import { createContext, useSyncExternalStore, useRef, useEffect, useState, Component, useContext, createElement } from 'react';
6
6
  import { createEmitter } from '@weasel-js/registry';
7
7
  import { jsx } from 'react/jsx-runtime';
8
8
  import { f } from '@weasel-js/labkit/config';
9
+ import { iconFromData } from '@weasel-js/ui';
9
10
 
10
11
  // src/frame/a11y.ts
11
12
  var IMPACTS = /* @__PURE__ */ new Set(["minor", "moderate", "serious", "critical"]);
@@ -56,12 +57,85 @@ async function runAxe(element, { page = true } = {}) {
56
57
  };
57
58
  }
58
59
 
59
- // src/frame/cssVars.ts
60
+ // src/frame/cssVarUse.ts
60
61
  var VAR_REF = /var\(\s*(--[\w-]+)/g;
61
- function collect(text, names) {
62
- if (!text.includes("var(")) return;
63
- for (const [, name] of text.matchAll(VAR_REF)) names.add(name);
62
+ var CUSTOM_DECL = /(?:^|[;{\s])(--[\w-]+)\s*:\s*([^;]*)/g;
63
+ var RESTLESS = /::?(?:before|after|first-line|first-letter|marker|placeholder|selection|backdrop|file-selector-button)\b|::[\w-]+(?:\([^)]*\))?|:(?:hover|active|focus-visible|focus-within|focus|visited|target)\b/g;
64
+ var STYLE_RULE = 1;
65
+ function varRefs(text, into = /* @__PURE__ */ new Set()) {
66
+ if (!text.includes("var(")) return into;
67
+ for (const [, name] of text.matchAll(VAR_REF)) into.add(name);
68
+ return into;
69
+ }
70
+ function reach(selector, root) {
71
+ const resting = selector.replace(RESTLESS, "").trim() || "*";
72
+ try {
73
+ return { within: root.matches(resting) || root.querySelector(resting) !== null, above: root.parentElement?.closest(resting) != null };
74
+ } catch {
75
+ return { within: true, above: true };
76
+ }
77
+ }
78
+ function readBlock(block, defs, seeds) {
79
+ for (const [, name, value] of block.matchAll(CUSTOM_DECL)) {
80
+ const refs = defs.get(name) ?? /* @__PURE__ */ new Set();
81
+ varRefs(value, refs);
82
+ defs.set(name, refs);
83
+ }
84
+ if (seeds) varRefs(block.replace(CUSTOM_DECL, ""), seeds);
64
85
  }
86
+ function blockOf(rule) {
87
+ const text = rule.cssText;
88
+ const open = text.indexOf("{");
89
+ return open < 0 ? "" : text.slice(open + 1, text.lastIndexOf("}"));
90
+ }
91
+ function walk(rules, root, defs, seeds, parent) {
92
+ for (const rule of Array.from(rules)) {
93
+ const imported = rule.styleSheet;
94
+ if (imported) {
95
+ const inner = cssRulesOf(imported);
96
+ if (inner) walk(inner, root, defs, seeds);
97
+ continue;
98
+ }
99
+ const children = rule.cssRules;
100
+ if (rule.type !== STYLE_RULE) {
101
+ if (children) walk(children, root, defs, seeds);
102
+ continue;
103
+ }
104
+ const at = reach(rule.selectorText, root);
105
+ if (at.within || at.above) readBlock(blockOf(rule), defs, at.within ? seeds : null);
106
+ }
107
+ }
108
+ function cssRulesOf(sheet) {
109
+ try {
110
+ return sheet.cssRules;
111
+ } catch {
112
+ return null;
113
+ }
114
+ }
115
+ function usedCssVars(doc, root) {
116
+ const defs = /* @__PURE__ */ new Map();
117
+ const seeds = /* @__PURE__ */ new Set();
118
+ for (const sheet of Array.from(doc.styleSheets)) {
119
+ const rules = cssRulesOf(sheet);
120
+ if (rules) walk(rules, root, defs, seeds);
121
+ }
122
+ for (const el of Array.from(doc.querySelectorAll("[style]"))) {
123
+ const within = root.contains(el);
124
+ if (within || el.contains(root)) readBlock(el.getAttribute("style") ?? "", defs, within ? seeds : null);
125
+ }
126
+ const used = /* @__PURE__ */ new Set();
127
+ const queue = [...seeds];
128
+ while (queue.length > 0) {
129
+ const name = queue.pop();
130
+ if (used.has(name)) continue;
131
+ used.add(name);
132
+ for (const ref of defs.get(name) ?? []) queue.push(ref);
133
+ }
134
+ return used;
135
+ }
136
+
137
+ // src/frame/cssVars.ts
138
+ var collect = (text, names) => void varRefs(text, names);
65
139
  function walkRules(sheet, names) {
66
140
  let rules;
67
141
  try {
@@ -80,7 +154,8 @@ function scanCssVars(doc, overridden = () => false, root = doc.documentElement)
80
154
  for (const el of Array.from(doc.querySelectorAll("[style]"))) collect(el.getAttribute("style") ?? "", names);
81
155
  for (const sheet of Array.from(doc.styleSheets)) walkRules(sheet, names);
82
156
  const values = resolveValues(doc, names, root);
83
- return [...names].sort().map((name) => ({ name, value: values.get(name) ?? "", overridden: overridden(name) }));
157
+ const used = usedCssVars(doc, root);
158
+ return [...names].sort().map((name) => ({ name, value: values.get(name) ?? "", overridden: overridden(name), used: used.has(name) }));
84
159
  }
85
160
  function resolveValues(doc, names, root) {
86
161
  const view = doc.defaultView;
@@ -390,7 +465,10 @@ function controlled(control, argType, has, value) {
390
465
  const { icons } = control;
391
466
  const node = f.enum(
392
467
  def(),
393
- icons ? options.map((value2) => ({ value: value2, label: value2, ...icons[value2] ? { icon: icons[value2] } : {} })) : options
468
+ icons ? options.map((value2) => {
469
+ const ref = iconFromData(icons[value2]);
470
+ return { value: value2, label: value2, ...ref ? { icon: ref } : {} };
471
+ }) : options
394
472
  );
395
473
  return control.type === "radio" || control.type === "inline-radio" ? node.radio() : node;
396
474
  }
@@ -664,5 +742,5 @@ function useNearViewport(ref, margin, initial = true) {
664
742
  }
665
743
 
666
744
  export { IN_VIEW_MARGIN, StoryHost, createGlobalsTarget, createOverrides, indexRenderOf, loadStories, resolveCssVar, runAxe, scanCssVars, useClockLoop, useNearViewport, useStoryClock };
667
- //# sourceMappingURL=chunk-AP3DRQLI.js.map
668
- //# sourceMappingURL=chunk-AP3DRQLI.js.map
745
+ //# sourceMappingURL=chunk-NVNTQ4AT.js.map
746
+ //# sourceMappingURL=chunk-NVNTQ4AT.js.map