@weasel-js/core 1.8.1 → 1.9.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.
- package/CHANGELOG.md +49 -0
- package/README.md +9 -5
- package/dist/{builtins-CMEh6-Oc.d.ts → builtins-CQcvcLXh.d.ts} +98 -31
- package/dist/canvas/DrawCanvas.js +33 -33
- package/dist/canvas/DrawCanvas.js.map +1 -1
- package/dist/canvas/MinimapCanvas.js +29 -29
- package/dist/canvas/MinimapCanvas.js.map +1 -1
- package/dist/canvas/NodeShape.js +63 -54
- package/dist/canvas/NodeShape.js.map +1 -1
- package/dist/canvas/SceneCanvas/features.js +26 -5
- package/dist/canvas/SceneCanvas/features.js.map +1 -1
- package/dist/canvas/SceneCanvas/useSceneSelectTool.js +3 -2
- package/dist/canvas/SceneCanvas/useSceneSelectTool.js.map +1 -1
- package/dist/canvas/SceneCanvas.js +526 -529
- package/dist/canvas/SceneCanvas.js.map +1 -1
- package/dist/canvas/SceneViewCanvas.js +35 -35
- package/dist/canvas/SceneViewCanvas.js.map +1 -1
- package/dist/canvas/defaultDrawOne.js +6 -1
- package/dist/canvas/defaultDrawOne.js.map +1 -1
- package/dist/canvas/pickWalk.js.map +1 -1
- package/dist/canvas/sceneAdapter.js.map +1 -1
- package/dist/canvas/useHitObserver.js +23 -0
- package/dist/canvas/useHitObserver.js.map +1 -0
- package/dist/canvas/useHostAnchor.js.map +1 -1
- package/dist/core/device/useDeviceProfile.js.map +1 -1
- package/dist/core/scene/derivedPath.js.map +1 -1
- package/dist/core/scene/effectivePose.js.map +1 -1
- package/dist/core/scene/kitRegistry.js.map +1 -1
- package/dist/core/scene/scene.js.map +1 -1
- package/dist/core/scene/types.js.map +1 -1
- package/dist/core/scene/useScene.js.map +1 -1
- package/dist/core/viewport/fitViewToBounds.js +3 -3
- package/dist/core/viewport/fitViewToBounds.js.map +1 -1
- package/dist/core/viewport/screenSlop.js +8 -2
- package/dist/core/viewport/screenSlop.js.map +1 -1
- package/dist/features/minimap/actions.js.map +1 -1
- package/dist/features/paths/markerCommands.js +95 -63
- package/dist/features/paths/markerCommands.js.map +1 -1
- package/dist/features/paths/tessellate/dash.js +52 -0
- package/dist/features/paths/tessellate/dash.js.map +1 -0
- package/dist/features/paths/tessellate/insets.js +32 -0
- package/dist/features/paths/tessellate/insets.js.map +1 -0
- package/dist/features/paths/tessellate/metric.js +72 -0
- package/dist/features/paths/tessellate/metric.js.map +1 -0
- package/dist/features/paths/tessellate/stroke.js +74 -134
- package/dist/features/paths/tessellate/stroke.js.map +1 -1
- package/dist/features/paths/tessellate/vertexWidths.js +32 -0
- package/dist/features/paths/tessellate/vertexWidths.js.map +1 -0
- package/dist/features/pointer/PointerContext.js +2 -2
- package/dist/features/pointer/PointerContext.js.map +1 -1
- package/dist/features/poseRun/usePoseRun.js.map +1 -1
- package/dist/features/text/useTextEdit.js +86 -84
- package/dist/features/text/useTextEdit.js.map +1 -1
- package/dist/index.d.ts +78 -39
- package/dist/index.js +148 -148
- package/dist/interactions/actions/defaults/align.js.map +1 -1
- package/dist/interactions/actions/defaults/anchorEditing.js.map +1 -1
- package/dist/interactions/actions/defaults/areaSelect.js.map +1 -1
- package/dist/interactions/actions/defaults/booleans.js.map +1 -1
- package/dist/interactions/actions/defaults/cancelGesture.js.map +1 -1
- package/dist/interactions/actions/defaults/clearSelection.js.map +1 -1
- package/dist/interactions/actions/defaults/clipboard.js.map +1 -1
- package/dist/interactions/actions/defaults/clone.js.map +1 -1
- package/dist/interactions/actions/defaults/createOutlines.js +1 -1
- package/dist/interactions/actions/defaults/createOutlines.js.map +1 -1
- package/dist/interactions/actions/defaults/createPaintAction.js.map +1 -1
- package/dist/interactions/actions/defaults/delete.js.map +1 -1
- package/dist/interactions/actions/defaults/distribute.js.map +1 -1
- package/dist/interactions/actions/defaults/duplicate.js.map +1 -1
- package/dist/interactions/actions/defaults/editAnchors.js.map +1 -1
- package/dist/interactions/actions/defaults/enterPathEdit.js.map +1 -1
- package/dist/interactions/actions/defaults/enterTextEdit.js.map +1 -1
- package/dist/interactions/actions/defaults/escape.js +1 -1
- package/dist/interactions/actions/defaults/escape.js.map +1 -1
- package/dist/interactions/actions/defaults/exitPathEdit.js.map +1 -1
- package/dist/interactions/actions/defaults/flip.js.map +1 -1
- package/dist/interactions/actions/defaults/group.js.map +1 -1
- package/dist/interactions/actions/defaults/ingest.js.map +1 -1
- package/dist/interactions/actions/defaults/insert.js.map +1 -1
- package/dist/interactions/actions/defaults/insertPathAnchor.js +1 -1
- package/dist/interactions/actions/defaults/insertPathAnchor.js.map +1 -1
- package/dist/interactions/actions/defaults/lassoSelect.js.map +1 -1
- package/dist/interactions/actions/defaults/move.js.map +1 -1
- package/dist/interactions/actions/defaults/nudge.js.map +1 -1
- package/dist/interactions/actions/defaults/pinchZoom.js.map +1 -1
- package/dist/interactions/actions/defaults/reorder.js.map +1 -1
- package/dist/interactions/actions/defaults/requiresSelection.js.map +1 -1
- package/dist/interactions/actions/defaults/resize.js.map +1 -1
- package/dist/interactions/actions/defaults/rotate.js.map +1 -1
- package/dist/interactions/actions/defaults/selectAll.js.map +1 -1
- package/dist/interactions/actions/defaults/slice.js.map +1 -1
- package/dist/interactions/actions/defaults/toolActivate.js.map +1 -1
- package/dist/interactions/actions/defaults/toolResetToDefault.js.map +1 -1
- package/dist/interactions/actions/defaults/undoRedo.js +1 -1
- package/dist/interactions/actions/defaults/undoRedo.js.map +1 -1
- package/dist/interactions/actions/defaults/viewportDragPan.js.map +1 -1
- package/dist/interactions/actions/defaults/viewportWheelPan.js.map +1 -1
- package/dist/interactions/actions/defaults/viewportZoom.js.map +1 -1
- package/dist/interactions/actions/planeInput.js.map +1 -1
- package/dist/interactions/gestures/shared/screenTolerance.js.map +1 -1
- package/dist/{registerProgram-ateHDGjw.d.ts → registerProgram-BMZRDgrh.d.ts} +4 -0
- package/dist/renderer/cache/markerCommandCache.js +46 -42
- package/dist/renderer/cache/markerCommandCache.js.map +1 -1
- package/dist/renderer/cache/outlineStrokeMeshCache.js +30 -25
- package/dist/renderer/cache/outlineStrokeMeshCache.js.map +1 -1
- package/dist/renderer/cache/strokeMeshCache.js +42 -31
- package/dist/renderer/cache/strokeMeshCache.js.map +1 -1
- package/dist/renderer/cullDrawCommands.js +32 -31
- package/dist/renderer/cullDrawCommands.js.map +1 -1
- package/dist/renderer/draw.js +315 -362
- package/dist/renderer/draw.js.map +1 -1
- package/dist/renderer/glyphOutlineMesh.js +67 -0
- package/dist/renderer/glyphOutlineMesh.js.map +1 -0
- package/dist/renderer/math/mat3.js +8 -3
- package/dist/renderer/math/mat3.js.map +1 -1
- package/dist/renderer/strokeLengths.js +50 -0
- package/dist/renderer/strokeLengths.js.map +1 -0
- package/dist/renderer.d.ts +2 -2
- package/dist/{test-seams-fYf6m5pu.d.ts → test-seams-CuIxe0xY.d.ts} +1 -1
- package/dist/test-seams.d.ts +2 -2
- package/dist/tools/builtin/eyedropper/useEyedropperTool.js.map +1 -1
- package/dist/tools/builtin/pen/usePenTool.js +1 -1
- package/dist/tools/builtin/pen/usePenTool.js.map +1 -1
- package/dist/tools/builtin/select/selectionContributions.js +43 -23
- package/dist/tools/builtin/select/selectionContributions.js.map +1 -1
- package/dist/tools/builtin/select/useSelectTool.js.map +1 -1
- package/dist/tools/builtin/slice/useSliceTool.js.map +1 -1
- package/dist/version.js +1 -1
- package/package.json +17 -17
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { gestureLifecycleParams as e } from "../../../interactions/actions/gestureLifecycle.js";
|
|
2
2
|
import { isAnchorOrControl as t, isResizeHandle as n, isRotateHandle as r } from "@weasel-js/routing";
|
|
3
3
|
//#region src/tools/builtin/select/selectionContributions.ts
|
|
4
|
-
var i = "selection.move", a = "selection.transform";
|
|
5
|
-
function
|
|
4
|
+
var i = "selection.move", a = "selection.transform", o = "selection.resize", s = "selection.rotate";
|
|
5
|
+
function c(n = {}) {
|
|
6
6
|
let r = (() => {
|
|
7
7
|
let t = n.move ?? {}, r = e({
|
|
8
8
|
...t,
|
|
@@ -50,60 +50,80 @@ function o(n = {}) {
|
|
|
50
50
|
}
|
|
51
51
|
];
|
|
52
52
|
}
|
|
53
|
-
function
|
|
54
|
-
let i = t.rotate ?? {}, a = e({
|
|
55
|
-
...i,
|
|
56
|
-
label: i.rotateLabel
|
|
57
|
-
});
|
|
58
|
-
i.pivot && (a.pivot = i.pivot);
|
|
59
|
-
let o = {
|
|
60
|
-
...Object.keys(a).length > 0 ? { params: a } : {},
|
|
61
|
-
...i.behaviors?.length ? { behaviors: i.behaviors } : {}
|
|
62
|
-
};
|
|
53
|
+
function l() {
|
|
63
54
|
return [{
|
|
64
55
|
spec: {
|
|
65
56
|
kind: "drag",
|
|
66
57
|
target: { kindOf: n }
|
|
67
58
|
},
|
|
68
59
|
actionId: "resize"
|
|
69
|
-
}
|
|
60
|
+
}];
|
|
61
|
+
}
|
|
62
|
+
function u(t = {}) {
|
|
63
|
+
let n = t.rotate ?? {}, i = e({
|
|
64
|
+
...n,
|
|
65
|
+
label: n.rotateLabel
|
|
66
|
+
});
|
|
67
|
+
n.pivot && (i.pivot = n.pivot);
|
|
68
|
+
let a = {
|
|
69
|
+
...Object.keys(i).length > 0 ? { params: i } : {},
|
|
70
|
+
...n.behaviors?.length ? { behaviors: n.behaviors } : {}
|
|
71
|
+
};
|
|
72
|
+
return [{
|
|
70
73
|
spec: {
|
|
71
74
|
kind: "drag",
|
|
72
75
|
target: { kindOf: r }
|
|
73
76
|
},
|
|
74
77
|
actionId: "rotate",
|
|
75
|
-
...Object.keys(
|
|
78
|
+
...Object.keys(a).length > 0 ? { opts: a } : {}
|
|
76
79
|
}];
|
|
77
80
|
}
|
|
78
|
-
function
|
|
81
|
+
function d(e = {}) {
|
|
82
|
+
return [...l(), ...u(e)];
|
|
83
|
+
}
|
|
84
|
+
function f(e = {}) {
|
|
79
85
|
return {
|
|
80
86
|
id: i,
|
|
81
87
|
eligibility: { always: !0 },
|
|
82
|
-
bindings:
|
|
88
|
+
bindings: c(e)
|
|
83
89
|
};
|
|
84
90
|
}
|
|
85
|
-
function
|
|
91
|
+
function p(e = {}) {
|
|
86
92
|
return {
|
|
87
93
|
id: a,
|
|
88
94
|
eligibility: { always: !0 },
|
|
89
|
-
bindings:
|
|
95
|
+
bindings: d(e)
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
function m() {
|
|
99
|
+
return {
|
|
100
|
+
id: o,
|
|
101
|
+
eligibility: { always: !0 },
|
|
102
|
+
bindings: l()
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
function h(e = {}) {
|
|
106
|
+
return {
|
|
107
|
+
id: s,
|
|
108
|
+
eligibility: { always: !0 },
|
|
109
|
+
bindings: u(e)
|
|
90
110
|
};
|
|
91
111
|
}
|
|
92
|
-
var
|
|
93
|
-
function
|
|
112
|
+
var g = "selection.areaSelect", _ = (e, t) => e == null && t === "empty";
|
|
113
|
+
function v() {
|
|
94
114
|
return {
|
|
95
|
-
id:
|
|
115
|
+
id: g,
|
|
96
116
|
eligibility: { always: !0 },
|
|
97
117
|
bindings: [{
|
|
98
118
|
spec: {
|
|
99
119
|
kind: "drag",
|
|
100
|
-
target: { kindOf:
|
|
120
|
+
target: { kindOf: _ }
|
|
101
121
|
},
|
|
102
122
|
actionId: "areaSelect"
|
|
103
123
|
}]
|
|
104
124
|
};
|
|
105
125
|
}
|
|
106
126
|
//#endregion
|
|
107
|
-
export {
|
|
127
|
+
export { g as AREA_SELECT_ID, i as SELECTION_MOVE_ID, o as SELECTION_RESIZE_ID, s as SELECTION_ROTATE_ID, a as SELECTION_TRANSFORM_ID, v as areaSelectContribution, _ as onEmptyCanvas, c as selectionMoveBindings, f as selectionMoveContribution, l as selectionResizeBindings, m as selectionResizeContribution, u as selectionRotateBindings, h as selectionRotateContribution, d as selectionTransformBindings, p as selectionTransformContribution };
|
|
108
128
|
|
|
109
129
|
//# sourceMappingURL=selectionContributions.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"selectionContributions.js","names":["SELECTION_MOVE_ID","SELECTION_TRANSFORM_ID","selectionMoveBindings","moveOpts","move","options","params","gestureLifecycleParams","withParams","behaviors","body","isAnchorOrControl","afford","selectionTransformBindings","rotate","opts","isResizeHandle","isRotateHandle","selectionMoveContribution","selectionTransformContribution","AREA_SELECT_ID","onEmptyCanvas","hit","areaSelectContribution"],"sources":["../../../../src/tools/builtin/select/selectionContributions.ts"],"sourcesContent":["/**\n * The ambient bindings that act on the selection: moving it, cloning it, and\n * resizing or rotating it from its handles. They belong to the selection, not\n * to the select tool, so they run under any tool that does not claim the\n * gesture itself. `<SceneCanvas features>` installs them as the `move` and\n * `transform` presets.\n */\nimport type { BindingOpts, GestureBinding } from '@weasel-js/routing';\nimport { isResizeHandle, isRotateHandle, isAnchorOrControl } from '@weasel-js/routing';\nimport type { Contribution } from '../../overlayBinding';\nimport type { UseMoveOptions } from '../../../interactions/actions/move/options';\nimport type { UseRotateOptions } from '../../../interactions/actions/rotate/options';\nimport { gestureLifecycleParams } from '../../../interactions/actions/gestureLifecycle';\n\n/** Options for {@link selectionMoveContribution}. */\nexport interface SelectionMoveOptions<TPose = unknown> {\n /** Move-action options: `behaviors` become the move bindings'\n * `opts.behaviors`, everything else their `opts.params`. */\n move?: UseMoveOptions<TPose>;\n /** Reparent-on-drop behavior for drag-to-move. `'off'` (default) keeps\n * translate-only commits. `'top'` lands the moved nodes at the top of the\n * container under the drop point; `'above'` lands them immediately above the\n * hit sibling. Requires the `nodeAtPoint` dep (`<SceneCanvas>` sources it). */\n reparentOnDrop?: 'off' | 'top' | 'above';\n}\n\n/** Id of the entry {@link selectionMoveContribution} builds. */\nexport const SELECTION_MOVE_ID = 'selection.move';\n/** Id of the entry {@link selectionTransformContribution} builds. */\nexport const SELECTION_TRANSFORM_ID = 'selection.transform';\n\n/** Drag a body to move the selection; Alt-drag to clone it. */\nexport function selectionMoveBindings<TPose>(\n options: SelectionMoveOptions<TPose> = {},\n): GestureBinding[] {\n // Shared move-binding opts (params + behaviors). Applied to\n // both the selected-body and unselected-body move bindings so a\n // first-touch drag and a re-drag commit identically.\n const moveOpts: { opts?: BindingOpts } = (() => {\n const move = options.move ?? {};\n const params: Record<string, unknown> = gestureLifecycleParams({ ...move, label: move.moveLabel });\n if (options.reparentOnDrop && options.reparentOnDrop !== 'off') params.reparentOnDrop = options.reparentOnDrop;\n if (move.dragThresholdPx !== undefined) params.dragThresholdPx = move.dragThresholdPx;\n if (move.expandIds) params.expandIds = move.expandIds;\n const withParams = Object.keys(params).length > 0 ? { params } : undefined;\n const behaviors = options.move?.behaviors?.length\n ? { behaviors: options.move.behaviors as BindingOpts['behaviors'] }\n : undefined;\n return withParams || behaviors\n ? { opts: { ...withParams, ...behaviors } satisfies BindingOpts }\n : {};\n })();\n\n return [\n // Alt-drag on a body → clone (Illustrator convention).\n // Listed BEFORE bare move so the strict-modifier dispatcher\n // picks this when Alt is held; bare move matches no-mod drags.\n // Both selected and unselected bodies are valid clone targets — the\n // select tool's pointerDown classifier calls `selection.applyClick(top, mods)`\n // on an unselected hit before the drag fires, so cloneAction's\n // `start` sees the hit node in `selection.get()` either way.\n { spec: { kind: 'drag' as const, target: 'selected-body' as const, mods: { alt: true } }, actionId: 'clone' },\n { spec: { kind: 'drag' as const, target: 'unselected-body' as const, mods: { alt: true } }, actionId: 'clone' },\n {\n // Body-drag → move, BUT defer when the pointerdown hit a path\n // anchor / control affordance. Anchors lie on the curve so the\n // body classifier still reports 'selected-body'; without this\n // opt-out, move's binding beats editAnchors's on every anchor drag.\n //\n // `isAnchorOrControl` is the SAME predicate `editAnchorsAction`\n // matches on. That is load-bearing: the two must agree on what\n // counts as an anchor hit or move steals the drag — which is\n // exactly the bug this opt-out exists to prevent.\n spec: {\n kind: 'drag' as const,\n target: {\n kindOf: (afford: unknown, body?: string): boolean =>\n body === 'selected-body' && !isAnchorOrControl(afford),\n },\n },\n actionId: 'move',\n ...moveOpts,\n },\n // Body-drag on a NOT-yet-selected node → also move. The select tool's\n // pointerDown classifier selects the hit node before the drag fires (same\n // contract clone relies on), so by the time moveAction.start() runs the\n // node is in `selection.get()`. Without this binding an unselected-body\n // drag falls through to whatever ambient drag binding comes next — once\n // the `rotate` catch-all, which made the first drag rotate and later ones\n // move. Unselected nodes never carry anchor affordances (those gate on\n // selection), so the plain string-form target is sufficient here.\n {\n spec: { kind: 'drag' as const, target: 'unselected-body' as const },\n actionId: 'move',\n ...moveOpts,\n },\n ];\n}\n\n/** Options for {@link selectionTransformContribution}. Resize takes its\n * options through the `resizePolicy` dep (`useResizePolicy`), not here. */\nexport interface SelectionTransformOptions<TPose = unknown> {\n /** Rotate-action options: `behaviors` become the rotate binding's\n * `opts.behaviors`, everything else its `opts.params`. */\n rotate?: UseRotateOptions<TPose>;\n}\n\n/** Drag a resize handle to resize the selection, the rotation handle to rotate it. */\nexport function selectionTransformBindings<TPose>(\n options: SelectionTransformOptions<TPose> = {},\n): GestureBinding[] {\n const rotate = options.rotate ?? {};\n const params: Record<string, unknown> = gestureLifecycleParams({ ...rotate, label: rotate.rotateLabel });\n if (rotate.pivot) params.pivot = rotate.pivot;\n const opts: BindingOpts = {\n ...(Object.keys(params).length > 0 ? { params } : {}),\n ...(rotate.behaviors?.length ? { behaviors: rotate.behaviors as BindingOpts['behaviors'] } : {}),\n };\n return [\n { spec: { kind: 'drag' as const, target: { kindOf: isResizeHandle } }, actionId: 'resize' },\n {\n spec: { kind: 'drag' as const, target: { kindOf: isRotateHandle } },\n actionId: 'rotate',\n ...(Object.keys(opts).length > 0 ? { opts } : {}),\n },\n ];\n}\n\n/** An always-live entry carrying {@link selectionMoveBindings}. Add it to a\n * canvas's ambient list; `<SceneCanvas features={['move']}>` does. */\nexport function selectionMoveContribution<TPose>(\n options: SelectionMoveOptions<TPose> = {},\n): Contribution {\n return {\n id: SELECTION_MOVE_ID,\n eligibility: { always: true },\n bindings: selectionMoveBindings(options),\n };\n}\n\n/** An always-live entry carrying {@link selectionTransformBindings}. Add it\n * to a canvas's ambient list; `<SceneCanvas features={['transform']}>` does. */\nexport function selectionTransformContribution<TPose>(\n options: SelectionTransformOptions<TPose> = {},\n): Contribution {\n return {\n id: SELECTION_TRANSFORM_ID,\n eligibility: { always: true },\n bindings: selectionTransformBindings(options),\n };\n}\n\n/** Id of the entry {@link areaSelectContribution} builds. */\nexport const AREA_SELECT_ID = 'selection.areaSelect';\n\n/** A press on empty canvas: no hit, and not on chrome over it — the rotation\n * handle and the outer half of a resize handle sit off the body. */\nexport const onEmptyCanvas = (hit: unknown, body?: string): boolean => hit == null && body === 'empty';\n\n/** An always-live entry that marquee-selects on a drag across empty canvas,\n * under any tool that does not claim the drag itself. No preset installs it:\n * the select tool already marquees, and a canvas that wants it under every\n * tool adds this to its ambient list. */\nexport function areaSelectContribution(): Contribution {\n return {\n id: AREA_SELECT_ID,\n eligibility: { always: true },\n bindings: [{ spec: { kind: 'drag', target: { kindOf: onEmptyCanvas } }, actionId: 'areaSelect' }],\n };\n}\n"],"mappings":";;;AA2BA,IAAaA,IAAoB,kBAEpBC,IAAyB;AAGtC,SAAgBC,EACd,IAAuC,CAAC,GACtB;CAIlB,IAAMC,WAA0C;EAC9C,IAAMC,IAAOC,EAAQ,QAAQ,CAAC,GACxBC,IAAkCC,EAAuB;GAAE,GAAGH;GAAM,OAAOA,EAAK;EAAU,CAAC;EAGjG,AAFIC,EAAQ,kBAAkBA,EAAQ,mBAAmB,UAAO,EAAO,iBAAiBA,EAAQ,iBAC5FD,EAAK,oBAAoB,KAAA,MAAW,EAAO,kBAAkBA,EAAK,kBAClEA,EAAK,cAAW,EAAO,YAAYA,EAAK;EAC5C,IAAMI,IAAa,OAAO,KAAKF,CAAM,CAAC,CAAC,SAAS,IAAI,EAAE,UAAO,IAAI,KAAA,GAC3DG,IAAYJ,EAAQ,MAAM,WAAW,SACvC,EAAE,WAAWA,EAAQ,KAAK,UAAsC,IAChE,KAAA;EACJ,OAAOG,KAAcC,IACjB,EAAE,MAAM;GAAE,GAAGD;GAAY,GAAGC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B,UAAUE,EAAsBG,CAAO;CACzC;AACF;AAIA,SAAgBc,EACd,IAA4C,CAAC,GAC/B;CACd,OAAO;EACL,IAAIlB;EACJ,aAAa,EAAE,QAAQ,GAAK;EAC5B,UAAUY,EAA2BR,CAAO;CAC9C;AACF;AAGA,IAAae,IAAiB,wBAIjBC,KAAiB,GAAc,MAA2BC,KAAO,QAAQZ,MAAS;AAM/F,SAAgBa,IAAuC;CACrD,OAAO;EACL,IAAIH;EACJ,aAAa,EAAE,QAAQ,GAAK;EAC5B,UAAU,CAAC;GAAE,MAAM;IAAE,MAAM;IAAQ,QAAQ,EAAE,QAAQC,EAAc;GAAE;GAAG,UAAU;EAAa,CAAC;CAClG;AACF"}
|
|
1
|
+
{"version":3,"file":"selectionContributions.js","names":["SELECTION_MOVE_ID","SELECTION_TRANSFORM_ID","SELECTION_RESIZE_ID","SELECTION_ROTATE_ID","selectionMoveBindings","moveOpts","move","options","params","gestureLifecycleParams","withParams","behaviors","body","isAnchorOrControl","afford","selectionResizeBindings","isResizeHandle","selectionRotateBindings","rotate","opts","isRotateHandle","selectionTransformBindings","selectionMoveContribution","selectionTransformContribution","selectionResizeContribution","selectionRotateContribution","AREA_SELECT_ID","onEmptyCanvas","hit","areaSelectContribution"],"sources":["../../../../src/tools/builtin/select/selectionContributions.ts"],"sourcesContent":["/**\n * The ambient bindings that act on the selection: moving it, cloning it, and\n * resizing or rotating it from its handles. They belong to the selection, not\n * to the select tool, so they run under any tool that does not claim the\n * gesture itself. `<SceneCanvas features>` installs them as the `move`,\n * `resize` and `rotate` presets.\n */\nimport type { BindingOpts, GestureBinding } from '@weasel-js/routing';\nimport { isResizeHandle, isRotateHandle, isAnchorOrControl } from '@weasel-js/routing';\nimport type { Contribution } from '../../overlayBinding';\nimport type { UseMoveOptions } from '../../../interactions/actions/move/options';\nimport type { UseRotateOptions } from '../../../interactions/actions/rotate/options';\nimport { gestureLifecycleParams } from '../../../interactions/actions/gestureLifecycle';\n\n/** Options for {@link selectionMoveContribution}. */\nexport interface SelectionMoveOptions<TPose = unknown> {\n /** Move-action options: `behaviors` become the move bindings'\n * `opts.behaviors`, everything else their `opts.params`. */\n move?: UseMoveOptions<TPose>;\n /** Reparent-on-drop behavior for drag-to-move. `'off'` (default) keeps\n * translate-only commits. `'top'` lands the moved nodes at the top of the\n * container under the drop point; `'above'` lands them immediately above the\n * hit sibling. Requires the `nodeAtPoint` dep (`<SceneCanvas>` sources it). */\n reparentOnDrop?: 'off' | 'top' | 'above';\n}\n\n/** Id of the entry {@link selectionMoveContribution} builds. */\nexport const SELECTION_MOVE_ID = 'selection.move';\n/** Id of the entry {@link selectionTransformContribution} builds. */\nexport const SELECTION_TRANSFORM_ID = 'selection.transform';\n/** Id of the entry {@link selectionResizeContribution} builds. */\nexport const SELECTION_RESIZE_ID = 'selection.resize';\n/** Id of the entry {@link selectionRotateContribution} builds. */\nexport const SELECTION_ROTATE_ID = 'selection.rotate';\n\n/** Drag a body to move the selection; Alt-drag to clone it. */\nexport function selectionMoveBindings<TPose>(\n options: SelectionMoveOptions<TPose> = {},\n): GestureBinding[] {\n // Shared move-binding opts (params + behaviors). Applied to\n // both the selected-body and unselected-body move bindings so a\n // first-touch drag and a re-drag commit identically.\n const moveOpts: { opts?: BindingOpts } = (() => {\n const move = options.move ?? {};\n const params: Record<string, unknown> = gestureLifecycleParams({ ...move, label: move.moveLabel });\n if (options.reparentOnDrop && options.reparentOnDrop !== 'off') params.reparentOnDrop = options.reparentOnDrop;\n if (move.dragThresholdPx !== undefined) params.dragThresholdPx = move.dragThresholdPx;\n if (move.expandIds) params.expandIds = move.expandIds;\n const withParams = Object.keys(params).length > 0 ? { params } : undefined;\n const behaviors = options.move?.behaviors?.length\n ? { behaviors: options.move.behaviors as BindingOpts['behaviors'] }\n : undefined;\n return withParams || behaviors\n ? { opts: { ...withParams, ...behaviors } satisfies BindingOpts }\n : {};\n })();\n\n return [\n // Alt-drag on a body → clone (Illustrator convention).\n // Listed BEFORE bare move so the strict-modifier dispatcher\n // picks this when Alt is held; bare move matches no-mod drags.\n // Both selected and unselected bodies are valid clone targets — the\n // select tool's pointerDown classifier calls `selection.applyClick(top, mods)`\n // on an unselected hit before the drag fires, so cloneAction's\n // `start` sees the hit node in `selection.get()` either way.\n { spec: { kind: 'drag' as const, target: 'selected-body' as const, mods: { alt: true } }, actionId: 'clone' },\n { spec: { kind: 'drag' as const, target: 'unselected-body' as const, mods: { alt: true } }, actionId: 'clone' },\n {\n // Body-drag → move, BUT defer when the pointerdown hit a path\n // anchor / control affordance. Anchors lie on the curve so the\n // body classifier still reports 'selected-body'; without this\n // opt-out, move's binding beats editAnchors's on every anchor drag.\n //\n // `isAnchorOrControl` is the SAME predicate `editAnchorsAction`\n // matches on. That is load-bearing: the two must agree on what\n // counts as an anchor hit or move steals the drag — which is\n // exactly the bug this opt-out exists to prevent.\n spec: {\n kind: 'drag' as const,\n target: {\n kindOf: (afford: unknown, body?: string): boolean =>\n body === 'selected-body' && !isAnchorOrControl(afford),\n },\n },\n actionId: 'move',\n ...moveOpts,\n },\n // Body-drag on a NOT-yet-selected node → also move. The select tool's\n // pointerDown classifier selects the hit node before the drag fires (same\n // contract clone relies on), so by the time moveAction.start() runs the\n // node is in `selection.get()`. Without this binding an unselected-body\n // drag falls through to whatever ambient drag binding comes next — once\n // the `rotate` catch-all, which made the first drag rotate and later ones\n // move. Unselected nodes never carry anchor affordances (those gate on\n // selection), so the plain string-form target is sufficient here.\n {\n spec: { kind: 'drag' as const, target: 'unselected-body' as const },\n actionId: 'move',\n ...moveOpts,\n },\n ];\n}\n\n/** Options for {@link selectionRotateContribution}. */\nexport interface SelectionRotateOptions<TPose = unknown> {\n /** Rotate-action options: `behaviors` become the rotate binding's\n * `opts.behaviors`, everything else its `opts.params`. */\n rotate?: UseRotateOptions<TPose>;\n}\n\n/** Options for {@link selectionTransformContribution}. Resize takes its\n * options through the `resizePolicy` dep (`useResizePolicy`), not here. */\nexport type SelectionTransformOptions<TPose = unknown> = SelectionRotateOptions<TPose>;\n\n/** Drag a resize handle to resize the selection. Options come through the\n * `resizePolicy` dep (`useResizePolicy`). */\nexport function selectionResizeBindings(): GestureBinding[] {\n return [{ spec: { kind: 'drag' as const, target: { kindOf: isResizeHandle } }, actionId: 'resize' }];\n}\n\n/** Drag the rotation handle to rotate the selection. */\nexport function selectionRotateBindings<TPose>(\n options: SelectionRotateOptions<TPose> = {},\n): GestureBinding[] {\n const rotate = options.rotate ?? {};\n const params: Record<string, unknown> = gestureLifecycleParams({ ...rotate, label: rotate.rotateLabel });\n if (rotate.pivot) params.pivot = rotate.pivot;\n const opts: BindingOpts = {\n ...(Object.keys(params).length > 0 ? { params } : {}),\n ...(rotate.behaviors?.length ? { behaviors: rotate.behaviors as BindingOpts['behaviors'] } : {}),\n };\n return [{\n spec: { kind: 'drag' as const, target: { kindOf: isRotateHandle } },\n actionId: 'rotate',\n ...(Object.keys(opts).length > 0 ? { opts } : {}),\n }];\n}\n\n/** Drag a resize handle to resize the selection, the rotation handle to rotate it. */\nexport function selectionTransformBindings<TPose>(\n options: SelectionTransformOptions<TPose> = {},\n): GestureBinding[] {\n return [...selectionResizeBindings(), ...selectionRotateBindings(options)];\n}\n\n/** An always-live entry carrying {@link selectionMoveBindings}. Add it to a\n * canvas's ambient list; `<SceneCanvas features={['move']}>` does. */\nexport function selectionMoveContribution<TPose>(\n options: SelectionMoveOptions<TPose> = {},\n): Contribution {\n return {\n id: SELECTION_MOVE_ID,\n eligibility: { always: true },\n bindings: selectionMoveBindings(options),\n };\n}\n\n/** An always-live entry carrying {@link selectionTransformBindings}: resize\n * and rotate in one entry, what `<SceneCanvas features={['transform']}>`\n * turns on. */\nexport function selectionTransformContribution<TPose>(\n options: SelectionTransformOptions<TPose> = {},\n): Contribution {\n return {\n id: SELECTION_TRANSFORM_ID,\n eligibility: { always: true },\n bindings: selectionTransformBindings(options),\n };\n}\n\n/** An always-live entry carrying {@link selectionResizeBindings}. Add it to a\n * canvas's ambient list; `<SceneCanvas features={['resize']}>` does. */\nexport function selectionResizeContribution(): Contribution {\n return {\n id: SELECTION_RESIZE_ID,\n eligibility: { always: true },\n bindings: selectionResizeBindings(),\n };\n}\n\n/** An always-live entry carrying {@link selectionRotateBindings}. Add it to a\n * canvas's ambient list; `<SceneCanvas features={['rotate']}>` does. */\nexport function selectionRotateContribution<TPose>(\n options: SelectionRotateOptions<TPose> = {},\n): Contribution {\n return {\n id: SELECTION_ROTATE_ID,\n eligibility: { always: true },\n bindings: selectionRotateBindings(options),\n };\n}\n\n/** Id of the entry {@link areaSelectContribution} builds. */\nexport const AREA_SELECT_ID = 'selection.areaSelect';\n\n/** A press on empty canvas: no hit, and not on chrome over it — the rotation\n * handle and the outer half of a resize handle sit off the body. */\nexport const onEmptyCanvas = (hit: unknown, body?: string): boolean => hit == null && body === 'empty';\n\n/** An always-live entry that marquee-selects on a drag across empty canvas,\n * under any tool that does not claim the drag itself. No preset installs it:\n * the select tool already marquees, and a canvas that wants it under every\n * tool adds this to its ambient list. */\nexport function areaSelectContribution(): Contribution {\n return {\n id: AREA_SELECT_ID,\n eligibility: { always: true },\n bindings: [{ spec: { kind: 'drag', target: { kindOf: onEmptyCanvas } }, actionId: 'areaSelect' }],\n };\n}\n"],"mappings":";;;AA2BA,IAAaA,IAAoB,kBAEpBC,IAAyB,uBAEzBC,IAAsB,oBAEtBC,IAAsB;AAGnC,SAAgBC,EACd,IAAuC,CAAC,GACtB;CAIlB,IAAMC,WAA0C;EAC9C,IAAMC,IAAOC,EAAQ,QAAQ,CAAC,GACxBC,IAAkCC,EAAuB;GAAE,GAAGH;GAAM,OAAOA,EAAK;EAAU,CAAC;EAGjG,AAFIC,EAAQ,kBAAkBA,EAAQ,mBAAmB,UAAO,EAAO,iBAAiBA,EAAQ,iBAC5FD,EAAK,oBAAoB,KAAA,MAAW,EAAO,kBAAkBA,EAAK,kBAClEA,EAAK,cAAW,EAAO,YAAYA,EAAK;EAC5C,IAAMI,IAAa,OAAO,KAAKF,CAAM,CAAC,CAAC,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,EAAE,QAAQE,EAAe;EAAE;EAClE,UAAU;EACV,GAAI,OAAO,KAAKD,CAAI,CAAC,CAAC,SAAS,IAAI,EAAE,QAAK,IAAI,CAAC;CACjD,CAAC;AACH;AAGA,SAAgBE,EACd,IAA4C,CAAC,GAC3B;CAClB,OAAO,CAAC,GAAGN,EAAwB,GAAG,GAAGE,EAAwBV,CAAO,CAAC;AAC3E;AAIA,SAAgBe,EACd,IAAuC,CAAC,GAC1B;CACd,OAAO;EACL,IAAItB;EACJ,aAAa,EAAE,QAAQ,GAAK;EAC5B,UAAUI,EAAsBG,CAAO;CACzC;AACF;AAKA,SAAgBgB,EACd,IAA4C,CAAC,GAC/B;CACd,OAAO;EACL,IAAItB;EACJ,aAAa,EAAE,QAAQ,GAAK;EAC5B,UAAUoB,EAA2Bd,CAAO;CAC9C;AACF;AAIA,SAAgBiB,IAA4C;CAC1D,OAAO;EACL,IAAItB;EACJ,aAAa,EAAE,QAAQ,GAAK;EAC5B,UAAUa,EAAwB;CACpC;AACF;AAIA,SAAgBU,EACd,IAAyC,CAAC,GAC5B;CACd,OAAO;EACL,IAAItB;EACJ,aAAa,EAAE,QAAQ,GAAK;EAC5B,UAAUc,EAAwBV,CAAO;CAC3C;AACF;AAGA,IAAamB,IAAiB,wBAIjBC,KAAiB,GAAc,MAA2BC,KAAO,QAAQhB,MAAS;AAM/F,SAAgBiB,IAAuC;CACrD,OAAO;EACL,IAAIH;EACJ,aAAa,EAAE,QAAQ,GAAK;EAC5B,UAAU,CAAC;GAAE,MAAM;IAAE,MAAM;IAAQ,QAAQ,EAAE,QAAQC,EAAc;GAAE;GAAG,UAAU;EAAa,CAAC;CAClG;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useSelectTool.js","names":["SelectIcon","useSelectTool","d","options","AUTO_POSE_DESCRIPTOR","preciseLeaves","tolerance","pickEveryFn","pointQuery","covers","slop","t","px","b","py","shapeCoversPoint","node","pose","poseDescriptorForNode","own","ownClipOf","pathContainsPoint","clip","p","toPlane","m","meanScale","camera","planeOf","scenePlaneOf","adapter","pickWalk","adapterPickSource","worldX","worldY","pickEveryRef","useLatest","pressRef","useRef","optionsRef","adapterRef","pickAction","useMemo","params","selection","deps","mods","opts","sel","top","ids","pickTopMostHit","hitAlreadySelected","isExtend","extendLocked","deferClick","collapseDeferredAction","ActionDisabledReason","deferred","defineTool","createElement","hit","onEmptyCanvas","body"],"sources":["../../../../src/tools/builtin/select/useSelectTool.ts"],"sourcesContent":["import { useMemo, useRef, createElement } from 'react';\nimport { useLatest } from '@weasel-js/react';\nimport { SelectIcon } from '../../../icons';\nimport { pathContainsPoint } from '@weasel-js/geom';\nimport { shapeCoversPoint } from 'canvas/NodeShape';\nimport { pickWalk, adapterPickSource, ownClipOf, scenePlaneOf, type PickQuery } from 'canvas/pickWalk';\nimport { toPlane } from 'core/viewport/parallax';\nimport { meanScale } from 'core/viewport/meanScale';\nimport type { View } from 'core/viewport/view';\nimport type { LayerEnumerableAdapter } from 'core/adapters/types';\nimport type { Node } from 'core/scene/types';\nimport type { MoveAdapter } from 'core/adapters/types';\nimport type { AreaSelectAdapter } from 'core/adapters/types';\nimport type { NodeId } from 'core/scene/types';\nimport { defineTool } from '../../overlayBinding';\nimport type { Action } from '@weasel-js/routing';\nimport { ActionDisabledReason } from '@weasel-js/routing';\nimport type { SelectionApi } from 'core/selection/useSelection';\nimport type { Tool } from '../../overlayBinding';\nimport { pickTopMostHit } from '../pickTopMostHit';\nimport { onEmptyCanvas } from './selectionContributions';\nimport { poseDescriptorForNode, type PoseDescriptor } from 'core/geometry/poseDescriptor';\nimport { AUTO_POSE_DESCRIPTOR } from 'interactions/actions/resize/autoPoseDescriptor';\nimport { MULTI_RESIZE_TARGET_ID, type Bounds } from '../shared/selectionTarget';\nexport type { Bounds };\nexport { MULTI_RESIZE_TARGET_ID };\n\n/** Options for `useSelectTool`: how a point resolves to nodes, how a click\n * chooses among them, and the appearance of the marquee. */\nexport interface UseSelectToolOptions<TPose> {\n /** Return ids of all objects whose painted body covers (worldX, worldY).\n * Order doesn't matter — the tool collapses parent/child overlap via\n * `pickTopMostHit`. When omitted, defaults to an AABB-vs-point scan over\n * `adapter.getNodes()` using the pose descriptor. Override for tighter\n * shapes (path / polygon hit-tests). */\n pickEvery?: (worldX: number, worldY: number) => string[];\n /** Optional alt-aware selection-update hit returning the single id the\n * click should act on. */\n pickBest?: (\n worldX: number,\n worldY: number,\n alt: boolean,\n selection: readonly string[],\n ) => string | null;\n /** How to read poses for the default `pickEvery`. Default\n * `AUTO_POSE_DESCRIPTOR`. */\n poseDescriptor?: PoseDescriptor<TPose>;\n /**\n * How the default `pickEvery` decides a **leaf** node covers the pointer.\n * Ignored when `pickEvery` is supplied.\n *\n * - `'aabb'` (default) — the pose rect. Cheap, and the historical behavior:\n * a click anywhere in the bounding box selects the node.\n * - `'silhouette'` — the pose rect as a pre-test, then the ink the painter\n * lays down: `findShapeSilhouette` filled or not per the painter's `ink`,\n * plus its outline widened by the stroke half-width and `pickTolerance`.\n * A click inside the bounding box but outside the drawn shape misses —\n * the concave notch of a star, the corner outside an ellipse, the blank\n * half of a text box — while a click on the thin outline of an unfilled\n * shape hits.\n *\n * Container nodes already consult their silhouette unconditionally (it is\n * how their clip is derived); this extends the same test to leaves. Not the\n * default because it changes what a click selects for every existing\n * consumer, and a painter with no `silhouette` is unaffected either way —\n * it falls back to the AABB.\n */\n leafPicking?: 'aabb' | 'silhouette';\n /**\n * Grab slop around a shape's outline, in **world** units. Default 0.\n *\n * Only consulted under `leafPicking: 'silhouette'`. World units because\n * this hook has no view; `<SceneCanvas>` takes a screen-pixel figure\n * (`geometry.pickTolerancePx`) and divides by scale on its own pick path.\n * Without some slop a hairline outline is an unhittable target.\n */\n pickTolerance?: number;\n /** Painted alpha per node in the view this tool picks for. A node painted\n * at alpha 0 is not under the pointer. Ignored when `pickEvery` is\n * supplied. */\n alphaOf?: (id: string) => number;\n /** Whether a node's `layer` reaches the screen in the view this tool picks\n * for. Ignored when `pickEvery` is supplied. */\n layerIsPainted?: (layer: string) => boolean;\n /** The camera of the view this tool picks for. With it, a node on an\n * adapter layer carrying `parallax` (`getLayers`) is picked where that\n * camera's plane paints it; without it, every layer is taken to move with\n * the camera. Ignored when `pickEvery` is supplied. */\n getView?: () => View | null;\n /**\n * When this returns true, a Shift/Meta extend-click must NOT change the\n * node selection.\n *\n * `<SceneCanvas>` wires it to \"a path is in anchor-edit mode\", where\n * Shift-click means \"add this anchor to the anchor selection\". Without\n * the lock the same click also toggles the edited node out of the node\n * selection, and the `editAnchors` dep treats that as the edit target\n * disappearing — so multi-selecting anchors silently exited edit mode.\n *\n * Only extend-clicks are locked. A plain click still re-selects, so\n * clicking a different node exits edit mode as usual.\n */\n extendClickLocked?: () => boolean;\n}\n\n/** Intersection of the move + area-select adapter interfaces.\n * Resize and rotate run through `resizeAction` / `rotateAction`. */\nexport type SelectAdapter<TNode extends { id: string }, TPose> =\n MoveAdapter<TNode, TPose>\n & AreaSelectAdapter\n & LayerEnumerableAdapter;\n\n/**\n * What the press classified, carried from `select.pick` (pointerDown) to\n * `select.collapseDeferred` (click) and to the tool's cursor.\n *\n * This is tool-local bookkeeping between two dispatches of the same gesture,\n * so it lives in a ref the tool owns rather than in dispatcher state. It used\n * to be the tool's `SelectScratch`, held by the tool-routing dispatcher, and\n * carried an `ids` list that nothing ever read — `moveAction` computes its own\n * ids from the live selection.\n *\n * @internal\n */\ninterface PressClassification {\n /**\n * Set when the press hit an already-selected node inside a multi-selection\n * with no extend modifier.\n *\n * The selection is deliberately NOT collapsed on the press: the user may be\n * starting a drag of the whole set. If the gesture turns out to be a click,\n * `select.collapseDeferred` collapses to this id on release.\n */\n deferredClickId: string | null;\n}\n\n/** Active-slot Tool:\n * - `select.pick` classifies the press (pointerDown) — it runs the tool's own\n * pickBest/pickEvery so click semantics (selection replace, extend,\n * deferred collapse) live in one place.\n * - an empty drag marquees (`areaSelect`) and a click on empty clears the\n * selection (`clearSelection`); the marquee renders via the dispatcher\n * overlay layer, driven by areaSelectAction's `overlay()`.\n * - moving and transforming the selection are not the tool's: they are the\n * ambient bindings in `selectionContributions.ts`.\n */\nexport function useSelectTool<TNode extends { id: string }, TPose>(\n adapter: SelectAdapter<TNode, TPose>,\n options: UseSelectToolOptions<TPose>,\n): Tool<null> {\n\n // pickEvery / boundsOf defaults — for any adapter the kit can derive both\n // from `adapter.getNodes()` + `adapter.getPose(id)` + the descriptor.\n const d = (options.poseDescriptor ?? AUTO_POSE_DESCRIPTOR) as PoseDescriptor<TPose>;\n const preciseLeaves = options.leafPicking === 'silhouette';\n // World units here, not screen: this hook has no view. `<SceneCanvas>`\n // converts from screen px on its own pick path; a bare `useSelectTool`\n // consumer that zooms should pass `pickTolerance` from its own scale.\n const tolerance = options.pickTolerance ?? 0;\n const pickEveryFn = options.pickEvery ?? ((worldX: number, worldY: number): string[] => {\n /** A point query at (px, py) with `t` world units of slop. AABB first\n * (cheap), then the painter's ink when asked for and available. A painter\n * with no `silhouette` — or one that returns null, as `kit:text` does for\n * an empty node — keeps the AABB answer.\n *\n * The AABB pre-filter is grown by the slop for the same reason\n * `<SceneCanvas>`'s is: a shape's outline, and the slop around it, reach\n * outside the shape's own bounds, and an un-grown pre-filter would\n * discard those hits before the refinement could claim them. */\n const pointQuery = (px: number, py: number, t: number): PickQuery<TPose> => {\n const covers = (node: unknown, pose: TPose, b: Bounds): boolean => {\n const slop = preciseLeaves ? t : 0;\n if (!(px >= b.x - slop && px <= b.x + b.width + slop\n && py >= b.y - slop && py <= b.y + b.height + slop)) {\n return false;\n }\n if (!preciseLeaves) return true;\n return shapeCoversPoint(\n node as Node<unknown, string, TPose>, pose, px, py, { tolerance: t },\n );\n };\n return {\n hits: (node, pose) => {\n const b = poseDescriptorForNode(d, node).getBounds(pose);\n if (node.kind !== 'container') return covers(node, pose, b);\n // A container's own clip *is* its hit shape — it is picked where it\n // paints, and it paints only inside its clip. Ancestor clips are the\n // walk's business; this one is not.\n const inAabb = px >= b.x && px <= b.x + b.width\n && py >= b.y && py <= b.y + b.height;\n if (!inAabb) return false;\n const own = ownClipOf(node, pose);\n return own === null || pathContainsPoint(own, px, py);\n },\n clipAdmits: (clip) => pathContainsPoint(clip, px, py),\n inPlane: (m) => {\n const p = toPlane(m, { x: px, y: py });\n return pointQuery(p.x, p.y, t * meanScale(m.scale));\n },\n };\n };\n\n const camera = options.getView?.() ?? null;\n const planeOf = camera ? scenePlaneOf(adapter.getLayers?.(), camera) : null;\n return pickWalk<TPose>(adapterPickSource(adapter as never, {\n ...(options.alphaOf ? { alphaOf: options.alphaOf } : {}),\n ...(options.layerIsPainted ? { layerIsPainted: options.layerIsPainted } : {}),\n ...(planeOf ? { planeOf } : {}),\n }), pointQuery(worldX, worldY, tolerance));\n });\n\n const pickEveryRef = useLatest(pickEveryFn);\n\n // What the last press classified. Written by `select.pick`, read by\n // `select.collapseDeferred` and the cursor. See `PressClassification`.\n const pressRef = useRef<PressClassification>({ deferredClickId: null });\n\n // Options in a ref so the actions — built once — always see the live\n // callbacks without rebuilding the Tool record.\n const optionsRef = useLatest(options);\n const adapterRef = useLatest(adapter);\n\n /**\n * `select.pick` — classifies the press and updates the node selection.\n *\n * Bound to `pointerDown` rather than `click` on purpose: pressing an\n * unselected node must highlight it while the button is still down, and any\n * drag that follows has to start from the updated selection (both\n * `moveAction` and `cloneAction` read `selection.get()` in their `start`).\n *\n * Eligibility replaces the `selectionAllowed` option the audit added as an\n * interim per-route patch: this action carries the same\n * `creates-selection` capability rule the `clearSelection` binding declares,\n * so a mode that forbids selection now gates both halves of the tool by one\n * mechanism instead of by which dispatcher the route happened to live on.\n */\n const pickAction = useMemo<Action>(() => ({\n id: 'select.pick',\n label: 'Select — pick under pointer',\n eligible: { capability: 'creates-selection' },\n requires: ['selection'],\n invoker: {\n timing: 'immediate' as const,\n run: (deps, params) => {\n const p = params as {\n worldX?: number; worldY?: number;\n affordance?: unknown;\n mods?: { alt: boolean; ctrl: boolean; meta: boolean; shift: boolean };\n } | undefined;\n const selection = deps.selection as SelectionApi | undefined;\n if (!selection || p?.worldX === undefined || p.worldY === undefined) return;\n const mods = p.mods ?? { alt: false, ctrl: false, meta: false, shift: false };\n const opts = optionsRef.current;\n\n const sel = selection.get();\n const top = opts.pickBest\n ? opts.pickBest(p.worldX, p.worldY, mods.alt, sel)\n : (() => {\n const ids = pickEveryRef.current(p.worldX, p.worldY);\n if (ids.length === 0) return null;\n return pickTopMostHit(ids, adapterRef.current) ?? ids[0];\n })();\n\n if (top === null) {\n pressRef.current = { deferredClickId: null };\n return;\n }\n\n const hitAlreadySelected = sel.includes(top as NodeId);\n const isExtend = mods.shift || mods.meta;\n // While a path is in anchor-edit mode, an extend-click belongs to the\n // anchor selection, not the node selection. Letting it through would\n // toggle the edited node out of the node selection, which the\n // `editAnchors` dep reads as \"the edit target is gone\" — so\n // shift-clicking a second anchor silently tore down edit mode.\n // Plain clicks still fall through: clicking a different node exits\n // edit mode, which is what you'd expect.\n //\n // This stays an option rather than becoming `Action.enabled` because\n // it only applies to *extend* presses, and `enabled` is evaluated\n // without the event's modifiers.\n const extendLocked = isExtend && opts.extendClickLocked?.() === true;\n const deferClick = hitAlreadySelected && sel.length > 1 && !isExtend;\n if (!deferClick && !extendLocked) {\n selection.applyClick(top as NodeId, mods);\n }\n pressRef.current = { deferredClickId: deferClick ? top : null };\n },\n },\n }), [optionsRef, pickEveryRef, adapterRef]);\n\n /**\n * `select.collapseDeferred` — the release half of the deferred multi-click.\n *\n * Pressing an already-selected node inside a multi-selection leaves the\n * selection alone so the press can start a drag of the whole set. If the\n * gesture ends without a drag, this collapses to the clicked node.\n */\n const collapseDeferredAction = useMemo<Action>(() => ({\n id: 'select.collapseDeferred',\n label: 'Select — collapse deferred click',\n eligible: { capability: 'creates-selection' },\n requires: ['selection'],\n // Declining when there is nothing deferred is what keeps this binding\n // from swallowing every click. It is bound with no target (any click can\n // in principle be the release of a deferred press) at ACTIVE scope, so\n // without the gate it would outrank ambient click bindings like\n // `selectAnchor` and silently break anchor selection. Same fall-through\n // contract `clearSelection.enabled` relies on.\n enabled: () =>\n pressRef.current.deferredClickId !== null\n ? true\n : ActionDisabledReason.NotApplicable,\n invoker: {\n timing: 'immediate' as const,\n run: (deps, params) => {\n const deferred = pressRef.current.deferredClickId;\n pressRef.current = { deferredClickId: null };\n if (deferred === null) return;\n const selection = deps.selection as SelectionApi | undefined;\n if (!selection) return;\n const p = params as {\n mods?: { alt: boolean; ctrl: boolean; meta: boolean; shift: boolean };\n } | undefined;\n selection.applyClick(\n deferred as NodeId,\n p?.mods ?? { alt: false, ctrl: false, meta: false, shift: false },\n );\n },\n },\n }), []);\n\n return useMemo(\n () => {\n const base = defineTool<null>({\n id: 'select',\n capabilities: ['creates-selection'],\n hookName: 'useSelectTool',\n // A plain string: the mid-gesture cursors this used to compute from\n // gesture scratch now live on the actions that own those gestures\n // (`moveAction.activeCursor`, `areaSelectAction.activeCursor`), so\n // they apply to any consumer binding them, not just this tool.\n cursor: 'default',\n presentation: {\n label: 'Select',\n icon: createElement(SelectIcon),\n group: 'select',\n },\n actions: [pickAction, collapseDeferredAction],\n });\n\n return {\n ...base,\n // Declarative bindings for the gesture dispatcher. The select tool\n // only chooses: press → classify + select, release → collapse a\n // deferred multi-click, empty drag → marquee, click on empty → clear.\n // Moving, cloning, resizing and rotating the selection are ambient\n // bindings owned by the selection (`selectionContributions.ts`), so\n // they run under any tool that leaves the gesture unclaimed.\n bindings: [\n // Every press that landed on the scene rather than on chrome. This\n // is the former `initial.pointerDown['*']` route: it classifies the\n // press and applies the selection change, and it does not consume\n // the gesture — the same press goes on to open a drag or synthesize\n // a click.\n //\n // The no-affordance target is load-bearing twice over. A press on a\n // resize handle, a rotate ring, a path anchor, or a registered\n // layer's own chrome is not a body pick, and re-picking underneath\n // it would change the selection the user was about to act on. And\n // because it is expressed in the SPEC rather than as an early\n // return in the action, the press falls through to whatever owns\n // that chrome instead of being consumed here — which is how an\n // ambient binding (`@weasel-js/hud`) gets to see it at all. The old\n // pipeline got both properties by construction: affordance hits\n // bypassed the active tool entirely.\n //\n // Modifiers are all `'optional'` because they are *data* here\n // (forwarded to `SelectionApi.applyClick`, which resolves them\n // against the host's configured extend key) rather than a route.\n {\n spec: {\n kind: 'pointerDown' as const,\n target: { kindOf: (hit: unknown) => hit == null },\n mods: { shift: 'optional' as const, alt: 'optional' as const, meta: 'optional' as const, ctrl: 'optional' as const },\n },\n actionId: 'select.pick',\n },\n // Release half of the deferred multi-click. Same `'optional'`\n // modifiers, same reason.\n {\n spec: {\n kind: 'click' as const,\n target: { kindOf: (hit: unknown) => hit == null },\n mods: { shift: 'optional' as const, alt: 'optional' as const, meta: 'optional' as const, ctrl: 'optional' as const },\n },\n actionId: 'select.collapseDeferred',\n },\n // Empty drag → marquee. `onEmptyCanvas` rather than a bare `'empty'`\n // target: the ambient bindings that own the handles rank below this\n // active one, so `'empty'` took drags that start on them.\n {\n spec: { kind: 'drag' as const, target: { kindOf: onEmptyCanvas } },\n actionId: 'areaSelect',\n },\n // resize/rotate bind only drag (no click), so a click on either handle\n // (body genuinely empty) would hit target:'empty' and wrongly clear selection.\n {\n spec: {\n kind: 'click' as const,\n target: { kindOf: (hit: unknown, body?: string) => hit == null && body === 'empty' },\n mods: {},\n },\n actionId: 'clearSelection',\n },\n ],\n };\n },\n [pickAction, collapseDeferredAction],\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkJA,SAAgBC,EACd,GACA,GACY;CAIZ,IAAMC,IAAKC,EAAQ,kBAAkBC,GAC/BC,IAAgBF,EAAQ,gBAAgB,cAIxCG,IAAYH,EAAQ,iBAAiB,GACrCI,IAAcJ,EAAQ,eAAe,GAAgB,MAA6B;EAUtF,IAAMK,KAAc,GAAY,GAAY,MAAgC;GAC1E,IAAMC,KAAU,GAAe,GAAa,MAAuB;IACjE,IAAMC,IAAOL,IAAgBM,IAAI;IAMjC,OALMC,KAAMC,EAAE,IAAIH,KAAQE,KAAMC,EAAE,IAAIA,EAAE,QAAQH,KACvCI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F,CAACtB,GAAYe,CAAsB,CACrC;AACF"}
|
|
1
|
+
{"version":3,"file":"useSelectTool.js","names":["SelectIcon","useSelectTool","d","options","AUTO_POSE_DESCRIPTOR","preciseLeaves","tolerance","pickEveryFn","pointQuery","covers","slop","t","px","b","py","shapeCoversPoint","node","pose","poseDescriptorForNode","own","ownClipOf","pathContainsPoint","clip","p","toPlane","m","meanScale","camera","planeOf","scenePlaneOf","adapter","pickWalk","adapterPickSource","worldX","worldY","pickEveryRef","useLatest","pressRef","useRef","optionsRef","adapterRef","pickAction","useMemo","params","selection","deps","mods","opts","sel","top","ids","pickTopMostHit","hitAlreadySelected","isExtend","extendLocked","deferClick","collapseDeferredAction","ActionDisabledReason","deferred","defineTool","createElement","hit","onEmptyCanvas","body"],"sources":["../../../../src/tools/builtin/select/useSelectTool.ts"],"sourcesContent":["import { useMemo, useRef, createElement } from 'react';\nimport { useLatest } from '@weasel-js/react';\nimport { SelectIcon } from '../../../icons';\nimport { pathContainsPoint } from '@weasel-js/geom';\nimport { shapeCoversPoint } from 'canvas/NodeShape';\nimport { pickWalk, adapterPickSource, ownClipOf, scenePlaneOf, type PickQuery } from 'canvas/pickWalk';\nimport { toPlane } from 'core/viewport/parallax';\nimport { meanScale } from 'core/viewport/meanScale';\nimport type { View } from 'core/viewport/view';\nimport type { LayerEnumerableAdapter } from 'core/adapters/types';\nimport type { Node } from 'core/scene/types';\nimport type { MoveAdapter } from 'core/adapters/types';\nimport type { AreaSelectAdapter } from 'core/adapters/types';\nimport type { NodeId } from 'core/scene/types';\nimport { defineTool } from '../../overlayBinding';\nimport type { Action } from '@weasel-js/routing';\nimport { ActionDisabledReason } from '@weasel-js/routing';\nimport type { Tool } from '../../overlayBinding';\nimport { pickTopMostHit } from '../pickTopMostHit';\nimport { onEmptyCanvas } from './selectionContributions';\nimport { poseDescriptorForNode, type PoseDescriptor } from 'core/geometry/poseDescriptor';\nimport { AUTO_POSE_DESCRIPTOR } from 'interactions/actions/resize/autoPoseDescriptor';\nimport { MULTI_RESIZE_TARGET_ID, type Bounds } from '../shared/selectionTarget';\nexport type { Bounds };\nexport { MULTI_RESIZE_TARGET_ID };\n\n/** Options for `useSelectTool`: how a point resolves to nodes, how a click\n * chooses among them, and the appearance of the marquee. */\nexport interface UseSelectToolOptions<TPose> {\n /** Return ids of all objects whose painted body covers (worldX, worldY).\n * Order doesn't matter — the tool collapses parent/child overlap via\n * `pickTopMostHit`. When omitted, defaults to an AABB-vs-point scan over\n * `adapter.getNodes()` using the pose descriptor. Override for tighter\n * shapes (path / polygon hit-tests). */\n pickEvery?: (worldX: number, worldY: number) => string[];\n /** Optional alt-aware selection-update hit returning the single id the\n * click should act on. */\n pickBest?: (\n worldX: number,\n worldY: number,\n alt: boolean,\n selection: readonly string[],\n ) => string | null;\n /** How to read poses for the default `pickEvery`. Default\n * `AUTO_POSE_DESCRIPTOR`. */\n poseDescriptor?: PoseDescriptor<TPose>;\n /**\n * How the default `pickEvery` decides a **leaf** node covers the pointer.\n * Ignored when `pickEvery` is supplied.\n *\n * - `'aabb'` (default) — the pose rect. Cheap, and the historical behavior:\n * a click anywhere in the bounding box selects the node.\n * - `'silhouette'` — the pose rect as a pre-test, then the ink the painter\n * lays down: `findShapeSilhouette` filled or not per the painter's `ink`,\n * plus its outline widened by the stroke half-width and `pickTolerance`.\n * A click inside the bounding box but outside the drawn shape misses —\n * the concave notch of a star, the corner outside an ellipse, the blank\n * half of a text box — while a click on the thin outline of an unfilled\n * shape hits.\n *\n * Container nodes already consult their silhouette unconditionally (it is\n * how their clip is derived); this extends the same test to leaves. Not the\n * default because it changes what a click selects for every existing\n * consumer, and a painter with no `silhouette` is unaffected either way —\n * it falls back to the AABB.\n */\n leafPicking?: 'aabb' | 'silhouette';\n /**\n * Grab slop around a shape's outline, in **world** units. Default 0.\n *\n * Only consulted under `leafPicking: 'silhouette'`. World units because\n * this hook has no view; `<SceneCanvas>` takes a screen-pixel figure\n * (`geometry.pickTolerancePx`) and divides by scale on its own pick path.\n * Without some slop a hairline outline is an unhittable target.\n */\n pickTolerance?: number;\n /** Painted alpha per node in the view this tool picks for. A node painted\n * at alpha 0 is not under the pointer. Ignored when `pickEvery` is\n * supplied. */\n alphaOf?: (id: string) => number;\n /** Whether a node's `layer` reaches the screen in the view this tool picks\n * for. Ignored when `pickEvery` is supplied. */\n layerIsPainted?: (layer: string) => boolean;\n /** The camera of the view this tool picks for. With it, a node on an\n * adapter layer carrying `parallax` (`getLayers`) is picked where that\n * camera's plane paints it; without it, every layer is taken to move with\n * the camera. Ignored when `pickEvery` is supplied. */\n getView?: () => View | null;\n /**\n * When this returns true, a Shift/Meta extend-click must NOT change the\n * node selection.\n *\n * `<SceneCanvas>` wires it to \"a path is in anchor-edit mode\", where\n * Shift-click means \"add this anchor to the anchor selection\". Without\n * the lock the same click also toggles the edited node out of the node\n * selection, and the `editAnchors` dep treats that as the edit target\n * disappearing — so multi-selecting anchors silently exited edit mode.\n *\n * Only extend-clicks are locked. A plain click still re-selects, so\n * clicking a different node exits edit mode as usual.\n */\n extendClickLocked?: () => boolean;\n}\n\n/** Intersection of the move + area-select adapter interfaces.\n * Resize and rotate run through `resizeAction` / `rotateAction`. */\nexport type SelectAdapter<TNode extends { id: string }, TPose> =\n MoveAdapter<TNode, TPose>\n & AreaSelectAdapter\n & LayerEnumerableAdapter;\n\n/**\n * What the press classified, carried from `select.pick` (pointerDown) to\n * `select.collapseDeferred` (click) and to the tool's cursor.\n *\n * This is tool-local bookkeeping between two dispatches of the same gesture,\n * so it lives in a ref the tool owns rather than in dispatcher state. It used\n * to be the tool's `SelectScratch`, held by the tool-routing dispatcher, and\n * carried an `ids` list that nothing ever read — `moveAction` computes its own\n * ids from the live selection.\n *\n * @internal\n */\ninterface PressClassification {\n /**\n * Set when the press hit an already-selected node inside a multi-selection\n * with no extend modifier.\n *\n * The selection is deliberately NOT collapsed on the press: the user may be\n * starting a drag of the whole set. If the gesture turns out to be a click,\n * `select.collapseDeferred` collapses to this id on release.\n */\n deferredClickId: string | null;\n}\n\n/** Active-slot Tool:\n * - `select.pick` classifies the press (pointerDown) — it runs the tool's own\n * pickBest/pickEvery so click semantics (selection replace, extend,\n * deferred collapse) live in one place.\n * - an empty drag marquees (`areaSelect`) and a click on empty clears the\n * selection (`clearSelection`); the marquee renders via the dispatcher\n * overlay layer, driven by areaSelectAction's `overlay()`.\n * - moving and transforming the selection are not the tool's: they are the\n * ambient bindings in `selectionContributions.ts`.\n */\nexport function useSelectTool<TNode extends { id: string }, TPose>(\n adapter: SelectAdapter<TNode, TPose>,\n options: UseSelectToolOptions<TPose>,\n): Tool<null> {\n\n // pickEvery / boundsOf defaults — for any adapter the kit can derive both\n // from `adapter.getNodes()` + `adapter.getPose(id)` + the descriptor.\n const d = (options.poseDescriptor ?? AUTO_POSE_DESCRIPTOR) as PoseDescriptor<TPose>;\n const preciseLeaves = options.leafPicking === 'silhouette';\n // World units here, not screen: this hook has no view. `<SceneCanvas>`\n // converts from screen px on its own pick path; a bare `useSelectTool`\n // consumer that zooms should pass `pickTolerance` from its own scale.\n const tolerance = options.pickTolerance ?? 0;\n const pickEveryFn = options.pickEvery ?? ((worldX: number, worldY: number): string[] => {\n /** A point query at (px, py) with `t` world units of slop. AABB first\n * (cheap), then the painter's ink when asked for and available. A painter\n * with no `silhouette` — or one that returns null, as `kit:text` does for\n * an empty node — keeps the AABB answer.\n *\n * The AABB pre-filter is grown by the slop for the same reason\n * `<SceneCanvas>`'s is: a shape's outline, and the slop around it, reach\n * outside the shape's own bounds, and an un-grown pre-filter would\n * discard those hits before the refinement could claim them. */\n const pointQuery = (px: number, py: number, t: number): PickQuery<TPose> => {\n const covers = (node: unknown, pose: TPose, b: Bounds): boolean => {\n const slop = preciseLeaves ? t : 0;\n if (!(px >= b.x - slop && px <= b.x + b.width + slop\n && py >= b.y - slop && py <= b.y + b.height + slop)) {\n return false;\n }\n if (!preciseLeaves) return true;\n return shapeCoversPoint(\n node as Node<unknown, string, TPose>, pose, px, py, { tolerance: t },\n );\n };\n return {\n hits: (node, pose) => {\n const b = poseDescriptorForNode(d, node).getBounds(pose);\n if (node.kind !== 'container') return covers(node, pose, b);\n // A container's own clip *is* its hit shape — it is picked where it\n // paints, and it paints only inside its clip. Ancestor clips are the\n // walk's business; this one is not.\n const inAabb = px >= b.x && px <= b.x + b.width\n && py >= b.y && py <= b.y + b.height;\n if (!inAabb) return false;\n const own = ownClipOf(node, pose);\n return own === null || pathContainsPoint(own, px, py);\n },\n clipAdmits: (clip) => pathContainsPoint(clip, px, py),\n inPlane: (m) => {\n const p = toPlane(m, { x: px, y: py });\n return pointQuery(p.x, p.y, t * meanScale(m.scale));\n },\n };\n };\n\n const camera = options.getView?.() ?? null;\n const planeOf = camera ? scenePlaneOf(adapter.getLayers?.(), camera) : null;\n return pickWalk<TPose>(adapterPickSource(adapter as never, {\n ...(options.alphaOf ? { alphaOf: options.alphaOf } : {}),\n ...(options.layerIsPainted ? { layerIsPainted: options.layerIsPainted } : {}),\n ...(planeOf ? { planeOf } : {}),\n }), pointQuery(worldX, worldY, tolerance));\n });\n\n const pickEveryRef = useLatest(pickEveryFn);\n\n // What the last press classified. Written by `select.pick`, read by\n // `select.collapseDeferred` and the cursor. See `PressClassification`.\n const pressRef = useRef<PressClassification>({ deferredClickId: null });\n\n // Options in a ref so the actions — built once — always see the live\n // callbacks without rebuilding the Tool record.\n const optionsRef = useLatest(options);\n const adapterRef = useLatest(adapter);\n\n /**\n * `select.pick` — classifies the press and updates the node selection.\n *\n * Bound to `pointerDown` rather than `click` on purpose: pressing an\n * unselected node must highlight it while the button is still down, and any\n * drag that follows has to start from the updated selection (both\n * `moveAction` and `cloneAction` read `selection.get()` in their `start`).\n *\n * Eligibility replaces the `selectionAllowed` option the audit added as an\n * interim per-route patch: this action carries the same\n * `creates-selection` capability rule the `clearSelection` binding declares,\n * so a mode that forbids selection now gates both halves of the tool by one\n * mechanism instead of by which dispatcher the route happened to live on.\n */\n const pickAction = useMemo<Action>(() => ({\n id: 'select.pick',\n label: 'Select — pick under pointer',\n eligible: { capability: 'creates-selection' },\n requires: ['selection'],\n invoker: {\n timing: 'immediate' as const,\n run: (deps, params) => {\n const p = params as {\n worldX?: number; worldY?: number;\n affordance?: unknown;\n mods?: { alt: boolean; ctrl: boolean; meta: boolean; shift: boolean };\n } | undefined;\n const selection = deps.selection;\n if (!selection || p?.worldX === undefined || p.worldY === undefined) return;\n const mods = p.mods ?? { alt: false, ctrl: false, meta: false, shift: false };\n const opts = optionsRef.current;\n\n const sel = selection.get();\n const top = opts.pickBest\n ? opts.pickBest(p.worldX, p.worldY, mods.alt, sel)\n : (() => {\n const ids = pickEveryRef.current(p.worldX, p.worldY);\n if (ids.length === 0) return null;\n return pickTopMostHit(ids, adapterRef.current) ?? ids[0];\n })();\n\n if (top === null) {\n pressRef.current = { deferredClickId: null };\n return;\n }\n\n const hitAlreadySelected = sel.includes(top as NodeId);\n const isExtend = mods.shift || mods.meta;\n // While a path is in anchor-edit mode, an extend-click belongs to the\n // anchor selection, not the node selection. Letting it through would\n // toggle the edited node out of the node selection, which the\n // `editAnchors` dep reads as \"the edit target is gone\" — so\n // shift-clicking a second anchor silently tore down edit mode.\n // Plain clicks still fall through: clicking a different node exits\n // edit mode, which is what you'd expect.\n //\n // This stays an option rather than becoming `Action.enabled` because\n // it only applies to *extend* presses, and `enabled` is evaluated\n // without the event's modifiers.\n const extendLocked = isExtend && opts.extendClickLocked?.() === true;\n const deferClick = hitAlreadySelected && sel.length > 1 && !isExtend;\n if (!deferClick && !extendLocked) {\n selection.applyClick(top as NodeId, mods);\n }\n pressRef.current = { deferredClickId: deferClick ? top : null };\n },\n },\n }), [optionsRef, pickEveryRef, adapterRef]);\n\n /**\n * `select.collapseDeferred` — the release half of the deferred multi-click.\n *\n * Pressing an already-selected node inside a multi-selection leaves the\n * selection alone so the press can start a drag of the whole set. If the\n * gesture ends without a drag, this collapses to the clicked node.\n */\n const collapseDeferredAction = useMemo<Action>(() => ({\n id: 'select.collapseDeferred',\n label: 'Select — collapse deferred click',\n eligible: { capability: 'creates-selection' },\n requires: ['selection'],\n // Declining when there is nothing deferred is what keeps this binding\n // from swallowing every click. It is bound with no target (any click can\n // in principle be the release of a deferred press) at ACTIVE scope, so\n // without the gate it would outrank ambient click bindings like\n // `selectAnchor` and silently break anchor selection. Same fall-through\n // contract `clearSelection.enabled` relies on.\n enabled: () =>\n pressRef.current.deferredClickId !== null\n ? true\n : ActionDisabledReason.NotApplicable,\n invoker: {\n timing: 'immediate' as const,\n run: (deps, params) => {\n const deferred = pressRef.current.deferredClickId;\n pressRef.current = { deferredClickId: null };\n if (deferred === null) return;\n const selection = deps.selection;\n if (!selection) return;\n const p = params as {\n mods?: { alt: boolean; ctrl: boolean; meta: boolean; shift: boolean };\n } | undefined;\n selection.applyClick(\n deferred as NodeId,\n p?.mods ?? { alt: false, ctrl: false, meta: false, shift: false },\n );\n },\n },\n }), []);\n\n return useMemo(\n () => {\n const base = defineTool<null>({\n id: 'select',\n capabilities: ['creates-selection'],\n hookName: 'useSelectTool',\n // A plain string: the mid-gesture cursors this used to compute from\n // gesture scratch now live on the actions that own those gestures\n // (`moveAction.activeCursor`, `areaSelectAction.activeCursor`), so\n // they apply to any consumer binding them, not just this tool.\n cursor: 'default',\n presentation: {\n label: 'Select',\n icon: createElement(SelectIcon),\n group: 'select',\n },\n actions: [pickAction, collapseDeferredAction],\n });\n\n return {\n ...base,\n // Declarative bindings for the gesture dispatcher. The select tool\n // only chooses: press → classify + select, release → collapse a\n // deferred multi-click, empty drag → marquee, click on empty → clear.\n // Moving, cloning, resizing and rotating the selection are ambient\n // bindings owned by the selection (`selectionContributions.ts`), so\n // they run under any tool that leaves the gesture unclaimed.\n bindings: [\n // Every press that landed on the scene rather than on chrome. This\n // is the former `initial.pointerDown['*']` route: it classifies the\n // press and applies the selection change, and it does not consume\n // the gesture — the same press goes on to open a drag or synthesize\n // a click.\n //\n // The no-affordance target is load-bearing twice over. A press on a\n // resize handle, a rotate ring, a path anchor, or a registered\n // layer's own chrome is not a body pick, and re-picking underneath\n // it would change the selection the user was about to act on. And\n // because it is expressed in the SPEC rather than as an early\n // return in the action, the press falls through to whatever owns\n // that chrome instead of being consumed here — which is how an\n // ambient binding (`@weasel-js/hud`) gets to see it at all. The old\n // pipeline got both properties by construction: affordance hits\n // bypassed the active tool entirely.\n //\n // Modifiers are all `'optional'` because they are *data* here\n // (forwarded to `SelectionApi.applyClick`, which resolves them\n // against the host's configured extend key) rather than a route.\n {\n spec: {\n kind: 'pointerDown' as const,\n target: { kindOf: (hit: unknown) => hit == null },\n mods: { shift: 'optional' as const, alt: 'optional' as const, meta: 'optional' as const, ctrl: 'optional' as const },\n },\n actionId: 'select.pick',\n },\n // Release half of the deferred multi-click. Same `'optional'`\n // modifiers, same reason.\n {\n spec: {\n kind: 'click' as const,\n target: { kindOf: (hit: unknown) => hit == null },\n mods: { shift: 'optional' as const, alt: 'optional' as const, meta: 'optional' as const, ctrl: 'optional' as const },\n },\n actionId: 'select.collapseDeferred',\n },\n // Empty drag → marquee. `onEmptyCanvas` rather than a bare `'empty'`\n // target: the ambient bindings that own the handles rank below this\n // active one, so `'empty'` took drags that start on them.\n {\n spec: { kind: 'drag' as const, target: { kindOf: onEmptyCanvas } },\n actionId: 'areaSelect',\n },\n // resize/rotate bind only drag (no click), so a click on either handle\n // (body genuinely empty) would hit target:'empty' and wrongly clear selection.\n {\n spec: {\n kind: 'click' as const,\n target: { kindOf: (hit: unknown, body?: string) => hit == null && body === 'empty' },\n mods: {},\n },\n actionId: 'clearSelection',\n },\n ],\n };\n },\n [pickAction, collapseDeferredAction],\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAiJA,SAAgBC,EACd,GACA,GACY;CAIZ,IAAMC,IAAKC,EAAQ,kBAAkBC,GAC/BC,IAAgBF,EAAQ,gBAAgB,cAIxCG,IAAYH,EAAQ,iBAAiB,GACrCI,IAAcJ,EAAQ,eAAe,GAAgB,MAA6B;EAUtF,IAAMK,KAAc,GAAY,GAAY,MAAgC;GA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GACZ;GAGA;IACE,MAAM;KACJ,MAAM;KACN,QAAQ,EAAE,SAAS,GAAc,MAAkBD,KAAO,QAAQE,MAAS,QAAQ;KACnF,MAAM,CAAC;IACT;IACA,UAAU;GACZ;EACF;CACF,IAEF,CAACtB,GAAYe,CAAsB,CACrC;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useSliceTool.js","names":["VERTEX_RADIUS_PX","useSliceTool","scratchRef","useRef","optsRef","useLatest","options","live","useMemo","listeners","pointer","offPointer","notify","fn","next","actions","points","pending","ActionDisabledReason","reset","commit","cut","deps","place","pts","first","scale","withinPxRadius","x","y","eligible","sliceAction","\"slice\"","p","params","reason","at","endCtx","overlay","t","viewToTransform","view","toScreen","worldToScreen","run","stroke","OVERLAY_ROLE_STROKES","\"cut\"","out","polylineFromPoints","ellipsePath","defineTool","keybinding"],"sources":["../../../../src/tools/builtin/slice/useSliceTool.ts"],"sourcesContent":["import { useMemo, useRef } from 'react';\nimport { useLatest } from '@weasel-js/react';\nimport { defineTool } from '../../overlayBinding';\nimport type { Tool } from '../../overlayBinding';\nimport type { RenderLayer } from 'core/layers/render';\nimport type { DrawCommand } from '../../../renderer';\nimport type { Action, ActionDeps, InvocationCtx, ToolKeybinding } from '@weasel-js/routing';\nimport { ActionDisabledReason } from '@weasel-js/routing';\nimport type { SliceDep, ViewApi } from 'interactions/actions/depSchema';\nimport type { PointerContextValue } from 'features/pointer/PointerContext';\nimport { sliceAction } from 'interactions/actions/defaults/slice';\nimport { withinPxRadius } from 'core/viewport/pxExtent';\nimport { worldToScreen } from 'core/viewport/viewTransform';\nimport { viewToTransform } from 'core/viewport/view';\nimport { ellipsePath, polylineFromPoints } from '@weasel-js/geom';\nimport { OVERLAY_ROLE_STROKES } from 'canvas/overlayRoleStrokes';\n\n/** Options for `useSliceTool`. */\nexport interface UseSliceToolOptions {\n /** Override the default keybinding (`{ key: 'K' }`). Pass `null` to omit. */\n keybinding?: ToolKeybinding | null;\n /** Screen-px radius around the first point within which a click closes the\n * cut into a loop and commits it. Default `8`. */\n closeHitRadius?: number;\n}\n\n/** The click-by-click cut in progress, in world coords. */\nexport interface SliceScratch {\n points: { x: number; y: number }[];\n}\n\nconst VERTEX_RADIUS_PX = 3;\n\n/**\n * Knife tool. A drag cuts along a straight line, and an Alt-drag along its\n * freehand trail, through `sliceAction`. Clicks place a cut one point at a\n * time: Enter or a double-click commits it, Escape discards it, Backspace\n * takes back the last point, and a click on the first point closes it into a\n * loop and commits. While points are placed, a drag places one more where it\n * is released instead of cutting on its own.\n *\n * Every cut goes to the `slice` dep, which decides what it does to the scene.\n * `<SceneCanvas>` publishes one that cuts every path the cut crosses. The pending cut paints through\n * `Tool.overlay`, trailing to the pointer when the host publishes one.\n */\nexport function useSliceTool(options: UseSliceToolOptions = {}): Tool<null> {\n const scratchRef = useRef<SliceScratch>({ points: [] });\n const optsRef = useLatest({ closeHitRadius: options.closeHitRadius ?? 8 });\n\n // What the overlay layer's `subscribe` hears: a change to the points, and,\n // while any are placed, every move of the pointer the rubber band follows.\n const live = useMemo(() => {\n const listeners = new Set<() => void>();\n let pointer: PointerContextValue | null = null;\n let offPointer: (() => void) | null = null;\n const notify = (): void => { for (const fn of [...listeners]) fn(); };\n return {\n notify,\n listen(fn: () => void): () => void {\n listeners.add(fn);\n return () => { listeners.delete(fn); };\n },\n pointer: () => pointer,\n follow(next: PointerContextValue | undefined): void {\n if (!next || next === pointer) return;\n offPointer?.();\n pointer = next;\n offPointer = next.subscribe(notify);\n },\n unfollow(): void {\n offPointer?.();\n offPointer = null;\n pointer = null;\n },\n };\n }, []);\n\n const actions = useMemo<Action[]>(() => {\n const points = () => scratchRef.current.points;\n const pending = () => (points().length > 0 ? true : ActionDisabledReason.NotApplicable);\n\n const reset = (): void => {\n scratchRef.current.points = [];\n live.unfollow();\n live.notify();\n };\n const commit = (deps: ActionDeps): void => {\n const cut = points().slice();\n reset();\n if (cut.length >= 2) (deps.slice as SliceDep | undefined)?.commit(cut);\n };\n const place = (deps: ActionDeps, x: number, y: number): void => {\n const pts = points();\n const first = pts[0];\n const scale = (deps.view as ViewApi | undefined)?.get().scale ?? { x: 1, y: 1 };\n if (pts.length >= 3 && withinPxRadius(x - first.x, y - first.y, optsRef.current.closeHitRadius, scale)) {\n pts.push({ x: first.x, y: first.y });\n commit(deps);\n return;\n }\n pts.push({ x, y });\n live.follow(deps.pointer as PointerContextValue | undefined);\n live.notify();\n };\n\n const eligible = { capability: 'edits-page' } as const;\n return [\n sliceAction,\n {\n id: 'slice.addPoint',\n label: 'Slice — place point',\n eligible,\n requires: ['slice', 'view', 'pointer'],\n enabled: (deps) => (deps?.['slice'] ? true : ActionDisabledReason.NotApplicable),\n invoker: {\n timing: 'immediate',\n run: (deps, params) => {\n const p = params as { pressX?: number; pressY?: number } | undefined;\n if (p?.pressX === undefined || p.pressY === undefined) return;\n place(deps, p.pressX, p.pressY);\n },\n },\n },\n {\n id: 'slice.dragPoint',\n label: 'Slice — drag out a point',\n eligible,\n requires: ['slice', 'view', 'pointer'],\n enabled: pending,\n invoker: {\n timing: 'ongoing',\n start: () => ({\n onMove: () => {},\n onEnd: (endCtx: InvocationCtx, reason: 'commit' | 'cancel') => {\n if (reason === 'cancel' || points().length === 0) return;\n const at = endCtx.drag?.current ?? endCtx.world;\n place(endCtx.deps, at.x, at.y);\n },\n }),\n },\n },\n {\n id: 'slice.finish',\n label: 'Slice — cut along the points',\n eligible,\n requires: ['slice'],\n enabled: pending,\n invoker: {\n timing: 'immediate',\n run: (deps, params) => {\n // A double click arrives after both of its clicks, so the second\n // has already placed a point on top of the first.\n if ((params as { viaDoubleClick?: boolean } | undefined)?.viaDoubleClick) points().pop();\n commit(deps);\n },\n },\n },\n {\n id: 'slice.dropPoint',\n label: 'Slice — take back the last point',\n eligible,\n enabled: pending,\n invoker: {\n timing: 'immediate',\n run: () => {\n points().pop();\n if (points().length === 0) reset();\n else live.notify();\n },\n },\n },\n {\n id: 'slice.cancel',\n label: 'Slice — discard the points',\n eligible,\n // Declining with nothing placed leaves Escape to the ambient `escape`.\n enabled: pending,\n invoker: { timing: 'immediate', run: () => reset() },\n },\n ];\n }, [live, optsRef]);\n\n const overlay = useMemo<RenderLayer<unknown>>(() => ({\n id: 'slice-pending-cut',\n label: 'Slice — pending cut',\n space: 'screen',\n subscribe: live.listen,\n draw: (_data, view) => {\n const pts = scratchRef.current.points;\n if (pts.length === 0) return [];\n const t = viewToTransform(view);\n const toScreen = (p: { x: number; y: number }) => {\n const [x, y] = worldToScreen(p.x, p.y, t);\n return { x, y };\n };\n const run = pts.map(toScreen);\n const at = live.pointer()?.get();\n if (at) run.push(toScreen({ x: at.worldX, y: at.worldY }));\n const stroke = OVERLAY_ROLE_STROKES['cut'];\n const out: DrawCommand[] = [];\n if (run.length >= 2) out.push({ kind: 'path', path: polylineFromPoints(run), stroke });\n for (const p of pts.map(toScreen)) {\n out.push({\n kind: 'path',\n path: ellipsePath({\n x: p.x - VERTEX_RADIUS_PX,\n y: p.y - VERTEX_RADIUS_PX,\n width: VERTEX_RADIUS_PX * 2,\n height: VERTEX_RADIUS_PX * 2,\n }),\n fill: stroke.paint,\n });\n }\n return out;\n },\n }), [live]);\n\n const { keybinding } = options;\n return useMemo(() => defineTool<null>({\n id: 'slice',\n capabilities: ['edits-page'],\n hookName: 'useSliceTool',\n cursor: 'crosshair',\n presentation: { label: 'Slice', group: 'shape' },\n ...(keybinding === null ? {} : { keybinding: keybinding ?? { key: 'K' } }),\n actions,\n overlay,\n onDeactivate: () => {\n scratchRef.current.points = [];\n live.unfollow();\n live.notify();\n },\n bindings: [\n { spec: { kind: 'click', mods: { shift: 'optional', alt: 'optional' } }, actionId: 'slice.addPoint' },\n {\n spec: { kind: 'doubleClick', mods: { shift: 'optional', alt: 'optional' } },\n actionId: 'slice.finish',\n opts: { params: { viaDoubleClick: true } },\n },\n // Ahead of the cutting drags: it declines unless points are placed.\n { spec: { kind: 'drag', mods: { shift: 'optional', alt: 'optional' } }, actionId: 'slice.dragPoint' },\n { spec: { kind: 'drag' }, actionId: 'slice' },\n { spec: { kind: 'drag', mods: { alt: true } }, actionId: 'slice', opts: { params: { cut: 'freehand' } } },\n { spec: { kind: 'key', key: 'Enter' }, actionId: 'slice.finish' },\n { spec: { kind: 'key', key: 'Escape' }, actionId: 'slice.cancel' },\n { spec: { kind: 'key', key: 'Backspace' }, actionId: 'slice.dropPoint' },\n ],\n }), [actions, overlay, keybinding, live]);\n}\n"],"mappings":";;;;;;;;;;;AA+BA,IAAMA,IAAmB;AAczB,SAAgBC,EAAa,IAA+B,CAAC,GAAe;CAC1E,IAAMC,IAAaC,EAAqB,EAAE,QAAQ,CAAC,EAAE,CAAC,GAChDC,IAAUC,EAAU,EAAE,gBAAgBC,EAAQ,kBAAkB,EAAE,CAAC,GAInEC,IAAOC,QAAc;EACzB,IAAMC,oBAAY,IAAI,IAAgB,GAClCC,IAAsC,MACtCC,IAAkC,MAChCC,UAAqB;GAAE,KAAK,IAAMC,KAAM,CAAC,GAAGJ,CAAS,GAAG,EAAG;EAAG;EACpE,OAAO;GACL;GACA,OAAO,GAA4B;IAEjC,OADAA,EAAU,IAAII,CAAE,SACH;KAAE,EAAU,OAAOA,CAAE;IAAG;GACvC;GACA,eAAeH;GACf,OAAO,GAA6C;IAClD,AAAKI,KAAQA,MAASJ,MACtBC,IAAa,GACb,IAAUG,GACV,IAAaA,EAAK,UAAUF,CAAM;GACpC;GACA,WAAiB;IAGf,AAFAD,IAAa,GACb,IAAa,MACb,IAAU;GACZ;EACF;CACF,GAAG,CAAC,CAAC,GAECI,IAAUP,QAAwB;EACtC,IAAMQ,UAAed,EAAW,QAAQ,QAClCe,UAAiBD,EAAO,CAAC,CAAC,SAAS,KAAWE,EAAqB,eAEnEC,UAAoB;GAGxB,AAFA,EAAW,QAAQ,SAAS,CAAC,GAC7BZ,EAAK,SAAS,GACdA,EAAK,OAAO;EACd,GACMa,KAAU,MAA2B;GACzC,IAAMC,IAAML,EAAO,CAAC,CAAC,MAAM;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;IAAG,UAAU;GAAe;GAChE;IAAE,MAAM;KAAE,MAAM;KAAO,KAAK;IAAS;IAAG,UAAU;GAAe;GACjE;IAAE,MAAM;KAAE,MAAM;KAAO,KAAK;IAAY;IAAG,UAAU;GAAkB;EACzE;CACF,CAAC,GAAG;EAACQ;EAASuB;EAASc;EAAY7C;CAAI,CAAC;AAC1C"}
|
|
1
|
+
{"version":3,"file":"useSliceTool.js","names":["VERTEX_RADIUS_PX","useSliceTool","scratchRef","useRef","optsRef","useLatest","options","live","useMemo","listeners","pointer","offPointer","notify","fn","next","actions","points","pending","ActionDisabledReason","reset","commit","cut","deps","place","pts","first","scale","withinPxRadius","x","y","eligible","sliceAction","\"slice\"","p","params","reason","at","endCtx","overlay","t","viewToTransform","view","toScreen","worldToScreen","run","stroke","OVERLAY_ROLE_STROKES","\"cut\"","out","polylineFromPoints","ellipsePath","defineTool","keybinding"],"sources":["../../../../src/tools/builtin/slice/useSliceTool.ts"],"sourcesContent":["import { useMemo, useRef } from 'react';\nimport { useLatest } from '@weasel-js/react';\nimport { defineTool } from '../../overlayBinding';\nimport type { Tool } from '../../overlayBinding';\nimport type { RenderLayer } from 'core/layers/render';\nimport type { DrawCommand } from '../../../renderer';\nimport type { Action, ActionDeps, InvocationCtx, ToolKeybinding } from '@weasel-js/routing';\nimport { ActionDisabledReason } from '@weasel-js/routing';\nimport type { PointerContextValue } from 'features/pointer/PointerContext';\nimport { sliceAction } from 'interactions/actions/defaults/slice';\nimport { withinPxRadius } from 'core/viewport/pxExtent';\nimport { worldToScreen } from 'core/viewport/viewTransform';\nimport { viewToTransform } from 'core/viewport/view';\nimport { ellipsePath, polylineFromPoints } from '@weasel-js/geom';\nimport { OVERLAY_ROLE_STROKES } from 'canvas/overlayRoleStrokes';\n\n/** Options for `useSliceTool`. */\nexport interface UseSliceToolOptions {\n /** Override the default keybinding (`{ key: 'K' }`). Pass `null` to omit. */\n keybinding?: ToolKeybinding | null;\n /** Screen-px radius around the first point within which a click closes the\n * cut into a loop and commits it. Default `8`. */\n closeHitRadius?: number;\n}\n\n/** The click-by-click cut in progress, in world coords. */\nexport interface SliceScratch {\n points: { x: number; y: number }[];\n}\n\nconst VERTEX_RADIUS_PX = 3;\n\n/**\n * Knife tool. A drag cuts along a straight line, and an Alt-drag along its\n * freehand trail, through `sliceAction`. Clicks place a cut one point at a\n * time: Enter or a double-click commits it, Escape discards it, Backspace\n * takes back the last point, and a click on the first point closes it into a\n * loop and commits. While points are placed, a drag places one more where it\n * is released instead of cutting on its own.\n *\n * Every cut goes to the `slice` dep, which decides what it does to the scene.\n * `<SceneCanvas>` publishes one that cuts every path the cut crosses. The pending cut paints through\n * `Tool.overlay`, trailing to the pointer when the host publishes one.\n */\nexport function useSliceTool(options: UseSliceToolOptions = {}): Tool<null> {\n const scratchRef = useRef<SliceScratch>({ points: [] });\n const optsRef = useLatest({ closeHitRadius: options.closeHitRadius ?? 8 });\n\n // What the overlay layer's `subscribe` hears: a change to the points, and,\n // while any are placed, every move of the pointer the rubber band follows.\n const live = useMemo(() => {\n const listeners = new Set<() => void>();\n let pointer: PointerContextValue | null = null;\n let offPointer: (() => void) | null = null;\n const notify = (): void => { for (const fn of [...listeners]) fn(); };\n return {\n notify,\n listen(fn: () => void): () => void {\n listeners.add(fn);\n return () => { listeners.delete(fn); };\n },\n pointer: () => pointer,\n follow(next: PointerContextValue | undefined): void {\n if (!next || next === pointer) return;\n offPointer?.();\n pointer = next;\n offPointer = next.subscribe(notify);\n },\n unfollow(): void {\n offPointer?.();\n offPointer = null;\n pointer = null;\n },\n };\n }, []);\n\n const actions = useMemo<Action[]>(() => {\n const points = () => scratchRef.current.points;\n const pending = () => (points().length > 0 ? true : ActionDisabledReason.NotApplicable);\n\n const reset = (): void => {\n scratchRef.current.points = [];\n live.unfollow();\n live.notify();\n };\n const commit = (deps: ActionDeps): void => {\n const cut = points().slice();\n reset();\n if (cut.length >= 2) deps.slice?.commit(cut);\n };\n const place = (deps: ActionDeps, x: number, y: number): void => {\n const pts = points();\n const first = pts[0];\n const scale = deps.view?.get().scale ?? { x: 1, y: 1 };\n if (pts.length >= 3 && withinPxRadius(x - first.x, y - first.y, optsRef.current.closeHitRadius, scale)) {\n pts.push({ x: first.x, y: first.y });\n commit(deps);\n return;\n }\n pts.push({ x, y });\n live.follow(deps.pointer);\n live.notify();\n };\n\n const eligible = { capability: 'edits-page' } as const;\n return [\n sliceAction,\n {\n id: 'slice.addPoint',\n label: 'Slice — place point',\n eligible,\n requires: ['slice', 'view', 'pointer'],\n enabled: (deps) => (deps?.['slice'] ? true : ActionDisabledReason.NotApplicable),\n invoker: {\n timing: 'immediate',\n run: (deps, params) => {\n const p = params as { pressX?: number; pressY?: number } | undefined;\n if (p?.pressX === undefined || p.pressY === undefined) return;\n place(deps, p.pressX, p.pressY);\n },\n },\n },\n {\n id: 'slice.dragPoint',\n label: 'Slice — drag out a point',\n eligible,\n requires: ['slice', 'view', 'pointer'],\n enabled: pending,\n invoker: {\n timing: 'ongoing',\n start: () => ({\n onMove: () => {},\n onEnd: (endCtx: InvocationCtx, reason: 'commit' | 'cancel') => {\n if (reason === 'cancel' || points().length === 0) return;\n const at = endCtx.drag?.current ?? endCtx.world;\n place(endCtx.deps, at.x, at.y);\n },\n }),\n },\n },\n {\n id: 'slice.finish',\n label: 'Slice — cut along the points',\n eligible,\n requires: ['slice'],\n enabled: pending,\n invoker: {\n timing: 'immediate',\n run: (deps, params) => {\n // A double click arrives after both of its clicks, so the second\n // has already placed a point on top of the first.\n if ((params as { viaDoubleClick?: boolean } | undefined)?.viaDoubleClick) points().pop();\n commit(deps);\n },\n },\n },\n {\n id: 'slice.dropPoint',\n label: 'Slice — take back the last point',\n eligible,\n enabled: pending,\n invoker: {\n timing: 'immediate',\n run: () => {\n points().pop();\n if (points().length === 0) reset();\n else live.notify();\n },\n },\n },\n {\n id: 'slice.cancel',\n label: 'Slice — discard the points',\n eligible,\n // Declining with nothing placed leaves Escape to the ambient `escape`.\n enabled: pending,\n invoker: { timing: 'immediate', run: () => reset() },\n },\n ];\n }, [live, optsRef]);\n\n const overlay = useMemo<RenderLayer<unknown>>(() => ({\n id: 'slice-pending-cut',\n label: 'Slice — pending cut',\n space: 'screen',\n subscribe: live.listen,\n draw: (_data, view) => {\n const pts = scratchRef.current.points;\n if (pts.length === 0) return [];\n const t = viewToTransform(view);\n const toScreen = (p: { x: number; y: number }) => {\n const [x, y] = worldToScreen(p.x, p.y, t);\n return { x, y };\n };\n const run = pts.map(toScreen);\n const at = live.pointer()?.get();\n if (at) run.push(toScreen({ x: at.worldX, y: at.worldY }));\n const stroke = OVERLAY_ROLE_STROKES['cut'];\n const out: DrawCommand[] = [];\n if (run.length >= 2) out.push({ kind: 'path', path: polylineFromPoints(run), stroke });\n for (const p of pts.map(toScreen)) {\n out.push({\n kind: 'path',\n path: ellipsePath({\n x: p.x - VERTEX_RADIUS_PX,\n y: p.y - VERTEX_RADIUS_PX,\n width: VERTEX_RADIUS_PX * 2,\n height: VERTEX_RADIUS_PX * 2,\n }),\n fill: stroke.paint,\n });\n }\n return out;\n },\n }), [live]);\n\n const { keybinding } = options;\n return useMemo(() => defineTool<null>({\n id: 'slice',\n capabilities: ['edits-page'],\n hookName: 'useSliceTool',\n cursor: 'crosshair',\n presentation: { label: 'Slice', group: 'shape' },\n ...(keybinding === null ? {} : { keybinding: keybinding ?? { key: 'K' } }),\n actions,\n overlay,\n onDeactivate: () => {\n scratchRef.current.points = [];\n live.unfollow();\n live.notify();\n },\n bindings: [\n { spec: { kind: 'click', mods: { shift: 'optional', alt: 'optional' } }, actionId: 'slice.addPoint' },\n {\n spec: { kind: 'doubleClick', mods: { shift: 'optional', alt: 'optional' } },\n actionId: 'slice.finish',\n opts: { params: { viaDoubleClick: true } },\n },\n // Ahead of the cutting drags: it declines unless points are placed.\n { spec: { kind: 'drag', mods: { shift: 'optional', alt: 'optional' } }, actionId: 'slice.dragPoint' },\n { spec: { kind: 'drag' }, actionId: 'slice' },\n { spec: { kind: 'drag', mods: { alt: true } }, actionId: 'slice', opts: { params: { cut: 'freehand' } } },\n { spec: { kind: 'key', key: 'Enter' }, actionId: 'slice.finish' },\n { spec: { kind: 'key', key: 'Escape' }, actionId: 'slice.cancel' },\n { spec: { kind: 'key', key: 'Backspace' }, actionId: 'slice.dropPoint' },\n ],\n }), [actions, overlay, keybinding, live]);\n}\n"],"mappings":";;;;;;;;;;;AA8BA,IAAMA,IAAmB;AAczB,SAAgBC,EAAa,IAA+B,CAAC,GAAe;CAC1E,IAAMC,IAAaC,EAAqB,EAAE,QAAQ,CAAC,EAAE,CAAC,GAChDC,IAAUC,EAAU,EAAE,gBAAgBC,EAAQ,kBAAkB,EAAE,CAAC,GAInEC,IAAOC,QAAc;EACzB,IAAMC,oBAAY,IAAI,IAAgB,GAClCC,IAAsC,MACtCC,IAAkC,MAChCC,UAAqB;GAAE,KAAK,IAAMC,KAAM,CAAC,GAAGJ,CAAS,GAAG,EAAG;EAAG;EACpE,OAAO;GACL;GACA,OAAO,GAA4B;IAEjC,OADAA,EAAU,IAAII,CAAE,SACH;KAAE,EAAU,OAAOA,CAAE;IAAG;GACvC;GACA,eAAeH;GACf,OAAO,GAA6C;IAClD,AAAKI,KAAQA,MAASJ,MACtBC,IAAa,GACb,IAAUG,GACV,IAAaA,EAAK,UAAUF,CAAM;GACpC;GACA,WAAiB;IAGf,AAFAD,IAAa,GACb,IAAa,MACb,IAAU;GACZ;EACF;CACF,GAAG,CAAC,CAAC,GAECI,IAAUP,QAAwB;EACtC,IAAMQ,UAAed,EAAW,QAAQ,QAClCe,UAAiBD,EAAO,CAAC,CAAC,SAAS,KAAWE,EAAqB,eAEnEC,UAAoB;GAGxB,AAFA,EAAW,QAAQ,SAAS,CAAC,GAC7BZ,EAAK,SAAS,GACdA,EAAK,OAAO;EACd,GACMa,KAAU,MAA2B;GACzC,IAAMC,IAAML,EAAO,CAAC,CAAC,MAAM;GAE3B,AADAG,EAAM,GACFE,EAAI,UAAU,KAAGC,EAAK,OAAO,OAAOD,CAAG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,UAAU;GAAe;GACjE;IAAE,MAAM;KAAE,MAAM;KAAO,KAAK;IAAY;IAAG,UAAU;GAAkB;EACzE;CACF,CAAC,GAAG;EAACQ;EAASuB;EAASc;EAAY7C;CAAI,CAAC;AAC1C"}
|
package/dist/version.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@weasel-js/core",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.9.0",
|
|
4
4
|
"description": "Domain-agnostic 2D scene graph primitives for React: viewport math, drag/resize/insert/clone interactions, layered canvas rendering.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "orochi235",
|
|
@@ -85,23 +85,23 @@
|
|
|
85
85
|
"typecheck": "tsc --noEmit -p tsconfig.json"
|
|
86
86
|
},
|
|
87
87
|
"peerDependencies": {
|
|
88
|
-
"@weasel-js/font": "1.
|
|
88
|
+
"@weasel-js/font": "1.9.0",
|
|
89
89
|
"react": ">=18"
|
|
90
90
|
},
|
|
91
91
|
"dependencies": {
|
|
92
|
-
"@msb235/blits": "0.
|
|
93
|
-
"@weasel-js/cursor": "1.
|
|
94
|
-
"@weasel-js/geom": "1.
|
|
95
|
-
"@weasel-js/gestures": "1.
|
|
96
|
-
"@weasel-js/history": "1.
|
|
97
|
-
"@weasel-js/modes": "1.
|
|
98
|
-
"@weasel-js/quantity": "1.
|
|
99
|
-
"@weasel-js/paint": "1.
|
|
100
|
-
"@weasel-js/react": "1.
|
|
101
|
-
"@weasel-js/registry": "1.
|
|
102
|
-
"@weasel-js/routing": "1.
|
|
103
|
-
"@weasel-js/select": "1.
|
|
104
|
-
"@weasel-js/text": "1.
|
|
92
|
+
"@msb235/blits": "0.6.0",
|
|
93
|
+
"@weasel-js/cursor": "1.9.0",
|
|
94
|
+
"@weasel-js/geom": "1.9.0",
|
|
95
|
+
"@weasel-js/gestures": "1.9.0",
|
|
96
|
+
"@weasel-js/history": "1.9.0",
|
|
97
|
+
"@weasel-js/modes": "1.9.0",
|
|
98
|
+
"@weasel-js/quantity": "1.9.0",
|
|
99
|
+
"@weasel-js/paint": "1.9.0",
|
|
100
|
+
"@weasel-js/react": "1.9.0",
|
|
101
|
+
"@weasel-js/registry": "1.9.0",
|
|
102
|
+
"@weasel-js/routing": "1.9.0",
|
|
103
|
+
"@weasel-js/select": "1.9.0",
|
|
104
|
+
"@weasel-js/text": "1.9.0",
|
|
105
105
|
"earcut": "3.2.3",
|
|
106
106
|
"polygon-clipping": "^0.15.7"
|
|
107
107
|
},
|
|
@@ -119,7 +119,7 @@
|
|
|
119
119
|
"2d"
|
|
120
120
|
],
|
|
121
121
|
"devDependencies": {
|
|
122
|
-
"@weasel-js/modes": "1.
|
|
123
|
-
"@weasel-js/theme": "1.
|
|
122
|
+
"@weasel-js/modes": "1.9.0",
|
|
123
|
+
"@weasel-js/theme": "1.9.0"
|
|
124
124
|
}
|
|
125
125
|
}
|