@weasel-js/core 1.15.1 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/dist/animation/poseTarget.js +3 -3
  3. package/dist/animation/poseTarget.js.map +1 -1
  4. package/dist/animation/reflow.js +7 -7
  5. package/dist/animation/reflow.js.map +1 -1
  6. package/dist/animation/rig/rigNode.js +2 -2
  7. package/dist/animation/rig/rigNode.js.map +1 -1
  8. package/dist/barrel/input.js +2 -1
  9. package/dist/barrel/paint.js +2 -2
  10. package/dist/barrel/viewport.js +3 -3
  11. package/dist/canvas/NodeShape.js +23 -10
  12. package/dist/canvas/NodeShape.js.map +1 -1
  13. package/dist/canvas/SceneCanvas/PointerProviderIfRoot.js +17 -64
  14. package/dist/canvas/SceneCanvas/PointerProviderIfRoot.js.map +1 -1
  15. package/dist/canvas/SceneCanvas/props.js.map +1 -1
  16. package/dist/canvas/SceneCanvas/useSceneCanvasLayers.js +1 -1
  17. package/dist/canvas/SceneCanvas/useSceneCanvasLayers.js.map +1 -1
  18. package/dist/canvas/SceneCanvas/useSceneRedrawSources.js +4 -1
  19. package/dist/canvas/SceneCanvas/useSceneRedrawSources.js.map +1 -1
  20. package/dist/canvas/SceneCanvas/useSceneSlotLayers.js +3 -3
  21. package/dist/canvas/SceneCanvas/useSceneSlotLayers.js.map +1 -1
  22. package/dist/canvas/SceneCanvas.js +1 -1
  23. package/dist/canvas/SceneCanvas.js.map +1 -1
  24. package/dist/canvas/SceneViewCanvas.js +4 -1
  25. package/dist/canvas/SceneViewCanvas.js.map +1 -1
  26. package/dist/canvas/accentColor.js +3 -3
  27. package/dist/canvas/accentColor.js.map +1 -1
  28. package/dist/canvas/deps/enteredGroup.js +5 -4
  29. package/dist/canvas/deps/enteredGroup.js.map +1 -1
  30. package/dist/canvas/deps/selectionSnapshot.js +7 -2
  31. package/dist/canvas/deps/selectionSnapshot.js.map +1 -1
  32. package/dist/canvas/nodeShapes/derivedPainter.js +57 -8
  33. package/dist/canvas/nodeShapes/derivedPainter.js.map +1 -1
  34. package/dist/canvas/nodeShapes/nodePaint.js +33 -2
  35. package/dist/canvas/nodeShapes/nodePaint.js.map +1 -1
  36. package/dist/canvas/nodeShapes/pathPainter.js +5 -4
  37. package/dist/canvas/nodeShapes/pathPainter.js.map +1 -1
  38. package/dist/canvas/nodeShapes/pickOutline.js +48 -0
  39. package/dist/canvas/nodeShapes/pickOutline.js.map +1 -0
  40. package/dist/canvas/nodeShapes/shapePainter.js +6 -4
  41. package/dist/canvas/nodeShapes/shapePainter.js.map +1 -1
  42. package/dist/canvas/paintOverrides.js +43 -0
  43. package/dist/canvas/paintOverrides.js.map +1 -0
  44. package/dist/canvas/renderSceneToPixels.js +1 -1
  45. package/dist/canvas/renderSceneToPixels.js.map +1 -1
  46. package/dist/canvas/sceneSlotWiring.js +3 -3
  47. package/dist/canvas/sceneSlotWiring.js.map +1 -1
  48. package/dist/canvas/sceneViewRender.js +11 -7
  49. package/dist/canvas/sceneViewRender.js.map +1 -1
  50. package/dist/canvas/slopsDebugLayer.js +8 -2
  51. package/dist/canvas/slopsDebugLayer.js.map +1 -1
  52. package/dist/canvas/trimOverrides.js +18 -0
  53. package/dist/canvas/trimOverrides.js.map +1 -0
  54. package/dist/canvas/useViewRegistrySurface.js +6 -3
  55. package/dist/canvas/useViewRegistrySurface.js.map +1 -1
  56. package/dist/canvas/viewRegistry.js +5 -5
  57. package/dist/canvas/viewRegistry.js.map +1 -1
  58. package/dist/core/ops/reorder/index.js +2 -6
  59. package/dist/core/ops/reorder/index.js.map +1 -1
  60. package/dist/core/pages/fitViewToPage.js +2 -7
  61. package/dist/core/pages/fitViewToPage.js.map +1 -1
  62. package/dist/core/pages/pages.js +3 -9
  63. package/dist/core/pages/pages.js.map +1 -1
  64. package/dist/core/paint/meshKindLazy.js +13 -6
  65. package/dist/core/paint/meshKindLazy.js.map +1 -1
  66. package/dist/core/scene/pathEffects/blend.js +2 -2
  67. package/dist/core/scene/pathEffects/blend.js.map +1 -1
  68. package/dist/core/scene/pathEffects/textAlong.js +6 -5
  69. package/dist/core/scene/pathEffects/textAlong.js.map +1 -1
  70. package/dist/core/scene/scene.js +12 -1
  71. package/dist/core/scene/scene.js.map +1 -1
  72. package/dist/core/viewport/clientToWorld.js +7 -1
  73. package/dist/core/viewport/clientToWorld.js.map +1 -1
  74. package/dist/core/viewport/zoomAt.js +6 -6
  75. package/dist/core/viewport/zoomAt.js.map +1 -1
  76. package/dist/devtools/root.js +11 -4
  77. package/dist/devtools/root.js.map +1 -1
  78. package/dist/devtools/transport.js +12 -16
  79. package/dist/devtools/transport.js.map +1 -1
  80. package/dist/devtools-protocol.d.ts +0 -11
  81. package/dist/domains/measure/measureHit.js +2 -8
  82. package/dist/domains/measure/measureHit.js.map +1 -1
  83. package/dist/domains/paths/anchorMarkers.js +5 -11
  84. package/dist/domains/paths/anchorMarkers.js.map +1 -1
  85. package/dist/domains/paths/pathEditingOverlayLayer.js +5 -9
  86. package/dist/domains/paths/pathEditingOverlayLayer.js.map +1 -1
  87. package/dist/domains/paths/pathLayer.js +20 -6
  88. package/dist/domains/paths/pathLayer.js.map +1 -1
  89. package/dist/domains/paths/penPreviewLayer.js +9 -12
  90. package/dist/domains/paths/penPreviewLayer.js.map +1 -1
  91. package/dist/domains/paths/shapeGenerator.js +1 -2
  92. package/dist/domains/paths/shapeGenerator.js.map +1 -1
  93. package/dist/domains/snap/angle2d.js +2 -1
  94. package/dist/domains/snap/angle2d.js.map +1 -1
  95. package/dist/domains/snap/outcomeStore.js +5 -8
  96. package/dist/domains/snap/outcomeStore.js.map +1 -1
  97. package/dist/domains/text/useSceneTextEdit.js +9 -4
  98. package/dist/domains/text/useSceneTextEdit.js.map +1 -1
  99. package/dist/domains/viewports/aim.js +3 -8
  100. package/dist/domains/viewports/aim.js.map +1 -1
  101. package/dist/domains/viewports/viewResolver.js +5 -3
  102. package/dist/domains/viewports/viewResolver.js.map +1 -1
  103. package/dist/index.d.ts +66 -50
  104. package/dist/index.js +5 -4
  105. package/dist/input/usePublishPointer.js +59 -0
  106. package/dist/input/usePublishPointer.js.map +1 -0
  107. package/dist/interactions/actions/defaults/containerScroll.js +9 -3
  108. package/dist/interactions/actions/defaults/containerScroll.js.map +1 -1
  109. package/dist/interactions/actions/defaults/enterGroup.js +3 -3
  110. package/dist/interactions/actions/defaults/enterGroup.js.map +1 -1
  111. package/dist/interactions/actions/defaults/pathEditMarks.js +2 -5
  112. package/dist/interactions/actions/defaults/pathEditMarks.js.map +1 -1
  113. package/dist/interactions/actions/edit-anchors/handleDrag.js +4 -7
  114. package/dist/interactions/actions/edit-anchors/handleDrag.js.map +1 -1
  115. package/dist/interactions/actions/move/behaviors/clampMove.js +42 -0
  116. package/dist/interactions/actions/move/behaviors/clampMove.js.map +1 -0
  117. package/dist/interactions/actions/move/layout/container.js +3 -6
  118. package/dist/interactions/actions/move/layout/container.js.map +1 -1
  119. package/dist/interactions/actions/move/layout/exits.js +2 -2
  120. package/dist/interactions/actions/move/layout/exits.js.map +1 -1
  121. package/dist/interactions/actions/transform-again/memory.js +2 -2
  122. package/dist/interactions/actions/transform-again/memory.js.map +1 -1
  123. package/dist/move.d.ts +18 -3
  124. package/dist/move.js +2 -1
  125. package/dist/version.js +1 -1
  126. package/package.json +25 -25
  127. package/dist/canvas/colorOverrides.js +0 -23
  128. package/dist/canvas/colorOverrides.js.map +0 -1
@@ -1,7 +1,7 @@
1
1
  import { chromeStateFrom, isVisibleFrom, previewSourcesFrom } from "../../canvas/drawEnvelope.js";
2
2
  import { paintsLayer } from "../../core/selection/chromeState.js";
3
- import { DEFAULT_OVERLAY_STYLE, anchorMarkerCommands, worldToScreen } from "./anchorMarkers.js";
4
- import { pathToAnchors, rectMarkerPath } from "@weasel-js/geom";
3
+ import { DEFAULT_OVERLAY_STYLE, anchorMarkerCommands } from "./anchorMarkers.js";
4
+ import { pathToAnchors, rectMarkerPath, viewRectToScreen, viewWorldToScreen } from "@weasel-js/geom";
5
5
 
6
6
  // src/domains/paths/pathEditingOverlayLayer.ts
7
7
  var EMPTY_SELECTION = /* @__PURE__ */ new Set();
@@ -34,7 +34,7 @@ function createPathEditingOverlayLayer(opts) {
34
34
  if (node) {
35
35
  const mark = opts.getSelectedMark?.() ?? null;
36
36
  const anchors = pathToAnchors(pose);
37
- const toScreen = (p) => worldToScreen(p, view);
37
+ const toScreen = (p) => viewWorldToScreen(view, p);
38
38
  for (const ext of opts.getExtensions?.() ?? []) {
39
39
  if (!ext.marks) continue;
40
40
  out.push(...ext.marks({
@@ -52,14 +52,10 @@ function createPathEditingOverlayLayer(opts) {
52
52
  out.push(...anchorMarkerCommands(pose, view, selected, style, markers));
53
53
  const marquee = opts.getMarquee?.(view);
54
54
  if (marquee) {
55
- const m = worldToScreen(marquee, view);
56
- const m2 = worldToScreen({
57
- x: marquee.x + marquee.width,
58
- y: marquee.y + marquee.height
59
- }, view);
55
+ const m = viewRectToScreen(view, marquee);
60
56
  out.push({
61
57
  kind: "path",
62
- path: rectMarkerPath(m.x, m.y, m2.x - m.x, m2.y - m.y),
58
+ path: rectMarkerPath(m.x, m.y, m.width, m.height),
63
59
  fill: { paint: {
64
60
  kind: "solid",
65
61
  color: style.marqueeFill
@@ -1 +1 @@
1
- {"version":3,"file":"pathEditingOverlayLayer.js","names":[],"sources":["../../../src/domains/paths/pathEditingOverlayLayer.ts"],"sourcesContent":["/**\n * Screen-space render layer for path-editing chrome — the open path's\n * outline, anchor markers, tangent lines, and control-point dots for a\n * polygon path that is the current edit target, under them whatever marks\n * its path-edit extensions draw. Marker sizes stay constant regardless of zoom.\n */\n\nimport type { DrawCommand } from '@weasel-js/renderer';\nimport type { RenderLayer } from 'core/layers/render';\nimport {\n type AnchorSet, type Path, type PolygonPath, type View, pathToAnchors, rectMarkerPath,\n} from '@weasel-js/geom';\nimport type { GesturePreviewSource } from 'canvas/gestureBounds';\nimport { chromeStateFrom, previewSourcesFrom, isVisibleFrom } from 'canvas/drawEnvelope';\nimport { paintsLayer } from 'core/selection/chromeState';\nimport {\n anchorMarkerCommands, DEFAULT_OVERLAY_STYLE, worldToScreen, type PathEditingOverlayStyle,\n} from './anchorMarkers';\nimport type { PathEditExtension, PathEditMark } from './pathEditExtension';\nimport type { AnchorMarkerShape } from './pathRepresentation';\n\nexport type { PathEditingOverlayStyle } from './anchorMarkers';\n\n/** Options for `createPathEditingOverlayLayer`. Everything is read per frame,\n * so the layer follows a changing edit target without being rebuilt. */\nexport interface CreatePathEditingOverlayLayerOptions {\n /** Returns the id of the polygon currently in anchor-edit mode, or null\n * when no node is being edited. */\n getEditingId(): string | null;\n /**\n * Returns the pose for an id, or null if the node has been deleted.\n * Non-polygon poses are tolerated (the layer no-ops on them).\n *\n * `previews` are the drawing view's in-flight preview surfaces, so an\n * anchor dragged in one panel does not move in the others. Resolve against\n * them before falling back to the committed pose.\n *\n * `view` is the drawing view's camera. Answer in its world: a node whose\n * layer is a parallax plane stores its path in the plane's.\n */\n getPose(id: string, previews: readonly GesturePreviewSource[], view: View): Path | null;\n /** The marker of each anchor, by flat index, for a node whose path was\n * drawn from a form (`PathRepresentation.anchorMarkers`); null, or an\n * anchor with none, draws a square. Resolve against `previews` as\n * `getPose` does. */\n getAnchorMarkers?(id: string, previews: readonly GesturePreviewSource[]): readonly (AnchorMarkerShape | null)[] | null;\n /** Flat indices of the selected anchors. Selected anchors render\n * filled; unselected ones hollow. */\n getSelectedAnchors?(): ReadonlySet<number>;\n /** In-flight anchor-marquee rect in world coords, or null. Drawn as a\n * rubber band while `marqueeAnchorsAction` is dragging. */\n getMarquee?(view: View): { x: number; y: number; width: number; height: number } | null;\n /** The edited node's committed pose and data, which extensions' marks read. */\n getNode?(id: string): { pose: unknown; data: unknown; layer?: string } | null;\n /** The path-edit extensions whose marks are drawn, in order. */\n getExtensions?(): readonly PathEditExtension[];\n /** The selected extension mark, or null. */\n getSelectedMark?(): PathEditMark | null;\n /** Optional styling overrides. */\n style?: PathEditingOverlayStyle;\n}\n\nconst EMPTY_SELECTION: ReadonlySet<number> = new Set();\nconst ALWAYS = (): boolean => true;\n\n/** Render layer that draws the outline and the anchors and control handles\n * of the path currently being anchor-edited. Draws nothing when no path is\n * being edited. */\nexport function createPathEditingOverlayLayer(\n opts: CreatePathEditingOverlayLayerOptions,\n): RenderLayer<unknown> {\n const style = { ...DEFAULT_OVERLAY_STYLE, ...(opts.style ?? {}) };\n\n return {\n id: 'path-editing-overlay',\n label: 'Path editing',\n space: 'screen',\n draw: (data, view) => {\n const id = opts.getEditingId();\n if (!id) return [];\n // Chrome-caps gate off the envelope, so paint and the anchor hit-test in\n // `affordanceAt` consult the same rule — otherwise a consumer that hides\n // the chrome still gets grabbable invisible anchors, or vice versa.\n const isVisible = isVisibleFrom(data);\n if (isVisible && !isVisible('path-edit.anchors')) return [];\n const node = opts.getNode?.(id);\n if (!paintsLayer(chromeStateFrom(data), node?.layer)) return [];\n const previews = previewSourcesFrom(data);\n const pose = opts.getPose(id, previews, view);\n if (!pose || pose.kind !== 'polygon') return [];\n const markers = opts.getAnchorMarkers?.(id, previews) ?? null;\n\n const selected = opts.getSelectedAnchors?.() ?? EMPTY_SELECTION;\n // Extensions' marks under the markers, which are what a press reaches first.\n const out: DrawCommand[] = [];\n if (node) {\n const mark = opts.getSelectedMark?.() ?? null;\n const anchors = pathToAnchors(pose as PolygonPath) as AnchorSet;\n const toScreen = (p: { x: number; y: number }) => worldToScreen(p, view);\n for (const ext of opts.getExtensions?.() ?? []) {\n if (!ext.marks) continue;\n out.push(...ext.marks({\n id, node, path: pose as PolygonPath, anchors, view, toScreen,\n isVisible: isVisible ?? ALWAYS,\n selected: mark?.owner === ext.id ? mark.index : null,\n }));\n }\n }\n out.push(...anchorMarkerCommands(pose as PolygonPath, view, selected, style, markers));\n\n // Marquee rubber band, on top of everything.\n const marquee = opts.getMarquee?.(view);\n if (marquee) {\n const m = worldToScreen(marquee, view);\n const m2 = worldToScreen({ x: marquee.x + marquee.width, y: marquee.y + marquee.height }, view);\n out.push({\n kind: 'path',\n path: rectMarkerPath(m.x, m.y, m2.x - m.x, m2.y - m.y),\n fill: { paint: { kind: 'solid', color: style.marqueeFill } },\n stroke: { paint: { kind: 'solid', color: style.marqueeStroke }, width: 1 },\n });\n }\n\n return out;\n },\n };\n}\n"],"mappings":";;;;;;AA8DA,IAAM,kCAAuC,IAAI,IAAI;AACrD,IAAM,eAAwB;;;;AAK9B,SAAgB,8BACd,MACsB;CACtB,MAAM,QAAQ;EAAE,GAAG;EAAuB,GAAI,KAAK,SAAS,CAAC;CAAG;CAEhE,OAAO;EACL,IAAI;EACJ,OAAO;EACP,OAAO;EACP,OAAO,MAAM,SAAS;GACpB,MAAM,KAAK,KAAK,aAAa;GAC7B,IAAI,CAAC,IAAI,OAAO,CAAC;GAIjB,MAAM,YAAY,cAAc,IAAI;GACpC,IAAI,aAAa,CAAC,UAAU,mBAAmB,GAAG,OAAO,CAAC;GAC1D,MAAM,OAAO,KAAK,UAAU,EAAE;GAC9B,IAAI,CAAC,YAAY,gBAAgB,IAAI,GAAG,MAAM,KAAK,GAAG,OAAO,CAAC;GAC9D,MAAM,WAAW,mBAAmB,IAAI;GACxC,MAAM,OAAO,KAAK,QAAQ,IAAI,UAAU,IAAI;GAC5C,IAAI,CAAC,QAAQ,KAAK,SAAS,WAAW,OAAO,CAAC;GAC9C,MAAM,UAAU,KAAK,mBAAmB,IAAI,QAAQ,KAAK;GAEzD,MAAM,WAAW,KAAK,qBAAqB,KAAK;GAEhD,MAAM,MAAqB,CAAC;GAC5B,IAAI,MAAM;IACR,MAAM,OAAO,KAAK,kBAAkB,KAAK;IACzC,MAAM,UAAU,cAAc,IAAmB;IACjD,MAAM,YAAY,MAAgC,cAAc,GAAG,IAAI;IACvE,KAAK,MAAM,OAAO,KAAK,gBAAgB,KAAK,CAAC,GAAG;KAC9C,IAAI,CAAC,IAAI,OAAO;KAChB,IAAI,KAAK,GAAG,IAAI,MAAM;MACpB;MAAI;MAAM,MAAM;MAAqB;MAAS;MAAM;MACpD,WAAW,aAAa;MACxB,UAAU,MAAM,UAAU,IAAI,KAAK,KAAK,QAAQ;KAClD,CAAC,CAAC;IACJ;GACF;GACA,IAAI,KAAK,GAAG,qBAAqB,MAAqB,MAAM,UAAU,OAAO,OAAO,CAAC;GAGrF,MAAM,UAAU,KAAK,aAAa,IAAI;GACtC,IAAI,SAAS;IACX,MAAM,IAAI,cAAc,SAAS,IAAI;IACrC,MAAM,KAAK,cAAc;KAAE,GAAG,QAAQ,IAAI,QAAQ;KAAO,GAAG,QAAQ,IAAI,QAAQ;IAAO,GAAG,IAAI;IAC9F,IAAI,KAAK;KACP,MAAM;KACN,MAAM,eAAe,EAAE,GAAG,EAAE,GAAG,GAAG,IAAI,EAAE,GAAG,GAAG,IAAI,EAAE,CAAC;KACrD,MAAM,EAAE,OAAO;MAAE,MAAM;MAAS,OAAO,MAAM;KAAY,EAAE;KAC3D,QAAQ;MAAE,OAAO;OAAE,MAAM;OAAS,OAAO,MAAM;MAAc;MAAG,OAAO;KAAE;IAC3E,CAAC;GACH;GAEA,OAAO;EACT;CACF;AACF"}
1
+ {"version":3,"file":"pathEditingOverlayLayer.js","names":[],"sources":["../../../src/domains/paths/pathEditingOverlayLayer.ts"],"sourcesContent":["/**\n * Screen-space render layer for path-editing chrome — the open path's\n * outline, anchor markers, tangent lines, and control-point dots for a\n * polygon path that is the current edit target, under them whatever marks\n * its path-edit extensions draw. Marker sizes stay constant regardless of zoom.\n */\n\nimport type { DrawCommand } from '@weasel-js/renderer';\nimport type { RenderLayer } from 'core/layers/render';\nimport {\n type AnchorSet, type Path, type PolygonPath, type View, pathToAnchors, rectMarkerPath, viewRectToScreen, viewWorldToScreen,\n} from '@weasel-js/geom';\nimport type { GesturePreviewSource } from 'canvas/gestureBounds';\nimport { chromeStateFrom, previewSourcesFrom, isVisibleFrom } from 'canvas/drawEnvelope';\nimport { paintsLayer } from 'core/selection/chromeState';\nimport {\n anchorMarkerCommands, DEFAULT_OVERLAY_STYLE, type PathEditingOverlayStyle,\n} from './anchorMarkers';\nimport type { PathEditExtension, PathEditMark } from './pathEditExtension';\nimport type { AnchorMarkerShape } from './pathRepresentation';\n\nexport type { PathEditingOverlayStyle } from './anchorMarkers';\n\n/** Options for `createPathEditingOverlayLayer`. Everything is read per frame,\n * so the layer follows a changing edit target without being rebuilt. */\nexport interface CreatePathEditingOverlayLayerOptions {\n /** Returns the id of the polygon currently in anchor-edit mode, or null\n * when no node is being edited. */\n getEditingId(): string | null;\n /**\n * Returns the pose for an id, or null if the node has been deleted.\n * Non-polygon poses are tolerated (the layer no-ops on them).\n *\n * `previews` are the drawing view's in-flight preview surfaces, so an\n * anchor dragged in one panel does not move in the others. Resolve against\n * them before falling back to the committed pose.\n *\n * `view` is the drawing view's camera. Answer in its world: a node whose\n * layer is a parallax plane stores its path in the plane's.\n */\n getPose(id: string, previews: readonly GesturePreviewSource[], view: View): Path | null;\n /** The marker of each anchor, by flat index, for a node whose path was\n * drawn from a form (`PathRepresentation.anchorMarkers`); null, or an\n * anchor with none, draws a square. Resolve against `previews` as\n * `getPose` does. */\n getAnchorMarkers?(id: string, previews: readonly GesturePreviewSource[]): readonly (AnchorMarkerShape | null)[] | null;\n /** Flat indices of the selected anchors. Selected anchors render\n * filled; unselected ones hollow. */\n getSelectedAnchors?(): ReadonlySet<number>;\n /** In-flight anchor-marquee rect in world coords, or null. Drawn as a\n * rubber band while `marqueeAnchorsAction` is dragging. */\n getMarquee?(view: View): { x: number; y: number; width: number; height: number } | null;\n /** The edited node's committed pose and data, which extensions' marks read. */\n getNode?(id: string): { pose: unknown; data: unknown; layer?: string } | null;\n /** The path-edit extensions whose marks are drawn, in order. */\n getExtensions?(): readonly PathEditExtension[];\n /** The selected extension mark, or null. */\n getSelectedMark?(): PathEditMark | null;\n /** Optional styling overrides. */\n style?: PathEditingOverlayStyle;\n}\n\nconst EMPTY_SELECTION: ReadonlySet<number> = new Set();\nconst ALWAYS = (): boolean => true;\n\n/** Render layer that draws the outline and the anchors and control handles\n * of the path currently being anchor-edited. Draws nothing when no path is\n * being edited. */\nexport function createPathEditingOverlayLayer(\n opts: CreatePathEditingOverlayLayerOptions,\n): RenderLayer<unknown> {\n const style = { ...DEFAULT_OVERLAY_STYLE, ...(opts.style ?? {}) };\n\n return {\n id: 'path-editing-overlay',\n label: 'Path editing',\n space: 'screen',\n draw: (data, view) => {\n const id = opts.getEditingId();\n if (!id) return [];\n // Chrome-caps gate off the envelope, so paint and the anchor hit-test in\n // `affordanceAt` consult the same rule — otherwise a consumer that hides\n // the chrome still gets grabbable invisible anchors, or vice versa.\n const isVisible = isVisibleFrom(data);\n if (isVisible && !isVisible('path-edit.anchors')) return [];\n const node = opts.getNode?.(id);\n if (!paintsLayer(chromeStateFrom(data), node?.layer)) return [];\n const previews = previewSourcesFrom(data);\n const pose = opts.getPose(id, previews, view);\n if (!pose || pose.kind !== 'polygon') return [];\n const markers = opts.getAnchorMarkers?.(id, previews) ?? null;\n\n const selected = opts.getSelectedAnchors?.() ?? EMPTY_SELECTION;\n // Extensions' marks under the markers, which are what a press reaches first.\n const out: DrawCommand[] = [];\n if (node) {\n const mark = opts.getSelectedMark?.() ?? null;\n const anchors = pathToAnchors(pose as PolygonPath) as AnchorSet;\n const toScreen = (p: { x: number; y: number }) => viewWorldToScreen(view, p);\n for (const ext of opts.getExtensions?.() ?? []) {\n if (!ext.marks) continue;\n out.push(...ext.marks({\n id, node, path: pose as PolygonPath, anchors, view, toScreen,\n isVisible: isVisible ?? ALWAYS,\n selected: mark?.owner === ext.id ? mark.index : null,\n }));\n }\n }\n out.push(...anchorMarkerCommands(pose as PolygonPath, view, selected, style, markers));\n\n // Marquee rubber band, on top of everything.\n const marquee = opts.getMarquee?.(view);\n if (marquee) {\n const m = viewRectToScreen(view, marquee);\n out.push({\n kind: 'path',\n path: rectMarkerPath(m.x, m.y, m.width, m.height),\n fill: { paint: { kind: 'solid', color: style.marqueeFill } },\n stroke: { paint: { kind: 'sol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,GAAG,qBAAqB,MAAqB,MAAM,UAAU,OAAO,OAAO,CAAC;GAGrF,MAAM,UAAU,KAAK,aAAa,IAAI;GACtC,IAAI,SAAS;IACX,MAAM,IAAI,iBAAiB,MAAM,OAAO;IACxC,IAAI,KAAK;KACP,MAAM;KACN,MAAM,eAAe,EAAE,GAAG,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM;KAChD,MAAM,EAAE,OAAO;MAAE,MAAM;MAAS,OAAO,MAAM;KAAY,EAAE;KAC3D,QAAQ;MAAE,OAAO;OAAE,MAAM;OAAS,OAAO,MAAM;MAAc;MAAG,OAAO;KAAE;IAC3E,CAAC;GACH;GAEA,OAAO;EACT;CACF;AACF"}
@@ -1,3 +1,6 @@
1
+ import { subscribeToSources } from "../../core/layers/redrawSource.js";
2
+ import { paintOverrideSources } from "../../canvas/paintOverrides.js";
3
+ import { overrideTrim } from "../../canvas/trimOverrides.js";
1
4
  import "@weasel-js/renderer";
2
5
  import { countPathAnchors } from "@weasel-js/geom";
3
6
  import { isDev } from "@weasel-js/react";
@@ -9,14 +12,29 @@ var PLACEHOLDER_STROKE = {
9
12
  paint: { color: "#ffffff" },
10
13
  width: 1
11
14
  };
15
+ /** `base` with the per-anchor arrays that validated, and a trim override's edges. */
16
+ function strokeWith(base, vertexColors, vertexWidths, override) {
17
+ const trim = overrideTrim(base.trim, override);
18
+ return {
19
+ ...base,
20
+ ...vertexColors != null ? { vertexColors } : {},
21
+ ...vertexWidths != null ? { vertexWidths } : {},
22
+ ...trim !== void 0 ? { trim } : {}
23
+ };
24
+ }
12
25
  /** Build a `RenderLayer` that fills/strokes `Path` instances enumerated from a node list. */
13
26
  function createPathLayer(opts) {
14
- const { id = "paths", label = "Paths", getNodes, getPath, getFill, getStroke, isHidden, getVertexColors, getStrokeVertexColors, getStrokeVertexWidths, colorOverrides, now = () => typeof performance !== "undefined" ? performance.now() : Date.now() } = opts;
27
+ const { id = "paths", label = "Paths", getNodes, getPath, getFill, getStroke, isHidden, getVertexColors, getStrokeVertexColors, getStrokeVertexWidths, colorOverrides, trimOverrides, now = () => typeof performance !== "undefined" ? performance.now() : Date.now() } = opts;
15
28
  const warned = /* @__PURE__ */ new Set();
16
29
  const dev = isDev();
30
+ const sources = paintOverrideSources({
31
+ colorOverrides,
32
+ trimOverrides
33
+ });
17
34
  return {
18
35
  id,
19
36
  label,
37
+ ...sources.length > 0 ? { subscribe: subscribeToSources(sources) } : {},
20
38
  draw: () => {
21
39
  const children = [];
22
40
  const nodes = getNodes();
@@ -71,11 +89,7 @@ function createPathLayer(opts) {
71
89
  }
72
90
  }
73
91
  const baseStroke = strokeFromHook != null ? strokeFromHook : useStrokeVColors != null || useStrokeVWidths != null ? PLACEHOLDER_STROKE : void 0;
74
- const stroke = baseStroke != null ? {
75
- ...baseStroke,
76
- ...useStrokeVColors != null ? { vertexColors: useStrokeVColors } : {},
77
- ...useStrokeVWidths != null ? { vertexWidths: useStrokeVWidths } : {}
78
- } : baseStroke;
92
+ const stroke = baseStroke && strokeWith(baseStroke, useStrokeVColors, useStrokeVWidths, trimOverrides?.resolve(nodeId));
79
93
  if (fill == null && stroke == null) continue;
80
94
  children.push({
81
95
  kind: "path",
@@ -1 +1 @@
1
- {"version":3,"file":"pathLayer.js","names":[],"sources":["../../../src/domains/paths/pathLayer.ts"],"sourcesContent":["/**\n * `RenderLayer` that fills/strokes `Path` instances. Mirrors the shape of\n * `createTextLayer`: caller hands over a `getNodes()` enumerator and a\n * `getPath(node)` lookup; the layer iterates and renders. Fill and\n * stroke are looked up per node so consumers can keep the path geometry\n * separate from the visual style record (the typical scene-graph layout).\n */\n\nimport { type DrawCommand } from '@weasel-js/renderer';\nimport { type CommandStroke, type CommandFill, type VertexWidth } from '@weasel-js/paint';\nimport type { RenderLayer } from 'core/layers/render';\nimport { type Path, countPathAnchors } from '@weasel-js/geom';\nimport type { ColorOverrideRegistry } from '@weasel-js/animator';\nimport { isDev } from '@weasel-js/react';\n\nconst PLACEHOLDER_FILL: CommandFill = { paint: { color: '#ffffff' } };\nconst PLACEHOLDER_STROKE: CommandStroke = { paint: { color: '#ffffff' }, width: 1 };\n\n\n/** Options for `createPathLayer`. */\nexport interface CreatePathLayerOpts<T> {\n id?: string;\n label?: string;\n getNodes: () => readonly T[];\n getPath: (node: T) => Path;\n /** Per-node fill. Return `null`/`undefined` to skip filling. */\n getFill?: (node: T) => CommandFill | null | undefined;\n /** Per-node stroke. Return `null`/`undefined` to skip stroking. */\n getStroke?: (node: T) => CommandStroke | null | undefined;\n /** Optional per-node hide hook (e.g., suppress while editing). */\n isHidden?: (node: T) => boolean;\n /**\n * Per-node fill vertex-color array, flat RGBA-per-path-anchor, in\n * 0..1 floats (same color space as `PathDrawCommand.vertexColors`).\n * Length must be `4 × countPathAnchors(getPath(node))`. When set and\n * `getFill` returns null/undefined, a white placeholder fill is\n * synthesized so the renderer's per-vertex shader path activates.\n */\n getVertexColors?: (node: T) => number[] | null | undefined;\n /**\n * Per-node stroke vertex-color array, flat RGBA-per-path-anchor, in\n * 0..1 floats (same color space as `Stroke.vertexColors`).\n * Length must be `4 × countPathAnchors(getPath(node))`. When set and\n * `getStroke` returns null/undefined, a white 1px placeholder stroke\n * is synthesized.\n */\n getStrokeVertexColors?: (node: T) => number[] | null | undefined;\n /**\n * Per-node stroke vertex-width array (one `VertexWidth` per anchor: a\n * width, or a `{ left, right }` pair).\n * Length must be `countPathAnchors(getPath(node))`. The tessellator\n * interpolates half-widths along each segment for tapered strokes.\n * When set and `getStroke` returns null/undefined, a 1px placeholder\n * stroke is synthesized so the per-anchor widths take effect.\n */\n getStrokeVertexWidths?: (node: T) => VertexWidth[] | null | undefined;\n /**\n * Optional color override registry, typically `animator.colorOverrides`.\n * When set, the renderer consults it before falling back to\n * `getVertexColors` / `getStrokeVertexColors`. Function-form overrides\n * receive the base color array and the current animation timestamp.\n */\n colorOverrides?: ColorOverrideRegistry;\n /** Clock used to timestamp function-form color overrides. Defaults to\n * `performance.now`. Override in tests. */\n now?: () => number;\n}\n\n/** Build a `RenderLayer` that fills/strokes `Path` instances enumerated from a node list. */\nexport function createPathLayer<T>(opts: CreatePathLayerOpts<T>): RenderLayer<unknown> {\n const {\n id = 'paths', label = 'Paths',\n getNodes, getPath, getFill, getStroke, isHidden,\n getVertexColors, getStrokeVertexColors, getStrokeVertexWidths,\n colorOverrides,\n now = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now()),\n } = opts;\n const warned = new Set<string>();\n const dev = isDev();\n\n return {\n id,\n label,\n draw: () => {\n const children: DrawCommand[] = [];\n const nodes = getNodes();\n for (let idx = 0; idx < nodes.length; idx++) {\n const node = nodes[idx];\n if (isHidden?.(node)) continue;\n const path = getPath(node);\n const fillFromHook = getFill?.(node);\n const strokeFromHook = getStroke?.(node);\n const baseVColors = getVertexColors?.(node);\n const baseStrokeVColors = getStrokeVertexColors?.(node);\n const strokeVWidths = getStrokeVertexWidths?.(node);\n\n const nodeId = (node as { id?: string }).id ?? String(idx);\n const tMs = colorOverrides ? now() : 0;\n\n const vColors = colorOverrides\n ? colorOverrides.resolve(nodeId, 'fill', baseVColors ?? undefined, tMs)\n : baseVColors;\n const strokeVColors = colorOverrides\n ? colorOverrides.resolve(nodeId, 'stroke', baseStrokeVColors ?? undefined, tMs)\n : baseStrokeVColors;\n\n const nodeKey = nodeId;\n const anchorCount = countPathAnchors(path);\n const expectedLen = 4 * anchorCount;\n\n let useVColors: readonly number[] | null = null;\n if (vColors != null) {\n if (vColors.length === expectedLen) {\n useVColors = vColors;\n } else if (dev) {\n const key = `${id}:${nodeKey}:fill`;\n if (!warned.has(key)) {\n warned.add(key);\n console.warn(\n `[createPathLayer ${id}] node ${nodeKey}: fill vertexColors length ${vColors.length}, expected ${expectedLen}; dropping`,\n );\n }\n }\n }\n\n let useStrokeVColors: readonly number[] | null = null;\n if (strokeVColors != null) {\n if (strokeVColors.length === expectedLen) {\n useStrokeVColors = strokeVColors;\n } else if (dev) {\n const key = `${id}:${nodeKey}:stroke`;\n if (!warned.has(key)) {\n warned.add(key);\n console.warn(\n `[createPathLayer ${id}] node ${nodeKey}: stroke vertexColors length ${strokeVColors.length}, expected ${expectedLen}; dropping`,\n );\n }\n }\n }\n\n // Synthesize placeholder only when colors validate (useVColors != null),\n // not on any raw hook return. Mismatched-length arrays drop both the\n // colors and placeholder so the dev signal (console warning) isn't duplicated.\n const fill: CommandFill | undefined =\n fillFromHook != null ? fillFromHook\n : (useVColors != null ? PLACEHOLDER_FILL : undefined);\n\n let useStrokeVWidths: VertexWidth[] | null = null;\n if (strokeVWidths != null) {\n if (strokeVWidths.length === anchorCount) {\n useStrokeVWidths = strokeVWidths;\n } else if (dev) {\n const key = `${id}:${nodeKey}:strokeWidths`;\n if (!warned.has(key)) {\n warned.add(key);\n console.warn(\n `[createPathLayer ${id}] node ${nodeKey}: stroke vertexWidths length ${strokeVWidths.length}, expected ${anchorCount}; dropping`,\n );\n }\n }\n }\n\n const baseStroke: CommandStroke | undefined =\n strokeFromHook != null ? strokeFromHook\n : (useStrokeVColors != null || useStrokeVWidths != null ? PLACEHOLDER_STROKE : undefined);\n\n const stroke: CommandStroke | undefined =\n baseStroke != null\n ? {\n ...baseStroke,\n ...(useStrokeVColors != null ? { vertexColors: useStrokeVColors as number[] } : {}),\n ...(useStrokeVWidths != null ? { vertexWidths: useStrokeVWidths } : {}),\n }\n : baseStroke;\n\n if (fill == null && stroke == null) continue;\n\n children.push({\n kind: 'path',\n path,\n ...(fill != null ? { fill } : {}),\n ...(stroke != null ? { stroke } : {}),\n ...(useVColors != null ? { vertexColors: useVColors as number[] } : {}),\n });\n }\n // World-space commands; drawLayers wraps in viewToMat3 automatically.\n return children;\n },\n };\n}\n"],"mappings":";;;;;;AAeA,IAAM,mBAAgC,EAAE,OAAO,EAAE,OAAO,UAAU,EAAE;AACpE,IAAM,qBAAoC;CAAE,OAAO,EAAE,OAAO,UAAU;CAAG,OAAO;AAAE;;AAqDlF,SAAgB,gBAAmB,MAAoD;CACrF,MAAM,EACJ,KAAK,SAAS,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ayer.ts"],"sourcesContent":["/**\n * `RenderLayer` that fills/strokes `Path` instances. Mirrors the shape of\n * `createTextLayer`: caller hands over a `getNodes()` enumerator and a\n * `getPath(node)` lookup; the layer iterates and renders. Fill and\n * stroke are looked up per node so consumers can keep the path geometry\n * separate from the visual style record (the typical scene-graph layout).\n */\n\nimport { type DrawCommand } from '@weasel-js/renderer';\nimport { type CommandStroke, type CommandFill, type VertexWidth } from '@weasel-js/paint';\nimport { subscribeToSources, type RenderLayer } from 'core/layers/render';\nimport { paintOverrideSources, type PaintOverrides } from 'canvas/paintOverrides';\nimport { type Path, countPathAnchors } from '@weasel-js/geom';\nimport type { TrimOverride } from '@weasel-js/animator';\nimport { overrideTrim } from 'canvas/trimOverrides';\nimport { isDev } from '@weasel-js/react';\n\nconst PLACEHOLDER_FILL: CommandFill = { paint: { color: '#ffffff' } };\nconst PLACEHOLDER_STROKE: CommandStroke = { paint: { color: '#ffffff' }, width: 1 };\n\n\n/** Options for `createPathLayer`. Its animated paint, typically an animator,\n * comes before `getVertexColors`, `getStrokeVertexColors` and `getStroke`'s\n * trim; a function-form color override receives the base colors and the\n * timestamp `now` gives. The layer repaints for a `set` or `clear` on either registry. */\nexport interface CreatePathLayerOpts<T> extends PaintOverrides {\n id?: string;\n label?: string;\n getNodes: () => readonly T[];\n getPath: (node: T) => Path;\n /** Per-node fill. Return `null`/`undefined` to skip filling. */\n getFill?: (node: T) => CommandFill | null | undefined;\n /** Per-node stroke. Return `null`/`undefined` to skip stroking. */\n getStroke?: (node: T) => CommandStroke | null | undefined;\n /** Optional per-node hide hook (e.g., suppress while editing). */\n isHidden?: (node: T) => boolean;\n /**\n * Per-node fill vertex-color array, flat RGBA-per-path-anchor, in\n * 0..1 floats (same color space as `PathDrawCommand.vertexColors`).\n * Length must be `4 × countPathAnchors(getPath(node))`. When set and\n * `getFill` returns null/undefined, a white placeholder fill is\n * synthesized so the renderer's per-vertex shader path activates.\n */\n getVertexColors?: (node: T) => number[] | null | undefined;\n /**\n * Per-node stroke vertex-color array, flat RGBA-per-path-anchor, in\n * 0..1 floats (same color space as `Stroke.vertexColors`).\n * Length must be `4 × countPathAnchors(getPath(node))`. When set and\n * `getStroke` returns null/undefined, a white 1px placeholder stroke\n * is synthesized.\n */\n getStrokeVertexColors?: (node: T) => number[] | null | undefined;\n /**\n * Per-node stroke vertex-width array (one `VertexWidth` per anchor: a\n * width, or a `{ left, right }` pair).\n * Length must be `countPathAnchors(getPath(node))`. The tessellator\n * interpolates half-widths along each segment for tapered strokes.\n * When set and `getStroke` returns null/undefined, a 1px placeholder\n * stroke is synthesized so the per-anchor widths take effect.\n */\n getStrokeVertexWidths?: (node: T) => VertexWidth[] | null | undefined;\n /** Clock used to timestamp function-form color overrides. Defaults to\n * `performance.now`. Override in tests. */\n now?: () => number;\n}\n\n/** `base` with the per-anchor arrays that validated, and a trim override's edges. */\nfunction strokeWith(\n base: CommandStroke,\n vertexColors: readonly number[] | null,\n vertexWidths: VertexWidth[] | null,\n override: TrimOverride | undefined,\n): CommandStroke {\n const trim = overrideTrim(base.trim, override);\n return {\n ...base,\n ...(vertexColors != null ? { vertexColors: vertexColors as number[] } : {}),\n ...(vertexWidths != null ? { vertexWidths } : {}),\n ...(trim !== undefined ? { trim } : {}),\n };\n}\n\n/** Build a `RenderLayer` that fills/strokes `Path` instances enumerated from a node list. */\nexport function createPathLayer<T>(opts: CreatePathLayerOpts<T>): RenderLayer<unknown> {\n const {\n id = 'paths', label = 'Paths',\n getNodes, getPath, getFill, getStroke, isHidden,\n getVertexColors, getStrokeVertexColors, getStrokeVertexWidths,\n colorOverrides, trimOverrides,\n now = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now()),\n } = opts;\n const warned = new Set<string>();\n const dev = isDev();\n const sources = paintOverrideSources({ colorOverrides, trimOverrides });\n\n return {\n id,\n label,\n ...(sources.length > 0 ? { subscribe: subscribeToSources(sources) } : {}),\n draw: () => {\n const children: DrawCommand[] = [];\n const nodes = getNodes();\n for (let idx = 0; idx < nodes.length; idx++) {\n const node = nodes[idx];\n if (isHidden?.(node)) continue;\n const path = getPath(node);\n const fillFromHook = getFill?.(node);\n const strokeFromHook = getStroke?.(node);\n const baseVColors = getVertexColors?.(node);\n const baseStrokeVColors = getStrokeVertexColors?.(node);\n const strokeVWidths = getStrokeVertexWidths?.(node);\n\n const nodeId = (node as { id?: string }).id ?? String(idx);\n const tMs = colorOverrides ? now() : 0;\n\n const vColors = colorOverrides\n ? colorOverrides.resolve(nodeId, 'fill', baseVColors ?? undefined, tMs)\n : baseVColors;\n const strokeVColors = colorOverrides\n ? colorOverrides.resolve(nodeId, 'stroke', baseStrokeVColors ?? undefined, tMs)\n : baseStrokeVColors;\n\n const nodeKey = nodeId;\n const anchorCount = countPathAnchors(path);\n const expectedLen = 4 * anchorCount;\n\n let useVColors: readonly number[] | null = null;\n if (vColors != null) {\n if (vColors.length === expectedLen) {\n useVColors = vColors;\n } else if (dev) {\n const key = `${id}:${nodeKey}:fill`;\n if (!warned.has(key)) {\n warned.add(key);\n console.warn(\n `[createPathLayer ${id}] node ${nodeKey}: fill vertexColors length ${vColors.length}, expected ${expectedLen}; dropping`,\n );\n }\n }\n }\n\n let useStrokeVColors: readonly number[] | null = null;\n if (strokeVColors != null) {\n if (strokeVColors.length === expectedLen) {\n useStrokeVColors = strokeVColors;\n } else if (dev) {\n const key = `${id}:${nodeKey}:stroke`;\n if (!warned.has(key)) {\n warned.add(key);\n console.warn(\n `[createPathLayer ${id}] node ${nodeKey}: stroke vertexColors length ${strokeVColors.length}, expected ${expectedLen}; dropping`,\n );\n }\n }\n }\n\n // Synthesize placeholder only when colors validate (useVColors != null),\n // not on any raw hook return. Mismatched-length arrays drop both the\n // colors and placeholder so the dev signal (console warning) isn't duplicated.\n const fill: CommandFill | undefined =\n fillFromHook != null ? fillFromHook\n : (useVColors != null ? PLACEHOLDER_FILL : undefined);\n\n let useStrokeVWidths: VertexWidth[] | null = null;\n if (strokeVWidths != null) {\n if (strokeVWidths.length === anchorCount) {\n useStrokeVWidths = strokeVWidths;\n } else if (dev) {\n const key = `${id}:${nodeKey}:strokeWidths`;\n if (!warned.has(key)) {\n warned.add(key);\n console.warn(\n `[createPathLayer ${id}] node ${nodeKey}: stroke vertexWidths length ${strokeVWidths.length}, expected ${anchorCount}; dropping`,\n );\n }\n }\n }\n\n const baseStroke: CommandStroke | undefined =\n strokeFromHook != null ? strokeFromHook\n : (useStrokeVColors != null || useStrokeVWidths != null ? PLACEHOLDER_STROKE : undefined);\n\n const stroke = baseStroke && strokeWith(baseStroke, useStrokeVColors, useStrokeVWidths, trimOverrides?.resolve(nodeId));\n\n if (fill == null && stroke == null) continue;\n\n children.push({\n kind: 'path',\n path,\n ...(fill != null ? { fill } : {}),\n ...(stroke != null ? { stroke } : {}),\n ...(useVColors != null ? { vertexColors: useVColors as number[] } : {}),\n });\n }\n // World-space commands; drawLayers wraps in viewToMat3 automatically.\n return children;\n },\n };\n}\n"],"mappings":";;;;;;;;;AAiBA,IAAM,mBAAgC,EAAE,OAAO,EAAE,OAAO,UAAU,EAAE;AACpE,IAAM,qBAAoC;CAAE,OAAO,EAAE,OAAO,UAAU;CAAG,OAAO;AAAE;;AAiDlF,SAAS,WACP,MACA,cACA,cACA,UACe;CACf,MAAM,OAAO,aAAa,KAAK,MAAM,QAAQ;CAC7C,OAAO;EACL,GAAG;EACH,GAAI,gBAAgB,OAAO,EAAgB,aAAyB,IAAI,CAAC;EACzE,GAAI,gBAAgB,OAAO,EAAE,aAAa,IAAI,CAAC;EAC/C,GAAI,SAAS,SAAY,EAAE,KAAK,IAAI,CAAC;CACvC;AACF;;AAGA,SAAgB,gBAAmB,MAAoD;CACrF,MAAM,EACJ,KAAK,SAAS,QAAQ,SACtB,UAAU,SAAS,SAAS,WAAW,UACvC,iBAAiB,uBAAuB,uBACxC,gBAAgB,eAChB,YAAqB,OAAO,gBAAgB,cAAc,YAAY,IAAI,IAAI,KAAK,IAAI,MACrF;CACJ,MAAM,yBAAS,IAAI,IAAY;C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WAAW,aAC3B,mBAAmB;UACd,IAAI,KAAK;MACd,MAAM,MAAM,GAAG,GAAG,GAAG,QAAQ;MAC7B,IAAI,CAAC,OAAO,IAAI,GAAG,GAAG;OACpB,OAAO,IAAI,GAAG;OACd,QAAQ,KACN,oBAAoB,GAAG,SAAS,QAAQ,+BAA+B,cAAc,OAAO,aAAa,YAAY,WACvH;MACF;KACF;IACF;IAKA,MAAM,OACJ,gBAAgB,OAAO,eACpB,cAAc,OAAO,mBAAmB;IAE7C,IAAI,mBAAyC;IAC7C,IAAI,iBAAiB,MAAM;KACzB,IAAI,cAAc,WAAW,aAC3B,mBAAmB;UACd,IAAI,KAAK;MACd,MAAM,MAAM,GAAG,GAAG,GAAG,QAAQ;MAC7B,IAAI,CAAC,OAAO,IAAI,GAAG,GAAG;OACpB,OAAO,IAAI,GAAG;OACd,QAAQ,KACN,oBAAoB,GAAG,SAAS,QAAQ,+BAA+B,cAAc,OAAO,aAAa,YAAY,WACvH;MACF;KACF;IACF;IAEA,MAAM,aACJ,kBAAkB,OAAO,iBACtB,oBAAoB,QAAQ,oBAAoB,OAAO,qBAAqB;IAEjF,MAAM,SAAS,cAAc,WAAW,YAAY,kBAAkB,kBAAkB,eAAe,QAAQ,MAAM,CAAC;IAEtH,IAAI,QAAQ,QAAQ,UAAU,MAAM;IAEpC,SAAS,KAAK;KACZ,MAAM;KACN;KACA,GAAI,QAAQ,OAAO,EAAE,KAAK,IAAI,CAAC;KAC/B,GAAI,UAAU,OAAO,EAAE,OAAO,IAAI,CAAC;KACnC,GAAI,cAAc,OAAO,EAAE,cAAc,WAAuB,IAAI,CAAC;IACvE,CAAC;GACH;GAEA,OAAO;EACT;CACF;AACF"}
@@ -1,4 +1,4 @@
1
- import { PATH_C, PATH_L, PATH_M, anchorsToPath, circlePath } from "@weasel-js/geom";
1
+ import { PATH_C, PATH_L, PATH_M, anchorsToPath, circlePath, viewWorldToScreen } from "@weasel-js/geom";
2
2
 
3
3
  // src/domains/paths/penPreviewLayer.ts
4
4
  var DEFAULT_STYLE = {
@@ -21,9 +21,6 @@ var radiiOf = (kit) => ({
21
21
  handleDot: kit?.get("targets.penHandleDotRadiusPx") ?? HANDLE_DOT_RADIUS_PX,
22
22
  closeHint: kit?.get("targets.penCloseHintRadiusPx") ?? CLOSE_HINT_RADIUS_PX
23
23
  });
24
- function w2s(wx, wy, view) {
25
- return [(wx - view.x) * view.scale.x, (wy - view.y) * view.scale.y];
26
- }
27
24
  function approximateCircle(cx, cy, r) {
28
25
  return circlePath(cx, cy, r);
29
26
  }
@@ -32,7 +29,7 @@ function approximateCircle(cx, cy, r) {
32
29
  function subpathToPath(sp, view) {
33
30
  if (sp.anchors.length === 0) return null;
34
31
  const pt = (p) => {
35
- const [x, y] = w2s(p.x, p.y, view);
32
+ const { x, y } = viewWorldToScreen(view, p);
36
33
  return {
37
34
  x,
38
35
  y
@@ -95,11 +92,11 @@ function createPenPreviewLayer(opts) {
95
92
  if (cur && cur.anchors.length > 0 && s.cursor && s.draggingHandleAt === null) {
96
93
  const last = cur.anchors[cur.anchors.length - 1];
97
94
  const out2 = last.outHandle;
98
- const [sx, sy] = w2s(last.x, last.y, view);
99
- const [cx, cy] = w2s(s.cursor.x, s.cursor.y, view);
95
+ const { x: sx, y: sy } = viewWorldToScreen(view, last);
96
+ const { x: cx, y: cy } = viewWorldToScreen(view, s.cursor);
100
97
  let path;
101
98
  if (out2) {
102
- const [c1x, c1y] = w2s(out2.x, out2.y, view);
99
+ const { x: c1x, y: c1y } = viewWorldToScreen(view, out2);
103
100
  path = {
104
101
  kind: "polygon",
105
102
  commands: new Uint8Array([PATH_M, PATH_C]),
@@ -141,7 +138,7 @@ function createPenPreviewLayer(opts) {
141
138
  if (cur) {
142
139
  for (let i = 0; i < cur.anchors.length; i++) {
143
140
  const a = cur.anchors[i];
144
- const [ax, ay] = w2s(a.x, a.y, view);
141
+ const { x: ax, y: ay } = viewWorldToScreen(view, a);
145
142
  out.push({
146
143
  kind: "path",
147
144
  path: approximateCircle(ax, ay, r.anchor),
@@ -158,7 +155,7 @@ function createPenPreviewLayer(opts) {
158
155
  }
159
156
  });
160
157
  if (i === cur.anchors.length - 1 && a.outHandle) {
161
- const [hx, hy] = w2s(a.outHandle.x, a.outHandle.y, view);
158
+ const { x: hx, y: hy } = viewWorldToScreen(view, a.outHandle);
162
159
  const linePath = {
163
160
  kind: "polygon",
164
161
  commands: new Uint8Array([PATH_M, PATH_L]),
@@ -191,7 +188,7 @@ function createPenPreviewLayer(opts) {
191
188
  });
192
189
  const inSide = a.inHandle;
193
190
  if (inSide) {
194
- const [mx, my] = w2s(inSide.x, inSide.y, view);
191
+ const { x: mx, y: my } = viewWorldToScreen(view, inSide);
195
192
  const inLine = {
196
193
  kind: "polygon",
197
194
  commands: new Uint8Array([PATH_M, PATH_L]),
@@ -227,7 +224,7 @@ function createPenPreviewLayer(opts) {
227
224
  }
228
225
  if (s.closeHintActive && cur.anchors.length >= 3) {
229
226
  const first = cur.anchors[0];
230
- const [fx, fy] = w2s(first.x, first.y, view);
227
+ const { x: fx, y: fy } = viewWorldToScreen(view, first);
231
228
  out.push({
232
229
  kind: "path",
233
230
  path: approximateCircle(fx, fy, r.closeHint),
@@ -1 +1 @@
1
- {"version":3,"file":"penPreviewLayer.js","names":[],"sources":["../../../src/domains/paths/penPreviewLayer.ts"],"sourcesContent":["/**\n * Screen-space preview layer for `usePenTool`. Reads the pen's state each\n * frame and renders the in-progress path: finished\n * subpaths (faded), the current subpath (bright + anchor dots + handles),\n * a rubber-band segment from the latest anchor to the cursor, and a\n * close-hint ring on the first anchor when the tool flags it as hot.\n *\n * Runs in screen space so anchor/handle sizes stay constant under zoom.\n * All world-space coords go through `worldToScreen` via the layer's `view`\n * argument.\n */\n\nimport type { DrawCommand } from '@weasel-js/renderer';\nimport type { RenderLayer } from 'core/layers/render';\nimport type { KitSettingsStore } from '@weasel-js/react';\nimport type { PenScratch, PenAnchor, PenSubpath } from 'tools/builtin/pen';\nimport { PATH_C, PATH_L, PATH_M, type PolygonPath, anchorsToPath, circlePath } from '@weasel-js/geom';\n\n/** Appearance of the pen tool's in-progress path. */\nexport interface PenPreviewStyle {\n anchorFill?: string;\n anchorStroke?: string;\n handleStroke?: string;\n rubberBandStroke?: string;\n closeHintFill?: string;\n finishedSubpathStroke?: string;\n}\n\n/** Options for `createPenPreviewLayer`. */\nexport interface CreatePenPreviewLayerOptions {\n /** The pen's state. One object for the pen's life, changed in place, so\n * the layer reads the same one on every frame. */\n state: PenScratch;\n style?: PenPreviewStyle;\n /** The kit settings whose `targets.pen*RadiusPx` size the dots, read each frame. */\n kitSettings?: () => KitSettingsStore;\n}\n\nconst DEFAULT_STYLE: Required<PenPreviewStyle> = {\n anchorFill: '#d4c4a8',\n anchorStroke: '#d4c4a8',\n handleStroke: '#d4c4a8',\n rubberBandStroke: '#d4c4a8',\n closeHintFill: '#d4c4a8',\n finishedSubpathStroke: '#8a7a5e',\n};\n\nexport const ANCHOR_RADIUS_PX = 4;\nexport const HANDLE_DOT_RADIUS_PX = 3;\nexport const CLOSE_HINT_RADIUS_PX = 8;\n\n/** How near the pen's first anchor, in screen px, a click closes the subpath. */\nexport const PEN_CLOSE_HIT_PX = 8;\n\n/** The pen's reach in screen px: its own option, else the kit setting, else the constant. */\nexport const penReachOf = (o: { closeHitRadius?: number; kitSettings?: KitSettingsStore }) => ({\n close: o.closeHitRadius ?? o.kitSettings?.get('targets.penCloseHitPx') ?? PEN_CLOSE_HIT_PX,\n});\n\nconst radiiOf = (kit: KitSettingsStore | undefined) => ({\n anchor: kit?.get('targets.penAnchorRadiusPx') ?? ANCHOR_RADIUS_PX,\n handleDot: kit?.get('targets.penHandleDotRadiusPx') ?? HANDLE_DOT_RADIUS_PX,\n closeHint: kit?.get('targets.penCloseHintRadiusPx') ?? CLOSE_HINT_RADIUS_PX,\n});\n\nfunction w2s(wx: number, wy: number, view: { x: number; y: number; scale: { x: number; y: number } }): [number, number] {\n return [(wx - view.x) * view.scale.x, (wy - view.y) * view.scale.y];\n}\n\n// approximateCircle has moved to `./markers.ts` as `circlePath`. Re-exported\n// locally so we don't rename callers in this file.\nfunction approximateCircle(cx: number, cy: number, r: number): PolygonPath {\n return circlePath(cx, cy, r);\n}\n\n/** A pen subpath as a screen-space `PolygonPath`, segmented by the same rule\n * the pen commits with. */\nfunction subpathToPath(\n sp: PenSubpath,\n view: { x: number; y: number; scale: { x: number; y: number } },\n): PolygonPath | null {\n if (sp.anchors.length === 0) return null;\n const pt = (p: { x: number; y: number }) => {\n const [x, y] = w2s(p.x, p.y, view);\n return { x, y };\n };\n const anchors = sp.anchors.map((a: PenAnchor) => ({\n ...pt(a),\n ...(a.inHandle ? { inHandle: pt(a.inHandle) } : {}),\n ...(a.outHandle ? { outHandle: pt(a.outHandle) } : {}),\n }));\n return anchorsToPath([anchors], [sp.closed]);\n}\n\n/** Render layer that draws the pen tool's path as it is being placed —\n * committed anchors, the rubber band to the cursor, and the close hint. Draws\n * nothing when the pen is idle. */\nexport function createPenPreviewLayer(\n opts: CreatePenPreviewLayerOptions,\n): RenderLayer<unknown> {\n const style = { ...DEFAULT_STYLE, ...(opts.style ?? {}) };\n const s = opts.state;\n\n return {\n id: 'penPreview',\n label: 'Pen preview',\n space: 'screen',\n draw: (_data, view) => {\n const out: DrawCommand[] = [];\n const r = radiiOf(opts.kitSettings?.());\n // (1) Finished subpaths — faded outline.\n for (const sp of s.finishedSubpaths) {\n const path = subpathToPath(sp, view);\n if (path === null) continue;\n out.push({\n kind: 'path',\n path,\n stroke: { paint: { kind: 'solid', color: style.finishedSubpathStroke }, width: 1 },\n });\n }\n\n const cur = s.current;\n if (!cur && s.cursor === null) return out;\n\n // (2) Current subpath — bright outline.\n if (cur) {\n const path = subpathToPath(cur, view);\n if (path !== null) {\n out.push({\n kind: 'path',\n path,\n stroke: { paint: { kind: 'solid', color: style.rubberBandStroke }, width: 1 },\n });\n }\n }\n\n // (3) Rubber-band from latest anchor to cursor.\n if (cur && cur.anchors.length > 0 && s.cursor && s.draggingHandleAt === null) {\n const last = cur.anchors[cur.anchors.length - 1];\n const out2 = last.outHandle;\n const [sx, sy] = w2s(last.x, last.y, view);\n const [cx, cy] = w2s(s.cursor.x, s.cursor.y, view);\n let path: PolygonPath;\n if (out2) {\n const [c1x, c1y] = w2s(out2.x, out2.y, view);\n path = {\n kind: 'polygon',\n commands: new Uint8Array([PATH_M, PATH_C]),\n coords: new Float32Array([sx, sy, c1x, c1y, cx, cy, cx, cy]),\n fillRule: 'nonzero',\n };\n } else {\n path = {\n kind: 'polygon',\n commands: new Uint8Array([PATH_M, PATH_L]),\n coords: new Float32Array([sx, sy, cx, cy]),\n fillRule: 'nonzero',\n };\n }\n out.push({\n kind: 'path',\n path,\n stroke: { paint: { kind: 'solid', color: style.rubberBandStroke }, width: 1 },\n });\n }\n\n // (4) Anchor dots + handles.\n if (cur) {\n for (let i = 0; i < cur.anchors.length; i++) {\n const a = cur.anchors[i];\n const [ax, ay] = w2s(a.x, a.y, view);\n out.push({\n kind: 'path',\n path: approximateCircle(ax, ay, r.anchor),\n fill: { paint: { kind: 'solid', color: style.anchorFill } },\n stroke: { paint: { kind: 'solid', color: style.anchorStroke }, width: 1 },\n });\n // Handle line + dot (only the latest anchor, per spec).\n if (i === cur.anchors.length - 1 && a.outHandle) {\n const [hx, hy] = w2s(a.outHandle.x, a.outHandle.y, view);\n const linePath: PolygonPath = {\n kind: 'polygon',\n commands: new Uint8Array([PATH_M, PATH_L]),\n coords: new Float32Array([ax, ay, hx, hy]),\n fillRule: 'nonzero',\n };\n out.push({\n kind: 'path',\n path: linePath,\n stroke: { paint: { kind: 'solid', color: style.handleStroke }, width: 1 },\n });\n out.push({\n kind: 'path',\n path: approximateCircle(hx, hy, r.handleDot),\n fill: { paint: { kind: 'solid', color: style.handleStroke } },\n });\n const inSide = a.inHandle;\n if (inSide) {\n const [mx, my] = w2s(inSide.x, inSide.y, view);\n const inLine: PolygonPath = {\n kind: 'polygon',\n commands: new Uint8Array([PATH_M, PATH_L]),\n coords: new Float32Array([ax, ay, mx, my]),\n fillRule: 'nonzero',\n };\n out.push({\n kind: 'path',\n path: inLine,\n stroke: { paint: { kind: 'solid', color: style.handleStroke }, width: 1 },\n });\n out.push({\n kind: 'path',\n path: approximateCircle(mx, my, r.handleDot),\n fill: { paint: { kind: 'solid', color: style.handleStroke } },\n });\n }\n }\n }\n\n // (5) Close-hint ring on first anchor.\n if (s.closeHintActive && cur.anchors.length >= 3) {\n const first = cur.anchors[0];\n const [fx, fy] = w2s(first.x, first.y, view);\n out.push({\n kind: 'path',\n path: approximateCircle(fx, fy, r.closeHint),\n stroke: { paint: { kind: 'solid', color: style.closeHintFill }, width: 1.5 },\n });\n }\n }\n\n return out;\n },\n };\n}\n"],"mappings":";;;AAsCA,IAAM,gBAA2C;CAC/C,YAAY;CACZ,cAAc;CACd,cAAc;CACd,kBAAkB;CAClB,eAAe;CACf,uBAAuB;AACzB;AAEA,IAAa,mBAAmB;AAChC,IAAa,uBAAuB;AACpC,IAAa,uBAAuB;;AAGpC,IAAa,mBAAmB;;AAGhC,IAAa,cAAc,OAAoE,EAC7F,OAAO,EAAE,kBAAkB,EAAE,aAAa,IAAI,uBAAuB,KAAK,iBAC5E;AAEA,IAAM,WAAW,SAAuC;CACtD,QAAQ,KAAK,IAAI,2BAA2B,KAAK;CACjD,WAAW,KAAK,IAAI,8BAA8B,KAAK;CACvD,WAAW,KAAK,IAAI,8BAA8B,KAAK;AACzD;AAEA,SAAS,IAAI,IAAY,IAAY,MAAmF;CACtH,OAAO,EAAE,KAAK,KAAK,KAAK,KAAK,MAAM,IAAI,KAAK,KAAK,KAAK,KAAK,MAAM,CAAC;AACpE;AAIA,SAAS,kBAAkB,IAAY,IAAY,GAAwB;CACzE,OAAO,WAAW,IAAI,IAAI,CAAC;AAC7B;;;AAIA,SAAS,cACP,IACA,MACoB;CACpB,IAAI,GAAG,QAAQ,WAAW,GAAG,OAAO;CACpC,MAAM,MAAM,MAAgC;EAC1C,MAAM,CAAC,GAAG,KAA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KAAK;MACP,MAAM;MACN,MAAM,kBAAkB,IAAI,IAAI,EAAE,SAAS;MAC3C,QAAQ;OAAE,OAAO;QAAE,MAAM;QAAS,OAAO,MAAM;OAAc;OAAG,OAAO;MAAI;KAC7E,CAAC;IACH;GACF;GAEA,OAAO;EACT;CACF;AACF"}
1
+ {"version":3,"file":"penPreviewLayer.js","names":[],"sources":["../../../src/domains/paths/penPreviewLayer.ts"],"sourcesContent":["/**\n * Screen-space preview layer for `usePenTool`. Reads the pen's state each\n * frame and renders the in-progress path: finished\n * subpaths (faded), the current subpath (bright + anchor dots + handles),\n * a rubber-band segment from the latest anchor to the cursor, and a\n * close-hint ring on the first anchor when the tool flags it as hot.\n *\n * Runs in screen space so anchor/handle sizes stay constant under zoom.\n * All world-space coords go through `viewWorldToScreen` with the layer's `view`\n * argument.\n */\n\nimport type { DrawCommand } from '@weasel-js/renderer';\nimport type { RenderLayer } from 'core/layers/render';\nimport type { KitSettingsStore } from '@weasel-js/react';\nimport type { PenScratch, PenAnchor, PenSubpath } from 'tools/builtin/pen';\nimport { PATH_C, PATH_L, PATH_M, type PolygonPath, anchorsToPath, circlePath, viewWorldToScreen } from '@weasel-js/geom';\n\n/** Appearance of the pen tool's in-progress path. */\nexport interface PenPreviewStyle {\n anchorFill?: string;\n anchorStroke?: string;\n handleStroke?: string;\n rubberBandStroke?: string;\n closeHintFill?: string;\n finishedSubpathStroke?: string;\n}\n\n/** Options for `createPenPreviewLayer`. */\nexport interface CreatePenPreviewLayerOptions {\n /** The pen's state. One object for the pen's life, changed in place, so\n * the layer reads the same one on every frame. */\n state: PenScratch;\n style?: PenPreviewStyle;\n /** The kit settings whose `targets.pen*RadiusPx` size the dots, read each frame. */\n kitSettings?: () => KitSettingsStore;\n}\n\nconst DEFAULT_STYLE: Required<PenPreviewStyle> = {\n anchorFill: '#d4c4a8',\n anchorStroke: '#d4c4a8',\n handleStroke: '#d4c4a8',\n rubberBandStroke: '#d4c4a8',\n closeHintFill: '#d4c4a8',\n finishedSubpathStroke: '#8a7a5e',\n};\n\nexport const ANCHOR_RADIUS_PX = 4;\nexport const HANDLE_DOT_RADIUS_PX = 3;\nexport const CLOSE_HINT_RADIUS_PX = 8;\n\n/** How near the pen's first anchor, in screen px, a click closes the subpath. */\nexport const PEN_CLOSE_HIT_PX = 8;\n\n/** The pen's reach in screen px: its own option, else the kit setting, else the constant. */\nexport const penReachOf = (o: { closeHitRadius?: number; kitSettings?: KitSettingsStore }) => ({\n close: o.closeHitRadius ?? o.kitSettings?.get('targets.penCloseHitPx') ?? PEN_CLOSE_HIT_PX,\n});\n\nconst radiiOf = (kit: KitSettingsStore | undefined) => ({\n anchor: kit?.get('targets.penAnchorRadiusPx') ?? ANCHOR_RADIUS_PX,\n handleDot: kit?.get('targets.penHandleDotRadiusPx') ?? HANDLE_DOT_RADIUS_PX,\n closeHint: kit?.get('targets.penCloseHintRadiusPx') ?? CLOSE_HINT_RADIUS_PX,\n});\n\n// approximateCircle has moved to `./markers.ts` as `circlePath`. Re-exported\n// locally so we don't rename callers in this file.\nfunction approximateCircle(cx: number, cy: number, r: number): PolygonPath {\n return circlePath(cx, cy, r);\n}\n\n/** A pen subpath as a screen-space `PolygonPath`, segmented by the same rule\n * the pen commits with. */\nfunction subpathToPath(\n sp: PenSubpath,\n view: { x: number; y: number; scale: { x: number; y: number } },\n): PolygonPath | null {\n if (sp.anchors.length === 0) return null;\n const pt = (p: { x: number; y: number }) => {\n const { x: x, y: y } = viewWorldToScreen(view, p);\n return { x, y };\n };\n const anchors = sp.anchors.map((a: PenAnchor) => ({\n ...pt(a),\n ...(a.inHandle ? { inHandle: pt(a.inHandle) } : {}),\n ...(a.outHandle ? { outHandle: pt(a.outHandle) } : {}),\n }));\n return anchorsToPath([anchors], [sp.closed]);\n}\n\n/** Render layer that draws the pen tool's path as it is being placed —\n * committed anchors, the rubber band to the cursor, and the close hint. Draws\n * nothing when the pen is idle. */\nexport function createPenPreviewLayer(\n opts: CreatePenPreviewLayerOptions,\n): RenderLayer<unknown> {\n const style = { ...DEFAULT_STYLE, ...(opts.style ?? {}) };\n const s = opts.state;\n\n return {\n id: 'penPreview',\n label: 'Pen preview',\n space: 'screen',\n draw: (_data, view) => {\n const out: DrawCommand[] = [];\n const r = radiiOf(opts.kitSettings?.());\n // (1) Finished subpaths — faded outline.\n for (const sp of s.finishedSubpaths) {\n const path = subpathToPath(sp, view);\n if (path === null) continue;\n out.push({\n kind: 'path',\n path,\n stroke: { paint: { kind: 'solid', color: style.finishedSubpathStroke }, width: 1 },\n });\n }\n\n const cur = s.current;\n if (!cur && s.cursor === null) return out;\n\n // (2) Current subpath — bright outline.\n if (cur) {\n const path = subpathToPath(cur, view);\n if (path !== null) {\n out.push({\n kind: 'path',\n path,\n stroke: { paint: { kind: 'solid', color: style.rubberBandStroke }, width: 1 },\n });\n }\n }\n\n // (3) Rubber-band from latest anchor to cursor.\n if (cur && cur.anchors.length > 0 && s.cursor && s.draggingHandleAt === null) {\n const last = cur.anchors[cur.anchors.length - 1];\n const out2 = last.outHandle;\n const { x: sx, y: sy } = viewWorldToScreen(view, last);\n const { x: cx, y: cy } = viewWorldToScreen(view, s.cursor);\n let path: PolygonPath;\n if (out2) {\n const { x: c1x, y: c1y } = viewWorldToScreen(view, out2);\n path = {\n kind: 'polygon',\n commands: new Uint8Array([PATH_M, PATH_C]),\n coords: new Float32Array([sx, sy, c1x, c1y, cx, cy, cx, cy]),\n fillRule: 'nonzero',\n };\n } else {\n path = {\n kind: 'polygon',\n commands: new Uint8Array([PATH_M, PATH_L]),\n coords: new Float32Array([sx, sy, cx, cy]),\n fillRule: 'nonzero',\n };\n }\n out.push({\n kind: 'path',\n path,\n stroke: { paint: { kind: 'solid', color: style.rubberBandStroke }, width: 1 },\n });\n }\n\n // (4) Anchor dots + handles.\n if (cur) {\n for (let i = 0; i < cur.anchors.length; i++) {\n const a = cur.anchors[i];\n const { x: ax, y: ay } = viewWorldToScreen(view, a);\n out.push({\n kind: 'path',\n path: approximateCircle(ax, ay, r.anchor),\n fill: { paint: { kind: 'solid', color: style.anchorFill } },\n stroke: { paint: { kind: 'solid', color: style.anchorStroke }, width: 1 },\n });\n // Handle line + dot (only the latest anchor, per spec).\n if (i === cur.anchors.length - 1 && a.outHandle) {\n const { x: hx, y: hy } = viewWorldToScreen(view, a.outHandle);\n const linePath: PolygonPath = {\n kind: 'polygon',\n commands: new Uint8Array([PATH_M, PATH_L]),\n coords: new Float32Array([ax, ay, hx, hy]),\n fillRule: 'nonzero',\n };\n out.push({\n kind: 'path',\n path: linePath,\n stroke: { paint: { kind: 'solid', color: style.handleStroke }, width: 1 },\n });\n out.push({\n kind: 'path',\n path: approximateCircle(hx, hy, r.handleDot),\n fill: { paint: { kind: 'solid', color: style.handleStroke } },\n });\n const inSide = a.inHandle;\n if (inSide) {\n const { x: mx, y: my } = viewWorldToScreen(view, inSide);\n const inLine: PolygonPath = {\n kind: 'polygon',\n commands: new Uint8Array([PATH_M, PATH_L]),\n coords: new Float32Array([ax, ay, mx, my]),\n fillRule: 'nonzero',\n };\n out.push({\n kind: 'path',\n path: inLine,\n stroke: { paint: { kind: 'solid', color: style.handleStroke }, width: 1 },\n });\n out.push({\n kind: 'path',\n path: approximateCircle(mx, my, r.handleDot),\n fill: { paint: { kind: 'solid', color: style.handleStroke } },\n });\n }\n }\n }\n\n // (5) Close-hint ring on first anchor.\n if (s.closeHintActive && cur.anchors.length >= 3) {\n const first = cur.anchors[0];\n const { x: fx, y: fy } = viewWorldToScreen(view, first);\n out.push({\n kind: 'path',\n path: approximateCircle(fx, fy, r.closeHint),\n stroke: { paint: { kind: 'solid', color: style.closeHintFill }, width: 1.5 },\n });\n }\n }\n\n return out;\n },\n };\n}\n"],"mappings":";;;AAsCA,IAAM,gBAA2C;CAC/C,YAAY;CACZ,cAAc;CACd,cAAc;CACd,kBAAkB;CAClB,eAAe;CACf,uBAAuB;AACzB;AAEA,IAAa,mBAAmB;AAChC,IAAa,uBAAuB;AACpC,IAAa,uBAAuB;;AAGpC,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N,QAAQ;SAAE,OAAO;UAAE,MAAM;UAAS,OAAO,MAAM;SAAa;SAAG,OAAO;QAAE;OAC1E,CAAC;OACD,IAAI,KAAK;QACP,MAAM;QACN,MAAM,kBAAkB,IAAI,IAAI,EAAE,SAAS;QAC3C,MAAM,EAAE,OAAO;SAAE,MAAM;SAAS,OAAO,MAAM;QAAa,EAAE;OAC9D,CAAC;MACH;KACF;IACF;IAGA,IAAI,EAAE,mBAAmB,IAAI,QAAQ,UAAU,GAAG;KAChD,MAAM,QAAQ,IAAI,QAAQ;KAC1B,MAAM,EAAE,GAAG,IAAI,GAAG,OAAO,kBAAkB,MAAM,KAAK;KACtD,IAAI,KAAK;MACP,MAAM;MACN,MAAM,kBAAkB,IAAI,IAAI,EAAE,SAAS;MAC3C,QAAQ;OAAE,OAAO;QAAE,MAAM;QAAS,OAAO,MAAM;OAAc;OAAG,OAAO;MAAI;KAC7E,CAAC;IACH;GACF;GAEA,OAAO;EACT;CACF;AACF"}
@@ -1,4 +1,4 @@
1
- import { boundsOfPath, boxToBox, originOf, poseFrameOf, regularPolygonPath, starPath, transformPath, worldCoords, worldEditToStorage } from "@weasel-js/geom";
1
+ import { boundsOfPath, boxToBox, clamp, originOf, poseFrameOf, regularPolygonPath, starPath, transformPath, worldCoords, worldEditToStorage } from "@weasel-js/geom";
2
2
 
3
3
  // src/domains/paths/shapeGenerator.ts
4
4
  /**
@@ -37,7 +37,6 @@ function shapeGeneratorOf(data) {
37
37
  const g = data?.generator;
38
38
  return isShapeGenerator(g) ? g : null;
39
39
  }
40
- var clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
41
40
  var count = (v) => clamp(Math.round(v), SHAPE_COUNT_RANGE.min, SHAPE_COUNT_RANGE.max);
42
41
  /** `g` with its counts rounded and every field held in range. */
43
42
  function clampShapeGenerator(g) {
@@ -1 +1 @@
1
- {"version":3,"file":"shapeGenerator.js","names":[],"sources":["../../../src/domains/paths/shapeGenerator.ts"],"sourcesContent":["/**\n * The parameters a polygon or star was drawn with, kept on the node beside the\n * geometry they made (`data.generator` beside `data.path`), so the shape stays\n * editable as a polygon or a star after it is drawn.\n *\n * `data.path` stays the geometry every reader uses; the generator only says how\n * to make it again. Editing the path itself turns the shape into plain\n * geometry: the generator is dropped, since it could no longer reproduce what\n * is drawn. A generator whose path no longer matches it (a writer that changed\n * the path without dropping it) is treated the same way.\n */\nimport {\n boundsOfPath,\n boxToBox,\n poseFrameOf,\n regularPolygonPath,\n starPath,\n transformPath,\n originOf,\n worldCoords,\n worldEditToStorage,\n type PathInWorldPose,\n type PolygonPath,\n} from '@weasel-js/geom';\n\n/** A regular polygon's parameters. `rotation` is the angle of its first\n * vertex, in radians, inside the pose's own rotation. */\nexport interface PolygonGenerator {\n kind: 'polygon';\n sides: number;\n rotation: number;\n}\n\n/** A star's parameters. `innerRadiusRatio` is the inner radius over the outer\n * one; `rotation` is the angle of its first point, in radians, inside the\n * pose's own rotation. */\nexport interface StarGenerator {\n kind: 'star';\n points: number;\n innerRadiusRatio: number;\n rotation: number;\n}\n\n/** The parameters a node's `data.path` was generated from. */\nexport type ShapeGenerator = PolygonGenerator | StarGenerator;\n\n/** The range of a polygon's side count and a star's point count. */\nexport const SHAPE_COUNT_RANGE = { min: 3, max: 32 } as const;\n\n/** The range of a star's `innerRadiusRatio`. */\nexport const STAR_RATIO_RANGE = { min: 0.01, max: 1 } as const;\n\nconst finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);\n\n/** Whether `v` is a well-formed {@link ShapeGenerator}. */\nexport function isShapeGenerator(v: unknown): v is ShapeGenerator {\n if (v === null || typeof v !== 'object') return false;\n const g = v as Record<string, unknown>;\n if (!finite(g.rotation)) return false;\n if (g.kind === 'polygon') return finite(g.sides);\n if (g.kind === 'star') return finite(g.points) && finite(g.innerRadiusRatio);\n return false;\n}\n\n/** The generator a node's `data` holds, or `null`. */\nexport function shapeGeneratorOf(data: unknown): ShapeGenerator | null {\n const g = (data as { generator?: unknown } | null | undefined)?.generator;\n return isShapeGenerator(g) ? g : null;\n}\n\nconst clamp = (v: number, lo: number, hi: number): number => Math.min(hi, Math.max(lo, v));\nconst count = (v: number): number => clamp(Math.round(v), SHAPE_COUNT_RANGE.min, SHAPE_COUNT_RANGE.max);\n\n/** `g` with its counts rounded and every field held in range. */\nexport function clampShapeGenerator(g: ShapeGenerator): ShapeGenerator {\n if (g.kind === 'polygon') return { kind: 'polygon', sides: count(g.sides), rotation: g.rotation };\n return {\n kind: 'star',\n points: count(g.points),\n innerRadiusRatio: clamp(g.innerRadiusRatio, STAR_RATIO_RANGE.min, STAR_RATIO_RANGE.max),\n rotation: g.rotation,\n };\n}\n\n/** The shape `g` makes, on a circle of `radius` around `center`. */\nexport function shapeGeneratorPath(\n g: ShapeGenerator,\n center: { x: number; y: number } = { x: 0, y: 0 },\n radius = 1,\n): PolygonPath {\n const c = clampShapeGenerator(g);\n return c.kind === 'polygon'\n ? regularPolygonPath(center, radius, c.sides, c.rotation)\n : starPath(center, radius, c.points, radius * c.innerRadiusRatio, c.rotation);\n}\n\n/** `data` without its generator: the shape as plain geometry. */\nexport function withoutShapeGenerator<T>(data: T): T {\n if (data === null || typeof data !== 'object' || !('generator' in data)) return data;\n const { generator: _dropped, ...rest } = data as Record<string, unknown>;\n void _dropped;\n return rest as T;\n}\n\n/** Whether `path` is what `g` makes, up to the box-to-box map storage applies. */\nfunction pathMatches(path: unknown, g: ShapeGenerator): boolean {\n const p = path as PolygonPath | undefined;\n if (p?.kind !== 'polygon') return false;\n const unit = shapeGeneratorPath(g);\n if (p.coords.length !== unit.coords.length) return false;\n const u = boundsOfPath(unit);\n const b = boundsOfPath(p);\n const m = boxToBox(u.x, u.y, u.width, u.height, b.x, b.y, b.width, b.height);\n // Paths store float32 coordinates, so the slack scales with how far they are from the point they are measured from.\n const o = originOf(p);\n const tol = 1e-4 * Math.max(1, Math.abs(b.x - o.x) + b.width, Math.abs(b.y - o.y) + b.height);\n const at = worldCoords(p);\n for (let i = 0; i + 1 < unit.coords.length; i += 2) {\n const x = m[0] * unit.coords[i] + m[4];\n const y = m[3] * unit.coords[i + 1] + m[5];\n if (Math.abs(x - at[i]) > tol || Math.abs(y - at[i + 1]) > tol) return false;\n }\n return true;\n}\n\n/** A node's two halves, as a regeneration reads and writes them. */\nexport interface GeneratedShape<P extends PathInWorldPose = PathInWorldPose> {\n pose: P;\n data: unknown;\n}\n\n/**\n * `node` made again from `next`, in place: the new shape takes the box the old\n * one's circle had, under the same rotation and transform, so a star given\n * more points keeps its center and its size. Returns `null` when the node holds\n * no generator, or its path no longer matches the one it holds.\n */\nexport function regenerateShape<P extends PathInWorldPose>(\n node: GeneratedShape<P>,\n next: ShapeGenerator,\n): GeneratedShape<P> | null {\n const held = shapeGeneratorOf(node.data);\n if (!held || !pathMatches((node.data as { path?: unknown }).path, held)) return null;\n const g = clampShapeGenerator(next);\n const was = boundsOfPath(shapeGeneratorPath(held));\n const { pose } = node;\n // Where the unit circle of the held generator lands in the pose's local frame.\n const toLocal = boxToBox(was.x, was.y, was.width, was.height, pose.x, pose.y, pose.width, pose.height);\n const local = transformPath(shapeGeneratorPath(g), toLocal) as PolygonPath;\n const frame = poseFrameOf(pose);\n const world = frame ? (transformPath(local, frame) as PolygonPath) : local;\n const stored = worldEditToStorage(pose, world);\n return { pose: stored.pose, data: { ...(node.data as object), path: stored.path, generator: g } };\n}\n\n/**\n * What a write that left a node as `next`, from `prev`, stores: when the write\n * changed the generator, the shape made again from it. A generator written\n * onto a node that held none, or of another kind, or onto one whose path no\n * longer matches, is dropped, leaving the shape as plain geometry. Any other\n * write is stored as written. Fits `NodePropertiesEntry.settle`.\n */\nexport function settleShapeGenerator<N extends { pose: unknown; data: unknown }>(next: N, prev: N): N {\n const data = next.data as Record<string, unknown> | null;\n if (data === null || typeof data !== 'object' || !('generator' in data)) return next;\n const raw = data.generator;\n const held = shapeGeneratorOf(prev.data);\n if (held !== null && JSON.stringify(raw) === JSON.stringify(held)) return next;\n const regenerated = held !== null && isShapeGenerator(raw) && raw.kind === held.kind\n ? regenerateShape({ pose: next.pose as PathInWorldPose, data: { ...data, generator: held } }, raw)\n : null;\n return { ...next, ...(regenerated ?? { data: withoutShapeGenerator(next.data) }) };\n}\n"],"mappings":";;;;;;;;;;;;;;;AA+CA,IAAa,oBAAoB;CAAE,KAAK;CAAG,KAAK;AAAG;;AAGnD,IAAa,mBAAmB;CAAE,KAAK;CAAM,KAAK;AAAE;AAEpD,IAAM,UAAU,MAA4B,OAAO,MAAM,YAAY,OAAO,SAAS,CAAC;;AAGtF,SAAgB,iBAAiB,GAAiC;CAChE,IAAI,MAAM,QAAQ,OAAO,MAAM,UAAU,OAAO;CAChD,MAAM,IAAI;CACV,IAAI,CAAC,OAAO,EAAE,QAAQ,GAAG,OAAO;CAChC,IAAI,EAAE,SAAS,WAAW,OAAO,OAAO,EAAE,KAAK;CAC/C,IAAI,EAAE,SAAS,QAAQ,OAAO,OAAO,EAAE,MAAM,KAAK,OAAO,EAAE,gBAAgB;CAC3E,OAAO;AACT;;AAGA,SAAgB,iBAAiB,MAAsC;CACrE,MAAM,IAAK,MAAqD;CAChE,OAAO,iBAAiB,CAAC,IAAI,IAAI;AACnC;AAEA,IAAM,SAAS,GAAW,IAAY,OAAuB,KAAK,IAAI,IAAI,KAAK,IAAI,IAAI,CAAC,CAAC;AACzF,IAAM,SAAS,MAAsB,MAAM,KAAK,MAAM,CAAC,GAAG,kBAAkB,KAAK,kBAAkB,GAAG;;AAGtG,SAAgB,oBAAoB,GAAmC;CACrE,IAAI,EAAE,SAAS,WAAW,OAAO;EAAE,MAAM;EAAW,OAAO,MAAM,EAAE,KAAK;EAAG,UAAU,EAAE;CAAS;CAChG,OAAO;EACL,MAAM;EACN,QAAQ,MAAM,EAAE,MAAM;EACtB,kBAAkB,MAAM,EAAE,kBAAkB,iBAAiB,KAAK,iBAAiB,GAAG;EACtF,UAAU,EAAE;CACd;AACF;;AAGA,SAAgB,mBACd,GACA,SAAmC;CAAE,GAAG;CAAG,GAAG;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 {"version":3,"file":"shapeGenerator.js","names":[],"sources":["../../../src/domains/paths/shapeGenerator.ts"],"sourcesContent":["/**\n * The parameters a polygon or star was drawn with, kept on the node beside the\n * geometry they made (`data.generator` beside `data.path`), so the shape stays\n * editable as a polygon or a star after it is drawn.\n *\n * `data.path` stays the geometry every reader uses; the generator only says how\n * to make it again. Editing the path itself turns the shape into plain\n * geometry: the generator is dropped, since it could no longer reproduce what\n * is drawn. A generator whose path no longer matches it (a writer that changed\n * the path without dropping it) is treated the same way.\n */\nimport {\n boundsOfPath,\n boxToBox,\n clamp,\n poseFrameOf,\n regularPolygonPath,\n starPath,\n transformPath,\n originOf,\n worldCoords,\n worldEditToStorage,\n type PathInWorldPose,\n type PolygonPath,\n} from '@weasel-js/geom';\n\n/** A regular polygon's parameters. `rotation` is the angle of its first\n * vertex, in radians, inside the pose's own rotation. */\nexport interface PolygonGenerator {\n kind: 'polygon';\n sides: number;\n rotation: number;\n}\n\n/** A star's parameters. `innerRadiusRatio` is the inner radius over the outer\n * one; `rotation` is the angle of its first point, in radians, inside the\n * pose's own rotation. */\nexport interface StarGenerator {\n kind: 'star';\n points: number;\n innerRadiusRatio: number;\n rotation: number;\n}\n\n/** The parameters a node's `data.path` was generated from. */\nexport type ShapeGenerator = PolygonGenerator | StarGenerator;\n\n/** The range of a polygon's side count and a star's point count. */\nexport const SHAPE_COUNT_RANGE = { min: 3, max: 32 } as const;\n\n/** The range of a star's `innerRadiusRatio`. */\nexport const STAR_RATIO_RANGE = { min: 0.01, max: 1 } as const;\n\nconst finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);\n\n/** Whether `v` is a well-formed {@link ShapeGenerator}. */\nexport function isShapeGenerator(v: unknown): v is ShapeGenerator {\n if (v === null || typeof v !== 'object') return false;\n const g = v as Record<string, unknown>;\n if (!finite(g.rotation)) return false;\n if (g.kind === 'polygon') return finite(g.sides);\n if (g.kind === 'star') return finite(g.points) && finite(g.innerRadiusRatio);\n return false;\n}\n\n/** The generator a node's `data` holds, or `null`. */\nexport function shapeGeneratorOf(data: unknown): ShapeGenerator | null {\n const g = (data as { generator?: unknown } | null | undefined)?.generator;\n return isShapeGenerator(g) ? g : null;\n}\n\nconst count = (v: number): number => clamp(Math.round(v), SHAPE_COUNT_RANGE.min, SHAPE_COUNT_RANGE.max);\n\n/** `g` with its counts rounded and every field held in range. */\nexport function clampShapeGenerator(g: ShapeGenerator): ShapeGenerator {\n if (g.kind === 'polygon') return { kind: 'polygon', sides: count(g.sides), rotation: g.rotation };\n return {\n kind: 'star',\n points: count(g.points),\n innerRadiusRatio: clamp(g.innerRadiusRatio, STAR_RATIO_RANGE.min, STAR_RATIO_RANGE.max),\n rotation: g.rotation,\n };\n}\n\n/** The shape `g` makes, on a circle of `radius` around `center`. */\nexport function shapeGeneratorPath(\n g: ShapeGenerator,\n center: { x: number; y: number } = { x: 0, y: 0 },\n radius = 1,\n): PolygonPath {\n const c = clampShapeGenerator(g);\n return c.kind === 'polygon'\n ? regularPolygonPath(center, radius, c.sides, c.rotation)\n : starPath(center, radius, c.points, radius * c.innerRadiusRatio, c.rotation);\n}\n\n/** `data` without its generator: the shape as plain geometry. */\nexport function withoutShapeGenerator<T>(data: T): T {\n if (data === null || typeof data !== 'object' || !('generator' in data)) return data;\n const { generator: _dropped, ...rest } = data as Record<string, unknown>;\n void _dropped;\n return rest as T;\n}\n\n/** Whether `path` is what `g` makes, up to the box-to-box map storage applies. */\nfunction pathMatches(path: unknown, g: ShapeGenerator): boolean {\n const p = path as PolygonPath | undefined;\n if (p?.kind !== 'polygon') return false;\n const unit = shapeGeneratorPath(g);\n if (p.coords.length !== unit.coords.length) return false;\n const u = boundsOfPath(unit);\n const b = boundsOfPath(p);\n const m = boxToBox(u.x, u.y, u.width, u.height, b.x, b.y, b.width, b.height);\n // Paths store float32 coordinates, so the slack scales with how far they are from the point they are measured from.\n const o = originOf(p);\n const tol = 1e-4 * Math.max(1, Math.abs(b.x - o.x) + b.width, Math.abs(b.y - o.y) + b.height);\n const at = worldCoords(p);\n for (let i = 0; i + 1 < unit.coords.length; i += 2) {\n const x = m[0] * unit.coords[i] + m[4];\n const y = m[3] * unit.coords[i + 1] + m[5];\n if (Math.abs(x - at[i]) > tol || Math.abs(y - at[i + 1]) > tol) return false;\n }\n return true;\n}\n\n/** A node's two halves, as a regeneration reads and writes them. */\nexport interface GeneratedShape<P extends PathInWorldPose = PathInWorldPose> {\n pose: P;\n data: unknown;\n}\n\n/**\n * `node` made again from `next`, in place: the new shape takes the box the old\n * one's circle had, under the same rotation and transform, so a star given\n * more points keeps its center and its size. Returns `null` when the node holds\n * no generator, or its path no longer matches the one it holds.\n */\nexport function regenerateShape<P extends PathInWorldPose>(\n node: GeneratedShape<P>,\n next: ShapeGenerator,\n): GeneratedShape<P> | null {\n const held = shapeGeneratorOf(node.data);\n if (!held || !pathMatches((node.data as { path?: unknown }).path, held)) return null;\n const g = clampShapeGenerator(next);\n const was = boundsOfPath(shapeGeneratorPath(held));\n const { pose } = node;\n // Where the unit circle of the held generator lands in the pose's local frame.\n const toLocal = boxToBox(was.x, was.y, was.width, was.height, pose.x, pose.y, pose.width, pose.height);\n const local = transformPath(shapeGeneratorPath(g), toLocal) as PolygonPath;\n const frame = poseFrameOf(pose);\n const world = frame ? (transformPath(local, frame) as PolygonPath) : local;\n const stored = worldEditToStorage(pose, world);\n return { pose: stored.pose, data: { ...(node.data as object), path: stored.path, generator: g } };\n}\n\n/**\n * What a write that left a node as `next`, from `prev`, stores: when the write\n * changed the generator, the shape made again from it. A generator written\n * onto a node that held none, or of another kind, or onto one whose path no\n * longer matches, is dropped, leaving the shape as plain geometry. Any other\n * write is stored as written. Fits `NodePropertiesEntry.settle`.\n */\nexport function settleShapeGenerator<N extends { pose: unknown; data: unknown }>(next: N, prev: N): N {\n const data = next.data as Record<string, unknown> | null;\n if (data === null || typeof data !== 'object' || !('generator' in data)) return next;\n const raw = data.generator;\n const held = shapeGeneratorOf(prev.data);\n if (held !== null && JSON.stringify(raw) === JSON.stringify(held)) return next;\n const regenerated = held !== null && isShapeGenerator(raw) && raw.kind === held.kind\n ? regenerateShape({ pose: next.pose as PathInWorldPose, data: { ...data, generator: held } }, raw)\n : null;\n return { ...next, ...(regenerated ?? { data: withoutShapeGenerator(next.data) }) };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgDA,IAAa,oBAAoB;CAAE,KAAK;CAAG,KAAK;AAAG;;AAGnD,IAAa,mBAAmB;CAAE,KAAK;CAAM,KAAK;AAAE;AAEpD,IAAM,UAAU,MAA4B,OAAO,MAAM,YAAY,OAAO,SAAS,CAAC;;AAGtF,SAAgB,iBAAiB,GAAiC;CAChE,IAAI,MAAM,QAAQ,OAAO,MAAM,UAAU,OAAO;CAChD,MAAM,IAAI;CACV,IAAI,CAAC,OAAO,EAAE,QAAQ,GAAG,OAAO;CAChC,IAAI,EAAE,SAAS,WAAW,OAAO,OAAO,EAAE,KAAK;CAC/C,IAAI,EAAE,SAAS,QAAQ,OAAO,OAAO,EAAE,MAAM,KAAK,OAAO,EAAE,gBAAgB;CAC3E,OAAO;AACT;;AAGA,SAAgB,iBAAiB,MAAsC;CACrE,MAAM,IAAK,MAAqD;CAChE,OAAO,iBAAiB,CAAC,IAAI,IAAI;AACnC;AAEA,IAAM,SAAS,MAAsB,MAAM,KAAK,MAAM,CAAC,GAAG,kBAAkB,KAAK,kBAAkB,GAAG;;AAGtG,SAAgB,oBAAoB,GAAmC;CACrE,IAAI,EAAE,SAAS,WAAW,OAAO;EAAE,MAAM;EAAW,OAAO,MAAM,EAAE,KAAK;EAAG,UAAU,EAAE;CAAS;CAChG,OAAO;EACL,MAAM;EACN,QAAQ,MAAM,EAAE,MAAM;EACtB,kBAAkB,MAAM,EAAE,kBAAkB,iBAAiB,KAAK,iBAAiB,GAAG;EACtF,UAAU,EAAE;CACd;AACF;;AAGA,SAAgB,mBACd,GACA,SAAmC;CAAE,GAAG;CAAG,GAAG;AAAE,GAChD,SAAS,GACI;CACb,MAAM,IAAI,oBAAo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";
2
2
  import { screenOf } from "./screen.js";
3
3
  import { stepAngles } from "./stepAngles.js";
4
+ import { RAD_TO_DEG, wrapPositive } from "@weasel-js/geom";
4
5
  import { resolveSnap } from "@weasel-js/geom/nd";
5
6
 
6
7
  // src/domains/snap/angle2d.ts
@@ -140,7 +141,7 @@ function rayMarks(inputs, theta) {
140
141
  x: pivot.x + r * Math.cos(dir),
141
142
  y: pivot.y + r * Math.sin(dir)
142
143
  };
143
- const deg = (Math.round(theta * 180 / Math.PI) % 360 + 360) % 360;
144
+ const deg = wrapPositive(Math.round(theta * RAD_TO_DEG), 360);
144
145
  return [{
145
146
  kind: "line",
146
147
  from: pivot,
@@ -1 +1 @@
1
- {"version":3,"file":"angle2d.js","names":[],"sources":["../../../src/domains/snap/angle2d.ts"],"sourcesContent":["/** A snap session's one-dimensional path: an angle about a pivot, snapped by\n * the same resolver as a point, with reach carried through the radius. */\nimport { resolveSnap, type SnapCandidate } from '@weasel-js/geom/nd';\nimport type { SnapMods } from 'interactions/actions/snapDep';\nimport { distinct, markFromPlane } from './marks';\nimport { screenOf } from './screen';\nimport { stepAngles } from './stepAngles';\nimport type { Session2dInputs } from './session2d';\nimport type { AngleCollect, SnapMark, SnapMarks, SnapSource } from './types';\n\nconst TURN = Math.PI * 2;\nconst PROBE = 'angle';\n/** A press near the pivot turns px reach into a wide angle; it reaches no\n * further than this. */\nconst MAX_REACH_RAD = Math.PI / 6;\n\n/** Where `theta` lands, and what it met. Writes the marks to the store. */\nexport function angleAt(\n inputs: Session2dInputs, sources: readonly SnapSource[], theta: number, mods: SnapMods,\n): { theta: number; marks: readonly SnapMark[] } {\n const { req, store } = inputs;\n // Screen px per radian, or 1 when the gesture gives its reach in radians.\n const scale = req.reachRad !== undefined ? 1 : pressRadiusPx(inputs);\n const reachOf = (s: SnapSource) => req.reachRad\n ?? Math.min(s.reachPx ?? inputs.reachPx, MAX_REACH_RAD * scale);\n const candidates = collectAngles(inputs, sources, theta, mods, reachOf);\n if (candidates.length === 0) {\n store.set([]);\n return { theta, marks: [] };\n }\n const res = resolveSnap({\n probes: [{ id: PROBE, at: [0], role: 'pointer' }],\n input: { at: [0], dirs: [[1]] },\n delta0: [theta],\n candidates,\n // No radius, no reach: only a required angle can win.\n toScreen: ([t]) => [scale > 0 ? t * scale : NaN],\n });\n const out = res.delta[0];\n const marks = distinct(res.satisfied.flatMap((c) => {\n const m = c.mark ?? rayMarks(inputs, out);\n return 'kind' in m ? [m] : m;\n }));\n const plane = req.plane?.() ?? null;\n store.set(plane ? marks.map((m) => markFromPlane(m, plane)) : marks);\n return { theta: out, marks };\n}\n\nfunction collectAngles(\n inputs: Session2dInputs, sources: readonly SnapSource[], theta: number, mods: SnapMods,\n reachOf: (s: SnapSource) => number,\n): SnapCandidate<SnapMarks>[] {\n const { req } = inputs;\n const out: SnapCandidate<SnapMarks>[] = [];\n const c = req.constrain;\n if (mods.constrain && typeof c === 'object' && c.step > 0) {\n for (const at of stepAngles(theta, c.step)) {\n out.push({ probe: PROBE, locus: { at: [at], dirs: [] }, source: 'constrain', order: -1, tier: 'target', reachPx: 0, required: true });\n }\n }\n const theta0 = req.theta0 ?? 0;\n if (mods.hold) {\n const at = theta0 + TURN * Math.round((theta - theta0) / TURN);\n out.push({ probe: PROBE, locus: { at: [at], dirs: [] }, source: 'hold', order: -1, tier: 'target', reachPx: 0, required: true, mark: [] });\n }\n if (mods.suspend) return out;\n const q: AngleCollect = {\n pivot: req.pivot ?? req.press,\n press: req.press,\n theta0,\n theta,\n ids: req.ids ?? [],\n exclude: inputs.exclude ?? req.ids ?? [],\n mods,\n ...(req.also ? { also: req.also } : {}),\n ...(inputs.scene ? { scene: inputs.scene } : {}),\n ...(inputs.rotationOf ? { rotationOf: inputs.rotationOf } : {}),\n };\n // Runs across sources and their yields: an earlier source, then an earlier\n // yield, wins a tie.\n let order = 0;\n sources.forEach((source) => {\n if (!source.angles) return;\n const reachPx = reachOf(source);\n for (const a of source.angles(q)) {\n // The whole turn of the angle nearest `theta`: 0 catches 359°.\n const at = a.angle + TURN * Math.round((theta - a.angle) / TURN);\n out.push({\n probe: PROBE, locus: { at: [at], dirs: [] }, source: source.id, order: order++, tier: source.tier ?? 'target', reachPx,\n ...(a.required ? { required: true } : {}),\n ...(a.mark ? { mark: a.mark } : {}),\n });\n }\n });\n return out;\n}\n\n/** The screen distance from the pivot to the press: what turns reach in px\n * into radians. */\nfunction pressRadiusPx(inputs: Session2dInputs): number {\n const { req } = inputs;\n const pivot = req.pivot ?? req.press;\n const toScreen = screenOf(inputs.view(), req.plane?.() ?? null);\n const [ax, ay] = toScreen([pivot.x, pivot.y]);\n const [bx, by] = toScreen([req.press.x, req.press.y]);\n return Math.hypot(bx - ax, by - ay);\n}\n\n/** A ray from the pivot out to the press radius, along where the pointer\n * lands at `theta`, labeled with `theta` in degrees. */\nfunction rayMarks(inputs: Session2dInputs, theta: number): SnapMark[] {\n const { req } = inputs;\n const pivot = req.pivot ?? req.press;\n const r = Math.hypot(req.press.x - pivot.x, req.press.y - pivot.y);\n const dir = Math.atan2(req.press.y - pivot.y, req.press.x - pivot.x) + theta - (req.theta0 ?? 0);\n const end = { x: pivot.x + r * Math.cos(dir), y: pivot.y + r * Math.sin(dir) };\n const deg = ((Math.round(theta * 180 / Math.PI) % 360) + 360) % 360;\n return [\n { kind: 'line', from: pivot, to: end },\n { kind: 'point', at: end, glyph: 'quadrant', label: `${deg}°` },\n ];\n}\n"],"mappings":";;;;;;;;AAUA,IAAM,OAAO,KAAK,KAAK;AACvB,IAAM,QAAQ;;;AAGd,IAAM,gBAAgB,KAAK,KAAK;;AAGhC,SAAgB,QACd,QAAyB,SAAgC,OAAe,MACzB;CAC/C,MAAM,EAAE,KAAK,UAAU;CAEvB,MAAM,QAAQ,IAAI,aAAa,SAAY,IAAI,cAAc,MAAM;CACnE,MAAM,WAAW,MAAkB,IAAI,YAClC,KAAK,IAAI,EAAE,WAAW,OAAO,SAAS,gBAAgB,KAAK;CAChE,MAAM,aAAa,cAAc,QAAQ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AI,SAAS,IAAI;CAC/B,MAAM,WAAW,SAAS,OAAO,KAAK,GAAG,IAAI,QAAQ,KAAK,IAAI;CAC9D,MAAM,CAAC,IAAI,MAAM,SAAS,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC;CAC5C,MAAM,CAAC,IAAI,MAAM,SAAS,CAAC,IAAI,MAAM,GAAG,IAAI,MAAM,CAAC,CAAC;CACpD,OAAO,KAAK,MAAM,KAAK,IAAI,KAAK,EAAE;AACpC;;;AAIA,SAAS,SAAS,QAAyB,OAA2B;CACpE,MAAM,EAAE,QAAQ;CAChB,MAAM,QAAQ,IAAI,SAAS,IAAI;CAC/B,MAAM,IAAI,KAAK,MAAM,IAAI,MAAM,IAAI,MAAM,GAAG,IAAI,MAAM,IAAI,MAAM,CAAC;CACjE,MAAM,MAAM,KAAK,MAAM,IAAI,MAAM,IAAI,MAAM,GAAG,IAAI,MAAM,IAAI,MAAM,CAAC,IAAI,SAAS,IAAI,UAAU;CAC9F,MAAM,MAAM;EAAE,GAAG,MAAM,IAAI,IAAI,KAAK,IAAI,GAAG;EAAG,GAAG,MAAM,IAAI,IAAI,KAAK,IAAI,GAAG;CAAE;CAC7E,MAAM,OAAQ,KAAK,MAAM,QAAQ,MAAM,KAAK,EAAE,IAAI,MAAO,OAAO;CAChE,OAAO,CACL;EAAE,MAAM;EAAQ,MAAM;EAAO,IAAI;CAAI,GACrC;EAAE,MAAM;EAAS,IAAI;EAAK,OAAO;EAAY,OAAO,GAAG,IAAI;CAAG,CAChE;AACF"}
1
+ {"version":3,"file":"angle2d.js","names":[],"sources":["../../../src/domains/snap/angle2d.ts"],"sourcesContent":["/** A snap session's one-dimensional path: an angle about a pivot, snapped by\n * the same resolver as a point, with reach carried through the radius. */\nimport { RAD_TO_DEG, wrapPositive } from '@weasel-js/geom';\nimport { resolveSnap, type SnapCandidate } from '@weasel-js/geom/nd';\nimport type { SnapMods } from 'interactions/actions/snapDep';\nimport { distinct, markFromPlane } from './marks';\nimport { screenOf } from './screen';\nimport { stepAngles } from './stepAngles';\nimport type { Session2dInputs } from './session2d';\nimport type { AngleCollect, SnapMark, SnapMarks, SnapSource } from './types';\n\nconst TURN = Math.PI * 2;\nconst PROBE = 'angle';\n/** A press near the pivot turns px reach into a wide angle; it reaches no\n * further than this. */\nconst MAX_REACH_RAD = Math.PI / 6;\n\n/** Where `theta` lands, and what it met. Writes the marks to the store. */\nexport function angleAt(\n inputs: Session2dInputs, sources: readonly SnapSource[], theta: number, mods: SnapMods,\n): { theta: number; marks: readonly SnapMark[] } {\n const { req, store } = inputs;\n // Screen px per radian, or 1 when the gesture gives its reach in radians.\n const scale = req.reachRad !== undefined ? 1 : pressRadiusPx(inputs);\n const reachOf = (s: SnapSource) => req.reachRad\n ?? Math.min(s.reachPx ?? inputs.reachPx, MAX_REACH_RAD * scale);\n const candidates = collectAngles(inputs, sources, theta, mods, reachOf);\n if (candidates.length === 0) {\n store.set([]);\n return { theta, marks: [] };\n }\n const res = resolveSnap({\n probes: [{ id: PROBE, at: [0], role: 'pointer' }],\n input: { at: [0], dirs: [[1]] },\n delta0: [theta],\n candidates,\n // No radius, no reach: only a required angle can win.\n toScreen: ([t]) => [scale > 0 ? t * scale : NaN],\n });\n const out = res.delta[0];\n const marks = distinct(res.satisfied.flatMap((c) => {\n const m = c.mark ?? rayMarks(inputs, out);\n return 'kind' in m ? [m] : m;\n }));\n const plane = req.plane?.() ?? null;\n store.set(plane ? marks.map((m) => markFromPlane(m, plane)) : marks);\n return { theta: out, marks };\n}\n\nfunction collectAngles(\n inputs: Session2dInputs, sources: readonly SnapSource[], theta: number, mods: SnapMods,\n reachOf: (s: SnapSource) => number,\n): SnapCandidate<SnapMarks>[] {\n const { req } = inputs;\n const out: SnapCandidate<SnapMarks>[] = [];\n const c = req.constrain;\n if (mods.constrain && typeof c === 'object' && c.step > 0) {\n for (const at of stepAngles(theta, c.step)) {\n out.push({ probe: PROBE, locus: { at: [at], dirs: [] }, source: 'constrain', order: -1, tier: 'target', reachPx: 0, required: true });\n }\n }\n const theta0 = req.theta0 ?? 0;\n if (mods.hold) {\n const at = theta0 + TURN * Math.round((theta - theta0) / TURN);\n out.push({ probe: PROBE, locus: { at: [at], dirs: [] }, source: 'hold', order: -1, tier: 'target', reachPx: 0, required: true, mark: [] });\n }\n if (mods.suspend) return out;\n const q: AngleCollect = {\n pivot: req.pivot ?? req.press,\n press: req.press,\n theta0,\n theta,\n ids: req.ids ?? [],\n exclude: inputs.exclude ?? req.ids ?? [],\n mods,\n ...(req.also ? { also: req.also } : {}),\n ...(inputs.scene ? { scene: inputs.scene } : {}),\n ...(inputs.rotationOf ? { rotationOf: inputs.rotationOf } : {}),\n };\n // Runs across sources and their yields: an earlier source, then an earlier\n // yield, wins a tie.\n let order = 0;\n sources.forEach((source) => {\n if (!source.angles) return;\n const reachPx = reachOf(source);\n for (const a of source.angles(q)) {\n // The whole turn of the angle nearest `theta`: 0 catches 359°.\n const at = a.angle + TURN * Math.round((theta - a.angle) / TURN);\n out.push({\n probe: PROBE, locus: { at: [at], dirs: [] }, source: source.id, order: order++, tier: source.tier ?? 'target', reachPx,\n ...(a.required ? { required: true } : {}),\n ...(a.mark ? { mark: a.mark } : {}),\n });\n }\n });\n return out;\n}\n\n/** The screen distance from the pivot to the press: what turns reach in px\n * into radians. */\nfunction pressRadiusPx(inputs: Session2dInputs): number {\n const { req } = inputs;\n const pivot = req.pivot ?? req.press;\n const toScreen = screenOf(inputs.view(), req.plane?.() ?? null);\n const [ax, ay] = toScreen([pivot.x, pivot.y]);\n const [bx, by] = toScreen([req.press.x, req.press.y]);\n return Math.hypot(bx - ax, by - ay);\n}\n\n/** A ray from the pivot out to the press radius, along where the pointer\n * lands at `theta`, labeled with `theta` in degrees. */\nfunction rayMarks(inputs: Session2dInputs, theta: number): SnapMark[] {\n const { req } = inputs;\n const pivot = req.pivot ?? req.press;\n const r = Math.hypot(req.press.x - pivot.x, req.press.y - pivot.y);\n const dir = Math.atan2(req.press.y - pivot.y, req.press.x - pivot.x) + theta - (req.theta0 ?? 0);\n const end = { x: pivot.x + r * Math.cos(dir), y: pivot.y + r * Math.sin(dir) };\n const deg = wrapPositive(Math.round(theta * RAD_TO_DEG), 360);\n return [\n { kind: 'line', from: pivot, to: end },\n { kind: 'point', at: end, glyph: 'quadrant', label: `${deg}°` },\n ];\n}\n"],"mappings":";;;;;;;;;AAWA,IAAM,OAAO,KAAK,KAAK;AACvB,IAAM,QAAQ;;;AAGd,IAAM,gBAAgB,KAAK,KAAK;;AAGhC,SAAgB,QACd,QAAyB,SAAgC,OAAe,MACzB;CAC/C,MAAM,EAAE,KAAK,UAAU;CAEvB,MAAM,QAAQ,IAAI,aAAa,SAAY,IAAI,cAAc,MAAM;CACnE,MAAM,WAAW,MAAkB,IAAI,YAClC,KAAK,IAAI,EAAE,WAAW,OAAO,SAAS,gBAAgB,KAAK;CAChE,MAAM,aAAa,cAAc,QAAQ,SAAS,OAAO,MAAM,OAAO;CACtE,IAAI,WAAW,WAAW,GAAG;EAC3B,MAAM,IAAI,CAAC,CAAC;EACZ,OAAO;GAAE;GAAO,OAAO,CAAC;EAAE;CAC5B;CACA,MAAM,MAAM,YAAY;EACtB,QAAQ,CAAC;GAAE,IAAI;GAAO,IAAI,CAAC,CAAC;GAAG,MAAM;EAAU,CAAC;EAChD,OAAO;GAAE,IAAI,CAAC,CAAC;GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;EAAE;EAC9B,QAAQ,CAAC,KAAK;EACd;EAEA,WAAW,CAAC,OAAO,CAAC,QAAQ,IAAI,IAAI,QAAQ,GAAG;CACjD,CAAC;CACD,MAAM,MAAM,IAAI,MAAM;CACtB,MAAM,QAAQ,SAAS,IAAI,UAAU,SAAS,MAAM;EAClD,MAAM,IAAI,EAAE,QAAQ,SAAS,QAAQ,GAAG;EACxC,OAAO,UAAU,IAAI,CAAC,CAAC,IAAI;CAC7B,CAAC,CAAC;CACF,MAAM,QAAQ,IAAI,QAAQ,KAAK;CAC/B,MAAM,IAAI,QAAQ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GAAG,MAAM,IAAI,IAAI,KAAK,IAAI,GAAG;CAAE;CAC7E,MAAM,MAAM,aAAa,KAAK,MAAM,QAAQ,UAAU,GAAG,GAAG;CAC5D,OAAO,CACL;EAAE,MAAM;EAAQ,MAAM;EAAO,IAAI;CAAI,GACrC;EAAE,MAAM;EAAS,IAAI;EAAK,OAAO;EAAY,OAAO,GAAG,IAAI;CAAG,CAChE;AACF"}
@@ -1,22 +1,19 @@
1
+ import { createEmitter } from "@weasel-js/registry";
2
+
1
3
  // src/domains/snap/outcomeStore.ts
2
4
  var NONE = [];
3
5
  /** An empty outcome store, which notifies only when the marks change. */
4
6
  function createSnapOutcomeStore() {
5
7
  let marks = NONE;
6
- const listeners = /* @__PURE__ */ new Set();
8
+ const changed = createEmitter();
7
9
  return {
8
10
  get: () => marks,
9
11
  set(next) {
10
12
  if (next.length === 0 && marks.length === 0) return;
11
13
  marks = next.length === 0 ? NONE : next;
12
- for (const l of [...listeners]) l();
14
+ changed.emit();
13
15
  },
14
- subscribe(listener) {
15
- listeners.add(listener);
16
- return () => {
17
- listeners.delete(listener);
18
- };
19
- }
16
+ subscribe: changed.subscribe
20
17
  };
21
18
  }
22
19
 
@@ -1 +1 @@
1
- {"version":3,"file":"outcomeStore.js","names":[],"sources":["../../../src/domains/snap/outcomeStore.ts"],"sourcesContent":["import type { SnapMark } from './types';\nimport type { Point } from '@weasel-js/geom';\n\n/** The marks of the snap in flight, for the readout to draw. */\nexport interface SnapOutcomeStore<P = Point> {\n get(): readonly SnapMark<P>[];\n set(marks: readonly SnapMark<P>[]): void;\n subscribe(listener: () => void): () => void;\n}\n\nconst NONE: readonly never[] = [];\n\n/** An empty outcome store, which notifies only when the marks change. */\nexport function createSnapOutcomeStore<P = Point>(): SnapOutcomeStore<P> {\n let marks: readonly SnapMark<P>[] = NONE;\n const listeners = new Set<() => void>();\n return {\n get: () => marks,\n set(next) {\n if (next.length === 0 && marks.length === 0) return;\n marks = next.length === 0 ? NONE : next;\n for (const l of [...listeners]) l();\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => { listeners.delete(listener); };\n },\n };\n}\n"],"mappings":";AAUA,IAAM,OAAyB,CAAC;;AAGhC,SAAgB,yBAAyD;CACvE,IAAI,QAAgC;CACpC,MAAM,4BAAY,IAAI,IAAgB;CACtC,OAAO;EACL,WAAW;EACX,IAAI,MAAM;GACR,IAAI,KAAK,WAAW,KAAK,MAAM,WAAW,GAAG;GAC7C,QAAQ,KAAK,WAAW,IAAI,OAAO;GACnC,KAAK,MAAM,KAAK,CAAC,GAAG,SAAS,GAAG,EAAE;EACpC;EACA,UAAU,UAAU;GAClB,UAAU,IAAI,QAAQ;GACtB,aAAa;IAAE,UAAU,OAAO,QAAQ;GAAG;EAC7C;CACF;AACF"}
1
+ {"version":3,"file":"outcomeStore.js","names":[],"sources":["../../../src/domains/snap/outcomeStore.ts"],"sourcesContent":["import type { SnapMark } from './types';\nimport type { Point } from '@weasel-js/geom';\nimport { createEmitter } from '@weasel-js/registry';\n\n/** The marks of the snap in flight, for the readout to draw. */\nexport interface SnapOutcomeStore<P = Point> {\n get(): readonly SnapMark<P>[];\n set(marks: readonly SnapMark<P>[]): void;\n subscribe(listener: () => void): () => void;\n}\n\nconst NONE: readonly never[] = [];\n\n/** An empty outcome store, which notifies only when the marks change. */\nexport function createSnapOutcomeStore<P = Point>(): SnapOutcomeStore<P> {\n let marks: readonly SnapMark<P>[] = NONE;\n const changed = createEmitter();\n return {\n get: () => marks,\n set(next) {\n if (next.length === 0 && marks.length === 0) return;\n marks = next.length === 0 ? NONE : next;\n changed.emit();\n },\n subscribe: changed.subscribe,\n };\n}\n"],"mappings":";;;AAWA,IAAM,OAAyB,CAAC;;AAGhC,SAAgB,yBAAyD;CACvE,IAAI,QAAgC;CACpC,MAAM,UAAU,cAAc;CAC9B,OAAO;EACL,WAAW;EACX,IAAI,MAAM;GACR,IAAI,KAAK,WAAW,KAAK,MAAM,WAAW,GAAG;GAC7C,QAAQ,KAAK,WAAW,IAAI,OAAO;GACnC,QAAQ,KAAK;EACf;EACA,WAAW,QAAQ;CACrB;AACF"}
@@ -7,7 +7,7 @@ import { editedData, sceneTextDrafts } from "./sceneTextDrafts.js";
7
7
  import { inheritedPaintIn, withInheritedPaint } from "../../core/scene/inheritedPaint.js";
8
8
  import { findMountedCanvas } from "../../canvas/mountedCanvases.js";
9
9
  import { textBoxOf } from "../../canvas/nodeShapes/textPainter.js";
10
- import { poseFrameOf } from "@weasel-js/geom";
10
+ import { poseFrameOf, viewScreenToWorld } from "@weasel-js/geom";
11
11
  import { useCallback, useEffect, useMemo, useRef } from "react";
12
12
  import { useLatest } from "@weasel-js/react";
13
13
  import { clientToCanvas } from "@weasel-js/routing";
@@ -132,9 +132,14 @@ function useSceneTextEditor(scene, container, options = {}) {
132
132
  const [canvasX, canvasY] = clientToCanvas(canvas, e.clientX, e.clientY);
133
133
  const root = containerRef.current;
134
134
  const view = resolveView(optsRef.current.view) ?? (root ? findMountedCanvas(root, canvas)?.getView() : void 0);
135
- const cx = view ? canvasX / view.scale.x + view.x : canvasX;
136
- const cy = view ? canvasY / view.scale.y + view.y : canvasY;
137
- const hit = textHitAt(sceneRef.current, read, cx, cy);
135
+ const at = view ? viewScreenToWorld(view, {
136
+ x: canvasX,
137
+ y: canvasY
138
+ }) : {
139
+ x: canvasX,
140
+ y: canvasY
141
+ };
142
+ const hit = textHitAt(sceneRef.current, read, at.x, at.y);
138
143
  if (!hit) return;
139
144
  openedOnRef.current = canvas;
140
145
  edit.startEdit(hit.id, { caret: hit.caret });