copper3d 4.1.2 → 4.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -491,8 +491,11 @@ nrrdTools.drag({
491
491
 
492
492
  ```typescript
493
493
  nrrdTools.draw({
494
- getMaskData: (sliceData, layerId, channelId, sliceIndex, axis, width, height, clearFlag?) => {
495
- sendSliceToBackend({ sliceData, layerId, channelId, sliceIndex, axis, width, height, clearFlag });
494
+ getMaskData: (sliceData, layerId, channelId, sliceIndex, axis, width, height, clearFlag, history) => {
495
+ // `history` is set only for undo/redo. On those, channelId is the *active* channel,
496
+ // which need not be the one that changed — history.channels is.
497
+ const channels = history ? history.channels : [channelId];
498
+ sendSliceToBackend({ sliceData, layerId, channels, sliceIndex, axis, width, height, clearFlag });
496
499
  },
497
500
  onClearLayerVolume: (layerId) => notifyBackendLayerCleared(layerId),
498
501
  getSphereData: (sphereOrigin, sphereRadius) => sendSphereToBackend({ sphereOrigin, sphereRadius }),
@@ -753,7 +756,8 @@ yourself. It throws on an unknown layer, or a channel outside `[1, 255]`.
753
756
  | **Data** | `reset()` | Reset all volumes, undo histories, canvases, sphere data |
754
757
  | | `clearActiveLayer()` | Clear active layer volume + undo history |
755
758
  | | `clearActiveSlice()` | Clear current slice (undoable) |
756
- | | `clearChannel(id, ch)` | Erase one channel across a whole layer (undoable); throws on unknown layer or channel outside [1, 255] |
759
+ | | `clearChannel(id, ch)` | Erase one channel across a whole layer (undoable); returns a `ChannelClear` handle, or `null` if the channel was empty; throws on unknown layer or channel outside [1, 255] |
760
+ | | `undoChannelClear(clear)` | Reverse that specific clear on its own layer, whatever layer is active; `false` if a later operation sits on it |
757
761
  | | `setAllSlices(slices)` | Load NRRD slices, init MaskVolumes |
758
762
  | | `setMasksFromNIfTI(map, bar?)` | Load saved NIfTI voxel data (grids must be registered first) |
759
763
  | | `registerNiftiMaskGrid(data, dims)` | *(module export)* Record a mask buffer's NIfTI grid for validation |
@@ -849,11 +853,25 @@ interface RGBAColor { r: number; g: number; b: number; a: number; } // 0-255
849
853
 
850
854
  type ChannelColorMap = Record<number, RGBAColor>; // key = channel number, 1-255
851
855
 
856
+ // One channel clear, as clearChannel returns it, for undoChannelClear
857
+ interface ChannelClear {
858
+ readonly layerId: string;
859
+ readonly channel: number;
860
+ readonly entry: UndoEntry; // compared by identity
861
+ }
862
+
863
+ // What an undo or redo changed; getMaskData's last argument, set only for undo/redo
864
+ interface IMaskHistoryChange {
865
+ /** Channels whose voxels the undone or redone delta changed, ascending. */
866
+ channels: number[];
867
+ }
868
+
852
869
  interface IDrawOpts {
853
870
  getMaskData?: (
854
871
  sliceData: Uint8Array, layerId: string, channelId: number,
855
872
  sliceIndex: number, axis: 'x' | 'y' | 'z',
856
- width: number, height: number, clearFlag?: boolean
873
+ width: number, height: number, clearFlag?: boolean,
874
+ history?: IMaskHistoryChange
857
875
  ) => void;
858
876
  onClearLayerVolume?: (layerId: string) => void;
859
877
  getSphereData?: (sphereOrigin: number[], sphereRadius: number) => void;
@@ -99,10 +99,22 @@ All read-only.
99
99
 
100
100
  | Tool | What it does |
101
101
  |---|---|
102
- | `copper3d_search_api` | Search by name, module, summary or parameter type. Members are indexed on their own, so `aiApplyMask` finds `NrrdTools.aiApplyMask` |
103
- | `copper3d_get_symbol` | One symbol in full: signature, every parameter, return type, source location, related guides |
104
- | `copper3d_list_guides` | Table of contents for the hand-written guides |
105
- | `copper3d_get_guide` | Full markdown of one guide |
102
+ | `copper3d_search_api` | Search by name, module, summary or parameter type. Members are indexed on their own, so `aiApplyMask` finds `NrrdTools.aiApplyMask`. Several words are fine (`copperRenderer createScene`) — symbols matching all of them rank first. `limit` (or `max_results`) caps the results |
103
+ | `copper3d_get_symbol` | One symbol in full: signature, every parameter, return type, source location, related guides. On a class or interface, every member with its signature |
104
+ | `copper3d_list_guides` | Table of contents for the hand-written guides, with their sizes |
105
+ | `copper3d_get_guide` | Markdown of one guide. A guide over 20K characters comes back as its **outline**; pass `section` (`"4"`, `"4.2"`, or a title) to read one part |
106
+
107
+ ::: tip A miss is a miss, not proof of absence
108
+ The index holds names, signatures and summaries — not behaviour. When nothing matches, the
109
+ reply says so and points on to the type declarations and guides inside the installed package,
110
+ rather than letting an assistant conclude the API does not exist.
111
+ :::
112
+
113
+ ::: warning Replies stay under 20K characters
114
+ Claude Code refuses larger tool results, saving them to a file and leaving the assistant to
115
+ grep it. That is why a long guide is served as an outline plus sections rather than in one
116
+ piece.
117
+ :::
106
118
 
107
119
  ## Options
108
120
 
@@ -510,7 +510,8 @@ nrrdTools.draw({
510
510
  axis: 'x' | 'y' | 'z', // Current viewing axis
511
511
  width: number, // Slice width in voxels
512
512
  height: number, // Slice height in voxels
513
- clearFlag?: boolean // true if the user cleared the slice
513
+ clearFlag?: boolean, // true if the user cleared the slice
514
+ history?: IMaskHistoryChange // set only for undo/redo — see below
514
515
  ) => {
515
516
  sendSliceToBackend({ sliceData, layerId, channelId, sliceIndex, axis, width, height, clearFlag });
516
517
  },
@@ -552,6 +553,38 @@ nrrdTools.draw({
552
553
  });
553
554
  ```
554
555
 
556
+ ##### `history`: which channels an undo actually touched <Badge type="tip" text="4.1.3" />
557
+
558
+ `getMaskData` fires for undo and redo as well as for strokes. On those, **`channelId` is not
559
+ the channel that changed** — it is whatever channel happens to be active. The `history`
560
+ argument, set only for undo/redo, names the channels the restored delta really touched:
561
+
562
+ ```typescript
563
+ interface IMaskHistoryChange {
564
+ /** Channels whose voxels the undone or redone delta changed, ascending. */
565
+ channels: number[];
566
+ }
567
+ ```
568
+
569
+ ::: warning This matters if you sync per channel
570
+ A backend keyed on `channelId` attributes an undo to the active channel, which may have
571
+ nothing to do with it — undo channel 3's stroke while channel 1 is selected and the change
572
+ lands on channel 1. Branch on `history` instead:
573
+
574
+ ```typescript
575
+ getMaskData: (sliceData, layerId, channelId, sliceIndex, axis, w, h, clearFlag, history) => {
576
+ const channels = history ? history.channels : [channelId];
577
+ sendSliceToBackend({ sliceData, layerId, channels, sliceIndex, axis, w, h, clearFlag });
578
+ },
579
+ ```
580
+
581
+ `history.channels` can hold more than one channel — a single delta may have crossed several —
582
+ and it can be empty if the delta changed only background voxels.
583
+ :::
584
+
585
+ Because a voxel's value *is* its channel in a label volume, the set is computed by comparing
586
+ the slice before and after the delta, with background (`0`) excluded.
587
+
555
588
  #### 5.3 SphereTool — 3D Sphere Placement & Distance Calculator
556
589
 
557
590
  The SphereTool provides unified sphere placement with 4 sphere types controlled by `gui_states.mode.activeSphereType`. The active type determines which origin and color are used. The old separate "Calculator" mode has been merged into SphereTool.
@@ -1067,6 +1100,47 @@ Only slices that actually carry the label are touched, so a small annotation in
1067
1100
  costs one scan and a handful of `getMaskData` callbacks rather than one callback per slice.
1068
1101
  If the channel is empty, nothing is pushed and nothing fires.
1069
1102
 
1103
+ ##### Reversing *that* clear — `undoChannelClear()` <Badge type="tip" text="4.1.4" />
1104
+
1105
+ `undo()` reverses the latest operation on the **active** layer. That is the wrong tool for an
1106
+ "Undo" affordance next to a deleted finding: by the time the user clicks it, the active layer
1107
+ may have moved on, and plain `undo()` would reverse something else entirely.
1108
+
1109
+ `clearChannel` now hands back a handle for exactly that:
1110
+
1111
+ ```typescript
1112
+ const clear = nrrdTools.clearChannel('layer1', 3); // ChannelClear | null
1113
+
1114
+ // …the user switches to layer2, then clicks "Undo delete" on the toast
1115
+ if (clear && nrrdTools.undoChannelClear(clear)) {
1116
+ toast.dismiss(); // finding 3 is back on layer1
1117
+ }
1118
+ ```
1119
+
1120
+ | | |
1121
+ |---|---|
1122
+ | Returns `null` | The channel held nothing, so there is nothing to undo |
1123
+ | `undoChannelClear` → `true` | The clear was reversed, on **its own** layer, whatever layer is active |
1124
+ | `undoChannelClear` → `false` | A later operation is stacked on it on that layer, or it was already undone |
1125
+
1126
+ ::: tip It refuses rather than reaching past newer work
1127
+ A later edit on that layer is newer work, and reversing the clear underneath it would discard
1128
+ that edit silently. So `undoChannelClear` reverses the clear only while it is still that
1129
+ layer's latest operation; otherwise it changes nothing and returns `false`, and `undo()` is
1130
+ the way back — it steps through the stack in order.
1131
+
1132
+ Edits on a **different** layer do not block it; each layer has its own stack.
1133
+ :::
1134
+
1135
+ It is a once-only reversal, and it leaves the clear **redoable** exactly as `Ctrl+Z` does. The
1136
+ restored voxels are reported through `onMaskChanged` with their channels, like any other undo.
1137
+
1138
+ ::: warning It repaints every slice, not just the visible one
1139
+ `undo()` repaints only the slice on screen when it lies on the undone delta's axis. A channel
1140
+ clear spans every slice carrying the label, so this repaints them all — the same work
1141
+ `clearChannel` itself does.
1142
+ :::
1143
+
1070
1144
  ::: warning Errors are thrown, not swallowed
1071
1145
  - Unknown `layerId` → `Error` listing the known layers. It deliberately does **not** go
1072
1146
  through `getVolumeForLayer`, which warns and falls back to the first layer; for a
@@ -1299,6 +1373,17 @@ window.addEventListener('keydown', (e) => {
1299
1373
  | Scroll:Zoom shortcut | `Ctrl+1` |
1300
1374
  | Scroll:Slice shortcut | `Ctrl+2` |
1301
1375
 
1376
+ Undo and redo are taken with `Ctrl` / `Meta` held: `Ctrl+Z`, and `Ctrl+Y` or `Ctrl+Shift+Z`.
1377
+
1378
+ ::: tip Undo and redo now cancel the browser default <Badge type="tip" text="4.1.3" />
1379
+ Both call `preventDefault()`. Without it the browser also ran its own page-level undo, which
1380
+ reverts the last text typed anywhere on the page and moves focus there — so a clinician
1381
+ undoing a stroke could find a form field behind the viewer silently rolled back instead.
1382
+
1383
+ This applies while shortcuts are active. `enterKeyboardConfig()` still suppresses the whole
1384
+ set, so a focused input keeps normal browser undo.
1385
+ :::
1386
+
1302
1387
  ::: warning Sphere mode no longer has a shortcut <Badge type="warning" text="breaking in 3.11.5" />
1303
1388
  The `sphere: "q"` binding is **gone**, and `sphere` has been removed from
1304
1389
  `IKeyBoardSettings`. Sphere mode is now entered only through `setMode("sphere")` — which is
@@ -1865,7 +1950,8 @@ interface IDrawOpts {
1865
1950
  axis: 'x' | 'y' | 'z',
1866
1951
  width: number,
1867
1952
  height: number,
1868
- clearFlag?: boolean
1953
+ clearFlag?: boolean,
1954
+ history?: IMaskHistoryChange // undo/redo only
1869
1955
  ) => void;
1870
1956
  onClearLayerVolume?: (layerId: string) => void;
1871
1957
  getSphereData?: (sphereOrigin: number[], sphereRadius: number) => void;
@@ -1901,6 +1987,19 @@ interface IKeyBoardSettings {
1901
1987
  }
1902
1988
 
1903
1989
  // 3D coordinate (used in sphere position callbacks)
1990
+ // One channel clear, as clearChannel returns it, for undoChannelClear
1991
+ interface ChannelClear {
1992
+ readonly layerId: string;
1993
+ readonly channel: number;
1994
+ readonly entry: UndoEntry; // compared by identity
1995
+ }
1996
+
1997
+ // What an undo or redo changed; passed as getMaskData's last argument
1998
+ interface IMaskHistoryChange {
1999
+ /** Channels whose voxels the undone or redone delta changed, ascending. */
2000
+ channels: number[];
2001
+ }
2002
+
1904
2003
  interface ICommXYZ {
1905
2004
  x: number;
1906
2005
  y: number;
@@ -1939,7 +2038,8 @@ cap it below what the byte allows. Capping it lower is your product's call, not
1939
2038
  | **Data** | `reset()` | Reset all volumes, undo histories, canvases, and sphere data |
1940
2039
  | | `clearActiveLayer()` | Clear annotations and undo history for the *currently active layer* |
1941
2040
  | | `clearActiveSlice()` | Clear annotations exclusively on the *currently viewed slice* of the active layer |
1942
- | | `clearChannel(id, ch)` | Erase one channel across a whole layer, undoably. Throws on an unknown layer or a channel outside [1, 255] |
2041
+ | | `clearChannel(id, ch)` | Erase one channel across a whole layer, undoably. Returns a `ChannelClear` handle, or `null` if the channel was empty. Throws on an unknown layer or a channel outside [1, 255] |
2042
+ | | `undoChannelClear(clear)` | Reverse that specific clear on its own layer, whatever layer is active. `false` if a later operation sits on it, or it was already undone |
1943
2043
  | | `setAllSlices(slices)` | Load NRRD slices, init MaskVolumes |
1944
2044
  | | `setMasksFromNIfTI(map, bar?)` | Load saved NIfTI voxel data (each buffer must be registered via `registerNiftiMaskGrid` first, or it is refused) |
1945
2045
  | | `registerNiftiMaskGrid(data, dims)` | *(module export, not a method)* Record a mask buffer's NIfTI voxel grid so `setMasksFromNIfTI` can validate it |
@@ -118,7 +118,8 @@ protectedData.maskData.volumes = {
118
118
  |--------|-----------|-------------|
119
119
  | `setActiveLayer` | `(layerId: string): void` | Set the active Layer; also updates fillColor/brushColor |
120
120
  | `setActiveChannel` | `(channel: ChannelValue): void` | Set the active Channel (1–`MAX_ENGINE_CHANNEL`); updates brush color |
121
- | `clearChannel` | `(layerId: string, channel: number): void` | Erase one label across a whole layer, undoably. Throws on an unknown layer (deliberately not via `getVolumeForLayer`, whose fallback would erase a different layer) or a channel outside [1, 255] |
121
+ | `clearChannel` | `(layerId, channel): ChannelClear \| null` | Erase one label across a whole layer, undoably. Returns the clear as a handle for `undoChannelClear`, or `null` when the channel held nothing. Throws on an unknown layer (deliberately not via `getVolumeForLayer`, whose fallback would erase a different layer) or a channel outside [1, 255] |
122
+ | `undoChannelClear` | `(clear: ChannelClear): boolean` | Reverse that clear on **its own** layer, whatever layer is active, and only while it is still that layer's latest operation. `false` when a later operation is stacked on it or it was already undone. Repaints every slice, since a clear spans them all |
122
123
  | `setCurrentLayer` | `(): { ctx, canvas } \| null` *(ToolHost)* | The layer canvas drawing should target. **Returns `null`** when the instance has no layers at all — `new NrrdTools(el, { layers: [] })`, a read-only reference viewer. Every caller must skip its work on `null` rather than dereference |
123
124
  | `getLayerVolume` | `(layerId: string): Uint8Array \| null` | A **copy** of the layer's voxel buffer — not the live array, which a caller could mutate with nothing invalidating the slice cache. Delegates to `DrawToolCore.getLayerVolume` |
124
125
  | `replaceLayerVolume` | `(layerId, data, opts?): void` | Replace the whole buffer. `{ undoable: true }` pushes one `VolumeSnapshot`. Does **not** fire `onLayerVolumeReplaced` itself — that fires only on a later undo/redo, when the backend holds the newer volume and must be told to fall back |
@@ -818,12 +819,32 @@ onMaskChanged: (
818
819
  axis: "x" | "y" | "z", // Current axis
819
820
  width: number, // Slice width
820
821
  height: number, // Slice height
821
- clearFlag: boolean // Whether this is a clear operation
822
+ clearFlag: boolean, // Whether this is a clear operation
823
+ history?: IMaskHistoryChange // undo/redo only — see below
822
824
  ) => void
823
825
  ```
824
826
 
825
827
  **Called**: After each completed drawing stroke (mouseup), and after undo/redo.
826
828
 
829
+ #### `history` <Badge type="tip" text="4.1.3" />
830
+
831
+ ```ts
832
+ interface IMaskHistoryChange {
833
+ /** Channels whose voxels the undone or redone delta changed, ascending. */
834
+ channels: number[];
835
+ }
836
+ ```
837
+
838
+ Set **only** on undo/redo. It exists because `channelId` is the *active* channel on those
839
+ calls, which need not be the channel that changed — undoing a channel-3 stroke while channel
840
+ 1 is selected reports `channelId === 1`. A host that syncs per channel must read
841
+ `history.channels` when it is present and fall back to `[channelId]` when it is not.
842
+
843
+ `DrawToolCore.changedChannels(oldSlice, newSlice)` computes it by comparing the slice before
844
+ and after the delta and collecting every differing non-zero label — in a label volume a
845
+ voxel's value *is* its channel, so that set is exactly what the delta touched. It may hold
846
+ several channels, or none if only background changed.
847
+
827
848
  ### 4.2 onLayerVolumeCleared
828
849
 
829
850
  Storage location: `CanvasState.annotationCallbacks.onLayerVolumeCleared`
@@ -1504,6 +1525,48 @@ broke in two different ways for any other id — and `NrrdTools`'s constructor h
1504
1525
  needs to know which layers exist, and `clearAll()` now iterates the maps rather than a fixed
1505
1526
  id list.
1506
1527
 
1528
+ ### Undoing a named entry <Badge type="tip" text="4.1.4" />
1529
+
1530
+ `undo()` always acts on the *active* layer's top entry. Reversing one specific earlier
1531
+ operation — a channel clear the host offered an "Undo" button for — needs to address the entry
1532
+ itself, which is what these add:
1533
+
1534
+ | Member | Does |
1535
+ |--------|------|
1536
+ | `undoOn(layerId)` | Like `undo()`, but on the layer named rather than the active one. The entry moves to that layer's redo stack just the same |
1537
+ | `peek(layerId)` | The entry an undo on that layer *would* take next, left in place |
1538
+ | `entryLayer(entry)` | The layer an entry belongs to — `entry[0].layerId` for a delta group, `entry.layerId` for a volume snapshot |
1539
+
1540
+ ```ts
1541
+ interface ChannelClear {
1542
+ readonly layerId: string;
1543
+ readonly channel: number;
1544
+ /** The undo entry the clear pushed; compared by identity. */
1545
+ readonly entry: UndoEntry;
1546
+ }
1547
+ ```
1548
+
1549
+ `DrawToolCore.undoEntry(entry)` is the guard that makes this safe:
1550
+
1551
+ ```
1552
+ undoEntry(entry)
1553
+ ├─ layerId = entryLayer(entry) → undefined? refuse
1554
+ ├─ undoManager.peek(layerId) !== entry → refuse ◀ a later op is stacked on it
1555
+ ├─ undoManager.undoOn(layerId)
1556
+ └─ applyUndo(entry) → write "before" back, repaint, report
1557
+ ```
1558
+
1559
+ The identity comparison in `peek(layerId) !== entry` is the whole mechanism: it reverses the
1560
+ entry only while it is still the top of its layer's stack. A later edit there is newer work,
1561
+ and silently reversing underneath it would discard that edit — so it refuses and returns
1562
+ `false`, leaving `undo()` to step back through the stack in order. It is also what makes a
1563
+ second call a no-op: after the first, the entry has moved to the redo stack and is no longer
1564
+ the top of the undo stack.
1565
+
1566
+ `applyUndo` was split out of `undoLastPainting` so both paths share one implementation: the
1567
+ write-back, the repaint and the `onMaskChanged` report are identical whichever way the entry
1568
+ was chosen.
1569
+
1507
1570
  **Undo flow:**
1508
1571
 
1509
1572
  ```
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "copper3dVersion": "4.1.2",
4
- "generatedAt": "2026-10-20T08:42:30.496Z",
5
- "symbolCount": 1204,
3
+ "copper3dVersion": "4.1.4",
4
+ "generatedAt": "2026-11-10T07:12:41.579Z",
5
+ "symbolCount": 1207,
6
6
  "guides": [
7
7
  {
8
8
  "id": "4D-MRI-LV-rendering",
@@ -82,7 +82,7 @@
82
82
  "title": "AI Coding Assistants (MCP) <Badge type=\"tip\" text=\"3.11.0\" />",
83
83
  "summary": "copper3d ships a machine-readable index of its own API and guides. Point your AI assistant at it through the [`copper3d-mcp`](https://www.npmjs.com/package/copper3d-mcp) server and it can look up real signatures instead of inventing them.",
84
84
  "lang": "en",
85
- "bytes": 4931
85
+ "bytes": 5813
86
86
  },
87
87
  {
88
88
  "id": "nrrd-tools",
@@ -90,7 +90,7 @@
90
90
  "title": "NrrdTools Usage Guide",
91
91
  "summary": "Copper3D `NrrdTools` — Medical Image Segmentation Annotation Engine",
92
92
  "lang": "en",
93
- "bytes": 82294
93
+ "bytes": 87023
94
94
  },
95
95
  {
96
96
  "id": "on-demand-controls",
@@ -130,7 +130,7 @@
130
130
  "title": "Segmentation Module Documentation",
131
131
  "summary": "⚠️ **Note**: All line number references in this document are from historical versions. After multiple rounds of refactoring (State Management Refactor, NrrdTools God Class Split, inheritance → composition refactor), these references are ou…",
132
132
  "lang": "en",
133
- "bytes": 84465
133
+ "bytes": 87754
134
134
  },
135
135
  {
136
136
  "id": "surface-annotation-api",