@weasel-js/editing 0.0.0-stage → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +60 -2
- package/dist/actionGroups.js +27 -0
- package/dist/actionGroups.js.map +1 -0
- package/dist/actions/align/action.js +105 -0
- package/dist/actions/align/action.js.map +1 -0
- package/dist/actions/align/align.js +115 -0
- package/dist/actions/align/align.js.map +1 -0
- package/dist/actions/clipboard/action.js +133 -0
- package/dist/actions/clipboard/action.js.map +1 -0
- package/dist/actions/clone/action.js +217 -0
- package/dist/actions/clone/action.js.map +1 -0
- package/dist/actions/clone/behaviors.js +65 -0
- package/dist/actions/clone/behaviors.js.map +1 -0
- package/dist/actions/delete/delete.js +123 -0
- package/dist/actions/delete/delete.js.map +1 -0
- package/dist/actions/derivedBox.js +16 -0
- package/dist/actions/derivedBox.js.map +1 -0
- package/dist/actions/distribute/action.js +96 -0
- package/dist/actions/distribute/action.js.map +1 -0
- package/dist/actions/distribute/distribute.js +61 -0
- package/dist/actions/distribute/distribute.js.map +1 -0
- package/dist/actions/distribute/plan.js +55 -0
- package/dist/actions/distribute/plan.js.map +1 -0
- package/dist/actions/edit/createPaintAction.js +138 -0
- package/dist/actions/edit/createPaintAction.js.map +1 -0
- package/dist/actions/edit/deselect.js +34 -0
- package/dist/actions/edit/deselect.js.map +1 -0
- package/dist/actions/edit/duplicate.js +93 -0
- package/dist/actions/edit/duplicate.js.map +1 -0
- package/dist/actions/edit/group.js +281 -0
- package/dist/actions/edit/group.js.map +1 -0
- package/dist/actions/edit/ingest.js +114 -0
- package/dist/actions/edit/ingest.js.map +1 -0
- package/dist/actions/edit/nudge.js +97 -0
- package/dist/actions/edit/nudge.js.map +1 -0
- package/dist/actions/edit/selectAll.js +48 -0
- package/dist/actions/edit/selectAll.js.map +1 -0
- package/dist/actions/edit/setFill.js +52 -0
- package/dist/actions/edit/setFill.js.map +1 -0
- package/dist/actions/edit/setFillOpacity.js +26 -0
- package/dist/actions/edit/setFillOpacity.js.map +1 -0
- package/dist/actions/edit/setStroke.js +57 -0
- package/dist/actions/edit/setStroke.js.map +1 -0
- package/dist/actions/edit/setStrokeOpacity.js +28 -0
- package/dist/actions/edit/setStrokeOpacity.js.map +1 -0
- package/dist/actions/edit/setStrokeWidth.js +53 -0
- package/dist/actions/edit/setStrokeWidth.js.map +1 -0
- package/dist/actions/edit/setVertexColor.js +45 -0
- package/dist/actions/edit/setVertexColor.js.map +1 -0
- package/dist/actions/flip/action.js +209 -0
- package/dist/actions/flip/action.js.map +1 -0
- package/dist/actions/flip/helpers.js +80 -0
- package/dist/actions/flip/helpers.js.map +1 -0
- package/dist/actions/group/enterGroup.js +81 -0
- package/dist/actions/group/enterGroup.js.map +1 -0
- package/dist/actions/insert/action.js +152 -0
- package/dist/actions/insert/action.js.map +1 -0
- package/dist/actions/insert/commit.js +52 -0
- package/dist/actions/insert/commit.js.map +1 -0
- package/dist/actions/insert/extras.js +88 -0
- package/dist/actions/insert/extras.js.map +1 -0
- package/dist/actions/insert/frame.js +96 -0
- package/dist/actions/insert/frame.js.map +1 -0
- package/dist/actions/insert/geometry.js +35 -0
- package/dist/actions/insert/geometry.js.map +1 -0
- package/dist/actions/insert/lands.js +41 -0
- package/dist/actions/insert/lands.js.map +1 -0
- package/dist/actions/insert/params.js +42 -0
- package/dist/actions/insert/params.js.map +1 -0
- package/dist/actions/insert/placeAction.js +137 -0
- package/dist/actions/insert/placeAction.js.map +1 -0
- package/dist/actions/insert/repositionAction.js +47 -0
- package/dist/actions/insert/repositionAction.js.map +1 -0
- package/dist/actions/insert/rotateAction.js +34 -0
- package/dist/actions/insert/rotateAction.js.map +1 -0
- package/dist/actions/insert/session.js +99 -0
- package/dist/actions/insert/session.js.map +1 -0
- package/dist/actions/insert/shape.js +117 -0
- package/dist/actions/insert/shape.js.map +1 -0
- package/dist/actions/insert/style.js +23 -0
- package/dist/actions/insert/style.js.map +1 -0
- package/dist/actions/lassoSelect/action.js +201 -0
- package/dist/actions/lassoSelect/action.js.map +1 -0
- package/dist/actions/lassoSelect/behaviors/selectFromLasso.js +61 -0
- package/dist/actions/lassoSelect/behaviors/selectFromLasso.js.map +1 -0
- package/dist/actions/lockedWrites.js +20 -0
- package/dist/actions/lockedWrites.js.map +1 -0
- package/dist/actions/move/action.js +138 -0
- package/dist/actions/move/action.js.map +1 -0
- package/dist/actions/move/behaviors/clampMove.js +42 -0
- package/dist/actions/move/behaviors/clampMove.js.map +1 -0
- package/dist/actions/move/behaviors/layoutDrop.js +84 -0
- package/dist/actions/move/behaviors/layoutDrop.js.map +1 -0
- package/dist/actions/move/behaviors/pageDrop.js +30 -0
- package/dist/actions/move/behaviors/pageDrop.js.map +1 -0
- package/dist/actions/move/behaviors/reparentOnDrop.js +44 -0
- package/dist/actions/move/behaviors/reparentOnDrop.js.map +1 -0
- package/dist/actions/move/behaviors/snapBackOrDelete.js +52 -0
- package/dist/actions/move/behaviors/snapBackOrDelete.js.map +1 -0
- package/dist/actions/move/behaviors/snapToContainer.js +214 -0
- package/dist/actions/move/behaviors/snapToContainer.js.map +1 -0
- package/dist/actions/move/behaviors/swapOnDrop.js +180 -0
- package/dist/actions/move/behaviors/swapOnDrop.js.map +1 -0
- package/dist/actions/move/capture.js +116 -0
- package/dist/actions/move/capture.js.map +1 -0
- package/dist/actions/move/commit/index.js +47 -0
- package/dist/actions/move/commit/index.js.map +1 -0
- package/dist/actions/move/commit/layoutDrop.js +68 -0
- package/dist/actions/move/commit/layoutDrop.js.map +1 -0
- package/dist/actions/move/commit/layoutRelease.js +146 -0
- package/dist/actions/move/commit/layoutRelease.js.map +1 -0
- package/dist/actions/move/commit/pageDrop.js +162 -0
- package/dist/actions/move/commit/pageDrop.js.map +1 -0
- package/dist/actions/move/commit/rebase.js +24 -0
- package/dist/actions/move/commit/rebase.js.map +1 -0
- package/dist/actions/move/commit/reparent.js +157 -0
- package/dist/actions/move/commit/reparent.js.map +1 -0
- package/dist/actions/move/delta.js +127 -0
- package/dist/actions/move/delta.js.map +1 -0
- package/dist/actions/move/dragSnap.js +55 -0
- package/dist/actions/move/dragSnap.js.map +1 -0
- package/dist/actions/move/frame.js +67 -0
- package/dist/actions/move/frame.js.map +1 -0
- package/dist/actions/move/gestureAdapter.js +36 -0
- package/dist/actions/move/gestureAdapter.js.map +1 -0
- package/dist/actions/move/landedDescendants.js +50 -0
- package/dist/actions/move/landedDescendants.js.map +1 -0
- package/dist/actions/move/layout/container.js +119 -0
- package/dist/actions/move/layout/container.js.map +1 -0
- package/dist/actions/move/layout/dragged.js +75 -0
- package/dist/actions/move/layout/dragged.js.map +1 -0
- package/dist/actions/move/layout/dropPass.js +205 -0
- package/dist/actions/move/layout/dropPass.js.map +1 -0
- package/dist/actions/move/layout/exits.js +62 -0
- package/dist/actions/move/layout/exits.js.map +1 -0
- package/dist/actions/move/layout/glide.js +70 -0
- package/dist/actions/move/layout/glide.js.map +1 -0
- package/dist/actions/move/layout/view.js +60 -0
- package/dist/actions/move/layout/view.js.map +1 -0
- package/dist/actions/move/refusal.js +49 -0
- package/dist/actions/move/refusal.js.map +1 -0
- package/dist/actions/move/session.js +105 -0
- package/dist/actions/move/session.js.map +1 -0
- package/dist/actions/move/sessionOf.js +27 -0
- package/dist/actions/move/sessionOf.js.map +1 -0
- package/dist/actions/move/translate.js +49 -0
- package/dist/actions/move/translate.js.map +1 -0
- package/dist/actions/pathfinder/action.js +109 -0
- package/dist/actions/pathfinder/action.js.map +1 -0
- package/dist/actions/pathfinder/booleanGroupAction.js +117 -0
- package/dist/actions/pathfinder/booleanGroupAction.js.map +1 -0
- package/dist/actions/pathfinder/keymap.js +51 -0
- package/dist/actions/pathfinder/keymap.js.map +1 -0
- package/dist/actions/reorder/reorder.js +245 -0
- package/dist/actions/reorder/reorder.js.map +1 -0
- package/dist/actions/resize/action.js +105 -0
- package/dist/actions/resize/action.js.map +1 -0
- package/dist/actions/resize/aspect.js +42 -0
- package/dist/actions/resize/aspect.js.map +1 -0
- package/dist/actions/resize/behaviors/clampMinSize.js +100 -0
- package/dist/actions/resize/behaviors/clampMinSize.js.map +1 -0
- package/dist/actions/resize/boxFrame.js +19 -0
- package/dist/actions/resize/boxFrame.js.map +1 -0
- package/dist/actions/resize/capture.js +121 -0
- package/dist/actions/resize/capture.js.map +1 -0
- package/dist/actions/resize/commit.js +104 -0
- package/dist/actions/resize/commit.js.map +1 -0
- package/dist/actions/resize/frame.js +171 -0
- package/dist/actions/resize/frame.js.map +1 -0
- package/dist/actions/resize/held.js +44 -0
- package/dist/actions/resize/held.js.map +1 -0
- package/dist/actions/resize/minimum.js +34 -0
- package/dist/actions/resize/minimum.js.map +1 -0
- package/dist/actions/resize/replay.js +58 -0
- package/dist/actions/resize/replay.js.map +1 -0
- package/dist/actions/resize/ruleBounds.js +11 -0
- package/dist/actions/resize/ruleBounds.js.map +1 -0
- package/dist/actions/resize/session.js +118 -0
- package/dist/actions/resize/session.js.map +1 -0
- package/dist/actions/rotate/action.js +99 -0
- package/dist/actions/rotate/action.js.map +1 -0
- package/dist/actions/rotate/commit.js +48 -0
- package/dist/actions/rotate/commit.js.map +1 -0
- package/dist/actions/rotate/frame.js +96 -0
- package/dist/actions/rotate/frame.js.map +1 -0
- package/dist/actions/rotate/replay.js +25 -0
- package/dist/actions/rotate/replay.js.map +1 -0
- package/dist/actions/rotate/session.js +135 -0
- package/dist/actions/rotate/session.js.map +1 -0
- package/dist/actions/select/areaSelect.js +83 -0
- package/dist/actions/select/areaSelect.js.map +1 -0
- package/dist/actions/select/clearSelection.js +33 -0
- package/dist/actions/select/clearSelection.js.map +1 -0
- package/dist/actions/swap/action.js +63 -0
- package/dist/actions/swap/action.js.map +1 -0
- package/dist/actions/swap/swapOps.js +160 -0
- package/dist/actions/swap/swapOps.js.map +1 -0
- package/dist/actions/transformAgain/action.js +90 -0
- package/dist/actions/transformAgain/action.js.map +1 -0
- package/dist/actions/transformAgain/transformSelection.js +49 -0
- package/dist/actions/transformAgain/transformSelection.js.map +1 -0
- package/dist/booleans/booleans.js +130 -0
- package/dist/booleans/booleans.js.map +1 -0
- package/dist/booleans/commit.js +45 -0
- package/dist/booleans/commit.js.map +1 -0
- package/dist/booleans/custom.js +48 -0
- package/dist/booleans/custom.js.map +1 -0
- package/dist/booleans/operands.js +50 -0
- package/dist/booleans/operands.js.map +1 -0
- package/dist/booleans/pieces.js +43 -0
- package/dist/booleans/pieces.js.map +1 -0
- package/dist/booleans/placement.js +37 -0
- package/dist/booleans/placement.js.map +1 -0
- package/dist/booleans/useBooleans.js +34 -0
- package/dist/booleans/useBooleans.js.map +1 -0
- package/dist/booleans/useBooleansAdapter.js +11 -0
- package/dist/booleans/useBooleansAdapter.js.map +1 -0
- package/dist/chrome/affordances/cornerResize.js +123 -0
- package/dist/chrome/affordances/cornerResize.js.map +1 -0
- package/dist/chrome/affordances/rotateCursor.js +17 -0
- package/dist/chrome/affordances/rotateCursor.js.map +1 -0
- package/dist/chrome/affordances/rotationHandle.js +117 -0
- package/dist/chrome/affordances/rotationHandle.js.map +1 -0
- package/dist/chrome/handleCommands.js +110 -0
- package/dist/chrome/handleCommands.js.map +1 -0
- package/dist/chrome/overlay.js +271 -0
- package/dist/chrome/overlay.js.map +1 -0
- package/dist/chrome/rotationBadge.js +132 -0
- package/dist/chrome/rotationBadge.js.map +1 -0
- package/dist/chrome/rotationHandleGeometry.js +49 -0
- package/dist/chrome/rotationHandleGeometry.js.map +1 -0
- package/dist/chrome/selectionChrome.js +25 -0
- package/dist/chrome/selectionChrome.js.map +1 -0
- package/dist/chrome/selectionPose.js +112 -0
- package/dist/chrome/selectionPose.js.map +1 -0
- package/dist/chrome/shapeOutline.js +137 -0
- package/dist/chrome/shapeOutline.js.map +1 -0
- package/dist/clipboard/clipboardOps.js +48 -0
- package/dist/clipboard/clipboardOps.js.map +1 -0
- package/dist/clipboard/materializePaste.js +34 -0
- package/dist/clipboard/materializePaste.js.map +1 -0
- package/dist/clipboard/osClipboard.js +67 -0
- package/dist/clipboard/osClipboard.js.map +1 -0
- package/dist/clipboard/useClipboard.js +64 -0
- package/dist/clipboard/useClipboard.js.map +1 -0
- package/dist/clipboard/wireFormat.js +108 -0
- package/dist/clipboard/wireFormat.js.map +1 -0
- package/dist/deps/areaSelect.js +42 -0
- package/dist/deps/areaSelect.js.map +1 -0
- package/dist/deps/booleans.js +99 -0
- package/dist/deps/booleans.js.map +1 -0
- package/dist/deps/insert.js +260 -0
- package/dist/deps/insert.js.map +1 -0
- package/dist/deps/lassoSelect.js +37 -0
- package/dist/deps/lassoSelect.js.map +1 -0
- package/dist/deps/presetDeps.js +40 -0
- package/dist/deps/presetDeps.js.map +1 -0
- package/dist/deps/resizePolicy.js +41 -0
- package/dist/deps/resizePolicy.js.map +1 -0
- package/dist/engine-BV9RDHOL.d.ts +339 -0
- package/dist/engine.d.ts +6 -0
- package/dist/engine.js +10 -0
- package/dist/engineStandardActions.js +54 -0
- package/dist/engineStandardActions.js.map +1 -0
- package/dist/groups.d.ts +27 -0
- package/dist/groups.js +4 -0
- package/dist/icons.gen.js +8 -0
- package/dist/icons.gen.js.map +1 -0
- package/dist/icons.table.d.ts +6 -0
- package/dist/icons.table.js +8 -0
- package/dist/icons.table.js.map +1 -0
- package/dist/icons.table.json +156 -0
- package/dist/icons2.table.js +163 -0
- package/dist/icons2.table.js.map +1 -0
- package/dist/index.d.ts +1867 -0
- package/dist/index.js +86 -0
- package/dist/ingest/ghost.js +58 -0
- package/dist/ingest/ghost.js.map +1 -0
- package/dist/ingest/imageHandler.js +80 -0
- package/dist/ingest/imageHandler.js.map +1 -0
- package/dist/ingest/kitHandlers.js +15 -0
- package/dist/ingest/kitHandlers.js.map +1 -0
- package/dist/ingest/svgHandler.js +97 -0
- package/dist/ingest/svgHandler.js.map +1 -0
- package/dist/ingest/weaselJsonHandler.js +68 -0
- package/dist/ingest/weaselJsonHandler.js.map +1 -0
- package/dist/namedPresets.js +83 -0
- package/dist/namedPresets.js.map +1 -0
- package/dist/presets/arrange.js +65 -0
- package/dist/presets/arrange.js.map +1 -0
- package/dist/presets/booleans.js +13 -0
- package/dist/presets/booleans.js.map +1 -0
- package/dist/presets/composites.js +46 -0
- package/dist/presets/composites.js.map +1 -0
- package/dist/presets/edit.js +125 -0
- package/dist/presets/edit.js.map +1 -0
- package/dist/presets/ingest.js +17 -0
- package/dist/presets/ingest.js.map +1 -0
- package/dist/presets/insert.js +28 -0
- package/dist/presets/insert.js.map +1 -0
- package/dist/presets/pathfinder.js +26 -0
- package/dist/presets/pathfinder.js.map +1 -0
- package/dist/presets/select.js +31 -0
- package/dist/presets/select.js.map +1 -0
- package/dist/presets/selection.js +13 -0
- package/dist/presets/selection.js.map +1 -0
- package/dist/presets/selectionChrome.js +15 -0
- package/dist/presets/selectionChrome.js.map +1 -0
- package/dist/presets/tools.js +84 -0
- package/dist/presets/tools.js.map +1 -0
- package/dist/presets/transform.js +52 -0
- package/dist/presets/transform.js.map +1 -0
- package/dist/presets.d.ts +104 -0
- package/dist/presets.js +15 -0
- package/dist/selection/useSelection.js +127 -0
- package/dist/selection/useSelection.js.map +1 -0
- package/dist/test-seams.d.ts +50 -0
- package/dist/test-seams.js +4 -0
- package/dist/tools/ellipse/useEllipseTool.js +72 -0
- package/dist/tools/ellipse/useEllipseTool.js.map +1 -0
- package/dist/tools/eyedropper/useEyedropperTool.js +100 -0
- package/dist/tools/eyedropper/useEyedropperTool.js.map +1 -0
- package/dist/tools/image/useImageTool.js +57 -0
- package/dist/tools/image/useImageTool.js.map +1 -0
- package/dist/tools/lasso/useLassoTool.js +96 -0
- package/dist/tools/lasso/useLassoTool.js.map +1 -0
- package/dist/tools/line/useLineTool.js +67 -0
- package/dist/tools/line/useLineTool.js.map +1 -0
- package/dist/tools/polygon/usePolygonTool.js +149 -0
- package/dist/tools/polygon/usePolygonTool.js.map +1 -0
- package/dist/tools/rect/useRectTool.js +74 -0
- package/dist/tools/rect/useRectTool.js.map +1 -0
- package/dist/tools/select/adapterPointQuery.js +56 -0
- package/dist/tools/select/adapterPointQuery.js.map +1 -0
- package/dist/tools/select/collapseDeferred.js +35 -0
- package/dist/tools/select/collapseDeferred.js.map +1 -0
- package/dist/tools/select/extendPressLocked.js +17 -0
- package/dist/tools/select/extendPressLocked.js.map +1 -0
- package/dist/tools/select/groupEntry.js +73 -0
- package/dist/tools/select/groupEntry.js.map +1 -0
- package/dist/tools/select/pressDecision.js +39 -0
- package/dist/tools/select/pressDecision.js.map +1 -0
- package/dist/tools/select/selectDeep.js +39 -0
- package/dist/tools/select/selectDeep.js.map +1 -0
- package/dist/tools/select/selectPick.js +60 -0
- package/dist/tools/select/selectPick.js.map +1 -0
- package/dist/tools/select/selectionContributions.js +191 -0
- package/dist/tools/select/selectionContributions.js.map +1 -0
- package/dist/tools/select/usePickerSelectTool.js +145 -0
- package/dist/tools/select/usePickerSelectTool.js.map +1 -0
- package/dist/tools/select/useSelectTool.js +54 -0
- package/dist/tools/select/useSelectTool.js.map +1 -0
- package/dist/tools/shared/countOption.js +24 -0
- package/dist/tools/shared/countOption.js.map +1 -0
- package/dist/tools/shared/insertToolOptions.js +8 -0
- package/dist/tools/shared/insertToolOptions.js.map +1 -0
- package/dist/tools/shared/pointerFollower.js +23 -0
- package/dist/tools/shared/pointerFollower.js.map +1 -0
- package/dist/tools/shared/styleOptions.js +76 -0
- package/dist/tools/shared/styleOptions.js.map +1 -0
- package/dist/tools/star/useStarTool.js +149 -0
- package/dist/tools/star/useStarTool.js.map +1 -0
- package/dist/tools/toolSets.js +26 -0
- package/dist/tools/toolSets.js.map +1 -0
- package/dist/useStandardActions.js +26 -0
- package/dist/useStandardActions.js.map +1 -0
- package/package.json +87 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"selectionPose.js","names":["unionAabb"],"sources":["../../src/chrome/selectionPose.ts"],"sourcesContent":["/**\n * The pose and box a selection's chrome is drawn around: precedence between\n * the in-flight overlays and the stored pose, a container's union over its\n * leaves, and the drawn box a scene supplies.\n */\nimport type { Scale2 } from '@weasel-js/geom';\nimport { drawnAabbOf, drawnBoundsOf, type DrawnBoundsScene } from '@weasel-js/core';\nimport { unionAabb } from '@weasel-js/core/engine';\nimport { framedBounds, visualBoundsViaDescriptor, type PoseDescriptor } from '@weasel-js/core';\nimport { AUTO_POSE_DESCRIPTOR } from '@weasel-js/core/engine';\nimport type { NodeId } from '@weasel-js/core';\nimport type { Bounds } from '@weasel-js/core';\n\n/**\n * Transitive leaf ids under `id`. A childless node is a leaf only if it is not\n * itself a container: an empty container contributes no bounds, and its own\n * stored pose is at its most stale when no children are left to have moved it.\n */\nfunction leavesOf(\n id: string,\n getChildren: (id: string) => readonly string[],\n isContainer: (id: string) => boolean,\n): string[] {\n if (!isContainer(id)) return [id];\n const out: string[] = [];\n const visit = (nid: string) => {\n const kids = getChildren(nid);\n if (kids.length === 0) { if (!isContainer(nid)) out.push(nid); return; }\n for (const k of kids) visit(k);\n };\n visit(id);\n return out;\n}\n\n/** How one id's pose becomes a box: the pose box, or with a scene the box the\n * node is drawn with. Each id is read as a leaf — the pose already says where\n * a container is, so its members' stored poses are not consulted again. */\nfunction boxReader<TPose>(\n d: PoseDescriptor<TPose>,\n scene: DrawnBoundsScene | undefined,\n): { framed(id: string, pose: TPose, scale?: number | Scale2): Bounds; aabb(id: string, pose: TPose, scale?: number | Scale2): Bounds } {\n if (!scene) {\n return {\n framed: (_id, pose) => framedBounds(pose, d),\n aabb: (_id, pose) => visualBoundsViaDescriptor(pose, d),\n };\n }\n // Everything but `childrenOf`: the scene's own painters still say how each node is drawn.\n const leaves: DrawnBoundsScene = {\n get: (id) => scene.get(id),\n ...(scene.derivedPathOf ? { derivedPathOf: (id: NodeId) => scene.derivedPathOf!(id) } : {}),\n get shapes() { return scene.shapes; },\n };\n const opts = (scale: number | Scale2 | undefined) => ({\n descriptor: d as PoseDescriptor<unknown>,\n ...(scale !== undefined ? { scale } : {}),\n });\n return {\n framed: (id, pose, scale) => drawnBoundsOf(leaves, id as NodeId, pose, opts(scale)),\n aabb: (id, pose, scale) => drawnAabbOf(leaves, id as NodeId, pose, opts(scale)),\n };\n}\n\n/** Options for `composeSelectionPose`. */\nexport interface ComposeSelectionPoseOptions<TPose> {\n /** Move overlay; when present its `poses` map wins over everything else. */\n moveOverlay?: { poses: Map<string, TPose> } | null;\n /**\n * Resize overlay; consulted only when move overlay does not own the id.\n * For container resize, `leafPoses` (when present) maps each leaf id under\n * the container to its overlay pose. If absent the container falls back to\n * stored leaf poses.\n */\n resizeOverlay?: {\n id: string;\n currentPose: TPose;\n leafPoses?: Map<string, TPose>;\n } | null;\n /** Fallback pose lookup (typically the stored/committed pose). */\n getStoredPose: (id: string) => TPose;\n /** How to read poses. Default `AUTO_POSE_DESCRIPTOR`. */\n poseDescriptor?: PoseDescriptor<TPose>;\n /** Walk a container's direct children (e.g. `scene.childrenOf`). With\n * `isContainer`, a selected container resolves to the union AABB of its\n * transitive leaf poses instead of its own stored pose. */\n getChildren?: (id: string) => readonly string[];\n /** True when `id` is a structural container. */\n isContainer?: (id: string) => boolean;\n /** The nodes behind the ids. With it, a container's union takes each leaf\n * as drawn, stroke included (`drawnBoundsOf`); without, its pose box. */\n scene?: DrawnBoundsScene;\n /** View scale a screen-pixel stroke is resolved at. Default 1. */\n viewScale?: () => number | Scale2;\n}\n\n/**\n * Build a pose resolver for a selection. Precedence per id:\n * move overlay > resize overlay > stored. When `getChildren`/`isContainer`\n * are supplied and the id resolves to a container, the resolver returns the\n * union AABB of all transitive leaf poses (each leaf still subject to the\n * precedence rules). Containers with no leaves resolve to `null`.\n */\nexport function composeSelectionPose<TPose>(\n opts: ComposeSelectionPoseOptions<TPose>,\n): (id: string) => TPose | null {\n const { moveOverlay, resizeOverlay, getStoredPose, getChildren, isContainer } = opts;\n const d = (opts.poseDescriptor ?? AUTO_POSE_DESCRIPTOR) as PoseDescriptor<TPose>;\n const boxes = boxReader(d, opts.scene);\n\n const selectionLeaves = (id: string): string[] =>\n getChildren && isContainer ? leavesOf(id, getChildren, isContainer) : [id];\n\n const resolveLeaf = (id: string): TPose => {\n const moved = moveOverlay?.poses.get(id);\n if (moved !== undefined) return moved;\n if (resizeOverlay && resizeOverlay.id === id) return resizeOverlay.currentPose;\n return getStoredPose(id);\n };\n\n return (id: string): TPose | null => {\n if (isContainer?.(id)) {\n const leaves = selectionLeaves(id);\n if (leaves.length === 0) return null;\n const containerResizeLeafPoses =\n resizeOverlay && resizeOverlay.id === id ? resizeOverlay.leafPoses : undefined;\n const scale = opts.viewScale?.();\n const leafBounds: Bounds[] = [];\n for (const leafId of leaves) {\n const pose = moveOverlay?.poses.get(leafId)\n ?? containerResizeLeafPoses?.get(leafId)\n ?? resolveLeaf(leafId);\n leafBounds.push(boxes.aabb(leafId, pose, scale));\n }\n const u = unionAabb(leafBounds);\n if (u === null) return null;\n return d.fromBounds(u, getStoredPose(leaves[0]!));\n }\n return resolveLeaf(id);\n };\n}\n\n/**\n * Build a bounds resolver that handles container ids by computing the union\n * AABB of every leaf's bounds. Non-container ids pass through directly. When\n * `getChildren`/`isContainer` are omitted, every id is treated as a leaf.\n * With a scene, each leaf is boxed as drawn at the view's scale.\n */\nexport function containerAwareBoundsResolver<TPose>(\n getPose: (id: string) => TPose | null,\n d: PoseDescriptor<TPose>,\n getChildren: ((id: string) => readonly string[]) | undefined,\n isContainer: ((id: string) => boolean) | undefined,\n scene: DrawnBoundsScene | undefined,\n): (id: string, scale: Scale2) => Bounds | null {\n const boxes = boxReader(d, scene);\n const leaf = (id: string, scale: Scale2): Bounds | null => {\n const p = getPose(id);\n return p === null ? null : boxes.framed(id, p, scale);\n };\n if (getChildren === undefined || isContainer === undefined) return leaf;\n return (id, scale) => {\n if (!isContainer(id)) return leaf(id, scale);\n const leaves = leavesOf(id, getChildren, isContainer);\n if (leaves.length === 0) return null;\n const leafBounds: Bounds[] = [];\n for (const leafId of leaves) {\n const p = getPose(leafId);\n if (p !== null) leafBounds.push(boxes.aabb(leafId, p, scale));\n }\n if (leafBounds.length === 0) return null;\n return unionAabb(leafB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;GAC3B,MAAM,IAAI,QAAQ,MAAM;GACxB,IAAI,MAAM,MAAM,WAAW,KAAK,MAAM,KAAK,QAAQ,GAAG,KAAK,CAAC;EAC9D;EACA,IAAI,WAAW,WAAW,GAAG,OAAO;EACpC,OAAOA,YAAU,UAAU;CAC7B;AACF"}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { findShapeInk, nodeOutline, strokeRegion } from "@weasel-js/core";
|
|
2
|
+
import { inheritedPaintIn } from "@weasel-js/core/engine";
|
|
3
|
+
import { identity, invert, meanScale, multiply, pathToAnchors, poseFrameOf, rectToRect, transformPath } from "@weasel-js/geom";
|
|
4
|
+
import { viewToMat3 } from "@weasel-js/renderer";
|
|
5
|
+
import { offsetPath, strokeToPath } from "@weasel-js/stroke";
|
|
6
|
+
|
|
7
|
+
// src/chrome/shapeOutline.ts
|
|
8
|
+
/**
|
|
9
|
+
* A per-layer builder of shape outlines. It keeps each outlined node's drawn
|
|
10
|
+
* edge between frames: growing a curved silhouette past its stroke costs
|
|
11
|
+
* milliseconds, so it is rebuilt only when the shape or the stroke's reach
|
|
12
|
+
* changes, and a node in flight reuses its committed edge, carried by the
|
|
13
|
+
* move from the committed box to the previewed one.
|
|
14
|
+
*/
|
|
15
|
+
function createShapeOutliner() {
|
|
16
|
+
const edges = /* @__PURE__ */ new Map();
|
|
17
|
+
return { outline(ids, reads, scale) {
|
|
18
|
+
const paths = [];
|
|
19
|
+
const boxed = [];
|
|
20
|
+
for (const id of ids) {
|
|
21
|
+
const edge = traceEdge(id, reads, scale, edges);
|
|
22
|
+
if (edge) paths.push(edge);
|
|
23
|
+
else boxed.push(id);
|
|
24
|
+
}
|
|
25
|
+
if (edges.size > ids.length) {
|
|
26
|
+
const live = new Set(ids);
|
|
27
|
+
for (const id of edges.keys()) if (!live.has(id)) edges.delete(id);
|
|
28
|
+
}
|
|
29
|
+
return {
|
|
30
|
+
paths,
|
|
31
|
+
boxed
|
|
32
|
+
};
|
|
33
|
+
} };
|
|
34
|
+
}
|
|
35
|
+
function traceEdge(id, reads, scale, edges) {
|
|
36
|
+
const { scene } = reads;
|
|
37
|
+
const node = scene.get(id);
|
|
38
|
+
if (!node || node.kind === "group" || holdsMembers(scene, id)) return null;
|
|
39
|
+
const pose = reads.poseOf(id);
|
|
40
|
+
const derivedPath = scene.derivedPathOf?.(id) ?? null;
|
|
41
|
+
const shapes = scene.shapes;
|
|
42
|
+
const silhouette = nodeOutline(node, pose, derivedPath || shapes ? {
|
|
43
|
+
derivedPath,
|
|
44
|
+
shapes
|
|
45
|
+
} : void 0);
|
|
46
|
+
if (!silhouette) return null;
|
|
47
|
+
const inherited = inheritedPaintIn(scene, node);
|
|
48
|
+
const ink = findShapeInk(node, pose, {
|
|
49
|
+
scale,
|
|
50
|
+
shapes,
|
|
51
|
+
...inherited === void 0 ? {} : { inherited }
|
|
52
|
+
});
|
|
53
|
+
const distance = (ink?.outset ?? 0) + (ink?.outsetPx ?? 0) / scale;
|
|
54
|
+
const open = isOpen(silhouette);
|
|
55
|
+
if (open && distance <= 0) return null;
|
|
56
|
+
if (distance <= 0) {
|
|
57
|
+
edges.delete(id);
|
|
58
|
+
return silhouette;
|
|
59
|
+
}
|
|
60
|
+
const key = derivedPath ?? silhouette;
|
|
61
|
+
const held = edges.get(id);
|
|
62
|
+
if (held && held.key === key && held.inherited === inherited && held.distance === distance) return held.edge;
|
|
63
|
+
if (held && held.inherited === inherited && held.distance === distance && reads.inFlight(id)) {
|
|
64
|
+
const carry = boxMove(held.pose, pose);
|
|
65
|
+
if (carry) return transformPath(held.edge, carry);
|
|
66
|
+
}
|
|
67
|
+
const edge = open ? inkBand(silhouette, ink?.stroke, pose, distance, scale) : offsetPath(silhouette, distance);
|
|
68
|
+
if (edge.kind === "polygon" && edge.commands.length === 0) return null;
|
|
69
|
+
edges.set(id, {
|
|
70
|
+
key,
|
|
71
|
+
pose,
|
|
72
|
+
inherited,
|
|
73
|
+
distance,
|
|
74
|
+
edge
|
|
75
|
+
});
|
|
76
|
+
return edge;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* The region an open path's ink covers: its stroke's ribbon, caps and heads
|
|
80
|
+
* and all, unbroken by any dash; a band reaching `distance` either side when
|
|
81
|
+
* the painter does not say what stroke it draws.
|
|
82
|
+
*/
|
|
83
|
+
function inkBand(path, stroke, pose, distance, scale) {
|
|
84
|
+
if (stroke === void 0) return strokeToPath(path, {
|
|
85
|
+
width: distance * 2,
|
|
86
|
+
join: "round",
|
|
87
|
+
cap: "round"
|
|
88
|
+
});
|
|
89
|
+
const { dash: _dash, ...unbroken } = stroke;
|
|
90
|
+
return strokeRegion(path, unbroken, poseFrameOf(pose), { scale });
|
|
91
|
+
}
|
|
92
|
+
/** Whether `id` holds a child that can be picked on its own: a member, which its box has to take
|
|
93
|
+
* in. An unpickable child — a shape's own label or text row — is part of it, as a pick treats it. */
|
|
94
|
+
function holdsMembers(scene, id) {
|
|
95
|
+
return (scene.childrenOf?.(id) ?? []).some((child) => scene.get(child)?.pickable !== false);
|
|
96
|
+
}
|
|
97
|
+
/** An open run encloses nothing, so its edge is the band its ink covers. */
|
|
98
|
+
function isOpen(path) {
|
|
99
|
+
return path.kind !== "rect" && !pathToAnchors(path).closed.every(Boolean);
|
|
100
|
+
}
|
|
101
|
+
/** The map taking a box pose's drawing onto another box pose's, or `null` when either is not a box. */
|
|
102
|
+
function boxMove(from, to) {
|
|
103
|
+
const a = from;
|
|
104
|
+
const b = to;
|
|
105
|
+
if (a?.x == null || a.y == null || a.width == null || a.height == null) return null;
|
|
106
|
+
if (b?.x == null || b.y == null || b.width == null || b.height == null) return null;
|
|
107
|
+
const unframe = invert(poseFrameOf(from) ?? identity());
|
|
108
|
+
if (!unframe) return null;
|
|
109
|
+
const box = rectToRect(a.x, a.y, a.width, a.height, b.x, b.y, b.width, b.height);
|
|
110
|
+
return multiply(poseFrameOf(to) ?? identity(), multiply(box, unframe));
|
|
111
|
+
}
|
|
112
|
+
/** Screen-space commands stroking `paths` outward at `stroke`'s width in screen pixels. */
|
|
113
|
+
function shapeOutlineCommands(paths, stroke, view) {
|
|
114
|
+
if (paths.length === 0) return [];
|
|
115
|
+
const w = stroke.width ?? 1;
|
|
116
|
+
const ribbon = {
|
|
117
|
+
...stroke,
|
|
118
|
+
width: typeof w === "number" ? { px: w } : w,
|
|
119
|
+
align: stroke.align ?? "outer"
|
|
120
|
+
};
|
|
121
|
+
return [{
|
|
122
|
+
kind: "group",
|
|
123
|
+
transform: viewToMat3(view),
|
|
124
|
+
children: paths.map((path) => ({
|
|
125
|
+
kind: "path",
|
|
126
|
+
path,
|
|
127
|
+
stroke: ribbon
|
|
128
|
+
}))
|
|
129
|
+
}];
|
|
130
|
+
}
|
|
131
|
+
/** The view's mean scale, which a `{ px }` stroke reach is resolved at. */
|
|
132
|
+
function viewScaleOf(view) {
|
|
133
|
+
return meanScale(view.scale);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export { createShapeOutliner, shapeOutlineCommands, viewScaleOf };
|
|
137
|
+
//# sourceMappingURL=shapeOutline.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"shapeOutline.js","names":[],"sources":["../../src/chrome/shapeOutline.ts"],"sourcesContent":["/**\n * Selection outlines that follow a node's shape rather than its box.\n *\n * The outline is a world-space path stroked outward at a fixed screen width,\n * so the view transform carries it through pan and zoom without rebuilding\n * it. It starts at the node's drawn edge: the silhouette, grown past the\n * node's own stroke when it has one.\n */\nimport type { DrawCommand } from '@weasel-js/renderer';\nimport { viewToMat3 } from '@weasel-js/renderer';\nimport {\n rectToRect, identity, invert, meanScale, multiply, pathToAnchors, poseFrameOf, transformPath, type Affine, type Path,\n} from '@weasel-js/geom';\nimport { offsetPath, strokeToPath } from '@weasel-js/stroke';\nimport type { CommandStroke, Stroke } from '@weasel-js/paint';\nimport type { NodeId } from '@weasel-js/core';\nimport type { View } from '@weasel-js/core';\nimport { inheritedPaintIn } from '@weasel-js/core/engine';\nimport { findShapeInk } from '@weasel-js/core';\nimport { nodeOutline } from '@weasel-js/core';\nimport { strokeRegion } from '@weasel-js/core';\nimport type { DrawnBoundsScene } from '@weasel-js/core';\n\n/** How a shape outline reads one node each frame. */\nexport interface ShapeOutlineReads {\n scene: DrawnBoundsScene;\n /** Where the node is drawn this frame, in-flight preview included. */\n poseOf: (id: string) => unknown;\n /** True while a gesture previews `id` somewhere other than its committed pose. */\n inFlight: (id: string) => boolean;\n}\n\ninterface Edge {\n /** What the edge was built from: the silhouette, or the derived path that stands in for the pose. */\n key: Path;\n pose: unknown;\n /** The paint the node inherits from its containers, which `inheritedPaintIn` hands back as the\n * same object while it holds: a container's stroke edit changes an inheriting band's caps\n * and heads without touching the node or its silhouette. */\n inherited: unknown;\n distance: number;\n edge: Path;\n}\n\n/**\n * A per-layer builder of shape outlines. It keeps each outlined node's drawn\n * edge between frames: growing a curved silhouette past its stroke costs\n * milliseconds, so it is rebuilt only when the shape or the stroke's reach\n * changes, and a node in flight reuses its committed edge, carried by the\n * move from the committed box to the previewed one.\n */\nexport function createShapeOutliner(): {\n /** World-space paths to stroke, and the ids that have no shape to follow. */\n outline(ids: readonly string[], reads: ShapeOutlineReads, scale: number): { paths: Path[]; boxed: string[] };\n} {\n const edges = new Map<string, Edge>();\n return {\n outline(ids, reads, scale) {\n const paths: Path[] = [];\n const boxed: string[] = [];\n for (const id of ids) {\n const edge = traceEdge(id, reads, scale, edges);\n if (edge) paths.push(edge);\n else boxed.push(id);\n }\n if (edges.size > ids.length) {\n const live = new Set(ids);\n for (const id of edges.keys()) if (!live.has(id)) edges.delete(id);\n }\n return { paths, boxed };\n },\n };\n}\n\nfunction traceEdge(id: string, reads: ShapeOutlineReads, scale: number, edges: Map<string, Edge>): Path | null {\n const { scene } = reads;\n const node = scene.get(id as NodeId);\n if (!node || node.kind === 'group' || holdsMembers(scene, id as NodeId)) return null;\n const pose = reads.poseOf(id);\n const derivedPath = scene.derivedPathOf?.(id as NodeId) ?? null;\n const shapes = scene.shapes;\n const silhouette = nodeOutline(node, pose, derivedPath || shapes ? { derivedPath, shapes } : undefined);\n if (!silhouette) return null;\n const inherited = inheritedPaintIn(scene, node);\n const ink = findShapeInk(node, pose, { scale, shapes, ...(inherited === undefined ? {} : { inherited }) });\n const distance = (ink?.outset ?? 0) + (ink?.outsetPx ?? 0) / scale;\n const open = isOpen(silhouette);\n if (open && distance <= 0) return null;\n if (distance <= 0) {\n edges.delete(id);\n return silhouette;\n }\n const key = derivedPath ?? silhouette;\n const held = edges.get(id);\n if (held && held.key === key && held.inherited === inherited && held.distance === distance) return held.edge;\n if (held && held.inherited === inherited && held.distance === distance && reads.inFlight(id)) {\n const carry = boxMove(held.pose, pose);\n if (carry) return transformPath(held.edge, carry);\n }\n const edge = open ? inkBand(silhouette, ink?.stroke, pose, distance, scale) : offsetPath(silhouette, distance);\n if (edge.kind === 'polygon' && edge.commands.length === 0) return null;\n edges.set(id, { key, pose, inherited, distance, edge });\n return edge;\n}\n\n/**\n * The region an open path's ink covers: its stroke's ribbon, caps and heads\n * and all, unbroken by any dash; a band reaching `distance` either side when\n * the painter does not say what stroke it draws.\n */\nfunction inkBand(path: Path, stroke: Stroke | undefined, pose: unknown, distance: number, scale: number): Path {\n if (stroke === undefined) return strokeToPath(path, { width: distance * 2, join: 'round', cap: 'round' });\n const { dash: _dash, ...unbroken } = stroke;\n return strokeRegion(path, unbroken, poseFrameOf(pose), { scale });\n}\n\n/** Whether `id` holds a child that can be picked on its own: a member, which its box has to take\n * in. An unpickable child — a shape's own label or text row — is part of it, as a pick treats it. */\nfunction holdsMembers(scene: DrawnBoundsScene, id: NodeId): boolean {\n return (scene.childrenOf?.(id) ?? []).some((child) => scene.get(child)?.pickable !== false);\n}\n\n/** An open run encloses nothing, so its edge is the band its ink covers. */\nfunction isOpen(path: Path): boolean {\n return path.kind !== 'rect' && !pathToAnchors(path).closed.every(Boolean);\n}\n\n/** The map taking a box pose's drawing onto another box pose's, or `null` when either is not a box. */\nfunction boxMove(from: unknown, to: unknown): Affine | null {\n const a = from as { x?: number; y?: number; width?: number; height?: number } | null;\n const b = to as { x?: number; y?: number; width?: number; height?: number } | null;\n if (a?.x == null || a.y == null || a.width == null || a.height == null) return null;\n if (b?.x == null || b.y == null || b.width == null || b.height == null) return null;\n const unframe = invert(poseFrameOf(from) ?? identity());\n if (!unframe) return null;\n const box = rectToRect(a.x, a.y, a.width, a.height, b.x, b.y, b.width, b.height);\n return multiply(poseFrameOf(to) ?? identity(), multiply(box, unframe));\n}\n\n/** Screen-space commands stroking `paths` outward at `stroke`'s width in screen pixels. */\nexport function shapeOutlineCommands(paths: readonly Path[], stroke: CommandStroke, view: View): DrawCommand[] {\n if (paths.length === 0) return [];\n const w = stroke.width ?? 1;\n const ribbon: CommandStroke = {\n ...stroke,\n width: typeof w === 'number' ? { px: w } : w,\n align: stroke.align ?? 'outer',\n };\n return [{\n kind: 'group',\n transform: viewToMat3(view),\n children: paths.map((path) => ({ kind: 'path', path, stroke: ribbon })),\n }];\n}\n\n/** The view's mean scale, which a `{ px }` stroke reach is resolved at. */\nexport function viewScaleOf(view: View): number {\n return meanScale(view.scale);\n}\n"],"mappings":";;;;;;;;;;;;;;AAmDA,SAAgB,sBAGd;CACA,MAAM,wBAAQ,IAAI,IAAkB;CACpC,OAAO,EACL,QAAQ,KAAK,OAAO,OAAO;EACzB,MAAM,QAAgB,CAAC;EACvB,MAAM,QAAkB,CAAC;EACzB,KAAK,MAAM,MAAM,KAAK;GACpB,MAAM,OAAO,UAAU,IAAI,OAAO,OAAO,KAAK;GAC9C,IAAI,MAAM,MAAM,KAAK,IAAI;QACpB,MAAM,KAAK,EAAE;EACpB;EACA,IAAI,MAAM,OAAO,IAAI,QAAQ;GAC3B,MAAM,OAAO,IAAI,IAAI,GAAG;GACxB,KAAK,MAAM,MAAM,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,EAAE,GAAG,MAAM,OAAO,EAAE;EACnE;EACA,OAAO;GAAE;GAAO;EAAM;CACxB,EACF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AC;CAChC,MAAM,IAAI,OAAO,SAAS;CAC1B,MAAM,SAAwB;EAC5B,GAAG;EACH,OAAO,OAAO,MAAM,WAAW,EAAE,IAAI,EAAE,IAAI;EAC3C,OAAO,OAAO,SAAS;CACzB;CACA,OAAO,CAAC;EACN,MAAM;EACN,WAAW,WAAW,IAAI;EAC1B,UAAU,MAAM,KAAK,UAAU;GAAE,MAAM;GAAQ;GAAM,QAAQ;EAAO,EAAE;CACxE,CAAC;AACH;;AAGA,SAAgB,YAAY,MAAoB;CAC9C,OAAO,UAAU,KAAK,KAAK;AAC7B"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { materializePaste } from "./materializePaste.js";
|
|
2
|
+
import { useClipboard } from "./useClipboard.js";
|
|
3
|
+
import { dispatchApplyBatch } from "@weasel-js/core";
|
|
4
|
+
import { useCallback } from "react";
|
|
5
|
+
import { useLatest } from "@weasel-js/react";
|
|
6
|
+
|
|
7
|
+
// src/clipboard/clipboardOps.ts
|
|
8
|
+
/** `useClipboard` over `InsertAdapter.snapshotSelection` / `commitPaste`, each paste one undoable op batch. */
|
|
9
|
+
function useClipboardOps(adapter, options) {
|
|
10
|
+
const { getSelection, onPaste, onPasteOmitted, pasteLabel = "Paste", getDropPoint, produceFlavors, jsonReplacer } = options;
|
|
11
|
+
const live = useLatest({
|
|
12
|
+
adapter,
|
|
13
|
+
getSelection,
|
|
14
|
+
onPasteOmitted,
|
|
15
|
+
pasteLabel
|
|
16
|
+
});
|
|
17
|
+
const copy = useCallback((ids) => {
|
|
18
|
+
const snap = live.current.adapter.snapshotSelection;
|
|
19
|
+
return snap ? snap.call(live.current.adapter, [...ids]).items : null;
|
|
20
|
+
}, [live]);
|
|
21
|
+
const paste = useCallback((items, at) => {
|
|
22
|
+
const { adapter: a, getSelection: selected, onPasteOmitted: omitted, pasteLabel: label } = live.current;
|
|
23
|
+
const result = materializePaste(a, { items: [...items] }, {
|
|
24
|
+
currentSelection: selected(),
|
|
25
|
+
dropPoint: at.dropPoint,
|
|
26
|
+
onOmitted: omitted
|
|
27
|
+
});
|
|
28
|
+
if (!result) return null;
|
|
29
|
+
dispatchApplyBatch(a, result.ops, label);
|
|
30
|
+
const again = a.snapshotSelection?.call(a, [...result.newIds]).items ?? [];
|
|
31
|
+
return {
|
|
32
|
+
ids: result.newIds,
|
|
33
|
+
items: again.length > 0 ? again : result.created
|
|
34
|
+
};
|
|
35
|
+
}, [live]);
|
|
36
|
+
return useClipboard({
|
|
37
|
+
getSelection,
|
|
38
|
+
copy,
|
|
39
|
+
paste,
|
|
40
|
+
...onPaste ? { onPaste: (ids) => onPaste(ids) } : {},
|
|
41
|
+
...getDropPoint ? { getDropPoint } : {},
|
|
42
|
+
...produceFlavors ? { produceFlavors: ({ items }) => produceFlavors({ items: [...items] }) } : {},
|
|
43
|
+
...jsonReplacer ? { jsonReplacer } : {}
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export { useClipboardOps };
|
|
48
|
+
//# sourceMappingURL=clipboardOps.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"clipboardOps.js","names":[],"sources":["../../src/clipboard/clipboardOps.ts"],"sourcesContent":["import { useCallback } from 'react';\nimport { useLatest } from '@weasel-js/react';\nimport type { NodeId } from '@weasel-js/core';\nimport { dispatchApplyBatch } from '@weasel-js/core';\nimport type { ClipboardSnapshot, InsertAdapter, PasteOmission } from '@weasel-js/core/engine';\nimport type { WorldPoint } from '@weasel-js/routing';\nimport { materializePaste } from './materializePaste';\nimport type { ClipboardFlavors } from './osClipboard';\nimport { useClipboard } from './useClipboard';\n\nexport type { ClipboardFlavors } from './osClipboard';\n\n/** Options for `useClipboardOps`. */\nexport interface UseClipboardOpsOptions {\n /** How the hook reads \"current selection\" for copy. The kit doesn't assume\n * a global selection store; each consumer wires this. */\n getSelection: () => NodeId[];\n /** Called after a successful paste with the ids of the newly inserted objects. */\n onPaste?: (newIds: NodeId[]) => void;\n /** Called when a paste left copied nodes out, with each one and the reason\n * — an edge whose endpoints were not copied with it, say. Also called for\n * a paste that made nothing. */\n onPasteOmitted?: (omitted: PasteOmission[]) => void;\n /** Label for the history entry produced by paste. Default 'Paste'. */\n pasteLabel?: string;\n /** Pulled once per paste() call. When non-null, threaded to commitPaste\n * as `ctx.dropPoint`; adapters typically use it as the cluster origin\n * (ignoring `offset`). When null/undefined, the hook falls back to the\n * existing cascade-offset behavior. */\n getDropPoint?: () => WorldPoint | null;\n /** Produce the OS-clipboard flavor map for a copied snapshot. Keys are MIME\n * types, values the serialized payload. The kit default emits\n * `application/x-weasel-clipboard+json` plus `text/plain` carrying the\n * same JSON. Apps override to add richer flavors (e.g. real SVG) or to\n * replace the text flavor. Return an empty object to skip the OS write\n * entirely. A value may be a promise — an SVG flavor waiting on\n * `warmSvg`, say: the write is still issued inside the copy gesture and\n * the clipboard takes the text when it resolves. The producer itself runs\n * synchronously, so it reads the selection as it stood at the copy. */\n produceFlavors?: (snapshot: ClipboardSnapshot) => ClipboardFlavors;\n /** Replacer for the kit-default JSON flavor (typed arrays etc.). Ignored\n * when `produceFlavors` is supplied. */\n jsonReplacer?: (key: string, value: unknown) => unknown;\n}\n\n/** Return shape of `useClipboardOps`: imperative `copy`, `paste`, and `isEmpty` functions. */\nexport interface UseClipboardOpsReturn {\n copy(): void;\n /** Paste at `at` when given; otherwise at the drop point, else the cascade offset. */\n paste(at?: WorldPoint): void;\n isEmpty(): boolean;\n}\n\n/** `useClipboard` over `InsertAdapter.snapshotSelection` / `commitPaste`, each paste one undoable op batch. */\nexport function useClipboardOps<TNode extends { id: string }>(\n adapter: InsertAdapter<TNode>,\n options: UseClipboardOpsOptions,\n): UseClipboardOpsReturn {\n const { getSelection, onPaste, onPasteOmitted, pasteLabel = 'Paste', getDropPoint, produceFlavors, jsonReplacer } = options;\n const live = useLatest({ adapter, getSelection, onPasteOmitted, pasteLabel });\n const copy = useCallback((ids: readonly string[]) => {\n const snap = live.current.adapter.snapshotSelection;\n return snap ? snap.call(live.current.adapter, [...ids]).items : null;\n }, [live]);\n const paste = useCallback((items: readonly unknown[], at: { dropPoint?: WorldPoint }) => {\n const { adapter: a, getSelection: selected, onPasteOmitted: omitted, pasteLabel: label } = live.current;\n const result = materializePaste(a, { items: [...items] }, {\n currentSelection: selected(),\n dropPoint: at.dropPoint,\n onOmitted: omitted,\n });\n if (!result) return null;\n dispatchApplyBatch(a, result.ops, label);\n // A snapshot captures roots in world, as a copy does; a created node's pose is local to the page or container\n // it landed in. A React-state adapter has not flushed the insert yet, and its empty snapshot falls back.\n const again = a.snapshotSelection?.call(a, [...result.newIds]).items ?? [];\n return { ids: result.newIds, items: again.length > 0 ? again : result.created };\n }, [live]);\n return useClipboard<unknown>({\n getSelection,\n copy,\n paste,\n ...(onPaste ? { onPaste: (ids: string[]) => onPaste(ids as NodeId[]) } : {}),\n ...(getDropPoint ? { getDropPoint } : {}),\n ...(produceFlavors ? { produceFlavors: ({ items }) => produceFlavors({ items: [...items] }) } : {}),\n ...(jsonReplacer ? { jsonReplacer } : {}),\n });\n}\n"],"mappings":";;;;;;;;AAsDA,SAAgB,gBACd,SACA,SACuB;CACvB,MAAM,EAAE,cAAc,SAAS,gBAAgB,aAAa,SAAS,cAAc,gBAAgB,iBAAiB;CACpH,MAAM,OAAO,UAAU;EAAE;EAAS;EAAc;EAAgB;CAAW,CAAC;CAC5E,MAAM,OAAO,aAAa,QAA2B;EACnD,MAAM,OAAO,KAAK,QAAQ,QAAQ;EAClC,OAAO,OAAO,KAAK,KAAK,KAAK,QAAQ,SAAS,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,QAAQ;CAClE,GAAG,CAAC,IAAI,CAAC;CACT,MAAM,QAAQ,aAAa,OAA2B,OAAmC;EACvF,MAAM,EAAE,SAAS,GAAG,cAAc,UAAU,gBAAgB,SAAS,YAAY,UAAU,KAAK;EAChG,MAAM,SAAS,iBAAiB,GAAG,EAAE,OAAO,CAAC,GAAG,KAAK,EAAE,GAAG;GACxD,kBAAkB,SAAS;GAC3B,WAAW,GAAG;GACd,WAAW;EACb,CAAC;EACD,IAAI,CAAC,QAAQ,OAAO;EACpB,mBAAmB,GAAG,OAAO,KAAK,KAAK;EAGvC,MAAM,QAAQ,EAAE,mBAAmB,KAAK,GAAG,CAAC,GAAG,OAAO,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC;EACzE,OAAO;GAAE,KAAK,OAAO;GAAQ,OAAO,MAAM,SAAS,IAAI,QAAQ,OAAO;EAAQ;CAChF,GAAG,CAAC,IAAI,CAAC;CACT,OAAO,aAAsB;EAC3B;EACA;EACA;EACA,GAAI,UAAU,EAAE,UAAU,QAAkB,QAAQ,GAAe,EAAE,IAAI,CAAC;EAC1E,GAAI,eAAe,EAAE,aAAa,IAAI,CAAC;EACvC,GAAI,iBAAiB,EAAE,iBAAiB,EAAE,YAAY,eAAe,EAAE,OAAO,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE,IAAI,CAAC;EACjG,GAAI,eAAe,EAAE,aAAa,IAAI,CAAC;CACzC,CAAC;AACH"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import * as coreOps from "@weasel-js/core/ops";
|
|
2
|
+
|
|
3
|
+
// src/clipboard/materializePaste.ts
|
|
4
|
+
/** Shared paste materialization: offset policy → commitPaste → the op batch
|
|
5
|
+
* both the in-memory paste and the OS-paste handler dispatch. Returns null
|
|
6
|
+
* when the adapter can't paste or nothing was created. */
|
|
7
|
+
function materializePaste(adapter, snapshot, opts) {
|
|
8
|
+
const commitPaste = adapter.commitPaste;
|
|
9
|
+
if (!commitPaste) return null;
|
|
10
|
+
const offset = adapter.getPasteOffset?.(snapshot) ?? {
|
|
11
|
+
dx: 0,
|
|
12
|
+
dy: 0
|
|
13
|
+
};
|
|
14
|
+
const omitted = [];
|
|
15
|
+
const ctx = {
|
|
16
|
+
...opts.dropPoint != null ? { dropPoint: opts.dropPoint } : {},
|
|
17
|
+
...opts.onOmitted ? { onOmit: (omission) => omitted.push(omission) } : {}
|
|
18
|
+
};
|
|
19
|
+
const created = commitPaste.call(adapter, snapshot, offset, Object.keys(ctx).length > 0 ? ctx : void 0);
|
|
20
|
+
if (omitted.length > 0) opts.onOmitted?.(omitted);
|
|
21
|
+
if (created.length === 0) return null;
|
|
22
|
+
const newIds = created.map((o) => o.id);
|
|
23
|
+
return {
|
|
24
|
+
ops: [...created.map((o) => coreOps.insert({ node: o })), coreOps.setSelection({
|
|
25
|
+
from: opts.currentSelection,
|
|
26
|
+
to: newIds
|
|
27
|
+
})],
|
|
28
|
+
newIds,
|
|
29
|
+
created
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export { materializePaste };
|
|
34
|
+
//# sourceMappingURL=materializePaste.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"materializePaste.js","names":[],"sources":["../../src/clipboard/materializePaste.ts"],"sourcesContent":["/**\n * Shared paste materialization — the one place the paste recipe lives:\n * offset policy → `commitPaste` → the op batch (InsertOps parents-first +\n * a SetSelectionOp). Both `useClipboardOps.paste` (in-memory paste) and the\n * kit weasel-JSON content handler (OS-clipboard paste) dispatch exactly this\n * batch, so the two arrival paths stay indistinguishable in history.\n *\n * Pure: no dispatching here — callers own how the ops are applied\n * (`dispatchApplyBatch` vs `IngestCtx.applyOps`) and any post-paste\n * bookkeeping (the hook's cascade re-snapshot, the handler's selection set).\n */\nimport type { Op, NodeId } from '@weasel-js/core';\nimport type { WorldPoint } from '@weasel-js/routing';\nimport type { ClipboardSnapshot, InsertAdapter, PasteCtx, PasteOmission } from '@weasel-js/core/engine';\nimport * as coreOps from '@weasel-js/core/ops';\n\n/** Shared paste materialization: offset policy → commitPaste → the op batch\n * both the in-memory paste and the OS-paste handler dispatch. Returns null\n * when the adapter can't paste or nothing was created. */\nexport function materializePaste<TNode extends { id: string }>(\n adapter: InsertAdapter<TNode>,\n snapshot: ClipboardSnapshot,\n opts: {\n currentSelection: string[];\n dropPoint?: WorldPoint | null;\n /** Told what the paste left out and why, when it left anything out —\n * including a paste that made nothing. */\n onOmitted?: (omitted: PasteOmission[]) => void;\n },\n): { ops: Op[]; newIds: string[]; created: TNode[] } | null {\n const commitPaste = adapter.commitPaste;\n if (!commitPaste) return null;\n const offset = adapter.getPasteOffset?.(snapshot) ?? { dx: 0, dy: 0 };\n const omitted: PasteOmission[] = [];\n const ctx: PasteCtx = {\n ...(opts.dropPoint != null ? { dropPoint: opts.dropPoint } : {}),\n ...(opts.onOmitted ? { onOmit: (omission: PasteOmission) => omitted.push(omission) } : {}),\n };\n const created = commitPaste.call(\n adapter, snapshot, offset, Object.keys(ctx).length > 0 ? ctx : undefined,\n );\n if (omitted.length > 0) opts.onOmitted?.(omitted);\n if (created.length === 0) return null;\n const newIds = created.map((o) => o.id);\n const ops: Op[] = [\n ...created.map((o) => coreOps.insert({ node: o })),\n coreOps.setSelection({ from: opts.currentSelection as NodeId[], to: newIds as NodeId[] }),\n ];\n return { ops, newIds, created };\n}\n"],"mappings":";;;;;;AAmBA,SAAgB,iBACd,SACA,UACA,MAO0D;CAC1D,MAAM,cAAc,QAAQ;CAC5B,IAAI,CAAC,aAAa,OAAO;CACzB,MAAM,SAAS,QAAQ,iBAAiB,QAAQ,KAAK;EAAE,IAAI;EAAG,IAAI;CAAE;CACpE,MAAM,UAA2B,CAAC;CAClC,MAAM,MAAgB;EACpB,GAAI,KAAK,aAAa,OAAO,EAAE,WAAW,KAAK,UAAU,IAAI,CAAC;EAC9D,GAAI,KAAK,YAAY,EAAE,SAAS,aAA4B,QAAQ,KAAK,QAAQ,EAAE,IAAI,CAAC;CAC1F;CACA,MAAM,UAAU,YAAY,KAC1B,SAAS,UAAU,QAAQ,OAAO,KAAK,GAAG,CAAC,CAAC,SAAS,IAAI,MAAM,MACjE;CACA,IAAI,QAAQ,SAAS,GAAG,KAAK,YAAY,OAAO;CAChD,IAAI,QAAQ,WAAW,GAAG,OAAO;CACjC,MAAM,SAAS,QAAQ,KAAK,MAAM,EAAE,EAAE;CAKtC,OAAO;EAAE,MAHP,GAAG,QAAQ,KAAK,MAAM,QAAQ,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC,GACjD,QAAQ,aAAa;GAAE,MAAM,KAAK;GAA8B,IAAI;EAAmB,CAAC,CAEjF;EAAK;EAAQ;CAAQ;AAChC"}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { WEASEL_CLIPBOARD_MIME, buildWeaselClipboardText } from "./wireFormat.js";
|
|
2
|
+
import { dwarn } from "@weasel-js/core";
|
|
3
|
+
|
|
4
|
+
// src/clipboard/osClipboard.ts
|
|
5
|
+
/** The kit's flavors for a copy: its own MIME, and `text/plain` carrying the same JSON. */
|
|
6
|
+
function defaultFlavors(items, replacer) {
|
|
7
|
+
const text = buildWeaselClipboardText(items, replacer);
|
|
8
|
+
return {
|
|
9
|
+
[WEASEL_CLIPBOARD_MIME]: text,
|
|
10
|
+
"text/plain": text
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
/** MIME types the async Clipboard API accepts unprefixed. Every other type
|
|
14
|
+
* (including our own custom MIME, and app-supplied flavors like
|
|
15
|
+
* `image/svg+xml`) must carry Chromium's `web ` prefix or `ClipboardItem`'s
|
|
16
|
+
* constructor throws. */
|
|
17
|
+
var WELL_KNOWN_CLIPBOARD_MIMES = /* @__PURE__ */ new Set([
|
|
18
|
+
"text/plain",
|
|
19
|
+
"text/html",
|
|
20
|
+
"image/png"
|
|
21
|
+
]);
|
|
22
|
+
/** Degradation ladder: full map (every non-well-known MIME web-prefixed) →
|
|
23
|
+
* the same minus any promised flavor that rejected → well-known-only → give
|
|
24
|
+
* up with a dwarn. Chromium writes nothing when one flavor rejects, so a
|
|
25
|
+
* rejection costs only that flavor, never the clipboard's previous content
|
|
26
|
+
* half-overwritten. */
|
|
27
|
+
async function writeOsClipboard(flavors) {
|
|
28
|
+
const entries = Object.entries(flavors);
|
|
29
|
+
if (entries.length === 0) return;
|
|
30
|
+
const rejected = /* @__PURE__ */ new Set();
|
|
31
|
+
for (const [mime, text] of entries) if (typeof text !== "string") text.catch(() => {
|
|
32
|
+
rejected.add(mime);
|
|
33
|
+
});
|
|
34
|
+
const cb = typeof navigator !== "undefined" ? navigator.clipboard : void 0;
|
|
35
|
+
if (!cb?.write || typeof ClipboardItem === "undefined") return;
|
|
36
|
+
const wireMime = (mime) => WELL_KNOWN_CLIPBOARD_MIMES.has(mime) ? mime : `web ${mime}`;
|
|
37
|
+
const toItem = (fs) => new ClipboardItem(Object.fromEntries(fs.map(([mime, text]) => {
|
|
38
|
+
const wire = wireMime(mime);
|
|
39
|
+
const blob = (t) => new Blob([t], { type: wire });
|
|
40
|
+
if (typeof text === "string") return [wire, blob(text)];
|
|
41
|
+
const promised = text.then(blob);
|
|
42
|
+
promised.catch(() => {});
|
|
43
|
+
return [wire, promised];
|
|
44
|
+
})));
|
|
45
|
+
const writeLive = async (fs) => {
|
|
46
|
+
let live = fs;
|
|
47
|
+
for (;;) try {
|
|
48
|
+
await cb.write([toItem(live)]);
|
|
49
|
+
return null;
|
|
50
|
+
} catch (err) {
|
|
51
|
+
const next = live.filter(([mime]) => !rejected.has(mime));
|
|
52
|
+
if (next.length === live.length || next.length === 0) return err;
|
|
53
|
+
live = next;
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
if (await writeLive(entries) === null) return;
|
|
57
|
+
const standard = entries.filter(([mime]) => WELL_KNOWN_CLIPBOARD_MIMES.has(mime) && !rejected.has(mime));
|
|
58
|
+
if (standard.length === 0) {
|
|
59
|
+
dwarn("clipboard", "OS write failed; no standard flavors to fall back to");
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
const err = await writeLive(standard);
|
|
63
|
+
if (err !== null) dwarn("clipboard", `OS clipboard write failed twice — copy stays in-memory only: ${String(err)}`);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export { defaultFlavors, writeOsClipboard };
|
|
67
|
+
//# sourceMappingURL=osClipboard.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"osClipboard.js","names":[],"sources":["../../src/clipboard/osClipboard.ts"],"sourcesContent":["import { dwarn } from '@weasel-js/core';\nimport { WEASEL_CLIPBOARD_MIME, buildWeaselClipboardText } from './wireFormat';\n\n/** MIME type to payload, as `produceFlavors` returns it. */\nexport type ClipboardFlavors = Record<string, string | Promise<string>>;\n\ntype Flavor = [mime: string, text: string | Promise<string>];\n\n/** The kit's flavors for a copy: its own MIME, and `text/plain` carrying the same JSON. */\nexport function defaultFlavors(items: readonly unknown[], replacer?: (key: string, value: unknown) => unknown): ClipboardFlavors {\n const text = buildWeaselClipboardText(items as unknown[], replacer);\n return { [WEASEL_CLIPBOARD_MIME]: text, 'text/plain': text };\n}\n\n/** MIME types the async Clipboard API accepts unprefixed. Every other type\n * (including our own custom MIME, and app-supplied flavors like\n * `image/svg+xml`) must carry Chromium's `web ` prefix or `ClipboardItem`'s\n * constructor throws. */\nconst WELL_KNOWN_CLIPBOARD_MIMES = new Set(['text/plain', 'text/html', 'image/png']);\n\n/** Degradation ladder: full map (every non-well-known MIME web-prefixed) →\n * the same minus any promised flavor that rejected → well-known-only → give\n * up with a dwarn. Chromium writes nothing when one flavor rejects, so a\n * rejection costs only that flavor, never the clipboard's previous content\n * half-overwritten. */\nexport async function writeOsClipboard(flavors: ClipboardFlavors): Promise<void> {\n const entries = Object.entries(flavors);\n if (entries.length === 0) return;\n const rejected = new Set<string>();\n for (const [mime, text] of entries) {\n if (typeof text !== 'string') text.catch(() => { rejected.add(mime); });\n }\n const cb = typeof navigator !== 'undefined' ? navigator.clipboard : undefined;\n if (!cb?.write || typeof ClipboardItem === 'undefined') return;\n const wireMime = (mime: string) => (WELL_KNOWN_CLIPBOARD_MIMES.has(mime) ? mime : `web ${mime}`);\n const toItem = (fs: Flavor[]) => new ClipboardItem(Object.fromEntries(\n fs.map(([mime, text]) => {\n const wire = wireMime(mime);\n const blob = (t: string) => new Blob([t], { type: wire });\n if (typeof text === 'string') return [wire, blob(text)];\n const promised = text.then(blob);\n // Chromium leaves a ClipboardItem's rejected promise unhandled.\n promised.catch(() => {});\n return [wire, promised];\n }),\n ));\n // Writes `fs`, dropping flavors whose promise rejected and retrying the\n // rest. Returns the last error, or null once a write lands.\n const writeLive = async (fs: Flavor[]): Promise<unknown> => {\n let live = fs;\n for (;;) {\n try {\n await cb.write([toItem(live)]);\n return null;\n } catch (err) {\n const next = live.filter(([mime]) => !rejected.has(mime));\n if (next.length === live.length || next.length === 0) return err;\n live = next;\n }\n }\n };\n if (await writeLive(entries) === null) return;\n const standard = entries.filter(([mime]) => WELL_KNOWN_CLIPBOARD_MIMES.has(mime) && !rejected.has(mime));\n if (standard.length === 0) { dwarn('clipboard', 'OS write failed; no standard flavors to fall back to'); return; }\n const err = await writeLive(standard);\n if (err !== null) dwarn('clipboard', `OS clipboard write failed twice — copy stays in-memory only: ${String(err)}`);\n}\n"],"mappings":";;;;;AASA,SAAgB,eAAe,OAA2B,UAAuE;CAC/H,MAAM,OAAO,yBAAyB,OAAoB,QAAQ;CAClE,OAAO;GAAG,wBAAwB;EAAM,cAAc;CAAK;AAC7D;;;;;AAMA,IAAM,6CAA6B,IAAI,IAAI;CAAC;CAAc;CAAa;AAAW,CAAC;;;;;;AAOnF,eAAsB,iBAAiB,SAA0C;CAC/E,MAAM,UAAU,OAAO,QAAQ,OAAO;CACtC,IAAI,QAAQ,WAAW,GAAG;CAC1B,MAAM,2BAAW,IAAI,IAAY;CACjC,KAAK,MAAM,CAAC,MAAM,SAAS,SACzB,IAAI,OAAO,SAAS,UAAU,KAAK,YAAY;EAAE,SAAS,IAAI,IAAI;CAAG,CAAC;CAExE,MAAM,KAAK,OAAO,cAAc,cAAc,UAAU,YAAY;CACpE,IAAI,CAAC,IAAI,SAAS,OAAO,kBAAkB,aAAa;CACxD,MAAM,YAAY,SAAkB,2BAA2B,IAAI,IAAI,IAAI,OAAO,OAAO;CACzF,MAAM,UAAU,OAAiB,IAAI,cAAc,OAAO,YACxD,GAAG,KAAK,CAAC,MAAM,UAAU;EACvB,MAAM,OAAO,SAAS,IAAI;EAC1B,MAAM,QAAQ,MAAc,IAAI,KAAK,CAAC,CAAC,GAAG,EAAE,MAAM,KAAK,CAAC;EACxD,IAAI,OAAO,SAAS,UAAU,OAAO,CAAC,MAAM,KAAK,IAAI,CAAC;EACtD,MAAM,WAAW,KAAK,KAAK,IAAI;EAE/B,SAAS,YAAY,CAAC,CAAC;EACvB,OAAO,CAAC,MAAM,QAAQ;CACxB,CAAC,CACH,CAAC;CAGD,MAAM,YAAY,OAAO,OAAmC;EAC1D,IAAI,OAAO;EACX,SACE,IAAI;GACF,MAAM,GAAG,MAAM,CAAC,OAAO,IAAI,CAAC,CAAC;GAC7B,OAAO;EACT,SAAS,KAAK;GACZ,MAAM,OAAO,KAAK,QAAQ,CAAC,UAAU,CAAC,SAAS,IAAI,IAAI,CAAC;GACxD,IAAI,KAAK,WAAW,KAAK,UAAU,KAAK,WAAW,GAAG,OAAO;GAC7D,OAAO;EACT;CAEJ;CACA,IAAI,MAAM,UAAU,OAAO,MAAM,MAAM;CACvC,MAAM,WAAW,QAAQ,QAAQ,CAAC,UAAU,2BAA2B,IAAI,IAAI,KAAK,CAAC,SAAS,IAAI,IAAI,CAAC;CACvG,IAAI,SAAS,WAAW,GAAG;EAAE,MAAM,aAAa,sDAAsD;EAAG;CAAQ;CACjH,MAAM,MAAM,MAAM,UAAU,QAAQ;CACpC,IAAI,QAAQ,MAAM,MAAM,aAAa,gEAAgE,OAAO,GAAG,GAAG;AACpH"}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { defaultFlavors, writeOsClipboard } from "./osClipboard.js";
|
|
2
|
+
import { dwarn } from "@weasel-js/core";
|
|
3
|
+
import { useCallback, useMemo, useRef } from "react";
|
|
4
|
+
import { useLatest } from "@weasel-js/react";
|
|
5
|
+
import { usePointerContext } from "@weasel-js/routing/react";
|
|
6
|
+
|
|
7
|
+
// src/clipboard/useClipboard.ts
|
|
8
|
+
/**
|
|
9
|
+
* Copy and paste over any document: an in-memory clipboard of what `copy` returns, written to the OS clipboard as
|
|
10
|
+
* well, and pasted through `paste`. The returned object is the `clipboard` dep's shape. `useClipboardOps` is this
|
|
11
|
+
* over an `InsertAdapter` and the scene's op history; an app whose own document owns its nodes passes its own
|
|
12
|
+
* functions, or uses `@weasel-js/editor`'s `useDocClipboard`, which adds the commands.
|
|
13
|
+
*/
|
|
14
|
+
function useClipboard(options) {
|
|
15
|
+
const pointerCtx = usePointerContext();
|
|
16
|
+
const opts = useLatest({
|
|
17
|
+
...options,
|
|
18
|
+
getDropPoint: options.getDropPoint ?? (pointerCtx ? () => pointerCtx.get()?.world ?? null : void 0)
|
|
19
|
+
});
|
|
20
|
+
const held = useRef([]);
|
|
21
|
+
const copy = useCallback(() => {
|
|
22
|
+
const o = opts.current;
|
|
23
|
+
const ids = o.getSelection();
|
|
24
|
+
if (ids.length === 0) return;
|
|
25
|
+
const items = o.copy(ids);
|
|
26
|
+
if (!items || items.length === 0) return;
|
|
27
|
+
held.current = items;
|
|
28
|
+
let flavors = null;
|
|
29
|
+
if (o.produceFlavors) try {
|
|
30
|
+
flavors = o.produceFlavors({ items });
|
|
31
|
+
} catch (err) {
|
|
32
|
+
console.error("weasel useClipboard: produceFlavors threw, so the OS clipboard was not written.", err);
|
|
33
|
+
}
|
|
34
|
+
else try {
|
|
35
|
+
flavors = defaultFlavors(items, o.jsonReplacer);
|
|
36
|
+
} catch (err) {
|
|
37
|
+
dwarn("clipboard", `default flavors threw — skipping OS write: ${String(err)}`);
|
|
38
|
+
}
|
|
39
|
+
if (flavors) writeOsClipboard(flavors);
|
|
40
|
+
}, [opts]);
|
|
41
|
+
const paste = useCallback((at) => {
|
|
42
|
+
const items = held.current;
|
|
43
|
+
if (items.length === 0) return;
|
|
44
|
+
const o = opts.current;
|
|
45
|
+
const dropPoint = at ?? o.getDropPoint?.() ?? void 0;
|
|
46
|
+
const pasted = o.paste(items, dropPoint ? { dropPoint } : {});
|
|
47
|
+
if (!pasted || pasted.ids.length === 0) return;
|
|
48
|
+
if (pasted.items.length > 0) held.current = pasted.items;
|
|
49
|
+
o.onPaste?.(pasted.ids);
|
|
50
|
+
}, [opts]);
|
|
51
|
+
const isEmpty = useCallback(() => held.current.length === 0, []);
|
|
52
|
+
return useMemo(() => ({
|
|
53
|
+
copy,
|
|
54
|
+
paste,
|
|
55
|
+
isEmpty
|
|
56
|
+
}), [
|
|
57
|
+
copy,
|
|
58
|
+
paste,
|
|
59
|
+
isEmpty
|
|
60
|
+
]);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export { useClipboard };
|
|
64
|
+
//# sourceMappingURL=useClipboard.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useClipboard.js","names":[],"sources":["../../src/clipboard/useClipboard.ts"],"sourcesContent":["import { useCallback, useMemo, useRef } from 'react';\nimport { useLatest } from '@weasel-js/react';\nimport type { WorldPoint } from '@weasel-js/routing';\nimport { usePointerContext } from '@weasel-js/routing/react';\nimport { dwarn } from '@weasel-js/core';\nimport type { ClipboardDep } from '@weasel-js/core/engine';\nimport { defaultFlavors, writeOsClipboard, type ClipboardFlavors } from './osClipboard';\n\n/** What a paste wrote: the new nodes' ids, and the copies the next paste of this clipboard starts from. */\nexport interface PastedItems<TItem> {\n ids: string[];\n /** Shaped like what `copy` returns. Pasting again pastes these, so a run of pastes steps on from the last one\n * instead of stacking on the first. */\n items: readonly TItem[];\n}\n\n/** Options for `useClipboard`. */\nexport interface UseClipboardOptions<TItem> {\n /** The ids Copy takes. */\n getSelection: () => readonly string[];\n /** The copyable form of `ids`, or `null` when they cannot be copied. */\n copy: (ids: readonly string[]) => readonly TItem[] | null;\n /** Write copies of `items` into the document, and say what was written, or `null` when nothing was.\n * `at.dropPoint` is where the paste was asked to land, when it was. */\n paste: (items: readonly TItem[], at: { dropPoint?: WorldPoint }) => PastedItems<TItem> | null;\n /** Called after a paste with the new ids. */\n onPaste?: (ids: string[]) => void;\n /** Where a paste with no point of its own lands. Defaults to the pointer, as `<SceneCanvas>` publishes it. */\n getDropPoint?: () => WorldPoint | null;\n /** The OS-clipboard flavors for a copy, by MIME type. Defaults to the kit's JSON flavor and `text/plain`\n * carrying the same JSON; `{}` writes nothing to the OS clipboard. A value may be a promise. Runs inside\n * `copy()`, so it reads the document as it stood at the copy. */\n produceFlavors?: (copied: { items: readonly TItem[] }) => ClipboardFlavors;\n /** Replacer for the default JSON flavor. Ignored when `produceFlavors` is given. */\n jsonReplacer?: (key: string, value: unknown) => unknown;\n}\n\n/**\n * Copy and paste over any document: an in-memory clipboard of what `copy` returns, written to the OS clipboard as\n * well, and pasted through `paste`. The returned object is the `clipboard` dep's shape. `useClipboardOps` is this\n * over an `InsertAdapter` and the scene's op history; an app whose own document owns its nodes passes its own\n * functions, or uses `@weasel-js/editor`'s `useDocClipboard`, which adds the commands.\n */\nexport function useClipboard<TItem>(options: UseClipboardOptions<TItem>): ClipboardDep {\n const pointerCtx = usePointerContext();\n const opts = useLatest({\n ...options,\n getDropPoint: options.getDropPoint ?? (pointerCtx ? () => pointerCtx.get()?.world ?? null : undefined),\n });\n const held = useRef<readonly TItem[]>([]);\n\n const copy = useCallback(() => {\n const o = opts.current;\n const ids = o.getSelection();\n if (ids.length === 0) return;\n const items = o.copy(ids);\n if (!items || items.length === 0) return;\n held.current = items;\n // The in-memory copy is already made; a producer that throws, or a browser with no clipboard API, costs only\n // the OS write.\n let flavors: ClipboardFlavors | null = null;\n if (o.produceFlavors) {\n try {\n flavors = o.produceFlavors({ items });\n } catch (err) {\n console.error('weasel useClipboard: produceFlavors threw, so the OS clipboard was not written.', err);\n }\n } else {\n try {\n flavors = defaultFlavors(items, o.jsonReplacer);\n } catch (err) {\n dwarn('clipboard', `default flavors threw — skipping OS write: ${String(err)}`);\n }\n }\n if (flavors) void writeOsClipboard(flavors);\n }, [opts]);\n\n const paste = useCallback((at?: WorldPoint) => {\n const items = held.current;\n if (items.length === 0) return;\n const o = opts.current;\n const dropPoint = at ?? o.getDropPoint?.() ?? undefined;\n const pasted = o.paste(items, dropPoint ? { dropPoint } : {});\n if (!pasted || pasted.ids.length === 0) return;\n if (pasted.items.length > 0) held.current = pasted.items;\n o.onPaste?.(pasted.ids);\n }, [opts]);\n\n const isEmpty = useCallback(() => held.current.length === 0, []);\n return useMemo(() => ({ copy, paste, isEmpty }), [copy, paste, isEmpty]);\n}\n"],"mappings":";;;;;;;;;;;;;AA2CA,SAAgB,aAAoB,SAAmD;CACrF,MAAM,aAAa,kBAAkB;CACrC,MAAM,OAAO,UAAU;EACrB,GAAG;EACH,cAAc,QAAQ,iBAAiB,mBAAmB,WAAW,IAAI,CAAC,EAAE,SAAS,OAAO;CAC9F,CAAC;CACD,MAAM,OAAO,OAAyB,CAAC,CAAC;CAExC,MAAM,OAAO,kBAAkB;EAC7B,MAAM,IAAI,KAAK;EACf,MAAM,MAAM,EAAE,aAAa;EAC3B,IAAI,IAAI,WAAW,GAAG;EACtB,MAAM,QAAQ,EAAE,KAAK,GAAG;EACxB,IAAI,CAAC,SAAS,MAAM,WAAW,GAAG;EAClC,KAAK,UAAU;EAGf,IAAI,UAAmC;EACvC,IAAI,EAAE,gBACJ,IAAI;GACF,UAAU,EAAE,eAAe,EAAE,MAAM,CAAC;EACtC,SAAS,KAAK;GACZ,QAAQ,MAAM,mFAAmF,GAAG;EACtG;OAEA,IAAI;GACF,UAAU,eAAe,OAAO,EAAE,YAAY;EAChD,SAAS,KAAK;GACZ,MAAM,aAAa,8CAA8C,OAAO,GAAG,GAAG;EAChF;EAEF,IAAI,SAAS,AAAK,iBAAiB,OAAO;CAC5C,GAAG,CAAC,IAAI,CAAC;CAET,MAAM,QAAQ,aAAa,OAAoB;EAC7C,MAAM,QAAQ,KAAK;EACnB,IAAI,MAAM,WAAW,GAAG;EACxB,MAAM,IAAI,KAAK;EACf,MAAM,YAAY,MAAM,EAAE,eAAe,KAAK;EAC9C,MAAM,SAAS,EAAE,MAAM,OAAO,YAAY,EAAE,UAAU,IAAI,CAAC,CAAC;EAC5D,IAAI,CAAC,UAAU,OAAO,IAAI,WAAW,GAAG;EACxC,IAAI,OAAO,MAAM,SAAS,GAAG,KAAK,UAAU,OAAO;EACnD,EAAE,UAAU,OAAO,GAAG;CACxB,GAAG,CAAC,IAAI,CAAC;CAET,MAAM,UAAU,kBAAkB,KAAK,QAAQ,WAAW,GAAG,CAAC,CAAC;CAC/D,OAAO,eAAe;EAAE;EAAM;EAAO;CAAQ,IAAI;EAAC;EAAM;EAAO;CAAO,CAAC;AACzE"}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { decodeSnapshot, dwarn, snapshotReplacer } from "@weasel-js/core";
|
|
2
|
+
|
|
3
|
+
// src/clipboard/wireFormat.ts
|
|
4
|
+
/** MIME type the kit writes its full-fidelity clipboard payload under, so a
|
|
5
|
+
* copy/paste between two weasel canvases round-trips scene nodes rather than
|
|
6
|
+
* the SVG or text flavors other apps read. */
|
|
7
|
+
var WEASEL_CLIPBOARD_MIME = "application/x-weasel-clipboard+json";
|
|
8
|
+
/** Chromium's async-clipboard spelling for custom formats. */
|
|
9
|
+
var WEASEL_CLIPBOARD_MIME_WEB = `web ${WEASEL_CLIPBOARD_MIME}`;
|
|
10
|
+
/** Serialize snapshot items into the versioned wire text.
|
|
11
|
+
*
|
|
12
|
+
* JSON drops a function-valued field (a container's `clipFromPose`, a
|
|
13
|
+
* node's `derivePath`). A scene adapter's snapshot also carries each one's
|
|
14
|
+
* `SceneRegistry` key (`clipFromPoseKey`, `derivePathKey`, …), which does
|
|
15
|
+
* cross, and its paste restores the function from the pasting scene's
|
|
16
|
+
* registry. A function that is not registered does not survive. Written with the snapshot codec unless
|
|
17
|
+
* `replacer` says otherwise, so typed arrays and non-finite numbers cross. */
|
|
18
|
+
function buildWeaselClipboardText(items, replacer = snapshotReplacer) {
|
|
19
|
+
return JSON.stringify({
|
|
20
|
+
weaselClipboard: 1,
|
|
21
|
+
nodes: items
|
|
22
|
+
}, replacer);
|
|
23
|
+
}
|
|
24
|
+
var isPayload = (parsed) => !!parsed && parsed.weaselClipboard === 1 && Array.isArray(parsed.nodes);
|
|
25
|
+
/** Cheap check: is this text a payload {@link parseWeaselClipboardText}
|
|
26
|
+
* accepts? Substring pre-check, then a guarded parse. */
|
|
27
|
+
function sniffWeaselClipboardText(text) {
|
|
28
|
+
if (!text.includes("\"weaselClipboard\"")) return false;
|
|
29
|
+
try {
|
|
30
|
+
return isPayload(JSON.parse(text));
|
|
31
|
+
} catch {
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
var SVG_OPEN_TAG = /<svg(?:\s[^>]*)?>/i;
|
|
36
|
+
/**
|
|
37
|
+
* Embed a weasel clipboard payload in an SVG document as a `<metadata>`
|
|
38
|
+
* child of the root — legal SVG 1.1, ignored by external tools — so one
|
|
39
|
+
* `text/plain` flavor serves both audiences.
|
|
40
|
+
*
|
|
41
|
+
* Intended for OUR serializer's output only (`serializeSvg` — single
|
|
42
|
+
* `<svg ...>` open tag, XML-escaped attributes). When no open tag is found
|
|
43
|
+
* the input is returned unchanged with a debug warning.
|
|
44
|
+
*/
|
|
45
|
+
function embedWeaselMetadataInSvg(svgText, payloadText) {
|
|
46
|
+
const open = SVG_OPEN_TAG.exec(svgText);
|
|
47
|
+
if (!open) {
|
|
48
|
+
dwarn("clipboard", "embedWeaselMetadataInSvg: no <svg ...> open tag found — returning input unchanged");
|
|
49
|
+
return svgText;
|
|
50
|
+
}
|
|
51
|
+
const cdata = `<![CDATA[${payloadText.replaceAll("]]>", "]]]]><![CDATA[>")}]]>`;
|
|
52
|
+
const at = open.index + open[0].length;
|
|
53
|
+
return `${svgText.slice(0, at)}<metadata>${cdata}</metadata>${svgText.slice(at)}`;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* The weasel clipboard payload embedded in SVG text by
|
|
57
|
+
* {@link embedWeaselMetadataInSvg}, or null when the first `<metadata>` block
|
|
58
|
+
* is absent or not the weasel wire format. A text scan, not an XML parse.
|
|
59
|
+
*/
|
|
60
|
+
function extractWeaselClipboardFromSvg(svgText) {
|
|
61
|
+
const open = /<metadata(?:\s[^>]*)?>/i.exec(svgText);
|
|
62
|
+
if (!open) return null;
|
|
63
|
+
const sections = [];
|
|
64
|
+
let plain = "";
|
|
65
|
+
let at = open.index + open[0].length;
|
|
66
|
+
for (;;) {
|
|
67
|
+
const cdata = svgText.indexOf("<![CDATA[", at);
|
|
68
|
+
const close = svgText.slice(at).search(/<\/metadata>/i);
|
|
69
|
+
if (close < 0) return null;
|
|
70
|
+
if (cdata < 0 || cdata > at + close) {
|
|
71
|
+
plain += svgText.slice(at, at + close);
|
|
72
|
+
break;
|
|
73
|
+
}
|
|
74
|
+
const end = svgText.indexOf("]]>", cdata + 9);
|
|
75
|
+
if (end < 0) return null;
|
|
76
|
+
plain += svgText.slice(at, cdata);
|
|
77
|
+
sections.push(svgText.slice(cdata + 9, end));
|
|
78
|
+
at = end + 3;
|
|
79
|
+
}
|
|
80
|
+
const payload = sections.length > 0 ? sections.join("") : plain;
|
|
81
|
+
return sniffWeaselClipboardText(payload) ? payload : null;
|
|
82
|
+
}
|
|
83
|
+
/** Parse wire text to snapshot items, or null when malformed/mismatched
|
|
84
|
+
* (callers decline to the next content handler). Decoded with the snapshot codec unless `reviver` says otherwise;
|
|
85
|
+
* a `reviver` that throws declines too, logged with `console.error`. */
|
|
86
|
+
function parseWeaselClipboardText(text, reviver) {
|
|
87
|
+
let reviverThrew = false;
|
|
88
|
+
const revive = reviver && ((key, value) => {
|
|
89
|
+
try {
|
|
90
|
+
return reviver(key, value);
|
|
91
|
+
} catch (err) {
|
|
92
|
+
reviverThrew = true;
|
|
93
|
+
throw err;
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
try {
|
|
97
|
+
const parsed = JSON.parse(text, revive);
|
|
98
|
+
if (!isPayload(parsed)) return null;
|
|
99
|
+
return reviver ? parsed.nodes : decodeSnapshot(parsed.nodes);
|
|
100
|
+
} catch (err) {
|
|
101
|
+
if (reviverThrew) console.error("weasel clipboard: the paste reviver threw, so the paste was declined.", err);
|
|
102
|
+
else dwarn("clipboard", `weasel payload failed to parse: ${String(err)}`);
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export { WEASEL_CLIPBOARD_MIME, WEASEL_CLIPBOARD_MIME_WEB, buildWeaselClipboardText, embedWeaselMetadataInSvg, extractWeaselClipboardFromSvg, parseWeaselClipboardText, sniffWeaselClipboardText };
|
|
108
|
+
//# sourceMappingURL=wireFormat.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"wireFormat.js","names":[],"sources":["../../src/clipboard/wireFormat.ts"],"sourcesContent":["import { decodeSnapshot, snapshotReplacer, dwarn } from '@weasel-js/core';\n\n/** MIME type the kit writes its full-fidelity clipboard payload under, so a\n * copy/paste between two weasel canvases round-trips scene nodes rather than\n * the SVG or text flavors other apps read. */\nexport const WEASEL_CLIPBOARD_MIME = 'application/x-weasel-clipboard+json';\n/** Chromium's async-clipboard spelling for custom formats. */\nexport const WEASEL_CLIPBOARD_MIME_WEB = `web ${WEASEL_CLIPBOARD_MIME}`;\n\ninterface WeaselClipboardPayload { weaselClipboard: 1; nodes: unknown[] }\n\n/** Serialize snapshot items into the versioned wire text.\n *\n * JSON drops a function-valued field (a container's `clipFromPose`, a\n * node's `derivePath`). A scene adapter's snapshot also carries each one's\n * `SceneRegistry` key (`clipFromPoseKey`, `derivePathKey`, …), which does\n * cross, and its paste restores the function from the pasting scene's\n * registry. A function that is not registered does not survive. Written with the snapshot codec unless\n * `replacer` says otherwise, so typed arrays and non-finite numbers cross. */\nexport function buildWeaselClipboardText(\n items: unknown[],\n replacer: (key: string, value: unknown) => unknown = snapshotReplacer,\n): string {\n const payload: WeaselClipboardPayload = { weaselClipboard: 1, nodes: items };\n return JSON.stringify(payload, replacer);\n}\n\nconst isPayload = (parsed: Partial<WeaselClipboardPayload> | null): parsed is WeaselClipboardPayload =>\n !!parsed && parsed.weaselClipboard === 1 && Array.isArray(parsed.nodes);\n\n/** Cheap check: is this text a payload {@link parseWeaselClipboardText}\n * accepts? Substring pre-check, then a guarded parse. */\nexport function sniffWeaselClipboardText(text: string): boolean {\n if (!text.includes('\"weaselClipboard\"')) return false;\n try {\n return isPayload(JSON.parse(text) as Partial<WeaselClipboardPayload> | null);\n } catch {\n return false;\n }\n}\n\n// `[^>]*` is safe for OUR serializer's output only: attribute values are\n// XML-escaped, so no raw `>` can appear inside the tag.\nconst SVG_OPEN_TAG = /<svg(?:\\s[^>]*)?>/i;\n\n/**\n * Embed a weasel clipboard payload in an SVG document as a `<metadata>`\n * child of the root — legal SVG 1.1, ignored by external tools — so one\n * `text/plain` flavor serves both audiences.\n *\n * Intended for OUR serializer's output only (`serializeSvg` — single\n * `<svg ...>` open tag, XML-escaped attributes). When no open tag is found\n * the input is returned unchanged with a debug warning.\n */\nexport function embedWeaselMetadataInSvg(svgText: string, payloadText: string): string {\n const open = SVG_OPEN_TAG.exec(svgText);\n if (!open) {\n dwarn('clipboard', 'embedWeaselMetadataInSvg: no <svg ...> open tag found — returning input unchanged');\n return svgText;\n }\n const cdata = `<![CDATA[${payloadText.replaceAll(']]>', ']]]]><![CDATA[>')}]]>`;\n const at = open.index + open[0].length;\n return `${svgText.slice(0, at)}<metadata>${cdata}</metadata>${svgText.slice(at)}`;\n}\n\n/**\n * The weasel clipboard payload embedded in SVG text by\n * {@link embedWeaselMetadataInSvg}, or null when the first `<metadata>` block\n * is absent or not the weasel wire format. A text scan, not an XML parse.\n */\nexport function extractWeaselClipboardFromSvg(svgText: string): string | null {\n const open = /<metadata(?:\\s[^>]*)?>/i.exec(svgText);\n if (!open) return null;\n // CDATA sections are read whole before looking for the close, so a payload holding `</metadata>` survives.\n const sections: string[] = [];\n let plain = '';\n let at = open.index + open[0].length;\n for (;;) {\n const cdata = svgText.indexOf('<![CDATA[', at);\n const close = svgText.slice(at).search(/<\\/metadata>/i);\n if (close < 0) return null;\n if (cdata < 0 || cdata > at + close) {\n plain += svgText.slice(at, at + close);\n break;\n }\n const end = svgText.indexOf(']]>', cdata + 9);\n if (end < 0) return null;\n plain += svgText.slice(at, cdata);\n sections.push(svgText.slice(cdata + 9, end));\n at = end + 3;\n }\n const payload = sections.length > 0 ? sections.join('') : plain;\n return sniffWeaselClipboardText(payload) ? payload : null;\n}\n\n/** Parse wire text to snapshot items, or null when malformed/mismatched\n * (callers decline to the next content handler). Decoded with the snapshot codec unless `reviver` says otherwise;\n * a `reviver` that throws declines too, logged with `console.error`. */\nexport function parseWeaselClipboardText(text: string, reviver?: (key: string, value: unknown) => unknown): unknown[] | null {\n let reviverThrew = false;\n const revive = reviver && ((key: string, value: unknown): unknown => {\n try {\n return reviver(key, value);\n } catch (err) {\n reviverThrew = true;\n throw err;\n }\n });\n try {\n const parsed = JSON.parse(text, revive as Parameters<typeof JSON.parse>[1]) as\n Partial<WeaselClipboardPayload> | null;\n if (!isPayload(parsed)) return null;\n return reviver ? parsed.nodes : (decodeSnapshot(parsed.nodes) as unknown[]);\n } catch (err) {\n if (reviverThrew) console.error('weasel clipboard: the paste reviver threw, so the paste was declined.', err);\n else dwarn('clipboard', `weasel payload failed to parse: ${String(err)}`);\n return null;\n }\n}\n"],"mappings":";;;;;;AAKA,IAAa,wBAAwB;;AAErC,IAAa,4BAA4B,OAAO;;;;;;;;;AAYhD,SAAgB,yBACd,OACA,WAAqD,kBAC7C;CAER,OAAO,KAAK,UAAU;EADoB,iBAAiB;EAAG,OAAO;CAC/C,GAAS,QAAQ;AACzC;AAEA,IAAM,aAAa,WACjB,CAAC,CAAC,UAAU,OAAO,oBAAoB,KAAK,MAAM,QAAQ,OAAO,KAAK;;;AAIxE,SAAgB,yBAAyB,MAAuB;CAC9D,IAAI,CAAC,KAAK,SAAS,qBAAmB,GAAG,OAAO;CAChD,IAAI;EACF,OAAO,UAAU,KAAK,MAAM,IAAI,CAA2C;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S,aAAa,KAAa,UAA4B;EACnE,IAAI;GACF,OAAO,QAAQ,KAAK,KAAK;EAC3B,SAAS,KAAK;GACZ,eAAe;GACf,MAAM;EACR;CACF;CACA,IAAI;EACF,MAAM,SAAS,KAAK,MAAM,MAAM,MAA0C;EAE1E,IAAI,CAAC,UAAU,MAAM,GAAG,OAAO;EAC/B,OAAO,UAAU,OAAO,QAAS,eAAe,OAAO,KAAK;CAC9D,SAAS,KAAK;EACZ,IAAI,cAAc,QAAQ,MAAM,yEAAyE,GAAG;OACvG,MAAM,aAAa,mCAAmC,OAAO,GAAG,GAAG;EACxE,OAAO;CACT;AACF"}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { hitTestRect, regionPickOptions } from "@weasel-js/core";
|
|
2
|
+
import { useLatest } from "@weasel-js/react";
|
|
3
|
+
import { useDepSource } from "@weasel-js/routing/react";
|
|
4
|
+
|
|
5
|
+
// src/deps/areaSelect.ts
|
|
6
|
+
/**
|
|
7
|
+
* `useAreaSelectDepSource` — wires the `areaSelect` dep consumed by
|
|
8
|
+
* `areaSelectAction`. The dep exposes:
|
|
9
|
+
* - `hitTestArea(bounds)` — silhouette-aware scan over `scene.renderOrderNodes()`
|
|
10
|
+
* (rect poses by AABB; polygon poses by the kernel polygon-overlap test).
|
|
11
|
+
* - `getSelection` / `setSelection` — passthrough to the kit selection api.
|
|
12
|
+
*
|
|
13
|
+
* Built once per render and stabilised by `useDepSource` (which reads via a
|
|
14
|
+
* ref internally), so callers can pass fresh selection/scene refs without
|
|
15
|
+
* triggering re-registration.
|
|
16
|
+
*/
|
|
17
|
+
function useAreaSelectDepSource(scene, selection, descriptor, alphaOf, reachable, targetOf) {
|
|
18
|
+
const sceneRef = useLatest(scene);
|
|
19
|
+
const selectionRef = useLatest(selection);
|
|
20
|
+
const descriptorRef = useLatest(descriptor);
|
|
21
|
+
const alphaOfRef = useLatest(alphaOf);
|
|
22
|
+
const reachableRef = useLatest(reachable);
|
|
23
|
+
const targetOfRef = useLatest(targetOf);
|
|
24
|
+
useDepSource("areaSelect", () => {
|
|
25
|
+
const sc = sceneRef.current;
|
|
26
|
+
const s = selectionRef.current;
|
|
27
|
+
const d = descriptorRef.current;
|
|
28
|
+
const a = alphaOfRef.current;
|
|
29
|
+
const r = reachableRef.current;
|
|
30
|
+
const t = targetOfRef.current;
|
|
31
|
+
const keep = (ids) => r ? ids.filter((id) => r(id)) : ids;
|
|
32
|
+
return {
|
|
33
|
+
hitTestArea: (bounds, view) => keep(hitTestRect(sc, bounds, regionPickOptions(view, a), d)),
|
|
34
|
+
...t ? { targetOf: t } : {},
|
|
35
|
+
getSelection: () => s.current,
|
|
36
|
+
setSelection: (ids) => s.set(ids)
|
|
37
|
+
};
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export { useAreaSelectDepSource };
|
|
42
|
+
//# sourceMappingURL=areaSelect.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"areaSelect.js","names":[],"sources":["../../src/deps/areaSelect.ts"],"sourcesContent":["/**\n * `useAreaSelectDepSource` — wires the `areaSelect` dep consumed by\n * `areaSelectAction`. The dep exposes:\n * - `hitTestArea(bounds)` — silhouette-aware scan over `scene.renderOrderNodes()`\n * (rect poses by AABB; polygon poses by the kernel polygon-overlap test).\n * - `getSelection` / `setSelection` — passthrough to the kit selection api.\n *\n * Built once per render and stabilised by `useDepSource` (which reads via a\n * ref internally), so callers can pass fresh selection/scene refs without\n * triggering re-registration.\n */\nimport { useDepSource } from '@weasel-js/routing/react';\nimport { useLatest } from '@weasel-js/react';\nimport type { AreaSelectDep, PoseDescriptor } from '@weasel-js/core/engine';\nimport type { Scene, NodeId } from '@weasel-js/core';\nimport type { SelectionApi } from '@weasel-js/routing';\nimport { hitTestRect, regionPickOptions } from '@weasel-js/core';\n\nexport function useAreaSelectDepSource(\n scene: Scene<unknown, string, unknown>,\n selection: SelectionApi,\n descriptor?: PoseDescriptor<unknown>,\n /** The painted alpha the surface's layers apply, which every view shares. */\n alphaOf?: (id: string) => number,\n /** Whether a node can be reached at all: the canvas's one answer, which picking reads too. */\n reachable?: (id: string) => boolean,\n /** The node selecting a hit selects, as a click picks. */\n targetOf?: (id: string) => string,\n): void {\n const sceneRef = useLatest(scene);\n const selectionRef = useLatest(selection);\n const descriptorRef = useLatest(descriptor);\n const alphaOfRef = useLatest(alphaOf);\n const reachableRef = useLatest(reachable);\n const targetOfRef = useLatest(targetOf);\n\n useDepSource('areaSelect', (): AreaSelectDep => {\n const sc = sceneRef.current;\n const s = selectionRef.current;\n const d = descriptorRef.current;\n const a = alphaOfRef.current;\n const r = reachableRef.current;\n const t = targetOfRef.current;\n const keep = (ids: NodeId[]): NodeId[] => (r ? ids.filter((id) => r(id)) : ids);\n return {\n hitTestArea: (bounds, view) =>\n keep(hitTestRect(sc, bounds, regionPickOptions(view, a), d)),\n ...(t ? { targetOf: t } : {}),\n getSelection: () => s.current as NodeId[],\n setSelection: (ids) => s.set(ids),\n };\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkBA,SAAgB,uBACd,OACA,WACA,YAEA,SAEA,WAEA,UACM;CACN,MAAM,WAAW,UAAU,KAAK;CAChC,MAAM,eAAe,UAAU,SAAS;CACxC,MAAM,gBAAgB,UAAU,UAAU;CAC1C,MAAM,aAAa,UAAU,OAAO;CACpC,MAAM,eAAe,UAAU,SAAS;CACxC,MAAM,cAAc,UAAU,QAAQ;CAEtC,aAAa,oBAAmC;EAC9C,MAAM,KAAK,SAAS;EACpB,MAAM,IAAI,aAAa;EACvB,MAAM,IAAI,cAAc;EACxB,MAAM,IAAI,WAAW;EACrB,MAAM,IAAI,aAAa;EACvB,MAAM,IAAI,YAAY;EACtB,MAAM,QAAQ,QAA6B,IAAI,IAAI,QAAQ,OAAO,EAAE,EAAE,CAAC,IAAI;EAC3E,OAAO;GACL,cAAc,QAAQ,SACpB,KAAK,YAAY,IAAI,QAAQ,kBAAkB,MAAM,CAAC,GAAG,CAAC,CAAC;GAC7D,GAAI,IAAI,EAAE,UAAU,EAAE,IAAI,CAAC;GAC3B,oBAAoB,EAAE;GACtB,eAAe,QAAQ,EAAE,IAAI,GAAG;EAClC;CACF,CAAC;AACH"}
|