@weasel-js/measure 1.19.1 → 2.0.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 (39) hide show
  1. package/README.md +28 -4
  2. package/dist/MeasureReadout/MeasureReadout.d.ts +24 -0
  3. package/dist/MeasureReadout/MeasureReadout.d.ts.map +1 -0
  4. package/dist/MeasureReadout/index.d.ts +3 -0
  5. package/dist/MeasureReadout/index.d.ts.map +1 -0
  6. package/dist/actionIds.d.ts +18 -0
  7. package/dist/actionIds.d.ts.map +1 -0
  8. package/dist/actionParamSchema.d.ts +15 -0
  9. package/dist/actionParamSchema.d.ts.map +1 -0
  10. package/dist/icons.gen.d.ts +3 -0
  11. package/dist/icons.gen.d.ts.map +1 -0
  12. package/dist/index.d.ts +11 -195
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +940 -476
  15. package/dist/index.js.map +1 -1
  16. package/dist/measureActions.d.ts +35 -0
  17. package/dist/measureActions.d.ts.map +1 -0
  18. package/dist/measureCommands.d.ts +12 -0
  19. package/dist/measureCommands.d.ts.map +1 -0
  20. package/dist/measureContribution.d.ts +11 -0
  21. package/dist/measureContribution.d.ts.map +1 -0
  22. package/dist/measureEdits.d.ts +29 -0
  23. package/dist/measureEdits.d.ts.map +1 -0
  24. package/dist/measureHit.d.ts +22 -0
  25. package/dist/measureHit.d.ts.map +1 -0
  26. package/dist/measureLayer.d.ts +15 -0
  27. package/dist/measureLayer.d.ts.map +1 -0
  28. package/dist/measurePainter.d.ts +17 -0
  29. package/dist/measurePainter.d.ts.map +1 -0
  30. package/dist/measurement.d.ts +71 -0
  31. package/dist/measurement.d.ts.map +1 -0
  32. package/dist/measurements.d.ts +39 -0
  33. package/dist/measurements.d.ts.map +1 -0
  34. package/dist/style.css +47 -0
  35. package/dist/toolSets.d.ts +12 -0
  36. package/dist/toolSets.d.ts.map +1 -0
  37. package/dist/useMeasureTool.d.ts +26 -0
  38. package/dist/useMeasureTool.d.ts.map +1 -0
  39. package/package.json +23 -13
package/dist/index.js CHANGED
@@ -1,558 +1,1022 @@
1
- import { toolSet, sceneMagnification, nodeGates, shownLookup, nodesAsShown, isRectPose, nodeShapesOf, defineTool, SNAP_ROLE_MODS, OVERLAY_ROLE_STROKES, SNAP_ROLES, commitOps, spanSnap, SNAP_ANGLE_STEP, snapMods, viewToTransform, transformSelection, unitFrameAt, insertAt, worldToScreen, requiresSelection, reachesLocked, deleteNode, createTransformOp, createSetDataOp } from '@weasel-js/core';
2
- import { rectBetween, pointSegmentDist, polylineFromPoints, pxReach, rectPath } from '@weasel-js/geom';
3
- import { createValueStore } from '@weasel-js/registry';
4
- import { hitPredicate, ANY_MODS } from '@weasel-js/gestures';
5
- import { defineAction, resolveParams, ActionDisabledReason } from '@weasel-js/routing';
6
- import { useMemo } from 'react';
7
- import { useLatest } from '@weasel-js/react';
1
+ import { OVERLAY_ROLE_STROKES, SNAP_ANGLE_STEP, SNAP_ROLES, SNAP_ROLE_MODS, actionItems, commitOps, createSpanSnap, createUnitFrameLookup, defineTool, isRectPose, nodeGates, nodeShapesOf, nodesAsShown, reachesLocked, requiresOperands, sceneMagnification, shownLookup, snapMods, toolSet, useActionsRegistry, viewToTransform, worldToScreen } from "@weasel-js/core";
2
+ import { RAD_TO_DEG, pointSegmentDistance, polylineFromPoints, pxReach, rectBetween, rectPath } from "@weasel-js/geom";
3
+ import { createValueStore } from "@weasel-js/registry";
4
+ import { ANY_MODS, hitPredicate } from "@weasel-js/gestures";
5
+ import { ActionDisabledReason, defineAction, resolveParams } from "@weasel-js/routing";
6
+ import * as coreOps from "@weasel-js/core/ops";
7
+ import { selectionTransformAnswer, transformSelection } from "@weasel-js/editing";
8
+ import { useMemo, useSyncExternalStore } from "react";
9
+ import { useLatest } from "@weasel-js/react";
10
+ import { decimal, qty } from "@weasel-js/quantity";
11
+ import { reasonLabel, useActionStates } from "@weasel-js/ui/components/ActionBar";
12
+ import { ActionButton } from "@weasel-js/ui/components/ActionButton";
13
+ import { jsx, jsxs } from "react/jsx-runtime";
8
14
 
9
15
  // src/measurement.ts
16
+ /** Measure from `start` to `end`, landed in `frames`. */
10
17
  function measureBetween(start, end, frames) {
11
- const dx = end.x - start.x;
12
- const dy = end.y - start.y;
13
- return {
14
- start: { x: start.x, y: start.y },
15
- end: { x: end.x, y: end.y },
16
- dx,
17
- dy,
18
- distance: Math.hypot(dx, dy),
19
- // `|| 0` drops the sign of a negated zero, which would read a leftward line as -π.
20
- angle: dx === 0 && dy === 0 ? 0 : Math.atan2(-dy || 0, dx),
21
- ...frames ? { frames: { start: frames.start, end: frames.end } } : {}
22
- };
23
- }
18
+ const dx = end.x - start.x;
19
+ const dy = end.y - start.y;
20
+ return {
21
+ start: {
22
+ x: start.x,
23
+ y: start.y
24
+ },
25
+ end: {
26
+ x: end.x,
27
+ y: end.y
28
+ },
29
+ dx,
30
+ dy,
31
+ distance: Math.hypot(dx, dy),
32
+ angle: dx === 0 && dy === 0 ? 0 : Math.atan2(-dy || 0, dx),
33
+ ...frames ? { frames: {
34
+ start: frames.start,
35
+ end: frames.end
36
+ } } : {}
37
+ };
38
+ }
39
+ /** How large the frame `frames` share is drawn in world: a measurement's
40
+ * world lengths divided by it are its modeled lengths. 1 without frames. */
24
41
  function measureMagnification(scene, frames) {
25
- if (!frames || frames.start === null || frames.end === null) return 1;
26
- return sceneMagnification(scene, [frames.start, frames.end], { inclusive: true });
42
+ if (!frames || frames.start === null || frames.end === null) return 1;
43
+ return sceneMagnification(scene, [frames.start, frames.end], { inclusive: true });
27
44
  }
45
+ /** The ends `node` measures between, or null when it is not a measurement. */
28
46
  function measureEndsOf(node) {
29
- const m = node?.data?.measure;
30
- if (!m || typeof m !== "object" || !m.start || !m.end) return null;
31
- return m;
47
+ const m = (node?.data)?.measure;
48
+ if (!m || typeof m !== "object" || !m.start || !m.end) return null;
49
+ return m;
32
50
  }
51
+ /** The measurement `node` holds, or null when it is not one. */
33
52
  function measurementOf(node) {
34
- const ends = measureEndsOf(node);
35
- return ends ? measureBetween(ends.start, ends.end, ends.frames) : null;
53
+ const ends = measureEndsOf(node);
54
+ return ends ? measureBetween(ends.start, ends.end, ends.frames) : null;
36
55
  }
56
+ /** The box a measurement's pose holds: its two ends' bounds, which is what
57
+ * culling, area queries, and fitting the view read. */
37
58
  function measurePose(start, end) {
38
- return rectBetween(start.x, start.y, end.x, end.y);
59
+ return rectBetween(start.x, start.y, end.x, end.y);
39
60
  }
61
+ /** A measurement node on `layer`, ready to insert, or to list in a scene's
62
+ * `initial` nodes: typed with that layer and a `RectPose`. */
40
63
  function measureNode(id, layer, start, end, frames) {
41
- const data = { measure: { start: { ...start }, end: { ...end }, ...frames ? { frames: { ...frames } } : {} } };
42
- return { id, kind: "mark", layer, parent: null, pose: measurePose(start, end), data };
43
- }
64
+ const data = { measure: {
65
+ start: { ...start },
66
+ end: { ...end },
67
+ ...frames ? { frames: { ...frames } } : {}
68
+ } };
69
+ return {
70
+ id,
71
+ kind: "mark",
72
+ layer,
73
+ parent: null,
74
+ pose: measurePose(start, end),
75
+ data
76
+ };
77
+ }
78
+ /** `node`'s data and pose with its `which` end moved to `to`, landed in
79
+ * `frame`. Without `frame` the end keeps the one it had. */
44
80
  function withMeasureEnd(node, which, to, frame) {
45
- const ends = measureEndsOf(node);
46
- if (!ends) return null;
47
- const next = { ...ends, [which]: { x: to.x, y: to.y } };
48
- if (frame !== void 0) next.frames = { start: ends.frames?.start ?? null, end: ends.frames?.end ?? null, [which]: frame };
49
- const data = { ...node.data, measure: next };
50
- return { data, pose: measurePose(next.start, next.end) };
81
+ const ends = measureEndsOf(node);
82
+ if (!ends) return null;
83
+ const next = {
84
+ ...ends,
85
+ [which]: {
86
+ x: to.x,
87
+ y: to.y
88
+ }
89
+ };
90
+ if (frame !== void 0) next.frames = {
91
+ start: ends.frames?.start ?? null,
92
+ end: ends.frames?.end ?? null,
93
+ [which]: frame
94
+ };
95
+ return {
96
+ data: {
97
+ ...node.data,
98
+ measure: next
99
+ },
100
+ pose: measurePose(next.start, next.end)
101
+ };
51
102
  }
103
+
104
+ // src/measurements.ts
105
+ /** The measurements on `layer`, none picked and none in progress. */
52
106
  function createMeasurements(options) {
53
- return {
54
- layer: options.layer,
55
- picked: createValueStore(null),
56
- draft: createValueStore(null),
57
- measuring: createValueStore(false)
58
- };
59
- }
107
+ return {
108
+ layer: options.layer,
109
+ picked: createValueStore(null),
110
+ draft: createValueStore(null),
111
+ measuring: createValueStore(false)
112
+ };
113
+ }
114
+ /** The measurement nodes on `ms.layer`, oldest first. */
60
115
  function measureIds(scene, ms) {
61
- return scene.nodesOnLayer(ms.layer).filter((n) => measurementOf(n) !== null).map((n) => n.id);
116
+ return scene.nodesOnLayer(ms.layer).filter((n) => measurementOf(n) !== null).map((n) => n.id);
62
117
  }
118
+ /** The measurement commands act on: the picked one while it is still in the
119
+ * scene, else the newest. A hidden one (`nodeGates`), which nothing draws, is
120
+ * passed over as the hit test passes over it. */
63
121
  function currentMeasureId(scene, ms) {
64
- const picked = ms.picked.get();
65
- if (picked !== null && measurementOf(scene.get(picked)) !== null) return picked;
66
- return measureIds(scene, ms).at(-1) ?? null;
67
- }
68
- function measureAt(scene, ms, p, tolerance) {
69
- const gates = nodeGates(scene);
70
- const shown = shownLookup(scene);
71
- const ids = measureIds(scene, ms).reverse().filter((id) => !gates.hidden(id) && !gates.locked(id));
72
- for (const id of ids) {
73
- const ends = measureEndsOf(shown.get(id));
74
- if (!ends) continue;
75
- for (const part of ["end", "start"]) {
76
- if (Math.hypot(p.x - ends[part].x, p.y - ends[part].y) <= tolerance) return { id, part };
77
- }
78
- }
79
- for (const id of ids) {
80
- const ends = measureEndsOf(shown.get(id));
81
- if (ends && pointSegmentDist(p.x, p.y, ends.start.x, ends.start.y, ends.end.x, ends.end.y) <= tolerance) return { id, part: "line" };
82
- }
83
- return null;
122
+ const hidden = nodeGates(scene).hidden;
123
+ const picked = ms.picked.get();
124
+ if (picked !== null && measurementOf(scene.get(picked)) !== null && !hidden(picked)) return picked;
125
+ return measureIds(scene, ms).reverse().find((id) => !hidden(id)) ?? null;
84
126
  }
127
+
128
+ // src/measureHit.ts
129
+ /**
130
+ * The measurement under `p`, newest first: an end within `tolerance` world
131
+ * units of it, else a line within the same distance. A hidden or locked
132
+ * measurement (`nodeGates`) is passed over.
133
+ */
134
+ function measureHitAt(scene, ms, p, tolerance) {
135
+ const gates = nodeGates(scene);
136
+ const shown = shownLookup(scene);
137
+ const ids = measureIds(scene, ms).reverse().filter((id) => !gates.hidden(id) && !gates.locked(id));
138
+ for (const id of ids) {
139
+ const ends = measureEndsOf(shown.get(id));
140
+ if (!ends) continue;
141
+ for (const part of ["end", "start"]) if (Math.hypot(p.x - ends[part].x, p.y - ends[part].y) <= tolerance) return {
142
+ id,
143
+ part
144
+ };
145
+ }
146
+ for (const id of ids) {
147
+ const ends = measureEndsOf(shown.get(id));
148
+ if (ends && pointSegmentDistance(p.x, p.y, ends.start.x, ends.start.y, ends.end.x, ends.end.y) <= tolerance) return {
149
+ id,
150
+ part: "line"
151
+ };
152
+ }
153
+ return null;
154
+ }
155
+ /** The ends of every shown measurement as snap targets for a pointer probe. */
85
156
  function measureEndSource(opts = {}) {
86
- return {
87
- id: "measure-ends",
88
- roles: ["pointer"],
89
- ...opts.reachPx !== void 0 ? { reachPx: opts.reachPx } : {},
90
- *collect(q) {
91
- if (!q.scene) return;
92
- const gates = nodeGates(q.scene);
93
- const skip = new Set(q.exclude);
94
- const reach = q.reachWorld(q.reachPx);
95
- for (const node of nodesAsShown(q.scene.overrides, q.scene.renderOrderNodes())) {
96
- const ends = measureEndsOf(node);
97
- if (!ends || skip.has(node.id) || gates.hidden(node.id)) continue;
98
- for (const end of [ends.start, ends.end]) {
99
- const at = { x: end.x, y: end.y };
100
- for (const p of q.probes) {
101
- if (Math.hypot(at.x - p.at.x, at.y - p.at.y) > reach) continue;
102
- yield { probe: p.id, locus: { at, dirs: [] }, mark: { kind: "point", at, glyph: "center" } };
103
- }
104
- }
105
- }
106
- }
107
- };
157
+ return {
158
+ id: "measure-ends",
159
+ roles: ["pointer"],
160
+ ...opts.reachPx !== void 0 ? { reachPx: opts.reachPx } : {},
161
+ *collect(q) {
162
+ if (!q.scene) return;
163
+ const gates = nodeGates(q.scene);
164
+ const skip = new Set(q.exclude);
165
+ const reach = q.reachWorld(q.reachPx);
166
+ for (const node of nodesAsShown(q.scene.overrides, q.scene.renderOrderNodes())) {
167
+ const ends = measureEndsOf(node);
168
+ if (!ends || skip.has(node.id) || gates.hidden(node.id)) continue;
169
+ for (const end of [ends.start, ends.end]) {
170
+ const at = {
171
+ x: end.x,
172
+ y: end.y
173
+ };
174
+ for (const p of q.probes) {
175
+ if (Math.hypot(at.x - p.at.x, at.y - p.at.y) > reach) continue;
176
+ yield {
177
+ probe: p.id,
178
+ locus: {
179
+ at,
180
+ dirs: []
181
+ },
182
+ mark: {
183
+ kind: "point",
184
+ at,
185
+ glyph: "center"
186
+ }
187
+ };
188
+ }
189
+ }
190
+ }
191
+ }
192
+ };
108
193
  }
194
+
195
+ // src/measureEdits.ts
196
+ /** The labels measurement edits land in history under. */
109
197
  var MEASURE_LABELS = {
110
- add: "Measure",
111
- moveEnd: "Move Measurement End",
112
- move: "Move Measurement",
113
- delete: "Delete Measurement",
114
- clear: "Clear Measurements"
198
+ add: "Measure",
199
+ moveEnd: "Move Measurement End",
200
+ move: "Move Measurement",
201
+ delete: "Delete Measurement",
202
+ clear: "Clear Measurements"
115
203
  };
204
+ /** The op adding a measurement from `start` to `end` on `layer`, at the top,
205
+ * its ends landed in `frames`. */
116
206
  function addMeasureOp(scene, layer, start, end, frames) {
117
- const id = scene.mintId();
118
- return { id, op: insertAt(measureNode(id, layer, start, end, frames), -1, MEASURE_LABELS.add) };
207
+ const id = scene.mintId();
208
+ return {
209
+ id,
210
+ op: coreOps.insertNode(measureNode(id, layer, start, end, frames), -1, MEASURE_LABELS.add)
211
+ };
119
212
  }
213
+ /** `node` as it reads after `next`: what an edit writes and its preview shows. */
120
214
  function changeOps(node, next, label) {
121
- return [
122
- createTransformOp({ id: node.id, from: node.pose, to: next.pose, label }),
123
- createSetDataOp({ id: node.id, from: node.data, to: next.data, label })
124
- ];
125
- }
215
+ return [coreOps.setPose({
216
+ id: node.id,
217
+ from: node.pose,
218
+ to: next.pose,
219
+ label
220
+ }), coreOps.setData({
221
+ id: node.id,
222
+ from: node.data,
223
+ to: next.data,
224
+ label
225
+ })];
226
+ }
227
+ /** The ops moving `node`'s `which` end to `to`, landed in `frame`. */
126
228
  function moveEndOps(node, which, to, frame) {
127
- const next = withMeasureEnd(node, which, to, frame);
128
- return next ? changeOps(node, next, MEASURE_LABELS.moveEnd) : [];
229
+ const next = withMeasureEnd(node, which, to, frame);
230
+ return next ? changeOps(node, next, MEASURE_LABELS.moveEnd) : [];
129
231
  }
232
+ /** `node` carried by `(dx, dy)`, both ends together, each landing where
233
+ * `frameAt` says. Without `frameAt` the ends keep the frames they had. */
130
234
  function translatedMeasure(node, dx, dy, frameAt) {
131
- const ends = measureEndsOf(node);
132
- if (!ends) return null;
133
- const start = { x: ends.start.x + dx, y: ends.start.y + dy };
134
- const end = { x: ends.end.x + dx, y: ends.end.y + dy };
135
- const frames = frameAt ? { start: frameAt(start), end: frameAt(end) } : ends.frames;
136
- const measure = { start, end, ...frames ? { frames } : {} };
137
- return { data: { ...node.data, measure }, pose: measurePose(start, end) };
138
- }
235
+ const ends = measureEndsOf(node);
236
+ if (!ends) return null;
237
+ const start = {
238
+ x: ends.start.x + dx,
239
+ y: ends.start.y + dy
240
+ };
241
+ const end = {
242
+ x: ends.end.x + dx,
243
+ y: ends.end.y + dy
244
+ };
245
+ const frames = frameAt ? {
246
+ start: frameAt(start),
247
+ end: frameAt(end)
248
+ } : ends.frames;
249
+ const measure = {
250
+ start,
251
+ end,
252
+ ...frames ? { frames } : {}
253
+ };
254
+ return {
255
+ data: {
256
+ ...node.data,
257
+ measure
258
+ },
259
+ pose: measurePose(start, end)
260
+ };
261
+ }
262
+ /** The ops carrying `node` by `(dx, dy)`, its ends landing where `frameAt` says. */
139
263
  function moveMeasureOps(node, dx, dy, frameAt) {
140
- const next = translatedMeasure(node, dx, dy, frameAt);
141
- return next ? changeOps(node, next, MEASURE_LABELS.move) : [];
264
+ const next = translatedMeasure(node, dx, dy, frameAt);
265
+ return next ? changeOps(node, next, MEASURE_LABELS.move) : [];
142
266
  }
267
+ /** The ops deleting each of `ids`, as one edit labeled `label`. */
143
268
  function deleteMeasureOps(scene, ids, label) {
144
- const ops = [];
145
- for (const id of ids) {
146
- const node = scene.get(id);
147
- if (node) ops.push(deleteNode(scene, node, label));
148
- }
149
- return ops;
269
+ const ops = [];
270
+ for (const id of ids) {
271
+ const node = scene.get(id);
272
+ if (node) ops.push(coreOps.deleteNode(scene, node, label));
273
+ }
274
+ return ops;
150
275
  }
151
276
 
152
277
  // src/actionIds.ts
278
+ /** The ids of the measure feature's actions. */
153
279
  var MEASURE_ACTION_IDS = {
154
- /** The measure tool's drag, which adds a measurement. */
155
- measure: "measure",
156
- /** The measure tool's click, which picks the measurement under it. */
157
- pickAt: "measure.pickAt",
158
- /** A click on a measurement under any tool, which picks it. */
159
- pick: "measure.pick",
160
- /** A drag on a measurement under any tool: a picked end moves that end, the
161
- * rest moves the whole measurement. */
162
- drag: "measure.drag",
163
- moveBy: "measure.moveBy",
164
- rotateBy: "measure.rotateBy",
165
- delete: "measure.delete",
166
- clear: "measure.clear",
167
- unpick: "measure.unpick"
280
+ /** The measure tool's drag, which adds a measurement. */
281
+ measure: "measure",
282
+ /** The measure tool's click, which picks the measurement under it. */
283
+ pickAt: "measure.pickAt",
284
+ /** A click on a measurement under any tool, which picks it. */
285
+ pick: "measure.pick",
286
+ /** A drag on a measurement under any tool: a picked end moves that end, the
287
+ * rest moves the whole measurement. */
288
+ drag: "measure.drag",
289
+ moveBy: "measure.moveBy",
290
+ rotateBy: "measure.rotateBy",
291
+ delete: "measure.delete",
292
+ clear: "measure.clear",
293
+ unpick: "measure.unpick"
168
294
  };
169
295
 
170
296
  // src/measureCommands.ts
171
297
  var MOVE_LABEL = "Move by Measurement";
172
298
  var ROTATE_LABEL = "Rotate by Measurement";
173
299
  function current(deps, ms) {
174
- const scene = deps?.scene;
175
- if (!scene) return null;
176
- const id = currentMeasureId(scene, ms);
177
- const m = id === null ? null : measurementOf(scene.get(id));
178
- return id !== null && m ? { id, m } : null;
179
- }
180
- function transformable(ms, moves) {
181
- return (deps) => {
182
- const c = current(deps, ms);
183
- if (!c || !moves(c.m)) return ActionDisabledReason.NotApplicable;
184
- return requiresSelection(deps);
185
- };
186
- }
187
- var travels = (m) => m.distance !== 0;
188
- var turns = (m) => m.distance !== 0 && m.angle !== 0;
300
+ const scene = deps?.scene;
301
+ if (!scene) return null;
302
+ const id = currentMeasureId(scene, ms);
303
+ const m = id === null ? null : measurementOf(scene.get(id));
304
+ return id !== null && m ? {
305
+ id,
306
+ m
307
+ } : null;
308
+ }
309
+ /** Enabled with a measurement `transform` reads as a change and a selection it changes, none of it locked. */
310
+ function transformable(ms, transform, label) {
311
+ return (deps) => {
312
+ const c = current(deps, ms);
313
+ const t = c && transform(c.m);
314
+ if (!t) return ActionDisabledReason.NotApplicable;
315
+ const operands = requiresOperands(deps);
316
+ return operands === true ? selectionTransformAnswer(deps, t, label) : operands;
317
+ };
318
+ }
319
+ var translation = (m) => m.distance !== 0 ? {
320
+ kind: "translate",
321
+ dx: m.dx,
322
+ dy: m.dy
323
+ } : null;
324
+ /** A measurement along the x axis turns nothing. The measurement reads counterclockwise-positive; the canvas turns
325
+ * clockwise-positive. */
326
+ var rotation = (m) => m.distance !== 0 && m.angle !== 0 ? {
327
+ kind: "rotate",
328
+ angle: -m.angle,
329
+ pivot: "union"
330
+ } : null;
189
331
  function moveBy(ms) {
190
- return {
191
- id: MEASURE_ACTION_IDS.moveBy,
192
- label: MOVE_LABEL,
193
- group: "measure",
194
- eligible: { capability: "transforms-selection" },
195
- requires: ["selection", "scene", "applyOps", "geometryProjection", "poseDescriptor", "transformFollowers"],
196
- enabled: transformable(ms, travels),
197
- invoker: {
198
- timing: "immediate",
199
- run: (deps) => {
200
- const c = current(deps, ms);
201
- if (c) transformSelection(deps, { kind: "translate", dx: c.m.dx, dy: c.m.dy }, MOVE_LABEL);
202
- }
203
- }
204
- };
332
+ return {
333
+ id: MEASURE_ACTION_IDS.moveBy,
334
+ label: MOVE_LABEL,
335
+ group: "measure",
336
+ eligible: { capability: "transforms-selection" },
337
+ requires: [
338
+ "operands",
339
+ "scene",
340
+ "applyOps",
341
+ "geometryProjection",
342
+ "poseDescriptor",
343
+ "transformFollowers"
344
+ ],
345
+ enabled: transformable(ms, translation, MOVE_LABEL),
346
+ invoker: {
347
+ timing: "immediate",
348
+ run: (deps) => {
349
+ const c = current(deps, ms);
350
+ const t = c && translation(c.m);
351
+ if (t) transformSelection(deps, t, MOVE_LABEL);
352
+ }
353
+ }
354
+ };
205
355
  }
206
356
  function rotateBy(ms) {
207
- return {
208
- id: MEASURE_ACTION_IDS.rotateBy,
209
- label: ROTATE_LABEL,
210
- group: "measure",
211
- eligible: { capability: "transforms-selection" },
212
- requires: ["selection", "scene", "applyOps", "poseDescriptor", "view", "boundsIncludeStroke", "drawnBoxes", "transformFollowers"],
213
- enabled: transformable(ms, turns),
214
- invoker: {
215
- timing: "immediate",
216
- run: (deps) => {
217
- const c = current(deps, ms);
218
- if (c) transformSelection(deps, { kind: "rotate", angle: -c.m.angle, pivot: "union" }, ROTATE_LABEL);
219
- }
220
- }
221
- };
222
- }
357
+ return {
358
+ id: MEASURE_ACTION_IDS.rotateBy,
359
+ label: ROTATE_LABEL,
360
+ group: "measure",
361
+ eligible: { capability: "transforms-selection" },
362
+ requires: [
363
+ "operands",
364
+ "scene",
365
+ "applyOps",
366
+ "poseDescriptor",
367
+ "view",
368
+ "boundsIncludeStroke",
369
+ "drawnBoxes",
370
+ "transformFollowers"
371
+ ],
372
+ enabled: transformable(ms, rotation, ROTATE_LABEL),
373
+ invoker: {
374
+ timing: "immediate",
375
+ run: (deps) => {
376
+ const c = current(deps, ms);
377
+ const t = c && rotation(c.m);
378
+ if (t) transformSelection(deps, t, ROTATE_LABEL);
379
+ }
380
+ }
381
+ };
382
+ }
383
+ /** Whether removing `ids` would reach a locked node, which disables a removal rather than throwing from it. */
223
384
  var removesLocked = (deps, ids) => reachesLocked(deps?.scene, ids);
224
385
  function remove(ms) {
225
- return {
226
- id: MEASURE_ACTION_IDS.delete,
227
- label: MEASURE_LABELS.delete,
228
- group: "measure",
229
- requires: ["scene", "applyOps", "selection"],
230
- // Declining with nothing measured leaves Delete to the ambient `delete`.
231
- enabled: (deps) => {
232
- const c = current(deps, ms);
233
- if (!c) return ActionDisabledReason.NotApplicable;
234
- return removesLocked(deps, [c.id]) ? ActionDisabledReason.Locked : true;
235
- },
236
- invoker: {
237
- timing: "immediate",
238
- run: (deps) => {
239
- const c = current(deps, ms);
240
- if (!c || removesLocked(deps, [c.id])) return;
241
- commitOps(deps, deleteMeasureOps(deps.scene, [c.id], MEASURE_LABELS.delete), MEASURE_LABELS.delete);
242
- if (ms.picked.get() === c.id) ms.picked.set(null);
243
- }
244
- }
245
- };
386
+ return {
387
+ id: MEASURE_ACTION_IDS.delete,
388
+ label: MEASURE_LABELS.delete,
389
+ group: "measure",
390
+ requires: [
391
+ "scene",
392
+ "applyOps",
393
+ "operands"
394
+ ],
395
+ enabled: (deps) => {
396
+ const c = current(deps, ms);
397
+ if (!c) return ActionDisabledReason.NotApplicable;
398
+ return removesLocked(deps, [c.id]) ? ActionDisabledReason.Locked : true;
399
+ },
400
+ invoker: {
401
+ timing: "immediate",
402
+ run: (deps) => {
403
+ const c = current(deps, ms);
404
+ if (!c || removesLocked(deps, [c.id])) return;
405
+ commitOps(deps, deleteMeasureOps(deps.scene, [c.id], MEASURE_LABELS.delete), MEASURE_LABELS.delete);
406
+ if (ms.picked.get() === c.id) ms.picked.set(null);
407
+ }
408
+ }
409
+ };
246
410
  }
247
411
  function clearAll(ms) {
248
- const all = (deps) => {
249
- const scene = deps?.scene;
250
- return scene ? measureIds(scene, ms) : [];
251
- };
252
- return {
253
- id: MEASURE_ACTION_IDS.clear,
254
- label: MEASURE_LABELS.clear,
255
- group: "measure",
256
- requires: ["scene", "applyOps", "selection"],
257
- enabled: (deps) => {
258
- const ids = all(deps);
259
- if (ids.length === 0) return ActionDisabledReason.NotApplicable;
260
- return removesLocked(deps, ids) ? ActionDisabledReason.Locked : true;
261
- },
262
- invoker: {
263
- timing: "immediate",
264
- run: (deps) => {
265
- const ids = all(deps);
266
- if (ids.length === 0 || removesLocked(deps, ids)) return;
267
- commitOps(deps, deleteMeasureOps(deps.scene, ids, MEASURE_LABELS.clear), MEASURE_LABELS.clear);
268
- ms.picked.set(null);
269
- }
270
- }
271
- };
412
+ const all = (deps) => {
413
+ const scene = deps?.scene;
414
+ return scene ? measureIds(scene, ms) : [];
415
+ };
416
+ return {
417
+ id: MEASURE_ACTION_IDS.clear,
418
+ label: MEASURE_LABELS.clear,
419
+ group: "measure",
420
+ requires: [
421
+ "scene",
422
+ "applyOps",
423
+ "operands"
424
+ ],
425
+ enabled: (deps) => {
426
+ const ids = all(deps);
427
+ if (ids.length === 0) return ActionDisabledReason.NotApplicable;
428
+ return removesLocked(deps, ids) ? ActionDisabledReason.Locked : true;
429
+ },
430
+ invoker: {
431
+ timing: "immediate",
432
+ run: (deps) => {
433
+ const ids = all(deps);
434
+ if (ids.length === 0 || removesLocked(deps, ids)) return;
435
+ commitOps(deps, deleteMeasureOps(deps.scene, ids, MEASURE_LABELS.clear), MEASURE_LABELS.clear);
436
+ ms.picked.set(null);
437
+ }
438
+ }
439
+ };
272
440
  }
273
441
  function unpick(ms) {
274
- return {
275
- id: MEASURE_ACTION_IDS.unpick,
276
- label: "Deselect Measurement",
277
- // Declining with nothing picked leaves Escape to the ambient `escape`.
278
- enabled: () => ms.picked.get() !== null ? true : ActionDisabledReason.NotApplicable,
279
- invoker: { timing: "immediate", run: () => ms.picked.set(null) }
280
- };
281
- }
442
+ return {
443
+ id: MEASURE_ACTION_IDS.unpick,
444
+ label: "Deselect Measurement",
445
+ requires: ["scene"],
446
+ enabled: (deps) => {
447
+ const c = current(deps, ms);
448
+ return c !== null && c.id === ms.picked.get() ? true : ActionDisabledReason.NotApplicable;
449
+ },
450
+ invoker: {
451
+ timing: "immediate",
452
+ run: () => ms.picked.set(null)
453
+ }
454
+ };
455
+ }
456
+ /**
457
+ * The commands over a scene's measurements: move the content selection by
458
+ * the current measurement's offset, or turn it about its center by the
459
+ * measured angle — each one undo step Transform Again can repeat — delete the
460
+ * current measurement, clear them all, and drop the pick. The current
461
+ * measurement is the picked one, else the newest. All but the pick's are in
462
+ * the `measure` group.
463
+ */
282
464
  function measureCommands(ms) {
283
- return [moveBy(ms), rotateBy(ms), remove(ms), clearAll(ms), unpick(ms)];
465
+ return [
466
+ moveBy(ms),
467
+ rotateBy(ms),
468
+ remove(ms),
469
+ clearAll(ms),
470
+ unpick(ms)
471
+ ];
284
472
  }
473
+
474
+ // src/measureActions.ts
475
+ /** Screen-px radius around a measurement that picks it. */
285
476
  var MEASURE_HIT_PX = 6;
286
477
  var pointOf = (at) => at.drag?.current ?? at.world;
287
- var framesOf = (scene) => scene ? unitFrameAt(scene) : () => null;
478
+ /** Where an end lands among `scene`'s unit-scope frames; the top of the tree
479
+ * without a scene. Built once per gesture: the scene holds still under it. */
480
+ var framesOf = (scene) => scene ? createUnitFrameLookup(scene) : () => null;
481
+ /**
482
+ * The measure tool's drag: from press to pointer, each end through a `point`
483
+ * session of the `snap` dep. While `snap.constrain` (Shift) is held the end
484
+ * stays on the line through the snapped start at the nearest step of the
485
+ * binding param `angleStep` (radians, default 15°), and lands where that line
486
+ * meets a target. Each end records the unit-scope frame it lands in
487
+ * (`createUnitFrameLookup`), so the measurement reads in that frame's units. The drawing
488
+ * shows in `ms.draft`; on release it becomes a measurement node, one undo
489
+ * step, and the picked one.
490
+ */
288
491
  function measureCreateAction(ms) {
289
- return defineAction({
290
- id: MEASURE_ACTION_IDS.measure,
291
- label: "Measure",
292
- modifierRoles: SNAP_ROLES,
293
- requires: ["snap", "scene", "applyOps", "selection"],
294
- invoker: {
295
- timing: "ongoing",
296
- // The dispatcher builds deps once, for `start`; later events carry none.
297
- start(ctx, opts) {
298
- const deps = ctx.deps;
299
- const snap = spanSnap(deps.snap, () => {
300
- return { step: resolveParams(opts?.params)?.angleStep ?? SNAP_ANGLE_STEP };
301
- });
302
- const scene = deps.scene;
303
- const frameAt = framesOf(scene);
304
- const start = snap.start(ctx.drag?.start ?? ctx.world, snapMods(ctx)).point;
305
- const startFrame = frameAt(start);
306
- const endAt = (at) => snap.end(pointOf(at), snapMods(at)).point;
307
- const between = (end) => measureBetween(start, end, { start: startFrame, end: frameAt(end) });
308
- ms.draft.set(between(start));
309
- return {
310
- kind: "measure",
311
- onMove: (moveCtx) => ms.draft.set(between(endAt(moveCtx))),
312
- onEnd: (endCtx, reason) => {
313
- try {
314
- ms.draft.set(null);
315
- if (reason !== "commit" || !scene) return;
316
- const end = endAt(endCtx);
317
- if (end.x === start.x && end.y === start.y) return;
318
- const { id, op } = addMeasureOp(scene, ms.layer, start, end, between(end).frames);
319
- commitOps(deps, [op], "Measure");
320
- ms.picked.set(id);
321
- } finally {
322
- snap.close();
323
- }
324
- }
325
- };
326
- }
327
- }
328
- });
329
- }
492
+ return defineAction({
493
+ id: MEASURE_ACTION_IDS.measure,
494
+ label: "Measure",
495
+ modifierRoles: SNAP_ROLES,
496
+ requires: [
497
+ "snap",
498
+ "scene",
499
+ "applyOps",
500
+ "operands"
501
+ ],
502
+ invoker: {
503
+ timing: "ongoing",
504
+ start(ctx, opts) {
505
+ const deps = ctx.deps;
506
+ const snap = createSpanSnap(deps.snap, () => {
507
+ return { step: resolveParams(opts?.params)?.angleStep ?? SNAP_ANGLE_STEP };
508
+ });
509
+ const scene = deps.scene;
510
+ const frameAt = framesOf(scene);
511
+ const start = snap.start(ctx.drag?.start ?? ctx.world, snapMods(ctx)).point;
512
+ const startFrame = frameAt(start);
513
+ const endAt = (at) => snap.end(pointOf(at), snapMods(at)).point;
514
+ const between = (end) => measureBetween(start, end, {
515
+ start: startFrame,
516
+ end: frameAt(end)
517
+ });
518
+ ms.draft.set(between(start));
519
+ return {
520
+ kind: "measure",
521
+ onMove: (moveCtx) => ms.draft.set(between(endAt(moveCtx))),
522
+ onEnd: (endCtx, reason) => {
523
+ try {
524
+ ms.draft.set(null);
525
+ if (reason !== "commit" || !scene) return;
526
+ const end = endAt(endCtx);
527
+ if (end.x === start.x && end.y === start.y) return;
528
+ const { id, op } = addMeasureOp(scene, ms.layer, start, end, between(end).frames);
529
+ commitOps(deps, [op], "Measure");
530
+ ms.picked.set(id);
531
+ } finally {
532
+ snap.close();
533
+ }
534
+ }
535
+ };
536
+ }
537
+ }
538
+ });
539
+ }
540
+ /** The measure tool's click: picks the measurement under it, or drops the
541
+ * pick on empty canvas. */
330
542
  function measurePickAtAction(ms) {
331
- return defineAction({
332
- id: MEASURE_ACTION_IDS.pickAt,
333
- label: "Pick Measurement",
334
- requires: ["scene", "view"],
335
- invoker: {
336
- timing: "immediate",
337
- run: (deps, params) => {
338
- const press = params?.press;
339
- const scene = deps.scene;
340
- if (!scene || !press) return;
341
- const hit = measureAt(scene, ms, press, pxReach(MEASURE_HIT_PX, deps.view?.get().scale ?? { x: 1, y: 1 }));
342
- ms.picked.set(hit?.id ?? null);
343
- }
344
- }
345
- });
346
- }
543
+ return defineAction({
544
+ id: MEASURE_ACTION_IDS.pickAt,
545
+ label: "Pick Measurement",
546
+ requires: ["scene", "view"],
547
+ invoker: {
548
+ timing: "immediate",
549
+ run: (deps, params) => {
550
+ const press = params?.press;
551
+ const scene = deps.scene;
552
+ if (!scene || !press) return;
553
+ const hit = measureHitAt(scene, ms, press, pxReach(6, deps.view?.get().scale ?? {
554
+ x: 1,
555
+ y: 1
556
+ }));
557
+ ms.picked.set(hit?.id ?? null);
558
+ }
559
+ }
560
+ });
561
+ }
562
+ /** What a press on the measurements layer resolved, as its hit-test claims it. */
347
563
  var hitOf = (affordance) => affordance?.payload ?? null;
564
+ /** A click on a measurement under any tool: picks it, leaving the content
565
+ * selection as it was. */
348
566
  function measurePickAction(ms) {
349
- return defineAction({
350
- id: MEASURE_ACTION_IDS.pick,
351
- label: "Pick Measurement",
352
- invoker: {
353
- timing: "immediate",
354
- run: (_deps, params) => {
355
- const hit = hitOf(params?.affordance);
356
- if (hit) ms.picked.set(hit.id);
357
- }
358
- }
359
- });
360
- }
567
+ return defineAction({
568
+ id: MEASURE_ACTION_IDS.pick,
569
+ label: "Pick Measurement",
570
+ invoker: {
571
+ timing: "immediate",
572
+ run: (_deps, params) => {
573
+ const hit = hitOf(params?.affordance);
574
+ if (hit) ms.picked.set(hit.id);
575
+ }
576
+ }
577
+ });
578
+ }
579
+ /** The node `id` on `scene`, as a measurement edit reads it. */
361
580
  function nodeOf(scene, id) {
362
- return scene?.get(id);
363
- }
581
+ return scene?.get(id);
582
+ }
583
+ /**
584
+ * A drag on a measurement under any tool. On an end of the picked
585
+ * measurement it moves that end, keeping its offset from the press, through
586
+ * a `point` session of the `snap` dep in which the measurement's own ends
587
+ * offer nothing; anywhere else on a
588
+ * measurement it carries the whole measurement with the pointer. Either way
589
+ * each moved end records the unit-scope frame it lands in. Previewed while it
590
+ * runs; one undo step on release.
591
+ */
364
592
  function measureDragAction(ms) {
365
- return {
366
- id: MEASURE_ACTION_IDS.drag,
367
- label: "Drag Measurement",
368
- modifierRoles: SNAP_ROLES,
369
- requires: ["scene", "snap", "applyOps", "selection"],
370
- invoker: {
371
- timing: "ongoing",
372
- start(ctx) {
373
- const hit = hitOf(ctx.drag?.affordance);
374
- const deps = ctx.deps;
375
- const scene = deps.scene;
376
- const node = hit ? nodeOf(scene, hit.id) : void 0;
377
- if (!hit || !node) return {};
378
- const end = hit.part !== "line" && ms.picked.get() === hit.id ? hit.part : null;
379
- const from = ctx.drag?.start ?? ctx.world;
380
- const grabbed = end && measureEndsOf(node)?.[end] || from;
381
- const snap = end ? deps.snap?.begin({ gesture: "point", press: grabbed, ids: [hit.id] }) ?? null : null;
382
- const frameAt = framesOf(scene);
383
- let at = from;
384
- let landed = grabbed;
385
- const next = () => end ? withMeasureEnd(node, end, landed, frameAt(landed)) : translatedMeasure(node, at.x - from.x, at.y - from.y, frameAt);
386
- const follow = (c) => {
387
- at = pointOf(c);
388
- const held = { x: grabbed.x + at.x - from.x, y: grabbed.y + at.y - from.y };
389
- landed = snap ? snap.at(held, snapMods(c)).point : held;
390
- };
391
- ms.picked.set(hit.id);
392
- return {
393
- kind: MEASURE_ACTION_IDS.drag,
394
- onMove: follow,
395
- onEnd: (endCtx, reason) => {
396
- try {
397
- if (reason !== "commit") return;
398
- follow(endCtx);
399
- const ops = end ? moveEndOps(node, end, landed, frameAt(landed)) : moveMeasureOps(node, at.x - from.x, at.y - from.y, frameAt);
400
- commitOps(deps, ops, ops[0]?.label ?? "Move Measurement");
401
- } finally {
402
- snap?.end();
403
- }
404
- },
405
- previewIds: () => [hit.id],
406
- previewOpaqueIds: () => [hit.id],
407
- previewPose: () => next()?.pose ?? null,
408
- previewData: () => next()?.data ?? null
409
- };
410
- }
411
- }
412
- };
593
+ return {
594
+ id: MEASURE_ACTION_IDS.drag,
595
+ label: "Drag Measurement",
596
+ modifierRoles: SNAP_ROLES,
597
+ requires: [
598
+ "scene",
599
+ "snap",
600
+ "applyOps",
601
+ "operands"
602
+ ],
603
+ invoker: {
604
+ timing: "ongoing",
605
+ start(ctx) {
606
+ const hit = hitOf(ctx.drag?.affordance);
607
+ const deps = ctx.deps;
608
+ const scene = deps.scene;
609
+ const node = hit ? nodeOf(scene, hit.id) : void 0;
610
+ if (!hit || !node) return {};
611
+ const end = hit.part !== "line" && ms.picked.get() === hit.id ? hit.part : null;
612
+ const from = ctx.drag?.start ?? ctx.world;
613
+ const grabbed = end && measureEndsOf(node)?.[end] || from;
614
+ const snap = end ? deps.snap?.begin({
615
+ gesture: "point",
616
+ press: grabbed,
617
+ ids: [hit.id]
618
+ }) ?? null : null;
619
+ const frameAt = framesOf(scene);
620
+ let at = from;
621
+ let landed = grabbed;
622
+ const next = () => end ? withMeasureEnd(node, end, landed, frameAt(landed)) : translatedMeasure(node, at.x - from.x, at.y - from.y, frameAt);
623
+ const follow = (c) => {
624
+ at = pointOf(c);
625
+ const held = {
626
+ x: grabbed.x + at.x - from.x,
627
+ y: grabbed.y + at.y - from.y
628
+ };
629
+ landed = snap ? snap.at(held, snapMods(c)).point : held;
630
+ };
631
+ ms.picked.set(hit.id);
632
+ return {
633
+ kind: MEASURE_ACTION_IDS.drag,
634
+ onMove: follow,
635
+ onEnd: (endCtx, reason) => {
636
+ try {
637
+ if (reason !== "commit") return;
638
+ follow(endCtx);
639
+ const ops = end ? moveEndOps(node, end, landed, frameAt(landed)) : moveMeasureOps(node, at.x - from.x, at.y - from.y, frameAt);
640
+ commitOps(deps, ops, ops[0]?.label ?? "Move Measurement");
641
+ } finally {
642
+ snap?.end();
643
+ }
644
+ },
645
+ previewIds: () => [hit.id],
646
+ previewOpaqueIds: () => [hit.id],
647
+ previewPose: () => next()?.pose ?? null,
648
+ previewData: () => next()?.data ?? null
649
+ };
650
+ }
651
+ }
652
+ };
413
653
  }
654
+
655
+ // src/measurePainter.ts
656
+ /** Screen-px half-length of the tick across each end of a measurement. */
414
657
  var MEASURE_TICK_PX = 5;
415
- function measureCommands2(start, end, perPx) {
416
- const stroke = { ...OVERLAY_ROLE_STROKES["measure"], width: { px: 1 } };
417
- const len = Math.hypot(end.x - start.x, end.y - start.y);
418
- const nx = len > 0 ? -(end.y - start.y) / len : 0;
419
- const ny = len > 0 ? (end.x - start.x) / len : 1;
420
- const half = MEASURE_TICK_PX * perPx;
421
- const tick = (p) => ({
422
- kind: "path",
423
- path: polylineFromPoints([{ x: p.x - nx * half, y: p.y - ny * half }, { x: p.x + nx * half, y: p.y + ny * half }]),
424
- stroke
425
- });
426
- const out = [tick(start), tick(end)];
427
- if (len > 0) out.unshift({ kind: "path", path: polylineFromPoints([start, end]), stroke });
428
- return out;
429
- }
658
+ /**
659
+ * A measurement's line and a tick across each end, as the measure painter
660
+ * and the measurements layer draw it. `perPx` is world units per screen pixel, so the
661
+ * line and its ticks keep their screen size at any zoom.
662
+ */
663
+ function measureDrawCommands(start, end, perPx) {
664
+ const stroke = {
665
+ ...OVERLAY_ROLE_STROKES["measure"],
666
+ width: { px: 1 }
667
+ };
668
+ const len = Math.hypot(end.x - start.x, end.y - start.y);
669
+ const nx = len > 0 ? -(end.y - start.y) / len : 0;
670
+ const ny = len > 0 ? (end.x - start.x) / len : 1;
671
+ const half = 5 * perPx;
672
+ const tick = (p) => ({
673
+ kind: "path",
674
+ path: polylineFromPoints([{
675
+ x: p.x - nx * half,
676
+ y: p.y - ny * half
677
+ }, {
678
+ x: p.x + nx * half,
679
+ y: p.y + ny * half
680
+ }]),
681
+ stroke
682
+ });
683
+ const out = [tick(start), tick(end)];
684
+ if (len > 0) out.unshift({
685
+ kind: "path",
686
+ path: polylineFromPoints([start, end]),
687
+ stroke
688
+ });
689
+ return out;
690
+ }
691
+ /** Paints a measurement node — `data.measure`, in world units — in the
692
+ * canvas's measure color. It has no silhouette: a measurement is not content
693
+ * to pick. `createMeasurementsContribution` registers it for its scene; a render
694
+ * with no canvas registers it itself (`nodeShapesOf(scene).register`). */
430
695
  var MEASURE_PAINTER = {
431
- id: "measure:measurement",
432
- matches: (node) => (node.pose === void 0 || isRectPose(node.pose)) && measureEndsOf(node) !== null,
433
- paint: (node, _pose, ctx) => {
434
- const ends = measureEndsOf(node);
435
- if (!ends) return [];
436
- return measureCommands2(ends.start, ends.end, 1 / (ctx?.scale ?? 1));
437
- }
696
+ id: "measure:measurement",
697
+ matches: (node) => (node.pose === void 0 || isRectPose(node.pose)) && measureEndsOf(node) !== null,
698
+ paint: (node, _pose, ctx) => {
699
+ const ends = measureEndsOf(node);
700
+ if (!ends) return [];
701
+ return measureDrawCommands(ends.start, ends.end, 1 / (ctx?.scale ?? 1));
702
+ }
438
703
  };
439
704
 
440
705
  // src/measureLayer.ts
706
+ /** The registered layer's id; a press it claims routes as `layer:<id>`. */
441
707
  var MEASURE_LAYER_ID = "weasel-measure";
708
+ /** The affordance kind a press on a measurement routes under. */
442
709
  var MEASURE_AFFORDANCE_KIND = `layer:${MEASURE_LAYER_ID}`;
443
710
  var HANDLE_PX = 3.5;
444
- function measurementsLayer(scene, ms) {
445
- return {
446
- id: MEASURE_LAYER_ID,
447
- label: "Measurements",
448
- space: "screen",
449
- subscribe: (listener) => {
450
- const offs = [ms.picked.subscribe(listener), ms.draft.subscribe(listener), ms.measuring.subscribe(listener)];
451
- return () => {
452
- for (const off of offs) off();
453
- };
454
- },
455
- draw: (_data, view) => {
456
- const t = viewToTransform(view);
457
- const toScreen = (p) => {
458
- const [x, y] = worldToScreen(p.x, p.y, t);
459
- return { x, y };
460
- };
461
- const out = [];
462
- const draft = ms.draft.get();
463
- if (draft) out.push(...measureCommands2(toScreen(draft.start), toScreen(draft.end), 1));
464
- const picked = ms.picked.get();
465
- const ends = picked === null ? null : measureEndsOf(shownLookup(scene).get(picked));
466
- if (ends && !scene.isHidden(picked)) {
467
- const stroke = { ...OVERLAY_ROLE_STROKES["measure"], width: 1 };
468
- for (const p of [ends.start, ends.end].map(toScreen)) {
469
- out.push({
470
- kind: "path",
471
- path: rectPath(p.x - HANDLE_PX, p.y - HANDLE_PX, HANDLE_PX * 2, HANDLE_PX * 2),
472
- fill: { paint: { color: "#ffffff" } },
473
- stroke
474
- });
475
- }
476
- }
477
- return out;
478
- },
479
- hitTest: (wx, wy, _data, view) => {
480
- const hit = measureAt(scene, ms, { x: wx, y: wy }, pxReach(MEASURE_HIT_PX, view.scale));
481
- if (!hit) return null;
482
- const onPickedEnd = hit.part !== "line" && hit.id === ms.picked.get();
483
- if (ms.measuring.get() && !onPickedEnd) return null;
484
- return {
485
- initialScratch: hit,
486
- strength: "exclusive",
487
- claimedKinds: ["pointer"],
488
- cursor: onPickedEnd ? "crosshair" : "move"
489
- };
490
- }
491
- };
711
+ /**
712
+ * The measurements' interactive layer, under every tool: it draws the
713
+ * measurement a measure drag is making and a handle on each end of the picked
714
+ * one, and claims a press on a measurement so a click picks it and a drag
715
+ * edits it rather than reaching the tool. Under the measure tool it claims
716
+ * only the picked measurement's ends, so a drag from anywhere else measures.
717
+ */
718
+ function createMeasureLayer(scene, ms) {
719
+ return {
720
+ id: MEASURE_LAYER_ID,
721
+ label: "Measurements",
722
+ space: "screen",
723
+ subscribe: (listener) => {
724
+ const offs = [
725
+ ms.picked.subscribe(listener),
726
+ ms.draft.subscribe(listener),
727
+ ms.measuring.subscribe(listener)
728
+ ];
729
+ return () => {
730
+ for (const off of offs) off();
731
+ };
732
+ },
733
+ draw: (_data, view) => {
734
+ const t = viewToTransform(view);
735
+ const toScreen = (p) => {
736
+ const [x, y] = worldToScreen(p.x, p.y, t);
737
+ return {
738
+ x,
739
+ y
740
+ };
741
+ };
742
+ const out = [];
743
+ const draft = ms.draft.get();
744
+ if (draft) out.push(...measureDrawCommands(toScreen(draft.start), toScreen(draft.end), 1));
745
+ const picked = ms.picked.get();
746
+ const ends = picked === null ? null : measureEndsOf(shownLookup(scene).get(picked));
747
+ if (ends && !scene.isHidden(picked)) {
748
+ const stroke = {
749
+ ...OVERLAY_ROLE_STROKES["measure"],
750
+ width: 1
751
+ };
752
+ for (const p of [ends.start, ends.end].map(toScreen)) out.push({
753
+ kind: "path",
754
+ path: rectPath(p.x - HANDLE_PX, p.y - HANDLE_PX, HANDLE_PX * 2, HANDLE_PX * 2),
755
+ fill: { paint: { color: "#ffffff" } },
756
+ stroke
757
+ });
758
+ }
759
+ return out;
760
+ },
761
+ hitTest: (wx, wy, _data, view) => {
762
+ const hit = measureHitAt(scene, ms, {
763
+ x: wx,
764
+ y: wy
765
+ }, pxReach(6, view.scale));
766
+ if (!hit) return null;
767
+ const onPickedEnd = hit.part !== "line" && hit.id === ms.picked.get();
768
+ if (ms.measuring.get() && !onPickedEnd) return null;
769
+ return {
770
+ initialScratch: hit,
771
+ strength: "exclusive",
772
+ claimedKinds: ["pointer"],
773
+ cursor: onPickedEnd ? "crosshair" : "move"
774
+ };
775
+ }
776
+ };
492
777
  }
493
778
 
494
779
  // src/measureContribution.ts
495
780
  var onMeasurement = hitPredicate((hit) => hit?.kind === MEASURE_AFFORDANCE_KIND);
496
- function measurementsContribution(scene, ms) {
497
- const layer = measurementsLayer(scene, ms);
498
- return {
499
- id: "weasel-measure",
500
- eligibility: { claimed: true },
501
- attach: (api) => {
502
- const offShape = nodeShapesOf(scene).register(MEASURE_PAINTER);
503
- const offLayer = api.registerLayer(layer);
504
- api.requestRedraw();
505
- return () => {
506
- offLayer();
507
- offShape();
508
- };
509
- },
510
- actions: [...measureCommands(ms), measurePickAction(ms), measureDragAction(ms)],
511
- bindings: [
512
- { spec: { kind: "click", target: { kindOf: onMeasurement }, mods: ANY_MODS }, actionId: MEASURE_ACTION_IDS.pick, opts: { id: "weasel-measure.click" } },
513
- { spec: { kind: "drag", target: { kindOf: onMeasurement }, mods: ANY_MODS }, actionId: MEASURE_ACTION_IDS.drag, opts: { id: "weasel-measure.drag" } }
514
- ]
515
- };
781
+ /**
782
+ * A scene's measurements on a canvas, whatever tool is active: the painter
783
+ * that draws them, the layer that shows the picked one and claims presses on measurements, a click on
784
+ * one to pick it and a drag to edit it, and the commands — Move by, Rotate
785
+ * by, Delete, Clear — a readout binds buttons to. Install it with
786
+ * `<SceneCanvas ambient={[…]}>`; `useMeasureTool` adds the measuring itself.
787
+ */
788
+ function createMeasurementsContribution(scene, ms) {
789
+ const layer = createMeasureLayer(scene, ms);
790
+ return {
791
+ id: "weasel-measure",
792
+ eligibility: { claimed: true },
793
+ attach: (api) => {
794
+ const offShape = nodeShapesOf(scene).register(MEASURE_PAINTER);
795
+ const offLayer = api.registerLayer(layer);
796
+ api.requestRedraw();
797
+ return () => {
798
+ offLayer();
799
+ offShape();
800
+ };
801
+ },
802
+ actions: [
803
+ ...measureCommands(ms),
804
+ measurePickAction(ms),
805
+ measureDragAction(ms)
806
+ ],
807
+ bindings: [{
808
+ spec: {
809
+ kind: "click",
810
+ target: { kindOf: onMeasurement },
811
+ mods: ANY_MODS
812
+ },
813
+ actionId: MEASURE_ACTION_IDS.pick,
814
+ opts: { id: "weasel-measure.click" }
815
+ }, {
816
+ spec: {
817
+ kind: "drag",
818
+ target: { kindOf: onMeasurement },
819
+ mods: ANY_MODS
820
+ },
821
+ actionId: MEASURE_ACTION_IDS.drag,
822
+ opts: { id: "weasel-measure.drag" }
823
+ }]
824
+ };
516
825
  }
826
+
827
+ // src/useMeasureTool.ts
828
+ /**
829
+ * Measure tool. A drag adds a measurement from press to release in world
830
+ * units — both ends through the `snap` dep, Shift holding the angle to
831
+ * `angleStep` — as one undo step, and picks it. A click picks the
832
+ * measurement under it, Escape drops the pick, and Delete removes the
833
+ * current measurement. The measurements are scene nodes on an annotation
834
+ * layer, so they stay when the tool changes; editing them under any tool,
835
+ * and the commands that transform by them, come from
836
+ * `createMeasurementsContribution`, which the canvas installs beside this tool.
837
+ */
517
838
  function useMeasureTool(options) {
518
- const { measurements: ms, keybinding } = options;
519
- const actions = useMemo(() => [measureCreateAction(ms), measurePickAtAction(ms)], [ms]);
520
- const angleStep = useLatest(options.angleStep);
521
- return useMemo(() => defineTool({
522
- id: "measure",
523
- capabilities: ["navigation"],
524
- hookName: "useMeasureTool",
525
- cursor: "crosshair",
526
- presentation: { label: "Measure", icon: (
527
- /* @icon */
528
- "core:measure"
529
- ), group: "view" },
530
- ...keybinding === null ? {} : { keybinding: keybinding ?? { key: "M" } },
531
- actions,
532
- onActivate: () => ms.measuring.set(true),
533
- onDeactivate: () => {
534
- ms.measuring.set(false);
535
- ms.draft.set(null);
536
- },
537
- bindings: [
538
- { spec: { kind: "click" }, actionId: MEASURE_ACTION_IDS.pickAt, opts: { id: "measure.pick" } },
539
- {
540
- spec: { kind: "drag", mods: SNAP_ROLE_MODS },
541
- actionId: MEASURE_ACTION_IDS.measure,
542
- opts: { id: "measure.drag", params: () => angleStep.current === void 0 ? {} : { angleStep: angleStep.current } }
543
- },
544
- { spec: { kind: "key", key: "Escape" }, actionId: MEASURE_ACTION_IDS.unpick, opts: { id: "measure.unpick" } },
545
- { spec: { kind: "key", key: "Delete" }, actionId: MEASURE_ACTION_IDS.delete, opts: { id: "measure.delete" } },
546
- { spec: { kind: "key", key: "Backspace" }, actionId: MEASURE_ACTION_IDS.delete, opts: { id: "measure.backspace" } }
547
- ]
548
- }), [actions, keybinding, ms, angleStep]);
839
+ const { measurements: ms, keybinding } = options;
840
+ const actions = useMemo(() => [measureCreateAction(ms), measurePickAtAction(ms)], [ms]);
841
+ const angleStep = useLatest(options.angleStep);
842
+ return useMemo(() => defineTool({
843
+ id: "measure",
844
+ capabilities: ["navigation"],
845
+ hookName: "useMeasureTool",
846
+ cursor: "crosshair",
847
+ presentation: {
848
+ label: "Measure",
849
+ icon: /* @icon */ "core:measure",
850
+ group: "view"
851
+ },
852
+ ...keybinding === null ? {} : { keybinding: keybinding ?? { key: "M" } },
853
+ actions,
854
+ onActivate: () => ms.measuring.set(true),
855
+ onDeactivate: () => {
856
+ ms.measuring.set(false);
857
+ ms.draft.set(null);
858
+ },
859
+ bindings: [
860
+ {
861
+ spec: { kind: "click" },
862
+ actionId: MEASURE_ACTION_IDS.pickAt,
863
+ opts: { id: "measure.pick" }
864
+ },
865
+ {
866
+ spec: {
867
+ kind: "drag",
868
+ mods: SNAP_ROLE_MODS
869
+ },
870
+ actionId: MEASURE_ACTION_IDS.measure,
871
+ opts: {
872
+ id: "measure.drag",
873
+ params: () => angleStep.current === void 0 ? {} : { angleStep: angleStep.current }
874
+ }
875
+ },
876
+ {
877
+ spec: {
878
+ kind: "key",
879
+ key: "Escape"
880
+ },
881
+ actionId: MEASURE_ACTION_IDS.unpick,
882
+ opts: { id: "measure.unpick" }
883
+ },
884
+ {
885
+ spec: {
886
+ kind: "key",
887
+ key: "Delete"
888
+ },
889
+ actionId: MEASURE_ACTION_IDS.delete,
890
+ opts: { id: "measure.delete" }
891
+ },
892
+ {
893
+ spec: {
894
+ kind: "key",
895
+ key: "Backspace"
896
+ },
897
+ actionId: MEASURE_ACTION_IDS.delete,
898
+ opts: { id: "measure.backspace" }
899
+ }
900
+ ]
901
+ }), [
902
+ actions,
903
+ keybinding,
904
+ ms,
905
+ angleStep
906
+ ]);
549
907
  }
908
+
909
+ // src/toolSets.ts
910
+ /** Every tool `@weasel-js/measure` ships: the measure tool. */
550
911
  var MEASURE_TOOLS = toolSet("measure", ["measure"], { label: "Measure" });
912
+ /**
913
+ * Every tool in {@link MEASURE_TOOLS}, keyed by id, for `<SceneCanvas tools>` beside the
914
+ * `createMeasurementsContribution` whose actions they bind. `options` go to `useMeasureTool`.
915
+ */
551
916
  function useMeasureTools(options) {
552
- const measure = useMeasureTool(options);
553
- return useMemo(() => ({ measure }), [measure]);
917
+ const measure = useMeasureTool(options);
918
+ return useMemo(() => ({ measure }), [measure]);
919
+ }
920
+
921
+ // src/MeasureReadout/MeasureReadout.module.css
922
+ var readout = "_readout_7e51b2";
923
+ var actions = "_actions_7e51b2";
924
+ var cell = "_cell_7e51b2";
925
+ var name = "_name_7e51b2";
926
+ var value = "_value_7e51b2 _numeric_25fd0b";
927
+ var MeasureReadout_module_default = {
928
+ readout,
929
+ actions,
930
+ cell,
931
+ name,
932
+ value
933
+ };
934
+
935
+ // src/MeasureReadout/MeasureReadout.tsx
936
+ var COMMANDS = [
937
+ [MEASURE_ACTION_IDS.moveBy, "Move by"],
938
+ [MEASURE_ACTION_IDS.rotateBy, "Rotate by"],
939
+ [MEASURE_ACTION_IDS.delete, "Delete"],
940
+ [MEASURE_ACTION_IDS.clear, "Clear all"]
941
+ ];
942
+ var AT = decimal({
943
+ places: 2,
944
+ grouping: false
945
+ });
946
+ var format = (n) => qty(n, AT).text;
947
+ var NONE = Object.freeze([]);
948
+ var noSubscribe = () => () => {};
949
+ function useCommands() {
950
+ const registry = useActionsRegistry();
951
+ const all = useSyncExternalStore(registry ? registry.subscribe : noSubscribe, registry ? registry.list : () => NONE, registry ? registry.list : () => NONE);
952
+ return {
953
+ items: COMMANDS.flatMap(([id]) => all.filter((a) => a.id === id).flatMap(actionItems)),
954
+ trigger: (id) => {
955
+ registry?.trigger(id);
956
+ }
957
+ };
958
+ }
959
+ /**
960
+ * The measurement readout: a chip pinned to the bottom of the nearest
961
+ * positioned ancestor, showing the measurement a measure drag is drawing,
962
+ * else the picked one, else the newest — its distance, offset, and angle in
963
+ * the units of the frame its ends landed in, its world lengths divided by that
964
+ * frame's magnification (`measureMagnification`) — with Move by, Rotate by, Delete, and Clear all from the
965
+ * actions registry. A command that cannot run says why in its tooltip. The
966
+ * angle reads like a protractor, counterclockwise-positive: a line rising to
967
+ * the right at 30° reads 30°, and Rotate by turns the selection that way.
968
+ */
969
+ function MeasureReadout({ scene, measurements: ms, className }) {
970
+ useSyncExternalStore(scene.subscribe, scene.getVersion, scene.getVersion);
971
+ useSyncExternalStore(scene.overrides.subscribe, scene.overrides.getGeneration, scene.overrides.getGeneration);
972
+ useSyncExternalStore(ms.picked.subscribe, ms.picked.get, ms.picked.get);
973
+ const draft = useSyncExternalStore(ms.draft.subscribe, ms.draft.get, ms.draft.get);
974
+ const { items, trigger } = useCommands();
975
+ const states = useActionStates(items);
976
+ const id = currentMeasureId(scene, ms);
977
+ const m = draft ?? (id === null ? null : measurementOf(shownLookup(scene).get(id)));
978
+ if (!m) return null;
979
+ const mag = measureMagnification(scene, m.frames);
980
+ const cells = [
981
+ ["Distance", format(m.distance / mag)],
982
+ ["ΔX", format(m.dx / mag)],
983
+ ["ΔY", format(m.dy / mag)],
984
+ ["Angle", `${format(m.angle * RAD_TO_DEG)}°`]
985
+ ];
986
+ return /* @__PURE__ */ jsxs("div", {
987
+ className: [MeasureReadout_module_default.readout, className].filter(Boolean).join(" "),
988
+ role: "group",
989
+ "aria-label": "Measurement",
990
+ children: [/* @__PURE__ */ jsx("div", {
991
+ className: MeasureReadout_module_default.actions,
992
+ role: "toolbar",
993
+ "aria-label": "Measurement commands",
994
+ children: COMMANDS.map(([cmd, label]) => {
995
+ const i = items.findIndex((it) => it.action.id === cmd);
996
+ if (i < 0) return null;
997
+ const state = states[i];
998
+ return /* @__PURE__ */ jsx(ActionButton, {
999
+ label,
1000
+ description: items[i].description,
1001
+ grade: items[i].grade,
1002
+ labeled: true,
1003
+ disabled: state.disabled,
1004
+ ...state.disabledReason !== void 0 ? { disabledReason: reasonLabel(state.disabledReason) } : {},
1005
+ onPress: () => trigger(cmd)
1006
+ }, cmd);
1007
+ })
1008
+ }), cells.map(([name, value]) => /* @__PURE__ */ jsxs("span", {
1009
+ className: MeasureReadout_module_default.cell,
1010
+ children: [/* @__PURE__ */ jsx("span", {
1011
+ className: MeasureReadout_module_default.name,
1012
+ children: name
1013
+ }), /* @__PURE__ */ jsx("span", {
1014
+ className: MeasureReadout_module_default.value,
1015
+ children: value
1016
+ })]
1017
+ }, name))]
1018
+ });
554
1019
  }
555
1020
 
556
- export { MEASURE_ACTION_IDS, MEASURE_AFFORDANCE_KIND, MEASURE_LAYER_ID, MEASURE_PAINTER, MEASURE_TOOLS, createMeasurements, currentMeasureId, measureAt, measureBetween, measureEndSource, measureEndsOf, measureIds, measureMagnification, measureNode, measurePose, measurementOf, measurementsContribution, useMeasureTool, useMeasureTools };
557
- //# sourceMappingURL=index.js.map
1021
+ export { MEASURE_ACTION_IDS, MEASURE_AFFORDANCE_KIND, MEASURE_LAYER_ID, MEASURE_PAINTER, MEASURE_TOOLS, MeasureReadout, createMeasurements, createMeasurementsContribution, currentMeasureId, measureBetween, measureEndSource, measureEndsOf, measureHitAt, measureIds, measureMagnification, measureNode, measurePose, measurementOf, useMeasureTool, useMeasureTools };
558
1022
  //# sourceMappingURL=index.js.map