@weasel-js/core 1.8.1 → 1.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/README.md +9 -5
  3. package/dist/{builtins-CMEh6-Oc.d.ts → builtins-CQcvcLXh.d.ts} +98 -31
  4. package/dist/canvas/DrawCanvas.js +33 -33
  5. package/dist/canvas/DrawCanvas.js.map +1 -1
  6. package/dist/canvas/MinimapCanvas.js +29 -29
  7. package/dist/canvas/MinimapCanvas.js.map +1 -1
  8. package/dist/canvas/NodeShape.js +63 -54
  9. package/dist/canvas/NodeShape.js.map +1 -1
  10. package/dist/canvas/SceneCanvas/features.js +26 -5
  11. package/dist/canvas/SceneCanvas/features.js.map +1 -1
  12. package/dist/canvas/SceneCanvas/useSceneSelectTool.js +3 -2
  13. package/dist/canvas/SceneCanvas/useSceneSelectTool.js.map +1 -1
  14. package/dist/canvas/SceneCanvas.js +526 -529
  15. package/dist/canvas/SceneCanvas.js.map +1 -1
  16. package/dist/canvas/SceneViewCanvas.js +35 -35
  17. package/dist/canvas/SceneViewCanvas.js.map +1 -1
  18. package/dist/canvas/defaultDrawOne.js +6 -1
  19. package/dist/canvas/defaultDrawOne.js.map +1 -1
  20. package/dist/canvas/pickWalk.js.map +1 -1
  21. package/dist/canvas/sceneAdapter.js.map +1 -1
  22. package/dist/canvas/useHitObserver.js +23 -0
  23. package/dist/canvas/useHitObserver.js.map +1 -0
  24. package/dist/canvas/useHostAnchor.js.map +1 -1
  25. package/dist/core/device/useDeviceProfile.js.map +1 -1
  26. package/dist/core/scene/derivedPath.js.map +1 -1
  27. package/dist/core/scene/effectivePose.js.map +1 -1
  28. package/dist/core/scene/kitRegistry.js.map +1 -1
  29. package/dist/core/scene/scene.js.map +1 -1
  30. package/dist/core/scene/types.js.map +1 -1
  31. package/dist/core/scene/useScene.js.map +1 -1
  32. package/dist/core/viewport/fitViewToBounds.js +3 -3
  33. package/dist/core/viewport/fitViewToBounds.js.map +1 -1
  34. package/dist/core/viewport/screenSlop.js +8 -2
  35. package/dist/core/viewport/screenSlop.js.map +1 -1
  36. package/dist/features/minimap/actions.js.map +1 -1
  37. package/dist/features/paths/markerCommands.js +95 -63
  38. package/dist/features/paths/markerCommands.js.map +1 -1
  39. package/dist/features/paths/tessellate/dash.js +52 -0
  40. package/dist/features/paths/tessellate/dash.js.map +1 -0
  41. package/dist/features/paths/tessellate/insets.js +32 -0
  42. package/dist/features/paths/tessellate/insets.js.map +1 -0
  43. package/dist/features/paths/tessellate/metric.js +72 -0
  44. package/dist/features/paths/tessellate/metric.js.map +1 -0
  45. package/dist/features/paths/tessellate/stroke.js +74 -134
  46. package/dist/features/paths/tessellate/stroke.js.map +1 -1
  47. package/dist/features/paths/tessellate/vertexWidths.js +32 -0
  48. package/dist/features/paths/tessellate/vertexWidths.js.map +1 -0
  49. package/dist/features/pointer/PointerContext.js +2 -2
  50. package/dist/features/pointer/PointerContext.js.map +1 -1
  51. package/dist/features/poseRun/usePoseRun.js.map +1 -1
  52. package/dist/features/text/useTextEdit.js +86 -84
  53. package/dist/features/text/useTextEdit.js.map +1 -1
  54. package/dist/index.d.ts +78 -39
  55. package/dist/index.js +148 -148
  56. package/dist/interactions/actions/defaults/align.js.map +1 -1
  57. package/dist/interactions/actions/defaults/anchorEditing.js.map +1 -1
  58. package/dist/interactions/actions/defaults/areaSelect.js.map +1 -1
  59. package/dist/interactions/actions/defaults/booleans.js.map +1 -1
  60. package/dist/interactions/actions/defaults/cancelGesture.js.map +1 -1
  61. package/dist/interactions/actions/defaults/clearSelection.js.map +1 -1
  62. package/dist/interactions/actions/defaults/clipboard.js.map +1 -1
  63. package/dist/interactions/actions/defaults/clone.js.map +1 -1
  64. package/dist/interactions/actions/defaults/createOutlines.js +1 -1
  65. package/dist/interactions/actions/defaults/createOutlines.js.map +1 -1
  66. package/dist/interactions/actions/defaults/createPaintAction.js.map +1 -1
  67. package/dist/interactions/actions/defaults/delete.js.map +1 -1
  68. package/dist/interactions/actions/defaults/distribute.js.map +1 -1
  69. package/dist/interactions/actions/defaults/duplicate.js.map +1 -1
  70. package/dist/interactions/actions/defaults/editAnchors.js.map +1 -1
  71. package/dist/interactions/actions/defaults/enterPathEdit.js.map +1 -1
  72. package/dist/interactions/actions/defaults/enterTextEdit.js.map +1 -1
  73. package/dist/interactions/actions/defaults/escape.js +1 -1
  74. package/dist/interactions/actions/defaults/escape.js.map +1 -1
  75. package/dist/interactions/actions/defaults/exitPathEdit.js.map +1 -1
  76. package/dist/interactions/actions/defaults/flip.js.map +1 -1
  77. package/dist/interactions/actions/defaults/group.js.map +1 -1
  78. package/dist/interactions/actions/defaults/ingest.js.map +1 -1
  79. package/dist/interactions/actions/defaults/insert.js.map +1 -1
  80. package/dist/interactions/actions/defaults/insertPathAnchor.js +1 -1
  81. package/dist/interactions/actions/defaults/insertPathAnchor.js.map +1 -1
  82. package/dist/interactions/actions/defaults/lassoSelect.js.map +1 -1
  83. package/dist/interactions/actions/defaults/move.js.map +1 -1
  84. package/dist/interactions/actions/defaults/nudge.js.map +1 -1
  85. package/dist/interactions/actions/defaults/pinchZoom.js.map +1 -1
  86. package/dist/interactions/actions/defaults/reorder.js.map +1 -1
  87. package/dist/interactions/actions/defaults/requiresSelection.js.map +1 -1
  88. package/dist/interactions/actions/defaults/resize.js.map +1 -1
  89. package/dist/interactions/actions/defaults/rotate.js.map +1 -1
  90. package/dist/interactions/actions/defaults/selectAll.js.map +1 -1
  91. package/dist/interactions/actions/defaults/slice.js.map +1 -1
  92. package/dist/interactions/actions/defaults/toolActivate.js.map +1 -1
  93. package/dist/interactions/actions/defaults/toolResetToDefault.js.map +1 -1
  94. package/dist/interactions/actions/defaults/undoRedo.js +1 -1
  95. package/dist/interactions/actions/defaults/undoRedo.js.map +1 -1
  96. package/dist/interactions/actions/defaults/viewportDragPan.js.map +1 -1
  97. package/dist/interactions/actions/defaults/viewportWheelPan.js.map +1 -1
  98. package/dist/interactions/actions/defaults/viewportZoom.js.map +1 -1
  99. package/dist/interactions/actions/planeInput.js.map +1 -1
  100. package/dist/interactions/gestures/shared/screenTolerance.js.map +1 -1
  101. package/dist/{registerProgram-ateHDGjw.d.ts → registerProgram-BMZRDgrh.d.ts} +4 -0
  102. package/dist/renderer/cache/markerCommandCache.js +46 -42
  103. package/dist/renderer/cache/markerCommandCache.js.map +1 -1
  104. package/dist/renderer/cache/outlineStrokeMeshCache.js +30 -25
  105. package/dist/renderer/cache/outlineStrokeMeshCache.js.map +1 -1
  106. package/dist/renderer/cache/strokeMeshCache.js +42 -31
  107. package/dist/renderer/cache/strokeMeshCache.js.map +1 -1
  108. package/dist/renderer/cullDrawCommands.js +32 -31
  109. package/dist/renderer/cullDrawCommands.js.map +1 -1
  110. package/dist/renderer/draw.js +315 -362
  111. package/dist/renderer/draw.js.map +1 -1
  112. package/dist/renderer/glyphOutlineMesh.js +67 -0
  113. package/dist/renderer/glyphOutlineMesh.js.map +1 -0
  114. package/dist/renderer/math/mat3.js +8 -3
  115. package/dist/renderer/math/mat3.js.map +1 -1
  116. package/dist/renderer/strokeLengths.js +50 -0
  117. package/dist/renderer/strokeLengths.js.map +1 -0
  118. package/dist/renderer.d.ts +2 -2
  119. package/dist/{test-seams-fYf6m5pu.d.ts → test-seams-CuIxe0xY.d.ts} +1 -1
  120. package/dist/test-seams.d.ts +2 -2
  121. package/dist/tools/builtin/eyedropper/useEyedropperTool.js.map +1 -1
  122. package/dist/tools/builtin/pen/usePenTool.js +1 -1
  123. package/dist/tools/builtin/pen/usePenTool.js.map +1 -1
  124. package/dist/tools/builtin/select/selectionContributions.js +43 -23
  125. package/dist/tools/builtin/select/selectionContributions.js.map +1 -1
  126. package/dist/tools/builtin/select/useSelectTool.js.map +1 -1
  127. package/dist/tools/builtin/slice/useSliceTool.js.map +1 -1
  128. package/dist/version.js +1 -1
  129. package/package.json +17 -17
@@ -1 +1 @@
1
- {"version":3,"file":"viewportDragPan.js","names":["screenDeltaFromWorld","v0","scratch","now","drag","viewportDragPanAction","view","ctx","startView","params","resolveParams","opts","inertia","createVelocityTracker","debug","grab","moveCtx","screen","screenDx","screenDy","sv","next","v","reason","tracker","scale","vx","vy","cur","dx","dy"],"sources":["../../../../src/interactions/actions/defaults/viewportDragPan.ts"],"sourcesContent":["/**\n * `viewportDragPanAction` — ongoing Action descriptor for drag-to-pan the viewport.\n *\n * ## Bindings\n * None of its own. The hand tool binds a drag to it, and a canvas that pans on\n * any unclaimed drag adds `dragPanContribution`.\n *\n * ## Design notes\n * The drag delta from the dispatcher is in screen space (pixels). The pan\n * formula converts screen pixels to world units by dividing by zoom:\n *\n * newView.x = startView.x - screenDx / startView.scale.x\n * newView.y = startView.y - screenDy / startView.scale.y\n *\n * where `screenDx` / `screenDy` are the screen-space pixel deltas from the\n * drag origin. This ensures that at any zoom level, the drag behavior is\n * consistent: 1 screen pixel always pans the same amount relative to the\n * viewport's zoom (e.g., at 1x zoom: 100px → 100 world units; at 2x zoom:\n * 100px → 50 world units). The camera moves opposite to the drag direction\n * so that the scene content appears to follow the pointer.\n *\n * The descriptor captures `startView` in its own scratch at `start` time,\n * parallel to `useHandTool`'s `startView` capture in its scratch object.\n *\n * ## Axis locking and inertia\n * Both are read from the binding's `params` at `start`, so any consumer\n * binding this action gets them — not just `useHandTool`. `axis` drops one\n * component of every pan delta. `inertia` coasts the view after release,\n * through the optional `view.decay` dep; with no such dep wired the pan\n * simply lands, which is what an unconfigured consumer already expects.\n *\n * @see useHandTool — the React hook this descriptor parallels.\n */\n\nimport type { Action, DebugSink } from '@weasel-js/routing';\nimport { resolveParams, type InvocationCtx, type OngoingHandle, type BindingOpts } from '@weasel-js/routing';\nimport type { View } from 'core/viewport/view';\nimport type { ViewApi } from '../depSchema';\nimport type { InertiaConfig } from 'core/viewport/useDecayLoop';\nimport { createVelocityTracker, type VelocityTracker } from 'core/viewport/createVelocityTracker';\n\n// ---------------------------------------------------------------------------\n// Internal scratch\n// ---------------------------------------------------------------------------\n\ninterface DragPanScratch {\n startView: View;\n view: ViewApi;\n axis: 'both' | 'x' | 'y';\n inertia: InertiaConfig | undefined;\n tracker: VelocityTracker | undefined;\n lastScreen: { x: number; y: number };\n}\n\n/**\n * Rebuild the client-pixel drag delta from the world one, for an event source\n * that supplied no `clientX`/`clientY`.\n *\n * A world delta is self-referential mid-pan — its two ends were measured under\n * different views — so it cannot simply be scaled. Undoing each end against the\n * view that produced it recovers the client delta exactly, since\n * `world = (client - origin) / scale + view` and neither the canvas origin nor\n * the scale moves during a pan.\n */\nfunction screenDeltaFromWorld(\n drag: NonNullable<InvocationCtx['drag']>,\n scratch: DragPanScratch,\n): { x: number; y: number } {\n const v0 = scratch.startView;\n const now = scratch.view.get();\n return {\n x: (drag.current.x - now.x - (drag.start.x - v0.x)) * v0.scale.x,\n y: (drag.current.y - now.y - (drag.start.y - v0.y)) * v0.scale.y,\n };\n}\n\n/** Binding params `viewport.dragPan` understands. `useHandTool` supplies both;\n * a bare binding supplies neither and pans both axes with no coasting. */\nexport interface DragPanParams {\n axis?: 'both' | 'x' | 'y';\n inertia?: false | InertiaConfig;\n}\n\n// ---------------------------------------------------------------------------\n// Descriptor\n// ---------------------------------------------------------------------------\n\n/**\n * @experimental\n * Static descriptor for the `viewport.dragPan` Action.\n *\n * Requires dep-schema entry: `view`.\n *\n * Translates the viewport by the screen-space drag delta so the canvas content\n * follows the pointer. Produces no scene ops — view changes are not undoable.\n */\n// No `eligible` field → viewport pan is always eligible across all modes.\nexport const viewportDragPanAction: Action & { requires: string[] } = {\n id: 'viewport.dragPan',\n label: 'Drag to pan viewport',\n group: 'viewport',\n // Hover hint: when this action would win the drag at the hovered point\n // (e.g. empty canvas with no marquee-capable tool ahead of it), the\n // hover-cursor pump shows the open hand.\n cursor: 'grab',\n // ...and the closed hand once the pan is actually running. This was\n // `useHandTool`'s `engaged: { cursor: 'grabbing' }` — a phase-table entry\n // on a tool, which meant a consumer who bound `viewport.dragPan` without\n // the hand tool got no state cursor at all.\n activeCursor: 'grabbing',\n requires: ['view', 'debug'],\n invoker: {\n timing: 'ongoing',\n start(ctx: InvocationCtx, opts?: BindingOpts): OngoingHandle {\n const view = ctx.deps.view as ViewApi | undefined;\n if (!view) return {};\n\n const startView = view.get();\n // Gesture-driven ongoing actions never see `ctx.params` — the dispatcher\n // hands the binding's unresolved `opts` here and nowhere else, and pumps\n // `onMove` / `onEnd` with an empty deps bag. Everything the gesture needs\n // has to be captured now.\n const params = (resolveParams(opts?.params) ?? {}) as DragPanParams;\n const inertia = params.inertia === false ? undefined : params.inertia;\n const scratch: DragPanScratch = {\n startView,\n view,\n axis: params.axis ?? 'both',\n inertia,\n // Only track when a coast could actually happen, so the common\n // no-inertia drag does no per-move work.\n tracker: inertia && view.decay ? createVelocityTracker() : undefined,\n lastScreen: { x: 0, y: 0 },\n };\n const debug = ctx.deps.debug as DebugSink | undefined;\n const grab = ctx.drag?.start;\n\n return {\n kind: 'pan',\n onMove(moveCtx: InvocationCtx): void {\n if (!moveCtx.drag) return;\n // Use `screenDelta` (client/CSS pixels), NOT `delta` (world). Pan\n // mutates the view itself, so world deltas are self-referential —\n // after the first commit, `toWorld(currentClient)` returns a\n // position offset by the just-applied pan, halving the apparent\n // movement on every subsequent pointermove. Screen coords come\n // straight from the DOM event and don't drift.\n const screen = moveCtx.drag.screenDelta ?? screenDeltaFromWorld(moveCtx.drag, scratch);\n // An axis lock drops the other component of the *cumulative* delta,\n // so the locked axis never moves however the pointer wanders.\n const screenDx = scratch.axis === 'y' ? 0 : screen.x;\n const screenDy = scratch.axis === 'x' ? 0 : screen.y;\n if (scratch.tracker) {\n scratch.tracker.record(\n screenDx - scratch.lastScreen.x,\n screenDy - scratch.lastScreen.y,\n performance.now(),\n );\n scratch.lastScreen = { x: screenDx, y: screenDy };\n }\n const sv = scratch.startView;\n // 1 screen px maps to 1/scale world units (at 2x zoom, 100 px →\n // 50 world units of pan).\n const next = {\n ...sv,\n x: sv.x - screenDx / sv.scale.x,\n y: sv.y - screenDy / sv.scale.y,\n };\n scratch.view.set(next);\n debug?.recordViewport('pan', sv, next, grab && { x: grab.x, y: grab.y });\n },\n onEnd(_endCtx: InvocationCtx, reason: 'commit' | 'cancel'): void {\n // No scene ops to commit; the pan itself is already live. What is\n // left is the coast, and only for a drag that actually ended.\n const { tracker, inertia, view: v } = scratch;\n if (reason === 'cancel' || !tracker || !inertia || !v.decay) return;\n const { vx, vy } = tracker.getVelocity();\n const scale = scratch.startView.scale;\n v.decay({\n // Screen px/ms → world units/ms, matching the onMove conversion.\n velocity: { vx: -vx / scale.x, vy: -vy / scale.y },\n friction: inertia.friction,\n minSpeed: inertia.minSpeed,\n boundary: inertia.boundary,\n viewBounds: inertia.bounds,\n initialPosition: { x: v.get().x, y: v.get().y },\n onTick: (dx, dy) => {\n const cur = v.get();\n v.set({ ...cur, x: cur.x + dx, y: cur.y + dy });\n },\n });\n },\n };\n },\n },\n enabled: () => true,\n};\n"],"mappings":";;;AAgEA,SAASA,EACP,GACA,GAC0B;CAC1B,IAAMC,IAAKC,EAAQ,WACbC,IAAMD,EAAQ,KAAK,IAAI;CAC7B,OAAO;EACL,IAAIE,EAAK,QAAQ,IAAID,EAAI,KAAKC,EAAK,MAAM,IAAIH,EAAG,MAAMA,EAAG,MAAM;EAC/D,IAAIG,EAAK,QAAQ,IAAID,EAAI,KAAKC,EAAK,MAAM,IAAIH,EAAG,MAAMA,EAAG,MAAM;CACjE;AACF;AAuBA,IAAaI,IAAyD;CACpE,IAAI;CACJ,OAAO;CACP,OAAO;CAIP,QAAQ;CAKR,cAAc;CACd,UAAU,CAAC,QAAQ,OAAO;CAC1B,SAAS;EACP,QAAQ;EACR,MAAM,GAAoB,GAAmC;GAC3D,IAAMC,IAAOC,EAAI,KAAK;GACtB,IAAI,CAACD,GAAM,OAAO,CAAC;GAEnB,IAAME,IAAYF,EAAK,IAAI,GAKrBG,IAAUC,EAAcC,GAAM,MAAM,KAAK,CAAC,GAC1CC,IAAUH,EAAO,YAAY,KAAQ,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AG,IAAI,CAACE,IAAKF,EAAM;MAAE;MACjD,UAAUb,EAAQ;MAClB,UAAUA,EAAQ;MAClB,UAAUA,EAAQ;MAClB,YAAYA,EAAQ;MACpB,iBAAiB;OAAE,GAAGU,EAAE,IAAI,CAAC,CAAC;OAAG,GAAGA,EAAE,IAAI,CAAC,CAAC;MAAE;MAC9C,SAAS,GAAI,MAAO;OAClB,IAAMM,IAAMN,EAAE,IAAI;OAClB,EAAE,IAAI;QAAE,GAAGM;QAAK,GAAGA,EAAI,IAAIC;QAAI,GAAGD,EAAI,IAAIE;OAAG,CAAC;MAChD;KACF,CAAC;IACH;GACF;EACF;CACF;CACA,eAAe;AACjB"}
1
+ {"version":3,"file":"viewportDragPan.js","names":["screenDeltaFromWorld","v0","scratch","now","drag","viewportDragPanAction","view","ctx","startView","params","resolveParams","opts","inertia","createVelocityTracker","debug","grab","moveCtx","screen","screenDx","screenDy","sv","next","v","reason","tracker","scale","vx","vy","cur","dx","dy"],"sources":["../../../../src/interactions/actions/defaults/viewportDragPan.ts"],"sourcesContent":["/**\n * `viewportDragPanAction` — ongoing Action descriptor for drag-to-pan the viewport.\n *\n * ## Bindings\n * None of its own. The hand tool binds a drag to it, and a canvas that pans on\n * any unclaimed drag adds `dragPanContribution`.\n *\n * ## Design notes\n * The drag delta from the dispatcher is in screen space (pixels). The pan\n * formula converts screen pixels to world units by dividing by zoom:\n *\n * newView.x = startView.x - screenDx / startView.scale.x\n * newView.y = startView.y - screenDy / startView.scale.y\n *\n * where `screenDx` / `screenDy` are the screen-space pixel deltas from the\n * drag origin. This ensures that at any zoom level, the drag behavior is\n * consistent: 1 screen pixel always pans the same amount relative to the\n * viewport's zoom (e.g., at 1x zoom: 100px → 100 world units; at 2x zoom:\n * 100px → 50 world units). The camera moves opposite to the drag direction\n * so that the scene content appears to follow the pointer.\n *\n * The descriptor captures `startView` in its own scratch at `start` time,\n * parallel to `useHandTool`'s `startView` capture in its scratch object.\n *\n * ## Axis locking and inertia\n * Both are read from the binding's `params` at `start`, so any consumer\n * binding this action gets them — not just `useHandTool`. `axis` drops one\n * component of every pan delta. `inertia` coasts the view after release,\n * through the optional `view.decay` dep; with no such dep wired the pan\n * simply lands, which is what an unconfigured consumer already expects.\n *\n * @see useHandTool — the React hook this descriptor parallels.\n */\n\nimport type { Action } from '@weasel-js/routing';\nimport { resolveParams, type InvocationCtx, type OngoingHandle, type BindingOpts } from '@weasel-js/routing';\nimport type { View } from 'core/viewport/view';\nimport type { ViewApi } from '../depSchema';\nimport type { InertiaConfig } from 'core/viewport/useDecayLoop';\nimport { createVelocityTracker, type VelocityTracker } from 'core/viewport/createVelocityTracker';\n\n// ---------------------------------------------------------------------------\n// Internal scratch\n// ---------------------------------------------------------------------------\n\ninterface DragPanScratch {\n startView: View;\n view: ViewApi;\n axis: 'both' | 'x' | 'y';\n inertia: InertiaConfig | undefined;\n tracker: VelocityTracker | undefined;\n lastScreen: { x: number; y: number };\n}\n\n/**\n * Rebuild the client-pixel drag delta from the world one, for an event source\n * that supplied no `clientX`/`clientY`.\n *\n * A world delta is self-referential mid-pan — its two ends were measured under\n * different views — so it cannot simply be scaled. Undoing each end against the\n * view that produced it recovers the client delta exactly, since\n * `world = (client - origin) / scale + view` and neither the canvas origin nor\n * the scale moves during a pan.\n */\nfunction screenDeltaFromWorld(\n drag: NonNullable<InvocationCtx['drag']>,\n scratch: DragPanScratch,\n): { x: number; y: number } {\n const v0 = scratch.startView;\n const now = scratch.view.get();\n return {\n x: (drag.current.x - now.x - (drag.start.x - v0.x)) * v0.scale.x,\n y: (drag.current.y - now.y - (drag.start.y - v0.y)) * v0.scale.y,\n };\n}\n\n/** Binding params `viewport.dragPan` understands. `useHandTool` supplies both;\n * a bare binding supplies neither and pans both axes with no coasting. */\nexport interface DragPanParams {\n axis?: 'both' | 'x' | 'y';\n inertia?: false | InertiaConfig;\n}\n\n// ---------------------------------------------------------------------------\n// Descriptor\n// ---------------------------------------------------------------------------\n\n/**\n * @experimental\n * Static descriptor for the `viewport.dragPan` Action.\n *\n * Requires dep-schema entry: `view`.\n *\n * Translates the viewport by the screen-space drag delta so the canvas content\n * follows the pointer. Produces no scene ops — view changes are not undoable.\n */\n// No `eligible` field → viewport pan is always eligible across all modes.\nexport const viewportDragPanAction: Action & { requires: string[] } = {\n id: 'viewport.dragPan',\n label: 'Drag to pan viewport',\n group: 'viewport',\n // Hover hint: when this action would win the drag at the hovered point\n // (e.g. empty canvas with no marquee-capable tool ahead of it), the\n // hover-cursor pump shows the open hand.\n cursor: 'grab',\n // ...and the closed hand once the pan is actually running. This was\n // `useHandTool`'s `engaged: { cursor: 'grabbing' }` — a phase-table entry\n // on a tool, which meant a consumer who bound `viewport.dragPan` without\n // the hand tool got no state cursor at all.\n activeCursor: 'grabbing',\n requires: ['view', 'debug'],\n invoker: {\n timing: 'ongoing',\n start(ctx: InvocationCtx, opts?: BindingOpts): OngoingHandle {\n const view = ctx.deps.view;\n if (!view) return {};\n\n const startView = view.get();\n // Gesture-driven ongoing actions never see `ctx.params` — the dispatcher\n // hands the binding's unresolved `opts` here and nowhere else, and pumps\n // `onMove` / `onEnd` with an empty deps bag. Everything the gesture needs\n // has to be captured now.\n const params = (resolveParams(opts?.params) ?? {}) as DragPanParams;\n const inertia = params.inertia === false ? undefined : params.inertia;\n const scratch: DragPanScratch = {\n startView,\n view,\n axis: params.axis ?? 'both',\n inertia,\n // Only track when a coast could actually happen, so the common\n // no-inertia drag does no per-move work.\n tracker: inertia && view.decay ? createVelocityTracker() : undefined,\n lastScreen: { x: 0, y: 0 },\n };\n const debug = ctx.deps.debug;\n const grab = ctx.drag?.start;\n\n return {\n kind: 'pan',\n onMove(moveCtx: InvocationCtx): void {\n if (!moveCtx.drag) return;\n // Use `screenDelta` (client/CSS pixels), NOT `delta` (world). Pan\n // mutates the view itself, so world deltas are self-referential —\n // after the first commit, `toWorld(currentClient)` returns a\n // position offset by the just-applied pan, halving the apparent\n // movement on every subsequent pointermove. Screen coords come\n // straight from the DOM event and don't drift.\n const screen = moveCtx.drag.screenDelta ?? screenDeltaFromWorld(moveCtx.drag, scratch);\n // An axis lock drops the other component of the *cumulative* delta,\n // so the locked axis never moves however the pointer wanders.\n const screenDx = scratch.axis === 'y' ? 0 : screen.x;\n const screenDy = scratch.axis === 'x' ? 0 : screen.y;\n if (scratch.tracker) {\n scratch.tracker.record(\n screenDx - scratch.lastScreen.x,\n screenDy - scratch.lastScreen.y,\n performance.now(),\n );\n scratch.lastScreen = { x: screenDx, y: screenDy };\n }\n const sv = scratch.startView;\n // 1 screen px maps to 1/scale world units (at 2x zoom, 100 px →\n // 50 world units of pan).\n const next = {\n ...sv,\n x: sv.x - screenDx / sv.scale.x,\n y: sv.y - screenDy / sv.scale.y,\n };\n scratch.view.set(next);\n debug?.recordViewport('pan', sv, next, grab && { x: grab.x, y: grab.y });\n },\n onEnd(_endCtx: InvocationCtx, reason: 'commit' | 'cancel'): void {\n // No scene ops to commit; the pan itself is already live. What is\n // left is the coast, and only for a drag that actually ended.\n const { tracker, inertia, view: v } = scratch;\n if (reason === 'cancel' || !tracker || !inertia || !v.decay) return;\n const { vx, vy } = tracker.getVelocity();\n const scale = scratch.startView.scale;\n v.decay({\n // Screen px/ms → world units/ms, matching the onMove conversion.\n velocity: { vx: -vx / scale.x, vy: -vy / scale.y },\n friction: inertia.friction,\n minSpeed: inertia.minSpeed,\n boundary: inertia.boundary,\n viewBounds: inertia.bounds,\n initialPosition: { x: v.get().x, y: v.get().y },\n onTick: (dx, dy) => {\n const cur = v.get();\n v.set({ ...cur, x: cur.x + dx, y: cur.y + dy });\n },\n });\n },\n };\n },\n },\n enabled: () => true,\n};\n"],"mappings":";;;AAgEA,SAASA,EACP,GACA,GAC0B;CAC1B,IAAMC,IAAKC,EAAQ,WACbC,IAAMD,EAAQ,KAAK,IAAI;CAC7B,OAAO;EACL,IAAIE,EAAK,QAAQ,IAAID,EAAI,KAAKC,EAAK,MAAM,IAAIH,EAAG,MAAMA,EAAG,MAAM;EAC/D,IAAIG,EAA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AChC;KAEA,AADAlB,EAAQ,KAAK,IAAImB,CAAI,GACrBP,GAAO,eAAe,OAAOM,GAAIC,GAAMN,KAAQ;MAAE,GAAGA,EAAK;MAAG,GAAGA,EAAK;KAAE,CAAC;IACzE;IACA,MAAM,GAAwB,GAAmC;KAG/D,IAAM,EAAE,YAAS,YAAS,MAAMO,MAAMpB;KACtC,IAAIqB,MAAW,YAAY,CAACC,KAAW,CAACZ,KAAW,CAACU,EAAE,OAAO;KAC7D,IAAM,EAAE,OAAI,UAAOE,EAAQ,YAAY,GACjCC,IAAQvB,EAAQ,UAAU;KAChC,EAAE,MAAM;MAEN,UAAU;OAAE,IAAI,CAACwB,IAAKD,EAAM;OAAG,IAAI,CAACE,IAAKF,EAAM;MAAE;MACjD,UAAUb,EAAQ;MAClB,UAAUA,EAAQ;MAClB,UAAUA,EAAQ;MAClB,YAAYA,EAAQ;MACpB,iBAAiB;OAAE,GAAGU,EAAE,IAAI,CAAC,CAAC;OAAG,GAAGA,EAAE,IAAI,CAAC,CAAC;MAAE;MAC9C,SAAS,GAAI,MAAO;OAClB,IAAMM,IAAMN,EAAE,IAAI;OAClB,EAAE,IAAI;QAAE,GAAGM;QAAK,GAAGA,EAAI,IAAIC;QAAI,GAAGD,EAAI,IAAIE;OAAG,CAAC;MAChD;KACF,CAAC;IACH;GACF;EACF;CACF;CACA,eAAe;AACjB"}
@@ -1 +1 @@
1
- {"version":3,"file":"viewportWheelPan.js","names":["viewportWheelPanAction","view","deps","axis","params","deltaX","deltaY","from","next","wheelPan","makeViewportWheelPanAction","opts"],"sources":["../../../../src/interactions/actions/defaults/viewportWheelPan.ts"],"sourcesContent":["/**\n * `viewportWheelPanAction` — immediate Action descriptor for wheel-based viewport pan.\n *\n * ## Bindings\n * - Plain wheel (no mod) → pan by deltaX/deltaY\n * - Shift+wheel → horizontal pan (mouse-wheel users get a horizontal axis\n * without a horizontal scroll device). Implemented by routing deltaY into\n * the x axis when the spec carries `params.swapAxis: true`.\n *\n * ## Design notes\n * The dispatcher merges wheel event data (deltaX, deltaY, clientX, clientY)\n * into params at dispatch time. The invoker reads them from the params bag\n * and defers to `wheelPan` (`core/viewport/wheelHandler`), the kit's one\n * statement of the wheel convention — which divides the delta by `view.scale`\n * so one screen-pixel scroll is one screen-pixel pan at any zoom.\n *\n * `axis` locks the pan to one axis, matching `viewport.dragPan`'s param of\n * the same name, so a consumer that wants a single-axis viewport can say so\n * once per action instead of clamping every committed view. An axis lock\n * outranks `swapAxis`: a shift-wheel routed into a barred axis moves nothing.\n */\n\nimport type { Action, DebugSink } from '@weasel-js/routing';\nimport type { ViewApi } from '../depSchema';\nimport { wheelPan } from 'core/viewport/wheelHandler';\n\n// ---------------------------------------------------------------------------\n// Descriptor\n// ---------------------------------------------------------------------------\n\n/**\n * @experimental\n * Static descriptor for the `viewport.wheelPan` Action.\n *\n * Companion to `viewport.dragPan` (drag-to-pan via the hand tool /\n * space-held). This one is the wheel/trackpad path; both share the\n * same `view` dep but fire on different gesture kinds, so they\n * coexist without competing.\n *\n * Requires dep-schema entry: `view`.\n */\nexport const viewportWheelPanAction: Action & { requires: string[] } = {\n id: 'viewport.wheelPan',\n label: 'Pan (wheel)',\n group: 'viewport',\n /**\n * Plain wheel → pan; Shift+wheel → horizontal pan (axis swap).\n * Cmd+wheel is claimed by `viewportZoomAction`. The matcher's strict\n * modifier check keeps the bindings exclusive: omitting `mods` forbids\n * any modifier, and `mods: { shift: true }` forbids the others.\n */\n defaultBinding: [\n { spec: { kind: 'wheel' }, opts: {} },\n { spec: { kind: 'wheel', mods: { shift: true } }, opts: { params: { swapAxis: true } } },\n ],\n requires: ['view', 'debug'],\n invoker: {\n timing: 'immediate',\n run(deps, params) {\n const view = deps.view as ViewApi | undefined;\n if (!view) return;\n const axis = (params?.axis as 'both' | 'x' | 'y' | undefined) ?? 'both';\n const deltaX = (params?.deltaX as number | undefined) ?? 0;\n const deltaY = (params?.deltaY as number | undefined) ?? 0;\n const from = view.get();\n const next = wheelPan(from, { deltaX, deltaY }, { axis, swapAxis: params?.swapAxis === true });\n view.set(next);\n (deps.debug as DebugSink | undefined)?.recordViewport('pan', from, next);\n },\n },\n enabled: () => true,\n};\n\n/** Tuning for {@link makeViewportWheelPanAction}. */\nexport interface WheelPanOptions {\n /** Lock the pan to one axis. Default `'both'`. Mirrors `viewport.dragPan`'s\n * `axis` param, so a single-axis viewport is declared once per action\n * rather than clamped on every committed view. */\n axis?: 'both' | 'x' | 'y';\n}\n\n/** Builds a `viewport.wheelPan` descriptor with `opts` baked into both of its\n * default bindings. `viewportWheelPanAction` is the unconfigured one. */\nexport function makeViewportWheelPanAction(\n opts: WheelPanOptions = {},\n): Action & { requires: string[] } {\n const axis = opts.axis ?? 'both';\n return {\n ...viewportWheelPanAction,\n defaultBinding: [\n { spec: { kind: 'wheel' }, opts: { params: { axis } } },\n { spec: { kind: 'wheel', mods: { shift: true } }, opts: { params: { swapAxis: true, axis } } },\n ],\n };\n}\n"],"mappings":";;AAyCA,IAAaA,IAA0D;CACrE,IAAI;CACJ,OAAO;CACP,OAAO;CAOP,gBAAgB,CACd;EAAE,MAAM,EAAE,MAAM,QAAQ;EAAG,MAAM,CAAC;CAAE,GACpC;EAAE,MAAM;GAAE,MAAM;GAAS,MAAM,EAAE,OAAO,GAAK;EAAE;EAAG,MAAM,EAAE,QAAQ,EAAE,UAAU,GAAK,EAAE;CAAE,CACzF;CACA,UAAU,CAAC,QAAQ,OAAO;CAC1B,SAAS;EACP,QAAQ;EACR,IAAI,GAAM,GAAQ;GAChB,IAAMC,IAAOC,EAAK;GAClB,IAAI,CAACD,GAAM;GACX,IAAME,IAAQC,GAAQ,QAA2C,QAC3DC,IAAUD,GAAQ,UAAiC,GACnDE,IAAUF,GAAQ,UAAiC,GACnDG,IAAON,EAAK,IAAI,GAChBO,IAAOC,EAASF,GAAM;IAAE;IAAQ;GAAO,GAAG;IAAE;IAAM,UAAUH,GAAQ,aAAa;GAAK,CAAC;GAE7F,AADAH,EAAK,IAAIO,CAAI,GACbN,EAAM,OAAiC,eAAe,OAAOK,GAAMC,CAAI;EACzE;CACF;CACA,eAAe;AACjB;AAYA,SAAgBE,EACd,IAAwB,CAAC,GACQ;CACjC,IAAMP,IAAOQ,EAAK,QAAQ;CAC1B,OAAO;EACL,GAAGX;EACH,gBAAgB,CACd;GAAE,MAAM,EAAE,MAAM,QAAQ;GAAG,MAAM,EAAE,QAAQ,EAAE,QAAK,EAAE;EAAE,GACtD;GAAE,MAAM;IAAE,MAAM;IAAS,MAAM,EAAE,OAAO,GAAK;GAAE;GAAG,MAAM,EAAE,QAAQ;IAAE,UAAU;IAAM;GAAK,EAAE;EAAE,CAC/F;CACF;AACF"}
1
+ {"version":3,"file":"viewportWheelPan.js","names":["viewportWheelPanAction","view","deps","axis","params","deltaX","deltaY","from","next","wheelPan","makeViewportWheelPanAction","opts"],"sources":["../../../../src/interactions/actions/defaults/viewportWheelPan.ts"],"sourcesContent":["/**\n * `viewportWheelPanAction` — immediate Action descriptor for wheel-based viewport pan.\n *\n * ## Bindings\n * - Plain wheel (no mod) → pan by deltaX/deltaY\n * - Shift+wheel → horizontal pan (mouse-wheel users get a horizontal axis\n * without a horizontal scroll device). Implemented by routing deltaY into\n * the x axis when the spec carries `params.swapAxis: true`.\n *\n * ## Design notes\n * The dispatcher merges wheel event data (deltaX, deltaY, clientX, clientY)\n * into params at dispatch time. The invoker reads them from the params bag\n * and defers to `wheelPan` (`core/viewport/wheelHandler`), the kit's one\n * statement of the wheel convention — which divides the delta by `view.scale`\n * so one screen-pixel scroll is one screen-pixel pan at any zoom.\n *\n * `axis` locks the pan to one axis, matching `viewport.dragPan`'s param of\n * the same name, so a consumer that wants a single-axis viewport can say so\n * once per action instead of clamping every committed view. An axis lock\n * outranks `swapAxis`: a shift-wheel routed into a barred axis moves nothing.\n */\n\nimport type { Action } from '@weasel-js/routing';\nimport { wheelPan } from 'core/viewport/wheelHandler';\n\n// ---------------------------------------------------------------------------\n// Descriptor\n// ---------------------------------------------------------------------------\n\n/**\n * @experimental\n * Static descriptor for the `viewport.wheelPan` Action.\n *\n * Companion to `viewport.dragPan` (drag-to-pan via the hand tool /\n * space-held). This one is the wheel/trackpad path; both share the\n * same `view` dep but fire on different gesture kinds, so they\n * coexist without competing.\n *\n * Requires dep-schema entry: `view`.\n */\nexport const viewportWheelPanAction: Action & { requires: string[] } = {\n id: 'viewport.wheelPan',\n label: 'Pan (wheel)',\n group: 'viewport',\n /**\n * Plain wheel → pan; Shift+wheel → horizontal pan (axis swap).\n * Cmd+wheel is claimed by `viewportZoomAction`. The matcher's strict\n * modifier check keeps the bindings exclusive: omitting `mods` forbids\n * any modifier, and `mods: { shift: true }` forbids the others.\n */\n defaultBinding: [\n { spec: { kind: 'wheel' }, opts: {} },\n { spec: { kind: 'wheel', mods: { shift: true } }, opts: { params: { swapAxis: true } } },\n ],\n requires: ['view', 'debug'],\n invoker: {\n timing: 'immediate',\n run(deps, params) {\n const view = deps.view;\n if (!view) return;\n const axis = (params?.axis as 'both' | 'x' | 'y' | undefined) ?? 'both';\n const deltaX = (params?.deltaX as number | undefined) ?? 0;\n const deltaY = (params?.deltaY as number | undefined) ?? 0;\n const from = view.get();\n const next = wheelPan(from, { deltaX, deltaY }, { axis, swapAxis: params?.swapAxis === true });\n view.set(next);\n deps.debug?.recordViewport('pan', from, next);\n },\n },\n enabled: () => true,\n};\n\n/** Tuning for {@link makeViewportWheelPanAction}. */\nexport interface WheelPanOptions {\n /** Lock the pan to one axis. Default `'both'`. Mirrors `viewport.dragPan`'s\n * `axis` param, so a single-axis viewport is declared once per action\n * rather than clamped on every committed view. */\n axis?: 'both' | 'x' | 'y';\n}\n\n/** Builds a `viewport.wheelPan` descriptor with `opts` baked into both of its\n * default bindings. `viewportWheelPanAction` is the unconfigured one. */\nexport function makeViewportWheelPanAction(\n opts: WheelPanOptions = {},\n): Action & { requires: string[] } {\n const axis = opts.axis ?? 'both';\n return {\n ...viewportWheelPanAction,\n defaultBinding: [\n { spec: { kind: 'wheel' }, opts: { params: { axis } } },\n { spec: { kind: 'wheel', mods: { shift: true } }, opts: { params: { swapAxis: true, axis } } },\n ],\n };\n}\n"],"mappings":";;AAwCA,IAAaA,IAA0D;CACrE,IAAI;CACJ,OAAO;CACP,OAAO;CAOP,gBAAgB,CACd;EAAE,MAAM,EAAE,MAAM,QAAQ;EAAG,MAAM,CAAC;CAAE,GACpC;EAAE,MAAM;GAAE,MAAM;GAAS,MAAM,EAAE,OAAO,GAAK;EAAE;EAAG,MAAM,EAAE,QAAQ,EAAE,UAAU,GAAK,EAAE;CAAE,CACzF;CACA,UAAU,CAAC,QAAQ,OAAO;CAC1B,SAAS;EACP,QAAQ;EACR,IAAI,GAAM,GAAQ;GAChB,IAAMC,IAAOC,EAAK;GAClB,IAAI,CAACD,GAAM;GACX,IAAME,IAAQC,GAAQ,QAA2C,QAC3DC,IAAUD,GAAQ,UAAiC,GACnDE,IAAUF,GAAQ,UAAiC,GACnDG,IAAON,EAAK,IAAI,GAChBO,IAAOC,EAASF,GAAM;IAAE;IAAQ;GAAO,GAAG;IAAE;IAAM,UAAUH,GAAQ,aAAa;GAAK,CAAC;GAE7F,AADAH,EAAK,IAAIO,CAAI,GACbN,EAAK,OAAO,eAAe,OAAOK,GAAMC,CAAI;EAC9C;CACF;CACA,eAAe;AACjB;AAYA,SAAgBE,EACd,IAAwB,CAAC,GACQ;CACjC,IAAMP,IAAOQ,EAAK,QAAQ;CAC1B,OAAO;EACL,GAAGX;EACH,gBAAgB,CACd;GAAE,MAAM,EAAE,MAAM,QAAQ;GAAG,MAAM,EAAE,QAAQ,EAAE,QAAK,EAAE;EAAE,GACtD;GAAE,MAAM;IAAE,MAAM;IAAS,MAAM,EAAE,OAAO,GAAK;GAAE;GAAG,MAAM,EAAE,QAAQ;IAAE,UAAU;IAAM;GAAK,EAAE;EAAE,CAC/F;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"viewportZoom.js","names":["KEY_STEP","keyAnchor","size","view","makeViewportZoomAction","clamp","opts","DEFAULT_MIN_ZOOM","DEFAULT_MAX_ZOOM","wheelSpec","rawAnimate","animateRest","tweenOpts","deps","debug","current","record","wx","wy","screenToWorld","anchor","viewToTransform","from","to","kind","params","canAnimate","stepTo","target","ms","stepFrom","focal","scaleBy","factor","next","zoomAt","wheelZoomFactor","resetMs","viewportZoomAction"],"sources":["../../../../src/interactions/actions/defaults/viewportZoom.ts"],"sourcesContent":["/**\n * `viewportZoomAction` — immediate Action descriptor for viewport zoom.\n *\n * ## Bindings (parametric — each passes `params.kind`)\n * - `{ kind: 'wheel', mods: { mod: true } }` → Cmd+wheel, params: `{ kind: 'wheel' }`\n * - `{ kind: 'wheel', mods: { ctrl: true } }` → trackpad pinch, params: `{ kind: 'wheel' }`.\n * Browsers synthesize a trackpad pinch as ctrl+wheel. On a Mac that is a\n * *different* event from the `mod` binding above (`mod` is metaKey there), so\n * pinch needs its own binding or nothing claims it and the page zooms instead.\n * - `{ kind: 'pinch' }` → Safari trackpad pinch (WebKit `gesturechange`),\n * params: `{ kind: 'pinch' }`. Safari may send the same pinch as ctrl+wheel\n * as well; the dispatcher swallows that copy while a claimed gesture is live,\n * so only one of the two bindings fires per pinch.\n * - `{ kind: 'key', key: '=' }` → zoom in, params: `{ kind: 'in' }`\n * - `{ kind: 'key', key: '-' }` → zoom out, params: `{ kind: 'out' }`\n * - `{ kind: 'key', key: '0' }` → reset zoom, params: `{ kind: 'reset' }`\n *\n * ## Design notes\n * The invoker switches on `params.kind`:\n * - `'wheel'` and `'pinch'`: both reduce to a scale factor about a focal\n * point and share one `zoomAt` call. A wheel sample's factor is\n * `wheelZoomFactor(deltaY)`, the kit's one statement of the wheel\n * convention; a pinch sample carries its factor as `scale`. The dispatcher\n * merges event data into params and converts client coords to canvas-local\n * (subtracting the canvas's bounding rect) before merging — `zoomAt`\n * expects canvas-local.\n * - `'in'`/`'out'`: step zoom by ×1.25 / ×0.8, anchored at the host center\n * when the `view` dep wires `hostSize()` (SceneCanvas does), falling back\n * to the canvas top-left origin for consumers that don't.\n * - `'reset'`: resets scale to 1, translation to 0, or calls the `view` dep's\n * `recenter()`.\n *\n * The three discrete branches glide instead of jumping when the `animate`\n * option is configured and the `view` dep implements `animate` — they hand the\n * action a target and nothing in between, which is the whole condition for\n * tweening. `'wheel'` and `'pinch'` always jump per sample.\n *\n * ## Key binding modifier notes\n * The key bindings (`=`, `-`, `0`) require `mod: true` (Cmd on Mac, Ctrl elsewhere).\n * This matches the behaviour of the dissolved `useKeyboardZoomTool`.\n */\n\nimport type { Action, DebugSink } from '@weasel-js/routing';\nimport type { ViewApi } from '../depSchema';\nimport { zoomAt } from 'core/viewport/zoomAt';\nimport { wheelZoomFactor } from 'core/viewport/wheelHandler';\nimport { DEFAULT_MIN_ZOOM, DEFAULT_MAX_ZOOM } from 'core/viewport/zoomBounds';\nimport { viewToTransform, type View } from 'core/viewport/view';\nimport { screenToWorld } from 'core/viewport/viewTransform';\nimport type { ViewAnimationOptions } from 'core/viewport/useViewAnimation';\n\n// Multiplicative step for keyboard zoom (matches useKeyboardZoomTool default).\nconst KEY_STEP = 1.25;\n\n/** Keyboard-zoom anchor: the host center when the view dep can measure it,\n * else the canvas top-left origin (see design notes). */\nfunction keyAnchor(view: ViewApi): { x: number; y: number } {\n const size = view.hostSize?.();\n return size ? { x: size.width / 2, y: size.height / 2 } : { x: 0, y: 0 };\n}\n// ---------------------------------------------------------------------------\n// Descriptor\n// ---------------------------------------------------------------------------\n\n/**\n * @experimental\n * Tuning for the animated form of the discrete zoom steps.\n */\nexport interface ViewportZoomAnimateOptions extends ViewAnimationOptions {\n /** Duration for the Cmd+0 reset branch. Defaults to `ms`. */\n resetMs?: number;\n}\n\n/**\n * @experimental\n * Tuning for {@link makeViewportZoomAction}.\n */\nexport interface ViewportZoomOptions {\n /**\n * Which wheel gesture triggers zoom.\n * - `'mod'` (default): Cmd/Ctrl+wheel — coexists with plain-wheel pan\n * (`viewport.wheelPan`). A Mac trackpad pinch arrives as ctrl+wheel, which\n * `mod: true` forbids on Mac; nothing here handles it.\n * - `'plain'`: bare wheel, no modifier. Pair with `viewport.pan: false`,\n * since plain wheel otherwise drives pan and the two would compete.\n */\n wheel?: 'plain' | 'mod';\n /** Lower clamp on the resulting view scale, forwarded to `zoomAt`. Default 0.1. */\n min?: number;\n /** Upper clamp on the resulting view scale, forwarded to `zoomAt`. Default 8. */\n max?: number;\n /**\n * Glide the discrete steps (Cmd+=, Cmd+-, Cmd+0) instead of jumping.\n * `true` uses the kit defaults; an object tunes them. Wheel and pinch never\n * animate — their input already samples every frame. Requires a `view` dep\n * that implements `animate`; without one this is ignored.\n */\n animate?: boolean | ViewportZoomAnimateOptions;\n}\n\n/**\n * @experimental\n * Build a `viewport.zoom` Action descriptor with a configurable wheel trigger\n * and scale clamp. The keyboard bindings (Cmd+=/-/0) are fixed; only the wheel\n * binding and the `zoomAt` clamp vary.\n *\n * Requires dep-schema entry: `view`.\n */\nexport function makeViewportZoomAction(\n opts: ViewportZoomOptions = {},\n): Action & { requires: string[] } {\n const clamp = { min: opts.min ?? DEFAULT_MIN_ZOOM, max: opts.max ?? DEFAULT_MAX_ZOOM };\n // 'plain': bare wheel (omitting `mods` forbids any modifier — see the\n // matcher's strict modifier check). 'mod': Cmd/Ctrl+wheel.\n const wheelSpec =\n opts.wheel === 'plain'\n ? { kind: 'wheel' as const }\n : { kind: 'wheel' as const, mods: { mod: true } };\n\n const rawAnimate: ViewportZoomAnimateOptions | null =\n opts.animate === true ? {} : (opts.animate || null);\n const { resetMs, ...animateRest } = rawAnimate ?? {};\n const tweenOpts: ViewAnimationOptions | null = rawAnimate ? animateRest : null;\n\n return {\n id: 'viewport.zoom',\n label: 'Zoom',\n group: 'viewport',\n defaultBinding: [\n // wheel → wheel zoom (mod-gated by default; plain when configured)\n {\n spec: wheelSpec,\n opts: { params: { kind: 'wheel' } },\n },\n // Trackpad pinch, which the browser delivers as ctrl+wheel. Distinct from\n // the `mod` binding on mac; a duplicate of it elsewhere, where `matchBest`\n // picks a single winner. `viewport.wheelPan` forbids ctrl, so no contest.\n {\n spec: { kind: 'wheel' as const, mods: { ctrl: true } },\n opts: { params: { kind: 'wheel' } },\n },\n // Safari's trackpad pinch, reported as a scale rather than a wheel.\n {\n spec: { kind: 'pinch' as const },\n opts: { params: { kind: 'pinch' } },\n },\n // Cmd+= → zoom in (also accepts Cmd+Shift+= which is Cmd++ on many keyboards)\n {\n spec: { kind: 'key', key: '=', mods: { mod: true, shift: 'optional' } },\n opts: { params: { kind: 'in' } },\n },\n // Cmd+- → zoom out\n {\n spec: { kind: 'key', key: '-', mods: { mod: true } },\n opts: { params: { kind: 'out' } },\n },\n // Cmd+0 → reset zoom\n {\n spec: { kind: 'key', key: '0', mods: { mod: true } },\n opts: { params: { kind: 'reset' } },\n },\n ],\n requires: ['view', 'debug'],\n invoker: {\n timing: 'immediate',\n run(deps, params) {\n const view = deps.view as ViewApi | undefined;\n if (!view) return;\n const debug = deps.debug as DebugSink | undefined;\n const current = view.get();\n // Report a zoom about `anchor` (canvas-local px) from `from` to `to`.\n const record = (from: View, to: View, anchor: { x: number; y: number }) => {\n if (!debug) return;\n const [wx, wy] = screenToWorld(anchor.x, anchor.y, viewToTransform(from));\n debug.recordViewport('zoom', from, to, { x: wx, y: wy });\n };\n const kind = params?.kind as string | undefined;\n\n const canAnimate = tweenOpts !== null && typeof view.animate === 'function';\n const stepTo = (target: View, ms?: number) => {\n if (!canAnimate) { view.set(target); return; }\n view.animate!(target, { ...tweenOpts!, ms: ms ?? tweenOpts!.ms });\n };\n // Successive presses compound off where the camera is heading, not off\n // whichever frame the tween happens to be on.\n const stepFrom = (): View => (canAnimate && view.animationTarget?.()) || current;\n\n const focal = () => ({\n x: (params?.clientX as number | undefined) ?? 0,\n y: (params?.clientY as number | undefined) ?? 0,\n });\n const scaleBy = (factor: number) => {\n if (!(factor > 0) || !Number.isFinite(factor)) return;\n const next = zoomAt(current, focal(), factor, clamp);\n view.set(next);\n record(current, next, focal());\n };\n\n switch (kind) {\n case 'wheel':\n scaleBy(wheelZoomFactor((params?.deltaY as number | undefined) ?? 0));\n break;\n case 'pinch':\n scaleBy((params?.scale as number | undefined) ?? Number.NaN);\n break;\n case 'in':\n case 'out': {\n const from = stepFrom();\n const target = zoomAt(from, keyAnchor(view), kind === 'in' ? KEY_STEP : 1 / KEY_STEP, clamp);\n stepTo(target);\n record(from, target, keyAnchor(view));\n break;\n }\n case 'reset': {\n // Prefer the consumer-supplied recenter when available — typically\n // re-fits the document page into the workspace. A recenter that\n // returns its target can be animated; one that returns nothing\n // dispatched the view itself and is already done.\n const target = view.recenter\n ? view.recenter()\n : { x: 0, y: 0, scale: { x: 1, y: 1 } };\n if (target) stepTo(target, resetMs);\n break;\n }\n default:\n // Unknown kind — no-op. Legacy bridge calls with params=undefined;\n // default to zoom-in as a sensible fallback.\n if (params === undefined) {\n view.set(zoomAt(current, { x: 0, y: 0 }, KEY_STEP, clamp));\n }\n break;\n }\n },\n },\n enabled: () => true,\n };\n}\n\n/**\n * @experimental\n * Default `viewport.zoom` descriptor: Cmd/Ctrl+wheel zoom with the kit's\n * default 0.1–8 scale clamp. Equivalent to `makeViewportZoomAction()`.\n *\n * Requires dep-schema entry: `view`.\n */\nexport const viewportZoomAction: Action & { requires: string[] } = makeViewportZoomAction();\n"],"mappings":";;;;;;AAoDA,IAAMA,IAAW;AAIjB,SAASC,EAAU,GAAyC;CAC1D,IAAMC,IAAOC,EAAK,WAAW;CAC7B,OAAOD,IAAO;EAAE,GAAGA,EAAK,QAAQ;EAAG,GAAGA,EAAK,SAAS;CAAE,IAAI;EAAE,GAAG;EAAG,GAAG;CAAE;AACzE;AAiDA,SAAgBE,EACd,IAA4B,CAAC,GACI;CACjC,IAAMC,IAAQ;EAAE,KAAKC,EAAK,OAAOC;EAAkB,KAAKD,EAAK,OAAOE;CAAiB,GAG/EC,IACJH,EAAK,UAAU,UACX,EAAE,MAAM,QAAiB,IACzB;EAAE,MAAM;EAAkB,MAAM,EAAE,KAAK,GAAK;CAAE,GAE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KACF;KACA,SAGE,AAAIZ,MAAW,KAAA,KACbtB,EAAK,IAAIgC,EAAOpB,GAAS;MAAE,GAAG;MAAG,GAAG;KAAE,GAAGf,GAAUK,CAAK,CAAC;IAG/D;GACF;EACF;EACA,eAAe;CACjB;AACF;AASA,IAAaiC,IAAsDlC,EAAuB"}
1
+ {"version":3,"file":"viewportZoom.js","names":["KEY_STEP","keyAnchor","size","view","makeViewportZoomAction","clamp","opts","DEFAULT_MIN_ZOOM","DEFAULT_MAX_ZOOM","wheelSpec","rawAnimate","animateRest","tweenOpts","deps","debug","current","record","wx","wy","screenToWorld","anchor","viewToTransform","from","to","kind","params","canAnimate","stepTo","target","ms","stepFrom","focal","scaleBy","factor","next","zoomAt","wheelZoomFactor","resetMs","viewportZoomAction"],"sources":["../../../../src/interactions/actions/defaults/viewportZoom.ts"],"sourcesContent":["/**\n * `viewportZoomAction` — immediate Action descriptor for viewport zoom.\n *\n * ## Bindings (parametric — each passes `params.kind`)\n * - `{ kind: 'wheel', mods: { mod: true } }` → Cmd+wheel, params: `{ kind: 'wheel' }`\n * - `{ kind: 'wheel', mods: { ctrl: true } }` → trackpad pinch, params: `{ kind: 'wheel' }`.\n * Browsers synthesize a trackpad pinch as ctrl+wheel. On a Mac that is a\n * *different* event from the `mod` binding above (`mod` is metaKey there), so\n * pinch needs its own binding or nothing claims it and the page zooms instead.\n * - `{ kind: 'pinch' }` → Safari trackpad pinch (WebKit `gesturechange`),\n * params: `{ kind: 'pinch' }`. Safari may send the same pinch as ctrl+wheel\n * as well; the dispatcher swallows that copy while a claimed gesture is live,\n * so only one of the two bindings fires per pinch.\n * - `{ kind: 'key', key: '=' }` → zoom in, params: `{ kind: 'in' }`\n * - `{ kind: 'key', key: '-' }` → zoom out, params: `{ kind: 'out' }`\n * - `{ kind: 'key', key: '0' }` → reset zoom, params: `{ kind: 'reset' }`\n *\n * ## Design notes\n * The invoker switches on `params.kind`:\n * - `'wheel'` and `'pinch'`: both reduce to a scale factor about a focal\n * point and share one `zoomAt` call. A wheel sample's factor is\n * `wheelZoomFactor(deltaY)`, the kit's one statement of the wheel\n * convention; a pinch sample carries its factor as `scale`. The dispatcher\n * merges event data into params and converts client coords to canvas-local\n * (subtracting the canvas's bounding rect) before merging — `zoomAt`\n * expects canvas-local.\n * - `'in'`/`'out'`: step zoom by ×1.25 / ×0.8, anchored at the host center\n * when the `view` dep wires `hostSize()` (SceneCanvas does), falling back\n * to the canvas top-left origin for consumers that don't.\n * - `'reset'`: resets scale to 1, translation to 0, or calls the `view` dep's\n * `recenter()`.\n *\n * The three discrete branches glide instead of jumping when the `animate`\n * option is configured and the `view` dep implements `animate` — they hand the\n * action a target and nothing in between, which is the whole condition for\n * tweening. `'wheel'` and `'pinch'` always jump per sample.\n *\n * ## Key binding modifier notes\n * The key bindings (`=`, `-`, `0`) require `mod: true` (Cmd on Mac, Ctrl elsewhere).\n * This matches the behaviour of the dissolved `useKeyboardZoomTool`.\n */\n\nimport type { Action } from '@weasel-js/routing';\nimport type { ViewApi } from '../depSchema';\nimport { zoomAt } from 'core/viewport/zoomAt';\nimport { wheelZoomFactor } from 'core/viewport/wheelHandler';\nimport { DEFAULT_MIN_ZOOM, DEFAULT_MAX_ZOOM } from 'core/viewport/zoomBounds';\nimport { viewToTransform, type View } from 'core/viewport/view';\nimport { screenToWorld } from 'core/viewport/viewTransform';\nimport type { ViewAnimationOptions } from 'core/viewport/useViewAnimation';\n\n// Multiplicative step for keyboard zoom (matches useKeyboardZoomTool default).\nconst KEY_STEP = 1.25;\n\n/** Keyboard-zoom anchor: the host center when the view dep can measure it,\n * else the canvas top-left origin (see design notes). */\nfunction keyAnchor(view: ViewApi): { x: number; y: number } {\n const size = view.hostSize?.();\n return size ? { x: size.width / 2, y: size.height / 2 } : { x: 0, y: 0 };\n}\n// ---------------------------------------------------------------------------\n// Descriptor\n// ---------------------------------------------------------------------------\n\n/**\n * @experimental\n * Tuning for the animated form of the discrete zoom steps.\n */\nexport interface ViewportZoomAnimateOptions extends ViewAnimationOptions {\n /** Duration for the Cmd+0 reset branch. Defaults to `ms`. */\n resetMs?: number;\n}\n\n/**\n * @experimental\n * Tuning for {@link makeViewportZoomAction}.\n */\nexport interface ViewportZoomOptions {\n /**\n * Which wheel gesture triggers zoom.\n * - `'mod'` (default): Cmd/Ctrl+wheel — coexists with plain-wheel pan\n * (`viewport.wheelPan`). A Mac trackpad pinch arrives as ctrl+wheel, which\n * `mod: true` forbids on Mac; nothing here handles it.\n * - `'plain'`: bare wheel, no modifier. Pair with `viewport.pan: false`,\n * since plain wheel otherwise drives pan and the two would compete.\n */\n wheel?: 'plain' | 'mod';\n /** Lower clamp on the resulting view scale, forwarded to `zoomAt`. Default 0.1. */\n min?: number;\n /** Upper clamp on the resulting view scale, forwarded to `zoomAt`. Default 8. */\n max?: number;\n /**\n * Glide the discrete steps (Cmd+=, Cmd+-, Cmd+0) instead of jumping.\n * `true` uses the kit defaults; an object tunes them. Wheel and pinch never\n * animate — their input already samples every frame. Requires a `view` dep\n * that implements `animate`; without one this is ignored.\n */\n animate?: boolean | ViewportZoomAnimateOptions;\n}\n\n/**\n * @experimental\n * Build a `viewport.zoom` Action descriptor with a configurable wheel trigger\n * and scale clamp. The keyboard bindings (Cmd+=/-/0) are fixed; only the wheel\n * binding and the `zoomAt` clamp vary.\n *\n * Requires dep-schema entry: `view`.\n */\nexport function makeViewportZoomAction(\n opts: ViewportZoomOptions = {},\n): Action & { requires: string[] } {\n const clamp = { min: opts.min ?? DEFAULT_MIN_ZOOM, max: opts.max ?? DEFAULT_MAX_ZOOM };\n // 'plain': bare wheel (omitting `mods` forbids any modifier — see the\n // matcher's strict modifier check). 'mod': Cmd/Ctrl+wheel.\n const wheelSpec =\n opts.wheel === 'plain'\n ? { kind: 'wheel' as const }\n : { kind: 'wheel' as const, mods: { mod: true } };\n\n const rawAnimate: ViewportZoomAnimateOptions | null =\n opts.animate === true ? {} : (opts.animate || null);\n const { resetMs, ...animateRest } = rawAnimate ?? {};\n const tweenOpts: ViewAnimationOptions | null = rawAnimate ? animateRest : null;\n\n return {\n id: 'viewport.zoom',\n label: 'Zoom',\n group: 'viewport',\n defaultBinding: [\n // wheel → wheel zoom (mod-gated by default; plain when configured)\n {\n spec: wheelSpec,\n opts: { params: { kind: 'wheel' } },\n },\n // Trackpad pinch, which the browser delivers as ctrl+wheel. Distinct from\n // the `mod` binding on mac; a duplicate of it elsewhere, where `matchBest`\n // picks a single winner. `viewport.wheelPan` forbids ctrl, so no contest.\n {\n spec: { kind: 'wheel' as const, mods: { ctrl: true } },\n opts: { params: { kind: 'wheel' } },\n },\n // Safari's trackpad pinch, reported as a scale rather than a wheel.\n {\n spec: { kind: 'pinch' as const },\n opts: { params: { kind: 'pinch' } },\n },\n // Cmd+= → zoom in (also accepts Cmd+Shift+= which is Cmd++ on many keyboards)\n {\n spec: { kind: 'key', key: '=', mods: { mod: true, shift: 'optional' } },\n opts: { params: { kind: 'in' } },\n },\n // Cmd+- → zoom out\n {\n spec: { kind: 'key', key: '-', mods: { mod: true } },\n opts: { params: { kind: 'out' } },\n },\n // Cmd+0 → reset zoom\n {\n spec: { kind: 'key', key: '0', mods: { mod: true } },\n opts: { params: { kind: 'reset' } },\n },\n ],\n requires: ['view', 'debug'],\n invoker: {\n timing: 'immediate',\n run(deps, params) {\n const view = deps.view;\n if (!view) return;\n const debug = deps.debug;\n const current = view.get();\n // Report a zoom about `anchor` (canvas-local px) from `from` to `to`.\n const record = (from: View, to: View, anchor: { x: number; y: number }) => {\n if (!debug) return;\n const [wx, wy] = screenToWorld(anchor.x, anchor.y, viewToTransform(from));\n debug.recordViewport('zoom', from, to, { x: wx, y: wy });\n };\n const kind = params?.kind as string | undefined;\n\n const canAnimate = tweenOpts !== null && typeof view.animate === 'function';\n const stepTo = (target: View, ms?: number) => {\n if (!canAnimate) { view.set(target); return; }\n view.animate!(target, { ...tweenOpts!, ms: ms ?? tweenOpts!.ms });\n };\n // Successive presses compound off where the camera is heading, not off\n // whichever frame the tween happens to be on.\n const stepFrom = (): View => (canAnimate && view.animationTarget?.()) || current;\n\n const focal = () => ({\n x: (params?.clientX as number | undefined) ?? 0,\n y: (params?.clientY as number | undefined) ?? 0,\n });\n const scaleBy = (factor: number) => {\n if (!(factor > 0) || !Number.isFinite(factor)) return;\n const next = zoomAt(current, focal(), factor, clamp);\n view.set(next);\n record(current, next, focal());\n };\n\n switch (kind) {\n case 'wheel':\n scaleBy(wheelZoomFactor((params?.deltaY as number | undefined) ?? 0));\n break;\n case 'pinch':\n scaleBy((params?.scale as number | undefined) ?? Number.NaN);\n break;\n case 'in':\n case 'out': {\n const from = stepFrom();\n const target = zoomAt(from, keyAnchor(view), kind === 'in' ? KEY_STEP : 1 / KEY_STEP, clamp);\n stepTo(target);\n record(from, target, keyAnchor(view));\n break;\n }\n case 'reset': {\n // Prefer the consumer-supplied recenter when available — typically\n // re-fits the document page into the workspace. A recenter that\n // returns its target can be animated; one that returns nothing\n // dispatched the view itself and is already done.\n const target = view.recenter\n ? view.recenter()\n : { x: 0, y: 0, scale: { x: 1, y: 1 } };\n if (target) stepTo(target, resetMs);\n break;\n }\n default:\n // Unknown kind — no-op. Legacy bridge calls with params=undefined;\n // default to zoom-in as a sensible fallback.\n if (params === undefined) {\n view.set(zoomAt(current, { x: 0, y: 0 }, KEY_STEP, clamp));\n }\n break;\n }\n },\n },\n enabled: () => true,\n };\n}\n\n/**\n * @experimental\n * Default `viewport.zoom` descriptor: Cmd/Ctrl+wheel zoom with the kit's\n * default 0.1–8 scale clamp. Equivalent to `makeViewportZoomAction()`.\n *\n * Requires dep-schema entry: `view`.\n */\nexport const viewportZoomAction: Action & { requires: string[] } = makeViewportZoomAction();\n"],"mappings":";;;;;;AAoDA,IAAMA,IAAW;AAIjB,SAASC,EAAU,GAAyC;CAC1D,IAAMC,IAAOC,EAAK,WAAW;CAC7B,OAAOD,IAAO;EAAE,GAAGA,EAAK,QAAQ;EAAG,GAAGA,EAAK,SAAS;CAAE,IAAI;EAAE,GAAG;EAAG,GAAG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AAOM,GAAMM,GAAQ3B,EAAUE,CAAI,CAAC;MACpC;KACF;KACA,KAAK,SAAS;MAKZ,IAAMyB,IAASzB,EAAK,WAChBA,EAAK,SAAS,IACd;OAAE,GAAG;OAAG,GAAG;OAAG,OAAO;QAAE,GAAG;QAAG,GAAG;OAAE;MAAE;MACxC,AAAIyB,KAAQD,EAAOC,GAAQS,CAAO;MAClC;KACF;KACA,SAGE,AAAIZ,MAAW,KAAA,KACbtB,EAAK,IAAIgC,EAAOpB,GAAS;MAAE,GAAG;MAAG,GAAG;KAAE,GAAGf,GAAUK,CAAK,CAAC;IAG/D;GACF;EACF;EACA,eAAe;CACjB;AACF;AASA,IAAaiC,IAAsDlC,EAAuB"}
@@ -1 +1 @@
1
- {"version":3,"file":"planeInput.js","names":["layerOfNode","id","deps","asNodeId","selectionLayer","selection","affordance","layer","insertLayer","editingLayer","planeOf","view","invertPlane","m","planeToPlane","carryPose","pose","b","d","rectToPlane","inPlane","inner","action","declared","requires","plane","livePlane","layerOf","params","wx","\"worldX\"","wy","\"worldY\"","at","toPlane","ctx","opts","planeHandle","scene","bag","viewApi","l","parallaxOf","parallax","IDENTITY","map","p","planeMap","planeView","camera","deriveParallaxView","edited","own","override","name","nodeAtPoint","fromPlane","exclude","snap","start0","pressedAt","trail","trailCarrier","out","c","start","current","aff","src","lastMap","same","points","i","handle","reason","ov","overlayFromPlane","pt","rectFromPlane","insertExtrasFromPlane","extras","e","r","v","\"a\"","\"b\"","\"center\"","\"radius\"","\"outerRadius\"","\"samples\"","s"],"sources":["../../../src/interactions/actions/planeInput.ts"],"sourcesContent":["/**\n * Editing a node on a parallax plane.\n *\n * The dispatcher hands every action the camera's world. A node on a layer\n * carrying `parallax` stores its pose in its plane's world, which the camera's\n * reaches through a `PlaneMap` that changes with the camera. An editing action\n * pairs the pointer with the pose it edits, so the two have to be in one world.\n *\n * `inPlane` is that one place: it wraps an action so its input is carried into\n * the plane of the layer it edits before the action reads it — pointer, drag,\n * trail, affordance pivot, and the camera it converts screen pixels through —\n * and so the chrome it publishes back comes out in the camera's world. A dep\n * that answers in world points (`nodeAtPoint`, `snap`) is the surface's, so it\n * keeps speaking the camera's world and the seam converts at its boundary.\n * The action sees the plane only as `view.plane()`, which it hands its snap\n * behaviors so they can bring the camera's guides and grid into the plane.\n *\n * A selection can span planes. The edit is measured in one of them, and a\n * node on another is carried into it as the gesture starts\n * (`planeOf` at press, inverted) and back out through `planeOf` as it is now,\n * so each node ends where it was drawn relative to the pointer.\n *\n * The map is read afresh on every call: a camera panning under a held drag, or\n * a plane whose factors are being animated, moves the node with the pointer.\n */\nimport type {\n Action, ActionDeps, AffordanceHit, BindingOpts, DragSample, InvocationCtx, OngoingHandle,\n OngoingOverlay,\n} from '@weasel-js/routing';\nimport type { Scene } from 'core/scene/types';\nimport { asNodeId } from 'core/scene/types';\nimport type { SelectionApi } from 'core/selection/useSelection';\nimport {\n deriveParallaxView, fromPlane, planeMap, planeToPlane, rectFromPlane, rectToPlane, toPlane,\n type ParallaxOpts, type PlaneMap,\n} from 'core/viewport/parallax';\nimport type { View } from 'core/viewport/view';\nimport type { PoseDescriptor } from 'core/geometry/poseDescriptor';\nimport type { EditAnchorsDep, InsertDep, NodeAtPointDep, SnapDep, ViewApi } from './depSchema';\n\ntype Point = { x: number; y: number };\n\n/** Which scene layer an invocation edits, read once as it starts, from its\n * deps and — for a drag — the affordance it grabbed. `undefined` means none:\n * the action runs in the camera's world. */\nexport type EditedLayerOf = (deps: ActionDeps, affordance?: AffordanceHit) => string | undefined;\n\nconst layerOfNode = (deps: ActionDeps, id: string | null | undefined): string | undefined =>\n (id ? (deps.scene as Scene<unknown, string, unknown> | undefined)?.get(asNodeId(id))?.layer : undefined);\n\n/** The layer of the node a selection edit acts on: the affordance's target\n * when the drag grabbed one, the first selected node otherwise. A selection\n * spanning planes is edited in that one node's plane. */\nexport const selectionLayer: EditedLayerOf = (deps, affordance) => {\n const selection = deps.selection as SelectionApi | undefined;\n for (const id of [...(affordance?.targetIds ?? []), ...(selection?.get() ?? [])]) {\n const layer = layerOfNode(deps, id);\n if (layer !== undefined) return layer;\n }\n return undefined;\n};\n\n/** The layer the `insert` dep will put a new node on. */\nexport const insertLayer: EditedLayerOf = (deps) =>\n (deps.insert as InsertDep | undefined)?.layer?.();\n\n/** The layer of the path in anchor-edit mode. */\nexport const editingLayer: EditedLayerOf = (deps) =>\n layerOfNode(deps, (deps.editAnchors as EditAnchorsDep | undefined)?.editingId);\n\n/** How the world an invocation edits in maps into the world `layer`'s nodes\n * are stored in, read now. Null when they are the same world. */\nexport function planeOf(view: unknown, layer: string): PlaneMap | null {\n return (view as ViewApi | undefined)?.planeOf?.(layer) ?? null;\n}\n\n/** `m` run backwards; null stays null. */\nexport function invertPlane(m: PlaneMap | null): PlaneMap | null {\n return m && planeToPlane(m, null);\n}\n\n/** `pose` carried through `m`. The map is axis-aligned, so remapping the\n * pose's bounds carries it exactly when the map scales both axes alike. */\nexport function carryPose<P>(d: PoseDescriptor<P>, pose: P, m: PlaneMap | null): P {\n if (m === null) return pose;\n const b = d.getBounds(pose);\n return d.remapBounds(pose, b, rectToPlane(m, b));\n}\n\n/** `action`, with its input carried into the plane of the layer `layerOf`\n * names. An action in a scene with no `parallax` layer, or invoked with no\n * scene or view to read a plane from, runs exactly as it would unwrapped.\n *\n * An ongoing action's drag is carried as a whole. An immediate one's world\n * point is `params.worldX` / `params.worldY`, the dispatcher's convention for\n * a click; it is carried when present. */\nexport function inPlane<A extends Action>(action: A, layerOf: EditedLayerOf): A {\n const inner = action.invoker;\n if (!inner) return action;\n const declared = action.requires ?? [];\n const requires = [...new Set([...declared, 'scene', 'selection', 'view'])];\n if (inner.timing === 'immediate') {\n return {\n ...action,\n requires,\n invoker: {\n timing: 'immediate',\n run(deps: ActionDeps, params?: Record<string, unknown>): void {\n const plane = livePlane(deps, layerOf(deps), declared, null);\n if (plane === null) return inner.run(deps, params);\n const wx = params?.['worldX'];\n const wy = params?.['worldY'];\n const at = typeof wx === 'number' && typeof wy === 'number'\n ? toPlane(plane.map(), { x: wx, y: wy })\n : null;\n inner.run(plane.deps, at ? { ...params, worldX: at.x, worldY: at.y } : params);\n },\n },\n } as A;\n }\n return {\n ...action,\n requires,\n invoker: {\n timing: 'ongoing',\n start(ctx: InvocationCtx, opts?: BindingOpts): OngoingHandle {\n const plane = livePlane(\n ctx.deps, layerOf(ctx.deps, ctx.drag?.affordance), declared, ctx.drag?.start ?? null,\n );\n if (plane === null) return inner.start(ctx, opts);\n return planeHandle(inner.start(plane.carry(ctx), opts), plane);\n },\n },\n } as A;\n}\n\ninterface LivePlane {\n map(): PlaneMap;\n /** The invocation's deps, speaking the plane's world. */\n deps: ActionDeps;\n /** `ctx` in the plane's world. */\n carry(ctx: InvocationCtx): InvocationCtx;\n}\n\nfunction livePlane(\n bag: ActionDeps,\n layer: string | undefined,\n /** What the wrapped action declared. The dispatcher's dev deps bag throws\n * on any other read, so the seam converts only the deps it can see. */\n declared: readonly string[],\n /** The drag's press point in the camera's world, when there is a drag. */\n pressedAt: Point | null,\n): LivePlane | null {\n const scene = bag.scene as Scene<unknown, string, unknown> | undefined;\n const viewApi = bag.view as ViewApi | undefined;\n if (layer === undefined || !scene || !viewApi) return null;\n if (!scene.layers.some((l) => l.parallax !== undefined)) return null;\n const parallaxOf = (id: string): ParallaxOpts | undefined => scene.layers.find((l) => l.id === id)?.parallax;\n const parallax = (): ParallaxOpts | undefined => parallaxOf(layer);\n\n const IDENTITY: PlaneMap = { scale: { x: 1, y: 1 }, offset: { x: 0, y: 0 } };\n const map = (): PlaneMap => {\n const p = parallax();\n return p ? planeMap(viewApi.get(), p) : IDENTITY;\n };\n\n // A screen-pixel tolerance, and anything else an action reads off the\n // camera, has to be read at the plane's scale.\n const planeView = Object.defineProperties(Object.create(viewApi), {\n get: {\n value: (): View => {\n const p = parallax();\n const camera = viewApi.get();\n return p ? deriveParallaxView(camera, p) : camera;\n },\n },\n plane: { value: map },\n planeOf: {\n value: (id: string): PlaneMap | null => {\n const edited = parallax();\n const own = parallaxOf(id);\n const camera = viewApi.get();\n return planeToPlane(edited ? planeMap(camera, edited) : null, own ? planeMap(camera, own) : null);\n },\n },\n }) as ViewApi;\n\n // Over the dispatcher's bag rather than a copy of it, so every other read\n // still goes through whatever checks the bag makes.\n const deps = Object.create(bag) as typeof bag;\n const override = (name: string, value: unknown) =>\n Object.defineProperty(deps, name, { value, enumerable: true });\n override('view', planeView);\n const nodeAtPoint = declared.includes('nodeAtPoint')\n ? bag.nodeAtPoint as NodeAtPointDep | undefined\n : undefined;\n if (nodeAtPoint) {\n override('nodeAtPoint', ((p, exclude) => nodeAtPoint(fromPlane(map(), p), exclude)) as NodeAtPointDep);\n }\n const snap = declared.includes('snap') ? bag.snap as SnapDep | undefined : undefined;\n if (snap) {\n override('snap', { point: (p: Point) => toPlane(map(), snap.point(fromPlane(map(), p))) } as SnapDep);\n }\n\n // The drag's origin, fixed in the plane at the moment it was pressed: where\n // the pointer went down on the node is where the node was grabbed, whatever\n // the camera does after.\n const start0 = pressedAt ? toPlane(map(), pressedAt) : null;\n const trail = trailCarrier();\n\n return {\n map,\n deps,\n carry(c) {\n const m = map();\n const out: InvocationCtx = { ...c, world: toPlane(m, c.world) };\n if (c.drag) {\n const start = start0 ?? toPlane(m, c.drag.start);\n const current = toPlane(m, c.drag.current);\n const aff = c.drag.affordance;\n out.drag = {\n ...c.drag,\n start,\n current,\n delta: { x: current.x - start.x, y: current.y - start.y },\n ...(c.drag.points ? { points: trail(c.drag.points, m) } : {}),\n ...(aff?.fixedPoint ? { affordance: { ...aff, fixedPoint: toPlane(m, aff.fixedPoint) } } : {}),\n };\n }\n // The dispatcher hands `onMove` no deps; only `start` has any to carry.\n if (c.deps) out.deps = deps;\n return out;\n },\n };\n}\n\n/** The drag trail in the plane. The dispatcher grows its trail in place, so\n * only the samples added since the last call are mapped — unless the map\n * moved, when every sample is. */\nfunction trailCarrier(): (points: DragSample[], m: PlaneMap) => DragSample[] {\n let src: DragSample[] | null = null;\n let lastMap: PlaneMap | null = null;\n let out: DragSample[] = [];\n return (points, m) => {\n const same = lastMap !== null\n && lastMap.scale.x === m.scale.x && lastMap.scale.y === m.scale.y\n && lastMap.offset.x === m.offset.x && lastMap.offset.y === m.offset.y;\n if (points !== src || !same || points.length < out.length) {\n src = points;\n out = [];\n }\n lastMap = m;\n for (let i = out.length; i < points.length; i++) {\n out.push({ ...points[i], ...toPlane(m, points[i]) });\n }\n // A copy, so a snapshot taken on `onEnd` is not the live accumulator.\n return out.slice();\n };\n}\n\nfunction planeHandle(handle: OngoingHandle, plane: LivePlane): OngoingHandle {\n const out: OngoingHandle = { ...handle };\n if (handle.onMove) out.onMove = (c) => handle.onMove!(plane.carry(c));\n if (handle.onEnd) out.onEnd = (c, reason) => handle.onEnd!(plane.carry(c), reason);\n if (handle.overlay) {\n out.overlay = () => {\n const ov = handle.overlay!();\n return ov ? overlayFromPlane(ov, plane.map()) : ov;\n };\n }\n return out;\n}\n\n/** An overlay drawn in the plane, in the camera's world: what every painter\n * reads an overlay as. */\nfunction overlayFromPlane(ov: OngoingOverlay, m: PlaneMap): OngoingOverlay {\n const pt = (p: Point) => fromPlane(m, p);\n switch (ov.kind) {\n case 'marquee':\n return { ...ov, start: pt(ov.start), current: pt(ov.current) };\n case 'lasso':\n return { ...ov, vertices: ov.vertices.map(pt), current: pt(ov.current) };\n case 'polyline':\n return { ...ov, points: ov.points.map(pt) };\n case 'insertPreview':\n return {\n ...ov,\n bounds: rectFromPlane(m, ov.bounds),\n extras: insertExtrasFromPlane(ov.extras, m),\n ...(ov.anchorPoint ? { anchorPoint: pt(ov.anchorPoint) } : {}),\n };\n }\n}\n\n/** The geometry the kit's insert kinds carry in `extras`, in the camera's\n * world. A consumer kind's extras are opaque, and pass through. */\nfunction insertExtrasFromPlane(extras: unknown, m: PlaneMap): unknown {\n if (extras === null || typeof extras !== 'object') return extras;\n const e = extras as Record<string, unknown>;\n const pt = (p: unknown) => fromPlane(m, p as Point);\n // Radial kinds inscribe in a square, so one scale carries a radius.\n const r = (v: unknown) => (typeof v === 'number' ? v / ((m.scale.x + m.scale.y) / 2) : v);\n const out: Record<string, unknown> = { ...e };\n if (e['a'] && e['b']) { out['a'] = pt(e['a']); out['b'] = pt(e['b']); }\n if (e['center']) out['center'] = pt(e['center']);\n if ('radius' in e) out['radius'] = r(e['radius']);\n if ('outerRadius' in e) out['outerRadius'] = r(e['outerRadius']);\n if (Array.isArray(e['samples'])) {\n out['samples'] = (e['samples'] as DragSample[]).map((s) => ({ ...s, ...pt(s) }));\n }\n return out;\n}\n"],"mappings":";;;AA+CA,IAAMA,KAAe,GAAkB,MACpCC,IAAMC,EAAK,OAAuD,IAAIC,EAASF,CAAE,CAAC,CAAC,EAAE,QAAQ,KAAA,GAKnFG,KAAiC,GAAM,MAAe;CACjE,IAAMC,IAAYH,EAAK;CACvB,KAAK,IAAMD,KAAM,CAAC,GAAIK,GAAY,aAAa,CAAC,GAAI,GAAID,GAAW,IAAI,KAAK,CAAC,CAAE,GAAG;EAChF,IAAME,IAAQP,EAAYE,GAAMD,CAAE;EAClC,IAAIM,MAAU,KAAA,GAAW,OAAOA;CAClC;AAEF,GAGaC,KAA8B,MACxCN,EAAK,QAAkC,QAAQ,GAGrCO,KAA+B,MAC1CT,EAAYE,GAAOA,EAAK,aAA4C,SAAS;AAI/E,SAAgBQ,EAAQ,GAAe,GAAgC;CACrE,OAAQC,GAA8B,UAAUJ,CAAK,KAAK;AAC5D;AAGA,SAAgBK,EAAY,GAAqC;CAC/D,OAAOC,KAAKC,EAAaD,GAAG,IAAI;AAClC;AAIA,SAAgBE,EAAa,GAAsB,GAAS,GAAuB;CACjF,IAAIF,MAAM,MAAM,OAAOG;CACvB,IAAMC,IAAIC,EAAE,UAAUF,CAAI;CAC1B,OAAOE,EAAE,YAAYF,GAAMC,GAAGE,EAAYN,GAAGI,CAAC,CAAC;AACjD;AASA,SAAgBG,EAA0B,GAAW,GAA2B;CAC9E,IAAMC,IAAQC,EAAO;CACrB,IAA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AGF,EAAG,WAAW,EAAE,IAAI,CAAC;EAC9D;CACJ;AACF;AAIA,SAASI,EAAsB,GAAiB,GAAsB;CACpE,IAAuB,OAAOC,KAAW,aAArCA,GAA+C,OAAOA;CAC1D,IAAMC,IAAID,GACJH,KAAM,MAAerB,EAAU3C,GAAGiC,CAAU,GAE5CoC,KAAK,MAAgB,OAAOC,KAAM,WAAWA,MAAMtE,EAAE,MAAM,IAAIA,EAAE,MAAM,KAAK,KAAKsE,GACjFpB,IAA+B,EAAE,GAAGkB,EAAE;CAQ5C,OAPIA,EAAEG,KAAQH,EAAEI,MAAQ,EAAID,IAAOP,EAAGI,EAAEG,CAAI,GAAG,EAAIC,IAAOR,EAAGI,EAAEI,CAAI,IAC/DJ,EAAEK,WAAW,EAAIA,SAAYT,EAAGI,EAAEK,MAAS,IAC3C,YAAYL,MAAG,EAAIM,SAAYL,EAAED,EAAEM,MAAS,IAC5C,iBAAiBN,MAAG,EAAIO,cAAiBN,EAAED,EAAEO,WAAc,IAC3D,MAAM,QAAQP,EAAEQ,OAAU,MAC5B,EAAIA,UAAcR,EAAEQ,QAA4B,KAAK,OAAO;EAAE,GAAGC;EAAG,GAAGb,EAAGa,CAAC;CAAE,EAAE,IAE1E3B;AACT"}
1
+ {"version":3,"file":"planeInput.js","names":["layerOfNode","id","deps","asNodeId","selectionLayer","selection","affordance","layer","insertLayer","editingLayer","planeOf","view","invertPlane","m","planeToPlane","carryPose","pose","b","d","rectToPlane","inPlane","inner","action","declared","requires","plane","livePlane","layerOf","params","wx","\"worldX\"","wy","\"worldY\"","at","toPlane","ctx","opts","planeHandle","scene","bag","viewApi","l","parallaxOf","parallax","IDENTITY","map","p","planeMap","planeView","camera","deriveParallaxView","edited","own","override","name","nodeAtPoint","fromPlane","exclude","snap","start0","pressedAt","trail","trailCarrier","out","c","start","current","aff","src","lastMap","same","points","i","handle","reason","ov","overlayFromPlane","pt","rectFromPlane","insertExtrasFromPlane","extras","e","r","v","\"a\"","\"b\"","\"center\"","\"radius\"","\"outerRadius\"","\"samples\"","s"],"sources":["../../../src/interactions/actions/planeInput.ts"],"sourcesContent":["/**\n * Editing a node on a parallax plane.\n *\n * The dispatcher hands every action the camera's world. A node on a layer\n * carrying `parallax` stores its pose in its plane's world, which the camera's\n * reaches through a `PlaneMap` that changes with the camera. An editing action\n * pairs the pointer with the pose it edits, so the two have to be in one world.\n *\n * `inPlane` is that one place: it wraps an action so its input is carried into\n * the plane of the layer it edits before the action reads it — pointer, drag,\n * trail, affordance pivot, and the camera it converts screen pixels through —\n * and so the chrome it publishes back comes out in the camera's world. A dep\n * that answers in world points (`nodeAtPoint`, `snap`) is the surface's, so it\n * keeps speaking the camera's world and the seam converts at its boundary.\n * The action sees the plane only as `view.plane()`, which it hands its snap\n * behaviors so they can bring the camera's guides and grid into the plane.\n *\n * A selection can span planes. The edit is measured in one of them, and a\n * node on another is carried into it as the gesture starts\n * (`planeOf` at press, inverted) and back out through `planeOf` as it is now,\n * so each node ends where it was drawn relative to the pointer.\n *\n * The map is read afresh on every call: a camera panning under a held drag, or\n * a plane whose factors are being animated, moves the node with the pointer.\n */\nimport type {\n Action, ActionDeps, AffordanceHit, BindingOpts, DragSample, InvocationCtx, OngoingHandle,\n OngoingOverlay,\n} from '@weasel-js/routing';\nimport type { Scene } from 'core/scene/types';\nimport { asNodeId } from 'core/scene/types';\nimport {\n deriveParallaxView, fromPlane, planeMap, planeToPlane, rectFromPlane, rectToPlane, toPlane,\n type ParallaxOpts, type PlaneMap,\n} from 'core/viewport/parallax';\nimport type { View } from 'core/viewport/view';\nimport type { PoseDescriptor } from 'core/geometry/poseDescriptor';\nimport type { NodeAtPointDep, SnapDep, ViewApi } from './depSchema';\n\ntype Point = { x: number; y: number };\n\n/** Which scene layer an invocation edits, read once as it starts, from its\n * deps and — for a drag — the affordance it grabbed. `undefined` means none:\n * the action runs in the camera's world. */\nexport type EditedLayerOf = (deps: ActionDeps, affordance?: AffordanceHit) => string | undefined;\n\nconst layerOfNode = (deps: ActionDeps, id: string | null | undefined): string | undefined =>\n (id ? deps.scene?.get(asNodeId(id))?.layer : undefined);\n\n/** The layer of the node a selection edit acts on: the affordance's target\n * when the drag grabbed one, the first selected node otherwise. A selection\n * spanning planes is edited in that one node's plane. */\nexport const selectionLayer: EditedLayerOf = (deps, affordance) => {\n const selection = deps.selection;\n for (const id of [...(affordance?.targetIds ?? []), ...(selection?.get() ?? [])]) {\n const layer = layerOfNode(deps, id);\n if (layer !== undefined) return layer;\n }\n return undefined;\n};\n\n/** The layer the `insert` dep will put a new node on. */\nexport const insertLayer: EditedLayerOf = (deps) =>\n deps.insert?.layer?.();\n\n/** The layer of the path in anchor-edit mode. */\nexport const editingLayer: EditedLayerOf = (deps) =>\n layerOfNode(deps, deps.editAnchors?.editingId);\n\n/** How the world an invocation edits in maps into the world `layer`'s nodes\n * are stored in, read now. Null when they are the same world. */\nexport function planeOf(view: unknown, layer: string): PlaneMap | null {\n return (view as ViewApi | undefined)?.planeOf?.(layer) ?? null;\n}\n\n/** `m` run backwards; null stays null. */\nexport function invertPlane(m: PlaneMap | null): PlaneMap | null {\n return m && planeToPlane(m, null);\n}\n\n/** `pose` carried through `m`. The map is axis-aligned, so remapping the\n * pose's bounds carries it exactly when the map scales both axes alike. */\nexport function carryPose<P>(d: PoseDescriptor<P>, pose: P, m: PlaneMap | null): P {\n if (m === null) return pose;\n const b = d.getBounds(pose);\n return d.remapBounds(pose, b, rectToPlane(m, b));\n}\n\n/** `action`, with its input carried into the plane of the layer `layerOf`\n * names. An action in a scene with no `parallax` layer, or invoked with no\n * scene or view to read a plane from, runs exactly as it would unwrapped.\n *\n * An ongoing action's drag is carried as a whole. An immediate one's world\n * point is `params.worldX` / `params.worldY`, the dispatcher's convention for\n * a click; it is carried when present. */\nexport function inPlane<A extends Action>(action: A, layerOf: EditedLayerOf): A {\n const inner = action.invoker;\n if (!inner) return action;\n const declared = action.requires ?? [];\n const requires = [...new Set([...declared, 'scene', 'selection', 'view'])];\n if (inner.timing === 'immediate') {\n return {\n ...action,\n requires,\n invoker: {\n timing: 'immediate',\n run(deps: ActionDeps, params?: Record<string, unknown>): void {\n const plane = livePlane(deps, layerOf(deps), declared, null);\n if (plane === null) return inner.run(deps, params);\n const wx = params?.['worldX'];\n const wy = params?.['worldY'];\n const at = typeof wx === 'number' && typeof wy === 'number'\n ? toPlane(plane.map(), { x: wx, y: wy })\n : null;\n inner.run(plane.deps, at ? { ...params, worldX: at.x, worldY: at.y } : params);\n },\n },\n } as A;\n }\n return {\n ...action,\n requires,\n invoker: {\n timing: 'ongoing',\n start(ctx: InvocationCtx, opts?: BindingOpts): OngoingHandle {\n const plane = livePlane(\n ctx.deps, layerOf(ctx.deps, ctx.drag?.affordance), declared, ctx.drag?.start ?? null,\n );\n if (plane === null) return inner.start(ctx, opts);\n return planeHandle(inner.start(plane.carry(ctx), opts), plane);\n },\n },\n } as A;\n}\n\ninterface LivePlane {\n map(): PlaneMap;\n /** The invocation's deps, speaking the plane's world. */\n deps: ActionDeps;\n /** `ctx` in the plane's world. */\n carry(ctx: InvocationCtx): InvocationCtx;\n}\n\nfunction livePlane(\n bag: ActionDeps,\n layer: string | undefined,\n /** What the wrapped action declared. The dispatcher's dev deps bag throws\n * on any other read, so the seam converts only the deps it can see. */\n declared: readonly string[],\n /** The drag's press point in the camera's world, when there is a drag. */\n pressedAt: Point | null,\n): LivePlane | null {\n const scene = bag.scene as Scene<unknown, string, unknown> | undefined;\n const viewApi = bag.view as ViewApi | undefined;\n if (layer === undefined || !scene || !viewApi) return null;\n if (!scene.layers.some((l) => l.parallax !== undefined)) return null;\n const parallaxOf = (id: string): ParallaxOpts | undefined => scene.layers.find((l) => l.id === id)?.parallax;\n const parallax = (): ParallaxOpts | undefined => parallaxOf(layer);\n\n const IDENTITY: PlaneMap = { scale: { x: 1, y: 1 }, offset: { x: 0, y: 0 } };\n const map = (): PlaneMap => {\n const p = parallax();\n return p ? planeMap(viewApi.get(), p) : IDENTITY;\n };\n\n // A screen-pixel tolerance, and anything else an action reads off the\n // camera, has to be read at the plane's scale.\n const planeView = Object.defineProperties(Object.create(viewApi), {\n get: {\n value: (): View => {\n const p = parallax();\n const camera = viewApi.get();\n return p ? deriveParallaxView(camera, p) : camera;\n },\n },\n plane: { value: map },\n planeOf: {\n value: (id: string): PlaneMap | null => {\n const edited = parallax();\n const own = parallaxOf(id);\n const camera = viewApi.get();\n return planeToPlane(edited ? planeMap(camera, edited) : null, own ? planeMap(camera, own) : null);\n },\n },\n }) as ViewApi;\n\n // Over the dispatcher's bag rather than a copy of it, so every other read\n // still goes through whatever checks the bag makes.\n const deps = Object.create(bag) as typeof bag;\n const override = (name: string, value: unknown) =>\n Object.defineProperty(deps, name, { value, enumerable: true });\n override('view', planeView);\n const nodeAtPoint = declared.includes('nodeAtPoint')\n ? bag.nodeAtPoint as NodeAtPointDep | undefined\n : undefined;\n if (nodeAtPoint) {\n override('nodeAtPoint', ((p, exclude) => nodeAtPoint(fromPlane(map(), p), exclude)) as NodeAtPointDep);\n }\n const snap = declared.includes('snap') ? bag.snap as SnapDep | undefined : undefined;\n if (snap) {\n override('snap', { point: (p: Point) => toPlane(map(), snap.point(fromPlane(map(), p))) } as SnapDep);\n }\n\n // The drag's origin, fixed in the plane at the moment it was pressed: where\n // the pointer went down on the node is where the node was grabbed, whatever\n // the camera does after.\n const start0 = pressedAt ? toPlane(map(), pressedAt) : null;\n const trail = trailCarrier();\n\n return {\n map,\n deps,\n carry(c) {\n const m = map();\n const out: InvocationCtx = { ...c, world: toPlane(m, c.world) };\n if (c.drag) {\n const start = start0 ?? toPlane(m, c.drag.start);\n const current = toPlane(m, c.drag.current);\n const aff = c.drag.affordance;\n out.drag = {\n ...c.drag,\n start,\n current,\n delta: { x: current.x - start.x, y: current.y - start.y },\n ...(c.drag.points ? { points: trail(c.drag.points, m) } : {}),\n ...(aff?.fixedPoint ? { affordance: { ...aff, fixedPoint: toPlane(m, aff.fixedPoint) } } : {}),\n };\n }\n // The dispatcher hands `onMove` no deps; only `start` has any to carry.\n if (c.deps) out.deps = deps;\n return out;\n },\n };\n}\n\n/** The drag trail in the plane. The dispatcher grows its trail in place, so\n * only the samples added since the last call are mapped — unless the map\n * moved, when every sample is. */\nfunction trailCarrier(): (points: DragSample[], m: PlaneMap) => DragSample[] {\n let src: DragSample[] | null = null;\n let lastMap: PlaneMap | null = null;\n let out: DragSample[] = [];\n return (points, m) => {\n const same = lastMap !== null\n && lastMap.scale.x === m.scale.x && lastMap.scale.y === m.scale.y\n && lastMap.offset.x === m.offset.x && lastMap.offset.y === m.offset.y;\n if (points !== src || !same || points.length < out.length) {\n src = points;\n out = [];\n }\n lastMap = m;\n for (let i = out.length; i < points.length; i++) {\n out.push({ ...points[i], ...toPlane(m, points[i]) });\n }\n // A copy, so a snapshot taken on `onEnd` is not the live accumulator.\n return out.slice();\n };\n}\n\nfunction planeHandle(handle: OngoingHandle, plane: LivePlane): OngoingHandle {\n const out: OngoingHandle = { ...handle };\n if (handle.onMove) out.onMove = (c) => handle.onMove!(plane.carry(c));\n if (handle.onEnd) out.onEnd = (c, reason) => handle.onEnd!(plane.carry(c), reason);\n if (handle.overlay) {\n out.overlay = () => {\n const ov = handle.overlay!();\n return ov ? overlayFromPlane(ov, plane.map()) : ov;\n };\n }\n return out;\n}\n\n/** An overlay drawn in the plane, in the camera's world: what every painter\n * reads an overlay as. */\nfunction overlayFromPlane(ov: OngoingOverlay, m: PlaneMap): OngoingOverlay {\n const pt = (p: Point) => fromPlane(m, p);\n switch (ov.kind) {\n case 'marquee':\n return { ...ov, start: pt(ov.start), current: pt(ov.current) };\n case 'lasso':\n return { ...ov, vertices: ov.vertices.map(pt), current: pt(ov.current) };\n case 'polyline':\n return { ...ov, points: ov.points.map(pt) };\n case 'insertPreview':\n return {\n ...ov,\n bounds: rectFromPlane(m, ov.bounds),\n extras: insertExtrasFromPlane(ov.extras, m),\n ...(ov.anchorPoint ? { anchorPoint: pt(ov.anchorPoint) } : {}),\n };\n }\n}\n\n/** The geometry the kit's insert kinds carry in `extras`, in the camera's\n * world. A consumer kind's extras are opaque, and pass through. */\nfunction insertExtrasFromPlane(extras: unknown, m: PlaneMap): unknown {\n if (extras === null || typeof extras !== 'object') return extras;\n const e = extras as Record<string, unknown>;\n const pt = (p: unknown) => fromPlane(m, p as Point);\n // Radial kinds inscribe in a square, so one scale carries a radius.\n const r = (v: unknown) => (typeof v === 'number' ? v / ((m.scale.x + m.scale.y) / 2) : v);\n const out: Record<string, unknown> = { ...e };\n if (e['a'] && e['b']) { out['a'] = pt(e['a']); out['b'] = pt(e['b']); }\n if (e['center']) out['center'] = pt(e['center']);\n if ('radius' in e) out['radius'] = r(e['radius']);\n if ('outerRadius' in e) out['outerRadius'] = r(e['outerRadius']);\n if (Array.isArray(e['samples'])) {\n out['samples'] = (e['samples'] as DragSample[]).map((s) => ({ ...s, ...pt(s) }));\n }\n return out;\n}\n"],"mappings":";;;AA8CA,IAAMA,KAAe,GAAkB,MACpCC,IAAKC,EAAK,OAAO,IAAIC,EAASF,CAAE,CAAC,CAAC,EAAE,QAAQ,KAAA,GAKlCG,KAAiC,GAAM,MAAe;CACjE,IAAMC,IAAYH,EAAK;CACvB,KAAK,IAAMD,KAAM,CAAC,GAAIK,GAAY,aAAa,CAAC,GAAI,GAAID,GAAW,IAAI,KAAK,CAAC,CAAE,GAAG;EAChF,IAAME,IAAQP,EAAYE,GAAMD,CAAE;EAClC,IAAIM,MAAU,KAAA,GAAW,OAAOA;CAClC;AAEF,GAGaC,KAA8B,MACzCN,EAAK,QAAQ,QAAQ,GAGVO,KAA+B,MAC1CT,EAAYE,GAAMA,EAAK,aAAa,SAAS;AAI/C,SAAgBQ,EAAQ,GAAe,GAAgC;CACrE,OAAQC,GAA8B,UAAUJ,CAAK,KAAK;AAC5D;AAGA,SAAgBK,EAAY,GAAqC;CAC/D,OAAOC,KAAKC,EAAaD,GAAG,IAAI;AAClC;AAIA,SAAgBE,EAAa,GAAsB,GAAS,GAAuB;CACjF,IAAIF,MAAM,MAAM,OA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AAO,IAAIE,CAAE;EAAE;EAC5C,KAAK,iBACH,OAAO;GACL,GAAGF;GACH,QAAQG,EAAcjE,GAAG8D,EAAG,MAAM;GAClC,QAAQI,EAAsBJ,EAAG,QAAQ9D,CAAC;GAC1C,GAAI8D,EAAG,cAAc,EAAE,aAAaE,EAAGF,EAAG,WAAW,EAAE,IAAI,CAAC;EAC9D;CACJ;AACF;AAIA,SAASI,EAAsB,GAAiB,GAAsB;CACpE,IAAuB,OAAOC,KAAW,aAArCA,GAA+C,OAAOA;CAC1D,IAAMC,IAAID,GACJH,KAAM,MAAerB,EAAU3C,GAAGiC,CAAU,GAE5CoC,KAAK,MAAgB,OAAOC,KAAM,WAAWA,MAAMtE,EAAE,MAAM,IAAIA,EAAE,MAAM,KAAK,KAAKsE,GACjFpB,IAA+B,EAAE,GAAGkB,EAAE;CAQ5C,OAPIA,EAAEG,KAAQH,EAAEI,MAAQ,EAAID,IAAOP,EAAGI,EAAEG,CAAI,GAAG,EAAIC,IAAOR,EAAGI,EAAEI,CAAI,IAC/DJ,EAAEK,WAAW,EAAIA,SAAYT,EAAGI,EAAEK,MAAS,IAC3C,YAAYL,MAAG,EAAIM,SAAYL,EAAED,EAAEM,MAAS,IAC5C,iBAAiBN,MAAG,EAAIO,cAAiBN,EAAED,EAAEO,WAAc,IAC3D,MAAM,QAAQP,EAAEQ,OAAU,MAC5B,EAAIA,UAAcR,EAAEQ,QAA4B,KAAK,OAAO;EAAE,GAAGC;EAAG,GAAGb,EAAGa,CAAC;CAAE,EAAE,IAE1E3B;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"screenTolerance.js","names":["screenTolerance","view","ctx","pxExtent","px","gestureViewReader","api","deps","gesturePlaneReader"],"sources":["../../../../src/interactions/gestures/shared/screenTolerance.ts"],"sourcesContent":["import type { View } from 'core/viewport/view';\nimport type { PlaneMap } from 'core/viewport/parallax';\nimport { pxExtent } from 'core/viewport/pxExtent';\nimport type { GestureContext } from '../types';\nimport type { ViewApi } from 'interactions/actions/depSchema';\n\n/** A screen-pixel tolerance in world units, per axis, through the camera of\n * the view the gesture landed in. With no view, one pixel is one unit. */\nexport function screenTolerance(\n px: number,\n ctx: Pick<GestureContext<unknown>, 'view'>,\n): { x: number; y: number } {\n const view: View | null = ctx.view;\n return view ? pxExtent(px, view.scale) : { x: px, y: px };\n}\n\n/** Reads the camera the gesture's `deps.view` answers for — the routed\n * view's, when the surface hosts several. Capture it at `start`: the\n * dispatcher hands `onMove` no deps. */\nexport function gestureViewReader(deps: { view?: unknown }): () => View | null {\n const api = deps.view as ViewApi | undefined;\n return () => api?.get() ?? null;\n}\n\n/** Reads the plane the gesture edits in, off the same `deps.view` — see\n * `ViewApi.plane`. Null in the camera's own world. */\nexport function gesturePlaneReader(deps: { view?: unknown }): () => PlaneMap | null {\n const api = deps.view as ViewApi | undefined;\n return () => api?.plane?.() ?? null;\n}\n"],"mappings":";;AAQA,SAAgBA,EACd,GACA,GAC0B;CAC1B,IAAMC,IAAoBC,EAAI;CAC9B,OAAOD,IAAOE,EAASC,GAAIH,EAAK,KAAK,IAAI;EAAE,GAAGG;EAAI,GAAGA;CAAG;AAC1D;AAKA,SAAgBC,EAAkB,GAA6C;CAC7E,IAAMC,IAAMC,EAAK;CACjB,aAAaD,GAAK,IAAI,KAAK;AAC7B;AAIA,SAAgBE,EAAmB,GAAiD;CAClF,IAAMF,IAAMC,EAAK;CACjB,aAAaD,GAAK,QAAQ,KAAK;AACjC"}
1
+ {"version":3,"file":"screenTolerance.js","names":["screenTolerance","view","ctx","pxExtent","px","gestureViewReader","api","deps","gesturePlaneReader"],"sources":["../../../../src/interactions/gestures/shared/screenTolerance.ts"],"sourcesContent":["import type { View } from 'core/viewport/view';\nimport type { PlaneMap } from 'core/viewport/parallax';\nimport { pxExtent } from 'core/viewport/pxExtent';\nimport type { GestureContext } from '../types';\nimport type { ActionDeps } from '@weasel-js/routing';\n\n/** A screen-pixel tolerance in world units, per axis, through the camera of\n * the view the gesture landed in. With no view, one pixel is one unit. */\nexport function screenTolerance(\n px: number,\n ctx: Pick<GestureContext<unknown>, 'view'>,\n): { x: number; y: number } {\n const view: View | null = ctx.view;\n return view ? pxExtent(px, view.scale) : { x: px, y: px };\n}\n\n/** Reads the camera the gesture's `deps.view` answers for — the routed\n * view's, when the surface hosts several. Capture it at `start`: the\n * dispatcher hands `onMove` no deps. */\nexport function gestureViewReader(deps: Pick<ActionDeps, 'view'>): () => View | null {\n const api = deps.view;\n return () => api?.get() ?? null;\n}\n\n/** Reads the plane the gesture edits in, off the same `deps.view` — see\n * `ViewApi.plane`. Null in the camera's own world. */\nexport function gesturePlaneReader(deps: Pick<ActionDeps, 'view'>): () => PlaneMap | null {\n const api = deps.view;\n return () => api?.plane?.() ?? null;\n}\n"],"mappings":";;AAQA,SAAgBA,EACd,GACA,GAC0B;CAC1B,IAAMC,IAAoBC,EAAI;CAC9B,OAAOD,IAAOE,EAASC,GAAIH,EAAK,KAAK,IAAI;EAAE,GAAGG;EAAI,GAAGA;CAAG;AAC1D;AAKA,SAAgBC,EAAkB,GAAmD;CACnF,IAAMC,IAAMC,EAAK;CACjB,aAAaD,GAAK,IAAI,KAAK;AAC7B;AAIA,SAAgBE,EAAmB,GAAuD;CACxF,IAAMF,IAAMC,EAAK;CACjB,aAAaD,GAAK,QAAQ,KAAK;AACjC"}
@@ -50,6 +50,9 @@ declare function screenToClip(width: number, height: number): GlMat3;
50
50
  * axes and exact on neither — the same compromise `meanScale` documents.
51
51
  */
52
52
  declare function meanScaleOf(m: GlMat3): number;
53
+ /** The least any direction is scaled by the linear part — its smaller singular
54
+ * value. What a screen length is worth in world units, at most. */
55
+ declare function minScaleOf(m: GlMat3): number;
53
56
  /** The renderer's 3x3 matrix operations, as one namespace. These work on the
54
57
  * 9-element `Float32Array` form the GL uniform upload wants — distinct from
55
58
  * `@weasel-js/geom`'s 6-element affine `GlMat3`, though the logical element
@@ -65,6 +68,7 @@ declare const mat3: {
65
68
  apply: typeof apply;
66
69
  screenToClip: typeof screenToClip;
67
70
  meanScaleOf: typeof meanScaleOf;
71
+ minScaleOf: typeof minScaleOf;
68
72
  };
69
73
 
70
74
  /**
@@ -1,59 +1,63 @@
1
- import { getMarker as e, markerGeneration as t } from "../../core/strokeMarkers.js";
2
- import { markerKeyOf as n } from "../../core/markerInset.js";
3
- import { STROKE_CONFIGS_PER_PATH as r } from "./strokeMeshCache.js";
4
- import { headCommands as i, markerHeads as a, markerReadsKey as o } from "../../features/paths/markerCommands.js";
1
+ import { screenSpaceKey as e } from "../../features/paths/tessellate/metric.js";
2
+ import { getMarker as t, markerGeneration as n } from "../../core/strokeMarkers.js";
3
+ import { markerKeyOf as r } from "../../core/markerInset.js";
4
+ import { STROKE_CONFIGS_PER_PATH as i } from "./strokeMeshCache.js";
5
+ import { headCommands as a, markerHeads as o, markerReadsKey as s } from "../../features/paths/markerCommands.js";
5
6
  //#region src/renderer/cache/markerCommandCache.ts
6
- var s = /* @__PURE__ */ new WeakMap(), c = /* @__PURE__ */ new WeakMap(), l = (e) => e === void 0 ? "" : typeof e == "string" ? e : `${e.key}@${String(e.size ?? "")}`;
7
- function u(t) {
8
- let r = "";
7
+ var c = /* @__PURE__ */ new WeakMap(), l = /* @__PURE__ */ new WeakMap(), u = (e) => e === void 0 ? "" : typeof e == "string" ? e : `${e.key}@${String(e.size ?? "")}`;
8
+ function d(e) {
9
+ let n = "";
9
10
  for (let i of [
10
- t.markerStart,
11
- t.markerMid,
12
- t.markerEnd
11
+ e.markerStart,
12
+ e.markerMid,
13
+ e.markerEnd
13
14
  ]) {
14
- let a = i === void 0 ? void 0 : e(n(i));
15
+ let a = i === void 0 ? void 0 : t(r(i));
15
16
  if (a === void 0) {
16
- r += "/";
17
+ n += "/";
17
18
  continue;
18
19
  }
19
- let s = o(a, t);
20
- if (s === null) return null;
21
- r += `${s}/`;
20
+ let o = s(a, e);
21
+ if (o === null) return null;
22
+ n += `${o}/`;
22
23
  }
23
- return r;
24
+ return n;
24
25
  }
25
- function d(e, t, n) {
26
+ function f(e, t, n) {
26
27
  if (n !== null) {
27
- let t = s.get(e);
28
- return t === void 0 && s.set(e, t = /* @__PURE__ */ new Map()), t;
28
+ let t = c.get(e);
29
+ return t === void 0 && c.set(e, t = /* @__PURE__ */ new Map()), t;
29
30
  }
30
- let r = c.get(e);
31
- r === void 0 && c.set(e, r = /* @__PURE__ */ new WeakMap());
31
+ let r = l.get(e);
32
+ r === void 0 && l.set(e, r = /* @__PURE__ */ new WeakMap());
32
33
  let i = r.get(t);
33
34
  return i === void 0 && r.set(t, i = /* @__PURE__ */ new Map()), i;
34
35
  }
35
- function f(e, n, o, s, c) {
36
- if (o.markerStart === void 0 && o.markerMid === void 0 && o.markerEnd === void 0) return [];
37
- let f = u(o), p = d(e, n, f), m = [
38
- s,
39
- c ?? "",
40
- t(),
41
- l(o.markerStart),
42
- l(o.markerMid),
43
- l(o.markerEnd),
44
- f ?? ""
45
- ].join("|"), h = p.get(m);
46
- if (h === void 0) {
47
- let t = a(e, o, s, c);
48
- h = {
49
- heads: t,
50
- paint: o.paint,
51
- cmds: i(t, o)
52
- }, p.size >= r && p.clear(), p.set(m, h);
53
- } else h.paint !== o.paint && (h.paint = o.paint, h.cmds = i(h.heads, o));
54
- return h.cmds;
36
+ function p(t, r, s, c, l, p = {}) {
37
+ if (s.markerStart === void 0 && s.markerMid === void 0 && s.markerEnd === void 0) return [];
38
+ let m = d(s), h = f(t, r, m), g = [
39
+ c,
40
+ l ?? "",
41
+ n(),
42
+ u(s.markerStart),
43
+ u(s.markerMid),
44
+ u(s.markerEnd),
45
+ m ?? "",
46
+ e(p.start),
47
+ e(p.mid),
48
+ e(p.end)
49
+ ].join("|"), _ = h.get(g);
50
+ if (_ === void 0) {
51
+ let e = o(t, s, c, l, p);
52
+ _ = {
53
+ heads: e,
54
+ paint: s.paint,
55
+ cmds: a(e, s)
56
+ }, h.size >= i && h.clear(), h.set(g, _);
57
+ } else _.paint !== s.paint && (_.paint = s.paint, _.cmds = a(_.heads, s));
58
+ return _.cmds;
55
59
  }
56
60
  //#endregion
57
- export { f as cachedMarkerCommands };
61
+ export { p as cachedMarkerCommands };
58
62
 
59
63
  //# sourceMappingURL=markerCommandCache.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"markerCommandCache.js","names":["byValue","byStroke","refKey","ref","readsKey","key","stroke","entry","getMarker","markerKeyOf","reads","markerReadsKey","mapFor","map","path","strokes","source","cachedMarkerCommands","strokeWidth","flattenTolerance","markerGeneration","heads","markerHeads","headCommands","STROKE_CONFIGS_PER_PATH"],"sources":["../../../src/renderer/cache/markerCommandCache.ts"],"sourcesContent":["/**\n * A stroke's marker commands, cached per path. The placed head is a fresh\n * `Path`, and the fill cache keys on path identity — so rebuilding it every\n * frame would re-tessellate and re-upload every head every frame.\n *\n * Keyed on value, so a painter that builds a new stroke object every frame\n * still hits: the resolved lengths, the flatten tolerance, the registry's\n * generation, the marker refs and whatever fields each head declares it reads.\n * A head that does not declare them may read any field, so for it the stroke\n * as the command carried it — before any `{ px }` length was resolved — joins\n * the key by identity. Paint is applied over the cached geometry, so a new\n * paint reuses the heads.\n */\n\nimport type { Path } from '@weasel-js/core';\nimport type { FillStyle, MarkerRef, Stroke } from '@weasel-js/paint';\nimport type { PathDrawCommand } from '../DrawCommand';\nimport {\n headCommands, markerHeads, markerReadsKey, type MarkerHead,\n} from 'features/paths/markerCommands';\nimport { getMarker, markerGeneration } from '../../core/strokeMarkers';\nimport { markerKeyOf } from '../../core/markerInset';\nimport { STROKE_CONFIGS_PER_PATH } from './strokeMeshCache';\n\ninterface Entry {\n readonly heads: MarkerHead[];\n paint: FillStyle | undefined;\n cmds: PathDrawCommand[];\n}\n\nlet byValue = new WeakMap<Path, Map<string, Entry>>();\nlet byStroke = new WeakMap<Path, WeakMap<Stroke, Map<string, Entry>>>();\n\nconst refKey = (ref: MarkerRef | undefined): string =>\n ref === undefined ? '' : typeof ref === 'string' ? ref : `${ref.key}@${String(ref.size ?? '')}`;\n\n/** What every head of `stroke` reads, or `null` if any head does not say. */\nfunction readsKey(stroke: Stroke): string | null {\n let key = '';\n for (const ref of [stroke.markerStart, stroke.markerMid, stroke.markerEnd]) {\n const entry = ref === undefined ? undefined : getMarker(markerKeyOf(ref));\n if (entry === undefined) {\n key += '/';\n continue;\n }\n const reads = markerReadsKey(entry, stroke);\n if (reads === null) return null;\n key += `${reads}/`;\n }\n return key;\n}\n\nfunction mapFor(path: Path, source: Stroke, reads: string | null): Map<string, Entry> {\n if (reads !== null) {\n let map = byValue.get(path);\n if (map === undefined) byValue.set(path, (map = new Map()));\n return map;\n }\n let strokes = byStroke.get(path);\n if (strokes === undefined) byStroke.set(path, (strokes = new WeakMap()));\n let map = strokes.get(source);\n if (map === undefined) strokes.set(source, (map = new Map()));\n return map;\n}\n\n/**\n * The marker commands for `path` under `stroke`, whose lengths are already\n * resolved to world units. `source` is the stroke before that resolution.\n */\nexport function cachedMarkerCommands(\n path: Path,\n source: Stroke,\n stroke: Stroke,\n strokeWidth: number,\n flattenTolerance: number | undefined,\n): PathDrawCommand[] {\n if (stroke.markerStart === undefined && stroke.markerMid === undefined && stroke.markerEnd === undefined) {\n return [];\n }\n const reads = readsKey(stroke);\n const map = mapFor(path, source, reads);\n const key = [\n strokeWidth,\n flattenTolerance ?? '',\n markerGeneration(),\n refKey(stroke.markerStart),\n refKey(stroke.markerMid),\n refKey(stroke.markerEnd),\n reads ?? '',\n ].join('|');\n let entry = map.get(key);\n if (entry === undefined) {\n const heads = markerHeads(path, stroke, strokeWidth, flattenTolerance);\n entry = { heads, paint: stroke.paint, cmds: headCommands(heads, stroke) };\n if (map.size >= STROKE_CONFIGS_PER_PATH) map.clear();\n map.set(key, entry);\n } else if (entry.paint !== stroke.paint) {\n entry.paint = stroke.paint;\n entry.cmds = headCommands(entry.heads, stroke);\n }\n return entry.cmds;\n}\n\n/** Test helper. Do not call from product code. */\nexport function _resetMarkerCommandCacheForTests(): void {\n byValue = new WeakMap();\n byStroke = new WeakMap();\n}\n"],"mappings":";;;;;AA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,IAAM;EACVa;EACAC,KAAoB;EACpBC,EAAiB;EACjBlB,EAAOI,EAAO,WAAW;EACzBJ,EAAOI,EAAO,SAAS;EACvBJ,EAAOI,EAAO,SAAS;EACvBI,KAAS;CACX,CAAC,CAAC,KAAK,GAAG,GACNH,IAAQM,EAAI,IAAIR,CAAG;CACvB,IAAIE,MAAU,KAAA,GAAW;EACvB,IAAMc,IAAQC,EAAYR,GAAMR,GAAQY,GAAaC,CAAgB;EAGrE,AAFA,IAAQ;GAAE;GAAO,OAAOb,EAAO;GAAO,MAAMiB,EAAaF,GAAOf,CAAM;EAAE,GACpEO,EAAI,QAAQW,KAAyBX,EAAI,MAAM,GACnDA,EAAI,IAAIR,GAAKE,CAAK;CACpB,OAAO,AAAIA,EAAM,UAAUD,EAAO,UAChC,EAAM,QAAQA,EAAO,OACrB,EAAM,OAAOiB,EAAahB,EAAM,OAAOD,CAAM;CAE/C,OAAOC,EAAM;AACf"}
1
+ {"version":3,"file":"markerCommandCache.js","names":["byValue","byStroke","refKey","ref","readsKey","key","stroke","entry","getMarker","markerKeyOf","reads","markerReadsKey","mapFor","map","path","strokes","source","cachedMarkerCommands","strokeWidth","flattenTolerance","markerGeneration","screenSpaceKey","spaces","heads","markerHeads","headCommands","STROKE_CONFIGS_PER_PATH"],"sources":["../../../src/renderer/cache/markerCommandCache.ts"],"sourcesContent":["/**\n * A stroke's marker commands, cached per path. The placed head is a fresh\n * `Path`, and the fill cache keys on path identity — so rebuilding it every\n * frame would re-tessellate and re-upload every head every frame.\n *\n * Keyed on value, so a painter that builds a new stroke object every frame\n * still hits: the resolved lengths, the flatten tolerance, the registry's\n * generation, the marker refs and whatever fields each head declares it reads.\n * A head that does not declare them may read any field, so for it the stroke\n * as the command carried it — before any `{ px }` length was resolved — joins\n * the key by identity. Paint is applied over the cached geometry, so a new\n * paint reuses the heads.\n */\n\nimport type { Path } from '@weasel-js/core';\nimport type { FillStyle, MarkerRef, Stroke } from '@weasel-js/paint';\nimport type { PathDrawCommand } from '../DrawCommand';\nimport {\n headCommands, markerHeads, markerReadsKey, type MarkerHead,\n} from 'features/paths/markerCommands';\nimport { getMarker, markerGeneration } from '../../core/strokeMarkers';\nimport { markerKeyOf } from '../../core/markerInset';\nimport { STROKE_CONFIGS_PER_PATH } from './strokeMeshCache';\nimport { screenSpaceKey, type StrokeSpaces } from 'features/paths/tessellate/metric';\n\ninterface Entry {\n readonly heads: MarkerHead[];\n paint: FillStyle | undefined;\n cmds: PathDrawCommand[];\n}\n\nlet byValue = new WeakMap<Path, Map<string, Entry>>();\nlet byStroke = new WeakMap<Path, WeakMap<Stroke, Map<string, Entry>>>();\n\nconst refKey = (ref: MarkerRef | undefined): string =>\n ref === undefined ? '' : typeof ref === 'string' ? ref : `${ref.key}@${String(ref.size ?? '')}`;\n\n/** What every head of `stroke` reads, or `null` if any head does not say. */\nfunction readsKey(stroke: Stroke): string | null {\n let key = '';\n for (const ref of [stroke.markerStart, stroke.markerMid, stroke.markerEnd]) {\n const entry = ref === undefined ? undefined : getMarker(markerKeyOf(ref));\n if (entry === undefined) {\n key += '/';\n continue;\n }\n const reads = markerReadsKey(entry, stroke);\n if (reads === null) return null;\n key += `${reads}/`;\n }\n return key;\n}\n\nfunction mapFor(path: Path, source: Stroke, reads: string | null): Map<string, Entry> {\n if (reads !== null) {\n let map = byValue.get(path);\n if (map === undefined) byValue.set(path, (map = new Map()));\n return map;\n }\n let strokes = byStroke.get(path);\n if (strokes === undefined) byStroke.set(path, (strokes = new WeakMap()));\n let map = strokes.get(source);\n if (map === undefined) strokes.set(source, (map = new Map()));\n return map;\n}\n\n/**\n * The marker commands for `path` under `stroke`, whose lengths are already\n * resolved. `source` is the stroke before that resolution. A head's lengths are\n * in the space `spaces` builds it in.\n */\nexport function cachedMarkerCommands(\n path: Path,\n source: Stroke,\n stroke: Stroke,\n strokeWidth: number,\n flattenTolerance: number | undefined,\n spaces: StrokeSpaces = {},\n): PathDrawCommand[] {\n if (stroke.markerStart === undefined && stroke.markerMid === undefined && stroke.markerEnd === undefined) {\n return [];\n }\n const reads = readsKey(stroke);\n const map = mapFor(path, source, reads);\n const key = [\n strokeWidth,\n flattenTolerance ?? '',\n markerGeneration(),\n refKey(stroke.markerStart),\n refKey(stroke.markerMid),\n refKey(stroke.markerEnd),\n reads ?? '',\n screenSpaceKey(spaces.start),\n screenSpaceKey(spaces.mid),\n screenSpaceKey(spaces.end),\n ].join('|');\n let entry = map.get(key);\n if (entry === undefined) {\n const heads = markerHeads(path, stroke, strokeWidth, flattenTolerance, spaces);\n entry = { heads, paint: stroke.paint, cmds: headCommands(heads, stroke) };\n if (map.size >= STROKE_CONFIGS_PER_PATH) map.clear();\n map.set(key, entry);\n } else if (entry.paint !== stroke.paint) {\n entry.paint = stroke.paint;\n entry.cmds = headCommands(entry.heads, stroke);\n }\n return entry.cmds;\n}\n\n/** Test helper. Do not call from product code. */\nexport function _resetMarkerCommandCacheForTests(): void {\n byValue = new WeakMap();\n byStroke = new WeakMap();\n}\n"],"mappings":";;;;;;AA+BA,IAAIA,oBAAU,IAAI,QAAkC,GAChDC,oBAAW,IAAI,QAAmD,GAEhEC,KAAU,MACdC,MAAQ,KAAA,IAAY,KAAK,OAAOA,KAAQ,WAAWA,IAAM,GAAGA,EAAI,IAAI,GAAG,OAAOA,EAAI,QAAQ,EAAE;AAG9F,SAASC,EAAS,GAA+B;CAC/C,IAAIC,IAAM;CACV,KAAK,IAAMF,KAAO;EAACG,EAAO;EAAaA,EAAO;EAAWA,EAAO;CAAS,GAAG;EAC1E,IAAMC,IAAQJ,MAAQ,KAAA,IAAY,KAAA,IAAYK,EAAUC,EAAYN,CAAG,CAAC;EACxE,IAAII,MAAU,KAAA,GAAW;GACvB,KAAO;GACP;EACF;EACA,IAAMG,IAAQC,EAAeJ,GAAOD,CAAM;EAC1C,IAAII,MAAU,MAAM,OAAO;EAC3B,KAAO,GAAGA,EAAM;CAClB;CACA,OAAOL;AACT;AAEA,SAASO,EAAO,GAAY,GAAgB,GAA0C;CAC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AAM,QAAQA,EAAO,OACrB,EAAM,OAAOmB,EAAalB,EAAM,OAAOD,CAAM;CAE/C,OAAOC,EAAM;AACf"}
@@ -1,31 +1,36 @@
1
- import { tessellateStroke as e } from "../../features/paths/tessellate/stroke.js";
2
- import { OUTLINE_FLATTEN_TOLERANCE as t } from "./outlineMeshCache.js";
3
- import { pathFromD as n } from "@weasel-js/geom";
1
+ import { metricKey as e } from "../../features/paths/tessellate/metric.js";
2
+ import { tessellateStroke as t } from "../../features/paths/tessellate/stroke.js";
3
+ import { OUTLINE_FLATTEN_TOLERANCE as n } from "./outlineMeshCache.js";
4
+ import { pathFromD as r } from "@weasel-js/geom";
4
5
  //#region src/renderer/cache/outlineStrokeMeshCache.ts
5
- var r = 2048, i = 1 / 1024, a = /* @__PURE__ */ new Map();
6
- function o(e) {
7
- return Math.round(e / i) * i;
6
+ var i = 2048, a = 1 / 1024, o = /* @__PURE__ */ new Map();
7
+ function s(e) {
8
+ return Math.round(e / a) * a;
8
9
  }
9
- function s(i, o, s, c) {
10
- if (!(s > 0)) return null;
11
- let l = [
12
- i,
13
- s,
14
- c.join ?? "miter",
15
- c.cap ?? "butt",
16
- c.miterLimit ?? "",
17
- c.align ?? "center",
18
- (c.dash ?? []).join(",")
19
- ].join("|"), u = a.get(l);
20
- if (u !== void 0) return u.indices.length === 0 ? null : u;
21
- a.size >= r && (a = /* @__PURE__ */ new Map());
22
- let d = e(n(o), {
23
- ...c,
24
- width: s
25
- }, { flattenTolerance: t });
26
- return a.set(l, d), d.indices.length === 0 ? null : d;
10
+ function c(a, s, c, l, u) {
11
+ if (!(c > 0)) return null;
12
+ let d = [
13
+ a,
14
+ c,
15
+ l.join ?? "miter",
16
+ l.cap ?? "butt",
17
+ l.miterLimit ?? "",
18
+ l.align ?? "center",
19
+ (l.dash ?? []).join(","),
20
+ e(u)
21
+ ].join("|"), f = o.get(d);
22
+ if (f !== void 0) return f.indices.length === 0 ? null : f;
23
+ o.size >= i && (o = /* @__PURE__ */ new Map());
24
+ let p = t(r(s), {
25
+ ...l,
26
+ width: c
27
+ }, {
28
+ flattenTolerance: n,
29
+ metric: u
30
+ });
31
+ return o.set(d, p), p.indices.length === 0 ? null : p;
27
32
  }
28
33
  //#endregion
29
- export { r as OUTLINE_STROKE_MESH_CACHE_LIMIT, s as outlineStrokeMesh, o as quantizeEmWidth };
34
+ export { i as OUTLINE_STROKE_MESH_CACHE_LIMIT, c as outlineStrokeMesh, s as quantizeEmWidth };
30
35
 
31
36
  //# sourceMappingURL=outlineStrokeMeshCache.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"outlineStrokeMeshCache.js","names":["OUTLINE_STROKE_MESH_CACHE_LIMIT","WIDTH_QUANTUM","cache","quantizeEmWidth","emWidth","outlineStrokeMesh","key","glyphKey","stroke","cached","mesh","tessellateStroke","pathFromD","d","OUTLINE_FLATTEN_TOLERANCE"],"sources":["../../../src/renderer/cache/outlineStrokeMeshCache.ts"],"sourcesContent":["/**\n * Tessellated glyph *outlines' strokes*, in em space.\n *\n * The sibling of `outlineMeshCache`, and cached for the same reason: parsing\n * `d` and tessellating a ribbon costs far more than the per-instance\n * transform that follows, and em space is size- and position-independent, so\n * one tessellation serves every occurrence of that glyph.\n *\n * ### Why the width is in the key\n *\n * A fill mesh is the same triangles at every size. A stroke's is not — the\n * ribbon's width relative to the glyph decides the geometry, so the em-space\n * mesh depends on `strokeWidth / fontSize`. That ratio is a property of the\n * run's style, not of the frame, so it is stable across frames and makes a\n * perfectly good cache key; what it is *not* is free, so a document that\n * animates stroke width or font size will miss every frame. That is the same\n * bargain `tessellate` makes everywhere else, and it is the reason the width\n * is quantized before it reaches the key: neighbouring sub-quantum widths\n * would otherwise each get their own entry and evict each other.\n *\n * Joins, caps, miter limit, alignment and dash all change the ribbon too, so\n * they are in the key as well — assembled by the caller, which already has\n * the `Stroke` in hand.\n */\n\nimport { pathFromD } from '@weasel-js/geom';\nimport { tessellateStroke } from 'features/paths/tessellate/stroke';\nimport type { Stroke } from '@weasel-js/paint';\nimport type { Mesh } from '@weasel-js/geom/tessellate';\nimport { OUTLINE_FLATTEN_TOLERANCE } from './outlineMeshCache';\n\n/** Cached ribbons before the cache is dropped wholesale. Matches the fill\n * cache's cap: the working set is a charset times the handful of stroke\n * widths a document actually uses. */\nexport const OUTLINE_STROKE_MESH_CACHE_LIMIT = 2048;\n\n/**\n * Em-width quantum. 1/1024 em is finer than any width a reader can\n * distinguish at the sizes this tier serves — a 0.001 em difference is a\n * fifth of a screen pixel on 200px text — and coarse enough that a slider\n * dragged across a range lands on a bounded set of keys.\n */\nconst WIDTH_QUANTUM = 1 / 1024;\n\nlet cache = new Map<string, Mesh>();\n\n/** Quantized em width, exported so the key builder and the tessellator agree\n * on the number rather than each rounding for themselves. */\nexport function quantizeEmWidth(emWidth: number): number {\n return Math.round(emWidth / WIDTH_QUANTUM) * WIDTH_QUANTUM;\n}\n\n/**\n * The em-space stroke tessellation of one glyph.\n *\n * `glyphKey` identifies the glyph (face identity plus codepoint, assembled by\n * `layoutRuns`); `emWidth` is the stroke width divided by the run's font\n * size, already quantized. `d` is only read on a miss.\n *\n * Returns `null` when the ribbon has no area — a zero or negative width, or a\n * glyph whose path is empty (a space).\n */\nexport function outlineStrokeMesh(\n glyphKey: string,\n d: string,\n emWidth: number,\n stroke: Stroke,\n): Mesh | null {\n if (!(emWidth > 0)) return null;\n const key = [\n glyphKey, emWidth, stroke.join ?? 'miter', stroke.cap ?? 'butt',\n stroke.miterLimit ?? '', stroke.align ?? 'center', (stroke.dash ?? []).join(','),\n ].join('|');\n\n const cached = cache.get(key);\n if (cached !== undefined) return cached.indices.length === 0 ? null : cached;\n if (cache.size >= OUTLINE_STROKE_MESH_CACHE_LIMIT) cache = new Map();\n\n const mesh = tessellateStroke(\n pathFromD(d),\n { ...stroke, width: emWidth },\n { flattenTolerance: OUTLINE_FLATTEN_TOLERANCE },\n );\n cache.set(key, mesh);\n return mesh.indices.length === 0 ? null : mesh;\n}\n\n/** Test helper. Do not call from product code. */\nexport function _resetOutlineStrokeMeshCacheForTests(): void {\n cache = new Map();\n}\n"],"mappings":";;;;AAkCA,IAAaA,IAAkC,MAQzCC,IAAgB,IAAI,MAEtBC,oBAAQ,IAAI,IAAkB;AAIlC,SAAgBC,EAAgB,GAAyB;CACvD,OAAO,KAAK,MAAMC,IAAUH,CAAa,IAAIA;AAC/C;AAYA,SAAgBI,EACd,GACA,GACA,GACA,GACa;CACb,IAAI,EAAED,IAAU,IAAI,OAAO;CAC3B,IAAME,IAAM;EACVC;EAAUH;EAASI,EAAO,QAAQ;EAASA,EAAO,OAAO;EACzDA,EAAO,cAAc;EAAIA,EAAO,SAAS;GAAWA,EAAO,QAAQ,CAAC,EAAA,CAAG,KAAK,GAAG;CACjF,CAAC,CAAC,KAAK,GAAG,GAEJC,IAASP,EAAM,IAAII,CAAG;CAC5B,IAAIG,MAAW,KAAA,GAAW,OAAOA,EAAO,QAAQ,WAAW,IAAI,OAAOA;CACtE,AAAIP,EAAM,QAAQF,MAAiC,oBAAQ,IAAI,IAAI;CAEnE,IAAMU,IAAOC,EACXC,EAAUC,CAAC,GACX;EAAE,GAAGL;EAAQ,OAAOJ;CAAQ,GAC5B,EAAE,kBAAkBU,EAA0B,CAChD;CAEA,OADAZ,EAAM,IAAII,GAAKI,CAAI,GACZA,EAAK,QAAQ,WAAW,IAAI,OAAOA;AAC5C"}
1
+ {"version":3,"file":"outlineStrokeMeshCache.js","names":["OUTLINE_STROKE_MESH_CACHE_LIMIT","WIDTH_QUANTUM","cache","quantizeEmWidth","emWidth","outlineStrokeMesh","key","glyphKey","stroke","metricKey","metric","cached","mesh","tessellateStroke","pathFromD","d","OUTLINE_FLATTEN_TOLERANCE"],"sources":["../../../src/renderer/cache/outlineStrokeMeshCache.ts"],"sourcesContent":["/**\n * Tessellated glyph *outlines' strokes*, in em space.\n *\n * The sibling of `outlineMeshCache`, and cached for the same reason: parsing\n * `d` and tessellating a ribbon costs far more than the per-instance\n * transform that follows, and em space is size- and position-independent, so\n * one tessellation serves every occurrence of that glyph.\n *\n * ### Why the width is in the key\n *\n * A fill mesh is the same triangles at every size. A stroke's is not — the\n * ribbon's width relative to the glyph decides the geometry, so the em-space\n * mesh depends on `strokeWidth / fontSize`. That ratio is a property of the\n * run's style, not of the frame, so it is stable across frames and makes a\n * perfectly good cache key; what it is *not* is free, so a document that\n * animates stroke width or font size will miss every frame. That is the same\n * bargain `tessellate` makes everywhere else, and it is the reason the width\n * is quantized before it reaches the key: neighbouring sub-quantum widths\n * would otherwise each get their own entry and evict each other.\n *\n * Joins, caps, miter limit, alignment and dash all change the ribbon too, so\n * they are in the key as well — assembled by the caller, which already has\n * the `Stroke` in hand.\n */\n\nimport { pathFromD } from '@weasel-js/geom';\nimport { tessellateStroke } from 'features/paths/tessellate/stroke';\nimport { metricKey, type StrokeMetric } from 'features/paths/tessellate/metric';\nimport type { Stroke } from '@weasel-js/paint';\nimport type { Mesh } from '@weasel-js/geom/tessellate';\nimport { OUTLINE_FLATTEN_TOLERANCE } from './outlineMeshCache';\n\n/** Cached ribbons before the cache is dropped wholesale. Matches the fill\n * cache's cap: the working set is a charset times the handful of stroke\n * widths a document actually uses. */\nexport const OUTLINE_STROKE_MESH_CACHE_LIMIT = 2048;\n\n/**\n * Em-width quantum. 1/1024 em is finer than any width a reader can\n * distinguish at the sizes this tier serves — a 0.001 em difference is a\n * fifth of a screen pixel on 200px text — and coarse enough that a slider\n * dragged across a range lands on a bounded set of keys.\n */\nconst WIDTH_QUANTUM = 1 / 1024;\n\nlet cache = new Map<string, Mesh>();\n\n/** Quantized em width, exported so the key builder and the tessellator agree\n * on the number rather than each rounding for themselves. */\nexport function quantizeEmWidth(emWidth: number): number {\n return Math.round(emWidth / WIDTH_QUANTUM) * WIDTH_QUANTUM;\n}\n\n/**\n * The em-space stroke tessellation of one glyph.\n *\n * `glyphKey` identifies the glyph (face identity plus codepoint, assembled by\n * `layoutRuns`); `emWidth` is the stroke width in em, already quantized, and\n * `stroke`'s dashes are in em too. Given a `metric`, the ribbon is built in its\n * space and both are lengths there. `d` is only read on a miss.\n *\n * Returns `null` when the ribbon has no area — a zero or negative width, or a\n * glyph whose path is empty (a space).\n */\nexport function outlineStrokeMesh(\n glyphKey: string,\n d: string,\n emWidth: number,\n stroke: Stroke,\n metric?: StrokeMetric,\n): Mesh | null {\n if (!(emWidth > 0)) return null;\n const key = [\n glyphKey, emWidth, stroke.join ?? 'miter', stroke.cap ?? 'butt',\n stroke.miterLimit ?? '', stroke.align ?? 'center', (stroke.dash ?? []).join(','),\n metricKey(metric),\n ].join('|');\n\n const cached = cache.get(key);\n if (cached !== undefined) return cached.indices.length === 0 ? null : cached;\n if (cache.size >= OUTLINE_STROKE_MESH_CACHE_LIMIT) cache = new Map();\n\n const mesh = tessellateStroke(\n pathFromD(d),\n { ...stroke, width: emWidth },\n { flattenTolerance: OUTLINE_FLATTEN_TOLERANCE, metric },\n );\n cache.set(key, mesh);\n return mesh.indices.length === 0 ? null : mesh;\n}\n\n/** Test helper. Do not call from product code. */\nexport function _resetOutlineStrokeMeshCacheForTests(): void {\n cache = new Map();\n}\n"],"mappings":";;;;;AAmCA,IAAaA,IAAkC,MAQzCC,IAAgB,IAAI,MAEtBC,oBAAQ,IAAI,IAAkB;AAIlC,SAAgBC,EAAgB,GAAyB;CACvD,OAAO,KAAK,MAAMC,IAAUH,CAAa,IAAIA;AAC/C;AAaA,SAAgBI,EACd,GACA,GACA,GACA,GACA,GACa;CACb,IAAI,EAAED,IAAU,IAAI,OAAO;CAC3B,IAAME,IAAM;EACVC;EAAUH;EAASI,EAAO,QAAQ;EAASA,EAAO,OAAO;EACzDA,EAAO,cAAc;EAAIA,EAAO,SAAS;GAAWA,EAAO,QAAQ,CAAC,EAAA,CAAG,KAAK,GAAG;EAC/EC,EAAUC,CAAM;CAClB,CAAC,CAAC,KAAK,GAAG,GAEJC,IAAST,EAAM,IAAII,CAAG;CAC5B,IAAIK,MAAW,KAAA,GAAW,OAAOA,EAAO,QAAQ,WAAW,IAAI,OAAOA;CACtE,AAAIT,EAAM,QAAQF,MAAiC,oBAAQ,IAAI,IAAI;CAEnE,IAAMY,IAAOC,EACXC,EAAUC,CAAC,GACX;EAAE,GAAGP;EAAQ,OAAOJ;CAAQ,GAC5B;EAAE,kBAAkBY;EAA2B;CAAO,CACxD;CAEA,OADAd,EAAM,IAAII,GAAKM,CAAI,GACZA,EAAK,QAAQ,WAAW,IAAI,OAAOA;AAC5C"}