@weasel-js/labkit 0.1.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 (217) hide show
  1. package/README.md +72 -0
  2. package/dist/_dts/fitViewToBounds-rWrBI4a6.d.ts +870 -0
  3. package/dist/_dts/index-C6Yze7sQ.d.ts +93 -0
  4. package/dist/_dts/types-Si4Fw-1F.d.ts +48 -0
  5. package/dist/_dts/useExperimentState-eSvpwV_P.d.ts +102 -0
  6. package/dist/canvas/index.d.ts +34 -0
  7. package/dist/canvas/index.js +4 -0
  8. package/dist/canvas/index.js.map +1 -0
  9. package/dist/chunk-2QNYYL3V.js +86 -0
  10. package/dist/chunk-2QNYYL3V.js.map +1 -0
  11. package/dist/chunk-54IQ2DX7.js +222 -0
  12. package/dist/chunk-54IQ2DX7.js.map +1 -0
  13. package/dist/chunk-6FO7G5BB.js +6095 -0
  14. package/dist/chunk-6FO7G5BB.js.map +1 -0
  15. package/dist/chunk-7BKDG73Z.js +54 -0
  16. package/dist/chunk-7BKDG73Z.js.map +1 -0
  17. package/dist/chunk-B5ZUYRKN.js +23330 -0
  18. package/dist/chunk-B5ZUYRKN.js.map +1 -0
  19. package/dist/chunk-HXZHVU4G.js +126 -0
  20. package/dist/chunk-HXZHVU4G.js.map +1 -0
  21. package/dist/chunk-PWC7AQZM.js +8 -0
  22. package/dist/chunk-PWC7AQZM.js.map +1 -0
  23. package/dist/chunk-SD3HDXR7.js +161 -0
  24. package/dist/chunk-SD3HDXR7.js.map +1 -0
  25. package/dist/chunk-SSMHPMDV.js +350 -0
  26. package/dist/chunk-SSMHPMDV.js.map +1 -0
  27. package/dist/chunk-VLAHRJOC.js +201 -0
  28. package/dist/chunk-VLAHRJOC.js.map +1 -0
  29. package/dist/controls/index.d.ts +13 -0
  30. package/dist/controls/index.js +3 -0
  31. package/dist/controls/index.js.map +1 -0
  32. package/dist/dragdrop/index.d.ts +3 -0
  33. package/dist/dragdrop/index.js +3 -0
  34. package/dist/dragdrop/index.js.map +1 -0
  35. package/dist/fonts/oswald-latin-variable.woff2 +0 -0
  36. package/dist/index.d.ts +410 -0
  37. package/dist/index.js +1425 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/layers/index.d.ts +17 -0
  40. package/dist/layers/index.js +3 -0
  41. package/dist/layers/index.js.map +1 -0
  42. package/dist/passthrough/weasel-canvas.d.ts +258 -0
  43. package/dist/passthrough/weasel-canvas.js +3 -0
  44. package/dist/passthrough/weasel-canvas.js.map +1 -0
  45. package/dist/passthrough/weasel-ui.d.ts +2826 -0
  46. package/dist/passthrough/weasel-ui.js +4 -0
  47. package/dist/passthrough/weasel-ui.js.map +1 -0
  48. package/dist/primitives/index.d.ts +57 -0
  49. package/dist/primitives/index.js +4 -0
  50. package/dist/primitives/index.js.map +1 -0
  51. package/dist/state/index.d.ts +33 -0
  52. package/dist/state/index.js +34 -0
  53. package/dist/state/index.js.map +1 -0
  54. package/dist/styles.css +1224 -0
  55. package/dist/theme-interstellar.css +25 -0
  56. package/dist/theme-light.css +13 -0
  57. package/dist/ui/layers/index.d.ts +42 -0
  58. package/dist/ui/layers/index.js +5 -0
  59. package/dist/ui/layers/index.js.map +1 -0
  60. package/dist/undo/index.d.ts +30 -0
  61. package/dist/undo/index.js +3 -0
  62. package/dist/undo/index.js.map +1 -0
  63. package/package.json +99 -0
  64. package/src/canvas/AGENTS.md +72 -0
  65. package/src/canvas/CanvasStack.less +22 -0
  66. package/src/canvas/CanvasStack.stories.tsx +63 -0
  67. package/src/canvas/CanvasStack.test.tsx +82 -0
  68. package/src/canvas/CanvasStack.tsx +108 -0
  69. package/src/canvas/CanvasStackContext.ts +8 -0
  70. package/src/canvas/canvasCoords.test.ts +30 -0
  71. package/src/canvas/canvasCoords.ts +15 -0
  72. package/src/canvas/index.ts +6 -0
  73. package/src/canvas/useLayerScheduler.ts +72 -0
  74. package/src/canvas/usePanZoom.ts +98 -0
  75. package/src/controls/ControlPanel.less +61 -0
  76. package/src/controls/ControlPanel.stories.tsx +77 -0
  77. package/src/controls/ControlPanel.test.tsx +149 -0
  78. package/src/controls/ControlPanel.tsx +249 -0
  79. package/src/controls/index.ts +12 -0
  80. package/src/controls/types.ts +61 -0
  81. package/src/dragdrop/DragDropRuntime.tsx +135 -0
  82. package/src/dragdrop/DragGhost.less +17 -0
  83. package/src/dragdrop/DragGhost.tsx +24 -0
  84. package/src/dragdrop/Palette.less +34 -0
  85. package/src/dragdrop/Palette.tsx +27 -0
  86. package/src/dragdrop/dragDrop.test.tsx +145 -0
  87. package/src/dragdrop/index.ts +1 -0
  88. package/src/fonts/oswald-latin-variable.woff2 +0 -0
  89. package/src/index.ts +70 -0
  90. package/src/instrument/SineWave.smoke.test.tsx +94 -0
  91. package/src/instrument/capabilityDetector.test.ts +64 -0
  92. package/src/instrument/capabilityDetector.ts +17 -0
  93. package/src/instrument/defineInstrument.test.ts +27 -0
  94. package/src/instrument/defineInstrument.ts +5 -0
  95. package/src/instrument/index.ts +19 -0
  96. package/src/instrument/types.ts +65 -0
  97. package/src/instrument/validateConfigSchema.test.ts +125 -0
  98. package/src/instrument/validateConfigSchema.ts +65 -0
  99. package/src/lab/Lab.less +3 -0
  100. package/src/lab/Lab.stories.tsx +51 -0
  101. package/src/lab/Lab.test.tsx +126 -0
  102. package/src/lab/Lab.tsx +196 -0
  103. package/src/lab/LabContext.test.ts +11 -0
  104. package/src/lab/LabContext.ts +28 -0
  105. package/src/lab/LabShell.less +45 -0
  106. package/src/lab/LabShell.stories.tsx +39 -0
  107. package/src/lab/LabShell.test.tsx +59 -0
  108. package/src/lab/LabShell.tsx +33 -0
  109. package/src/lab/WorkspaceGrid.less +8 -0
  110. package/src/lab/WorkspaceGrid.stories.tsx +61 -0
  111. package/src/lab/WorkspaceGrid.test.tsx +40 -0
  112. package/src/lab/WorkspaceGrid.tsx +20 -0
  113. package/src/lab/gridDims.test.ts +35 -0
  114. package/src/lab/gridDims.ts +11 -0
  115. package/src/lab/index.ts +10 -0
  116. package/src/layers/AGENTS.md +65 -0
  117. package/src/layers/LayerList.less +53 -0
  118. package/src/layers/LayerList.test.tsx +49 -0
  119. package/src/layers/LayerList.tsx +105 -0
  120. package/src/layers/index.ts +3 -0
  121. package/src/passthrough/weasel-canvas.test.ts +30 -0
  122. package/src/passthrough/weasel-canvas.ts +23 -0
  123. package/src/passthrough/weasel-ui.test.ts +79 -0
  124. package/src/passthrough/weasel-ui.ts +150 -0
  125. package/src/primitives/FpsMeter.less +14 -0
  126. package/src/primitives/FpsMeter.stories.tsx +14 -0
  127. package/src/primitives/FpsMeter.test.tsx +38 -0
  128. package/src/primitives/FpsMeter.tsx +36 -0
  129. package/src/primitives/ScaleIndicator.less +25 -0
  130. package/src/primitives/ScaleIndicator.stories.tsx +16 -0
  131. package/src/primitives/ScaleIndicator.test.tsx +46 -0
  132. package/src/primitives/ScaleIndicator.tsx +48 -0
  133. package/src/primitives/Sidebar.less +57 -0
  134. package/src/primitives/Sidebar.stories.tsx +38 -0
  135. package/src/primitives/Sidebar.test.tsx +74 -0
  136. package/src/primitives/Sidebar.tsx +32 -0
  137. package/src/primitives/StatusBar.less +21 -0
  138. package/src/primitives/StatusBar.stories.tsx +24 -0
  139. package/src/primitives/StatusBar.test.tsx +25 -0
  140. package/src/primitives/StatusBar.tsx +18 -0
  141. package/src/primitives/Toolbar.less +43 -0
  142. package/src/primitives/Toolbar.stories.tsx +36 -0
  143. package/src/primitives/Toolbar.test.tsx +65 -0
  144. package/src/primitives/Toolbar.tsx +44 -0
  145. package/src/primitives/fpsAverage.test.ts +21 -0
  146. package/src/primitives/fpsAverage.ts +5 -0
  147. package/src/primitives/index.ts +9 -0
  148. package/src/state/SingletonExperiment.test.tsx +101 -0
  149. package/src/state/SingletonExperiment.tsx +52 -0
  150. package/src/state/adapters.test.ts +94 -0
  151. package/src/state/adapters.ts +102 -0
  152. package/src/state/context.tsx +42 -0
  153. package/src/state/helpers.test.ts +89 -0
  154. package/src/state/helpers.ts +61 -0
  155. package/src/state/index.ts +40 -0
  156. package/src/state/store.test.ts +243 -0
  157. package/src/state/store.ts +225 -0
  158. package/src/state/types.ts +53 -0
  159. package/src/state/useExperimentState.test.tsx +102 -0
  160. package/src/state/useExperimentState.ts +28 -0
  161. package/src/styles.less +20 -0
  162. package/src/test-setup.ts +17 -0
  163. package/src/theme/Interstellar.stories.less +92 -0
  164. package/src/theme/Interstellar.stories.tsx +243 -0
  165. package/src/theme/base.less +122 -0
  166. package/src/theme/interstellar.less +34 -0
  167. package/src/theme/light.less +14 -0
  168. package/src/theme/tokens.less +85 -0
  169. package/src/ui/format.ts +19 -0
  170. package/src/ui/layers/LayerStack.less +143 -0
  171. package/src/ui/layers/LayerStack.stories.tsx +45 -0
  172. package/src/ui/layers/LayerStack.test.tsx +170 -0
  173. package/src/ui/layers/LayerStack.tsx +215 -0
  174. package/src/ui/layers/index.ts +1 -0
  175. package/src/ui/properties/CheckboxRow.stories.tsx +27 -0
  176. package/src/ui/properties/ColorRow.stories.tsx +106 -0
  177. package/src/ui/properties/CurveField.less +48 -0
  178. package/src/ui/properties/CurveField.stories.tsx +20 -0
  179. package/src/ui/properties/CurveField.test.tsx +127 -0
  180. package/src/ui/properties/CurveField.tsx +181 -0
  181. package/src/ui/properties/EffectCard.tsx +312 -0
  182. package/src/ui/properties/Gallery.stories.tsx +178 -0
  183. package/src/ui/properties/NumberRow.stories.tsx +65 -0
  184. package/src/ui/properties/PropertyGroup.less +50 -0
  185. package/src/ui/properties/PropertyGroup.stories.tsx +34 -0
  186. package/src/ui/properties/PropertyGroup.test.tsx +33 -0
  187. package/src/ui/properties/PropertyGroup.tsx +44 -0
  188. package/src/ui/properties/PropertyList.stories.tsx +83 -0
  189. package/src/ui/properties/PropertyPanel.less +592 -0
  190. package/src/ui/properties/PropertyPanel.stories.tsx +191 -0
  191. package/src/ui/properties/PropertyPanel.test.tsx +193 -0
  192. package/src/ui/properties/PropertyPanel.tsx +441 -0
  193. package/src/ui/properties/PropertyRow.stories.tsx +53 -0
  194. package/src/ui/properties/SelectRow.stories.tsx +58 -0
  195. package/src/ui/properties/SliderRow.stories.tsx +74 -0
  196. package/src/ui/properties/SpeechBalloonPanels.stories.tsx +396 -0
  197. package/src/ui/properties/TextRow.stories.tsx +62 -0
  198. package/src/ui/properties/ToggleRow.stories.tsx +57 -0
  199. package/src/ui/properties/index.ts +39 -0
  200. package/src/ui/properties/storyLayouts.tsx +36 -0
  201. package/src/undo/eventBus.test.ts +49 -0
  202. package/src/undo/eventBus.ts +32 -0
  203. package/src/undo/index.ts +5 -0
  204. package/src/undo/undoStack.test.ts +70 -0
  205. package/src/undo/undoStack.ts +38 -0
  206. package/src/workspace/DefaultSidebar.tsx +26 -0
  207. package/src/workspace/DefaultStatusBar.tsx +15 -0
  208. package/src/workspace/DefaultToolbar.tsx +88 -0
  209. package/src/workspace/Workspace.less +58 -0
  210. package/src/workspace/Workspace.stories.tsx +78 -0
  211. package/src/workspace/Workspace.test.tsx +186 -0
  212. package/src/workspace/Workspace.tsx +255 -0
  213. package/src/workspace/WorkspaceChrome.tsx +150 -0
  214. package/src/workspace/index.ts +24 -0
  215. package/src/workspace/slotTypes.ts +44 -0
  216. package/src/workspace/workspaceOps.test.ts +142 -0
  217. package/src/workspace/workspaceOps.ts +78 -0
@@ -0,0 +1,89 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import {
3
+ decodeUrlHash,
4
+ deserializeWorkspaces,
5
+ emptyUndoStack,
6
+ encodeUrlHash,
7
+ labStorageKey,
8
+ serializeWorkspaces,
9
+ } from './helpers';
10
+ import type { WorkspaceRecord } from './types';
11
+
12
+ describe('labStorageKey', () => {
13
+ it('produces namespaced keys', () => {
14
+ expect(labStorageKey('my-lab', 'workspaces')).toBe('lk:my-lab:workspaces');
15
+ expect(labStorageKey('my-lab', 'saves')).toBe('lk:my-lab:saves');
16
+ expect(labStorageKey('my-lab', 'theme')).toBe('lk:my-lab:theme');
17
+ });
18
+ });
19
+
20
+ describe('encodeUrlHash / decodeUrlHash', () => {
21
+ it('round-trips a string', () => {
22
+ const original = JSON.stringify({ workspaces: '[]', saves: '[]' });
23
+ expect(decodeUrlHash(encodeUrlHash(original))).toBe(original);
24
+ });
25
+
26
+ it('returns null for an empty or invalid hash', () => {
27
+ expect(decodeUrlHash('')).toBeNull();
28
+ expect(decodeUrlHash('not-base64!!!')).toBeNull();
29
+ });
30
+ });
31
+
32
+ describe('emptyUndoStack', () => {
33
+ it('returns an empty stack', () => {
34
+ expect(emptyUndoStack()).toEqual({ past: [], future: [] });
35
+ });
36
+ });
37
+
38
+ describe('serializeWorkspaces / deserializeWorkspaces', () => {
39
+ const ws: WorkspaceRecord = {
40
+ id: 'w1',
41
+ instrumentName: 'Test',
42
+ config: { x: 1 },
43
+ state: { items: [] },
44
+ view: { zoom: 1, pan: { x: 0, y: 0 } },
45
+ undoStack: { past: [1, 2], future: [] },
46
+ };
47
+
48
+ it('round-trips workspace records', () => {
49
+ const serialized = serializeWorkspaces([ws], {});
50
+ const [result] = deserializeWorkspaces(serialized, {});
51
+ expect(result?.id).toBe('w1');
52
+ expect(result?.state).toEqual({ items: [] });
53
+ });
54
+
55
+ it('strips undoStack on serialization', () => {
56
+ const serialized = serializeWorkspaces([ws], {});
57
+ const parsed = JSON.parse(serialized) as unknown[];
58
+ expect((parsed[0] as Record<string, unknown>).undoStack).toBeUndefined();
59
+ });
60
+
61
+ it('restores emptyUndoStack after deserialization', () => {
62
+ const serialized = serializeWorkspaces([ws], {});
63
+ const [result] = deserializeWorkspaces(serialized, {});
64
+ expect(result?.undoStack).toEqual({ past: [], future: [] });
65
+ });
66
+
67
+ it('uses instrument.serialize / deserialize when provided', () => {
68
+ const serializers = {
69
+ Test: {
70
+ serialize: (s: unknown) => ({ compressed: true, data: s }),
71
+ deserialize: (d: unknown) => (d as { data: unknown }).data,
72
+ },
73
+ };
74
+ const serialized = serializeWorkspaces([ws], serializers);
75
+ const [result] = deserializeWorkspaces(serialized, serializers);
76
+ expect(result?.state).toEqual({ items: [] });
77
+ });
78
+
79
+ it('falls back to identity when instrumentName not in registry', () => {
80
+ const serialized = serializeWorkspaces([ws], {});
81
+ const [result] = deserializeWorkspaces(serialized, {});
82
+ expect(result?.state).toEqual({ items: [] });
83
+ });
84
+
85
+ it('returns empty array for malformed JSON', () => {
86
+ const result = deserializeWorkspaces('NOT JSON', {});
87
+ expect(result).toEqual([]);
88
+ });
89
+ });
@@ -0,0 +1,61 @@
1
+ import type { InstrumentSerializers, UndoStack, WorkspaceRecord } from './types';
2
+
3
+ export function labStorageKey(
4
+ storageKey: string,
5
+ bucket: 'workspaces' | 'saves' | 'theme',
6
+ ): string {
7
+ return `lk:${storageKey}:${bucket}`;
8
+ }
9
+
10
+ export function encodeUrlHash(value: string): string {
11
+ return btoa(encodeURIComponent(value));
12
+ }
13
+
14
+ export function decodeUrlHash(hash: string): string | null {
15
+ if (!hash) return null;
16
+ try {
17
+ return decodeURIComponent(atob(hash));
18
+ } catch {
19
+ return null;
20
+ }
21
+ }
22
+
23
+ export function emptyUndoStack(): UndoStack {
24
+ return { past: [], future: [] };
25
+ }
26
+
27
+ type SerializedRecord = Omit<WorkspaceRecord, 'undoStack'>;
28
+
29
+ export function serializeWorkspaces(
30
+ workspaces: WorkspaceRecord[],
31
+ serializers: InstrumentSerializers,
32
+ ): string {
33
+ const records: SerializedRecord[] = workspaces.map(({ undoStack: _undo, ...w }) => {
34
+ const s = serializers[w.instrumentName];
35
+ return {
36
+ ...w,
37
+ state: s?.serialize ? s.serialize(w.state) : w.state,
38
+ };
39
+ });
40
+ return JSON.stringify(records);
41
+ }
42
+
43
+ export function deserializeWorkspaces(
44
+ raw: string,
45
+ deserializers: InstrumentSerializers,
46
+ ): WorkspaceRecord[] {
47
+ try {
48
+ const records = JSON.parse(raw) as SerializedRecord[];
49
+ return records.map((r) => {
50
+ const d = deserializers[r.instrumentName];
51
+ return {
52
+ ...r,
53
+ state: d?.deserialize ? d.deserialize(r.state) : r.state,
54
+ undoStack: emptyUndoStack(),
55
+ };
56
+ });
57
+ } catch {
58
+ console.warn('[labkit] deserializeWorkspaces: failed to parse, returning empty list');
59
+ return [];
60
+ }
61
+ }
@@ -0,0 +1,40 @@
1
+ export {
2
+ createMemoryAdapter,
3
+ localStorageAdapter,
4
+ noneAdapter,
5
+ sessionStorageAdapter,
6
+ urlHashAdapter,
7
+ } from './adapters';
8
+ export {
9
+ LabStoreContext,
10
+ LabStoreProvider,
11
+ useLabStore,
12
+ useWorkspaceId,
13
+ WorkspaceIdContext,
14
+ WorkspaceIdProvider,
15
+ } from './context';
16
+ export {
17
+ decodeUrlHash,
18
+ deserializeWorkspaces,
19
+ emptyUndoStack,
20
+ encodeUrlHash,
21
+ labStorageKey,
22
+ serializeWorkspaces,
23
+ } from './helpers';
24
+ export {
25
+ SingletonExperimentProvider,
26
+ type SingletonExperimentProviderProps,
27
+ } from './SingletonExperiment';
28
+ export type { LabStore, LabStoreActions } from './store';
29
+ export { createLabStore } from './store';
30
+ export type {
31
+ CreateLabStoreOptions,
32
+ ExperimentStateHandle,
33
+ InstrumentSerializers,
34
+ LabStoreState,
35
+ SavedSnapshot,
36
+ StorageAdapter,
37
+ UndoStack,
38
+ WorkspaceRecord,
39
+ } from './types';
40
+ export { useExperimentState } from './useExperimentState';
@@ -0,0 +1,243 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createMemoryAdapter } from './adapters';
3
+ import { createLabStore } from './store';
4
+
5
+ function makeStore(overrides?: Partial<Parameters<typeof createLabStore>[0]>) {
6
+ return createLabStore({
7
+ storageKey: 'test',
8
+ storage: createMemoryAdapter(),
9
+ ...overrides,
10
+ });
11
+ }
12
+
13
+ describe('createLabStore — initial state', () => {
14
+ it('starts with empty workspaces and saves', () => {
15
+ const s = makeStore();
16
+ expect(s.getState().workspaces).toEqual([]);
17
+ expect(s.getState().savedSnapshots).toEqual([]);
18
+ });
19
+
20
+ it('uses initialTheme when provided', () => {
21
+ const s = makeStore({ initialTheme: 'light' });
22
+ expect(s.getState().theme).toBe('light');
23
+ });
24
+
25
+ it('defaults theme to auto', () => {
26
+ const s = makeStore();
27
+ expect(s.getState().theme).toBe('auto');
28
+ });
29
+ });
30
+
31
+ describe('addWorkspace', () => {
32
+ it('adds a workspace with an empty undoStack', () => {
33
+ const s = makeStore();
34
+ s.getState().addWorkspace({
35
+ id: 'w1',
36
+ instrumentName: 'Test',
37
+ config: {},
38
+ state: {},
39
+ view: { zoom: 1, pan: { x: 0, y: 0 } },
40
+ });
41
+ expect(s.getState().workspaces).toHaveLength(1);
42
+ expect(s.getState().workspaces[0]?.undoStack).toEqual({ past: [], future: [] });
43
+ });
44
+ });
45
+
46
+ describe('removeWorkspace', () => {
47
+ it('removes by id', () => {
48
+ const s = makeStore();
49
+ s.getState().addWorkspace({
50
+ id: 'w1',
51
+ instrumentName: 'T',
52
+ config: {},
53
+ state: {},
54
+ view: { zoom: 1, pan: { x: 0, y: 0 } },
55
+ });
56
+ s.getState().removeWorkspace('w1');
57
+ expect(s.getState().workspaces).toHaveLength(0);
58
+ });
59
+ });
60
+
61
+ describe('updateWorkspaceState', () => {
62
+ it('updates state with a plain value', () => {
63
+ const s = makeStore();
64
+ s.getState().addWorkspace({
65
+ id: 'w1',
66
+ instrumentName: 'T',
67
+ config: {},
68
+ state: { n: 0 },
69
+ view: { zoom: 1, pan: { x: 0, y: 0 } },
70
+ });
71
+ s.getState().updateWorkspaceState('w1', { n: 42 });
72
+ expect(s.getState().workspaces[0]?.state).toEqual({ n: 42 });
73
+ });
74
+
75
+ it('updates state with an updater function', () => {
76
+ const s = makeStore();
77
+ s.getState().addWorkspace({
78
+ id: 'w1',
79
+ instrumentName: 'T',
80
+ config: {},
81
+ state: { n: 1 },
82
+ view: { zoom: 1, pan: { x: 0, y: 0 } },
83
+ });
84
+ s.getState().updateWorkspaceState('w1', (prev: unknown) => ({
85
+ n: (prev as { n: number }).n + 1,
86
+ }));
87
+ expect((s.getState().workspaces[0]?.state as { n: number }).n).toBe(2);
88
+ });
89
+ });
90
+
91
+ describe('updateWorkspaceConfig', () => {
92
+ it('updates a single config key', () => {
93
+ const s = makeStore();
94
+ s.getState().addWorkspace({
95
+ id: 'w1',
96
+ instrumentName: 'T',
97
+ config: { x: 1, y: 2 },
98
+ state: {},
99
+ view: { zoom: 1, pan: { x: 0, y: 0 } },
100
+ });
101
+ s.getState().updateWorkspaceConfig('w1', 'x' as never, 99 as never);
102
+ expect((s.getState().workspaces[0]?.config as { x: number }).x).toBe(99);
103
+ expect((s.getState().workspaces[0]?.config as { y: number }).y).toBe(2);
104
+ });
105
+ });
106
+
107
+ describe('setTheme', () => {
108
+ it('updates theme', () => {
109
+ const s = makeStore();
110
+ s.getState().setTheme('interstellar');
111
+ expect(s.getState().theme).toBe('interstellar');
112
+ });
113
+ });
114
+
115
+ describe('save/load/delete snapshots', () => {
116
+ it('saveSnapshot creates a snapshot', () => {
117
+ const s = makeStore();
118
+ s.getState().addWorkspace({
119
+ id: 'w1',
120
+ instrumentName: 'T',
121
+ config: { x: 1 },
122
+ state: { n: 5 },
123
+ view: { zoom: 1, pan: { x: 0, y: 0 } },
124
+ });
125
+ s.getState().saveSnapshot('w1', 'my save');
126
+ const snaps = s.getState().savedSnapshots;
127
+ expect(snaps).toHaveLength(1);
128
+ expect(snaps[0]?.name).toBe('my save');
129
+ expect(snaps[0]?.instrumentName).toBe('T');
130
+ });
131
+
132
+ it('loadSnapshot restores state and config', () => {
133
+ const s = makeStore();
134
+ s.getState().addWorkspace({
135
+ id: 'w1',
136
+ instrumentName: 'T',
137
+ config: { x: 1 },
138
+ state: { n: 5 },
139
+ view: { zoom: 1, pan: { x: 0, y: 0 } },
140
+ });
141
+ s.getState().saveSnapshot('w1', 'snap1');
142
+ s.getState().updateWorkspaceState('w1', { n: 99 });
143
+ const snapId = s.getState().savedSnapshots[0]?.id ?? '';
144
+ s.getState().loadSnapshot(snapId, 'w1');
145
+ expect((s.getState().workspaces[0]?.state as { n: number }).n).toBe(5);
146
+ });
147
+
148
+ it('loadSnapshot blocks cross-instrument load', () => {
149
+ const s = makeStore();
150
+ s.getState().addWorkspace({
151
+ id: 'w1',
152
+ instrumentName: 'A',
153
+ config: {},
154
+ state: { n: 1 },
155
+ view: { zoom: 1, pan: { x: 0, y: 0 } },
156
+ });
157
+ s.getState().saveSnapshot('w1', 'snap-a');
158
+ s.getState().setWorkspaceInstrument('w1', 'B');
159
+ const snapId = s.getState().savedSnapshots[0]?.id ?? '';
160
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
161
+ s.getState().loadSnapshot(snapId, 'w1');
162
+ expect(warn).toHaveBeenCalled();
163
+ warn.mockRestore();
164
+ });
165
+
166
+ it('deleteSnapshot removes the snapshot', () => {
167
+ const s = makeStore();
168
+ s.getState().addWorkspace({
169
+ id: 'w1',
170
+ instrumentName: 'T',
171
+ config: {},
172
+ state: {},
173
+ view: { zoom: 1, pan: { x: 0, y: 0 } },
174
+ });
175
+ s.getState().saveSnapshot('w1', 'snap');
176
+ const id = s.getState().savedSnapshots[0]?.id ?? '';
177
+ s.getState().deleteSnapshot(id);
178
+ expect(s.getState().savedSnapshots).toHaveLength(0);
179
+ });
180
+
181
+ it('listSnapshots returns newest first', () => {
182
+ const s = makeStore();
183
+ s.getState().addWorkspace({
184
+ id: 'w1',
185
+ instrumentName: 'T',
186
+ config: {},
187
+ state: {},
188
+ view: { zoom: 1, pan: { x: 0, y: 0 } },
189
+ });
190
+ s.getState().saveSnapshot('w1', 'first');
191
+ s.getState().saveSnapshot('w1', 'second');
192
+ const list = s.getState().listSnapshots('w1');
193
+ expect(list[0]?.name).toBe('second');
194
+ });
195
+ });
196
+
197
+ describe('persistence — hydration', () => {
198
+ it('hydrates workspaces from storage on construction', () => {
199
+ vi.useFakeTimers();
200
+ const mem = createMemoryAdapter();
201
+ const seedStore = createLabStore({ storageKey: 'test', storage: mem });
202
+ seedStore.getState().addWorkspace({
203
+ id: 'w1',
204
+ instrumentName: 'T',
205
+ config: {},
206
+ state: { n: 7 },
207
+ view: { zoom: 1, pan: { x: 0, y: 0 } },
208
+ });
209
+ vi.advanceTimersByTime(500);
210
+ vi.useRealTimers();
211
+
212
+ const hydrated = createLabStore({ storageKey: 'test', storage: mem });
213
+ expect(hydrated.getState().workspaces).toHaveLength(1);
214
+ expect((hydrated.getState().workspaces[0]?.state as { n: number }).n).toBe(7);
215
+ });
216
+ });
217
+
218
+ describe('persistence — debounced writes', () => {
219
+ it('multiple rapid mutations produce one write call', () => {
220
+ vi.useFakeTimers();
221
+ const mem = createMemoryAdapter();
222
+ const writeSpy = vi.spyOn(mem, 'write');
223
+ const s = createLabStore({ storageKey: 'test', storage: mem });
224
+
225
+ s.getState().addWorkspace({
226
+ id: 'w1',
227
+ instrumentName: 'T',
228
+ config: {},
229
+ state: {},
230
+ view: { zoom: 1, pan: { x: 0, y: 0 } },
231
+ });
232
+ s.getState().updateWorkspaceState('w1', { n: 1 });
233
+ s.getState().updateWorkspaceState('w1', { n: 2 });
234
+ s.getState().updateWorkspaceState('w1', { n: 3 });
235
+
236
+ const writesBefore = writeSpy.mock.calls.length;
237
+ vi.advanceTimersByTime(400);
238
+ const writesAfter = writeSpy.mock.calls.length;
239
+
240
+ expect(writesAfter - writesBefore).toBe(3);
241
+ vi.useRealTimers();
242
+ });
243
+ });
@@ -0,0 +1,225 @@
1
+ import { createStore, type StoreApi } from 'zustand/vanilla';
2
+ import {
3
+ deserializeWorkspaces,
4
+ emptyUndoStack,
5
+ labStorageKey,
6
+ serializeWorkspaces,
7
+ } from './helpers';
8
+ import type {
9
+ CreateLabStoreOptions,
10
+ InstrumentSerializers,
11
+ LabStoreState,
12
+ SavedSnapshot,
13
+ WorkspaceRecord,
14
+ } from './types';
15
+
16
+ export interface LabStoreActions {
17
+ addWorkspace: (record: Omit<WorkspaceRecord, 'undoStack'>) => void;
18
+ removeWorkspace: (id: string) => void;
19
+ updateWorkspaceState: <TS>(id: string, next: TS | ((prev: TS) => TS)) => void;
20
+ updateWorkspaceConfig: <TC>(id: string, key: keyof TC, value: TC[keyof TC]) => void;
21
+ updateWorkspaceView: (id: string, view: WorkspaceRecord['view']) => void;
22
+ updateWorkspaceUndoStack: (
23
+ id: string,
24
+ next:
25
+ | WorkspaceRecord['undoStack']
26
+ | ((prev: WorkspaceRecord['undoStack']) => WorkspaceRecord['undoStack']),
27
+ ) => void;
28
+ setWorkspaceInstrument: (id: string, instrumentName: string) => void;
29
+ saveSnapshot: (workspaceId: string, name: string) => void;
30
+ loadSnapshot: (snapshotId: string, workspaceId: string) => void;
31
+ deleteSnapshot: (snapshotId: string) => void;
32
+ listSnapshots: (workspaceId?: string) => SavedSnapshot[];
33
+ setTheme: (theme: 'light' | 'interstellar' | 'auto') => void;
34
+ }
35
+
36
+ export type LabStore = StoreApi<LabStoreState & LabStoreActions> & {
37
+ registerSerializers: (s: InstrumentSerializers) => void;
38
+ };
39
+
40
+ export function createLabStore(options: CreateLabStoreOptions): LabStore {
41
+ let serializers: InstrumentSerializers = {};
42
+ let flushTimer: ReturnType<typeof setTimeout> | null = null;
43
+
44
+ const workspacesRaw = options.storage.read(labStorageKey(options.storageKey, 'workspaces'));
45
+ let hydratedWorkspaces: WorkspaceRecord[] = [];
46
+ if (workspacesRaw) {
47
+ hydratedWorkspaces = deserializeWorkspaces(workspacesRaw, serializers);
48
+ }
49
+
50
+ const savesRaw = options.storage.read(labStorageKey(options.storageKey, 'saves'));
51
+ let hydratedSnapshots: SavedSnapshot[] = [];
52
+ if (savesRaw) {
53
+ try {
54
+ hydratedSnapshots = JSON.parse(savesRaw) as SavedSnapshot[];
55
+ } catch {
56
+ console.warn('[labkit] failed to parse saved snapshots, starting empty');
57
+ hydratedSnapshots = [];
58
+ }
59
+ }
60
+
61
+ const themeRaw = options.storage.read(labStorageKey(options.storageKey, 'theme'));
62
+ let hydratedTheme: 'light' | 'interstellar' | 'auto';
63
+ if (themeRaw === 'light' || themeRaw === 'interstellar' || themeRaw === 'auto') {
64
+ hydratedTheme = themeRaw;
65
+ } else {
66
+ hydratedTheme = options.initialTheme ?? 'auto';
67
+ }
68
+
69
+ const store = createStore<LabStoreState & LabStoreActions>()((set, get) => ({
70
+ workspaces: hydratedWorkspaces,
71
+ savedSnapshots: hydratedSnapshots,
72
+ theme: hydratedTheme,
73
+
74
+ addWorkspace: (record) => {
75
+ set((s) => ({
76
+ workspaces: [...s.workspaces, { ...record, undoStack: emptyUndoStack() }],
77
+ }));
78
+ scheduleFlush();
79
+ },
80
+
81
+ removeWorkspace: (id) => {
82
+ set((s) => ({ workspaces: s.workspaces.filter((w) => w.id !== id) }));
83
+ scheduleFlush();
84
+ },
85
+
86
+ updateWorkspaceState: (id, next) => {
87
+ set((s) => ({
88
+ workspaces: s.workspaces.map((w) => {
89
+ if (w.id !== id) return w;
90
+ const nextState =
91
+ typeof next === 'function' ? (next as (prev: unknown) => unknown)(w.state) : next;
92
+ return { ...w, state: nextState };
93
+ }),
94
+ }));
95
+ scheduleFlush();
96
+ },
97
+
98
+ updateWorkspaceConfig: (id, key, value) => {
99
+ set((s) => ({
100
+ workspaces: s.workspaces.map((w) => {
101
+ if (w.id !== id) return w;
102
+ return {
103
+ ...w,
104
+ config: { ...(w.config as Record<string, unknown>), [key as string]: value },
105
+ };
106
+ }),
107
+ }));
108
+ scheduleFlush();
109
+ },
110
+
111
+ updateWorkspaceView: (id, view) => {
112
+ set((s) => ({
113
+ workspaces: s.workspaces.map((w) => (w.id === id ? { ...w, view } : w)),
114
+ }));
115
+ scheduleFlush();
116
+ },
117
+
118
+ updateWorkspaceUndoStack: (id, next) => {
119
+ set((s) => ({
120
+ workspaces: s.workspaces.map((w) => {
121
+ if (w.id !== id) return w;
122
+ const undoStack =
123
+ typeof next === 'function'
124
+ ? (next as (prev: WorkspaceRecord['undoStack']) => WorkspaceRecord['undoStack'])(
125
+ w.undoStack,
126
+ )
127
+ : next;
128
+ return { ...w, undoStack };
129
+ }),
130
+ }));
131
+ },
132
+
133
+ setWorkspaceInstrument: (id, instrumentName) => {
134
+ set((s) => ({
135
+ workspaces: s.workspaces.map((w) => (w.id === id ? { ...w, instrumentName } : w)),
136
+ }));
137
+ scheduleFlush();
138
+ },
139
+
140
+ saveSnapshot: (workspaceId, name) => {
141
+ const workspace = get().workspaces.find((w) => w.id === workspaceId);
142
+ if (!workspace) return;
143
+ const reg = serializers[workspace.instrumentName];
144
+ const serializedState = reg?.serialize
145
+ ? reg.serialize(workspace.state)
146
+ : structuredClone(workspace.state);
147
+ const clonedConfig = structuredClone(workspace.config);
148
+ const lastAt = get().savedSnapshots.reduce((m, sn) => (sn.savedAt > m ? sn.savedAt : m), 0);
149
+ const savedAt = Math.max(Date.now(), lastAt + 1);
150
+ const snapshot: SavedSnapshot = {
151
+ id: crypto.randomUUID(),
152
+ name,
153
+ workspaceId,
154
+ instrumentName: workspace.instrumentName,
155
+ config: clonedConfig,
156
+ state: serializedState,
157
+ savedAt,
158
+ };
159
+ set((s) => ({ savedSnapshots: [...s.savedSnapshots, snapshot] }));
160
+ scheduleFlush();
161
+ },
162
+
163
+ loadSnapshot: (snapshotId, workspaceId) => {
164
+ const snapshot = get().savedSnapshots.find((sn) => sn.id === snapshotId);
165
+ if (!snapshot) return;
166
+ const workspace = get().workspaces.find((w) => w.id === workspaceId);
167
+ if (!workspace) return;
168
+ if (snapshot.instrumentName !== workspace.instrumentName) {
169
+ console.warn(
170
+ `[labkit] loadSnapshot: instrument mismatch (snapshot=${snapshot.instrumentName}, workspace=${workspace.instrumentName}); refusing to load`,
171
+ );
172
+ return;
173
+ }
174
+ const reg = serializers[snapshot.instrumentName];
175
+ const restoredState = reg?.deserialize ? reg.deserialize(snapshot.state) : snapshot.state;
176
+ set((s) => ({
177
+ workspaces: s.workspaces.map((w) =>
178
+ w.id === workspaceId ? { ...w, state: restoredState, config: snapshot.config } : w,
179
+ ),
180
+ }));
181
+ scheduleFlush();
182
+ },
183
+
184
+ deleteSnapshot: (snapshotId) => {
185
+ set((s) => ({
186
+ savedSnapshots: s.savedSnapshots.filter((sn) => sn.id !== snapshotId),
187
+ }));
188
+ scheduleFlush();
189
+ },
190
+
191
+ listSnapshots: (workspaceId) => {
192
+ const all = get().savedSnapshots;
193
+ const filtered = workspaceId ? all.filter((sn) => sn.workspaceId === workspaceId) : all;
194
+ return [...filtered].sort((a, b) => b.savedAt - a.savedAt);
195
+ },
196
+
197
+ setTheme: (theme) => {
198
+ set({ theme });
199
+ scheduleFlush();
200
+ },
201
+ }));
202
+
203
+ function scheduleFlush(): void {
204
+ if (flushTimer) clearTimeout(flushTimer);
205
+ flushTimer = setTimeout(() => {
206
+ const s = store.getState();
207
+ options.storage.write(
208
+ labStorageKey(options.storageKey, 'workspaces'),
209
+ serializeWorkspaces(s.workspaces, serializers),
210
+ );
211
+ options.storage.write(
212
+ labStorageKey(options.storageKey, 'saves'),
213
+ JSON.stringify(s.savedSnapshots),
214
+ );
215
+ options.storage.write(labStorageKey(options.storageKey, 'theme'), s.theme);
216
+ flushTimer = null;
217
+ }, 300);
218
+ }
219
+
220
+ return Object.assign(store, {
221
+ registerSerializers(s: InstrumentSerializers) {
222
+ serializers = s;
223
+ },
224
+ });
225
+ }