@weasel-js/forge 1.9.2 → 1.9.4

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 (48) hide show
  1. package/README.md +22 -0
  2. package/dist/{FrameController-CpcY0DNB.d.ts → FrameController-BQjKhdwk.d.ts} +2 -36
  3. package/dist/chunk-5DXUNLV2.js +6 -0
  4. package/dist/chunk-5DXUNLV2.js.map +1 -0
  5. package/dist/{chunk-MGQWCPYE.js → chunk-5KI5YSQ5.js} +4 -5
  6. package/dist/chunk-5KI5YSQ5.js.map +1 -0
  7. package/dist/{chunk-Q2EZXJFE.js → chunk-B3PPHJTS.js} +59 -45
  8. package/dist/chunk-B3PPHJTS.js.map +1 -0
  9. package/dist/{chunk-CJX3W5HY.js → chunk-FRUA5WJF.js} +4 -3
  10. package/dist/chunk-FRUA5WJF.js.map +1 -0
  11. package/dist/{chunk-GZPQMGXJ.js → chunk-JHL4ERDA.js} +4 -3
  12. package/dist/chunk-JHL4ERDA.js.map +1 -0
  13. package/dist/{chunk-JVRHBI3V.js → chunk-MQSFPRF6.js} +20 -44
  14. package/dist/chunk-MQSFPRF6.js.map +1 -0
  15. package/dist/chunk-TXLWQFF6.js +10 -0
  16. package/dist/chunk-TXLWQFF6.js.map +1 -0
  17. package/dist/{chunk-BGOHALHO.js → chunk-ZZCCIXEJ.js} +11 -90
  18. package/dist/chunk-ZZCCIXEJ.js.map +1 -0
  19. package/dist/{config-BfsYw5lg.d.ts → config-Dfu-NKxd.d.ts} +27 -4
  20. package/dist/csf/preview-api.js +2 -2
  21. package/dist/frame/index.d.ts +2 -2
  22. package/dist/frame/index.js +6 -40
  23. package/dist/frame/index.js.map +1 -1
  24. package/dist/index.d.ts +3 -3
  25. package/dist/index.js +3 -3
  26. package/dist/index.js.map +1 -1
  27. package/dist/shell/index.css +61 -61
  28. package/dist/shell/index.css.map +1 -1
  29. package/dist/shell/index.d.ts +5 -13
  30. package/dist/shell/index.js +345 -332
  31. package/dist/shell/index.js.map +1 -1
  32. package/dist/test/index.d.ts +4 -2
  33. package/dist/test/index.js +7 -7
  34. package/dist/test/index.js.map +1 -1
  35. package/dist/test/play.d.ts +3 -3
  36. package/dist/test/play.js.map +1 -1
  37. package/dist/vite/index.d.ts +3 -1
  38. package/dist/vite/index.js +365 -101
  39. package/dist/vite/index.js.map +1 -1
  40. package/package.json +5 -5
  41. package/dist/chunk-BGOHALHO.js.map +0 -1
  42. package/dist/chunk-CJX3W5HY.js.map +0 -1
  43. package/dist/chunk-GZPQMGXJ.js.map +0 -1
  44. package/dist/chunk-JVRHBI3V.js.map +0 -1
  45. package/dist/chunk-KJGXJD3U.js +0 -15
  46. package/dist/chunk-KJGXJD3U.js.map +0 -1
  47. package/dist/chunk-MGQWCPYE.js.map +0 -1
  48. package/dist/chunk-Q2EZXJFE.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/shell/globals.ts"],"names":["from"],"mappings":";;;;AAqCO,IAAM,WAAA,GAAc;AAEpB,IAAM,UAAA,GAAa,KAAA;AAEnB,IAAM,UAAA,GAAa;AAE1B,IAAM,UAAA,GAAa,EAAE,KAAA,EAAO,UAAA,EAAY,OAAO,KAAA,EAAM;AAErD,IAAM,QAAA,GAAW,aAAA;AAEV,IAAM,aAAA,GAAgB,CAAC,IAAA,KAA0B,IAAA,KAAS,eAAe,IAAA,CAAK,UAAA,CAAW,CAAA,EAAG,WAAW,CAAA,CAAA,CAAG;AAG1G,IAAM,YAAA,GAAe;AAG5B,IAAM,6BAAkC,IAAI,GAAA,CAAI,CAAC,WAAA,EAAa,YAAY,CAAC,CAAA;AAGpE,IAAM,WAAA,GAAc,CAAC,IAAA,KAA0B,UAAA,CAAW,GAAA,CAAI,KAAK,KAAA,CAAM,GAAG,CAAA,CAAE,CAAC,CAAE;AAGjF,SAAS,YAAA,CAAa,aAAgC,OAAA,EAAgD;AAC3G,EAAA,MAAM,EAAE,OAAM,GAAI,WAAA;AAClB,EAAA,OAA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AA,GAAU,MAAA,CAAO,OAAA,CAAQ,YAAY,CAAA;AAC3C,EAAA,IAAI,OAAA,CAAQ,MAAA,KAAW,CAAA,EAAG,OAAO,MAAA;AACjC,EAAA,MAAM,SAAS,MAAA,CAAO,WAAA;AAAA,IACpB,QAAQ,GAAA,CAAI,CAAC,CAAC,GAAA,EAAK,WAAW,CAAA,KAAM;AAAA,MAClC,GAAA;AAAA,MACA,EAAE,IAAA,CAAK,UAAA,EAAY,CAAC,EAAE,OAAO,UAAA,EAAY,KAAA,EAAO,KAAA,EAAM,EAAG,GAAG,WAAA,CAAY,OAAO,CAAC,CAAA,CAAE,KAAA,CAAM,YAAY,KAAK;AAAA,KAC1G;AAAA,GACH;AAEA,EAAA,MAAM,KAAA,GAAQ,CAAA,CAAE,KAAA,CAAM,MAAM,EAAE,KAAA,CAAM,EAAE,CAAA,CAAE,OAAA,CAAQ,WAAW,EAAE,MAAA,EAAQ,QAAA,EAAU,IAAA,EAAM,SAAS,CAAA;AAC9F,EAAA,OAAO,CAAA,CAAE,MAAA,CAAO,EAAE,GAAG,MAAA,CAAO,OAAO,CAAC,WAAW,GAAG,KAAA,EAAO,CAAA;AAC3D","file":"chunk-JHL4ERDA.js","sourcesContent":["import { isPlainObject } from '@weasel-js/core';\nimport type { IconName } from '@weasel-js/ui';\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 `tune`. */\n icon?: IconName;\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' });\n return f.schema({ ...schema.nodes, [GLOBALS_KEY]: group }) as ConfigSchema<unknown>;\n}\n"]}
@@ -1,11 +1,12 @@
1
- import { StoryHost } from './chunk-Q2EZXJFE.js';
1
+ import { useNearViewport, StoryHost } from './chunk-B3PPHJTS.js';
2
2
  import { sanitize } from './chunk-HRGPFQBW.js';
3
- import { PROTOCOL_VERSION, isPlainObject } from './chunk-KJGXJD3U.js';
3
+ import { PROTOCOL_VERSION } from './chunk-TXLWQFF6.js';
4
4
  import { f, isConfigBranch, resolveConfigSchema, schemaNodeAtPath, titleCase } from '@weasel-js/labkit/config';
5
+ import { createContext, useContext, useMemo, useState, useRef, useEffect, useId } from 'react';
5
6
  import { Badge } from '@weasel-js/ui/components/Badge';
6
7
  import { jsx, jsxs } from 'react/jsx-runtime';
7
8
  import { Button } from '@weasel-js/ui/components/Button';
8
- import { createContext, useMemo, useState, useRef, useEffect, useContext, useId } from 'react';
9
+ import { isPlainObject } from '@weasel-js/core';
9
10
 
10
11
  var joinPath = (at, key) => at === "" ? key : `${at}.${key}`;
11
12
  function describeShape(shape) {
@@ -153,31 +154,20 @@ function indexEntries(stories) {
153
154
  }
154
155
  return [...byTitle.values()];
155
156
  }
156
-
157
- // src/story/library.ts
158
- var LIBRARIES = [
159
- ["/packages/ui/", "ui"],
160
- ["/packages/labkit/", "labkit"],
161
- ["/packages/forge/", "forge"],
162
- ["/apps/draw/", "draw"],
163
- ["/apps/forge/", "forge"]
164
- ];
165
- function libraryOf(entry) {
166
- const file = entry.file.replaceAll("\\", "/");
167
- for (const [marker, label] of LIBRARIES) {
168
- if (file.includes(marker)) return label;
169
- }
170
- return entry.title.split("/")[0] ?? entry.title;
157
+ function librariesFrom(table = []) {
158
+ return {
159
+ of(entry) {
160
+ const file = entry.file.replaceAll("\\", "/");
161
+ return table.find((library) => file.includes(library.path))?.label ?? entry.title.split("/")[0] ?? entry.title;
162
+ },
163
+ toneOf: (label) => table.find((library) => library.label === label)?.tone
164
+ };
171
165
  }
172
- var tone = (swatch, light, dark) => `light-dark(color-mix(in oklab, var(--wzl-swatch-${swatch}), var(--wzl-fg) ${light}%), color-mix(in oklab, var(--wzl-swatch-${swatch}), var(--wzl-fg) ${dark}%))`;
173
- var LIBRARY_TONES = {
174
- ui: tone("amber", 55, 40),
175
- labkit: tone("teal", 55, 45),
176
- forge: tone("blue", 55, 35),
177
- draw: tone("rose", 55, 35)
178
- };
166
+ var TITLE_LIBRARIES = librariesFrom();
167
+ var LibrariesContext = createContext(TITLE_LIBRARIES);
179
168
  function LibraryBadge({ library, className }) {
180
- return /* @__PURE__ */ jsx(Badge, { status: "muted", tone: LIBRARY_TONES[library], variant: "subtle", size: "sm", ...className ? { className } : {}, children: library });
169
+ const tone = useContext(LibrariesContext).toneOf(library);
170
+ return /* @__PURE__ */ jsx(Badge, { status: "muted", ...tone === void 0 ? {} : { tone }, variant: "subtle", size: "sm", ...className ? { className } : {}, children: library });
181
171
  }
182
172
  var MAX_ENUM_OPTIONS = 8;
183
173
  var MAX_ROWS = 6;
@@ -227,26 +217,12 @@ function useEnv() {
227
217
  return env;
228
218
  }
229
219
  var NEAR_MARGIN = "100%";
230
- function useNearViewport(ref) {
231
- const [near, setNear] = useState(typeof IntersectionObserver === "undefined");
232
- useEffect(() => {
233
- const el = ref.current;
234
- if (!el || typeof IntersectionObserver === "undefined") return;
235
- const observer = new IntersectionObserver((entries) => {
236
- const last = entries.at(-1);
237
- if (last) setNear(last.isIntersecting);
238
- }, { rootMargin: NEAR_MARGIN });
239
- observer.observe(el);
240
- return () => observer.disconnect();
241
- }, [ref]);
242
- return near;
243
- }
244
220
  function IndexStory({ story, config: over, label }) {
245
221
  const env = useEnv();
246
222
  const [config, setConfig] = useState(() => mergeConfig(story.config.defaults(), over));
247
223
  const [state, setState] = useState(() => story.initialState?.(config) ?? null);
248
224
  const cell = useRef(null);
249
- const near = useNearViewport(cell);
225
+ const near = useNearViewport(cell, NEAR_MARGIN, false);
250
226
  const [height, setHeight] = useState(null);
251
227
  useEffect(() => {
252
228
  const el = cell.current;
@@ -400,6 +376,6 @@ function IndexPage({ env, render }) {
400
376
  return /* @__PURE__ */ jsx(IndexEnvContext.Provider, { value: env, children: render ? render(indexContext(env)) : /* @__PURE__ */ jsx(DefaultIndex, {}) });
401
377
  }
402
378
 
403
- export { IndexPage, LibraryBadge, answerSchema, describeSchema, indexEntries, indexId, isIndexId, libraryOf, openChannel, schemaFromDescription };
404
- //# sourceMappingURL=chunk-JVRHBI3V.js.map
405
- //# sourceMappingURL=chunk-JVRHBI3V.js.map
379
+ export { IndexPage, LibrariesContext, LibraryBadge, TITLE_LIBRARIES, answerSchema, describeSchema, indexEntries, indexId, isIndexId, librariesFrom, openChannel, schemaFromDescription };
380
+ //# sourceMappingURL=chunk-MQSFPRF6.js.map
381
+ //# sourceMappingURL=chunk-MQSFPRF6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/protocol/schema.ts","../src/protocol/channel.ts","../src/story/indexPages.ts","../src/story/library.ts","../src/frame/index/LibraryBadge.tsx","../src/frame/index/variants.ts","../src/frame/index/IndexPage.tsx"],"names":["isConfigBranch","createContext","useContext","jsx","Badge"],"mappings":";;;;;;;;;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,SAAS,GAAA,CAAI,OAAA;AAAA,IACb,KAAA,EAAO,UAAA;AAAA,IACP,QAAA,EAAU,aAAA;AAAA,IACV,YAAA;AAAA,IACA,YAAA,EAAc,iBAAA;AAAA,IACd,OAAA,EAAS,IAAI,OAAA,IAAW,KAAA;AAAA,IACxB,MAAM,GAAA,CAAI;AAAA,GACZ;AACF;AAGO,SAAS,SAAA,CAAU,EAAE,GAAA,EAAK,MAAA,EAAO,EAAyE;AAC/G,EAAA,uBACEA,GAAAA,CAAC,eAAA,CAAgB,QAAA,EAAhB,EAAyB,OAAO,GAAA,EAAM,QAAA,EAAA,MAAA,GAAS,MAAA,CAAO,YAAA,CAAa,GAAG,CAAC,CAAA,mBAAIA,GAAAA,CAAC,gBAAa,CAAA,EAAG,CAAA;AAEjG","file":"chunk-MQSFPRF6.js","sourcesContent":["import {\n f,\n isConfigBranch,\n resolveConfigSchema,\n schemaNodeAtPath,\n type Annotations,\n type BranchAnnotations,\n type ConfigBranch,\n type ConfigEntry,\n type ConfigNode,\n type ConfigSchema,\n type ConfigShape,\n type NodeOptions,\n} from '@weasel-js/labkit/config';\n\nexport interface SectionDescription {\n label: string;\n collapsed?: boolean;\n}\n\nexport type DescribedEntry =\n | {\n branch: true;\n annotations: BranchAnnotations;\n section?: SectionDescription;\n conditional: boolean;\n children: DescribedShape;\n }\n | {\n branch: false;\n kind: string | null;\n default: unknown;\n annotations: Annotations;\n section?: SectionDescription;\n conditional: boolean;\n validated: boolean;\n /** The node draws its own row with `.render`, which stays in the frame. */\n customControl: boolean;\n };\n\nexport type DescribedShape = { [key: string]: DescribedEntry };\n\n/** A story's `f.schema` as structured-clone data. */\nexport interface SchemaDescription {\n nodes: DescribedShape;\n}\n\n/** Answers the workshop has for the rebuilt schema's predicates. */\nexport interface SchemaAnswers {\n hidden(path: string, config: unknown): boolean;\n errors(path: string, config: unknown): string[];\n}\n\nconst joinPath = (at: string, key: string): string => (at === '' ? key : `${at}.${key}`);\n\nfunction describeShape(shape: ConfigShape): DescribedShape {\n const out: DescribedShape = {};\n for (const [key, entry] of Object.entries(shape)) {\n const { section, showIf } = entry.options;\n const common = {\n annotations: { ...entry.annotations },\n ...(section === undefined ? {} : { section: { ...section } }),\n conditional: showIf !== undefined,\n };\n out[key] = isConfigBranch(entry)\n ? { branch: true, ...common, children: describeShape(entry.children) }\n : {\n branch: false,\n kind: entry.kind,\n default: entry.default,\n ...common,\n validated: entry.options.validate !== undefined,\n customControl: entry.options.render !== undefined,\n };\n }\n return out;\n}\n\nexport function describeSchema(schema: ConfigSchema<unknown>): SchemaDescription {\n return { nodes: describeShape(schema.nodes) };\n}\n\nfunction rebuildShape(shape: DescribedShape, at: string, answers: SchemaAnswers): ConfigShape {\n const out: Record<string, ConfigEntry> = {};\n for (const [key, entry] of Object.entries(shape)) {\n const path = joinPath(at, key);\n const options: NodeOptions = {\n ...(entry.section === undefined ? {} : { section: entry.section }),\n ...(entry.conditional ? { showIf: (config) => !answers.hidden(path, config) } : {}),\n };\n if (entry.branch) {\n const branch: ConfigBranch = {\n children: rebuildShape(entry.children, path, answers),\n annotations: entry.annotations,\n options,\n };\n out[key] = branch;\n } else {\n const node: ConfigNode = {\n kind: entry.kind,\n default: entry.default,\n annotations: entry.annotations,\n options: entry.validated ? { ...options, validate: (_leaf, config) => answers.errors(path, config) } : options,\n };\n out[key] = node;\n }\n }\n return out;\n}\n\nexport function schemaFromDescription(\n description: SchemaDescription,\n answers: SchemaAnswers,\n): ConfigSchema<unknown> {\n return f.schema(rebuildShape(description.nodes, '', answers)) as ConfigSchema<unknown>;\n}\n\n/** Evaluate a schema's own predicates for one config — the frame's half of `answers`. */\nexport function answerSchema(\n schema: ConfigSchema<unknown>,\n config: unknown,\n): { hidden: string[]; errors: Record<string, string[]> } {\n const hidden: string[] = [];\n const errors: Record<string, string[]> = {};\n const record = config as Record<string, unknown>;\n let group: ReturnType<typeof resolveConfigSchema>['group'] | undefined;\n\n const walk = (shape: ConfigShape, at: string): void => {\n for (const [key, entry] of Object.entries(shape)) {\n const path = joinPath(at, key);\n if (entry.options.showIf && !entry.options.showIf(record)) hidden.push(path);\n if (isConfigBranch(entry)) {\n walk(entry.children, path);\n continue;\n }\n const { validate } = entry.options;\n if (!validate) continue;\n group ??= resolveConfigSchema(schema).group;\n const leaf = schemaNodeAtPath(group, path);\n if (!leaf || 'children' in leaf) continue;\n const found = validate(leaf, record);\n if (found.length > 0) errors[path] = found;\n }\n };\n walk(schema.nodes, '');\n return { hidden, errors };\n}\n","import { type Envelope, PROTOCOL_VERSION } from './messages';\n\nexport interface PortLike {\n postMessage(message: unknown): void;\n addEventListener(type: 'message', fn: (event: MessageEvent) => void): void;\n removeEventListener(type: 'message', fn: (event: MessageEvent) => void): void;\n start?(): void;\n close(): void;\n}\n\nexport interface Channel<In, Out> {\n send(msg: Out): void;\n on(fn: (msg: In) => void): () => void;\n close(): void;\n}\n\nexport type Mismatch = { reason: 'not-an-envelope' } | { reason: 'version'; version: unknown };\n\nexport interface ChannelOptions {\n onMismatch?: (mismatch: Mismatch) => void;\n}\n\nexport function openChannel<In, Out>(port: PortLike, options: ChannelOptions = {}): Channel<In, Out> {\n const listeners = new Set<(msg: In) => void>();\n const onMessage = (event: MessageEvent) => {\n const data: unknown = event.data;\n if (typeof data !== 'object' || data === null || !('msg' in data)) {\n options.onMismatch?.({ reason: 'not-an-envelope' });\n return;\n }\n const envelope = data as Partial<Envelope<In>>;\n if (envelope.v !== PROTOCOL_VERSION) {\n options.onMismatch?.({ reason: 'version', version: envelope.v });\n return;\n }\n for (const fn of listeners) fn(envelope.msg as In);\n };\n port.addEventListener('message', onMessage);\n port.start?.();\n return {\n send: (msg) => port.postMessage({ v: PROTOCOL_VERSION, msg } satisfies Envelope<Out>),\n on: (fn) => {\n listeners.add(fn);\n return () => listeners.delete(fn);\n },\n close: () => {\n port.removeEventListener('message', onMessage);\n listeners.clear();\n port.close();\n },\n };\n}\n","import { sanitize } from './ids';\nimport type { IndexEntry } from './types';\n\nconst SUFFIX = ':index';\n\n/** The name an index page goes by in the sidebar and in its trial's title. */\nexport const INDEX_NAME = 'Index';\n\n/** The id of `title`'s index page. A colon never survives `sanitize`, so no story id can collide with it. */\nexport function indexId(title: string): string {\n return `${sanitize(title)}${SUFFIX}`;\n}\n\nexport function isIndexId(id: string): boolean {\n return id.endsWith(SUFFIX);\n}\n\n/**\n * One index-page entry per title in `stories`, in the order titles first appear. It routes and runs like a story:\n * its `file` is the title's first story file, its descriptions are the title's own, and its tags are those every story\n * of the title carries.\n */\nexport function indexEntries(stories: readonly IndexEntry[]): IndexEntry[] {\n const byTitle = new Map<string, IndexEntry>();\n for (const entry of stories) {\n const page = byTitle.get(entry.title);\n if (page) {\n if (page.tags) {\n const common = page.tags.filter((tag) => entry.tags?.includes(tag));\n if (common.length > 0) page.tags = common;\n else delete page.tags;\n }\n continue;\n }\n byTitle.set(entry.title, {\n id: indexId(entry.title),\n title: entry.title,\n name: INDEX_NAME,\n exportName: '',\n file: entry.file,\n ...(entry.componentDescription === undefined ? {} : { componentDescription: entry.componentDescription }),\n ...(entry.componentName === undefined ? {} : { componentName: entry.componentName }),\n ...(entry.tags === undefined ? {} : { tags: entry.tags }),\n });\n }\n return [...byTitle.values()];\n}\n","import { createContext } from 'react';\n\n/** One library of a project: the story files under `path` carry `label`. */\nexport interface Library {\n /** A stretch of path every story file of the library has, with forward slashes: `/packages/ui/`. */\n path: string;\n label: string;\n /** The CSS color the library's badge is toned with. Default: the badge's own muted tone. */\n tone?: string;\n}\n\n/** A project's libraries, as the tree's package filter, the index page header, and Get Info ask about them. */\nexport interface Libraries {\n /** The label of the first library whose `path` the story's file holds, else its title's first segment. */\n of(entry: { file: string; title: string }): string;\n toneOf(label: string): string | undefined;\n}\n\nexport function librariesFrom(table: readonly Library[] = []): Libraries {\n return {\n of(entry) {\n const file = entry.file.replaceAll('\\\\', '/');\n return table.find((library) => file.includes(library.path))?.label ?? entry.title.split('/')[0] ?? entry.title;\n },\n toneOf: (label) => table.find((library) => library.label === label)?.tone,\n };\n}\n\n/** No table: every story's library is its title's first segment. */\nexport const TITLE_LIBRARIES = librariesFrom();\n\n/** The workshop's libraries, from `ShellConfig.libraries`. */\nexport const LibrariesContext = createContext<Libraries>(TITLE_LIBRARIES);\n","// The component's own entry, not the barrel: the barrel would bring every weasel-ui component into each frame.\nimport { Badge } from '@weasel-js/ui/components/Badge';\nimport { useContext } from 'react';\nimport { LibrariesContext } from '../../story/library';\n\n/** A component's library, as a badge in the tone the project gave that library. */\nexport function LibraryBadge({ library, className }: { library: string; className?: string }) {\n const tone = useContext(LibrariesContext).toneOf(library);\n return (\n <Badge status=\"muted\" {...(tone === undefined ? {} : { tone })} variant=\"subtle\" size=\"sm\" {...(className ? { className } : {})}>\n {library}\n </Badge>\n );\n}\n","import { type ConfigSchema, type ConfigShape, isConfigBranch, titleCase } from '@weasel-js/labkit/config';\nimport { isPlainObject } from '@weasel-js/core';\n\nexport interface VariantValue {\n value: unknown;\n label: string;\n}\n\n/** One control a story is shown varying along, with every other control at its default. */\nexport interface VariantRow {\n /** Dotted, as `setConfig` takes it. */\n path: string;\n label: string;\n values: VariantValue[];\n}\n\n/** Above this many choices a row stops being something to scan. */\nexport const MAX_ENUM_OPTIONS = 8;\nexport const MAX_ROWS = 6;\n\nconst labelOf = (key: string, name: string | undefined): string => name ?? titleCase(key);\n\n/**\n * The boolean and enum controls of `schema` a story can be shown varying along, in schema order: skipped are\n * controls that draw their own row, controls hidden at the defaults, and enums with more than\n * `MAX_ENUM_OPTIONS` choices. At most `MAX_ROWS`.\n */\nexport function variantRows(schema: ConfigSchema<unknown>): VariantRow[] {\n const defaults = schema.defaults() as Record<string, unknown>;\n const rows: VariantRow[] = [];\n const walk = (shape: ConfigShape, at: string): void => {\n for (const [key, entry] of Object.entries(shape)) {\n if (rows.length >= MAX_ROWS) return;\n const path = at === '' ? key : `${at}.${key}`;\n if (entry.options.showIf && !entry.options.showIf(defaults)) continue;\n if (isConfigBranch(entry)) {\n walk(entry.children, path);\n continue;\n }\n if (entry.annotations.hidden || entry.options.render) continue;\n const label = labelOf(key, entry.annotations.name);\n if (entry.kind === 'boolean') {\n rows.push({ path, label, values: [false, true].map((value) => ({ value, label: String(value) })) });\n } else if (entry.kind === 'enum') {\n const options = entry.annotations.options ?? [];\n if (options.length < 2 || options.length > MAX_ENUM_OPTIONS) continue;\n rows.push({ path, label, values: options.map((o) => ({ value: o.value, label: o.label })) });\n }\n }\n };\n walk(schema.nodes, '');\n return rows;\n}\n\n/** `over` merged into `base`: nested plain objects merge, anything else replaces. */\nexport function mergeConfig(base: unknown, over: unknown): unknown {\n if (!isPlainObject(base) || !isPlainObject(over)) return over === undefined ? base : over;\n const out: Record<string, unknown> = { ...base };\n for (const [key, value] of Object.entries(over)) out[key] = mergeConfig(base[key], value);\n return out;\n}\n\n/** `config` with `value` at dotted `path`, copying each object along the way. */\nexport function withValueAt(config: unknown, path: string, value: unknown): unknown {\n const [head, ...rest] = path.split('.');\n if (head === undefined) return value;\n const record = isPlainObject(config) ? config : {};\n return { ...record, [head]: rest.length === 0 ? value : withValueAt(record[head], rest.join('.'), value) };\n}\n","// The components' own entries, not the barrel: the barrel would bring every weasel-ui component into each frame.\nimport { Badge } from '@weasel-js/ui/components/Badge';\nimport { Button } from '@weasel-js/ui/components/Button';\nimport {\n createContext,\n type MouseEvent,\n type ReactNode,\n useContext,\n useEffect,\n useId,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport type { Globals } from '../../protocol/messages';\nimport { indexId } from '../../story/indexPages';\nimport type { ComponentDeps, Decorator, IndexContext, IndexStoryProps, LoadedStory, StoryContext } from '../../story/types';\nimport { StoryHost } from '../StoryHost';\nimport { useNearViewport } from '../useNearViewport';\nimport { mergeConfig, variantRows, withValueAt } from './variants';\nimport './index.css';\nimport { LibraryBadge } from './LibraryBadge';\n\n/** What every cell on an index page shares with the frame that hosts it. */\nexport interface IndexEnv {\n title: string;\n /** The package the component ships in. */\n library?: string;\n description?: string;\n stories: readonly LoadedStory[];\n /** Per story id, the JSDoc above its export. */\n descriptions: Readonly<Record<string, string>>;\n /** A catalog or showcase rather than one component: every story of it is tagged `gallery`. */\n gallery?: boolean;\n /** The ids of the stories tagged `gallery`. */\n galleries?: readonly string[];\n /** The component's place in the component graph; absent until the graph arrives, and for a gallery. */\n dependencies?: ComponentDeps;\n globals: Globals;\n /** The frame config's, outermost. */\n decorators: readonly Decorator[];\n open: (id: string) => void;\n onError: (error: unknown) => void;\n}\n\nexport const IndexEnvContext = createContext<IndexEnv | null>(null);\n\nfunction useEnv(): IndexEnv {\n const env = useContext(IndexEnvContext);\n if (!env) throw new Error('An index page part rendered outside its index page');\n return env;\n}\n\n/** How far past the viewport a cell stays mounted. */\nconst NEAR_MARGIN = '100%';\n\n/**\n * One story at its defaults with `config` over them. It keeps its own config and state, so it stays interactive, and\n * it mounts only while near the viewport, so a page of canvas stories stays under the browser's WebGL context cap.\n */\nexport function IndexStory({ story, config: over, label }: IndexStoryProps) {\n const env = useEnv();\n const [config, setConfig] = useState(() => mergeConfig(story.config.defaults(), over));\n const [state, setState] = useState<unknown>(() => story.initialState?.(config) ?? null);\n const cell = useRef<HTMLElement>(null);\n // Starts unmounted, so a page of canvas stories never mounts every cell at once.\n const near = useNearViewport(cell, NEAR_MARGIN, false);\n // Held while unmounted, so scrolling past a cell does not move everything after it.\n const [height, setHeight] = useState<number | null>(null);\n useEffect(() => {\n const el = cell.current;\n if (!near || !el || typeof ResizeObserver === 'undefined') return;\n const observer = new ResizeObserver(() => setHeight(el.getBoundingClientRect().height));\n observer.observe(el);\n return () => observer.disconnect();\n }, [near]);\n const ctx: StoryContext = {\n config,\n setConfig: (path, value) => setConfig((prev: unknown) => withValueAt(prev, path, value)),\n state,\n setState: (next) =>\n setState((prev: unknown) => (typeof next === 'function' ? (next as (p: unknown) => unknown)(prev) : next)),\n globals: env.globals,\n title: story.title,\n name: story.name,\n };\n return (\n <figure\n ref={cell}\n className={`fg-index-cell fg-index-cell--${story.layout}`}\n style={!near && height !== null ? { minHeight: height } : undefined}\n >\n <div className=\"fg-index-cell__stage\">\n {near ? (\n <StoryHost story={story} ctx={ctx} decorators={env.decorators} resetKey={0} onError={env.onError} />\n ) : null}\n </div>\n {label === undefined ? null : <figcaption className=\"fg-index-cell__label\">{label}</figcaption>}\n </figure>\n );\n}\n\n/** `story` once per value of each boolean and enum control, every other control at its default. */\nexport function IndexVariants({ story }: { story: LoadedStory }) {\n const rows = useMemo(() => variantRows(story.config), [story]);\n const defaults = useMemo(() => story.config.defaults(), [story]);\n if (rows.length === 0) return null;\n return (\n <div className=\"fg-index-variants\">\n {rows.map((row) => (\n <section key={row.path} className=\"fg-index-variants__row\" aria-label={row.label}>\n <h4 className=\"fg-index-variants__label\">{row.label}</h4>\n <div className=\"fg-index-variants__cells\">\n {row.values.map((v) => (\n <IndexStory\n key={String(v.value)}\n story={story}\n config={withValueAt(defaults, row.path, v.value) as Record<string, unknown>}\n label={v.label}\n />\n ))}\n </div>\n </section>\n ))}\n </div>\n );\n}\n\nfunction GalleryBadge() {\n return (\n <Badge status=\"accent\" variant=\"subtle\" size=\"sm\">\n Gallery\n </Badge>\n );\n}\n\nfunction DependencyList({ label, titles, empty }: { label: string; titles: readonly string[]; empty: string }) {\n const env = useEnv();\n const labelId = useId();\n const follow = (event: MouseEvent, id: string) => {\n if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;\n event.preventDefault();\n env.open(id);\n };\n return (\n <div className=\"fg-index-deps__row\">\n <dt id={labelId} className=\"fg-index-deps__label\">\n {label}\n </dt>\n <dd className=\"fg-index-deps__value\">\n {titles.length === 0 ? (\n <span className=\"fg-index-deps__empty\">{empty}</span>\n ) : (\n <ul className=\"fg-index-deps__list\" aria-labelledby={labelId}>\n {titles.map((title) => {\n const cut = title.lastIndexOf('/') + 1;\n const id = indexId(title);\n return (\n <li key={title}>\n <a className=\"fg-index-deps__link\" href={`#/${encodeURIComponent(id)}`} onClick={(event) => follow(event, id)}>\n <span className=\"fg-index-deps__prefix\">{title.slice(0, cut)}</span>\n {title.slice(cut)}\n </a>\n </li>\n );\n })}\n </ul>\n )}\n </dd>\n </div>\n );\n}\n\n/** The listed components this one uses and those that use it, read from source. Nothing for a gallery. */\nexport function IndexDependencies() {\n const { gallery, dependencies } = useEnv();\n if (gallery || !dependencies) return null;\n if (dependencies.source === null) {\n return (\n <p className=\"fg-index-deps__none\">\n forge found no source file for this component, so it lists none of its dependencies. It looks for the\n import the meta&rsquo;s <code>component</code> names, or else the one the title&rsquo;s last segment names.\n </p>\n );\n }\n return (\n <dl className=\"fg-index-deps\" aria-label=\"Dependencies\">\n <DependencyList label=\"Uses\" titles={dependencies.uses} empty=\"No listed component.\" />\n <DependencyList label=\"Used by\" titles={dependencies.usedBy} empty=\"No listed component uses it.\" />\n </dl>\n );\n}\n\nfunction StorySection({ story, variants }: { story: LoadedStory; variants: boolean }) {\n const env = useEnv();\n const headingId = useId();\n const description = env.descriptions[story.id];\n const gallery = !env.gallery && env.galleries?.includes(story.id);\n return (\n <section className=\"fg-index-story\" aria-labelledby={headingId}>\n <header className=\"fg-index-story__head\">\n <h2 id={headingId} className=\"fg-index-story__name\">\n {story.name}\n </h2>\n {gallery ? <GalleryBadge /> : null}\n <Button variant=\"secondary\" size=\"sm\" onClick={() => env.open(story.id)}>\n Open\n </Button>\n </header>\n {description ? <p className=\"fg-index-story__description\">{description}</p> : null}\n <IndexStory story={story} />\n {variants ? <IndexVariants story={story} /> : null}\n </section>\n );\n}\n\n/** Which of `stories` show their variants: the first of each set of controls. Stories of one CSF file share their\n * meta's controls, and the same rows under every story would only repeat. */\nfunction firstOfEachControlSet(stories: readonly LoadedStory[]): Set<string> {\n const seen = new Set<string>();\n const shown = new Set<string>();\n for (const story of stories) {\n const key = JSON.stringify(variantRows(story.config));\n if (seen.has(key)) continue;\n seen.add(key);\n shown.add(story.id);\n }\n return shown;\n}\n\n/** The generated page: the component's title and description, then each story, with the variants of the first of\n * each set of controls. */\nexport function DefaultIndex() {\n const env = useEnv();\n const withVariants = useMemo(() => firstOfEachControlSet(env.stories), [env.stories]);\n const segments = env.title.split('/');\n const name = segments.pop();\n const { library } = env;\n if (library !== undefined && segments[0] === library) segments.shift();\n return (\n <article className=\"fg-index\">\n <header className=\"fg-index__head\">\n {segments.length > 0 || library !== undefined ? (\n <p className=\"fg-index__path\">\n {library !== undefined ? <LibraryBadge library={library} className=\"fg-index__library\" /> : null}\n {segments.join(' / ')}\n </p>\n ) : null}\n <div className=\"fg-index__title-row\">\n <h1 className=\"fg-index__title\">{name}</h1>\n {env.gallery ? <GalleryBadge /> : null}\n </div>\n {env.description ? <p className=\"fg-index__description\">{env.description}</p> : null}\n <IndexDependencies />\n </header>\n {env.stories.map((story) => (\n <StorySection key={story.id} story={story} variants={withVariants.has(story.id)} />\n ))}\n </article>\n );\n}\n\n/** What a component's own index page is handed. */\nexport function indexContext(env: IndexEnv): IndexContext {\n return {\n title: env.title,\n ...(env.description === undefined ? {} : { description: env.description }),\n stories: env.stories,\n globals: env.globals,\n Story: IndexStory,\n Variants: IndexVariants,\n DefaultIndex,\n Dependencies: IndexDependencies,\n gallery: env.gallery ?? false,\n open: env.open,\n };\n}\n\n/** The page itself: the component's own, or the generated one. */\nexport function IndexPage({ env, render }: { env: IndexEnv; render: ((ctx: IndexContext) => ReactNode) | null }) {\n return (\n <IndexEnvContext.Provider value={env}>{render ? render(indexContext(env)) : <DefaultIndex />}</IndexEnvContext.Provider>\n );\n}\n"]}
@@ -0,0 +1,10 @@
1
+ export { stableStringify } from '@weasel-js/core';
2
+
3
+ // src/protocol/messages.ts
4
+ var PROTOCOL_VERSION = 1;
5
+ var PORT_HANDOFF = "weaselforge:port";
6
+ var FRAME_HELLO = "weaselforge:hello";
7
+
8
+ export { FRAME_HELLO, PORT_HANDOFF, PROTOCOL_VERSION };
9
+ //# sourceMappingURL=chunk-TXLWQFF6.js.map
10
+ //# sourceMappingURL=chunk-TXLWQFF6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/protocol/messages.ts"],"names":[],"mappings":";;;AAEO,IAAM,gBAAA,GAAmB;AAmFzB,IAAM,YAAA,GAAe;AASrB,IAAM,WAAA,GAAc","file":"chunk-TXLWQFF6.js","sourcesContent":["import type { SchemaDescription } from './schema.ts';\n\nexport const PROTOCOL_VERSION = 1;\n\nexport type Globals = Readonly<Record<string, unknown>>;\nexport type Layout = 'centered' | 'padded' | 'fullscreen';\nexport interface Viewport {\n width: number;\n height: number;\n}\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}\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\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\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"]}
@@ -1,16 +1,15 @@
1
- import { GLOBALS_KEY, effectiveGlobals, storyConfig, isForgePath, PLAYHEAD_KEY } from './chunk-GZPQMGXJ.js';
2
- import { StoryHost, createOverrides, createGlobalsTarget, useStoryClock, useClockLoop, scanCssVars, runAxe, captureElement } from './chunk-Q2EZXJFE.js';
1
+ import { GLOBALS_KEY, effectiveGlobals, storyConfig, isForgePath, PLAYHEAD_KEY } from './chunk-JHL4ERDA.js';
2
+ import { StoryHost, useNearViewport, IN_VIEW_MARGIN, createOverrides, createGlobalsTarget, useStoryClock, useClockLoop, scanCssVars, runAxe } from './chunk-B3PPHJTS.js';
3
3
  import { ClockContext } from './chunk-L5XM5VKB.js';
4
- import { createContext, memo, useContext, useCallback, useSyncExternalStore, useState, useEffect, useMemo, useId, useRef, useLayoutEffect } from 'react';
4
+ import { createContext, memo, useContext, useCallback, useSyncExternalStore, useMemo, useId, useState, useRef, useLayoutEffect, useEffect } from 'react';
5
5
  import { useLatest } from '@weasel-js/core';
6
6
  import { usePersistedState, TrialIdContext, LabBoundary } from '@weasel-js/labkit';
7
7
  import { OverlayPortalProvider } from '@weasel-js/ui';
8
8
  import { jsx } from 'react/jsx-runtime';
9
9
 
10
- var NO_FRAME = { send: null, vars: [], audit: null, a11y: null, capture: null, size: null };
10
+ var NO_FRAME = { send: null, vars: [], audit: null, a11y: null };
11
11
  function createTrialFrames() {
12
12
  const frames = /* @__PURE__ */ new Map();
13
- const hosts = /* @__PURE__ */ new Map();
14
13
  const listeners = /* @__PURE__ */ new Set();
15
14
  const changed = () => {
16
15
  for (const listener of [...listeners]) listener();
@@ -23,15 +22,7 @@ function createTrialFrames() {
23
22
  };
24
23
  return {
25
24
  connect(trialId, calls) {
26
- const held = frames.get(trialId);
27
- frames.set(trialId, {
28
- send: calls.send,
29
- vars: [],
30
- audit: calls.audit,
31
- a11y: null,
32
- capture: calls.capture,
33
- size: held?.size ?? null
34
- });
25
+ frames.set(trialId, { send: calls.send, vars: [], audit: calls.audit, a11y: null });
35
26
  changed();
36
27
  return () => {
37
28
  if (frames.get(trialId)?.send !== calls.send) return;
@@ -41,20 +32,6 @@ function createTrialFrames() {
41
32
  },
42
33
  report: (trialId, vars) => patch(trialId, { vars }),
43
34
  reportA11y: (trialId, a11y) => patch(trialId, { a11y }),
44
- reportSize(trialId, size) {
45
- const frame = frames.get(trialId) ?? NO_FRAME;
46
- if (frame.size?.width === size.width && frame.size?.height === size.height) return;
47
- frames.set(trialId, { ...frame, size });
48
- changed();
49
- },
50
- hostRef(trialId) {
51
- let ref = hosts.get(trialId);
52
- if (!ref) {
53
- ref = { current: null };
54
- hosts.set(trialId, ref);
55
- }
56
- return ref;
57
- },
58
35
  get: (trialId) => frames.get(trialId) ?? NO_FRAME,
59
36
  subscribe(listener) {
60
37
  listeners.add(listener);
@@ -71,49 +48,6 @@ function useTrialFrame(trialId) {
71
48
  return useSyncExternalStore(subscribe, read, read);
72
49
  }
73
50
  var StoryGlobalsContext = createContext({});
74
- var IN_VIEW_MARGIN = "50%";
75
- function useNearViewport(ref, margin) {
76
- const [near, setNear] = useState(true);
77
- useEffect(() => {
78
- const el = ref.current;
79
- if (!el || typeof IntersectionObserver === "undefined") return;
80
- const recheck = () => {
81
- observer.unobserve(el);
82
- observer.observe(el);
83
- };
84
- let watching = false;
85
- const watch = (on) => {
86
- if (on === watching) return;
87
- watching = on;
88
- if (on) {
89
- document.addEventListener("scroll", recheck, { capture: true, passive: true });
90
- window.addEventListener("resize", recheck);
91
- } else {
92
- document.removeEventListener("scroll", recheck, { capture: true });
93
- window.removeEventListener("resize", recheck);
94
- }
95
- };
96
- const observer = new IntersectionObserver(
97
- (entries) => {
98
- const last = entries.at(-1);
99
- if (!last) return;
100
- const root = last.rootBounds;
101
- const box = last.boundingClientRect;
102
- setNear(
103
- root ? box.bottom >= root.top && box.top <= root.bottom && box.right >= root.left && box.left <= root.right : last.isIntersecting
104
- );
105
- watch(Boolean(root) && !last.isIntersecting);
106
- },
107
- { root: document, rootMargin: margin }
108
- );
109
- observer.observe(el);
110
- return () => {
111
- observer.disconnect();
112
- watch(false);
113
- };
114
- }, [ref, margin]);
115
- return near;
116
- }
117
51
  var NONE = {};
118
52
  function useCssOverrides() {
119
53
  return usePersistedState("fg-css-overrides", NONE, { scope: "trial" });
@@ -163,11 +97,7 @@ function TrialHost({ layout, setup, config, children, hostRef, onRendered }) {
163
97
  const send = (msg) => {
164
98
  if (msg.type !== "vars.set") return;
165
99
  overrides.set(msg.name, msg.value);
166
- const at = lastVars?.findIndex((v) => v.name === msg.name) ?? -1;
167
- if (!lastVars || at < 0) return;
168
- const vars = lastVars.slice();
169
- vars[at] = { ...vars[at], overridden: overrides.has(msg.name) };
170
- scan();
100
+ if (lastVars?.some((v) => v.name === msg.name)) scan();
171
101
  };
172
102
  const audit = async () => {
173
103
  let outcome;
@@ -179,23 +109,14 @@ function TrialHost({ layout, setup, config, children, hostRef, onRendered }) {
179
109
  if (trialId) frames?.reportA11y(trialId, outcome);
180
110
  return outcome;
181
111
  };
182
- const capture = async () => captureElement(host);
183
- const disconnect = frames && trialId ? frames.connect(trialId, { send, audit, capture }) : () => {
112
+ const disconnect = frames && trialId ? frames.connect(trialId, { send, audit }) : () => {
184
113
  };
185
- if (frames && trialId) frames.hostRef(trialId).current = host;
186
- const sizes = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(() => {
187
- const { width, height } = host.getBoundingClientRect();
188
- if (trialId) frames?.reportSize(trialId, { width: Math.ceil(width), height: Math.ceil(height) });
189
- });
190
- sizes?.observe(host);
191
114
  return () => {
192
115
  disconnect();
193
- sizes?.disconnect();
194
116
  mutations?.disconnect();
195
117
  clearTimeout(settleTimer);
196
118
  overrides.dispose();
197
119
  overridesRef.current = null;
198
- if (frames && trialId && frames.hostRef(trialId).current === host) frames.hostRef(trialId).current = null;
199
120
  };
200
121
  }, [host, hostId, trialId, frames, latest]);
201
122
  const applied = useRef({});
@@ -215,10 +136,10 @@ function TrialHost({ layout, setup, config, children, hostRef, onRendered }) {
215
136
  const announced = useRef(false);
216
137
  useEffect(() => {
217
138
  if (!host || !inView || announced.current) return;
218
- announced.current = true;
219
139
  let canceled = false;
220
140
  const done = () => {
221
141
  if (canceled) return;
142
+ announced.current = true;
222
143
  setPending(false);
223
144
  latest.current.onRendered?.();
224
145
  };
@@ -368,6 +289,6 @@ function StoryTrial({ story, setup, ctx, hostRef, onRendered, onError }) {
368
289
  );
369
290
  }
370
291
 
371
- export { IN_VIEW_MARGIN, StoryGlobalsContext, StoryTrial, TrialClocksContext, TrialFramesContext, TrialHost, createTrialClocks, createTrialFrames, useCssOverrides, useNearViewport, useTrialClock, useTrialFrame };
372
- //# sourceMappingURL=chunk-BGOHALHO.js.map
373
- //# sourceMappingURL=chunk-BGOHALHO.js.map
292
+ export { StoryGlobalsContext, StoryTrial, TrialClocksContext, TrialFramesContext, TrialHost, createTrialClocks, createTrialFrames, useCssOverrides, useTrialClock, useTrialFrame };
293
+ //# sourceMappingURL=chunk-ZZCCIXEJ.js.map
294
+ //# sourceMappingURL=chunk-ZZCCIXEJ.js.map
@@ -0,0 +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","NONE","useSyncExternalStore","useRef","useLatest","useEffect","StoryBody","jsx","useState","useCallback","TrialIdContext"],"mappings":";;;;;;;;;AAoCA,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,SAAA,uBAAgB,GAAA,EAAgB;AACtC,EAAA,MAAM,UAAU,MAAM;AACpB,IAAA,KAAA,MAAW,QAAA,IAAY,CAAC,GAAG,SAAS,GAAG,QAAA,EAAS;AAAA,EAClD,CAAA;AACA,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,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R,GAAI,UAAA,GAAa,EAAE,UAAA,KAAe,EAAC;AAAA,MAEnC,QAAA,EAAA;AAAA;AAAA,GACH;AAEJ","file":"chunk-ZZCCIXEJ.js","sourcesContent":["import { createContext, useCallback, useContext, useSyncExternalStore } from 'react';\nimport type { A11yReport, CssVarReport, ToFrame } from '../protocol/messages';\n\ntype Send = (msg: ToFrame) => void;\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: Send;\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: Send | 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 listeners = new Set<() => void>();\n const changed = () => {\n for (const listener of [...listeners]) listener();\n };\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(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\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 { 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 listeners = new Set<() => void>();\n const notify = () => {\n for (const listener of [...listeners]) listener();\n };\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(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\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 latest = 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)) latest.current.setConfig(path, value);\n }, [latest]);\n const setState = useCallback((next: unknown) => latest.current.setState(next), [latest]);\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) => latest.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,7 +1,7 @@
1
1
  import { LabMode, LabContribution, LabPage } from '@weasel-js/labkit';
2
2
  import { Theme } from '@weasel-js/theme';
3
3
  import { ControlRenderer } from '@weasel-js/labkit/config';
4
- import { G as Globals, F as FrameSetup } from './FrameController-CpcY0DNB.js';
4
+ import { G as Globals, F as FrameSetup } from './FrameController-BQjKhdwk.js';
5
5
  import { IconName } from '@weasel-js/ui';
6
6
 
7
7
  /** One global the workshop's toolbar sets for every story, and a trial may pin for its own. */
@@ -37,9 +37,29 @@ type GlobalDeclarations = Readonly<Record<string, GlobalDeclaration>>;
37
37
  /** A lab value, for a declaration that `follows` the app, meaning whatever the app's chrome is set to. */
38
38
  declare const FOLLOW_APP = "app";
39
39
 
40
+ /** One library of a project: the story files under `path` carry `label`. */
41
+ interface Library {
42
+ /** A stretch of path every story file of the library has, with forward slashes: `/packages/ui/`. */
43
+ path: string;
44
+ label: string;
45
+ /** The CSS color the library's badge is toned with. Default: the badge's own muted tone. */
46
+ tone?: string;
47
+ }
48
+ /** A project's libraries, as the tree's package filter, the index page header, and Get Info ask about them. */
49
+ interface Libraries {
50
+ /** The label of the first library whose `path` the story's file holds, else its title's first segment. */
51
+ of(entry: {
52
+ file: string;
53
+ title: string;
54
+ }): string;
55
+ toneOf(label: string): string | undefined;
56
+ }
57
+
40
58
  /** A shell config module: what the workshop adds to the lab. Only the workshop page imports it. */
41
59
  interface ShellConfig {
42
- /** The workshop's name, in its header and as the document title. Default `weaselforge`. */
60
+ /** The workshop's name, in its header and as the document title. Default `weaselforge`. The served page reads
61
+ * it from this module's source, so write it as a string or a `const` of this file; a computed one titles the
62
+ * page only once the workshop has loaded. */
43
63
  title?: string;
44
64
  /** Whether the lab offers the CSS Vars panel. Default true. */
45
65
  cssVars?: boolean;
@@ -50,14 +70,17 @@ interface ShellConfig {
50
70
  /** The theme the workshop's own chrome takes at the lab's current globals, so a global can restyle the workshop
51
71
  * as well as the stories. Default: labkit's. */
52
72
  labTheme?: (globals: Globals) => Theme;
73
+ /** The project's libraries, each a stretch of file path and the label its stories carry in the tree's package
74
+ * filter, on index pages, and in Get Info. A story under none of them takes its title's first segment. */
75
+ libraries?: readonly Library[];
53
76
  /** The project's other labs, offered in the workshop's title menu. */
54
77
  pages?: readonly LabPage[];
55
78
  /** Which of `pages` the workshop is, when the URL alone cannot say, as across dev servers on different ports. */
56
79
  path?: string;
57
80
  }
58
- /** A frame config module's default export. Only frame documents import it, so its CSS stays out of the workshop. */
81
+ /** A frame config module's default export. The workshop page imports it as well as every frame document, so CSS it imports reaches both; the plugin's `frameStyles` is for CSS meant for frames alone. */
59
82
  declare function defineFrameConfig(config: FrameSetup): FrameSetup;
60
83
  /** A shell config module's default export. */
61
84
  declare function defineShellConfig(config: ShellConfig): ShellConfig;
62
85
 
63
- export { FOLLOW_APP as F, type GlobalDeclaration as G, type LabChrome as L, type ShellConfig as S, type GlobalDeclarations as a, defineShellConfig as b, defineFrameConfig as d };
86
+ export { FOLLOW_APP as F, type GlobalDeclaration as G, type LabChrome as L, type ShellConfig as S, type GlobalDeclarations as a, type Library as b, defineShellConfig as c, defineFrameConfig as d, type Libraries as e };
@@ -1,5 +1,5 @@
1
- import { ArgsContext, coverOf, isPortSafe } from '../chunk-MGQWCPYE.js';
2
- import '../chunk-KJGXJD3U.js';
1
+ import { ArgsContext, coverOf, isPortSafe } from '../chunk-5KI5YSQ5.js';
2
+ import '../chunk-TXLWQFF6.js';
3
3
  import { useContext } from 'react';
4
4
 
5
5
  var sendable = (value) => {
@@ -1,5 +1,5 @@
1
- import { F as FrameSetup, L as LoadedStory } from '../FrameController-CpcY0DNB.js';
2
- export { p as StartFrameOptions, r as reportImportFault, s as startFrame } from '../FrameController-CpcY0DNB.js';
1
+ import { F as FrameSetup, L as LoadedStory } from '../FrameController-BQjKhdwk.js';
2
+ export { o as StartFrameOptions, r as reportImportFault, s as startFrame } from '../FrameController-BQjKhdwk.js';
3
3
  import '@weasel-js/labkit/config';
4
4
  import 'react';
5
5