@weasel-js/labkit 1.4.1 → 1.4.2

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 (114) hide show
  1. package/README.md +8 -0
  2. package/dist/_dts/{CanvasStackContext-BIRUVVGH.d.ts → CanvasStackContext-kjILVnPj.d.ts} +1 -1
  3. package/dist/_dts/{frac-X7mWgd7y.d.ts → frac-A4R6v4ld.d.ts} +27 -10
  4. package/dist/_dts/{index-FEa1MudK.d.ts → index-CsU9WhjM.d.ts} +89 -29
  5. package/dist/_dts/{types-ChVJJHvk.d.ts → types-BbXpvQa8.d.ts} +20 -1
  6. package/dist/_dts/{useTrialState-Cdm13fvl.d.ts → useTrialState-DKjqpv20.d.ts} +5 -1
  7. package/dist/canvas/index.d.ts +5 -5
  8. package/dist/canvas/index.js +2 -2
  9. package/dist/chrome/index.d.ts +12 -6
  10. package/dist/chrome/index.js +5 -5
  11. package/dist/{chunk-DG2IFMLA.js → chunk-54ZWZ5FQ.js} +127 -100
  12. package/dist/chunk-54ZWZ5FQ.js.map +1 -0
  13. package/dist/{chunk-RLOXQZW3.js → chunk-D5KQ5OY6.js} +3 -3
  14. package/dist/{chunk-RLOXQZW3.js.map → chunk-D5KQ5OY6.js.map} +1 -1
  15. package/dist/{chunk-PP7ZWAMV.js → chunk-FJG4PHTL.js} +3 -3
  16. package/dist/{chunk-PP7ZWAMV.js.map → chunk-FJG4PHTL.js.map} +1 -1
  17. package/dist/chunk-ISSVF5PT.js +7263 -0
  18. package/dist/chunk-ISSVF5PT.js.map +1 -0
  19. package/dist/chunk-NSOVI3AZ.js +170 -0
  20. package/dist/chunk-NSOVI3AZ.js.map +1 -0
  21. package/dist/{chunk-D7QIPGEB.js → chunk-TN7YSJVU.js} +62 -60
  22. package/dist/chunk-TN7YSJVU.js.map +1 -0
  23. package/dist/{chunk-7TRFMIWX.js → chunk-UDXOYZEC.js} +4 -4
  24. package/dist/{chunk-7TRFMIWX.js.map → chunk-UDXOYZEC.js.map} +1 -1
  25. package/dist/{chunk-LJSIUFYD.js → chunk-ULDW42CR.js} +23 -2
  26. package/dist/chunk-ULDW42CR.js.map +1 -0
  27. package/dist/{chunk-MSR7EVS6.js → chunk-UTOEDPNU.js} +5 -5
  28. package/dist/{chunk-MSR7EVS6.js.map → chunk-UTOEDPNU.js.map} +1 -1
  29. package/dist/{chunk-BMQWLKOL.js → chunk-W2FJR5FF.js} +35 -22
  30. package/dist/chunk-W2FJR5FF.js.map +1 -0
  31. package/dist/{chunk-OFCBEZMU.js → chunk-WS6ZRV75.js} +3 -3
  32. package/dist/{chunk-OFCBEZMU.js.map → chunk-WS6ZRV75.js.map} +1 -1
  33. package/dist/{chunk-53AZ2O2N.js → chunk-XKENZTNE.js} +45 -14
  34. package/dist/chunk-XKENZTNE.js.map +1 -0
  35. package/dist/controls/index.d.ts +1 -1
  36. package/dist/controls/index.js +3 -3
  37. package/dist/dragdrop/index.d.ts +5 -5
  38. package/dist/dragdrop/index.js +2 -2
  39. package/dist/index.d.ts +71 -43
  40. package/dist/index.js +146 -113
  41. package/dist/index.js.map +1 -1
  42. package/dist/layers/index.d.ts +23 -8
  43. package/dist/layers/index.js +3 -3
  44. package/dist/loupe/index.d.ts +4 -4
  45. package/dist/loupe/index.js +2 -2
  46. package/dist/passthrough/weasel-canvas.js +1 -1
  47. package/dist/passthrough/weasel-ui.d.ts +84 -3
  48. package/dist/passthrough/weasel-ui.js +2 -2
  49. package/dist/primitives/index.js +4 -4
  50. package/dist/state/index.d.ts +3 -3
  51. package/dist/state/index.js +2 -2
  52. package/dist/styles.css +20 -3
  53. package/dist/surface/index.js +2 -2
  54. package/dist/ui/layers/index.d.ts +22 -9
  55. package/dist/ui/layers/index.js +2 -2
  56. package/dist/undo/index.d.ts +2 -2
  57. package/package.json +7 -7
  58. package/src/annotations/AnnotationTargets.tsx +6 -1
  59. package/src/annotations/Annotations.overlay.test.tsx +2 -0
  60. package/src/annotations/types.ts +4 -1
  61. package/src/canvas/useOrbit.test.ts +7 -3
  62. package/src/canvas/usePanZoom.test.ts +7 -3
  63. package/src/chrome/ChromeRegions.stories.tsx +42 -1
  64. package/src/chrome/builtins.test.ts +4 -0
  65. package/src/chrome/builtins.tsx +18 -0
  66. package/src/chrome/index.ts +1 -1
  67. package/src/chrome/regions/SidebarRegion.tsx +7 -6
  68. package/src/chrome/regions/TitleBarRegion.test.tsx +64 -0
  69. package/src/chrome/regions/TitleBarRegion.tsx +16 -7
  70. package/src/chrome/regions/ToolbarRegion.test.tsx +14 -0
  71. package/src/chrome/regions/ToolbarRegion.tsx +2 -2
  72. package/src/chrome/regions/ViewportRegion.tsx +2 -2
  73. package/src/chrome/regions/regions.test.tsx +45 -1
  74. package/src/chrome/types.ts +21 -3
  75. package/src/controls/ControlPanel.test.tsx +38 -0
  76. package/src/controls/ControlPanel.tsx +51 -6
  77. package/src/dragdrop/DragDropRuntime.tsx +74 -61
  78. package/src/dragdrop/Palette.tsx +4 -3
  79. package/src/dragdrop/dragDrop.test.tsx +35 -12
  80. package/src/index.ts +2 -1
  81. package/src/instrument/types.ts +4 -5
  82. package/src/lab/Lab.test.tsx +7 -0
  83. package/src/lab/Lab.tsx +2 -2
  84. package/src/lab/LabContext.ts +5 -1
  85. package/src/lab/LabShell.less +17 -2
  86. package/src/layers/AGENTS.md +29 -7
  87. package/src/layers/LayerList.less +16 -0
  88. package/src/layers/LayerList.stories.tsx +66 -0
  89. package/src/layers/LayerList.test.tsx +117 -5
  90. package/src/layers/LayerList.tsx +192 -53
  91. package/src/layers/index.ts +1 -1
  92. package/src/passthrough/weasel-ui.ts +5 -0
  93. package/src/primitives/FloatingPanel.test.tsx +8 -3
  94. package/src/state/store.test.ts +78 -0
  95. package/src/state/store.ts +27 -0
  96. package/src/state/types.ts +20 -0
  97. package/src/trial/Trial.less +4 -0
  98. package/src/trial/Trial.targets.test.tsx +96 -0
  99. package/src/trial/Trial.test.tsx +171 -14
  100. package/src/trial/Trial.tsx +4 -1
  101. package/src/trial/TrialChrome.tsx +22 -2
  102. package/src/trial/TrialTitleBar.tsx +7 -3
  103. package/src/trial/index.ts +1 -0
  104. package/src/trial/trialOps.test.ts +49 -1
  105. package/src/trial/trialOps.ts +28 -6
  106. package/dist/chunk-53AZ2O2N.js.map +0 -1
  107. package/dist/chunk-BMQWLKOL.js.map +0 -1
  108. package/dist/chunk-D7QIPGEB.js.map +0 -1
  109. package/dist/chunk-DG2IFMLA.js.map +0 -1
  110. package/dist/chunk-J6SBFZYT.js +0 -7121
  111. package/dist/chunk-J6SBFZYT.js.map +0 -1
  112. package/dist/chunk-LJSIUFYD.js.map +0 -1
  113. package/dist/chunk-MIT3ISW4.js +0 -100
  114. package/dist/chunk-MIT3ISW4.js.map +0 -1
@@ -35,6 +35,10 @@ export interface LabStoreActions {
35
35
  updateTrialConfig: <TC>(id: string, key: keyof TC, value: TC[keyof TC]) => void;
36
36
  updateTrialView: (id: string, view: unknown) => void;
37
37
  updateTrialSidebarWidth: (id: string, width: number) => void;
38
+ /** Retitle a trial. `null` returns it to its instrument's name. */
39
+ setTrialTitle: (id: string, title: string | null) => void;
40
+ /** Fold or unfold one of a trial's sections. */
41
+ setTrialSectionCollapsed: (id: string, key: string, collapsed: boolean) => void;
38
42
  updateTrialAnnotations: (id: string, doc: unknown) => void;
39
43
  updateTrialUndoStack: (
40
44
  id: string,
@@ -146,6 +150,29 @@ export function createLabStore(options: CreateLabStoreOptions): LabStore {
146
150
  scheduleFlush();
147
151
  },
148
152
 
153
+ setTrialTitle: (id, title) => {
154
+ set((s) => ({
155
+ trials: s.trials.map((w) => {
156
+ if (w.id !== id) return w;
157
+ const next = title === null ? undefined : title;
158
+ if ((w.title ?? undefined) === next) return w;
159
+ return { ...w, title: next };
160
+ }),
161
+ }));
162
+ scheduleFlush();
163
+ },
164
+
165
+ setTrialSectionCollapsed: (id, key, collapsed) => {
166
+ set((s) => ({
167
+ trials: s.trials.map((w) => {
168
+ if (w.id !== id) return w;
169
+ if (w.collapsedSections?.[key] === collapsed) return w;
170
+ return { ...w, collapsedSections: { ...w.collapsedSections, [key]: collapsed } };
171
+ }),
172
+ }));
173
+ scheduleFlush();
174
+ },
175
+
149
176
  updateTrialAnnotations: (id, doc) => {
150
177
  set((s) => ({
151
178
  trials: s.trials.map((w) =>
@@ -6,6 +6,15 @@ export interface UndoStack {
6
6
  future: unknown[];
7
7
  }
8
8
 
9
+ /** The trial a per-trial call is coming from. `id` is the id `useTileId`
10
+ * scopes a surface tile under, so a consumer keying its own per-trial
11
+ * registry and labkit's tiles agree on the key. */
12
+ export interface TrialInfo<TV = unknown> {
13
+ id: string;
14
+ /** The trial's view, in whatever shape the instrument keeps it. */
15
+ view: TV;
16
+ }
17
+
9
18
  /** One trial as the store holds it: which instrument it runs, that
10
19
  * instrument's config and state, the camera, and the undo history. */
11
20
  export interface TrialRecord<TS = unknown, TC = unknown, TV = unknown> {
@@ -16,11 +25,22 @@ export interface TrialRecord<TS = unknown, TC = unknown, TV = unknown> {
16
25
  /** Opaque to labkit: persisted, restored on Reset and handed to the instrument,
17
26
  * but never read into. A 3D lab puts an orbit here and keeps all three. */
18
27
  view: TV;
28
+ /** The config `addTrial` opened this trial on, overlaid on the instrument's
29
+ * defaults. Kept so Reset restores the trial's own subject rather than the
30
+ * bare defaults. */
31
+ configSeed?: Partial<TC>;
19
32
  /** This trial's own tool slot. Undefined means it reads the lab's. */
20
33
  activeToolId?: string | null;
21
34
  /** The extent the trial's sidebar was last dragged to, in pixels. Undefined
22
35
  * until someone moves the seam. */
23
36
  sidebarWidth?: number;
37
+ /** What the title bar reads. Undefined — the state a trial opens in, and the
38
+ * one `setTitle(null)` returns it to — means the instrument's name. */
39
+ title?: string | null;
40
+ /** Which of the trial's collapsible sections are folded, keyed as
41
+ * `TrialChromeContext.collapsedSections` describes. A key that is absent
42
+ * takes the section's own default. */
43
+ collapsedSections?: Record<string, boolean>;
24
44
  /** The marks on this trial's annotation targets, as `AnnotationsApi.toJSON`
25
45
  * wrote them. Opaque here, and absent for a trial whose instrument declares
26
46
  * no `annotations` — or declares its own `storage`. Not in `state`, which
@@ -164,10 +164,14 @@
164
164
  }
165
165
  }
166
166
 
167
+ .lk-trial__titlebar-lead,
167
168
  .lk-trial__titlebar-actions {
168
169
  display: inline-flex;
169
170
  align-items: center;
170
171
  gap: 2px;
172
+ }
173
+
174
+ .lk-trial__titlebar-actions {
171
175
  margin-left: auto;
172
176
  }
173
177
 
@@ -0,0 +1,96 @@
1
+ /**
2
+ * `annotations.targets` is declared once per instrument and called once per
3
+ * trial, so everything here runs two trials of one instrument: with a single
4
+ * trial open, a `targets` that ignored the trial it was asked about would look
5
+ * identical.
6
+ */
7
+ import { act, fireEvent, render, screen } from '@testing-library/react';
8
+ import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
9
+ import type { AnnotationTarget } from '../annotations/types';
10
+ import { defineInstrument } from '../instrument/defineInstrument';
11
+ import { Lab } from '../lab/Lab';
12
+ import { LabContext, type LabContextValue } from '../lab/LabContext';
13
+ import type { TrialInfo } from '../state/types';
14
+
15
+ beforeAll(() => {
16
+ HTMLCanvasElement.prototype.getContext = vi.fn(
17
+ () => null,
18
+ ) as unknown as HTMLCanvasElement['getContext'];
19
+ });
20
+
21
+ const asked: TrialInfo[] = [];
22
+
23
+ /** The last thing `targets` was told about `id`. */
24
+ function lastAsk(id: string): TrialInfo {
25
+ const found = [...asked].reverse().find((t) => t.id === id);
26
+ if (!found) throw new Error(`targets was never called for ${id}`);
27
+ return found;
28
+ }
29
+
30
+ const pane: AnnotationTarget = { id: 'pane', ref: { current: null }, content: { w: 200, h: 100 } };
31
+
32
+ const subject = defineInstrument<Record<string, never>, { subject: string }>({
33
+ name: 'Subject',
34
+ defaultConfig: () => ({ subject: 'none' }),
35
+ initialState: () => ({}),
36
+ render: (ctx) => (
37
+ <button
38
+ type="button"
39
+ data-testid={`zoom-${ctx.trial.id}`}
40
+ onClick={() => ctx.trial.setView({ zoom: 3, pan: { x: 0, y: 0 } })}
41
+ >
42
+ zoom
43
+ </button>
44
+ ),
45
+ annotations: {
46
+ targets: (_state, _config, trial) => {
47
+ asked.push({ id: trial.id, view: trial.view });
48
+ return [pane];
49
+ },
50
+ },
51
+ });
52
+
53
+ let labRef: LabContextValue | null = null;
54
+
55
+ function CaptureLab() {
56
+ return (
57
+ <LabContext.Consumer>
58
+ {(value) => {
59
+ if (value) labRef = value;
60
+ return null;
61
+ }}
62
+ </LabContext.Consumer>
63
+ );
64
+ }
65
+
66
+ function mountTwoTrials(): [string, string] {
67
+ render(
68
+ <Lab instruments={[subject]} defaultInstrument="Subject">
69
+ <CaptureLab />
70
+ </Lab>,
71
+ );
72
+ act(() => labRef?.addTrial('Subject'));
73
+ const ids = labRef?.trials.map((t) => t.id) ?? [];
74
+ const [a, b] = ids;
75
+ if (!a || !b) throw new Error('expected two trials');
76
+ return [a, b];
77
+ }
78
+
79
+ describe('annotations.targets', () => {
80
+ beforeEach(() => {
81
+ asked.length = 0;
82
+ labRef = null;
83
+ });
84
+
85
+ it('is told which trial is asking', () => {
86
+ const [a, b] = mountTwoTrials();
87
+ expect(new Set(asked.map((t) => t.id))).toEqual(new Set([a, b]));
88
+ });
89
+
90
+ it("is told that trial's own view, not the other's", () => {
91
+ const [a, b] = mountTwoTrials();
92
+ fireEvent.click(screen.getByTestId(`zoom-${a}`));
93
+ expect(lastAsk(a).view).toEqual({ zoom: 3, pan: { x: 0, y: 0 } });
94
+ expect(lastAsk(b).view).toEqual({ zoom: 1, pan: { x: 0, y: 0 } });
95
+ });
96
+ });
@@ -1,6 +1,8 @@
1
1
  import { fireEvent, render, screen, within } from '@testing-library/react';
2
- import type { ReactNode } from 'react';
2
+ import { type ReactNode, useState } from 'react';
3
3
  import { describe, expect, it, vi } from 'vitest';
4
+ import { useStore } from 'zustand/react';
5
+ import { f } from '../config/builder';
4
6
  import type { Instrument } from '../instrument/types';
5
7
  import { Lab } from '../lab/Lab';
6
8
  import { LabContext, type LabContextValue } from '../lab/LabContext';
@@ -9,6 +11,8 @@ import { createLabStore } from '../state/store';
9
11
  import type { SavedSnapshot, TrialRecord } from '../state/types';
10
12
  import { TrialChrome } from './TrialChrome';
11
13
 
14
+ const Glyph = () => <svg />;
15
+
12
16
  const stubInstrument: Instrument = {
13
17
  name: 'Stub',
14
18
  defaultConfig: () => ({}),
@@ -27,16 +31,32 @@ const stubRecord: TrialRecord = {
27
31
 
28
32
  type ChromeProps = Parameters<typeof TrialChrome>[0];
29
33
 
34
+ /** A store holding the stub trial, as `Trial` would have put it there. Title
35
+ * and section folds live on the record, so a test that outlives one mount
36
+ * keeps its own store and hands it to both. */
37
+ function makeChromeStore() {
38
+ const store = createLabStore({
39
+ storageKey: 'test',
40
+ storage: { read: () => null, write: () => {} },
41
+ });
42
+ const { undoStack: _undo, ...seed } = stubRecord;
43
+ store.getState().addTrial(seed);
44
+ return store;
45
+ }
46
+
30
47
  function ChromeHarness({
31
48
  children,
32
49
  labOverrides,
33
50
  instrument = stubInstrument,
51
+ store: storeProp,
34
52
  ...props
35
- }: { children?: ReactNode; labOverrides?: Partial<LabContextValue> } & Partial<ChromeProps>) {
36
- const store = createLabStore({
37
- storageKey: 'test',
38
- storage: { read: () => null, write: () => {} },
39
- });
53
+ }: {
54
+ children?: ReactNode;
55
+ labOverrides?: Partial<LabContextValue>;
56
+ store?: ReturnType<typeof createLabStore>;
57
+ } & Partial<ChromeProps>) {
58
+ const [ownStore] = useState(makeChromeStore);
59
+ const store = storeProp ?? ownStore;
40
60
  const labCtx: LabContextValue = {
41
61
  instruments: [instrument],
42
62
  trials: [stubRecord],
@@ -56,20 +76,31 @@ function ChromeHarness({
56
76
  return (
57
77
  <LabStoreContext.Provider value={{ store }}>
58
78
  <LabContext.Provider value={labCtx}>
59
- <TrialChrome
60
- trialId="ws-1"
61
- record={stubRecord}
62
- instrument={instrument}
63
- isLastTrial={false}
64
- {...props}
65
- >
79
+ <ChromeFromStore store={store} instrument={instrument} {...props}>
66
80
  {children ?? <div data-testid="content">content</div>}
67
- </TrialChrome>
81
+ </ChromeFromStore>
68
82
  </LabContext.Provider>
69
83
  </LabStoreContext.Provider>
70
84
  );
71
85
  }
72
86
 
87
+ /** Reads the record out of the store the way `Trial` does, so a mutation the
88
+ * chrome writes comes back to it. */
89
+ function ChromeFromStore({
90
+ store,
91
+ children,
92
+ ...props
93
+ }: { store: ReturnType<typeof createLabStore>; children: ReactNode } & Partial<ChromeProps> &
94
+ Pick<ChromeProps, 'instrument'>) {
95
+ const record = useStore(store, (s) => s.trials.find((t) => t.id === 'ws-1'));
96
+ if (!record) throw new Error('no stub trial in the store');
97
+ return (
98
+ <TrialChrome trialId="ws-1" record={record} isLastTrial={false} {...props}>
99
+ {children}
100
+ </TrialChrome>
101
+ );
102
+ }
103
+
73
104
  describe('<TrialChrome>', () => {
74
105
  it('renders children in the content area', () => {
75
106
  render(<ChromeHarness />);
@@ -131,6 +162,49 @@ describe('<TrialChrome>', () => {
131
162
  expect(screen.getByText('ready')).toBeInTheDocument();
132
163
  });
133
164
 
165
+ it('leads the title bar with a contribution that does not set `end`', () => {
166
+ const { container } = render(
167
+ <ChromeHarness
168
+ chrome={[
169
+ {
170
+ id: 'subject',
171
+ region: 'titlebar',
172
+ item: { icon: Glyph, label: 'Pick subject', onActivate: () => {} },
173
+ },
174
+ ]}
175
+ />,
176
+ );
177
+ const titlebar = container.querySelector('.lk-trial__titlebar');
178
+ if (!titlebar) throw new Error('no title bar');
179
+ const lead = screen.getByRole('button', { name: 'Pick subject' });
180
+ const heading = titlebar.querySelector('.lk-trial__title');
181
+ if (!heading) throw new Error('no title');
182
+ expect(titlebar.querySelector('.lk-trial__titlebar-lead')).toContainElement(lead);
183
+ expect(lead.compareDocumentPosition(heading) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
184
+ });
185
+
186
+ it('reads the instrument name until a contribution calls setTitle', () => {
187
+ render(
188
+ <ChromeHarness
189
+ chrome={[
190
+ {
191
+ id: 'rename',
192
+ region: 'titlebar',
193
+ item: {
194
+ icon: Glyph,
195
+ label: 'Rename',
196
+ onActivate: (ctx) => ctx.setTitle('Sprocket 7'),
197
+ },
198
+ },
199
+ ]}
200
+ />,
201
+ );
202
+ expect(screen.getByRole('region', { name: 'Trial Stub' })).toBeInTheDocument();
203
+ fireEvent.click(screen.getByRole('button', { name: 'Rename' }));
204
+ expect(screen.getByText('Sprocket 7')).toBeInTheDocument();
205
+ expect(screen.getByRole('region', { name: 'Trial Sprocket 7' })).toBeInTheDocument();
206
+ });
207
+
134
208
  it('Cmd+S triggers saveSnapshot', () => {
135
209
  const saveSnapshot = vi.fn();
136
210
  render(<ChromeHarness labOverrides={{ saveSnapshot }} />);
@@ -168,3 +242,86 @@ describe('chrome regions in a mounted lab', () => {
168
242
  expect(document.querySelector('.lk-lab')).toBeTruthy();
169
243
  });
170
244
  });
245
+
246
+ describe('<TrialChrome> — state that outlives a mount', () => {
247
+ const renameChrome: ChromeProps['chrome'] = [
248
+ {
249
+ id: 'rename',
250
+ region: 'titlebar',
251
+ item: {
252
+ icon: Glyph,
253
+ label: 'Rename',
254
+ onActivate: (ctx) => ctx.setTitle('Sprocket 7'),
255
+ },
256
+ },
257
+ ];
258
+
259
+ const sectionChrome: ChromeProps['chrome'] = [
260
+ {
261
+ id: 'notes',
262
+ region: 'sidebar',
263
+ item: { title: 'Notes', body: <p data-testid="notes-body">notes</p> },
264
+ },
265
+ ];
266
+
267
+ it('keeps a title across a remount', () => {
268
+ const store = makeChromeStore();
269
+ const first = render(<ChromeHarness store={store} chrome={renameChrome} />);
270
+ fireEvent.click(screen.getByRole('button', { name: 'Rename' }));
271
+ first.unmount();
272
+
273
+ render(<ChromeHarness store={store} chrome={renameChrome} />);
274
+ expect(screen.getByRole('region', { name: 'Trial Sprocket 7' })).toBeInTheDocument();
275
+ });
276
+
277
+ it('keeps a folded sidebar section across a remount', () => {
278
+ const store = makeChromeStore();
279
+ const first = render(<ChromeHarness store={store} chrome={sectionChrome} />);
280
+ expect(screen.getByTestId('notes-body')).toBeInTheDocument();
281
+ fireEvent.click(screen.getByRole('button', { name: 'Notes' }));
282
+ expect(screen.queryByTestId('notes-body')).toBeNull();
283
+ first.unmount();
284
+
285
+ render(<ChromeHarness store={store} chrome={sectionChrome} />);
286
+ expect(screen.getByRole('button', { name: 'Notes' })).toHaveAttribute('aria-expanded', 'false');
287
+ expect(screen.queryByTestId('notes-body')).toBeNull();
288
+ });
289
+
290
+ it('keeps a folded settings group across a remount', () => {
291
+ const sectioned: Instrument = {
292
+ ...stubInstrument,
293
+ config: f.schema({ size: f.number(1).section('Shape') }),
294
+ };
295
+ const store = makeChromeStore();
296
+ const first = render(<ChromeHarness store={store} instrument={sectioned} />);
297
+ const twisty = screen.getByRole('button', { name: 'Shape' });
298
+ expect(twisty).toHaveAttribute('aria-expanded', 'true');
299
+ fireEvent.click(twisty);
300
+ first.unmount();
301
+
302
+ render(<ChromeHarness store={store} instrument={sectioned} />);
303
+ expect(screen.getByRole('button', { name: 'Shape' })).toHaveAttribute('aria-expanded', 'false');
304
+ });
305
+
306
+ it('reopens a section that starts collapsed, and keeps it open across a remount', () => {
307
+ const collapsedChrome: ChromeProps['chrome'] = [
308
+ {
309
+ id: 'notes',
310
+ region: 'sidebar',
311
+ item: {
312
+ title: 'Notes',
313
+ defaultCollapsed: true,
314
+ body: <p data-testid="notes-body">notes</p>,
315
+ },
316
+ },
317
+ ];
318
+ const store = makeChromeStore();
319
+ const first = render(<ChromeHarness store={store} chrome={collapsedChrome} />);
320
+ expect(screen.queryByTestId('notes-body')).toBeNull();
321
+ fireEvent.click(screen.getByRole('button', { name: 'Notes' }));
322
+ first.unmount();
323
+
324
+ render(<ChromeHarness store={store} chrome={collapsedChrome} />);
325
+ expect(screen.getByTestId('notes-body')).toBeInTheDocument();
326
+ });
327
+ });
@@ -130,7 +130,9 @@ function TrialRuntime({ record, instrument, store, isLast, chrome, suppress }: T
130
130
  const annotationsCap = instrument.annotations;
131
131
  const targetsRef = useRef<() => readonly AnnotationTargetInfo[]>(() => []);
132
132
  targetsRef.current = () =>
133
- annotationsCap ? annotationsCap.targets(record.state, record.config) : [];
133
+ annotationsCap
134
+ ? annotationsCap.targets(record.state, record.config, { id: record.id, view: record.view })
135
+ : [];
134
136
 
135
137
  // One store for the trial's lifetime. Marks do not survive a reload yet —
136
138
  // the storage slot is 3d.
@@ -474,6 +476,7 @@ function TrialRuntime({ record, instrument, store, isLast, chrome, suppress }: T
474
476
  capability={annotationsCap}
475
477
  state={record.state}
476
478
  config={record.config}
479
+ trial={{ id: record.id, view: record.view }}
477
480
  annotations={annotations}
478
481
  activeToolId={resolvedToolId}
479
482
  />
@@ -62,6 +62,10 @@ export interface TrialChromeProps {
62
62
 
63
63
  const NO_OP = (): void => {};
64
64
 
65
+ /** One frozen empty map, so a trial that has folded nothing keeps a stable
66
+ * context identity across renders. */
67
+ const NO_SECTIONS: Readonly<Record<string, boolean>> = Object.freeze({});
68
+
65
69
  /** The frame around a running instrument. Builds one chrome context, assembles
66
70
  * the contributions the instrument, the runtime and the lab declare, and hands
67
71
  * each region its slice. */
@@ -85,6 +89,8 @@ export function TrialChrome({
85
89
  if (!storeCtx) throw new Error('[labkit] TrialChrome requires <LabStoreProvider>');
86
90
  const updateTrialView = useStore(storeCtx.store, (s) => s.updateTrialView);
87
91
  const updateTrialSidebarWidth = useStore(storeCtx.store, (s) => s.updateTrialSidebarWidth);
92
+ const setTrialTitle = useStore(storeCtx.store, (s) => s.setTrialTitle);
93
+ const setTrialSectionCollapsed = useStore(storeCtx.store, (s) => s.setTrialSectionCollapsed);
88
94
  const updateTrialConfig = useStore(storeCtx.store, (s) => s.updateTrialConfig);
89
95
  const updateTrialState = useStore(storeCtx.store, (s) => s.updateTrialState);
90
96
  const undockPanelAction = useStore(storeCtx.store, (s) => s.undockPanel);
@@ -104,6 +110,9 @@ export function TrialChrome({
104
110
 
105
111
  const configSchema = useConfigSchema(instrument);
106
112
 
113
+ const title = record.title ?? record.instrumentName;
114
+ const collapsedSections = record.collapsedSections ?? NO_SECTIONS;
115
+
107
116
  const ctx = useMemo<TrialChromeContext>(() => {
108
117
  const setZoom = (z: number): void => {
109
118
  if (!view2d) return;
@@ -112,6 +121,8 @@ export function TrialChrome({
112
121
  return {
113
122
  trialId,
114
123
  instrumentName: record.instrumentName,
124
+ title,
125
+ setTitle: (next) => setTrialTitle(trialId, next),
115
126
  isLastTrial,
116
127
  zoom: view2d ? view2d.zoom : null,
117
128
  setZoom,
@@ -138,6 +149,8 @@ export function TrialChrome({
138
149
  updateTrialState(trialId, nextState as never);
139
150
  }
140
151
  },
152
+ collapsedSections,
153
+ setSectionCollapsed: (key, collapsed) => setTrialSectionCollapsed(trialId, key, collapsed),
141
154
  undockedPanels: undockedIds,
142
155
  undockPanel: (sectionId, as) => undockPanelAction(trialId, sectionId, as),
143
156
  dockPanel: (sectionId) => dockPanelAction(trialId, sectionId),
@@ -155,6 +168,7 @@ export function TrialChrome({
155
168
  record,
156
169
  instrument,
157
170
  lab,
171
+ title,
158
172
  isLastTrial,
159
173
  updateTrialView,
160
174
  updateTrialConfig,
@@ -168,6 +182,9 @@ export function TrialChrome({
168
182
  undockedIds,
169
183
  undockPanelAction,
170
184
  dockPanelAction,
185
+ setTrialTitle,
186
+ setTrialSectionCollapsed,
187
+ collapsedSections,
171
188
  ]);
172
189
 
173
190
  const contributions = useMemo(
@@ -203,11 +220,14 @@ export function TrialChrome({
203
220
  return (
204
221
  <section
205
222
  className="lk-trial"
206
- aria-label={`Trial ${record.instrumentName}`}
223
+ aria-label={`Trial ${title}`}
207
224
  tabIndex={-1}
208
225
  onKeyDown={handleKeyDown}
209
226
  >
210
- <TrialTitleBar title={record.instrumentName}>
227
+ <TrialTitleBar
228
+ title={title}
229
+ lead={<TitleBarRegion placement="lead" contributions={inRegion('titlebar')} ctx={ctx} />}
230
+ >
211
231
  <TitleBarRegion contributions={inRegion('titlebar')} ctx={ctx} />
212
232
  </TrialTitleBar>
213
233
  <div className="lk-trial__toolbar">
@@ -6,15 +6,18 @@ import { useTrialDrag } from './TrialDragContext';
6
6
  /** Props for `<TrialTitleBar>`. */
7
7
  export interface TrialTitleBarProps {
8
8
  title: string;
9
+ /** Rendered at the leading edge, before the title. */
10
+ lead?: ReactNode;
9
11
  children?: ReactNode;
10
12
  }
11
13
 
12
14
  // `useDragHandle` needs a node id and windease's DragProvider, so the draggable
13
15
  // form is a separate component rather than a conditional hook.
14
- function Draggable({ nodeId, title, children }: TrialTitleBarProps & { nodeId: NodeId }) {
16
+ function Draggable({ nodeId, title, lead, children }: TrialTitleBarProps & { nodeId: NodeId }) {
15
17
  const handlers = useDragHandle(nodeId);
16
18
  return (
17
19
  <div className="lk-trial__titlebar lk-trial__titlebar--draggable" {...handlers}>
20
+ {lead}
18
21
  <span className="lk-trial__title">{title}</span>
19
22
  {children}
20
23
  </div>
@@ -24,16 +27,17 @@ function Draggable({ nodeId, title, children }: TrialTitleBarProps & { nodeId: N
24
27
  /** A trial's title bar. When the workspace allows reordering the whole bar is
25
28
  * the drag surface — there is no separate grip, because a window's title bar
26
29
  * is already the thing you expect to drag. */
27
- export function TrialTitleBar({ title, children }: TrialTitleBarProps) {
30
+ export function TrialTitleBar({ title, lead, children }: TrialTitleBarProps) {
28
31
  const drag = useTrialDrag();
29
32
  if (drag)
30
33
  return (
31
- <Draggable nodeId={drag.nodeId} title={title}>
34
+ <Draggable nodeId={drag.nodeId} title={title} lead={lead}>
32
35
  {children}
33
36
  </Draggable>
34
37
  );
35
38
  return (
36
39
  <div className="lk-trial__titlebar">
40
+ {lead}
37
41
  <span className="lk-trial__title">{title}</span>
38
42
  {children}
39
43
  </div>
@@ -4,6 +4,7 @@ export type { TrialBodyProps } from './TrialBody';
4
4
  export { TrialBody } from './TrialBody';
5
5
  export type { TrialChromeProps, UndoBindings } from './TrialChrome';
6
6
  export { TrialChrome } from './TrialChrome';
7
+ export type { AddTrialOptions } from './trialOps';
7
8
  export {
8
9
  addTrial,
9
10
  cloneTrial,
@@ -26,7 +26,23 @@ const counterWithCanvas: Instrument<CounterState, CounterConfig> = {
26
26
  },
27
27
  };
28
28
 
29
- const instruments: Instrument[] = [counter as Instrument, counterWithCanvas as Instrument];
29
+ interface SubjectConfig {
30
+ subject: string;
31
+ zoom: number;
32
+ }
33
+
34
+ const subjectInstrument: Instrument<{ label: string }, SubjectConfig> = {
35
+ name: 'Subject',
36
+ defaultConfig: () => ({ subject: 'none', zoom: 1 }),
37
+ initialState: (config) => ({ label: config.subject.toUpperCase() }),
38
+ render: () => null,
39
+ };
40
+
41
+ const instruments: Instrument[] = [
42
+ counter as Instrument,
43
+ counterWithCanvas as Instrument,
44
+ subjectInstrument as Instrument,
45
+ ];
30
46
 
31
47
  function head<T>(arr: T[]): T {
32
48
  const first = arr[0];
@@ -69,6 +85,28 @@ describe('addTrial', () => {
69
85
  addTrial(arr, instruments, 'Counter');
70
86
  expect(arr).toHaveLength(0);
71
87
  });
88
+
89
+ it('overlays a seed config on the instrument defaults', () => {
90
+ const out = addTrial([], instruments, 'Subject', { config: { subject: 'brick' } });
91
+ expect(out[0]?.config).toEqual({ subject: 'brick', zoom: 1 });
92
+ });
93
+
94
+ it('seeds the config before initialState reads it', () => {
95
+ const out = addTrial([], instruments, 'Subject', { config: { subject: 'brick' } });
96
+ expect(out[0]?.state).toEqual({ label: 'BRICK' });
97
+ });
98
+
99
+ it('gives each trial the seed it was opened with', () => {
100
+ const a = addTrial([], instruments, 'Subject', { config: { subject: 'one' } });
101
+ const b = addTrial(a, instruments, 'Subject', { config: { subject: 'two' } });
102
+ expect(b.map((t) => (t.config as SubjectConfig).subject)).toEqual(['one', 'two']);
103
+ expect(b.map((t) => (t.state as { label: string }).label)).toEqual(['ONE', 'TWO']);
104
+ });
105
+
106
+ it('ignores a seed key whose value is undefined', () => {
107
+ const out = addTrial([], instruments, 'Subject', { config: { subject: undefined } });
108
+ expect(out[0]?.config).toEqual({ subject: 'none', zoom: 1 });
109
+ });
72
110
  });
73
111
 
74
112
  describe('cloneTrial', () => {
@@ -139,6 +177,16 @@ describe('resetTrial', () => {
139
177
  resetTrial(arr, head(arr).id, instruments);
140
178
  expect((arr[0]?.config as CounterConfig).step).toBe(99);
141
179
  });
180
+
181
+ it('restores the seed the trial was opened with, not the bare defaults', () => {
182
+ let arr = addTrial([], instruments, 'Subject', { config: { subject: 'one' } });
183
+ arr = addTrial(arr, instruments, 'Subject', { config: { subject: 'two' } });
184
+ head(arr).config = { subject: 'edited', zoom: 4 } as SubjectConfig;
185
+ const reset = resetTrial(arr, head(arr).id, instruments);
186
+ expect(reset[0]?.config).toEqual({ subject: 'one', zoom: 1 });
187
+ expect(reset[0]?.state).toEqual({ label: 'ONE' });
188
+ expect(reset[1]?.config).toEqual({ subject: 'two', zoom: 1 });
189
+ });
142
190
  });
143
191
 
144
192
  describe('reorderTrials', () => {