@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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"anchorEditing.js","names":["SMALL_STEP","BIG_STEP","ANCHOR_CLICK_SLOP","depOf","dep","deps","worldPathOf","p","commitAnchorEdit","worldPath","next","editAnchorSet","edit","label","requiresAnchorSelection","ActionDisabledReason","selectAnchorAction","inPlane","wx","params","wy","hit","nearestAnchorIndex","additive","selectionAfterAnchorPress","editingLayer","KEY_FOR","LABEL_FOR","delta","dir","step","makeNudgeAnchorsAction","selected","any","flat","translateAnchorBy","set","dx","dy","nudgeAnchorsUpAction","nudgeAnchorsDownAction","nudgeAnchorsLeftAction","nudgeAnchorsRightAction","deleteAnchorsAction","doomed","deleteAnchorsAt","cutPathAtAnchorAction","nearest","openSubpathAt","best","bestD2","slop","sub","pathToAnchors","path","a","d2","marqueeAnchorsAction","ctx","base","start","rectFrom","cx","cy","rect","moveCtx","hits","anchorsOfPathInRect","reason","anchorsInRect"],"sources":["../../../../src/interactions/actions/defaults/anchorEditing.ts"],"sourcesContent":["/**\n * Anchor-editing Actions beyond the drag itself — the keyboard and\n * marquee half of path editing.\n *\n * These were previously only reachable through the pen tool's private\n * edit mode, which no consumer could actually enter (its `getPathObj`\n * hook needed a `pose.kind` that no kit-created node has). Porting them\n * onto the Action layer puts them behind the same `editAnchors` dep,\n * `edits-anchors` capability, and undo path as `editAnchorsAction`.\n *\n * ## Why these don't collide with their node-level counterparts\n *\n * Each has a node-level twin bound to the same gesture: `deleteAction`\n * (Delete/Backspace), `nudge.*` (arrows), `areaSelectAction` (drag on\n * empty). Two mechanisms keep them apart, and both are needed:\n *\n * - **Capability eligibility**, when a mode registry is wired. The\n * node-level twins gate on `edits-page` / `transforms-selection` /\n * `creates-selection`, none of which `path-edit` mode allows, so the\n * dispatcher filters them out before matching.\n * - **`enabled` fall-through**, for the many consumers with no mode\n * registry at all. There the eligibility filter is skipped entirely,\n * so these actions report themselves disabled unless a path is\n * actually being edited with anchors selected, and the dispatcher\n * moves on to the node-level twin.\n *\n * Relying on eligibility alone would break every non-modal consumer;\n * relying on `enabled` alone would let a node-level action fire inside\n * path-edit mode. See `anchorEditing.test.ts`.\n */\n\nimport type { Action } from '@weasel-js/routing';\nimport { ActionDisabledReason } from '@weasel-js/routing';\nimport type { ActionDeps } from '@weasel-js/routing';\nimport type { ImmediateInvoker, InvocationCtx, OngoingHandle } from '@weasel-js/routing';\nimport type { EditAnchorsDep } from '../depSchema';\nimport {\n anchorsInRect,\n deleteAnchorsAt,\n editAnchorSet,\n openSubpathAt,\n translateAnchorBy,\n type AnchorSet,\n} from 'features/paths/anchorEdits';\nimport { pathToAnchors } from 'features/paths/anchors';\nimport type { PolygonPath } from '@weasel-js/geom';\nimport { selectionAfterAnchorPress } from './editAnchors';\nimport { inPlane, editingLayer } from '../planeInput';\n\n// ---------------------------------------------------------------------------\n// Shared plumbing\n// ---------------------------------------------------------------------------\n\n/** Nudge step sizes — mirror `nudge.ts` so anchors and nodes move alike. */\nconst SMALL_STEP = 1;\nconst BIG_STEP = 10;\n\n/** World-unit radius for \"this click landed on an anchor\". Matches the\n * affordance hit radius closely enough that anything the user can see as\n * an anchor marker is cuttable. */\nconst ANCHOR_CLICK_SLOP = 10;\n\nfunction depOf(deps: ActionDeps | undefined): EditAnchorsDep | null {\n const dep = deps?.editAnchors as EditAnchorsDep | undefined;\n if (!dep || !dep.editingId) return null;\n return dep;\n}\n\n/** The edited node's world-space polygon, or null when unavailable. */\nfunction worldPathOf(dep: EditAnchorsDep): PolygonPath | null {\n const p = dep.getEditablePath(dep.editingId) as PolygonPath | undefined;\n if (!p || p.kind !== 'polygon') return null;\n return p;\n}\n\n/**\n * Decode → mutate → encode → commit, in one history entry. Returns false\n * when the edit changed nothing, so callers can skip the commit rather\n * than push an empty undo step.\n */\nfunction commitAnchorEdit(\n dep: EditAnchorsDep,\n label: string,\n edit: (set: Parameters<Parameters<typeof editAnchorSet>[1]>[0]) => boolean | void,\n): boolean {\n const worldPath = worldPathOf(dep);\n if (!worldPath) return false;\n const next = editAnchorSet(worldPath, edit);\n if (!next) return false;\n dep.applyEdit(dep.editingId, next, label);\n return true;\n}\n\n/** Enabled only while a path is in edit mode with anchors selected. */\nfunction requiresAnchorSelection(deps?: ActionDeps): true | ActionDisabledReason {\n const dep = depOf(deps);\n if (!dep || dep.selectedAnchors.size === 0) return ActionDisabledReason.SelectionRequired;\n return true;\n}\n\n// ---------------------------------------------------------------------------\n// selectAnchor\n// ---------------------------------------------------------------------------\n\n/**\n * Click an anchor to select it; Shift-click to toggle it in or out of the\n * selection. Clicking away from every anchor clears the anchor selection.\n *\n * ## Why this is a click action and not part of the drag\n *\n * The obvious home for \"pressing an anchor selects it\" is\n * `editAnchorsAction.start`, since that's the handler that receives the\n * anchor affordance. It can't live there: the dispatcher only dispatches\n * a drag binding once the pointer crosses the drag threshold, so a press\n * that never moves never reaches `start` at all. Verified in the running\n * app — down/up on an anchor logs a bare `click`, and down/move-3px/up\n * logs the same; only a real drag logs `pointerdown → editAnchors`.\n *\n * Clicks, in turn, carry no affordance (the dispatcher attaches those to\n * `pointerdown` only), so this resolves the anchor from the click's world\n * coords — the same thing `insertPathAnchorAction` does for segments.\n * `editAnchorsAction` still syncs the selection when a drag begins on an\n * unselected anchor, so drag-without-clicking-first behaves too.\n *\n * **Non-modal caveat:** `useSelectTool` binds `clearSelection` to\n * `{ click, target: 'empty', mods: {} }` at active scope, which outranks\n * this ambient binding. In path-edit mode that action is filtered out by\n * capability, so anchor clicks win. In a consumer with no mode registry\n * there's no filtering, so clicking an anchor that happens to sit over\n * empty canvas clears the node selection instead of selecting the anchor.\n * Anchors over the path body are unaffected.\n */\nexport const selectAnchorAction: Action & { requires: string[] } = inPlane({\n id: 'selectAnchor',\n label: 'Select anchor',\n defaultBinding: [\n { spec: { kind: 'click', mods: {} }, opts: { params: { additive: false } } },\n { spec: { kind: 'click', mods: { shift: true } }, opts: { params: { additive: true } } },\n ],\n eligible: { capability: 'edits-anchors' },\n requires: ['editAnchors'],\n invoker: {\n timing: 'immediate',\n run: (deps, params) => {\n const dep = depOf(deps);\n if (!dep) return;\n const wx = params?.worldX as number | undefined;\n const wy = params?.worldY as number | undefined;\n if (typeof wx !== 'number' || typeof wy !== 'number') return;\n const worldPath = worldPathOf(dep);\n if (!worldPath) return;\n\n const hit = nearestAnchorIndex(worldPath, wx, wy, ANCHOR_CLICK_SLOP);\n const additive = params?.additive === true;\n if (hit === -1) {\n // Missed every anchor. A bare click clears; a shift-click leaves\n // the selection alone so a stray miss mid-multi-select doesn't\n // undo the work.\n if (!additive) dep.setSelectedAnchors([]);\n return;\n }\n dep.setSelectedAnchors(selectionAfterAnchorPress(dep.selectedAnchors, hit, additive));\n },\n } as ImmediateInvoker,\n enabled: (deps) => (depOf(deps) ? true : ActionDisabledReason.SelectionRequired),\n}, editingLayer);\n\n// ---------------------------------------------------------------------------\n// nudgeAnchors\n// ---------------------------------------------------------------------------\n\ntype Direction = 'up' | 'down' | 'left' | 'right';\nconst KEY_FOR: Record<Direction, string> = {\n up: 'ArrowUp', down: 'ArrowDown', left: 'ArrowLeft', right: 'ArrowRight',\n};\nconst LABEL_FOR: Record<Direction, string> = {\n up: 'Up', down: 'Down', left: 'Left', right: 'Right',\n};\nfunction delta(dir: Direction, step: number): { dx: number; dy: number } {\n switch (dir) {\n case 'up': return { dx: 0, dy: -step };\n case 'down': return { dx: 0, dy: step };\n case 'left': return { dx: -step, dy: 0 };\n case 'right': return { dx: step, dy: 0 };\n }\n}\n\n/**\n * Move the selected anchors by one step. Shift multiplies the step, same\n * as node nudging.\n *\n * Every keystroke is its own history entry, matching node nudge — hold an\n * arrow down and undo walks back one step at a time rather than\n * collapsing the run.\n */\nfunction makeNudgeAnchorsAction(dir: Direction): Action & { requires: string[] } {\n return {\n id: `nudgeAnchors.${dir}`,\n label: `Nudge Anchors ${LABEL_FOR[dir]}`,\n group: 'nudgeAnchors',\n defaultBinding: [\n { spec: { kind: 'key', key: KEY_FOR[dir] }, opts: { params: { magnitude: 'small' } } },\n { spec: { kind: 'key', key: KEY_FOR[dir], mods: { shift: true } }, opts: { params: { magnitude: 'big' } } },\n ],\n eligible: { capability: 'edits-anchors' },\n requires: ['editAnchors'],\n invoker: {\n timing: 'immediate',\n run: (deps, params) => {\n const dep = depOf(deps);\n if (!dep || dep.selectedAnchors.size === 0) return;\n const step = params?.magnitude === 'big' ? BIG_STEP : SMALL_STEP;\n const { dx, dy } = delta(dir, step);\n const selected = [...dep.selectedAnchors];\n commitAnchorEdit(dep, 'Nudge anchor', (set) => {\n let any = false;\n for (const flat of selected) any = translateAnchorBy(set, flat, dx, dy) || any;\n return any;\n });\n },\n } as ImmediateInvoker,\n enabled: requiresAnchorSelection,\n };\n}\n\nexport const nudgeAnchorsUpAction = makeNudgeAnchorsAction('up');\nexport const nudgeAnchorsDownAction = makeNudgeAnchorsAction('down');\nexport const nudgeAnchorsLeftAction = makeNudgeAnchorsAction('left');\nexport const nudgeAnchorsRightAction = makeNudgeAnchorsAction('right');\n\n// ---------------------------------------------------------------------------\n// deleteAnchors\n// ---------------------------------------------------------------------------\n\n/**\n * Delete the selected anchors, refitting the surrounding curve through\n * each gap so the path keeps its shape.\n *\n * Deleting renumbers every anchor after the lowest deleted index, so the\n * selection is cleared rather than left pointing at whatever slid into\n * those slots.\n */\nexport const deleteAnchorsAction: Action & { requires: string[] } = {\n id: 'deleteAnchors',\n label: 'Delete Anchors',\n defaultBinding: {\n kind: 'key',\n key: ['Delete', 'Backspace'],\n phase: [{ channel: '*', phase: 'initial' }],\n },\n eligible: { capability: 'edits-anchors' },\n requires: ['editAnchors'],\n invoker: {\n timing: 'immediate',\n run: (deps) => {\n const dep = depOf(deps);\n if (!dep || dep.selectedAnchors.size === 0) return;\n const doomed = [...dep.selectedAnchors];\n const changed = commitAnchorEdit(dep, 'Delete anchor', (set) =>\n deleteAnchorsAt(set, doomed),\n );\n if (changed) dep.setSelectedAnchors([]);\n },\n } as ImmediateInvoker,\n enabled: requiresAnchorSelection,\n};\n\n// ---------------------------------------------------------------------------\n// cutPathAtAnchor (scissors)\n// ---------------------------------------------------------------------------\n\n/**\n * Open a closed subpath at the alt+shift-clicked anchor — the scissors\n * operation the pen tool used to own.\n *\n * Bound to Alt+Shift+click rather than plain Alt+click so it doesn't\n * collide with `insertPathAnchorAction`, which is already Alt+click on\n * the same path. Both are \"alt-click surgery on the edited path\"; the\n * extra modifier picks which one, instead of the two actions racing on an\n * identical binding where only one could ever win.\n *\n * No-ops on an open subpath: there's nothing to cut.\n */\nexport const cutPathAtAnchorAction: Action & { requires: string[] } = inPlane({\n id: 'cutPathAtAnchor',\n label: 'Cut path at anchor',\n defaultBinding: { kind: 'click', mods: { alt: true, shift: true } },\n eligible: { capability: 'edits-anchors' },\n requires: ['editAnchors'],\n invoker: {\n timing: 'immediate',\n run: (deps, params) => {\n const dep = depOf(deps);\n if (!dep) return;\n const wx = params?.worldX as number | undefined;\n const wy = params?.worldY as number | undefined;\n if (typeof wx !== 'number' || typeof wy !== 'number') return;\n const worldPath = worldPathOf(dep);\n if (!worldPath) return;\n\n // Find the anchor under the click. Clicks carry no affordance (only\n // pointerdown does), so this resolves the hit itself — the same\n // approach insertPathAnchorAction takes for segments.\n const nearest = nearestAnchorIndex(worldPath, wx, wy, ANCHOR_CLICK_SLOP);\n if (nearest === -1) return;\n\n const changed = commitAnchorEdit(dep, 'Cut path', (set) => openSubpathAt(set, nearest));\n // Cutting rotates the subpath's anchor order, so held indices are stale.\n if (changed) dep.setSelectedAnchors([]);\n },\n } as ImmediateInvoker,\n enabled: (deps) => (depOf(deps) ? true : ActionDisabledReason.SelectionRequired),\n}, editingLayer);\n\n/** Flat index of the anchor nearest `(wx, wy)` within `slop`, else -1. */\nfunction nearestAnchorIndex(\n path: PolygonPath,\n wx: number,\n wy: number,\n slop: number,\n): number {\n let best = -1;\n let bestD2 = slop * slop;\n let flat = 0;\n for (const sub of (pathToAnchors(path) as AnchorSet).anchors) {\n for (const a of sub) {\n const dx = a.x - wx;\n const dy = a.y - wy;\n const d2 = dx * dx + dy * dy;\n // `<=` so an exact-slop hit counts; ties go to the earlier anchor.\n if (d2 <= bestD2 && (best === -1 || d2 < bestD2)) {\n bestD2 = d2;\n best = flat;\n }\n flat++;\n }\n }\n return best;\n}\n\n// ---------------------------------------------------------------------------\n// marqueeAnchors\n// ---------------------------------------------------------------------------\n\n/**\n * Rubber-band select anchors by dragging on empty canvas while a path is\n * in edit mode.\n *\n * Shift adds to the existing anchor selection instead of replacing it.\n * The in-flight rect goes on the `editAnchors` dep so the path-editing\n * overlay can draw it — same \"ongoing action owns the state, chrome\n * draws it\" split the move ghosts and the node marquee use.\n */\nexport const marqueeAnchorsAction: Action & { requires: string[] } = inPlane({\n id: 'marqueeAnchors',\n label: 'Marquee-select anchors',\n defaultBinding: { kind: 'drag', target: 'empty' },\n eligible: { capability: 'edits-anchors' },\n requires: ['editAnchors'],\n invoker: {\n timing: 'ongoing',\n start(ctx: InvocationCtx): OngoingHandle {\n const dep = depOf(ctx.deps);\n // Not editing → decline so the dispatcher falls through to the\n // node-level areaSelect. This is what keeps non-modal consumers\n // (no eligibility filtering) behaving normally.\n if (!dep) return {};\n const worldPath = worldPathOf(dep);\n if (!worldPath) return {};\n\n const additive = ctx.modifiers.shift;\n const base = new Set(dep.selectedAnchors);\n const start = { x: ctx.world.x, y: ctx.world.y };\n\n const rectFrom = (cx: number, cy: number) => ({\n x: Math.min(start.x, cx),\n y: Math.min(start.y, cy),\n width: Math.abs(cx - start.x),\n height: Math.abs(cy - start.y),\n });\n\n return {\n kind: 'marquee-anchors',\n onMove(moveCtx: InvocationCtx): void {\n const rect = rectFrom(moveCtx.world.x, moveCtx.world.y);\n dep.setMarquee(rect);\n // Live selection preview: the user sees anchors light up as the\n // band sweeps them, rather than only on release.\n const hits = anchorsOfPathInRect(worldPath, rect);\n dep.setSelectedAnchors(additive ? new Set([...base, ...hits]) : hits);\n },\n onEnd(_endCtx: InvocationCtx, reason: 'commit' | 'cancel'): void {\n dep.setMarquee(null);\n if (reason === 'cancel') dep.setSelectedAnchors(base);\n },\n };\n },\n },\n enabled: () => true,\n}, editingLayer);\n\n// ---------------------------------------------------------------------------\n// Local geometry helper\n// ---------------------------------------------------------------------------\n\n/** Flat indices of `path`'s anchors inside `rect`. */\nfunction anchorsOfPathInRect(\n path: PolygonPath,\n rect: { x: number; y: number; width: number; height: number },\n): number[] {\n return anchorsInRect(pathToAnchors(path) as AnchorSet, rect);\n}\n"],"mappings":";;;;;;AAsDA,IAAMA,IAAa,GACbC,IAAW,IAKXC,IAAoB;AAE1B,SAASC,EAAM,GAAqD;CAClE,IAAMC,IAAMC,GAAM;CAElB,OADI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IvD,EAAI,eAAe,GAClCwD,IAAQ;IAAE,GAAGF,EAAI,MAAM;IAAG,GAAGA,EAAI,MAAM;GAAE,GAEzCG,KAAY,GAAY,OAAgB;IAC5C,GAAG,KAAK,IAAID,EAAM,GAAGE,CAAE;IACvB,GAAG,KAAK,IAAIF,EAAM,GAAGG,CAAE;IACvB,OAAO,KAAK,IAAID,IAAKF,EAAM,CAAC;IAC5B,QAAQ,KAAK,IAAIG,IAAKH,EAAM,CAAC;GAC/B;GAEA,OAAO;IACL,MAAM;IACN,OAAO,GAA8B;KACnC,IAAMI,IAAOH,EAASI,EAAQ,MAAM,GAAGA,EAAQ,MAAM,CAAC;KACtD,EAAI,WAAWD,CAAI;KAGnB,IAAME,IAAOC,EAAoB1D,GAAWuD,CAAI;KAChD,EAAI,mBAAmBzC,oBAAW,IAAI,IAAI,CAAC,GAAGoC,GAAM,GAAGO,CAAI,CAAC,IAAIA,CAAI;IACtE;IACA,MAAM,GAAwB,GAAmC;KAE/D,AADA9D,EAAI,WAAW,IAAI,GACfgE,MAAW,YAAUhE,EAAI,mBAAmBuD,CAAI;IACtD;GACF;EACF;CACF;CACA,eAAe;AACjB,GAAGlC,CAAY;AAOf,SAAS0C,EACP,GACA,GACU;CACV,OAAOE,EAAchB,EAAcC,CAAI,GAAgBU,CAAI;AAC7D"}
|
|
1
|
+
{"version":3,"file":"anchorEditing.js","names":["SMALL_STEP","BIG_STEP","ANCHOR_CLICK_SLOP","depOf","dep","deps","worldPathOf","p","commitAnchorEdit","worldPath","next","editAnchorSet","edit","label","requiresAnchorSelection","ActionDisabledReason","selectAnchorAction","inPlane","wx","params","wy","hit","nearestAnchorIndex","additive","selectionAfterAnchorPress","editingLayer","KEY_FOR","LABEL_FOR","delta","dir","step","makeNudgeAnchorsAction","selected","any","flat","translateAnchorBy","set","dx","dy","nudgeAnchorsUpAction","nudgeAnchorsDownAction","nudgeAnchorsLeftAction","nudgeAnchorsRightAction","deleteAnchorsAction","doomed","deleteAnchorsAt","cutPathAtAnchorAction","nearest","openSubpathAt","best","bestD2","slop","sub","pathToAnchors","path","a","d2","marqueeAnchorsAction","ctx","base","start","rectFrom","cx","cy","rect","moveCtx","hits","anchorsOfPathInRect","reason","anchorsInRect"],"sources":["../../../../src/interactions/actions/defaults/anchorEditing.ts"],"sourcesContent":["/**\n * Anchor-editing Actions beyond the drag itself — the keyboard and\n * marquee half of path editing.\n *\n * These were previously only reachable through the pen tool's private\n * edit mode, which no consumer could actually enter (its `getPathObj`\n * hook needed a `pose.kind` that no kit-created node has). Porting them\n * onto the Action layer puts them behind the same `editAnchors` dep,\n * `edits-anchors` capability, and undo path as `editAnchorsAction`.\n *\n * ## Why these don't collide with their node-level counterparts\n *\n * Each has a node-level twin bound to the same gesture: `deleteAction`\n * (Delete/Backspace), `nudge.*` (arrows), `areaSelectAction` (drag on\n * empty). Two mechanisms keep them apart, and both are needed:\n *\n * - **Capability eligibility**, when a mode registry is wired. The\n * node-level twins gate on `edits-page` / `transforms-selection` /\n * `creates-selection`, none of which `path-edit` mode allows, so the\n * dispatcher filters them out before matching.\n * - **`enabled` fall-through**, for the many consumers with no mode\n * registry at all. There the eligibility filter is skipped entirely,\n * so these actions report themselves disabled unless a path is\n * actually being edited with anchors selected, and the dispatcher\n * moves on to the node-level twin.\n *\n * Relying on eligibility alone would break every non-modal consumer;\n * relying on `enabled` alone would let a node-level action fire inside\n * path-edit mode. See `anchorEditing.test.ts`.\n */\n\nimport type { Action } from '@weasel-js/routing';\nimport { ActionDisabledReason } from '@weasel-js/routing';\nimport type { ActionDeps } from '@weasel-js/routing';\nimport type { ImmediateInvoker, InvocationCtx, OngoingHandle } from '@weasel-js/routing';\nimport type { EditAnchorsDep } from '../depSchema';\nimport {\n anchorsInRect,\n deleteAnchorsAt,\n editAnchorSet,\n openSubpathAt,\n translateAnchorBy,\n type AnchorSet,\n} from 'features/paths/anchorEdits';\nimport { pathToAnchors } from 'features/paths/anchors';\nimport type { PolygonPath } from '@weasel-js/geom';\nimport { selectionAfterAnchorPress } from './editAnchors';\nimport { inPlane, editingLayer } from '../planeInput';\n\n// ---------------------------------------------------------------------------\n// Shared plumbing\n// ---------------------------------------------------------------------------\n\n/** Nudge step sizes — mirror `nudge.ts` so anchors and nodes move alike. */\nconst SMALL_STEP = 1;\nconst BIG_STEP = 10;\n\n/** World-unit radius for \"this click landed on an anchor\". Matches the\n * affordance hit radius closely enough that anything the user can see as\n * an anchor marker is cuttable. */\nconst ANCHOR_CLICK_SLOP = 10;\n\nfunction depOf(deps: ActionDeps | undefined): EditAnchorsDep | null {\n const dep = deps?.editAnchors;\n if (!dep || !dep.editingId) return null;\n return dep;\n}\n\n/** The edited node's world-space polygon, or null when unavailable. */\nfunction worldPathOf(dep: EditAnchorsDep): PolygonPath | null {\n const p = dep.getEditablePath(dep.editingId) as PolygonPath | undefined;\n if (!p || p.kind !== 'polygon') return null;\n return p;\n}\n\n/**\n * Decode → mutate → encode → commit, in one history entry. Returns false\n * when the edit changed nothing, so callers can skip the commit rather\n * than push an empty undo step.\n */\nfunction commitAnchorEdit(\n dep: EditAnchorsDep,\n label: string,\n edit: (set: Parameters<Parameters<typeof editAnchorSet>[1]>[0]) => boolean | void,\n): boolean {\n const worldPath = worldPathOf(dep);\n if (!worldPath) return false;\n const next = editAnchorSet(worldPath, edit);\n if (!next) return false;\n dep.applyEdit(dep.editingId, next, label);\n return true;\n}\n\n/** Enabled only while a path is in edit mode with anchors selected. */\nfunction requiresAnchorSelection(deps?: ActionDeps): true | ActionDisabledReason {\n const dep = depOf(deps);\n if (!dep || dep.selectedAnchors.size === 0) return ActionDisabledReason.SelectionRequired;\n return true;\n}\n\n// ---------------------------------------------------------------------------\n// selectAnchor\n// ---------------------------------------------------------------------------\n\n/**\n * Click an anchor to select it; Shift-click to toggle it in or out of the\n * selection. Clicking away from every anchor clears the anchor selection.\n *\n * ## Why this is a click action and not part of the drag\n *\n * The obvious home for \"pressing an anchor selects it\" is\n * `editAnchorsAction.start`, since that's the handler that receives the\n * anchor affordance. It can't live there: the dispatcher only dispatches\n * a drag binding once the pointer crosses the drag threshold, so a press\n * that never moves never reaches `start` at all. Verified in the running\n * app — down/up on an anchor logs a bare `click`, and down/move-3px/up\n * logs the same; only a real drag logs `pointerdown → editAnchors`.\n *\n * Clicks, in turn, carry no affordance (the dispatcher attaches those to\n * `pointerdown` only), so this resolves the anchor from the click's world\n * coords — the same thing `insertPathAnchorAction` does for segments.\n * `editAnchorsAction` still syncs the selection when a drag begins on an\n * unselected anchor, so drag-without-clicking-first behaves too.\n *\n * **Non-modal caveat:** `useSelectTool` binds `clearSelection` to\n * `{ click, target: 'empty', mods: {} }` at active scope, which outranks\n * this ambient binding. In path-edit mode that action is filtered out by\n * capability, so anchor clicks win. In a consumer with no mode registry\n * there's no filtering, so clicking an anchor that happens to sit over\n * empty canvas clears the node selection instead of selecting the anchor.\n * Anchors over the path body are unaffected.\n */\nexport const selectAnchorAction: Action & { requires: string[] } = inPlane({\n id: 'selectAnchor',\n label: 'Select anchor',\n defaultBinding: [\n { spec: { kind: 'click', mods: {} }, opts: { params: { additive: false } } },\n { spec: { kind: 'click', mods: { shift: true } }, opts: { params: { additive: true } } },\n ],\n eligible: { capability: 'edits-anchors' },\n requires: ['editAnchors'],\n invoker: {\n timing: 'immediate',\n run: (deps, params) => {\n const dep = depOf(deps);\n if (!dep) return;\n const wx = params?.worldX as number | undefined;\n const wy = params?.worldY as number | undefined;\n if (typeof wx !== 'number' || typeof wy !== 'number') return;\n const worldPath = worldPathOf(dep);\n if (!worldPath) return;\n\n const hit = nearestAnchorIndex(worldPath, wx, wy, ANCHOR_CLICK_SLOP);\n const additive = params?.additive === true;\n if (hit === -1) {\n // Missed every anchor. A bare click clears; a shift-click leaves\n // the selection alone so a stray miss mid-multi-select doesn't\n // undo the work.\n if (!additive) dep.setSelectedAnchors([]);\n return;\n }\n dep.setSelectedAnchors(selectionAfterAnchorPress(dep.selectedAnchors, hit, additive));\n },\n } as ImmediateInvoker,\n enabled: (deps) => (depOf(deps) ? true : ActionDisabledReason.SelectionRequired),\n}, editingLayer);\n\n// ---------------------------------------------------------------------------\n// nudgeAnchors\n// ---------------------------------------------------------------------------\n\ntype Direction = 'up' | 'down' | 'left' | 'right';\nconst KEY_FOR: Record<Direction, string> = {\n up: 'ArrowUp', down: 'ArrowDown', left: 'ArrowLeft', right: 'ArrowRight',\n};\nconst LABEL_FOR: Record<Direction, string> = {\n up: 'Up', down: 'Down', left: 'Left', right: 'Right',\n};\nfunction delta(dir: Direction, step: number): { dx: number; dy: number } {\n switch (dir) {\n case 'up': return { dx: 0, dy: -step };\n case 'down': return { dx: 0, dy: step };\n case 'left': return { dx: -step, dy: 0 };\n case 'right': return { dx: step, dy: 0 };\n }\n}\n\n/**\n * Move the selected anchors by one step. Shift multiplies the step, same\n * as node nudging.\n *\n * Every keystroke is its own history entry, matching node nudge — hold an\n * arrow down and undo walks back one step at a time rather than\n * collapsing the run.\n */\nfunction makeNudgeAnchorsAction(dir: Direction): Action & { requires: string[] } {\n return {\n id: `nudgeAnchors.${dir}`,\n label: `Nudge Anchors ${LABEL_FOR[dir]}`,\n group: 'nudgeAnchors',\n defaultBinding: [\n { spec: { kind: 'key', key: KEY_FOR[dir] }, opts: { params: { magnitude: 'small' } } },\n { spec: { kind: 'key', key: KEY_FOR[dir], mods: { shift: true } }, opts: { params: { magnitude: 'big' } } },\n ],\n eligible: { capability: 'edits-anchors' },\n requires: ['editAnchors'],\n invoker: {\n timing: 'immediate',\n run: (deps, params) => {\n const dep = depOf(deps);\n if (!dep || dep.selectedAnchors.size === 0) return;\n const step = params?.magnitude === 'big' ? BIG_STEP : SMALL_STEP;\n const { dx, dy } = delta(dir, step);\n const selected = [...dep.selectedAnchors];\n commitAnchorEdit(dep, 'Nudge anchor', (set) => {\n let any = false;\n for (const flat of selected) any = translateAnchorBy(set, flat, dx, dy) || any;\n return any;\n });\n },\n } as ImmediateInvoker,\n enabled: requiresAnchorSelection,\n };\n}\n\nexport const nudgeAnchorsUpAction = makeNudgeAnchorsAction('up');\nexport const nudgeAnchorsDownAction = makeNudgeAnchorsAction('down');\nexport const nudgeAnchorsLeftAction = makeNudgeAnchorsAction('left');\nexport const nudgeAnchorsRightAction = makeNudgeAnchorsAction('right');\n\n// ---------------------------------------------------------------------------\n// deleteAnchors\n// ---------------------------------------------------------------------------\n\n/**\n * Delete the selected anchors, refitting the surrounding curve through\n * each gap so the path keeps its shape.\n *\n * Deleting renumbers every anchor after the lowest deleted index, so the\n * selection is cleared rather than left pointing at whatever slid into\n * those slots.\n */\nexport const deleteAnchorsAction: Action & { requires: string[] } = {\n id: 'deleteAnchors',\n label: 'Delete Anchors',\n defaultBinding: {\n kind: 'key',\n key: ['Delete', 'Backspace'],\n phase: [{ channel: '*', phase: 'initial' }],\n },\n eligible: { capability: 'edits-anchors' },\n requires: ['editAnchors'],\n invoker: {\n timing: 'immediate',\n run: (deps) => {\n const dep = depOf(deps);\n if (!dep || dep.selectedAnchors.size === 0) return;\n const doomed = [...dep.selectedAnchors];\n const changed = commitAnchorEdit(dep, 'Delete anchor', (set) =>\n deleteAnchorsAt(set, doomed),\n );\n if (changed) dep.setSelectedAnchors([]);\n },\n } as ImmediateInvoker,\n enabled: requiresAnchorSelection,\n};\n\n// ---------------------------------------------------------------------------\n// cutPathAtAnchor (scissors)\n// ---------------------------------------------------------------------------\n\n/**\n * Open a closed subpath at the alt+shift-clicked anchor — the scissors\n * operation the pen tool used to own.\n *\n * Bound to Alt+Shift+click rather than plain Alt+click so it doesn't\n * collide with `insertPathAnchorAction`, which is already Alt+click on\n * the same path. Both are \"alt-click surgery on the edited path\"; the\n * extra modifier picks which one, instead of the two actions racing on an\n * identical binding where only one could ever win.\n *\n * No-ops on an open subpath: there's nothing to cut.\n */\nexport const cutPathAtAnchorAction: Action & { requires: string[] } = inPlane({\n id: 'cutPathAtAnchor',\n label: 'Cut path at anchor',\n defaultBinding: { kind: 'click', mods: { alt: true, shift: true } },\n eligible: { capability: 'edits-anchors' },\n requires: ['editAnchors'],\n invoker: {\n timing: 'immediate',\n run: (deps, params) => {\n const dep = depOf(deps);\n if (!dep) return;\n const wx = params?.worldX as number | undefined;\n const wy = params?.worldY as number | undefined;\n if (typeof wx !== 'number' || typeof wy !== 'number') return;\n const worldPath = worldPathOf(dep);\n if (!worldPath) return;\n\n // Find the anchor under the click. Clicks carry no affordance (only\n // pointerdown does), so this resolves the hit itself — the same\n // approach insertPathAnchorAction takes for segments.\n const nearest = nearestAnchorIndex(worldPath, wx, wy, ANCHOR_CLICK_SLOP);\n if (nearest === -1) return;\n\n const changed = commitAnchorEdit(dep, 'Cut path', (set) => openSubpathAt(set, nearest));\n // Cutting rotates the subpath's anchor order, so held indices are stale.\n if (changed) dep.setSelectedAnchors([]);\n },\n } as ImmediateInvoker,\n enabled: (deps) => (depOf(deps) ? true : ActionDisabledReason.SelectionRequired),\n}, editingLayer);\n\n/** Flat index of the anchor nearest `(wx, wy)` within `slop`, else -1. */\nfunction nearestAnchorIndex(\n path: PolygonPath,\n wx: number,\n wy: number,\n slop: number,\n): number {\n let best = -1;\n let bestD2 = slop * slop;\n let flat = 0;\n for (const sub of (pathToAnchors(path) as AnchorSet).anchors) {\n for (const a of sub) {\n const dx = a.x - wx;\n const dy = a.y - wy;\n const d2 = dx * dx + dy * dy;\n // `<=` so an exact-slop hit counts; ties go to the earlier anchor.\n if (d2 <= bestD2 && (best === -1 || d2 < bestD2)) {\n bestD2 = d2;\n best = flat;\n }\n flat++;\n }\n }\n return best;\n}\n\n// ---------------------------------------------------------------------------\n// marqueeAnchors\n// ---------------------------------------------------------------------------\n\n/**\n * Rubber-band select anchors by dragging on empty canvas while a path is\n * in edit mode.\n *\n * Shift adds to the existing anchor selection instead of replacing it.\n * The in-flight rect goes on the `editAnchors` dep so the path-editing\n * overlay can draw it — same \"ongoing action owns the state, chrome\n * draws it\" split the move ghosts and the node marquee use.\n */\nexport const marqueeAnchorsAction: Action & { requires: string[] } = inPlane({\n id: 'marqueeAnchors',\n label: 'Marquee-select anchors',\n defaultBinding: { kind: 'drag', target: 'empty' },\n eligible: { capability: 'edits-anchors' },\n requires: ['editAnchors'],\n invoker: {\n timing: 'ongoing',\n start(ctx: InvocationCtx): OngoingHandle {\n const dep = depOf(ctx.deps);\n // Not editing → decline so the dispatcher falls through to the\n // node-level areaSelect. This is what keeps non-modal consumers\n // (no eligibility filtering) behaving normally.\n if (!dep) return {};\n const worldPath = worldPathOf(dep);\n if (!worldPath) return {};\n\n const additive = ctx.modifiers.shift;\n const base = new Set(dep.selectedAnchors);\n const start = { x: ctx.world.x, y: ctx.world.y };\n\n const rectFrom = (cx: number, cy: number) => ({\n x: Math.min(start.x, cx),\n y: Math.min(start.y, cy),\n width: Math.abs(cx - start.x),\n height: Math.abs(cy - start.y),\n });\n\n return {\n kind: 'marquee-anchors',\n onMove(moveCtx: InvocationCtx): void {\n const rect = rectFrom(moveCtx.world.x, moveCtx.world.y);\n dep.setMarquee(rect);\n // Live selection preview: the user sees anchors light up as the\n // band sweeps them, rather than only on release.\n const hits = anchorsOfPathInRect(worldPath, rect);\n dep.setSelectedAnchors(additive ? new Set([...base, ...hits]) : hits);\n },\n onEnd(_endCtx: InvocationCtx, reason: 'commit' | 'cancel'): void {\n dep.setMarquee(null);\n if (reason === 'cancel') dep.setSelectedAnchors(base);\n },\n };\n },\n },\n enabled: () => true,\n}, editingLayer);\n\n// ---------------------------------------------------------------------------\n// Local geometry helper\n// ---------------------------------------------------------------------------\n\n/** Flat indices of `path`'s anchors inside `rect`. */\nfunction anchorsOfPathInRect(\n path: PolygonPath,\n rect: { x: number; y: number; width: number; height: number },\n): number[] {\n return anchorsInRect(pathToAnchors(path) as AnchorSet, rect);\n}\n"],"mappings":";;;;;;AAsDA,IAAMA,IAAa,GACbC,IAAW,IAKXC,IAAoB;AAE1B,SAASC,EAAM,GAAqD;CAClE,IAAMC,IAAMC,GAAM;CAElB,OADI,CAACD,KAAO,CAACA,EAAI,YAAkB,OAC5BA;AACT;AAGA,SAASE,EAAY,GAAyC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,EAAI,MAAM;GAAE,GAEzCG,KAAY,GAAY,OAAgB;IAC5C,GAAG,KAAK,IAAID,EAAM,GAAGE,CAAE;IACvB,GAAG,KAAK,IAAIF,EAAM,GAAGG,CAAE;IACvB,OAAO,KAAK,IAAID,IAAKF,EAAM,CAAC;IAC5B,QAAQ,KAAK,IAAIG,IAAKH,EAAM,CAAC;GAC/B;GAEA,OAAO;IACL,MAAM;IACN,OAAO,GAA8B;KACnC,IAAMI,IAAOH,EAASI,EAAQ,MAAM,GAAGA,EAAQ,MAAM,CAAC;KACtD,EAAI,WAAWD,CAAI;KAGnB,IAAME,IAAOC,EAAoB1D,GAAWuD,CAAI;KAChD,EAAI,mBAAmBzC,oBAAW,IAAI,IAAI,CAAC,GAAGoC,GAAM,GAAGO,CAAI,CAAC,IAAIA,CAAI;IACtE;IACA,MAAM,GAAwB,GAAmC;KAE/D,AADA9D,EAAI,WAAW,IAAI,GACfgE,MAAW,YAAUhE,EAAI,mBAAmBuD,CAAI;IACtD;GACF;EACF;CACF;CACA,eAAe;AACjB,GAAGlC,CAAY;AAOf,SAAS0C,EACP,GACA,GACU;CACV,OAAOE,EAAchB,EAAcC,CAAI,GAAgBU,CAAI;AAC7D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"areaSelect.js","names":["areaSelectAction","dep","ctx","affordanceKind","scratch","moveCtx","reason","d","x","startX","currentX","y","startY","currentY","width","height","shiftHeld","hits","view","merged","id"],"sources":["../../../../src/interactions/actions/defaults/areaSelect.ts"],"sourcesContent":["/**\n * `areaSelectAction` — ongoing Action descriptor for marquee area selection.\n *\n * ## Status: REAL\n *\n * Implements the marquee selection logic from `useAreaSelect`:\n * - `start`: records the drag start world point and shift state.\n * - `onMove`: tracks the current drag corner (no scene writes).\n * - `onEnd('commit')`: derives the marquee bounds from start + current;\n * calls `deps.areaSelect.hitTestArea(bounds)` to find overlapping nodes;\n * calls `deps.areaSelect.setSelection(ids)` to update selection (extending\n * with shift held). This is a **transient** write (no undo entry) matching\n * `useAreaSelect`'s `defaultTransient: true` convention from\n * `selectFromMarquee`.\n * - `onEnd('cancel')`: no-op.\n *\n * ## Dependencies\n *\n * Requires `areaSelect` dep from DepSchema:\n * `{ hitTestArea(bounds): NodeId[], getSelection(): NodeId[], setSelection(ids): void }`\n *\n * `<SceneCanvas>` / `<StandardActionsRegistrar>` should source this dep by\n * iterating scene nodes and checking AABB overlap. The dep is intentionally\n * simple — consumers override it for custom hit-testing (contain-mode,\n * layer-aware filtering, etc.).\n *\n * ## What this does NOT wire (vs `useAreaSelect`)\n *\n * - Live marquee overlay rendering — deferred to Phase 7 overlay surface.\n * - `AreaSelectBehavior` pipeline — omitted; only the default replace/extend\n * semantics are implemented.\n * - Debug sink recording — not available in the descriptor model.\n */\n\nimport type { Action } from '@weasel-js/routing';\nimport type { InvocationCtx, OngoingHandle, OngoingOverlay } from '@weasel-js/routing';\nimport type { NodeId } from 'core/scene/types';\nimport type { AreaSelectDep, ViewApi } from '../depSchema';\n\n// ---------------------------------------------------------------------------\n// Internal scratch\n// ---------------------------------------------------------------------------\n\ninterface AreaSelectScratch {\n dep: AreaSelectDep;\n /** The view the marquee started in: what it does not paint is not taken. */\n view: ViewApi | undefined;\n startX: number;\n startY: number;\n shiftHeld: boolean;\n currentX: number;\n currentY: number;\n /** Cleared once `onEnd` runs so subsequent `overlay()` calls report no\n * in-flight marquee (the dispatcher releases the handle after onEnd so\n * this is belt-and-suspenders for any consumer that retains a handle). */\n open: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Descriptor\n// ---------------------------------------------------------------------------\n\n/**\n * @experimental\n * Static descriptor for the `areaSelect` Action.\n *\n * Requires dep-schema entry: `areaSelect`.\n *\n * The invoker implements replace/extend marquee selection via the `areaSelect`\n * dep. Hit-testing and selection writes are delegated to the dep; the invoker\n * contains only the bounds-derivation and shift-extend logic.\n *\n * @see useAreaSelect — the React hook this descriptor mirrors for the default case.\n */\nexport const areaSelectAction: Action & { requires: string[] } = {\n id: 'areaSelect',\n label: 'Area Select',\n // Crosshair while the marquee is being pulled — the select tool used to\n // read this off its own gesture scratch.\n activeCursor: 'crosshair',\n eligible: { capability: 'creates-selection' },\n requires: ['areaSelect', 'editAnchors', 'view'],\n invoker: {\n timing: 'ongoing',\n start(ctx: InvocationCtx, _opts): OngoingHandle {\n const dep = ctx.deps.areaSelect
|
|
1
|
+
{"version":3,"file":"areaSelect.js","names":["areaSelectAction","dep","ctx","affordanceKind","scratch","moveCtx","reason","d","x","startX","currentX","y","startY","currentY","width","height","shiftHeld","hits","view","merged","id"],"sources":["../../../../src/interactions/actions/defaults/areaSelect.ts"],"sourcesContent":["/**\n * `areaSelectAction` — ongoing Action descriptor for marquee area selection.\n *\n * ## Status: REAL\n *\n * Implements the marquee selection logic from `useAreaSelect`:\n * - `start`: records the drag start world point and shift state.\n * - `onMove`: tracks the current drag corner (no scene writes).\n * - `onEnd('commit')`: derives the marquee bounds from start + current;\n * calls `deps.areaSelect.hitTestArea(bounds)` to find overlapping nodes;\n * calls `deps.areaSelect.setSelection(ids)` to update selection (extending\n * with shift held). This is a **transient** write (no undo entry) matching\n * `useAreaSelect`'s `defaultTransient: true` convention from\n * `selectFromMarquee`.\n * - `onEnd('cancel')`: no-op.\n *\n * ## Dependencies\n *\n * Requires `areaSelect` dep from DepSchema:\n * `{ hitTestArea(bounds): NodeId[], getSelection(): NodeId[], setSelection(ids): void }`\n *\n * `<SceneCanvas>` / `<StandardActionsRegistrar>` should source this dep by\n * iterating scene nodes and checking AABB overlap. The dep is intentionally\n * simple — consumers override it for custom hit-testing (contain-mode,\n * layer-aware filtering, etc.).\n *\n * ## What this does NOT wire (vs `useAreaSelect`)\n *\n * - Live marquee overlay rendering — deferred to Phase 7 overlay surface.\n * - `AreaSelectBehavior` pipeline — omitted; only the default replace/extend\n * semantics are implemented.\n * - Debug sink recording — not available in the descriptor model.\n */\n\nimport type { Action } from '@weasel-js/routing';\nimport type { InvocationCtx, OngoingHandle, OngoingOverlay } from '@weasel-js/routing';\nimport type { NodeId } from 'core/scene/types';\nimport type { AreaSelectDep, ViewApi } from '../depSchema';\n\n// ---------------------------------------------------------------------------\n// Internal scratch\n// ---------------------------------------------------------------------------\n\ninterface AreaSelectScratch {\n dep: AreaSelectDep;\n /** The view the marquee started in: what it does not paint is not taken. */\n view: ViewApi | undefined;\n startX: number;\n startY: number;\n shiftHeld: boolean;\n currentX: number;\n currentY: number;\n /** Cleared once `onEnd` runs so subsequent `overlay()` calls report no\n * in-flight marquee (the dispatcher releases the handle after onEnd so\n * this is belt-and-suspenders for any consumer that retains a handle). */\n open: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Descriptor\n// ---------------------------------------------------------------------------\n\n/**\n * @experimental\n * Static descriptor for the `areaSelect` Action.\n *\n * Requires dep-schema entry: `areaSelect`.\n *\n * The invoker implements replace/extend marquee selection via the `areaSelect`\n * dep. Hit-testing and selection writes are delegated to the dep; the invoker\n * contains only the bounds-derivation and shift-extend logic.\n *\n * @see useAreaSelect — the React hook this descriptor mirrors for the default case.\n */\nexport const areaSelectAction: Action & { requires: string[] } = {\n id: 'areaSelect',\n label: 'Area Select',\n // Crosshair while the marquee is being pulled — the select tool used to\n // read this off its own gesture scratch.\n activeCursor: 'crosshair',\n eligible: { capability: 'creates-selection' },\n requires: ['areaSelect', 'editAnchors', 'view'],\n invoker: {\n timing: 'ongoing',\n start(ctx: InvocationCtx, _opts): OngoingHandle {\n const dep = ctx.deps.areaSelect;\n if (!dep) return {};\n\n // Decline on anchor / control-handle affordances: the select tool's\n // active-scope binding for this action is `{ kind: 'drag', target: 'empty' }`,\n // which matches whenever `bodyTarget === 'empty'` — including drags\n // where an anchor was hit on top of empty body. Without this opt-out\n // areaSelect would beat editAnchors via scope priority. The\n // dispatcher's empty-handle fallthrough then forwards the gesture.\n const affordanceKind = ctx.drag?.affordance?.kind;\n if (\n typeof affordanceKind === 'string'\n && /^(anchor|controlIn|controlOut):/.test(affordanceKind)\n ) {\n return {};\n }\n\n // Decline for the same reason while a path is in anchor-edit mode:\n // an empty-canvas drag there means \"rubber-band some anchors\", which\n // is `marqueeAnchorsAction`'s job. Capability eligibility already\n // filters this action out in path-edit mode, but only for consumers\n // that wired a mode registry — without one the dispatcher skips\n // eligibility entirely and areaSelect's active scope would beat\n // marqueeAnchors' ambient scope. Declining here covers both.\n const editAnchors = ctx.deps.editAnchors;\n if (editAnchors?.editingId) return {};\n\n // Drag start is the world point at the moment start() is called.\n const scratch: AreaSelectScratch = {\n dep,\n view: ctx.deps.view,\n startX: ctx.world.x,\n startY: ctx.world.y,\n shiftHeld: ctx.modifiers.shift,\n currentX: ctx.world.x,\n currentY: ctx.world.y,\n open: true,\n };\n\n return {\n kind: 'marquee',\n onMove(moveCtx: InvocationCtx): void {\n scratch.currentX = moveCtx.world.x;\n scratch.currentY = moveCtx.world.y;\n },\n overlay(): OngoingOverlay | null {\n if (!scratch.open) return null;\n return {\n kind: 'marquee',\n start: { x: scratch.startX, y: scratch.startY },\n current: { x: scratch.currentX, y: scratch.currentY },\n shiftHeld: scratch.shiftHeld,\n };\n },\n onEnd(_endCtx: InvocationCtx, reason: 'commit' | 'cancel'): void {\n scratch.open = false;\n if (reason === 'cancel') return;\n\n const { dep: d, view, startX, startY, currentX, currentY, shiftHeld } = scratch;\n\n // Derive the marquee AABB from the two world-space corners.\n const x = Math.min(startX, currentX);\n const y = Math.min(startY, currentY);\n const width = Math.abs(currentX - startX);\n const height = Math.abs(currentY - startY);\n\n // Zero-size marquee (click without drag) → clear selection (or no-op with shift).\n if (width === 0 || height === 0) {\n if (!shiftHeld) d.setSelection([]);\n return;\n }\n\n const hits = d.hitTestArea({ x, y, width, height }, view) as NodeId[];\n\n if (shiftHeld) {\n const current = d.getSelection();\n // Extend: merge current + hits (deduplicated).\n const merged = [...current];\n for (const id of hits) {\n if (!merged.includes(id)) merged.push(id);\n }\n d.setSelection(merged);\n } else {\n d.setSelection(hits);\n }\n },\n };\n },\n },\n /**\n * Always enabled at the dispatcher level. The dispatcher's\n * specificity-fallthrough loop treats anything `!== true` as \"skip this\n * match\" — returning a disabled reason would let lower-specificity\n * ambient bindings win. The invoker has no preconditions to guard.\n */\n enabled: () => true,\n};\n"],"mappings":";AA0EA,IAAaA,IAAoD;CAC/D,IAAI;CACJ,OAAO;CAGP,cAAc;CACd,UAAU,EAAE,YAAY,oBAAoB;CAC5C,UAAU;EAAC;EAAc;EAAe;CAAM;CAC9C,SAAS;EACP,QAAQ;EACR,MAAM,GAAoB,GAAsB;GAC9C,IAAMC,IAAMC,EAAI,KAAK;GACrB,IAAI,CAACD,GAAK,OAAO,CAAC;GAQlB,IAAME,IAAiBD,EAAI,MAAM,YAAY;GAgB7C,IAdE,OAAOC,KAAmB,YACvB,kCAAkC,KAAKA,CAAc,KAYtCD,EAAI,KAAK,aACZ,WAAW,OAAO,CAAC;GAGpC,IAAME,IAA6B;IACjC;IACA,MAAMF,EAAI,KAAK;IACf,QAAQA,EAAI,MAAM;IAClB,QAAQA,EAAI,MAAM;IAClB,WAAWA,EAAI,UAAU;IACzB,UAAUA,EAAI,MAAM;IACpB,UAAUA,EAAI,MAAM;IACpB,MAAM;GACR;GAEA,OAAO;IACL,MAAM;IACN,OAAO,GAA8B;KAEnC,AADA,EAAQ,WAAWG,EAAQ,MAAM,GACjC,EAAQ,WAAWA,EAAQ,MAAM;IACnC;IACA,UAAiC;KAE/B,OADKD,EAAQ,OACN;MACL,MAAM;MACN,OAAO;OAAE,GAAGA,EAAQ;OAAQ,GAAGA,EAAQ;MAAO;MAC9C,SAAS;OAAE,GAAGA,EAAQ;OAAU,GAAGA,EAAQ;MAAS;MACpD,WAAWA,EAAQ;KACrB,IAN0B;IAO5B;IACA,MAAM,GAAwB,GAAmC;KAE/D,IADA,EAAQ,OAAO,IACXE,MAAW,UAAU;KAEzB,IAAM,EAAE,KAAKC,GAAG,SAAM,WAAQ,WAAQ,aAAU,aAAU,iBAAcH,GAGlEI,IAAI,KAAK,IAAIC,GAAQC,CAAQ,GAC7BC,IAAI,KAAK,IAAIC,GAAQC,CAAQ,GAC7BC,IAAQ,KAAK,IAAIJ,IAAWD,CAAM,GAClCM,IAAS,KAAK,IAAIF,IAAWD,CAAM;KAGzC,IAAIE,MAAU,KAAKC,MAAW,GAAG;MAC/B,AAAKC,KAAWT,EAAE,aAAa,CAAC,CAAC;MACjC;KACF;KAEA,IAAMU,IAAOV,EAAE,YAAY;MAAE;MAAG;MAAG;MAAO;KAAO,GAAGW,CAAI;KAExD,IAAIF,GAAW;MAGb,IAAMG,IAAS,CAAC,GAFAZ,EAAE,aAEC,CAAO;MAC1B,KAAK,IAAMa,KAAMH,GACf,AAAKE,EAAO,SAASC,CAAE,KAAGD,EAAO,KAAKC,CAAE;MAE1C,EAAE,aAAaD,CAAM;KACvB,OACE,EAAE,aAAaF,CAAI;IAEvB;GACF;EACF;CACF;CAOA,eAAe;AACjB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"booleans.js","names":["ID_FOR","LABEL_FOR","ICON_FOR","UnionIcon","IntersectIcon","SubtractIcon","ExcludeIcon","DivideIcon","CropIcon","makePathfinderAction","op","adapter","deps","result","applyBooleanOp","ActionDisabledReason","pathfinderUnionAction","pathfinderSubtractAction","pathfinderIntersectAction","pathfinderExcludeAction","pathfinderDivideAction","pathfinderCropAction"],"sources":["../../../../src/interactions/actions/defaults/booleans.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\nimport { applyBooleanOp, type BooleanOp
|
|
1
|
+
{"version":3,"file":"booleans.js","names":["ID_FOR","LABEL_FOR","ICON_FOR","UnionIcon","IntersectIcon","SubtractIcon","ExcludeIcon","DivideIcon","CropIcon","makePathfinderAction","op","adapter","deps","result","applyBooleanOp","ActionDisabledReason","pathfinderUnionAction","pathfinderSubtractAction","pathfinderIntersectAction","pathfinderExcludeAction","pathfinderDivideAction","pathfinderCropAction"],"sources":["../../../../src/interactions/actions/defaults/booleans.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\nimport { applyBooleanOp, type BooleanOp } from '../booleans/booleans';\nimport type { Action } from '@weasel-js/routing';\nimport { ActionDisabledReason } from '@weasel-js/routing';\nimport type { ImmediateInvoker } from '@weasel-js/routing';\nimport {\n UnionIcon,\n IntersectIcon,\n SubtractIcon,\n ExcludeIcon,\n DivideIcon,\n CropIcon,\n} from './icons/booleanIcons';\n\nconst ID_FOR: Record<BooleanOp, string> = {\n union: 'pathfinder.union',\n intersect: 'pathfinder.intersect',\n subtract: 'pathfinder.subtract',\n exclude: 'pathfinder.exclude',\n divide: 'pathfinder.divide',\n crop: 'pathfinder.crop',\n};\n\nconst LABEL_FOR: Record<BooleanOp, string> = {\n union: 'Unite',\n intersect: 'Intersect',\n subtract: 'Minus Front',\n exclude: 'Exclude',\n divide: 'Divide',\n crop: 'Crop',\n};\n\nconst ICON_FOR: Record<BooleanOp, ReactNode> = {\n union: <UnionIcon />,\n intersect: <IntersectIcon />,\n subtract: <SubtractIcon />,\n exclude: <ExcludeIcon />,\n divide: <DivideIcon />,\n crop: <CropIcon />,\n};\n\n// ---------------------------------------------------------------------------\n// Static descriptors\n// ---------------------------------------------------------------------------\n\nfunction makePathfinderAction(op: BooleanOp): Action {\n return {\n id: ID_FOR[op],\n label: LABEL_FOR[op],\n icon: ICON_FOR[op],\n group: 'pathfinder',\n eligible: { capability: 'creates-shapes' },\n requires: ['selection', 'booleansAdapter'],\n // No default keybindings — there's no industry-standard chord set for\n // boolean ops. Wire bindings explicitly via the actions registry override map.\n invoker: {\n timing: 'immediate',\n run: (deps) => {\n const adapter = deps.booleansAdapter;\n if (!adapter) return;\n const result = applyBooleanOp(adapter, op);\n if (result.kind === 'failed') console.warn(`[pathfinder] ${result.error.message}`);\n },\n } satisfies ImmediateInvoker,\n enabled: (deps) => {\n const selection = deps?.selection;\n const count = selection?.get().length ?? 0;\n return count >= 2 ? true : ActionDisabledReason.SelectionRequired;\n },\n };\n}\n\n/** @experimental Static descriptor for pathfinder-union. */\nexport const pathfinderUnionAction = makePathfinderAction('union');\n/** @experimental Static descriptor for pathfinder-subtract. */\nexport const pathfinderSubtractAction = makePathfinderAction('subtract');\n/** @experimental Static descriptor for pathfinder-intersect. */\nexport const pathfinderIntersectAction = makePathfinderAction('intersect');\n/** @experimental Static descriptor for pathfinder-exclude. */\nexport const pathfinderExcludeAction = makePathfinderAction('exclude');\n/** @experimental Static descriptor for pathfinder-divide. */\nexport const pathfinderDivideAction = makePathfinderAction('divide');\n/** @experimental Static descriptor for pathfinder-crop. */\nexport const pathfinderCropAction = makePathfinderAction('crop');\n\n"],"mappings":";;;;;AAcA,IAAMA,IAAoC;CACxC,OAAO;CACP,WAAW;CACX,UAAU;CACV,SAAS;CACT,QAAQ;CACR,MAAM;AACR,GAEMC,IAAuC;CAC3C,OAAO;CACP,WAAW;CACX,UAAU;CACV,SAAS;CACT,QAAQ;CACR,MAAM;AACR,GAEMC,IAAyC;CAC7C,OAAO,kBAACC,GAAD,CAAY,CAAA;CACnB,WAAW,kBAACC,GAAD,CAAgB,CAAA;CAC3B,UAAU,kBAACC,GAAD,CAAe,CAAA;CACzB,SAAS,kBAACC,GAAD,CAAc,CAAA;CACvB,QAAQ,kBAACC,GAAD,CAAa,CAAA;CACrB,MAAM,kBAACC,GAAD,CAAW,CAAA;AACnB;AAMA,SAASC,EAAqB,GAAuB;CACnD,OAAO;EACL,IAAIT,EAAOU;EACX,OAAOT,EAAUS;EACjB,MAAMR,EAASQ;EACf,OAAO;EACP,UAAU,EAAE,YAAY,iBAAiB;EACzC,UAAU,CAAC,aAAa,iBAAiB;EAGzC,SAAS;GACP,QAAQ;GACR,MAAM,MAAS;IACb,IAAMC,IAAUC,EAAK;IACrB,IAAI,CAACD,GAAS;IACd,IAAME,IAASC,EAAeH,GAASD,CAAE;IACzC,AAAIG,EAAO,SAAS,YAAU,QAAQ,KAAK,gBAAgBA,EAAO,MAAM,SAAS;GACnF;EACF;EACA,UAAU,QACUD,GAAM,UAAA,EACC,IAAI,CAAC,CAAC,UAAU,MACzB,KAAWG,EAAqB;CAEpD;AACF;AAGA,IAAaC,IAA4BP,EAAqB,OAAO,GAExDQ,IAA4BR,EAAqB,UAAU,GAE3DS,IAA4BT,EAAqB,WAAW,GAE5DU,IAA4BV,EAAqB,SAAS,GAE1DW,IAA4BX,EAAqB,QAAQ,GAEzDY,IAA4BZ,EAAqB,MAAM"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cancelGesture.js","names":["cancelGestureAction"],"sources":["../../../../src/interactions/actions/defaults/cancelGesture.ts"],"sourcesContent":["import type { Action } from '@weasel-js/routing';\n\n/**\n * @experimental\n * Static descriptor for the `cancelGesture` Action — Escape mid-drag\n * tells the dispatcher to abort every in-flight handle (`onEnd('cancel')`\n * on each, scratch discarded, no scene mutation).\n *\n * Phase-gated to `[*:engaged]` so it fires only when at least one tool\n * has a handle in flight; the unmodified `escape` action retains its\n * idle-phase binding (clears selection) without conflict.\n */\n// No `eligible` field → always eligible. Cancelling an in-flight gesture\n// must work regardless of mode.\nexport const cancelGestureAction: Action & { requires: string[] } = {\n id: 'cancelGesture',\n label: 'Cancel gesture',\n defaultBinding: {\n kind: 'key',\n key: 'Escape',\n phase: [{ channel: '*', phase: 'engaged' }],\n },\n requires: ['dispatcher'],\n invoker: {\n timing: 'immediate',\n run: (deps) => {\n const d = deps.dispatcher
|
|
1
|
+
{"version":3,"file":"cancelGesture.js","names":["cancelGestureAction"],"sources":["../../../../src/interactions/actions/defaults/cancelGesture.ts"],"sourcesContent":["import type { Action } from '@weasel-js/routing';\n\n/**\n * @experimental\n * Static descriptor for the `cancelGesture` Action — Escape mid-drag\n * tells the dispatcher to abort every in-flight handle (`onEnd('cancel')`\n * on each, scratch discarded, no scene mutation).\n *\n * Phase-gated to `[*:engaged]` so it fires only when at least one tool\n * has a handle in flight; the unmodified `escape` action retains its\n * idle-phase binding (clears selection) without conflict.\n */\n// No `eligible` field → always eligible. Cancelling an in-flight gesture\n// must work regardless of mode.\nexport const cancelGestureAction: Action & { requires: string[] } = {\n id: 'cancelGesture',\n label: 'Cancel gesture',\n defaultBinding: {\n kind: 'key',\n key: 'Escape',\n phase: [{ channel: '*', phase: 'engaged' }],\n },\n requires: ['dispatcher'],\n invoker: {\n timing: 'immediate',\n run: (deps) => {\n const d = deps.dispatcher;\n d?.cancelAll('cancel');\n },\n },\n};\n"],"mappings":";AAcA,IAAaA,IAAuD;CAClE,IAAI;CACJ,OAAO;CACP,gBAAgB;EACd,MAAM;EACN,KAAK;EACL,OAAO,CAAC;GAAE,SAAS;GAAK,OAAO;EAAU,CAAC;CAC5C;CACA,UAAU,CAAC,YAAY;CACvB,SAAS;EACP,QAAQ;EACR,MAAM,MAAS;GAEb,EADe,YACZ,UAAU,QAAQ;EACvB;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clearSelection.js","names":["clearSelectionAction","deps","ActionDisabledReason"],"sources":["../../../../src/interactions/actions/defaults/clearSelection.ts"],"sourcesContent":["/**\n * `clearSelectionAction` — immediate Action descriptor for click-on-empty\n * selection clearing.\n *\n * ## Status: REAL\n *\n * Fires via `useSelectTool.bindings` when the user clicks on empty canvas\n * with no modifier held. Clears the selection by calling `deps.selection.set([])`.\n *\n * ## No defaultBinding\n *\n * This action has no ambient `defaultBinding` / `defaultBinding` — it fires\n * ONLY via `useSelectTool`'s `Tool.bindings` entry:\n * `{ spec: { kind: 'click', target: 'empty', mods: {} }, actionId: 'clearSelection' }`\n *\n * This avoids ambient double-fire and keeps the action scoped to select-tool\n * context where `classifyTarget` is wired.\n *\n * ## enabled — the anchor-editing fall-through\n *\n * There is no \"is anything selected?\" guard: clearing an already-empty\n * selection is a safe no-op, and the binding spec is the real gate for\n * where the click landed.\n *\n * What `enabled` *does* do is decline while a path is in anchor-edit mode,\n * so the dispatcher falls through to `selectAnchorAction`. This is the\n * click twin of the opt-out `areaSelectAction.start` already performs for\n * the drag gesture, and it exists for the same reason: `useSelectTool`\n * binds this action at **active** scope while `selectAnchor` is **ambient**,\n * so without the gate an anchor that happens to sit over empty canvas\n * clears the node selection instead of selecting the anchor.\n *\n * Capability eligibility (`creates-selection`, which `path-edit` does not\n * allow) already covers consumers that wired a mode registry. Consumers\n * without one get no eligibility filtering at all, so this gate is the only\n * thing separating the two. Both mechanisms are needed — see the header of\n * `anchorEditing.ts`.\n */\n\nimport type { Action } from '@weasel-js/routing';\nimport { ActionDisabledReason } from '@weasel-js/routing';\nimport type { ActionDeps } from '@weasel-js/routing';\
|
|
1
|
+
{"version":3,"file":"clearSelection.js","names":["clearSelectionAction","deps","ActionDisabledReason"],"sources":["../../../../src/interactions/actions/defaults/clearSelection.ts"],"sourcesContent":["/**\n * `clearSelectionAction` — immediate Action descriptor for click-on-empty\n * selection clearing.\n *\n * ## Status: REAL\n *\n * Fires via `useSelectTool.bindings` when the user clicks on empty canvas\n * with no modifier held. Clears the selection by calling `deps.selection.set([])`.\n *\n * ## No defaultBinding\n *\n * This action has no ambient `defaultBinding` / `defaultBinding` — it fires\n * ONLY via `useSelectTool`'s `Tool.bindings` entry:\n * `{ spec: { kind: 'click', target: 'empty', mods: {} }, actionId: 'clearSelection' }`\n *\n * This avoids ambient double-fire and keeps the action scoped to select-tool\n * context where `classifyTarget` is wired.\n *\n * ## enabled — the anchor-editing fall-through\n *\n * There is no \"is anything selected?\" guard: clearing an already-empty\n * selection is a safe no-op, and the binding spec is the real gate for\n * where the click landed.\n *\n * What `enabled` *does* do is decline while a path is in anchor-edit mode,\n * so the dispatcher falls through to `selectAnchorAction`. This is the\n * click twin of the opt-out `areaSelectAction.start` already performs for\n * the drag gesture, and it exists for the same reason: `useSelectTool`\n * binds this action at **active** scope while `selectAnchor` is **ambient**,\n * so without the gate an anchor that happens to sit over empty canvas\n * clears the node selection instead of selecting the anchor.\n *\n * Capability eligibility (`creates-selection`, which `path-edit` does not\n * allow) already covers consumers that wired a mode registry. Consumers\n * without one get no eligibility filtering at all, so this gate is the only\n * thing separating the two. Both mechanisms are needed — see the header of\n * `anchorEditing.ts`.\n */\n\nimport type { Action } from '@weasel-js/routing';\nimport { ActionDisabledReason } from '@weasel-js/routing';\nimport type { ActionDeps } from '@weasel-js/routing';\n\n/**\n * @experimental\n * Static descriptor for the `clearSelection` Action.\n *\n * Requires dep-schema entries: `selection`, `editAnchors`.\n *\n * Registered via `useStandardActions`; bound via `useSelectTool.bindings`.\n */\nexport const clearSelectionAction: Action & { requires: string[] } = {\n id: 'clearSelection',\n label: 'Clear selection',\n // No defaultBinding / defaultBinding — fires only via Tool.bindings.\n eligible: { capability: 'creates-selection' },\n // `editAnchors` is required for the `enabled` gate below, not for the run.\n requires: ['selection', 'editAnchors'],\n invoker: {\n timing: 'immediate',\n run: (deps) => {\n deps.selection?.set([]);\n },\n },\n enabled: (deps?: ActionDeps) => {\n const editAnchors = deps?.editAnchors;\n // Absent dep means the consumer never wired anchor editing — nothing to\n // defer to, so the click is ours.\n if (editAnchors?.editingId) return ActionDisabledReason.NotApplicable;\n return true;\n },\n};\n"],"mappings":";;AAmDA,IAAaA,IAAwD;CACnE,IAAI;CACJ,OAAO;CAEP,UAAU,EAAE,YAAY,oBAAoB;CAE5C,UAAU,CAAC,aAAa,aAAa;CACrC,SAAS;EACP,QAAQ;EACR,MAAM,MAAS;GACb,EAAK,WAAW,IAAI,CAAC,CAAC;EACxB;CACF;CACA,UAAU,MAIR,CAHoBC,GAAM,aAGT,aAAkBC,EAAqB;AAG5D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clipboard.js","names":["clipboardCopyAction","createElement","CopyIcon","requiresSelection","clipboardCutAction","CutIcon","clipboard","deps","selection","scene","applyOps","ids","ops","buildDeleteOps","defaultCommitAdapter","clipboardPasteAction","PasteIcon","ActionDisabledReason"],"sources":["../../../../src/interactions/actions/defaults/clipboard.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"clipboard.js","names":["clipboardCopyAction","createElement","CopyIcon","requiresSelection","clipboardCutAction","CutIcon","clipboard","deps","selection","scene","applyOps","ids","ops","buildDeleteOps","defaultCommitAdapter","clipboardPasteAction","PasteIcon","ActionDisabledReason"],"sources":["../../../../src/interactions/actions/defaults/clipboard.ts"],"sourcesContent":["import { createElement } from 'react';\nimport { CopyIcon, CutIcon, PasteIcon } from './icons/editIcons';\nimport { defaultCommitAdapter } from '../defaultCommitAdapter';\nimport { ActionDisabledReason, type Action } from '@weasel-js/routing';\nimport { buildDeleteOps } from './delete';\nimport { requiresSelection } from './requiresSelection';\n\n/**\n * @experimental\n * Static descriptor for the `clipboard.copy` Action (Cmd/Ctrl+C).\n */\nexport const clipboardCopyAction: Action & { requires: string[] } = {\n id: 'clipboard.copy',\n label: 'Copy',\n icon: createElement(CopyIcon),\n group: 'clipboard',\n defaultBinding: { kind: 'key', key: 'c', mods: { mod: true } },\n // Same gate as `duplicate`: a mode that can neither edit the page nor own a\n // selection has nothing to copy. Notably excludes `text-edit`, where Cmd+C\n // must stay the browser's own copy of the caret range.\n eligible: { capability: ['edits-page', 'creates-selection'] },\n // `selection` is read by the `enabled` gate, not the invoker — the\n // dispatcher builds deps for both, and an undeclared read is undefined.\n requires: ['clipboard', 'selection'],\n invoker: {\n timing: 'immediate',\n run: (deps) => {\n deps.clipboard?.copy();\n },\n },\n enabled: requiresSelection,\n};\n\n/**\n * @experimental\n * Static descriptor for the `clipboard.cut` Action (Cmd/Ctrl+X) — copy, then\n * the same batched delete `deleteAction` performs, as one undo entry.\n */\nexport const clipboardCutAction: Action & { requires: string[] } = {\n id: 'clipboard.cut',\n label: 'Cut',\n icon: createElement(CutIcon),\n group: 'clipboard',\n defaultBinding: { kind: 'key', key: 'x', mods: { mod: true } },\n eligible: { capability: 'edits-page' },\n requires: ['clipboard', 'scene', 'selection', 'applyOps'],\n invoker: {\n timing: 'immediate',\n run: (deps) => {\n const clipboard = deps.clipboard;\n const selection = deps.selection;\n const scene = deps.scene;\n const applyOps = deps.applyOps;\n if (!clipboard || !selection || !scene) return;\n const ids = selection.get();\n if (ids.length === 0) return;\n\n // Snapshot before removal — `snapshotSelection` reads live nodes.\n clipboard.copy();\n\n const ops = buildDeleteOps(scene, ids, 'Cut');\n if (ops.length > 0) {\n if (applyOps) applyOps(ops, 'Cut');\n else scene.applyBatch(ops, 'Cut', defaultCommitAdapter(scene, selection.adapterMethods));\n }\n selection.set([]);\n },\n },\n enabled: requiresSelection,\n};\n\n/**\n * @experimental\n * Static descriptor for the `clipboard.paste` Action — what a Paste button or\n * menu item triggers. It has no key binding: Cmd/Ctrl+V already arrives as a\n * DOM `paste` event, which the dispatcher routes to `ingest`, and a binding\n * here would fire alongside it and paste twice.\n */\nexport const clipboardPasteAction: Action & { requires: string[] } = {\n id: 'clipboard.paste',\n label: 'Paste',\n icon: createElement(PasteIcon),\n group: 'clipboard',\n eligible: { capability: 'edits-page' },\n requires: ['clipboard'],\n invoker: {\n timing: 'immediate',\n run: (deps) => {\n deps.clipboard?.paste();\n },\n },\n enabled: (deps) => {\n const clipboard = deps?.clipboard;\n return clipboard && !clipboard.isEmpty() ? true : ActionDisabledReason.NotApplicable;\n },\n};\n"],"mappings":";;;;;;;AAWA,IAAaA,IAAuD;CAClE,IAAI;CACJ,OAAO;CACP,MAAMC,EAAcC,CAAQ;CAC5B,OAAO;CACP,gBAAgB;EAAE,MAAM;EAAO,KAAK;EAAK,MAAM,EAAE,KAAK,GAAK;CAAE;CAI7D,UAAU,EAAE,YAAY,CAAC,cAAc,mBAAmB,EAAE;CAG5D,UAAU,CAAC,aAAa,WAAW;CACnC,SAAS;EACP,QAAQ;EACR,MAAM,MAAS;GACb,EAAK,WAAW,KAAK;EACvB;CACF;CACA,SAASC;AACX,GAOaC,IAAsD;CACjE,IAAI;CACJ,OAAO;CACP,MAAMH,EAAcI,CAAO;CAC3B,OAAO;CACP,gBAAgB;EAAE,MAAM;EAAO,KAAK;EAAK,MAAM,EAAE,KAAK,GAAK;CAAE;CAC7D,UAAU,EAAE,YAAY,aAAa;CACrC,UAAU;EAAC;EAAa;EAAS;EAAa;CAAU;CACxD,SAAS;EACP,QAAQ;EACR,MAAM,MAAS;GACb,IAAMC,IAAYC,EAAK,WACjBC,IAAYD,EAAK,WACjBE,IAAQF,EAAK,OACbG,IAAWH,EAAK;GACtB,IAAI,CAACD,KAAa,CAACE,KAAa,CAACC,GAAO;GACxC,IAAME,IAAMH,EAAU,IAAI;GAC1B,IAAIG,EAAI,WAAW,GAAG;GAGtB,EAAU,KAAK;GAEf,IAAMC,IAAMC,EAAeJ,GAAOE,GAAK,KAAK;GAK5C,AAJIC,EAAI,SAAS,MACXF,IAAUA,EAASE,GAAK,KAAK,IAC5BH,EAAM,WAAWG,GAAK,OAAOE,EAAqBL,GAAOD,EAAU,cAAc,CAAC,IAEzFA,EAAU,IAAI,CAAC,CAAC;EAClB;CACF;CACA,SAASL;AACX,GASaY,IAAwD;CACnE,IAAI;CACJ,OAAO;CACP,MAAMd,EAAce,CAAS;CAC7B,OAAO;CACP,UAAU,EAAE,YAAY,aAAa;CACrC,UAAU,CAAC,WAAW;CACtB,SAAS;EACP,QAAQ;EACR,MAAM,MAAS;GACb,EAAK,WAAW,MAAM;EACxB;CACF;CACA,UAAU,MAAS;EACjB,IAAMV,IAAYC,GAAM;EACxB,OAAOD,KAAa,CAACA,EAAU,QAAQ,IAAI,KAAOW,EAAqB;CACzE;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clone.js","names":["cloneAction","inPlane","selection","ctx","scene","applyOps","ids","frame","scenePoseFrame","originPoses","descriptor","poseDescriptorOf","id","node","toEdited","invertPlane","planeOf","carryPose","scratch","landed","origin","moved","translatePoseViaDescriptor","dx","dy","moveCtx","reason","ops","originNode","newPose","freshNodeId","createInsertOp","defaultCommitAdapter","selectionLayer"],"sources":["../../../../src/interactions/actions/defaults/clone.ts"],"sourcesContent":["/**\n * `cloneAction` — ongoing Action descriptor for alt-drag clone.\n *\n * ## Status: REAL (scene-direct, no overlay)\n *\n * Implements the core clone-by-drag logic via insert ops committed through\n * `scene.applyBatch`:\n * - `start`: validates selection + scene; captures origin poses for all\n * selected nodes. The alt-modifier check that activates cloning in\n * `useClone` (via `CloneBehavior.activates`) is intentionally NOT applied\n * here — the descriptor fires when the dispatcher routes to it; modifier\n * discrimination is a dispatcher concern (Phase 12 TODO for alt-gating).\n * - `onMove`: tracks current drag delta in scratch (no scene writes).\n * - `onEnd('commit')`: emits one insert op per selected node (translated\n * pose) and commits them as a single batch — via the consumer `applyOps`\n * hook when present, else `scene.applyBatch(ops, 'Clone', ...)`. One\n * undo entry for the whole batch.\n * - `onEnd('cancel')`: no-op (scene never mutated during drag).\n *\n * ## What this does NOT wire (vs `useClone`)\n *\n * - Modifier gate: `useClone` only activates when `CloneBehavior.activates(mods)`\n * returns true (typically alt-held). The descriptor lacks that gate — it runs\n * whenever the dispatcher routes `clone`. Proper alt-gating requires a modifier-\n * discriminant in the dispatcher (Phase 12 TODO).\n * - Overlay: `useClone` renders a ghost via `setOverlay / clearOverlay`. The\n * descriptor has no overlay surface (deferred to Phase 7 overlay system).\n * - `expandIds`: group expansion is omitted; only leaf poses are cloned.\n * - Custom `CloneBehavior.onEnd` ops (e.g. `cloneByAltDrag`): the descriptor\n * uses a simpler `scene.add` path that does not delegate to behavior `onEnd`.\n * Behavior-pipeline cloning waits for a later phase.\n *\n * ## Pose generics\n *\n * Poses are translated through the `poseDescriptor` dep, as `moveAction` does.\n */\n\nimport type { Action } from '@weasel-js/routing';\nimport type { InvocationCtx, OngoingHandle } from '@weasel-js/routing';\nimport type { Node, Scene, NodeId } from 'core/scene/types';\nimport type { SelectionApi } from 'core/selection/useSelection';\nimport type { Op } from 'core/ops/types';\nimport { createInsertOp } from 'core/ops/create';\nimport { defaultCommitAdapter } from '../defaultCommitAdapter';\nimport { freshNodeId } from './freshNodeId';\nimport { poseDescriptorOf } from '../poseDescriptorDep';\nimport { translatePoseViaDescriptor, type PoseDescriptor } from '../resize/geometry';\nimport { scenePoseFrame, type PoseFrame } from '../poseFrame';\nimport { carryPose, invertPlane, inPlane, planeOf, selectionLayer } from '../planeInput';\n\n// ---------------------------------------------------------------------------\n// Internal scratch\n// ---------------------------------------------------------------------------\n\ninterface CloneScratch {\n ids: NodeId[];\n scene: Scene<unknown, string, unknown>;\n descriptor: PoseDescriptor<unknown>;\n /** World reads and local writes over the scene's composition strategy. */\n frame: PoseFrame<unknown>;\n /** Origin poses captured at drag start, in world — the frame the drag\n * delta is expressed in, and the plane the edit is measured in. The copy\n * keeps its source's parent and layer, so each translated result is\n * carried back to that layer's plane and stored in that same frame. */\n originPoses: Map<NodeId, unknown>;\n /** The view the invocation started with, read for `planeOf`. */\n view: unknown;\n /** Running drag delta — updated each onMove, applied once at commit. */\n currentDelta: { dx: number; dy: number };\n /** Preview poses keyed by ORIGINAL node id (the clone targets don't have\n * scene ids yet; the preview-ghost layer paints the originals' silhouette\n * at the translated pose — original stays visible at its committed home,\n * ghost appears at the drag target). */\n previews: Map<NodeId, unknown>;\n /** Optional consumer commit hook captured at gesture start. When present,\n * the insert ops route through it (consumer history) instead of\n * `scene.applyBatch`. Undefined → fall back to `scene.applyBatch`. */\n applyOps?: (ops: Op[], label: string) => void;\n}\n\n// ---------------------------------------------------------------------------\n// Descriptor\n// ---------------------------------------------------------------------------\n\n/**\n * @experimental\n * Static descriptor for the `clone` Action.\n *\n * Requires dep-schema entries: `selection`, `scene`.\n *\n * Clones selected nodes into new scene nodes translated by the drag delta.\n * Commits insert ops via `scene.applyBatch(ops, 'Clone', ...)` (or the\n * consumer `applyOps` hook) for a single undo entry.\n *\n * @see useClone — the React hook this descriptor partially mirrors.\n */\nexport const cloneAction: Action & { requires: string[] } = inPlane({\n id: 'clone',\n label: 'Clone',\n // No default binding: a bare `{ kind: 'drag' }` would clone a non-empty\n // selection on any drag no tool claimed. Alt-drag on a body binds it\n // (`selectionMoveBindings`, the `move` preset).\n // The platform's duplicate cursor, and the whole reason this field is\n // modifier-aware: the select tool binds clone behind `mods: { alt: true }`,\n // so the pump predicts it — and shows this — only while Alt is down.\n cursor: 'copy',\n activeCursor: 'copy',\n eligible: { capability: ['edits-page', 'creates-selection'] },\n requires: ['selection', 'scene', 'applyOps', 'poseDescriptor', 'poseComposition'],\n invoker: {\n timing: 'ongoing',\n start(ctx: InvocationCtx, _opts): OngoingHandle {\n const selection = ctx.deps.selection as SelectionApi | undefined;\n const scene = ctx.deps.scene as Scene<unknown, string, unknown> | undefined;\n const applyOps = ctx.deps.applyOps as ((ops: Op[], label: string) => void) | undefined;\n\n if (!selection || !scene) return {};\n\n const ids = selection.get() as NodeId[];\n if (ids.length === 0) return {};\n\n // Capture origin poses once at drag start.\n const frame = scenePoseFrame(scene, ctx.deps.poseComposition);\n const originPoses = new Map<NodeId, unknown>();\n const descriptor = poseDescriptorOf(ctx.deps.poseDescriptor);\n for (const id of ids) {\n const node = scene.get(id);\n if (node === undefined) continue;\n const toEdited = invertPlane(planeOf(ctx.deps.view, node.layer));\n originPoses.set(id, carryPose(descriptor, frame.world(id), toEdited));\n }\n\n if (originPoses.size === 0) return {};\n\n const scratch: CloneScratch = {\n ids,\n scene,\n descriptor,\n frame,\n originPoses,\n view: ctx.deps.view,\n currentDelta: { dx: 0, dy: 0 },\n previews: new Map<NodeId, unknown>(),\n applyOps,\n };\n\n /** Where the copy of `id` lands for a drag of `(dx, dy)`, as stored. */\n const landed = (id: NodeId, dx: number, dy: number): unknown => {\n const origin = scratch.originPoses.get(id);\n const node = scratch.scene.get(id);\n if (origin === undefined || !node) return undefined;\n const moved = translatePoseViaDescriptor(origin, dx, dy, scratch.descriptor);\n return scratch.frame.local(id, carryPose(scratch.descriptor, moved, planeOf(scratch.view, node.layer)));\n };\n\n return {\n kind: 'clone',\n // Clone: source stays visible at its committed pose; the ghost\n // (rendered via previewIds/previewPose below) appears at the\n // drag target. Opt out of the default \"hide source\" behavior\n // move/resize/rotate use.\n previewHidesSource: false,\n onMove(moveCtx: InvocationCtx): void {\n if (!moveCtx.drag) return;\n scratch.currentDelta = {\n dx: moveCtx.drag.delta.x,\n dy: moveCtx.drag.delta.y,\n };\n // Preview: paint each original's silhouette at the translated pose.\n // The original stays at its committed location (we don't hide it);\n // the ghost overlay shows where the new copy will land on commit.\n scratch.previews.clear();\n const { dx, dy } = scratch.currentDelta;\n if (dx === 0 && dy === 0) return;\n for (const id of scratch.originPoses.keys()) scratch.previews.set(id, landed(id, dx, dy)!);\n },\n onEnd(_endCtx: InvocationCtx, reason: 'commit' | 'cancel'): void {\n if (reason === 'cancel') {\n scratch.previews.clear();\n return;\n }\n const { dx, dy } = scratch.currentDelta;\n // Zero-delta drag — no clone.\n if (dx === 0 && dy === 0) {\n scratch.previews.clear();\n return;\n }\n\n // Build one insert op per clone target — same nodes/values the old\n // direct `scene.add` loop produced (kind/layer/data/parent preserved,\n // pose translated by the drag delta), then route the batch through the\n // consumer `applyOps` hook when present (so an app with its own history\n // captures the clone as a single undo entry); otherwise commit straight\n // to the scene's own history. One applyOps / applyBatch call =\n // one undo entry, matching the prior single `scene.batch('Clone', …)`.\n const ops: Op[] = [];\n for (const id of scratch.ids) {\n const originNode = scratch.scene.get(id);\n const newPose = landed(id, dx, dy);\n if (newPose === undefined || !originNode) continue;\n // The old `scene.add` (no explicit id) minted a random id; we\n // pre-generate one so the insert op carries a full node. Id value\n // was never observable, so behavior is preserved.\n const node = {\n id: freshNodeId(),\n kind: originNode.kind,\n layer: originNode.layer,\n pose: newPose,\n data: originNode.data,\n parent: originNode.parent ?? null,\n } as Node<unknown, string, unknown>;\n ops.push(createInsertOp<Node<unknown, string, unknown>>({ node, label: 'Clone' }));\n }\n if (ops.length > 0) {\n if (scratch.applyOps) scratch.applyOps(ops, 'Clone');\n else scratch.scene.applyBatch(ops, 'Clone', defaultCommitAdapter(scratch.scene, selection.adapterMethods));\n }\n scratch.previews.clear();\n },\n previewIds: () => scratch.previews.keys(),\n previewPose: (id: string) => scratch.previews.get(id as NodeId) ?? null,\n };\n },\n },\n enabled: () => true,\n}, selectionLayer);\n"],"mappings":";;;;;;;;AAgGA,IAAaA,IAA+CC,EAAQ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,GAAK,SAASK,EAAqBd,EAAQ,OAAOhB,EAAU,cAAc,CAAC,IAE3GgB,EAAQ,SAAS,MAAM;IACzB;IACA,kBAAkBA,EAAQ,SAAS,KAAK;IACxC,cAAc,MAAeA,EAAQ,SAAS,IAAIN,CAAY,KAAK;GACrE;EACF;CACF;CACA,eAAe;AACjB,GAAGqB,CAAc"}
|
|
1
|
+
{"version":3,"file":"clone.js","names":["cloneAction","inPlane","selection","ctx","scene","applyOps","ids","frame","scenePoseFrame","originPoses","descriptor","poseDescriptorOf","id","node","toEdited","invertPlane","planeOf","carryPose","scratch","landed","origin","moved","translatePoseViaDescriptor","dx","dy","moveCtx","reason","ops","originNode","newPose","freshNodeId","createInsertOp","defaultCommitAdapter","selectionLayer"],"sources":["../../../../src/interactions/actions/defaults/clone.ts"],"sourcesContent":["/**\n * `cloneAction` — ongoing Action descriptor for alt-drag clone.\n *\n * ## Status: REAL (scene-direct, no overlay)\n *\n * Implements the core clone-by-drag logic via insert ops committed through\n * `scene.applyBatch`:\n * - `start`: validates selection + scene; captures origin poses for all\n * selected nodes. The alt-modifier check that activates cloning in\n * `useClone` (via `CloneBehavior.activates`) is intentionally NOT applied\n * here — the descriptor fires when the dispatcher routes to it; modifier\n * discrimination is a dispatcher concern (Phase 12 TODO for alt-gating).\n * - `onMove`: tracks current drag delta in scratch (no scene writes).\n * - `onEnd('commit')`: emits one insert op per selected node (translated\n * pose) and commits them as a single batch — via the consumer `applyOps`\n * hook when present, else `scene.applyBatch(ops, 'Clone', ...)`. One\n * undo entry for the whole batch.\n * - `onEnd('cancel')`: no-op (scene never mutated during drag).\n *\n * ## What this does NOT wire (vs `useClone`)\n *\n * - Modifier gate: `useClone` only activates when `CloneBehavior.activates(mods)`\n * returns true (typically alt-held). The descriptor lacks that gate — it runs\n * whenever the dispatcher routes `clone`. Proper alt-gating requires a modifier-\n * discriminant in the dispatcher (Phase 12 TODO).\n * - Overlay: `useClone` renders a ghost via `setOverlay / clearOverlay`. The\n * descriptor has no overlay surface (deferred to Phase 7 overlay system).\n * - `expandIds`: group expansion is omitted; only leaf poses are cloned.\n * - Custom `CloneBehavior.onEnd` ops (e.g. `cloneByAltDrag`): the descriptor\n * uses a simpler `scene.add` path that does not delegate to behavior `onEnd`.\n * Behavior-pipeline cloning waits for a later phase.\n *\n * ## Pose generics\n *\n * Poses are translated through the `poseDescriptor` dep, as `moveAction` does.\n */\n\nimport type { Action } from '@weasel-js/routing';\nimport type { InvocationCtx, OngoingHandle } from '@weasel-js/routing';\nimport type { Node, Scene, NodeId } from 'core/scene/types';\nimport type { Op } from 'core/ops/types';\nimport { createInsertOp } from 'core/ops/create';\nimport { defaultCommitAdapter } from '../defaultCommitAdapter';\nimport { freshNodeId } from './freshNodeId';\nimport { poseDescriptorOf } from '../poseDescriptorDep';\nimport { translatePoseViaDescriptor, type PoseDescriptor } from '../resize/geometry';\nimport { scenePoseFrame, type PoseFrame } from '../poseFrame';\nimport { carryPose, invertPlane, inPlane, planeOf, selectionLayer } from '../planeInput';\n\n// ---------------------------------------------------------------------------\n// Internal scratch\n// ---------------------------------------------------------------------------\n\ninterface CloneScratch {\n ids: NodeId[];\n scene: Scene<unknown, string, unknown>;\n descriptor: PoseDescriptor<unknown>;\n /** World reads and local writes over the scene's composition strategy. */\n frame: PoseFrame<unknown>;\n /** Origin poses captured at drag start, in world — the frame the drag\n * delta is expressed in, and the plane the edit is measured in. The copy\n * keeps its source's parent and layer, so each translated result is\n * carried back to that layer's plane and stored in that same frame. */\n originPoses: Map<NodeId, unknown>;\n /** The view the invocation started with, read for `planeOf`. */\n view: unknown;\n /** Running drag delta — updated each onMove, applied once at commit. */\n currentDelta: { dx: number; dy: number };\n /** Preview poses keyed by ORIGINAL node id (the clone targets don't have\n * scene ids yet; the preview-ghost layer paints the originals' silhouette\n * at the translated pose — original stays visible at its committed home,\n * ghost appears at the drag target). */\n previews: Map<NodeId, unknown>;\n /** Optional consumer commit hook captured at gesture start. When present,\n * the insert ops route through it (consumer history) instead of\n * `scene.applyBatch`. Undefined → fall back to `scene.applyBatch`. */\n applyOps?: (ops: Op[], label: string) => void;\n}\n\n// ---------------------------------------------------------------------------\n// Descriptor\n// ---------------------------------------------------------------------------\n\n/**\n * @experimental\n * Static descriptor for the `clone` Action.\n *\n * Requires dep-schema entries: `selection`, `scene`.\n *\n * Clones selected nodes into new scene nodes translated by the drag delta.\n * Commits insert ops via `scene.applyBatch(ops, 'Clone', ...)` (or the\n * consumer `applyOps` hook) for a single undo entry.\n *\n * @see useClone — the React hook this descriptor partially mirrors.\n */\nexport const cloneAction: Action & { requires: string[] } = inPlane({\n id: 'clone',\n label: 'Clone',\n // No default binding: a bare `{ kind: 'drag' }` would clone a non-empty\n // selection on any drag no tool claimed. Alt-drag on a body binds it\n // (`selectionMoveBindings`, the `move` preset).\n // The platform's duplicate cursor, and the whole reason this field is\n // modifier-aware: the select tool binds clone behind `mods: { alt: true }`,\n // so the pump predicts it — and shows this — only while Alt is down.\n cursor: 'copy',\n activeCursor: 'copy',\n eligible: { capability: ['edits-page', 'creates-selection'] },\n requires: ['selection', 'scene', 'applyOps', 'poseDescriptor', 'poseComposition'],\n invoker: {\n timing: 'ongoing',\n start(ctx: InvocationCtx, _opts): OngoingHandle {\n const selection = ctx.deps.selection;\n const scene = ctx.deps.scene;\n const applyOps = ctx.deps.applyOps;\n\n if (!selection || !scene) return {};\n\n const ids = selection.get() as NodeId[];\n if (ids.length === 0) return {};\n\n // Capture origin poses once at drag start.\n const frame = scenePoseFrame(scene, ctx.deps.poseComposition);\n const originPoses = new Map<NodeId, unknown>();\n const descriptor = poseDescriptorOf(ctx.deps.poseDescriptor);\n for (const id of ids) {\n const node = scene.get(id);\n if (node === undefined) continue;\n const toEdited = invertPlane(planeOf(ctx.deps.view, node.layer));\n originPoses.set(id, carryPose(descriptor, frame.world(id), toEdited));\n }\n\n if (originPoses.size === 0) return {};\n\n const scratch: CloneScratch = {\n ids,\n scene,\n descriptor,\n frame,\n originPoses,\n view: ctx.deps.view,\n currentDelta: { dx: 0, dy: 0 },\n previews: new Map<NodeId, unknown>(),\n applyOps,\n };\n\n /** Where the copy of `id` lands for a drag of `(dx, dy)`, as stored. */\n const landed = (id: NodeId, dx: number, dy: number): unknown => {\n const origin = scratch.originPoses.get(id);\n const node = scratch.scene.get(id);\n if (origin === undefined || !node) return undefined;\n const moved = translatePoseViaDescriptor(origin, dx, dy, scratch.descriptor);\n return scratch.frame.local(id, carryPose(scratch.descriptor, moved, planeOf(scratch.view, node.layer)));\n };\n\n return {\n kind: 'clone',\n // Clone: source stays visible at its committed pose; the ghost\n // (rendered via previewIds/previewPose below) appears at the\n // drag target. Opt out of the default \"hide source\" behavior\n // move/resize/rotate use.\n previewHidesSource: false,\n onMove(moveCtx: InvocationCtx): void {\n if (!moveCtx.drag) return;\n scratch.currentDelta = {\n dx: moveCtx.drag.delta.x,\n dy: moveCtx.drag.delta.y,\n };\n // Preview: paint each original's silhouette at the translated pose.\n // The original stays at its committed location (we don't hide it);\n // the ghost overlay shows where the new copy will land on commit.\n scratch.previews.clear();\n const { dx, dy } = scratch.currentDelta;\n if (dx === 0 && dy === 0) return;\n for (const id of scratch.originPoses.keys()) scratch.previews.set(id, landed(id, dx, dy)!);\n },\n onEnd(_endCtx: InvocationCtx, reason: 'commit' | 'cancel'): void {\n if (reason === 'cancel') {\n scratch.previews.clear();\n return;\n }\n const { dx, dy } = scratch.currentDelta;\n // Zero-delta drag — no clone.\n if (dx === 0 && dy === 0) {\n scratch.previews.clear();\n return;\n }\n\n // Build one insert op per clone target — same nodes/values the old\n // direct `scene.add` loop produced (kind/layer/data/parent preserved,\n // pose translated by the drag delta), then route the batch through the\n // consumer `applyOps` hook when present (so an app with its own history\n // captures the clone as a single undo entry); otherwise commit straight\n // to the scene's own history. One applyOps / applyBatch call =\n // one undo entry, matching the prior single `scene.batch('Clone', …)`.\n const ops: Op[] = [];\n for (const id of scratch.ids) {\n const originNode = scratch.scene.get(id);\n const newPose = landed(id, dx, dy);\n if (newPose === undefined || !originNode) continue;\n // The old `scene.add` (no explicit id) minted a random id; we\n // pre-generate one so the insert op carries a full node. Id value\n // was never observable, so behavior is preserved.\n const node = {\n id: freshNodeId(),\n kind: originNode.kind,\n layer: originNode.layer,\n pose: newPose,\n data: originNode.data,\n parent: originNode.parent ?? null,\n } as Node<unknown, string, unknown>;\n ops.push(createInsertOp<Node<unknown, string, unknown>>({ node, label: 'Clone' }));\n }\n if (ops.length > 0) {\n if (scratch.applyOps) scratch.applyOps(ops, 'Clone');\n else scratch.scene.applyBatch(ops, 'Clone', defaultCommitAdapter(scratch.scene, selection.adapterMethods));\n }\n scratch.previews.clear();\n },\n previewIds: () => scratch.previews.keys(),\n previewPose: (id: string) => scratch.previews.get(id as NodeId) ?? null,\n };\n },\n },\n enabled: () => true,\n}, selectionLayer);\n"],"mappings":";;;;;;;;AA+FA,IAAaA,IAA+CC,EAAQ;CAClE,IAAI;CACJ,OAAO;CAOP,QAAQ;CACR,cAAc;CACd,UAAU,EAAE,YAAY,CAAC,cAAc,mBAAmB,EAAE;CAC5D,UAAU;EAAC;EAAa;EAAS;EAAY;EAAkB;CAAiB;CAChF,SAAS;EACP,QAAQ;EACR,MAAM,GAAoB,GAAsB;GAC9C,IAAMC,IAAYC,EAAI,KAAK,WACrBC,IAAQD,EAAI,KAAK,OACjBE,IAAWF,EAAI,KAAK;GAE1B,IAAI,CAACD,KAAa,CAACE,GAAO,OAAO,CAAC;GAElC,IAAME,IAAMJ,EAAU,IAAI;GAC1B,IAAII,EAAI,WAAW,GAAG,OAAO,CAAC;GAG9B,IAAMC,IAAQC,EAAeJ,GAAOD,EAAI,KAAK,eAAe,GACtDM,oBAAc,IAAI,IAAqB,GACvCC,IAAaC,EAAiBR,EAAI,KAAK,cAAc;GAC3D,KAAK,IAAMS,KAAMN,GAAK;IACpB,IAAMO,IAAOT,EAAM,IAAIQ,CAAE;IACzB,IAAIC,MAAS,KAAA,GAAW;IACxB,IAAMC,IAAWC,EAAYC,EAAQb,EAAI,KAA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MACxB,EAAQ,SAAS,MAAM;MACvB;KACF;KASA,IAAMG,IAAY,CAAC;KACnB,KAAK,IAAMf,KAAMM,EAAQ,KAAK;MAC5B,IAAMU,IAAaV,EAAQ,MAAM,IAAIN,CAAE,GACjCiB,IAAUV,EAAOP,GAAIW,GAAIC,CAAE;MACjC,IAAIK,MAAY,KAAA,KAAa,CAACD,GAAY;MAI1C,IAAMf,IAAO;OACX,IAAIiB,EAAY;OAChB,MAAMF,EAAW;OACjB,OAAOA,EAAW;OAClB,MAAMC;OACN,MAAMD,EAAW;OACjB,QAAQA,EAAW,UAAU;MAC/B;MACA,EAAI,KAAKG,EAA+C;OAAE;OAAM,OAAO;MAAQ,CAAC,CAAC;KACnF;KAKA,AAJIJ,EAAI,SAAS,MACXT,EAAQ,WAAUA,EAAQ,SAASS,GAAK,OAAO,IAC9CT,EAAQ,MAAM,WAAWS,GAAK,SAASK,EAAqBd,EAAQ,OAAOhB,EAAU,cAAc,CAAC,IAE3GgB,EAAQ,SAAS,MAAM;IACzB;IACA,kBAAkBA,EAAQ,SAAS,KAAK;IACxC,cAAc,MAAeA,EAAQ,SAAS,IAAIN,CAAY,KAAK;GACrE;EACF;CACF;CACA,eAAe;AACjB,GAAGqB,CAAc"}
|
|
@@ -35,7 +35,7 @@ var o = {
|
|
|
35
35
|
}
|
|
36
36
|
},
|
|
37
37
|
enabled: (e) => {
|
|
38
|
-
let t =
|
|
38
|
+
let t = e?.selection?.get() ?? [];
|
|
39
39
|
if (t.length === 0) return r.SelectionRequired;
|
|
40
40
|
let n = e?.createOutlinesAdapter;
|
|
41
41
|
return n && t.some((e) => n.getTextSource(e) !== void 0) ? !0 : r.NotApplicable;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createOutlines.js","names":["runCreateOutlines","result","applyCreateOutlines","adapter","texts","id","t","loadTextOutlines","createOutlinesAction","CreateOutlinesIcon","deps","ids","ActionDisabledReason"],"sources":["../../../../src/interactions/actions/defaults/createOutlines.tsx"],"sourcesContent":["import type { Action, ImmediateInvoker } from '@weasel-js/routing';\nimport { ActionDisabledReason } from '@weasel-js/routing';\nimport type {
|
|
1
|
+
{"version":3,"file":"createOutlines.js","names":["runCreateOutlines","result","applyCreateOutlines","adapter","texts","id","t","loadTextOutlines","createOutlinesAction","CreateOutlinesIcon","deps","ids","ActionDisabledReason"],"sources":["../../../../src/interactions/actions/defaults/createOutlines.tsx"],"sourcesContent":["import type { Action, ImmediateInvoker } from '@weasel-js/routing';\nimport { ActionDisabledReason } from '@weasel-js/routing';\nimport type { NodeId } from 'core/scene/types';\nimport { loadTextOutlines, type TextNodeSource } from 'features/text/textToPath';\nimport {\n applyCreateOutlines, type CreateOutlinesAdapter, type CreateOutlinesResult,\n} from '../outlines/createOutlines';\nimport { CreateOutlinesIcon } from './icons/outlineIcons';\n\n/**\n * {@link applyCreateOutlines}, waiting first for any face whose outlines are\n * registered but not yet loaded — a face is parsed on first use, so the first\n * conversion in a session would otherwise fail. Warns with the reason when\n * the selection still cannot be converted.\n */\nexport async function runCreateOutlines(adapter: CreateOutlinesAdapter): Promise<CreateOutlinesResult> {\n let result = applyCreateOutlines(adapter);\n if (result.kind === 'failed' && result.error.reason === 'outlines-loading') {\n const texts = [...adapter.getSelection()]\n .map((id) => adapter.getTextSource(id as NodeId))\n .filter((t): t is TextNodeSource => t !== undefined);\n await Promise.all(texts.map((t) => loadTextOutlines(t.data)));\n result = applyCreateOutlines(adapter);\n }\n if (result.kind === 'failed') console.warn(`[createOutlines] ${result.error.message}`);\n return result;\n}\n\n/**\n * @experimental Static descriptor for Create Outlines: replace the selected\n * text nodes with path nodes carrying their glyph outlines. Reads the\n * `createOutlinesAdapter` dep, published with `useCreateOutlinesAdapter`.\n */\nexport const createOutlinesAction: Action = {\n id: 'createOutlines',\n label: 'Create Outlines',\n icon: <CreateOutlinesIcon />,\n group: 'text',\n defaultBinding: { kind: 'key', key: 'o', mods: { mod: true, shift: true } },\n eligible: { capability: 'creates-shapes' },\n requires: ['selection', 'createOutlinesAdapter'],\n invoker: {\n timing: 'immediate',\n run: (deps) => {\n const adapter = deps.createOutlinesAdapter;\n if (adapter) void runCreateOutlines(adapter);\n },\n } satisfies ImmediateInvoker,\n enabled: (deps) => {\n const ids = deps?.selection?.get() ?? [];\n if (ids.length === 0) return ActionDisabledReason.SelectionRequired;\n const adapter = deps?.createOutlinesAdapter;\n return adapter && ids.some((id) => adapter.getTextSource(id) !== undefined)\n ? true\n : ActionDisabledReason.NotApplicable;\n },\n};\n"],"mappings":";;;;;;AAeA,eAAsBA,EAAkB,GAA+D;CACrG,IAAIC,IAASC,EAAoBC,CAAO;CACxC,IAAIF,EAAO,SAAS,YAAYA,EAAO,MAAM,WAAW,oBAAoB;EAC1E,IAAMG,IAAQ,CAAC,GAAGD,EAAQ,aAAa,CAAC,CAAC,CACtC,KAAK,MAAOA,EAAQ,cAAcE,CAAY,CAAC,CAAC,CAChD,QAAQ,MAA2BC,MAAM,KAAA,CAAS;EAErD,AADA,MAAM,QAAQ,IAAIF,EAAM,KAAK,MAAMG,EAAiB,EAAE,IAAI,CAAC,CAAC,GAC5D,IAASL,EAAoBC,CAAO;CACtC;CAEA,OADIF,EAAO,SAAS,YAAU,QAAQ,KAAK,oBAAoBA,EAAO,MAAM,SAAS,GAC9EA;AACT;AAOA,IAAaO,IAA+B;CAC1C,IAAI;CACJ,OAAO;CACP,MAAM,kBAACC,GAAD,CAAqB,CAAA;CAC3B,OAAO;CACP,gBAAgB;EAAE,MAAM;EAAO,KAAK;EAAK,MAAM;GAAE,KAAK;GAAM,OAAO;EAAK;CAAE;CAC1E,UAAU,EAAE,YAAY,iBAAiB;CACzC,UAAU,CAAC,aAAa,uBAAuB;CAC/C,SAAS;EACP,QAAQ;EACR,MAAM,MAAS;GACb,IAAMN,IAAUO,EAAK;GACrB,AAAIP,KAASH,EAAuBG,CAAO;EAC7C;CACF;CACA,UAAU,MAAS;EACjB,IAAMQ,IAAMD,GAAM,WAAW,IAAI,KAAK,CAAC;EACvC,IAAIC,EAAI,WAAW,GAAG,OAAOC,EAAqB;EAClD,IAAMT,IAAUO,GAAM;EACtB,OAAOP,KAAWQ,EAAI,MAAM,MAAOR,EAAQ,cAAcE,CAAE,MAAM,KAAA,CAAS,IACtE,KACAO,EAAqB;CAC3B;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createPaintAction.js","names":["createPaintAction","refreshPreviews","id","scratch","prev","next","spec","selection","ctx","scene","applyOps","ids","fallback","opts","pick","key","startData","node","moveCtx","reason","ops","merged","nodeNow","from","to","createSetDataOp","defaultCommitAdapter","sel","deps","ActionDisabledReason"],"sources":["../../../../src/interactions/actions/defaults/createPaintAction.ts"],"sourcesContent":["import type { Action } from '@weasel-js/routing';\nimport type { InvocationCtx, OngoingHandle, BindingOpts } from '@weasel-js/routing';\nimport { ActionDisabledReason } from '@weasel-js/routing';\nimport type { Scene, NodeId } from 'core/scene/types';\nimport type {
|
|
1
|
+
{"version":3,"file":"createPaintAction.js","names":["createPaintAction","refreshPreviews","id","scratch","prev","next","spec","selection","ctx","scene","applyOps","ids","fallback","opts","pick","key","startData","node","moveCtx","reason","ops","merged","nodeNow","from","to","createSetDataOp","defaultCommitAdapter","sel","deps","ActionDisabledReason"],"sources":["../../../../src/interactions/actions/defaults/createPaintAction.ts"],"sourcesContent":["import type { Action } from '@weasel-js/routing';\nimport type { InvocationCtx, OngoingHandle, BindingOpts } from '@weasel-js/routing';\nimport { ActionDisabledReason } from '@weasel-js/routing';\nimport type { Scene, NodeId } from 'core/scene/types';\nimport type { Op } from 'core/ops/types';\nimport { createSetDataOp } from 'core/ops/setData';\nimport { defaultCommitAdapter } from '../defaultCommitAdapter';\n\n/** The node data one paint action reads and writes: its own key, nothing else. */\ntype PaintData<K extends string, TValue> = { [P in K]?: TValue | null };\n\ntype Params = Record<string, unknown> | undefined;\n\n/** Read a param from the invocation, falling back to the binding's. */\nexport type PickParam = <T>(key: string) => T | undefined;\n\n/**\n * What distinguishes one paint action from the other three.\n *\n * `TState` is the action's gesture state — a color plus an optional paint for\n * the two setters, a bare alpha for the two opacity actions. It is a reducer,\n * not a paint: `setFill` and `setStroke` supersede a paint with a later color,\n * which no per-field merge of the params can express.\n */\nexport interface PaintActionSpec<TState, TValue, K extends string> {\n id: string;\n label: string;\n /** The `data` key this action owns. */\n dataKey: K;\n /** Gesture state at start. */\n initialState(pick: PickParam): TState;\n /** The state one onMove tick moves to, or `null` when its params carry\n * nothing this action reads — the preview then stands. */\n readParams(prev: TState, params: Params): TState | null;\n /** The value to write for one node, from that node's value at gesture start.\n * `null` writes the absence of paint, which is a value like any other —\n * a node with `fill: null` paints no fill. */\n merge(prev: TValue | null | undefined, state: TState): TValue | null;\n}\n\ninterface Scratch<TState, TValue, K extends string> {\n ids: NodeId[];\n scene: Scene<PaintData<K, TValue>, string, unknown>;\n /** Data snapshot at gesture start, keyed by node id. */\n startData: Map<NodeId, PaintData<K, TValue>>;\n state: TState;\n /** Preview data entries — the merged value per selected node. Populated on\n * start and refreshed on every onMove. */\n previews: Map<NodeId, PaintData<K, TValue>>;\n /** Optional consumer commit hook captured at gesture start. When present,\n * the ops-based commit routes through it (consumer history) instead of\n * `scene.applyBatch`. Undefined → fall back to `scene.applyBatch`. */\n applyOps?: (ops: Op[], label: string) => void;\n}\n\n/**\n * The one ongoing-action body the four paint actions share.\n *\n * On start it captures each selected node's data; on each onMove it refreshes\n * the preview without touching the scene; on commit it emits one\n * `createSetDataOp` per node (from = pre-commit data, to = the same data with\n * the merged value) and routes the batch through the consumer `applyOps` hook\n * when present (consumer history) else `scene.applyBatch` +\n * `defaultCommitAdapter` (whose `setData` delegates to `scene.update({ data })`).\n * Either path is a single batch → one undo entry.\n *\n * The `from` data is re-read at commit rather than reused from the start\n * snapshot, so a concurrent edit to a field this action does not own is not\n * clobbered.\n */\nexport function createPaintAction<TState, TValue, K extends string>(\n spec: PaintActionSpec<TState, TValue, K>,\n): Action & { requires: string[] } {\n type Data = PaintData<K, TValue>;\n\n const refreshPreviews = (scratch: Scratch<TState, TValue, K>): void => {\n scratch.previews.clear();\n for (const id of scratch.ids) {\n const prev = scratch.startData.get(id);\n const next = spec.merge(prev?.[spec.dataKey], scratch.state);\n scratch.previews.set(id, { ...(prev ?? {}), [spec.dataKey]: next } as Data);\n }\n };\n\n return {\n id: spec.id,\n label: spec.label,\n eligible: { capability: 'applies-fill' },\n requires: ['selection', 'scene', 'applyOps'],\n invoker: {\n timing: 'ongoing',\n start(ctx: InvocationCtx, opts?: BindingOpts): OngoingHandle {\n const selection = ctx.deps.selection;\n const scene = ctx.deps.scene as Scene<Data, string, unknown> | undefined;\n const applyOps = ctx.deps.applyOps;\n\n if (!selection || !scene) return {};\n\n const ids = selection.get() as NodeId[];\n if (ids.length === 0) return {};\n\n const fallback = opts?.params as Params;\n const pick = (<T>(key: string) =>\n (ctx.params?.[key] ?? fallback?.[key]) as T | undefined) as PickParam;\n\n const startData = new Map<NodeId, Data>();\n for (const id of ids) {\n const node = scene.get(id);\n if (node) startData.set(id, { ...(node.data as Data) });\n }\n\n const scratch: Scratch<TState, TValue, K> = {\n ids,\n scene,\n startData,\n state: spec.initialState(pick),\n previews: new Map(),\n applyOps,\n };\n refreshPreviews(scratch);\n\n return {\n onMove(moveCtx: InvocationCtx): void {\n const next = spec.readParams(scratch.state, moveCtx.params);\n if (next === null) return;\n scratch.state = next;\n refreshPreviews(scratch);\n },\n onEnd(_endCtx: InvocationCtx, reason: 'commit' | 'cancel'): void {\n if (reason === 'cancel') {\n scratch.previews.clear();\n return;\n }\n const ops: Op[] = [];\n for (const id of scratch.ids) {\n const merged = spec.merge(\n scratch.startData.get(id)?.[spec.dataKey],\n scratch.state,\n );\n const nodeNow = scratch.scene.get(id);\n if (!nodeNow) continue;\n const from = { ...(nodeNow.data as object) } as Data;\n const to = { ...from, [spec.dataKey]: merged } as Data;\n ops.push(createSetDataOp<Data>({ id: id as string, from, to }));\n }\n if (ops.length > 0) {\n if (scratch.applyOps) scratch.applyOps(ops, spec.label);\n else scratch.scene.applyBatch(ops, spec.label, defaultCommitAdapter(scratch.scene, selection.adapterMethods));\n }\n scratch.previews.clear();\n },\n previewIds: () => scratch.previews.keys(),\n previewData: (id: string) => scratch.previews.get(id as unknown as NodeId) ?? null,\n };\n },\n },\n enabled: (deps) => {\n const sel = deps?.selection;\n if (!sel || (sel.get() as unknown[]).length === 0) {\n return ActionDisabledReason.SelectionRequired;\n }\n return true;\n },\n };\n}\n"],"mappings":";;;;AAsEA,SAAgBA,EACd,GACiC;CAGjC,IAAMC,KAAmB,MAA8C;EACrE,EAAQ,SAAS,MAAM;EACvB,KAAK,IAAMC,KAAMC,EAAQ,KAAK;GAC5B,IAAMC,IAAOD,EAAQ,UAAU,IAAID,CAAE,GAC/BG,IAAOC,EAAK,MAAMF,IAAOE,EAAK,UAAUH,EAAQ,KAAK;GAC3D,EAAQ,SAAS,IAAID,GAAI;IAAE,GAAIE,KAAQ,CAAC;KAAKE,EAAK,UAAUD;GAAK,CAAS;EAC5E;CACF;CAEA,OAAO;EACL,IAAIC,EAAK;EACT,OAAOA,EAAK;EACZ,UAAU,EAAE,YAAY,eAAe;EACvC,UAAU;GAAC;GAAa;GAAS;EAAU;EAC3C,SAAS;GACP,QAAQ;GACR,MAAM,GAAoB,GAAmC;IAC3D,IAAMC,IAAYC,EAAI,KAAK,WACrBC,IAAQD,EAAI,KAAK,OACjBE,IAAWF,EAAI,KAAK;IAE1B,IAAI,CAACD,KAAa,CAACE,GAAO,OAAO,CAAC;IAElC,IAAME,IAAMJ,EAAU,IAAI;IAC1B,IAAII,EAAI,WAAW,GAAG,OAAO,CAAC;IAE9B,IAAMC,IAAWC,GAAM,QACjBC,MAAY,MACfN,EAAI,SAASO,MAAQH,IAAWG,KAE7BC,oBAAY,IAAI,IAAkB;IACxC,KAAK,IAAMd,KAAMS,GAAK;KACpB,IAAMM,IAAOR,EAAM,IAAIP,CAAE;KACzB,AAAIe,KAAMD,EAAU,IAAId,GAAI,EAAE,GAAIe,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;EACT;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"delete.js","names":["hostIndex","node","scene","id","buildDeleteOps","covered","ops","ids","taken","createDeleteOp","deleteAction","createElement","DeleteIcon","selection","deps","applyOps","defaultCommitAdapter","requiresSelection"],"sources":["../../../../src/interactions/actions/defaults/delete.ts"],"sourcesContent":["import { createElement } from 'react';\nimport { DeleteIcon } from './icons/actionGlyphIcons';\nimport type { Node, NodeId, Scene } from 'core/scene/types';\nimport type {
|
|
1
|
+
{"version":3,"file":"delete.js","names":["hostIndex","node","scene","id","buildDeleteOps","covered","ops","ids","taken","createDeleteOp","deleteAction","createElement","DeleteIcon","selection","deps","applyOps","defaultCommitAdapter","requiresSelection"],"sources":["../../../../src/interactions/actions/defaults/delete.ts"],"sourcesContent":["import { createElement } from 'react';\nimport { DeleteIcon } from './icons/actionGlyphIcons';\nimport type { Node, NodeId, Scene } from 'core/scene/types';\nimport type { Op } from 'core/ops/types';\nimport { createDeleteOp } from 'core/ops/delete';\nimport { defaultCommitAdapter } from '../defaultCommitAdapter';\nimport type { Action } from '@weasel-js/routing';\nimport { requiresSelection } from './requiresSelection';\n\n/** Host-array index of `id`: its slot among the scene roots (parent `null`)\n * or among its parent's children. `-1` when not found. Forwarded to\n * `createDeleteOp` so the inverse re-insert restores paint order on undo. */\nfunction hostIndex(scene: Scene<unknown, string, unknown>, id: NodeId): number {\n const node = scene.get(id);\n const siblings = node?.parent == null ? scene.roots : scene.childrenOf(node.parent);\n return siblings.indexOf(id);\n}\n\n/**\n * Delete ops for `ids`, in the order given. Each op captures the node and its\n * host-array index BEFORE any removal, so `invert()` re-inserts at the right\n * slot and undo restores paint order. Ids with no live node are skipped.\n *\n * Ids an already-emitted op will take are skipped: `removeNode` cascades both\n * the subtree and the dependents, so a second op for a node the first has taken\n * would throw `unknown node id` mid-batch — escaping the batch with the scene\n * already mutated. Selecting a container and its members, or a node and an edge\n * drawn from it, is the ordinary way to hit this; Cmd+A does both.\n *\n * `scene.removalClosure` is what decides that, rather than a walk back up from\n * each candidate: the scene owns the cascade relations, so a third one added\n * there is honored here for free. Asking about the ops already emitted, rather\n * than about the whole selection, is what settles a cycle — two ids that reach\n * each other each cover the other, and filtering both deletes nothing, while\n * growing the covered set in input order keeps the first and drops the rest.\n *\n * Which ids survive the filter depends on their order, so the ops are a cover\n * of the selection rather than its minimal set of roots.\n *\n * Shared with `clipboardCutAction` — cut is copy plus exactly this.\n */\nexport function buildDeleteOps(\n scene: Scene<unknown, string, unknown>,\n ids: readonly string[],\n label: string,\n): Op[] {\n const covered = new Set<string>();\n const ops: Op[] = [];\n for (const id of ids) {\n const node = scene.get(id as NodeId);\n if (!node) continue;\n if (covered.has(id)) continue;\n for (const taken of scene.removalClosure([id as NodeId])) covered.add(taken);\n ops.push(createDeleteOp<Node<unknown, string, unknown>>({\n node,\n index: hostIndex(scene, id as NodeId),\n label,\n }));\n }\n return ops;\n}\n\n/**\n * @experimental\n * Static descriptor for the `delete` Action. Removes every selected\n * node from the scene as a single batched op (one undo entry).\n *\n * Undo restores everything the removal cascaded — a container's children and\n * a deleted node's dependents come back with it, at their own slots. Each op\n * snapshots that set through the adapter's `getRemovalClosure` before removing.\n */\nexport const deleteAction: Action & { requires: string[] } = {\n id: 'delete',\n label: 'Delete',\n icon: createElement(DeleteIcon),\n group: 'edit',\n // Suppressed while any tool is mid-gesture — accidentally hitting\n // Delete during a drag shouldn't wipe the selection out from under\n // the in-flight handle.\n defaultBinding: {\n kind: 'key',\n key: ['Delete', 'Backspace'],\n phase: [{ channel: '*', phase: 'initial' }],\n },\n eligible: { capability: 'edits-page' },\n requires: ['scene', 'selection', 'applyOps'],\n invoker: {\n timing: 'immediate',\n run: (deps) => {\n const selection = deps.selection;\n const scene = deps.scene;\n // Optional consumer commit hook. When present, ops route through it\n // (consumer history) as one undo entry; otherwise they fall back to the\n // scene's own history via `scene.applyBatch`.\n const applyOps = deps.applyOps;\n if (!selection || !scene) return;\n const ids = selection.get();\n if (ids.length === 0) return;\n\n const ops = buildDeleteOps(scene, ids, 'Delete');\n\n if (ops.length > 0) {\n if (applyOps) applyOps(ops, 'Delete');\n else scene.applyBatch(ops, 'Delete', defaultCommitAdapter(scene, selection.adapterMethods));\n }\n selection.set([]);\n },\n },\n enabled: requiresSelection,\n};\n"],"mappings":";;;;;;AAYA,SAASA,EAAU,GAAwC,GAAoB;CAC7E,IAAMC,IAAOC,EAAM,IAAIC,CAAE;CAEzB,QADiBF,GAAM,UAAU,OAAOC,EAAM,QAAQA,EAAM,WAAWD,EAAK,MAAM,EAAA,CAClE,QAAQE,CAAE;AAC5B;AAyBA,SAAgBC,EACd,GACA,GACA,GACM;CACN,IAAMC,oBAAU,IAAI,IAAY,GAC1BC,IAAY,CAAC;CACnB,KAAK,IAAMH,KAAMI,GAAK;EACpB,IAAMN,IAAOC,EAAM,IAAIC,CAAY;EACnC,IAAKF,KACD,GAAQ,IAAIE,CAAE,GAClB;QAAK,IAAMK,KAASN,EAAM,eAAe,CAACC,CAAY,CAAC,GAAG,EAAQ,IAAIK,CAAK;GAC3E,EAAI,KAAKC,EAA+C;IACtD;IACA,OAAOT,EAAUE,GAAOC,CAAY;IACpC;GACF,CAAC,CAAC;EALyE;CAM7E;CACA,OAAOG;AACT;AAWA,IAAaI,IAAgD;CAC3D,IAAI;CACJ,OAAO;CACP,MAAMC,EAAcC,CAAU;CAC9B,OAAO;CAIP,gBAAgB;EACd,MAAM;EACN,KAAK,CAAC,UAAU,WAAW;EAC3B,OAAO,CAAC;GAAE,SAAS;GAAK,OAAO;EAAU,CAAC;CAC5C;CACA,UAAU,EAAE,YAAY,aAAa;CACrC,UAAU;EAAC;EAAS;EAAa;CAAU;CAC3C,SAAS;EACP,QAAQ;EACR,MAAM,MAAS;GACb,IAAMC,IAAYC,EAAK,WACjBZ,IAAQY,EAAK,OAIbC,IAAWD,EAAK;GACtB,IAAI,CAACD,KAAa,CAACX,GAAO;GAC1B,IAAMK,IAAMM,EAAU,IAAI;GAC1B,IAAIN,EAAI,WAAW,GAAG;GAEtB,IAAMD,IAAMF,EAAeF,GAAOK,GAAK,QAAQ;GAM/C,AAJID,EAAI,SAAS,MACXS,IAAUA,EAAST,GAAK,QAAQ,IAC/BJ,EAAM,WAAWI,GAAK,UAAUU,EAAqBd,GAAOW,EAAU,cAAc,CAAC,IAE5FA,EAAU,IAAI,CAAC,CAAC;EAClB;CACF;CACA,SAASI;AACX"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"distribute.js","names":["ID_FOR","LABEL_FOR","ICON_FOR","DistributeHorizontalIcon","DistributeVerticalIcon","distributeSelection","ids","selection","frame","scenePoseFrame","scene","poseComposition","items","pose","id","visualBoundsViaDescriptor","geom","targets","planDistribute","it","axis","mode","i","delta","dx","dy","to","translatePoseViaDescriptor","makeDistributeAction","deps","params","poseDescriptorOf","ActionDisabledReason","distributeHorizontalAction","distributeVerticalAction"],"sources":["../../../../src/interactions/actions/defaults/distribute.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\nimport type { Scene } from 'core/scene/types';\nimport type { PoseDescriptor } from '../resize/geometry';\nimport { poseDescriptorOf } from '../poseDescriptorDep';\nimport { translatePoseViaDescriptor, visualBoundsViaDescriptor } from '../align/align';\nimport type { DistributeAxis, DistributeMode } from '../distribute/distribute';\nimport { planDistribute } from '../distribute/plan';\nimport { scenePoseFrame } from '../poseFrame';\nimport type { Action } from '@weasel-js/routing';\nimport { ActionDisabledReason } from '@weasel-js/routing';\nimport type { SelectionApi } from 'core/selection/useSelection';\nimport type { ImmediateInvoker } from '@weasel-js/routing';\nimport { DistributeHorizontalIcon, DistributeVerticalIcon } from './icons/distributeIcons';\n\nconst ID_FOR: Record<DistributeAxis, string> = { x: 'distribute.horizontal', y: 'distribute.vertical' };\nconst LABEL_FOR: Record<DistributeAxis, string> = { x: 'Distribute Horizontally', y: 'Distribute Vertically' };\nconst ICON_FOR: Record<DistributeAxis, ReactNode> = {\n x: <DistributeHorizontalIcon />,\n y: <DistributeVerticalIcon />,\n};\n\n// ---------------------------------------------------------------------------\n// Shared helper for descriptor invokers\n// ---------------------------------------------------------------------------\n\n/**\n * Apply a distribute operation to the current selection via the Scene API.\n * Reads poses through the `poseDescriptor` dep; `mode` comes from the\n * binding's `params.mode`.\n *\n * The span being divided is a world span, so the bounds are read and\n * translated in world and each result is stored back in its own parent's\n * frame.\n */\nfunction distributeSelection(\n selection: SelectionApi,\n scene: Scene<unknown, string, unknown>,\n axis: DistributeAxis,\n mode: DistributeMode,\n geom: PoseDescriptor<unknown>,\n poseComposition: unknown,\n): void {\n const ids = selection.get();\n if (ids.length < 3) return;\n const frame = scenePoseFrame(scene, poseComposition);\n\n const items = ids.map((id) => {\n const pose = frame.world(id);\n return { id, pose, b: visualBoundsViaDescriptor(pose, geom) };\n });\n const targets = planDistribute(items.map((it) => it.b), axis, mode);\n\n scene.batch('Distribute', () => {\n for (let i = 0; i < items.length; i++) {\n const it = items[i];\n const delta = targets[i] - (axis === 'x' ? it.b.x : it.b.y);\n if (delta === 0) continue;\n const dx = axis === 'x' ? delta : 0;\n const dy = axis === 'y' ? delta : 0;\n const to = translatePoseViaDescriptor(it.pose, dx, dy, geom);\n scene.setPose(it.id, frame.local(it.id, to));\n }\n });\n}\n\n// ---------------------------------------------------------------------------\n// Static descriptors\n// ---------------------------------------------------------------------------\n\nfunction makeDistributeAction(axis: DistributeAxis): Action {\n return {\n id: ID_FOR[axis],\n label: LABEL_FOR[axis],\n icon: ICON_FOR[axis],\n group: 'distribute',\n eligible: { capability: 'transforms-selection' },\n requires: ['selection', 'scene', 'poseDescriptor', 'poseComposition'],\n // No default keybindings. Wire bindings explicitly via the actions registry.\n invoker: {\n timing: 'immediate',\n run: (deps, params) => {\n const selection = deps.selection
|
|
1
|
+
{"version":3,"file":"distribute.js","names":["ID_FOR","LABEL_FOR","ICON_FOR","DistributeHorizontalIcon","DistributeVerticalIcon","distributeSelection","ids","selection","frame","scenePoseFrame","scene","poseComposition","items","pose","id","visualBoundsViaDescriptor","geom","targets","planDistribute","it","axis","mode","i","delta","dx","dy","to","translatePoseViaDescriptor","makeDistributeAction","deps","params","poseDescriptorOf","ActionDisabledReason","distributeHorizontalAction","distributeVerticalAction"],"sources":["../../../../src/interactions/actions/defaults/distribute.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\nimport type { Scene } from 'core/scene/types';\nimport type { PoseDescriptor } from '../resize/geometry';\nimport { poseDescriptorOf } from '../poseDescriptorDep';\nimport { translatePoseViaDescriptor, visualBoundsViaDescriptor } from '../align/align';\nimport type { DistributeAxis, DistributeMode } from '../distribute/distribute';\nimport { planDistribute } from '../distribute/plan';\nimport { scenePoseFrame } from '../poseFrame';\nimport type { Action } from '@weasel-js/routing';\nimport { ActionDisabledReason } from '@weasel-js/routing';\nimport type { SelectionApi } from 'core/selection/useSelection';\nimport type { ImmediateInvoker } from '@weasel-js/routing';\nimport { DistributeHorizontalIcon, DistributeVerticalIcon } from './icons/distributeIcons';\n\nconst ID_FOR: Record<DistributeAxis, string> = { x: 'distribute.horizontal', y: 'distribute.vertical' };\nconst LABEL_FOR: Record<DistributeAxis, string> = { x: 'Distribute Horizontally', y: 'Distribute Vertically' };\nconst ICON_FOR: Record<DistributeAxis, ReactNode> = {\n x: <DistributeHorizontalIcon />,\n y: <DistributeVerticalIcon />,\n};\n\n// ---------------------------------------------------------------------------\n// Shared helper for descriptor invokers\n// ---------------------------------------------------------------------------\n\n/**\n * Apply a distribute operation to the current selection via the Scene API.\n * Reads poses through the `poseDescriptor` dep; `mode` comes from the\n * binding's `params.mode`.\n *\n * The span being divided is a world span, so the bounds are read and\n * translated in world and each result is stored back in its own parent's\n * frame.\n */\nfunction distributeSelection(\n selection: SelectionApi,\n scene: Scene<unknown, string, unknown>,\n axis: DistributeAxis,\n mode: DistributeMode,\n geom: PoseDescriptor<unknown>,\n poseComposition: unknown,\n): void {\n const ids = selection.get();\n if (ids.length < 3) return;\n const frame = scenePoseFrame(scene, poseComposition);\n\n const items = ids.map((id) => {\n const pose = frame.world(id);\n return { id, pose, b: visualBoundsViaDescriptor(pose, geom) };\n });\n const targets = planDistribute(items.map((it) => it.b), axis, mode);\n\n scene.batch('Distribute', () => {\n for (let i = 0; i < items.length; i++) {\n const it = items[i];\n const delta = targets[i] - (axis === 'x' ? it.b.x : it.b.y);\n if (delta === 0) continue;\n const dx = axis === 'x' ? delta : 0;\n const dy = axis === 'y' ? delta : 0;\n const to = translatePoseViaDescriptor(it.pose, dx, dy, geom);\n scene.setPose(it.id, frame.local(it.id, to));\n }\n });\n}\n\n// ---------------------------------------------------------------------------\n// Static descriptors\n// ---------------------------------------------------------------------------\n\nfunction makeDistributeAction(axis: DistributeAxis): Action {\n return {\n id: ID_FOR[axis],\n label: LABEL_FOR[axis],\n icon: ICON_FOR[axis],\n group: 'distribute',\n eligible: { capability: 'transforms-selection' },\n requires: ['selection', 'scene', 'poseDescriptor', 'poseComposition'],\n // No default keybindings. Wire bindings explicitly via the actions registry.\n invoker: {\n timing: 'immediate',\n run: (deps, params) => {\n const selection = deps.selection;\n const scene = deps.scene;\n if (!selection || !scene) return;\n const mode = (params?.mode as DistributeMode | undefined) ?? 'centers';\n distributeSelection(selection, scene, axis, mode, poseDescriptorOf(deps.poseDescriptor), deps.poseComposition);\n },\n } satisfies ImmediateInvoker,\n // Deps-aware, matching `distributeSelection`'s own `ids.length < 3` guard:\n // a constant disabled reason greys the entry out forever (see\n // `requiresSelection`).\n enabled: (deps) => {\n const selection = deps?.selection;\n const count = selection?.get().length ?? 0;\n return count >= 3 ? true : ActionDisabledReason.SelectionRequired;\n },\n };\n}\n\n/** @experimental Static descriptor for distribute-horizontal. */\nexport const distributeHorizontalAction = makeDistributeAction('x');\n/** @experimental Static descriptor for distribute-vertical. */\nexport const distributeVerticalAction = makeDistributeAction('y');\n\n"],"mappings":";;;;;;;;AAcA,IAAMA,IAAyC;CAAE,GAAG;CAAyB,GAAG;AAAsB,GAChGC,IAA4C;CAAE,GAAG;CAA2B,GAAG;AA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,KAEnBL,EAAoBE,GAAWG,GAAOU,GADxBU,GAAQ,QAAuC,WACXC,EAAiBF,EAAK,cAAc,GAAGA,EAAK,eAAe;GAC/G;EACF;EAIA,UAAU,QACUA,GAAM,UAAA,EACC,IAAI,CAAC,CAAC,UAAU,MACzB,KAAWG,EAAqB;CAEpD;AACF;AAGA,IAAaC,IAA6BL,EAAqB,GAAG,GAErDM,IAA6BN,EAAqB,GAAG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"duplicate.js","names":["DUPLICATE_OFFSET","hasSelectedAncestor","parent","scene","id","set","copySubtree","node","newId","freshNodeId","copy","translatePoseViaDescriptor","offset","d","createInsertOp","childOffset","offsetDescendants","child","ops","duplicateAction","createElement","DuplicateIcon","selection","deps","applyOps","ids","descriptor","poseDescriptorOf","newIds","nid","asNodeId","defaultCommitAdapter","requiresSelection"],"sources":["../../../../src/interactions/actions/defaults/duplicate.ts"],"sourcesContent":["import type { Action } from '@weasel-js/routing';\nimport { createElement } from 'react';\nimport { DuplicateIcon } from './icons/editIcons';\nimport type { Node, NodeId, Scene } from 'core/scene/types';\nimport { asNodeId } from 'core/scene/types';\nimport type {
|
|
1
|
+
{"version":3,"file":"duplicate.js","names":["DUPLICATE_OFFSET","hasSelectedAncestor","parent","scene","id","set","copySubtree","node","newId","freshNodeId","copy","translatePoseViaDescriptor","offset","d","createInsertOp","childOffset","offsetDescendants","child","ops","duplicateAction","createElement","DuplicateIcon","selection","deps","applyOps","ids","descriptor","poseDescriptorOf","newIds","nid","asNodeId","defaultCommitAdapter","requiresSelection"],"sources":["../../../../src/interactions/actions/defaults/duplicate.ts"],"sourcesContent":["import type { Action } from '@weasel-js/routing';\nimport { createElement } from 'react';\nimport { DuplicateIcon } from './icons/editIcons';\nimport type { Node, NodeId, Scene } from 'core/scene/types';\nimport { asNodeId } from 'core/scene/types';\nimport type { Op } from 'core/ops/types';\nimport { createInsertOp } from 'core/ops/create';\nimport { defaultCommitAdapter } from '../defaultCommitAdapter';\nimport { freshNodeId } from './freshNodeId';\nimport { requiresSelection } from './requiresSelection';\nimport { poseDescriptorOf } from '../poseDescriptorDep';\nimport { translatePoseViaDescriptor, type PoseDescriptor } from '../resize/geometry';\n\n/** Same nudge `sceneToAdapter.getPasteOffset` gives a paste, so duplicate and\n * paste land in the same place rather than disagreeing by a few units. */\nconst DUPLICATE_OFFSET = 12;\n\n/** True when any ancestor of `id` is also in `set` — that ancestor's copy\n * already brings this node along, so duplicating it again would double it. */\nfunction hasSelectedAncestor(\n scene: Scene<unknown, string, unknown>,\n id: NodeId,\n set: ReadonlySet<string>,\n): boolean {\n let parent = scene.get(id)?.parent ?? null;\n while (parent != null) {\n if (set.has(parent)) return true;\n parent = scene.get(parent)?.parent ?? null;\n }\n return false;\n}\n\n/**\n * Copy `id`'s whole subtree, appending one insert op per node in pre-order so\n * a parent always exists before its children are inserted. Returns the new\n * root's id.\n *\n * `offsetDescendants` is false for local-pose consumers (those that registered\n * a `poseComposition`): a child's pose is relative there, so offsetting the\n * root already carries the subtree, and offsetting again would double it. With\n * the default absolute poses every node stores world coords and every one\n * moves.\n */\nfunction copySubtree(\n scene: Scene<unknown, string, unknown>,\n id: NodeId,\n parent: NodeId | null,\n offset: { dx: number; dy: number },\n offsetDescendants: boolean,\n ops: Op[],\n d: PoseDescriptor<unknown>,\n): NodeId | null {\n const node = scene.get(id);\n if (!node) return null;\n const newId = freshNodeId();\n const copy = {\n ...node,\n id: newId,\n pose: translatePoseViaDescriptor(node.pose, offset.dx, offset.dy, d),\n parent,\n } as Node<unknown, string, unknown>;\n ops.push(createInsertOp<Node<unknown, string, unknown>>({ node: copy, label: 'Duplicate' }));\n const childOffset = offsetDescendants ? offset : { dx: 0, dy: 0 };\n for (const child of scene.childrenOf(id)) {\n copySubtree(scene, child, newId, childOffset, offsetDescendants, ops, d);\n }\n return newId;\n}\n\n/**\n * @experimental\n * Static descriptor for the `duplicate` Action. Copies each selected node —\n * with its subtree, so duplicating a group produces a populated group — offset\n * by a small nudge, as one undoable batch, then selects the copies.\n */\nexport const duplicateAction: Action & { requires: string[] } = {\n id: 'duplicate',\n label: 'Duplicate',\n icon: createElement(DuplicateIcon),\n group: 'edit',\n defaultBinding: { kind: 'key', key: 'd', mods: { mod: true } },\n eligible: { capability: ['edits-page', 'creates-selection'] },\n // `selection` is read by the `enabled` gate as well as the invoker. An\n // undeclared read throws inside the dev-build deps Proxy before the gate can\n // answer, which is how this action spent a while doing nothing at all.\n requires: ['scene', 'selection', 'applyOps', 'poseComposition', 'poseDescriptor'],\n invoker: {\n timing: 'immediate',\n run: (deps) => {\n const selection = deps.selection;\n const scene = deps.scene;\n const applyOps = deps.applyOps;\n if (!selection || !scene) return;\n const ids = selection.get();\n if (ids.length === 0) return;\n\n const set = new Set<string>(ids);\n const descriptor = poseDescriptorOf(deps.poseDescriptor);\n const offset = { dx: DUPLICATE_OFFSET, dy: DUPLICATE_OFFSET };\n const ops: Op[] = [];\n const newIds: NodeId[] = [];\n for (const id of ids) {\n const nid = asNodeId(id);\n const node = scene.get(nid);\n if (!node) continue;\n if (hasSelectedAncestor(scene, nid, set)) continue;\n const newId = copySubtree(scene, nid, node.parent ?? null, offset, deps.poseComposition === undefined, ops, descriptor);\n if (newId) newIds.push(newId);\n }\n\n if (ops.length === 0) return;\n if (applyOps) applyOps(ops, 'Duplicate');\n else scene.applyBatch(ops, 'Duplicate', defaultCommitAdapter(scene, selection.adapterMethods));\n selection.set(newIds);\n },\n },\n enabled: requiresSelection,\n};\n"],"mappings":";;;;;;;;;;AAeA,IAAMA,IAAmB;AAIzB,SAASC,EACP,GACA,GACA,GACS;CACT,IAAIC,IAASC,EAAM,IAAIC,CAAE,CAAC,EAAE,UAAU;CACtC,OAAOF,KAAU,OAAM;EACrB,IAAIG,EAAI,IAAIH,CAAM,GAAG,OAAO;EAC5B,IAASC,EAAM,IAAID,CAAM,CAAC,EAAE,UAAU;CACxC;CACA,OAAO;AACT;AAaA,SAASI,EACP,GACA,GACA,GACA,G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