@weasel-js/labkit 1.4.4 → 1.5.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 (219) hide show
  1. package/README.md +13 -2
  2. package/dist/_dts/{CanvasStackContext-kTEZvEgE.d.ts → CanvasStackContext-CqkxkFJW.d.ts} +1 -1
  3. package/dist/_dts/ToggleBar.d-DbHoWKIA.d.ts +116 -0
  4. package/dist/_dts/{frac-z7ker2Vx.d.ts → frac-8R6UmlvN.d.ts} +253 -31
  5. package/dist/_dts/index-B8uu2ba7.d.ts +237 -0
  6. package/dist/_dts/{index-Blv9uQzu.d.ts → index-retnAut7.d.ts} +18 -10
  7. package/dist/_dts/{types-B9_zrHmb.d.ts → types-Ca2LCnPq.d.ts} +65 -2
  8. package/dist/_dts/usePanZoom-nS798rOF.d.ts +160 -0
  9. package/dist/_dts/useTrialState-jcx_TdU6.d.ts +212 -0
  10. package/dist/canvas/index.d.ts +17 -128
  11. package/dist/canvas/index.js +4 -2
  12. package/dist/chrome/index.d.ts +4 -92
  13. package/dist/chrome/index.js +9 -5
  14. package/dist/chunk-67SJLMC7.js +704 -0
  15. package/dist/chunk-67SJLMC7.js.map +1 -0
  16. package/dist/chunk-6ZDGOZQV.js +310 -0
  17. package/dist/chunk-6ZDGOZQV.js.map +1 -0
  18. package/dist/{chunk-MOM3GOVY.js → chunk-EKIICY6X.js} +111 -25
  19. package/dist/chunk-EKIICY6X.js.map +1 -0
  20. package/dist/{chunk-CTRKTLYZ.js → chunk-H6ZAOWNE.js} +11 -11
  21. package/dist/chunk-H6ZAOWNE.js.map +1 -0
  22. package/dist/{chunk-SMHP6XZ4.js → chunk-KJALCDWE.js} +9 -7
  23. package/dist/chunk-KJALCDWE.js.map +1 -0
  24. package/dist/{chunk-BKFVHKJH.js → chunk-MUKOW3TC.js} +3 -3
  25. package/dist/{chunk-BKFVHKJH.js.map → chunk-MUKOW3TC.js.map} +1 -1
  26. package/dist/chunk-NDRYLVOW.js +15 -0
  27. package/dist/chunk-NDRYLVOW.js.map +1 -0
  28. package/dist/{chunk-64ZCN3DA.js → chunk-NS64DXMN.js} +226 -159
  29. package/dist/chunk-NS64DXMN.js.map +1 -0
  30. package/dist/{chunk-I6JCVE24.js → chunk-PGETSEDK.js} +135 -13
  31. package/dist/chunk-PGETSEDK.js.map +1 -0
  32. package/dist/{chunk-FQMJUVHJ.js → chunk-QLSV2N3G.js} +32 -37
  33. package/dist/chunk-QLSV2N3G.js.map +1 -0
  34. package/dist/chunk-RWNDDKOH.js +682 -0
  35. package/dist/chunk-RWNDDKOH.js.map +1 -0
  36. package/dist/chunk-S2SHZRD7.js +7681 -0
  37. package/dist/chunk-S2SHZRD7.js.map +1 -0
  38. package/dist/{chunk-U3IYHIAE.js → chunk-TQBBYTAF.js} +19 -82
  39. package/dist/chunk-TQBBYTAF.js.map +1 -0
  40. package/dist/chunk-UU3NJO6N.js +72 -0
  41. package/dist/chunk-UU3NJO6N.js.map +1 -0
  42. package/dist/chunk-WIG6XHJ7.js +35 -0
  43. package/dist/chunk-WIG6XHJ7.js.map +1 -0
  44. package/dist/{chunk-TJ7QY3OC.js → chunk-ZPH5WTWF.js} +21 -15
  45. package/dist/chunk-ZPH5WTWF.js.map +1 -0
  46. package/dist/config/index.d.ts +232 -0
  47. package/dist/config/index.js +6 -0
  48. package/dist/config/index.js.map +1 -0
  49. package/dist/controls/index.d.ts +2 -3
  50. package/dist/controls/index.js +3 -2
  51. package/dist/dragdrop/index.d.ts +2 -4
  52. package/dist/index.d.ts +110 -381
  53. package/dist/index.js +691 -817
  54. package/dist/index.js.map +1 -1
  55. package/dist/layers/index.d.ts +3 -5
  56. package/dist/layers/index.js +2 -2
  57. package/dist/loupe/index.d.ts +6 -8
  58. package/dist/loupe/index.js +2 -2
  59. package/dist/passthrough/weasel-ui.d.ts +164 -122
  60. package/dist/passthrough/weasel-ui.js +1 -1
  61. package/dist/primitives/index.d.ts +53 -6
  62. package/dist/primitives/index.js +6 -4
  63. package/dist/state/index.d.ts +12 -7
  64. package/dist/state/index.js +16 -13
  65. package/dist/state/index.js.map +1 -1
  66. package/dist/styles.css +84 -50
  67. package/dist/surface/index.d.ts +44 -7
  68. package/dist/surface/index.js +2 -1
  69. package/dist/ui/layers/index.js +1 -1
  70. package/dist/undo/index.d.ts +2 -4
  71. package/package.json +15 -8
  72. package/src/annotations/AnnotationOverlay.tsx +53 -5
  73. package/src/annotations/Annotations.overlay.test.tsx +85 -6
  74. package/src/annotations/drawOne.test.ts +1 -1
  75. package/src/annotations/drawOne.ts +2 -2
  76. package/src/annotations/paint.test.ts +2 -2
  77. package/src/annotations/paint.ts +1 -1
  78. package/src/annotations/preload.ts +6 -0
  79. package/src/annotations/store.test.ts +18 -0
  80. package/src/annotations/store.ts +5 -4
  81. package/src/annotations/svgNodes.test.ts +2 -2
  82. package/src/annotations/toolMap.ts +3 -3
  83. package/src/annotations/types.ts +6 -3
  84. package/src/canvas/CameraWheelContext.ts +12 -0
  85. package/src/canvas/CanvasStack.test.tsx +25 -0
  86. package/src/canvas/CanvasStack.tsx +31 -4
  87. package/src/canvas/Stage.less +18 -0
  88. package/src/canvas/Stage.test.tsx +186 -0
  89. package/src/canvas/Stage.tsx +134 -0
  90. package/src/canvas/camera.test.ts +17 -2
  91. package/src/canvas/camera.ts +9 -9
  92. package/src/canvas/index.ts +4 -0
  93. package/src/canvas/usePanZoom.ts +10 -5
  94. package/src/chrome/ChromeRegions.stories.tsx +0 -3
  95. package/src/chrome/LabChrome.tsx +114 -0
  96. package/src/chrome/builtins.tsx +20 -31
  97. package/src/chrome/index.ts +15 -0
  98. package/src/chrome/labRegions.test.tsx +208 -0
  99. package/src/chrome/labTypes.ts +50 -0
  100. package/src/chrome/merge.ts +7 -9
  101. package/src/chrome/regions/PaletteRegion.test.tsx +6 -4
  102. package/src/chrome/regions/PaletteRegion.tsx +21 -9
  103. package/src/chrome/regions/SidebarRegion.tsx +25 -13
  104. package/src/chrome/regions/StatusRegion.tsx +15 -8
  105. package/src/chrome/regions/ToolbarRegion.tsx +30 -16
  106. package/src/chrome/types.ts +47 -20
  107. package/src/config/builder.test.ts +4 -0
  108. package/src/config/builder.ts +16 -10
  109. package/src/config/declarationEmit.fixture.ts +11 -0
  110. package/src/config/declarationEmit.test.ts +51 -0
  111. package/src/config/entry.test.ts +46 -0
  112. package/src/config/index.ts +13 -1
  113. package/src/config/nodeClasses.test.ts +18 -0
  114. package/src/config/types.ts +3 -1
  115. package/src/controls/ControlPanel.test.tsx +16 -0
  116. package/src/controls/ControlPanel.tsx +5 -2
  117. package/src/fake-indexeddb-auto.d.ts +5 -0
  118. package/src/index.test.ts +7 -0
  119. package/src/index.ts +38 -5
  120. package/src/instrument/serializers.test.ts +22 -0
  121. package/src/instrument/serializers.ts +11 -0
  122. package/src/instrument/types.ts +25 -1
  123. package/src/lab/Lab.less +4 -13
  124. package/src/lab/Lab.persist.test.tsx +147 -0
  125. package/src/lab/Lab.stories.tsx +0 -2
  126. package/src/lab/Lab.surface.test.tsx +66 -3
  127. package/src/lab/Lab.test.tsx +91 -17
  128. package/src/lab/Lab.tsx +337 -124
  129. package/src/lab/LabFit.stories.less +18 -0
  130. package/src/lab/LabFit.stories.tsx +219 -0
  131. package/src/lab/LabFullChrome.stories.tsx +0 -3
  132. package/src/lab/LabHeader.test.tsx +40 -9
  133. package/src/lab/LabHeader.tsx +7 -13
  134. package/src/lab/LabPalette.tsx +13 -26
  135. package/src/lab/LabShell.less +49 -12
  136. package/src/lab/LabSwitcher.less +8 -1
  137. package/src/lab/Workspace.surface.test.tsx +2 -1
  138. package/src/lab/fitCheck.test.ts +57 -0
  139. package/src/lab/fitCheck.ts +125 -0
  140. package/src/loupe/AGENTS.md +1 -1
  141. package/src/loupe/Loupe.less +1 -1
  142. package/src/loupe/canvasLens.ts +1 -1
  143. package/src/loupe/types.ts +1 -1
  144. package/src/loupe/useLoupe.test.tsx +1 -1
  145. package/src/loupe/useLoupe.ts +1 -1
  146. package/src/passthrough/weasel-ui.ts +9 -0
  147. package/src/primitives/FloatingPanel.stories.tsx +13 -1
  148. package/src/primitives/FloatingPanel.test.tsx +47 -16
  149. package/src/primitives/FloatingPanel.tsx +11 -25
  150. package/src/primitives/Split.less +14 -0
  151. package/src/primitives/Split.test.tsx +108 -0
  152. package/src/primitives/Split.tsx +159 -0
  153. package/src/primitives/ZoomControl.tsx +5 -2
  154. package/src/primitives/index.ts +2 -0
  155. package/src/state/Persistence.stories.tsx +75 -0
  156. package/src/state/Persistence.tsx +33 -0
  157. package/src/state/SingletonExperiment.test.tsx +47 -53
  158. package/src/state/SingletonExperiment.tsx +24 -13
  159. package/src/state/adapterContract.ts +116 -0
  160. package/src/state/adapters.test.ts +113 -61
  161. package/src/state/adapters.ts +328 -69
  162. package/src/state/document.test.ts +71 -96
  163. package/src/state/document.ts +66 -52
  164. package/src/state/helpers.test.ts +1 -1
  165. package/src/state/index.ts +8 -0
  166. package/src/state/labRecords.test.ts +105 -0
  167. package/src/state/labRecords.ts +160 -0
  168. package/src/state/openLabStore.test.ts +658 -0
  169. package/src/state/openLabStore.ts +403 -0
  170. package/src/state/records.test.ts +234 -0
  171. package/src/state/records.ts +219 -0
  172. package/src/state/store.test.ts +104 -635
  173. package/src/state/store.ts +116 -157
  174. package/src/state/toolSlot.test.ts +1 -1
  175. package/src/state/types.ts +39 -15
  176. package/src/state/useOpenOnce.ts +68 -0
  177. package/src/state/usePersistedState.test.tsx +125 -0
  178. package/src/state/usePersistedState.ts +66 -0
  179. package/src/state/useTrialState.test.tsx +2 -3
  180. package/src/state/view.test.ts +49 -15
  181. package/src/state/view.ts +18 -1
  182. package/src/styles.less +2 -0
  183. package/src/surface/AGENTS.md +39 -7
  184. package/src/surface/SurfaceContext.ts +26 -3
  185. package/src/surface/index.ts +2 -0
  186. package/src/surface/useSurfaceTile.test.tsx +2 -1
  187. package/src/surface/useSurfaceTile.ts +6 -5
  188. package/src/surface/useTiledSurface.test.tsx +175 -0
  189. package/src/surface/useTiledSurface.ts +54 -5
  190. package/src/theme/Interstellar.stories.tsx +7 -7
  191. package/src/theme/interstellar.test.ts +1 -1
  192. package/src/theme/interstellar.tokens.json +2 -2
  193. package/src/tools/labTool.ts +11 -0
  194. package/src/trial/Trial.annotations.persist.test.tsx +100 -58
  195. package/src/trial/Trial.annotations.test.tsx +47 -4
  196. package/src/trial/Trial.job.test.tsx +3 -3
  197. package/src/trial/Trial.less +1 -26
  198. package/src/trial/Trial.stories.tsx +1 -2
  199. package/src/trial/Trial.test.tsx +28 -4
  200. package/src/trial/Trial.trialId.test.tsx +23 -1
  201. package/src/trial/Trial.tsx +118 -38
  202. package/src/trial/TrialBody.tsx +17 -141
  203. package/src/trial/TrialChrome.tsx +7 -4
  204. package/src/trial/trialOps.ts +5 -3
  205. package/dist/_dts/types-BP2OCcpg.d.ts +0 -155
  206. package/dist/_dts/types-x92Kfeme.d.ts +0 -62
  207. package/dist/_dts/useTrialState-D6Vb3T-g.d.ts +0 -99
  208. package/dist/chunk-2P6PP5N4.js +0 -553
  209. package/dist/chunk-2P6PP5N4.js.map +0 -1
  210. package/dist/chunk-64ZCN3DA.js.map +0 -1
  211. package/dist/chunk-CTRKTLYZ.js.map +0 -1
  212. package/dist/chunk-FQMJUVHJ.js.map +0 -1
  213. package/dist/chunk-I6JCVE24.js.map +0 -1
  214. package/dist/chunk-MOM3GOVY.js.map +0 -1
  215. package/dist/chunk-SMHP6XZ4.js.map +0 -1
  216. package/dist/chunk-TJ7QY3OC.js.map +0 -1
  217. package/dist/chunk-U3IYHIAE.js.map +0 -1
  218. package/dist/chunk-W3ECWC2K.js +0 -7335
  219. package/dist/chunk-W3ECWC2K.js.map +0 -1
@@ -0,0 +1,159 @@
1
+ import { type ReactNode, useEffect, useMemo, useRef } from 'react';
2
+ import { asNodeId, createNode, Store, stripStrategy } from 'windease';
3
+ import { type ChromeMap, Container, Provider, StrategyRegistryProvider } from 'windease/react';
4
+
5
+ const ZONE_ID = asNodeId('lk-split');
6
+ const SIDEBAR_ID = asNodeId('lk-split-sidebar');
7
+ const CONTENT_ID = asNodeId('lk-split-content');
8
+ const STRATEGIES = { strip: stripStrategy as never };
9
+
10
+ /** Props for `<Split>`. */
11
+ export interface SplitProps {
12
+ /** The sidebar pane's contents. */
13
+ sidebar: ReactNode;
14
+ /** The content pane's contents. */
15
+ children: ReactNode;
16
+ /** Names the sidebar pane, and through it the seam. Default `'Sidebar'`. */
17
+ label?: string;
18
+ /** Extra classes on the strip, which always has `lk-split`. */
19
+ className?: string;
20
+ /** The class on the sidebar pane. */
21
+ sidebarClassName?: string;
22
+ /** The class on the content pane. */
23
+ contentClassName?: string;
24
+ /** The sidebar's current extent in pixels. Omit to leave it unpersisted: the
25
+ * seam still works, its result just does not outlive the mount. */
26
+ width?: number;
27
+ /** Where the sidebar starts before anyone drags it. */
28
+ defaultWidth?: number;
29
+ minWidth?: number;
30
+ maxWidth?: number;
31
+ /** How little the content pane may be squeezed to. Reported as the seam's
32
+ * reachable maximum, so the drag stops there rather than clamping silently. */
33
+ contentMinWidth?: number;
34
+ /** Fires through the drag, not on release: the pane is already there. */
35
+ onWidthChange?: (width: number) => void;
36
+ /**
37
+ * Fixed extent. Omit in an app — the strip measures its own box. Supply it
38
+ * where nothing measures, notably jsdom, or both panes lay out at zero.
39
+ */
40
+ viewport?: { w: number; h: number };
41
+ }
42
+
43
+ /**
44
+ * A sidebar and a content pane as a two-pane strip with a draggable seam.
45
+ *
46
+ * The seam is `stripStrategy`'s own resize affordance, so it arrives as a
47
+ * `role="separator"` carrying the reachable range, operable by pointer and by
48
+ * arrows / Home / End, and clamped against the content pane's floor rather
49
+ * than against the sidebar's alone.
50
+ */
51
+ export function Split({
52
+ sidebar,
53
+ children,
54
+ label = 'Sidebar',
55
+ className,
56
+ sidebarClassName,
57
+ contentClassName,
58
+ width,
59
+ defaultWidth = 320,
60
+ minWidth = 140,
61
+ maxWidth = 720,
62
+ contentMinWidth = 160,
63
+ onWidthChange,
64
+ viewport,
65
+ }: SplitProps) {
66
+ // The cross-axis half of every size hint below is inert: a horizontal strip
67
+ // stretches its panes to the container's height and never reads `h`.
68
+ const storeRef = useRef<Store | null>(null);
69
+ if (storeRef.current === null) {
70
+ const store = new Store();
71
+ store.registerNode(
72
+ createNode({
73
+ kind: 'zone',
74
+ id: ZONE_ID,
75
+ container: { strategyId: 'strip', config: { axis: 'x', resizable: true } },
76
+ }),
77
+ );
78
+ store.registerNode(
79
+ createNode({
80
+ kind: 'sidebar',
81
+ id: SIDEBAR_ID,
82
+ parentId: ZONE_ID,
83
+ meta: { title: label },
84
+ placement: { size: { w: width ?? defaultWidth } },
85
+ hints: { minSize: { w: minWidth, h: 0 }, maxSize: { w: maxWidth, h: 0 } },
86
+ }),
87
+ );
88
+ store.registerNode(
89
+ createNode({
90
+ kind: 'content',
91
+ id: CONTENT_ID,
92
+ parentId: ZONE_ID,
93
+ meta: { title: 'Content' },
94
+ hints: { minSize: { w: contentMinWidth, h: 0 } },
95
+ }),
96
+ );
97
+ store.showNode(SIDEBAR_ID);
98
+ store.showNode(CONTENT_ID);
99
+ storeRef.current = store;
100
+ }
101
+ const store = storeRef.current;
102
+
103
+ // What the store last held, so the placement event can tell a drag from the
104
+ // echo of our own write and a controlled `width` does not fight the seam.
105
+ const widthRef = useRef(width ?? defaultWidth);
106
+
107
+ useEffect(() => {
108
+ store.setHints(SIDEBAR_ID, {
109
+ minSize: { w: minWidth, h: 0 },
110
+ maxSize: { w: maxWidth, h: 0 },
111
+ });
112
+ store.setHints(CONTENT_ID, { minSize: { w: contentMinWidth, h: 0 } });
113
+ }, [store, minWidth, maxWidth, contentMinWidth]);
114
+
115
+ useEffect(() => {
116
+ store.setMeta(SIDEBAR_ID, { title: label });
117
+ }, [store, label]);
118
+
119
+ useEffect(() => {
120
+ if (width === undefined || width === widthRef.current) return;
121
+ widthRef.current = width;
122
+ store.patchPlacement(SIDEBAR_ID, { size: { w: width } });
123
+ }, [store, width]);
124
+
125
+ const onWidthChangeRef = useRef(onWidthChange);
126
+ onWidthChangeRef.current = onWidthChange;
127
+ useEffect(
128
+ () =>
129
+ store.events.on('node.placementChanged', () => {
130
+ const next = (store.getPlacement(SIDEBAR_ID)?.size as { w?: number } | undefined)?.w;
131
+ if (typeof next !== 'number' || next === widthRef.current) return;
132
+ widthRef.current = next;
133
+ onWidthChangeRef.current?.(next);
134
+ }),
135
+ [store],
136
+ );
137
+
138
+ const chrome = useMemo<ChromeMap>(
139
+ () => ({
140
+ sidebar: () => <div className={sidebarClassName}>{sidebar}</div>,
141
+ content: () => <div className={contentClassName}>{children}</div>,
142
+ }),
143
+ [sidebar, children, sidebarClassName, contentClassName],
144
+ );
145
+
146
+ return (
147
+ <Provider store={store}>
148
+ <StrategyRegistryProvider strategies={STRATEGIES}>
149
+ <Container
150
+ parentId={ZONE_ID}
151
+ chrome={chrome}
152
+ className={className ? `lk-split windease-zone ${className}` : 'lk-split windease-zone'}
153
+ affordances
154
+ viewport={viewport}
155
+ />
156
+ </StrategyRegistryProvider>
157
+ </Provider>
158
+ );
159
+ }
@@ -1,3 +1,4 @@
1
+ import { normalizeZoom } from '@weasel-js/core';
1
2
  import { NumberField, Slider } from '../passthrough/weasel-ui';
2
3
 
3
4
  /** Props for `<ZoomControl>`. */
@@ -30,10 +31,12 @@ export function ZoomControl({
30
31
  zoom,
31
32
  onZoomChange,
32
33
  onZoomCommit,
33
- min = 0.1,
34
- max = 8,
34
+ min: minProp = 0.1,
35
+ max: maxProp = 8,
35
36
  className,
36
37
  }: ZoomControlProps) {
38
+ const min = normalizeZoom(minProp);
39
+ const max = normalizeZoom(maxProp);
37
40
  const commit = onZoomCommit ?? onZoomChange;
38
41
  const emit = (track: number, done: boolean): void => {
39
42
  const next = clamp(fromTrack(track), min, max);
@@ -9,6 +9,8 @@ export type { ScaleIndicatorProps } from './ScaleIndicator';
9
9
  export { ScaleIndicator } from './ScaleIndicator';
10
10
  export type { SidebarProps } from './Sidebar';
11
11
  export { Sidebar } from './Sidebar';
12
+ export type { SplitProps } from './Split';
13
+ export { Split } from './Split';
12
14
  export type { StatusBarProps, StatusBarSectionProps } from './StatusBar';
13
15
  export { StatusBar } from './StatusBar';
14
16
  export type { ToolbarButtonProps, ToolbarGroupProps, ToolbarProps } from './Toolbar';
@@ -0,0 +1,75 @@
1
+ import type { Meta, StoryObj } from '@storybook/react-vite';
2
+ import { useState } from 'react';
3
+ import { expect, userEvent, waitFor, within } from 'storybook/test';
4
+ import { createIndexedDbAdapter } from './adapters';
5
+ import { Persistence } from './Persistence';
6
+ import { usePersistedState } from './usePersistedState';
7
+
8
+ // jsdom only has fake-indexeddb, an imitation. This round-trips a value through
9
+ // the browser's own IndexedDB: write it, unmount the provider so it closes,
10
+ // mount a fresh one, and read it back.
11
+
12
+ function Tab() {
13
+ const [tab, setTab] = usePersistedState('tab', 'shape');
14
+ return (
15
+ <p>
16
+ <output aria-label="tab">{tab}</output>
17
+ <button type="button" onClick={() => setTab('color')}>
18
+ choose color
19
+ </button>
20
+ </p>
21
+ );
22
+ }
23
+
24
+ function Remountable({ database }: { database: string }) {
25
+ const [generation, setGeneration] = useState(0);
26
+ const [shown, setShown] = useState(true);
27
+ const storage = useState(() => createIndexedDbAdapter({ database }))[0];
28
+ return (
29
+ <div>
30
+ <button
31
+ type="button"
32
+ onClick={() => {
33
+ setShown(false);
34
+ // Past the provider's deferred close, which sends the queued write.
35
+ setTimeout(() => {
36
+ setGeneration((g) => g + 1);
37
+ setShown(true);
38
+ }, 100);
39
+ }}
40
+ >
41
+ remount
42
+ </button>
43
+ {shown ? (
44
+ <Persistence
45
+ key={generation}
46
+ storageKey="story"
47
+ storage={storage}
48
+ fallback={<p>loading</p>}
49
+ >
50
+ <Tab />
51
+ </Persistence>
52
+ ) : null}
53
+ </div>
54
+ );
55
+ }
56
+
57
+ const meta: Meta<typeof Remountable> = {
58
+ title: 'labkit/State/Persistence',
59
+ component: Remountable,
60
+ };
61
+ export default meta;
62
+
63
+ export const SurvivesARemountInIndexedDb: StoryObj<typeof Remountable> = {
64
+ args: { database: `labkit-story-${Date.now()}` },
65
+ play: async ({ canvasElement }) => {
66
+ const canvas = within(canvasElement);
67
+ await waitFor(() => expect(canvas.getByLabelText('tab')).toHaveTextContent('shape'));
68
+ await userEvent.click(canvas.getByText('choose color'));
69
+ await userEvent.click(canvas.getByText('remount'));
70
+ await waitFor(() => expect(canvas.queryByLabelText('tab')).toBeNull());
71
+ await waitFor(() => expect(canvas.getByLabelText('tab')).toHaveTextContent('color'), {
72
+ timeout: 3000,
73
+ });
74
+ },
75
+ };
@@ -0,0 +1,33 @@
1
+ import { createContext, type ReactNode } from 'react';
2
+ import { defaultStorage } from './adapters';
3
+ import { labPrefix } from './labRecords';
4
+ import { openRecords, type RecordCache } from './records';
5
+ import type { StorageAdapter } from './types';
6
+ import { useOpenOnce, useWarnIgnoredChange } from './useOpenOnce';
7
+
8
+ /** The records `usePersistedState` reads and writes. `<Lab>`,
9
+ * `SingletonExperimentProvider` and `<Persistence>` provide one. */
10
+ export const PersistenceContext = createContext<RecordCache | null>(null);
11
+
12
+ /** Props for `<Persistence>`. */
13
+ export interface PersistenceProps {
14
+ /** Names the records, as `<Lab storageKey>` does. A lab and a
15
+ * `<Persistence>` given the same key share lab-scoped values. */
16
+ storageKey: string;
17
+ /** Default: IndexedDB, or localStorage where IndexedDB will not open. */
18
+ storage?: StorageAdapter;
19
+ /** Rendered until the records have loaded. Default: nothing. */
20
+ fallback?: ReactNode;
21
+ children: ReactNode;
22
+ }
23
+
24
+ /** Persisted values for a page with no lab: `usePersistedState` below it keeps
25
+ * what it holds across a reload. Both props are read once, at mount. */
26
+ export function Persistence({ storageKey, storage, fallback = null, children }: PersistenceProps) {
27
+ useWarnIgnoredChange('<Persistence>', { storageKey, storage });
28
+ const records = useOpenOnce(async () =>
29
+ openRecords({ storage: storage ?? (await defaultStorage()), prefix: labPrefix(storageKey) }),
30
+ );
31
+ if (!records) return <>{fallback}</>;
32
+ return <PersistenceContext.Provider value={records}>{children}</PersistenceContext.Provider>;
33
+ }
@@ -1,7 +1,7 @@
1
- import { act, render, renderHook } from '@testing-library/react';
2
- import { afterEach, describe, expect, it, vi } from 'vitest';
1
+ import { act, render, renderHook, screen, waitFor } from '@testing-library/react';
2
+ import { describe, expect, it } from 'vitest';
3
3
  import { createMemoryAdapter } from './adapters';
4
- import { labDocumentKey } from './document';
4
+ import { labPrefix } from './labRecords';
5
5
  import { SingletonExperimentProvider } from './SingletonExperiment';
6
6
  import { useTrialState } from './useTrialState';
7
7
 
@@ -13,31 +13,41 @@ interface State {
13
13
  zoom: number;
14
14
  }
15
15
 
16
- describe('SingletonExperimentProvider', () => {
17
- afterEach(() => {
18
- vi.useRealTimers();
19
- });
16
+ function Provider({
17
+ backing,
18
+ children,
19
+ }: {
20
+ backing: Map<string, unknown>;
21
+ children: React.ReactNode;
22
+ }) {
23
+ return (
24
+ <SingletonExperimentProvider<State, Config>
25
+ id="test"
26
+ initialConfig={{ width: 100, bg: '#000' }}
27
+ initialState={{ zoom: 1 }}
28
+ storage={createMemoryAdapter(backing)}
29
+ storageKey="test"
30
+ fallback={<p>loading</p>}
31
+ >
32
+ {children}
33
+ </SingletonExperimentProvider>
34
+ );
35
+ }
20
36
 
21
- it('exposes config and state via useTrialState', () => {
37
+ describe('SingletonExperimentProvider', () => {
38
+ it('shows its fallback, then exposes config and state via useTrialState', async () => {
39
+ const backing = new Map<string, unknown>();
22
40
  const wrapper = ({ children }: { children: React.ReactNode }) => (
23
- <SingletonExperimentProvider<State, Config>
24
- id="test"
25
- initialConfig={{ width: 100, bg: '#000' }}
26
- initialState={{ zoom: 1 }}
27
- storage={createMemoryAdapter()}
28
- storageKey="test"
29
- >
30
- {children}
31
- </SingletonExperimentProvider>
41
+ <Provider backing={backing}>{children}</Provider>
32
42
  );
33
43
  const { result } = renderHook(() => useTrialState<State, Config>(), { wrapper });
34
- expect(result.current.config).toEqual({ width: 100, bg: '#000' });
44
+ expect(screen.getByText('loading')).toBeInTheDocument();
45
+ await waitFor(() => expect(result.current?.config).toEqual({ width: 100, bg: '#000' }));
35
46
  expect(result.current.state).toEqual({ zoom: 1 });
36
47
  });
37
48
 
38
- it('persists config changes to storage', () => {
39
- vi.useFakeTimers();
40
- const storage = createMemoryAdapter();
49
+ it('persists config changes to storage', async () => {
50
+ const backing = new Map<string, unknown>();
41
51
  const Probe = () => {
42
52
  const h = useTrialState<State, Config>();
43
53
  return (
@@ -46,32 +56,24 @@ describe('SingletonExperimentProvider', () => {
46
56
  </button>
47
57
  );
48
58
  };
49
- const { getByText } = render(
50
- <SingletonExperimentProvider<State, Config>
51
- id="test"
52
- initialConfig={{ width: 100, bg: '#000' }}
53
- initialState={{ zoom: 1 }}
54
- storage={storage}
55
- storageKey="test"
56
- >
59
+ render(
60
+ <Provider backing={backing}>
57
61
  <Probe />
58
- </SingletonExperimentProvider>,
62
+ </Provider>,
63
+ );
64
+ const go = await screen.findByText('go');
65
+ act(() => go.click());
66
+ await waitFor(() =>
67
+ expect(backing.get(`${labPrefix('test')}trial:test`)).toMatchObject({
68
+ config: { width: 200 },
69
+ }),
59
70
  );
60
- act(() => {
61
- getByText('go').click();
62
- });
63
- act(() => {
64
- vi.advanceTimersByTime(400);
65
- });
66
- const raw = storage.read(labDocumentKey('test'));
67
- expect(raw).toBeTruthy();
68
- expect(raw).toContain('"width":200');
69
71
  });
70
72
 
71
- it('rehydrates from storage on mount', () => {
72
- const storage = createMemoryAdapter();
73
- // A pre-document lab, which createLabStore folds forward on hydration.
74
- storage.write(
73
+ it('rehydrates from storage on mount', async () => {
74
+ const backing = new Map<string, unknown>();
75
+ // A pre-document lab, which opening folds forward.
76
+ backing.set(
75
77
  'lk:test:workspaces',
76
78
  JSON.stringify([
77
79
  {
@@ -84,18 +86,10 @@ describe('SingletonExperimentProvider', () => {
84
86
  ]),
85
87
  );
86
88
  const wrapper = ({ children }: { children: React.ReactNode }) => (
87
- <SingletonExperimentProvider<State, Config>
88
- id="test"
89
- initialConfig={{ width: 100, bg: '#000' }}
90
- initialState={{ zoom: 1 }}
91
- storage={storage}
92
- storageKey="test"
93
- >
94
- {children}
95
- </SingletonExperimentProvider>
89
+ <Provider backing={backing}>{children}</Provider>
96
90
  );
97
91
  const { result } = renderHook(() => useTrialState<State, Config>(), { wrapper });
98
- expect(result.current.config).toEqual({ width: 999, bg: '#fff' });
92
+ await waitFor(() => expect(result.current?.config).toEqual({ width: 999, bg: '#fff' }));
99
93
  expect(result.current.state).toEqual({ zoom: 2 });
100
94
  });
101
95
  });
@@ -1,7 +1,10 @@
1
- import { type ReactNode, useRef } from 'react';
1
+ import type { ReactNode } from 'react';
2
+ import { defaultStorage } from './adapters';
2
3
  import { LabStoreProvider, TrialIdProvider } from './context';
3
- import { createLabStore, type LabStore } from './store';
4
+ import { openLabStore } from './openLabStore';
5
+ import { PersistenceContext } from './Persistence';
4
6
  import type { StorageAdapter } from './types';
7
+ import { useOpenOnce, useWarnIgnoredChange } from './useOpenOnce';
5
8
 
6
9
  const SINGLETON_INSTRUMENT = '__singleton__';
7
10
 
@@ -12,8 +15,11 @@ export interface SingletonExperimentProviderProps<TS, TC> {
12
15
  id: string;
13
16
  initialConfig: TC;
14
17
  initialState: TS;
15
- storage: StorageAdapter;
16
18
  storageKey: string;
19
+ /** Default: IndexedDB, or localStorage where IndexedDB will not open. */
20
+ storage?: StorageAdapter;
21
+ /** Rendered until the stored experiment has loaded. Default: nothing. */
22
+ fallback?: ReactNode;
17
23
  children: ReactNode;
18
24
  }
19
25
 
@@ -21,7 +27,8 @@ export interface SingletonExperimentProviderProps<TS, TC> {
21
27
  * One-trial `<Lab>` substitute for single-screen experiments. Mounts
22
28
  * a `LabStoreProvider` + `TrialIdProvider` with one synthetic
23
29
  * trial, so `useTrialState` works without going through the
24
- * full `<Lab instruments={...}>` runtime.
30
+ * full `<Lab instruments={...}>` runtime. `storageKey` and `storage` are read
31
+ * once, at mount.
25
32
  */
26
33
  export function SingletonExperimentProvider<TS, TC>({
27
34
  id,
@@ -29,13 +36,14 @@ export function SingletonExperimentProvider<TS, TC>({
29
36
  initialState,
30
37
  storage,
31
38
  storageKey,
39
+ fallback = null,
32
40
  children,
33
41
  }: SingletonExperimentProviderProps<TS, TC>) {
34
- const storeRef = useRef<LabStore | null>(null);
35
- if (storeRef.current === null) {
36
- const store = createLabStore({ storageKey, storage });
37
- if (!store.getState().trials.some((w) => w.id === id)) {
38
- store.getState().addTrial({
42
+ useWarnIgnoredChange('<SingletonExperimentProvider>', { storageKey, storage });
43
+ const opened = useOpenOnce(async () => {
44
+ const lab = await openLabStore({ storageKey, storage: storage ?? (await defaultStorage()) });
45
+ if (!lab.store.getState().trials.some((w) => w.id === id)) {
46
+ lab.store.getState().addTrial({
39
47
  id,
40
48
  instrumentName: SINGLETON_INSTRUMENT,
41
49
  config: initialConfig,
@@ -43,11 +51,14 @@ export function SingletonExperimentProvider<TS, TC>({
43
51
  view: { zoom: 1, pan: { x: 0, y: 0 } },
44
52
  });
45
53
  }
46
- storeRef.current = store;
47
- }
54
+ return lab;
55
+ });
56
+ if (!opened) return <>{fallback}</>;
48
57
  return (
49
- <LabStoreProvider store={storeRef.current}>
50
- <TrialIdProvider trialId={id}>{children}</TrialIdProvider>
58
+ <LabStoreProvider store={opened.store}>
59
+ <PersistenceContext.Provider value={opened.records}>
60
+ <TrialIdProvider trialId={id}>{children}</TrialIdProvider>
61
+ </PersistenceContext.Provider>
51
62
  </LabStoreProvider>
52
63
  );
53
64
  }
@@ -0,0 +1,116 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import type { StorageAdapter, StorageChange } from './types';
3
+
4
+ /** How the contract suite drives one adapter. */
5
+ export interface AdapterHarness {
6
+ adapter: StorageAdapter;
7
+ /** Whether a `Uint8Array` survives the round trip unchanged. */
8
+ binary: boolean;
9
+ /** Make a change the way another writer would, or omit when the adapter
10
+ * has no `subscribe`. */
11
+ foreign?: {
12
+ set(key: string, value: unknown): Promise<void> | void;
13
+ delete(key: string): Promise<void> | void;
14
+ };
15
+ }
16
+
17
+ async function until(check: () => boolean, ms = 1000): Promise<void> {
18
+ const end = Date.now() + ms;
19
+ while (!check()) {
20
+ if (Date.now() > end) throw new Error('timed out waiting for a change');
21
+ await new Promise((r) => setTimeout(r, 5));
22
+ }
23
+ }
24
+
25
+ const settle = (): Promise<void> => new Promise((r) => setTimeout(r, 50));
26
+
27
+ /** Every shipped adapter answers to these. `setup` runs once per test. */
28
+ export function describeAdapterContract(name: string, setup: () => AdapterHarness): void {
29
+ describe(`${name} — the adapter contract`, () => {
30
+ it('reads back what it stored, as a copy', async () => {
31
+ const { adapter } = setup();
32
+ const value = { trial: 'a', nested: { n: 1, list: [1, 'two', null] } };
33
+ await adapter.set('lk:x:one', value);
34
+ value.nested.n = 99;
35
+ expect(await adapter.get('lk:x:one')).toEqual({
36
+ trial: 'a',
37
+ nested: { n: 1, list: [1, 'two', null] },
38
+ });
39
+ });
40
+
41
+ it('answers undefined for a key it never held', async () => {
42
+ const { adapter } = setup();
43
+ expect(await adapter.get('lk:x:absent')).toBeUndefined();
44
+ });
45
+
46
+ it('lists only the keys under a prefix', async () => {
47
+ const { adapter } = setup();
48
+ await adapter.set('lk:x:a', 1);
49
+ await adapter.set('lk:x:b', 2);
50
+ await adapter.set('lk:y:a', 3);
51
+ const listed = await adapter.list('lk:x:');
52
+ expect(new Map(listed)).toEqual(
53
+ new Map<string, unknown>([
54
+ ['lk:x:a', 1],
55
+ ['lk:x:b', 2],
56
+ ]),
57
+ );
58
+ });
59
+
60
+ it('deletes a key', async () => {
61
+ const { adapter } = setup();
62
+ await adapter.set('lk:x:gone', { a: 1 });
63
+ await adapter.delete('lk:x:gone');
64
+ expect(await adapter.get('lk:x:gone')).toBeUndefined();
65
+ expect(await adapter.list('lk:x:')).toEqual([]);
66
+ });
67
+
68
+ it('keeps binary values exactly when it says it can', async () => {
69
+ const { adapter, binary } = setup();
70
+ if (!binary) return;
71
+ await adapter.set('lk:x:bytes', new Uint8Array([1, 2, 255]));
72
+ const back = await adapter.get('lk:x:bytes');
73
+ // Not `toBeInstanceOf`: under jsdom, structuredClone hands back Node's
74
+ // Uint8Array, which is not the test realm's.
75
+ expect(Object.prototype.toString.call(back)).toBe('[object Uint8Array]');
76
+ expect([...(back as Uint8Array)]).toEqual([1, 2, 255]);
77
+ });
78
+
79
+ it("reports another writer's changes under its prefix, and nothing else", async () => {
80
+ const { adapter, foreign } = setup();
81
+ if (!foreign) {
82
+ expect(adapter.subscribe).toBeUndefined();
83
+ return;
84
+ }
85
+ if (!adapter.subscribe) throw new Error(`${name} has a foreign writer but no subscribe`);
86
+ const heard: StorageChange[] = [];
87
+ const off = adapter.subscribe('lk:x:', (changes) => heard.push(...changes));
88
+ try {
89
+ await adapter.set('lk:x:own', 'mine');
90
+ await foreign.set('lk:y:elsewhere', 'not this prefix');
91
+ await settle();
92
+ expect(heard).toEqual([]);
93
+
94
+ await foreign.set('lk:x:theirs', { from: 'peer' });
95
+ await until(() => heard.length > 0);
96
+ expect(heard).toEqual([['lk:x:theirs', { from: 'peer' }]]);
97
+
98
+ await foreign.delete('lk:x:theirs');
99
+ await until(() => heard.length > 1);
100
+ expect(heard[1]).toEqual(['lk:x:theirs', undefined]);
101
+ } finally {
102
+ off();
103
+ }
104
+ });
105
+
106
+ it('stops reporting once unsubscribed', async () => {
107
+ const { adapter, foreign } = setup();
108
+ if (!foreign || !adapter.subscribe) return;
109
+ const heard: StorageChange[] = [];
110
+ adapter.subscribe('lk:x:', (changes) => heard.push(...changes))();
111
+ await foreign.set('lk:x:late', 1);
112
+ await settle();
113
+ expect(heard).toEqual([]);
114
+ });
115
+ });
116
+ }