@studio8collective/patent-render 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use client";
2
2
 
3
3
  // ../../src/patent-render/client/PatentRender.tsx
4
- import { useEffect as useEffect6, useMemo as useMemo5, useRef as useRef6 } from "react";
4
+ import { useEffect as useEffect6, useMemo as useMemo5, useRef as useRef7 } from "react";
5
5
 
6
6
  // ../../src/patent-render/schema/document.ts
7
7
  import { z } from "zod";
@@ -1241,7 +1241,7 @@ function useEditor() {
1241
1241
  }
1242
1242
 
1243
1243
  // ../../src/patent-render/client/PatentRenderEditor.tsx
1244
- import { useEffect as useEffect4, useRef as useRef4, useState as useState8 } from "react";
1244
+ import { useEffect as useEffect4, useRef as useRef5, useState as useState8 } from "react";
1245
1245
  import { cn as cn25 } from "cn";
1246
1246
 
1247
1247
  // ../../src/patent-render/render/nodes.ts
@@ -1658,7 +1658,7 @@ function isItemEditable(doc, id) {
1658
1658
  }
1659
1659
 
1660
1660
  // ../../src/patent-render/client/Canvas.tsx
1661
- import { useCallback as useCallback2, useEffect, useLayoutEffect, useMemo as useMemo3, useRef, useState as useState2 } from "react";
1661
+ import { useCallback as useCallback2, useEffect, useLayoutEffect as useLayoutEffect2, useMemo as useMemo3, useRef as useRef2, useState as useState2 } from "react";
1662
1662
  import { Loader2 } from "lucide-react";
1663
1663
  import { cn as cn6 } from "cn";
1664
1664
 
@@ -1879,7 +1879,7 @@ function ZoomControls({
1879
1879
  }
1880
1880
 
1881
1881
  // ../../src/patent-render/client/pathTools.tsx
1882
- import { useState } from "react";
1882
+ import { useLayoutEffect, useRef, useState } from "react";
1883
1883
 
1884
1884
  // ../../src/patent-render/geometry/bezier.ts
1885
1885
  var r32 = (n) => Math.round(n * 1e3) / 1e3;
@@ -2060,16 +2060,30 @@ function insertNode(subs, p, maxDist) {
2060
2060
  return { subs: out, ref: { s: b.s, n: b.i + 1 } };
2061
2061
  }
2062
2062
  function usePathTools({ doc, tool, zoom, addItem, apply }) {
2063
- const [pen, setPen] = useState(null);
2064
- const [edit, setEdit] = useState(null);
2063
+ const [pen, setPenState] = useState(null);
2064
+ const [edit, setEditState] = useState(null);
2065
+ const penRef = useRef(null);
2066
+ const editRef = useRef(null);
2067
+ const setPen = (p) => {
2068
+ penRef.current = p;
2069
+ setPenState(p);
2070
+ };
2071
+ const setEdit = (e) => {
2072
+ editRef.current = e;
2073
+ setEditState(e);
2074
+ };
2075
+ useLayoutEffect(() => {
2076
+ penRef.current = pen;
2077
+ editRef.current = edit;
2078
+ });
2065
2079
  const [lastTool, setLastTool] = useState(tool);
2066
2080
  if (tool !== lastTool) {
2067
2081
  setLastTool(tool);
2068
- setPen(null);
2069
- if (tool !== "select") setEdit(null);
2082
+ setPenState(null);
2083
+ if (tool !== "select") setEditState(null);
2070
2084
  }
2071
2085
  const px = (n) => n / zoom;
2072
- const finishPen = (closed, state = pen) => {
2086
+ const finishPen = (closed, state = penRef.current) => {
2073
2087
  if (!state) return;
2074
2088
  const nodes = state.nodes;
2075
2089
  const base3 = { rotation: 0, locked: false, hidden: false };
@@ -2113,22 +2127,23 @@ function usePathTools({ doc, tool, zoom, addItem, apply }) {
2113
2127
  }
2114
2128
  };
2115
2129
  const onPointerDown = (target, p, altKey) => {
2130
+ const pen2 = penRef.current, edit2 = editRef.current;
2116
2131
  if (tool === "polyline" || tool === "hatch") {
2117
- if (pen && nearFirst(p, pen)) {
2132
+ if (pen2 && nearFirst(p, pen2)) {
2118
2133
  finishPen(true);
2119
2134
  return true;
2120
2135
  }
2121
- const nodes = [...pen?.nodes ?? [], { p }];
2136
+ const nodes = [...pen2?.nodes ?? [], { p }];
2122
2137
  setPen({ tool, nodes, cur: p, dragging: tool === "polyline" ? nodes.length - 1 : null });
2123
2138
  return true;
2124
2139
  }
2125
- if (!edit) return false;
2140
+ if (!edit2) return false;
2126
2141
  const tag = target.getAttribute?.("data-node");
2127
2142
  if (tag) {
2128
2143
  const [kind, s, n] = tag.split(":");
2129
2144
  const ref = { s: Number(s), n: Number(n) };
2130
2145
  if (kind === "anchor" && altKey) {
2131
- const subs = clone(edit.subs);
2146
+ const subs = clone(edit2.subs);
2132
2147
  const sp = subs[ref.s], node = sp.nodes[ref.n];
2133
2148
  if (node.in || node.out) {
2134
2149
  delete node.in;
@@ -2139,33 +2154,34 @@ function usePathTools({ doc, tool, zoom, addItem, apply }) {
2139
2154
  node.in = [node.p[0] - dx, node.p[1] - dy];
2140
2155
  node.out = [node.p[0] + dx, node.p[1] + dy];
2141
2156
  }
2142
- const next = { ...edit, subs, sel: ref };
2157
+ const next = { ...edit2, subs, sel: ref };
2143
2158
  setEdit(next);
2144
2159
  commit(next);
2145
2160
  return true;
2146
2161
  }
2147
- setEdit({ ...edit, sel: ref, drag: { kind, ref, start: p, orig: clone(edit.subs), alt: altKey } });
2162
+ setEdit({ ...edit2, sel: ref, drag: { kind, ref, start: p, orig: clone(edit2.subs), alt: altKey } });
2148
2163
  return true;
2149
2164
  }
2150
- if (target.closest?.(`[data-hit-id="${edit.id}"]`)) {
2151
- setEdit({ ...edit, sel: null });
2165
+ if (target.closest?.(`[data-hit-id="${edit2.id}"]`)) {
2166
+ setEdit({ ...edit2, sel: null });
2152
2167
  return true;
2153
2168
  }
2154
2169
  setEdit(null);
2155
2170
  return false;
2156
2171
  };
2157
2172
  const onPointerMove = (p, altKey) => {
2158
- if (pen) {
2159
- if (pen.dragging !== null) {
2160
- const nodes = pen.nodes.slice();
2161
- const a = nodes[pen.dragging];
2162
- if (dist(p, a.p) > px(3)) nodes[pen.dragging] = { p: a.p, out: p, in: [2 * a.p[0] - p[0], 2 * a.p[1] - p[1]] };
2163
- setPen({ ...pen, nodes, cur: p });
2164
- } else setPen({ ...pen, cur: p });
2173
+ const pen2 = penRef.current, edit2 = editRef.current;
2174
+ if (pen2) {
2175
+ if (pen2.dragging !== null) {
2176
+ const nodes = pen2.nodes.slice();
2177
+ const a = nodes[pen2.dragging];
2178
+ if (dist(p, a.p) > px(3)) nodes[pen2.dragging] = { p: a.p, out: p, in: [2 * a.p[0] - p[0], 2 * a.p[1] - p[1]] };
2179
+ setPen({ ...pen2, nodes, cur: p });
2180
+ } else setPen({ ...pen2, cur: p });
2165
2181
  return;
2166
2182
  }
2167
- if (!edit?.drag) return;
2168
- const { kind, ref, start, orig } = edit.drag;
2183
+ if (!edit2?.drag) return;
2184
+ const { kind, ref, start, orig } = edit2.drag;
2169
2185
  const subs = clone(orig);
2170
2186
  const node = subs[ref.s].nodes[ref.n];
2171
2187
  const d = [p[0] - start[0], p[1] - start[1]];
@@ -2176,33 +2192,35 @@ function usePathTools({ doc, tool, zoom, addItem, apply }) {
2176
2192
  } else {
2177
2193
  const other = kind === "in" ? "out" : "in";
2178
2194
  node[kind] = p;
2179
- if (node[other] && !altKey && !edit.drag.alt) node[other] = mirrorHandle(node.p, p, node[other]);
2195
+ if (node[other] && !altKey && !edit2.drag.alt) node[other] = mirrorHandle(node.p, p, node[other]);
2180
2196
  }
2181
- setEdit({ ...edit, subs, dirty: true });
2197
+ setEdit({ ...edit2, subs, dirty: true });
2182
2198
  };
2183
2199
  const onPointerUp = () => {
2184
- if (pen && pen.dragging !== null) {
2185
- setPen({ ...pen, dragging: null });
2200
+ const pen2 = penRef.current, edit2 = editRef.current;
2201
+ if (pen2 && pen2.dragging !== null) {
2202
+ setPen({ ...pen2, dragging: null });
2186
2203
  return true;
2187
2204
  }
2188
- if (edit?.drag) {
2189
- const done = { ...edit, drag: null, dirty: false };
2190
- if (edit.dirty) commit(edit);
2205
+ if (edit2?.drag) {
2206
+ const done = { ...edit2, drag: null, dirty: false };
2207
+ if (edit2.dirty) commit(edit2);
2191
2208
  setEdit(done);
2192
2209
  return true;
2193
2210
  }
2194
2211
  return false;
2195
2212
  };
2196
2213
  const onDoubleClick = (p, hitId) => {
2197
- if (pen) {
2198
- const nodes = pen.nodes.length > 1 && dist(pen.nodes[pen.nodes.length - 1].p, pen.nodes[pen.nodes.length - 2].p) < px(4) ? pen.nodes.slice(0, -1) : pen.nodes;
2199
- finishPen(false, { ...pen, nodes });
2214
+ const pen2 = penRef.current, edit2 = editRef.current;
2215
+ if (pen2) {
2216
+ const nodes = pen2.nodes.length > 1 && dist(pen2.nodes[pen2.nodes.length - 1].p, pen2.nodes[pen2.nodes.length - 2].p) < px(4) ? pen2.nodes.slice(0, -1) : pen2.nodes;
2217
+ finishPen(false, { ...pen2, nodes });
2200
2218
  return true;
2201
2219
  }
2202
- if (edit) {
2203
- const r = insertNode(edit.subs, p, px(8));
2220
+ if (edit2) {
2221
+ const r = insertNode(edit2.subs, p, px(8));
2204
2222
  if (r) {
2205
- const next = { ...edit, subs: r.subs, sel: r.ref };
2223
+ const next = { ...edit2, subs: r.subs, sel: r.ref };
2206
2224
  setEdit(next);
2207
2225
  commit(next);
2208
2226
  }
@@ -2508,6 +2526,16 @@ import { Fragment, jsx as jsx8, jsxs as jsxs6 } from "react/jsx-runtime";
2508
2526
  var HANDLES = ["nw", "n", "ne", "e", "se", "s", "sw", "w"];
2509
2527
  var DRAW_TOOLS = ["line", "rect", "ellipse", "sectionLine", "shape"];
2510
2528
  var HIT_PX = 7;
2529
+ var WHEEL_LINE_PX = 16;
2530
+ var WHEEL_ZOOM_MAX = Math.log(1.25);
2531
+ var WHEEL_ZOOM_PER_PX = 0.01;
2532
+ var WHEEL_NOTCH_PX = 40;
2533
+ var PAN_EASE = 0.35;
2534
+ var INTERIOR_GRAB_MAX_PX = 200;
2535
+ function wheelPx(e, pageHeight) {
2536
+ const k = e.deltaMode === 1 ? WHEEL_LINE_PX : e.deltaMode === 2 ? pageHeight : 1;
2537
+ return [e.deltaX * k, e.deltaY * k];
2538
+ }
2511
2539
  function hitify(n, w) {
2512
2540
  const attrs = {};
2513
2541
  for (const [k, v] of Object.entries(n.attrs)) {
@@ -2520,6 +2548,7 @@ function hitify(n, w) {
2520
2548
  } else if (n.tag !== "g" && n.tag !== "clipPath") {
2521
2549
  attrs.stroke = "transparent";
2522
2550
  attrs["stroke-width"] = w;
2551
+ attrs["vector-effect"] = "non-scaling-stroke";
2523
2552
  attrs["pointer-events"] = attrs.fill && attrs.fill !== "none" ? "all" : "stroke";
2524
2553
  if (attrs.fill && attrs.fill !== "none") attrs.fill = "transparent";
2525
2554
  }
@@ -2544,59 +2573,138 @@ var CURSOR = {
2544
2573
  };
2545
2574
  function Canvas({ className }) {
2546
2575
  const ed = useEditor();
2547
- const { doc, selection, tool, view, snap } = ed.state;
2548
- const wrapRef = useRef(null);
2549
- const svgRef = useRef(null);
2576
+ const { doc, selection, tool, snap } = ed.state;
2577
+ const wrapRef = useRef2(null);
2578
+ const svgRef = useRef2(null);
2550
2579
  const [size, setSize] = useState2({ w: 0, h: 0 });
2551
- const [gesture, setGesture] = useState2(null);
2580
+ const [gesture, setGestureState] = useState2(null);
2581
+ const gestureRef = useRef2(null);
2582
+ const setGesture = useCallback2((g) => {
2583
+ gestureRef.current = g;
2584
+ setGestureState(g);
2585
+ }, []);
2552
2586
  const [inline, setInline] = useState2(null);
2553
2587
  const [spaceDown, setSpaceDown] = useState2(false);
2554
2588
  const [portHover, setPortHover] = useState2(null);
2555
2589
  const sheet = sheetDims(doc.sheet);
2556
2590
  const exploded = doc.view === "exploded" && hasExplode(doc);
2591
+ const [view, setViewState] = useState2(ed.state.view);
2592
+ const viewRef = useRef2(ed.state.view);
2593
+ const viewFrame = useRef2(null);
2594
+ const setView = useCallback2((next, immediate = false) => {
2595
+ viewRef.current = next;
2596
+ if (immediate) {
2597
+ if (viewFrame.current !== null) {
2598
+ cancelAnimationFrame(viewFrame.current);
2599
+ viewFrame.current = null;
2600
+ }
2601
+ setViewState(next);
2602
+ return;
2603
+ }
2604
+ if (viewFrame.current === null) {
2605
+ viewFrame.current = requestAnimationFrame(() => {
2606
+ viewFrame.current = null;
2607
+ setViewState(viewRef.current);
2608
+ });
2609
+ }
2610
+ }, []);
2611
+ useEffect(() => () => {
2612
+ if (viewFrame.current !== null) cancelAnimationFrame(viewFrame.current);
2613
+ }, []);
2614
+ const syncedView = useRef2(ed.state.view);
2615
+ useEffect(() => {
2616
+ if (!view || view === syncedView.current) return;
2617
+ const t = setTimeout(() => {
2618
+ syncedView.current = view;
2619
+ ed.setView(view);
2620
+ }, 250);
2621
+ return () => clearTimeout(t);
2622
+ }, [view]);
2623
+ useEffect(() => {
2624
+ const ext = ed.state.view;
2625
+ if (ext && ext !== syncedView.current && ext !== viewRef.current) {
2626
+ syncedView.current = ext;
2627
+ setView(ext, true);
2628
+ }
2629
+ }, [ed.state.view, setView]);
2557
2630
  const fit = useCallback2(() => {
2558
2631
  if (!size.w || !size.h) return;
2559
2632
  const zoom = Math.min(size.w / sheet.w, size.h / sheet.h) * 0.9;
2560
- ed.setView({ zoom, panX: (size.w - sheet.w * zoom) / 2, panY: (size.h - sheet.h * zoom) / 2 });
2561
- }, [size.w, size.h, sheet.w, sheet.h, ed]);
2562
- useLayoutEffect(() => {
2633
+ setView({ zoom, panX: (size.w - sheet.w * zoom) / 2, panY: (size.h - sheet.h * zoom) / 2 }, true);
2634
+ }, [size.w, size.h, sheet.w, sheet.h, setView]);
2635
+ useLayoutEffect2(() => {
2563
2636
  const el = wrapRef.current;
2564
2637
  if (!el) return;
2565
2638
  const ro = new ResizeObserver(([e]) => setSize({ w: e.contentRect.width, h: e.contentRect.height }));
2566
2639
  ro.observe(el);
2567
2640
  return () => ro.disconnect();
2568
2641
  }, []);
2569
- const userMoved = useRef(false);
2642
+ const userMoved = useRef2(false);
2643
+ const fitPending = useRef2(false);
2570
2644
  useEffect(() => {
2571
- if (size.w && (!view || !userMoved.current)) fit();
2645
+ if (!size.w || viewRef.current && userMoved.current) return;
2646
+ if (gestureRef.current) {
2647
+ fitPending.current = true;
2648
+ return;
2649
+ }
2650
+ fit();
2572
2651
  }, [size.w, size.h]);
2573
2652
  const v = view ?? { zoom: 1, panX: 0, panY: 0 };
2574
2653
  const zoomAt = useCallback2((factor, sx, sy) => {
2575
- const cur = ed.state.view;
2654
+ const cur = viewRef.current;
2576
2655
  if (!cur) return;
2577
2656
  userMoved.current = true;
2578
2657
  const zoom = Math.min(40, Math.max(0.3, cur.zoom * factor));
2579
2658
  const k = zoom / cur.zoom;
2580
- ed.setView({ zoom, panX: sx - (sx - cur.panX) * k, panY: sy - (sy - cur.panY) * k });
2581
- }, [ed]);
2659
+ setView({ zoom, panX: sx - (sx - cur.panX) * k, panY: sy - (sy - cur.panY) * k });
2660
+ }, [setView]);
2661
+ const panDebt = useRef2([0, 0]);
2662
+ const panFrame = useRef2(null);
2582
2663
  useEffect(() => {
2583
2664
  const el = svgRef.current;
2584
2665
  if (!el) return;
2666
+ function easePan() {
2667
+ panFrame.current = null;
2668
+ const cur = viewRef.current;
2669
+ if (!cur) {
2670
+ panDebt.current = [0, 0];
2671
+ return;
2672
+ }
2673
+ const [dx, dy] = panDebt.current;
2674
+ const done = Math.abs(dx) < 0.5 && Math.abs(dy) < 0.5;
2675
+ const sx = done ? dx : dx * PAN_EASE, sy = done ? dy : dy * PAN_EASE;
2676
+ panDebt.current = [dx - sx, dy - sy];
2677
+ setView({ ...cur, panX: cur.panX - sx, panY: cur.panY - sy });
2678
+ if (!done) panFrame.current = requestAnimationFrame(easePan);
2679
+ }
2585
2680
  const onWheel = (e) => {
2586
2681
  e.preventDefault();
2587
- const cur = ed.state.view;
2682
+ const cur = viewRef.current;
2588
2683
  if (!cur) return;
2589
- const r = el.getBoundingClientRect();
2684
+ const [dx, dy] = wheelPx(e, el.clientHeight || 800);
2590
2685
  if (e.ctrlKey || e.metaKey) {
2591
- zoomAt(Math.exp(-e.deltaY * 0.01), e.clientX - r.left, e.clientY - r.top);
2686
+ const step = Math.max(-WHEEL_ZOOM_MAX, Math.min(WHEEL_ZOOM_MAX, -dy * WHEEL_ZOOM_PER_PX));
2687
+ const r = el.getBoundingClientRect();
2688
+ zoomAt(Math.exp(step), e.clientX - r.left, e.clientY - r.top);
2689
+ return;
2690
+ }
2691
+ userMoved.current = true;
2692
+ if (Math.abs(dx) >= WHEEL_NOTCH_PX || Math.abs(dy) >= WHEEL_NOTCH_PX) {
2693
+ panDebt.current = [panDebt.current[0] + dx, panDebt.current[1] + dy];
2694
+ if (panFrame.current === null) panFrame.current = requestAnimationFrame(easePan);
2592
2695
  } else {
2593
- userMoved.current = true;
2594
- ed.setView({ ...cur, panX: cur.panX - e.deltaX, panY: cur.panY - e.deltaY });
2696
+ setView({ ...cur, panX: cur.panX - dx, panY: cur.panY - dy });
2595
2697
  }
2596
2698
  };
2597
2699
  el.addEventListener("wheel", onWheel, { passive: false });
2598
- return () => el.removeEventListener("wheel", onWheel);
2599
- }, [ed, zoomAt]);
2700
+ return () => {
2701
+ el.removeEventListener("wheel", onWheel);
2702
+ if (panFrame.current !== null) {
2703
+ cancelAnimationFrame(panFrame.current);
2704
+ panFrame.current = null;
2705
+ }
2706
+ };
2707
+ }, [zoomAt, setView]);
2600
2708
  const addItem = (item) => {
2601
2709
  const layer = targetLayer(doc, ed.state.activeLayerId);
2602
2710
  if (!layer) return;
@@ -2643,7 +2751,8 @@ function Canvas({ className }) {
2643
2751
  });
2644
2752
  const toMm = (e) => {
2645
2753
  const r = svgRef.current.getBoundingClientRect();
2646
- return [(e.clientX - r.left - v.panX) / v.zoom, (e.clientY - r.top - v.panY) / v.zoom];
2754
+ const cv = viewRef.current ?? v;
2755
+ return [(e.clientX - r.left - cv.panX) / cv.zoom, (e.clientY - r.top - cv.panY) / cv.zoom];
2647
2756
  };
2648
2757
  const snapPt = (p) => snap ? [Math.round(p[0] * 2) / 2, Math.round(p[1] * 2) / 2] : p;
2649
2758
  const px = (n) => n / v.zoom;
@@ -2698,12 +2807,30 @@ function Canvas({ className }) {
2698
2807
  const el = e.target.closest?.("[data-hit-id]");
2699
2808
  return el ? el.getAttribute("data-hit-id") : null;
2700
2809
  };
2810
+ const interiorHit = (p) => {
2811
+ const z4 = (viewRef.current ?? v).zoom;
2812
+ let best = null;
2813
+ for (const l of vdoc.layers) {
2814
+ if (!l.visible || l.locked) continue;
2815
+ for (const it of l.items) {
2816
+ const closed = it.type === "rect" || it.type === "ellipse" || it.type === "polyline" && it.closed || it.type === "path" && /z\s*$/i.test(it.d);
2817
+ if (!closed || it.hidden || it.locked || !isItemEditable(doc, it.id)) continue;
2818
+ const b = itemBoundsRotated(vdoc, it);
2819
+ if (b.w * z4 > INTERIOR_GRAB_MAX_PX || b.h * z4 > INTERIOR_GRAB_MAX_PX) continue;
2820
+ if (p[0] < b.x || p[0] > b.x + b.w || p[1] < b.y || p[1] > b.y + b.h) continue;
2821
+ const area = b.w * b.h;
2822
+ if (!best || area < best.area) best = { id: it.id, area };
2823
+ }
2824
+ }
2825
+ return best?.id ?? null;
2826
+ };
2701
2827
  const onPointerDown = (e) => {
2702
2828
  if (e.button !== 0 && e.button !== 1) return;
2703
2829
  svgRef.current?.setPointerCapture(e.pointerId);
2704
2830
  const p = toMm(e);
2705
2831
  if (e.button === 1 || tool === "pan" || spaceDown) {
2706
- setGesture({ kind: "pan", sx: e.clientX, sy: e.clientY, px: v.panX, py: v.panY });
2832
+ const cv = viewRef.current ?? v;
2833
+ setGesture({ kind: "pan", sx: e.clientX, sy: e.clientY, px: cv.panX, py: cv.panY });
2707
2834
  return;
2708
2835
  }
2709
2836
  if (ed.readOnly) return;
@@ -2729,16 +2856,16 @@ function Canvas({ className }) {
2729
2856
  }
2730
2857
  return;
2731
2858
  }
2732
- const hit2 = hitItemId(e);
2859
+ const hit = hitItemId(e) ?? (tool === "select" && !e.shiftKey ? interiorHit(p) : null);
2733
2860
  if (tool === "select") {
2734
- if (hit2 && isItemEditable(doc, hit2)) {
2861
+ if (hit && isItemEditable(doc, hit)) {
2735
2862
  let ids = selection;
2736
- if (e.shiftKey) ids = selection.includes(hit2) ? selection.filter((i) => i !== hit2) : [...selection, hit2];
2737
- else if (!selection.includes(hit2)) ids = [hit2];
2863
+ if (e.shiftKey) ids = selection.includes(hit) ? selection.filter((i) => i !== hit) : [...selection, hit];
2864
+ else if (!selection.includes(hit)) ids = [hit];
2738
2865
  ed.select(ids);
2739
- const loc = findItem(doc, hit2);
2866
+ const loc = findItem(doc, hit);
2740
2867
  if (loc) ed.setActiveLayer(doc.layers[loc.layerIndex].id);
2741
- if (ids.includes(hit2)) setGesture({ kind: "move", start: p, ids: ids.filter((i) => isItemEditable(doc, i)), dx: 0, dy: 0 });
2868
+ if (ids.includes(hit)) setGesture({ kind: "move", start: p, ids: ids.filter((i) => isItemEditable(doc, i)), dx: 0, dy: 0 });
2742
2869
  } else {
2743
2870
  setGesture({ kind: "marquee", start: p, cur: p, base: e.shiftKey ? selection : [] });
2744
2871
  if (!e.shiftKey) ed.select([]);
@@ -2763,19 +2890,22 @@ function Canvas({ className }) {
2763
2890
  const onPointerMove = (e) => {
2764
2891
  const p = toMm(e);
2765
2892
  paths.onPointerMove(snapPt(p), e.altKey);
2766
- if (tool === "connector" && !gesture) {
2893
+ const gesture2 = gestureRef.current;
2894
+ if (tool === "connector" && !gesture2) {
2767
2895
  const over = attachTarget(p);
2768
2896
  const next = over ? { id: over, side: portAt(over, p) } : null;
2769
2897
  if (next?.id !== portHover?.id || next?.side !== portHover?.side) setPortHover(next);
2770
2898
  }
2771
- if (!gesture) return;
2772
- switch (gesture.kind) {
2773
- case "pan":
2899
+ if (!gesture2) return;
2900
+ switch (gesture2.kind) {
2901
+ case "pan": {
2774
2902
  userMoved.current = true;
2775
- ed.setView({ ...v, panX: gesture.px + e.clientX - gesture.sx, panY: gesture.py + e.clientY - gesture.sy });
2903
+ const cv = viewRef.current ?? v;
2904
+ setView({ ...cv, panX: gesture2.px + e.clientX - gesture2.sx, panY: gesture2.py + e.clientY - gesture2.sy });
2776
2905
  break;
2906
+ }
2777
2907
  case "move": {
2778
- let dx = p[0] - gesture.start[0], dy = p[1] - gesture.start[1];
2908
+ let dx = p[0] - gesture2.start[0], dy = p[1] - gesture2.start[1];
2779
2909
  if (e.shiftKey) {
2780
2910
  if (Math.abs(dx) > Math.abs(dy)) dy = 0;
2781
2911
  else dx = 0;
@@ -2784,11 +2914,11 @@ function Canvas({ className }) {
2784
2914
  dx = Math.round(dx * 2) / 2;
2785
2915
  dy = Math.round(dy * 2) / 2;
2786
2916
  }
2787
- setGesture({ ...gesture, dx, dy });
2917
+ setGesture({ ...gesture2, dx, dy });
2788
2918
  break;
2789
2919
  }
2790
2920
  case "resize": {
2791
- const { box, handle, origin } = gesture;
2921
+ const { box, handle, origin } = gesture2;
2792
2922
  const hp = handlePos(box, handle);
2793
2923
  const dxh = hp[0] - origin[0], dyh = hp[1] - origin[1];
2794
2924
  let sx = handle === "n" || handle === "s" || Math.abs(dxh) < 1e-6 ? 1 : (p[0] - origin[0]) / dxh;
@@ -2798,51 +2928,58 @@ function Canvas({ className }) {
2798
2928
  sx = Math.sign(sx) * s;
2799
2929
  sy = Math.sign(sy) * s;
2800
2930
  }
2801
- setGesture({ ...gesture, sx: sx || 0.01, sy: sy || 0.01 });
2931
+ setGesture({ ...gesture2, sx: sx || 0.01, sy: sy || 0.01 });
2802
2932
  break;
2803
2933
  }
2804
2934
  case "rotate": {
2805
- const a = Math.atan2(p[1] - gesture.c[1], p[0] - gesture.c[0]);
2806
- let rot = gesture.r0 + (a - gesture.a0) * 180 / Math.PI;
2935
+ const a = Math.atan2(p[1] - gesture2.c[1], p[0] - gesture2.c[0]);
2936
+ let rot = gesture2.r0 + (a - gesture2.a0) * 180 / Math.PI;
2807
2937
  if (e.shiftKey) rot = Math.round(rot / 15) * 15;
2808
2938
  rot = (rot % 360 + 360) % 360;
2809
- setGesture({ ...gesture, rot: Math.round(rot * 10) / 10 });
2939
+ setGesture({ ...gesture2, rot: Math.round(rot * 10) / 10 });
2810
2940
  break;
2811
2941
  }
2812
2942
  case "marquee":
2813
- setGesture({ ...gesture, cur: p });
2943
+ setGesture({ ...gesture2, cur: p });
2814
2944
  break;
2815
2945
  case "draw": {
2816
2946
  let cur = snapPt(p);
2817
- if ((gesture.tool === "line" || gesture.tool === "sectionLine") && e.shiftKey) cur = constrain45(gesture.start, cur);
2818
- setGesture({ ...gesture, cur });
2947
+ if ((gesture2.tool === "line" || gesture2.tool === "sectionLine") && e.shiftKey) cur = constrain45(gesture2.start, cur);
2948
+ setGesture({ ...gesture2, cur });
2819
2949
  break;
2820
2950
  }
2821
2951
  case "connector": {
2822
2952
  {
2823
2953
  const over = attachTarget(p);
2824
- const overId = over && !("itemId" in gesture.from && gesture.from.itemId === over) ? over : null;
2825
- setGesture({ ...gesture, cur: snapPt(p), overId, overSide: overId ? portAt(overId, p) : void 0 });
2954
+ const overId = over && !("itemId" in gesture2.from && gesture2.from.itemId === over) ? over : null;
2955
+ setGesture({ ...gesture2, cur: snapPt(p), overId, overSide: overId ? portAt(overId, p) : void 0 });
2826
2956
  }
2827
2957
  break;
2828
2958
  }
2829
2959
  case "numeral":
2830
- setGesture({ ...gesture, cur: snapPt(p) });
2960
+ setGesture({ ...gesture2, cur: snapPt(p) });
2831
2961
  break;
2832
2962
  case "reconnect": {
2833
- const loc = findItem(doc, gesture.id);
2834
- const other = loc?.item.type === "connector" ? gesture.end === "from" ? loc.item.to : loc.item.from : null;
2963
+ const loc = findItem(doc, gesture2.id);
2964
+ const other = loc?.item.type === "connector" ? gesture2.end === "from" ? loc.item.to : loc.item.from : null;
2835
2965
  const over = attachTarget(p);
2836
2966
  const overId = over && !(other && "itemId" in other && other.itemId === over) ? over : null;
2837
- setGesture({ ...gesture, cur: snapPt(p), overId, overSide: overId ? portAt(overId, p) : void 0 });
2967
+ setGesture({ ...gesture2, cur: snapPt(p), overId, overSide: overId ? portAt(overId, p) : void 0 });
2838
2968
  break;
2839
2969
  }
2840
2970
  }
2841
2971
  };
2972
+ const endGesture = () => {
2973
+ setGesture(null);
2974
+ if (fitPending.current) {
2975
+ fitPending.current = false;
2976
+ if (!userMoved.current) fit();
2977
+ }
2978
+ };
2842
2979
  const onPointerUp = () => {
2843
2980
  if (paths.onPointerUp()) return;
2844
- const g = gesture;
2845
- setGesture(null);
2981
+ const g = gestureRef.current;
2982
+ endGesture();
2846
2983
  if (!g) return;
2847
2984
  switch (g.kind) {
2848
2985
  case "move":
@@ -2918,16 +3055,16 @@ function Canvas({ className }) {
2918
3055
  const onDoubleClick = (e) => {
2919
3056
  if (ed.readOnly) return;
2920
3057
  const under = document.elementFromPoint(e.clientX, e.clientY);
2921
- const hit2 = under ? hitItemId({ target: under }) : null;
2922
- const editable = hit2 && isItemEditable(doc, hit2) ? hit2 : null;
3058
+ const hit = under ? hitItemId({ target: under }) : null;
3059
+ const editable = hit && isItemEditable(doc, hit) ? hit : null;
2923
3060
  if (paths.onDoubleClick(snapPt(toMm(e)), tool === "select" && !exploded ? editable : null)) return;
2924
- if (!hit2) return;
2925
- const loc = findItem(doc, hit2);
2926
- if (!loc || !isItemEditable(doc, hit2)) return;
3061
+ if (!hit) return;
3062
+ const loc = findItem(doc, hit);
3063
+ if (!loc || !isItemEditable(doc, hit)) return;
2927
3064
  const it = loc.item;
2928
- if (it.type === "text") setInline({ id: hit2, field: "text", value: it.text });
2929
- if (it.type === "numeral") setInline({ id: hit2, field: "desc", value: doc.numerals[it.n] ?? "", placeholder: `What is ${it.n}?` });
2930
- if (it.type === "connector") setInline({ id: hit2, field: "label", value: it.label ?? "" });
3065
+ if (it.type === "text") setInline({ id: hit, field: "text", value: it.text });
3066
+ if (it.type === "numeral") setInline({ id: hit, field: "desc", value: doc.numerals[it.n] ?? "", placeholder: `What is ${it.n}?` });
3067
+ if (it.type === "connector") setInline({ id: hit, field: "label", value: it.label ?? "" });
2931
3068
  };
2932
3069
  const refocusEditor = () => {
2933
3070
  const root = wrapRef.current?.closest("[data-slot=patent-render]");
@@ -2947,22 +3084,25 @@ function Canvas({ className }) {
2947
3084
  setInline(null);
2948
3085
  };
2949
3086
  const onContextMenu = (e) => {
2950
- const hit2 = hitItemId(e);
2951
- if (hit2 && !selection.includes(hit2) && isItemEditable(doc, hit2)) ed.select([hit2]);
2952
- if (!hit2) ed.select([]);
3087
+ const hit = hitItemId(e);
3088
+ if (hit && !selection.includes(hit) && isItemEditable(doc, hit)) ed.select([hit]);
3089
+ if (!hit) ed.select([]);
2953
3090
  };
2954
- const hitW = px(HIT_PX * 2);
2955
- const visual = useMemo3(() => layerNodes(vdoc), [vdoc]);
2956
- const hit = useMemo3(
3091
+ const defsEl = useMemo3(() => nodeToReact(defsNode(), "defs"), []);
3092
+ const drawingEls = useMemo3(() => [
3093
+ ...sheetLabelNodes(vdoc).map((n, i) => nodeToReact(n, `sheet-${i}`)),
3094
+ ...layerNodes(vdoc).map((n, i) => nodeToReact(n, n.attrs["data-layer-id"] ?? i))
3095
+ ], [vdoc]);
3096
+ const hitEls = useMemo3(
2957
3097
  () => vdoc.layers.filter((l) => l.visible).flatMap((l) => (
2958
3098
  // Locked layers/items are not hittable at all.
2959
3099
  l.locked ? [] : l.items.filter((it) => !it.hidden && !it.locked).map((it) => {
2960
- const n = hitify(itemNode(vdoc, it), hitW);
3100
+ const n = hitify(itemNode(vdoc, it), HIT_PX * 2);
2961
3101
  n.attrs["data-hit-id"] = it.id;
2962
- return n;
3102
+ return nodeToReact(n, it.id);
2963
3103
  })
2964
3104
  )),
2965
- [vdoc, hitW]
3105
+ [vdoc]
2966
3106
  );
2967
3107
  const profile = PROFILES[doc.jurisdiction];
2968
3108
  const m = effectiveMargins(profile, doc.sheet.orientation);
@@ -3005,11 +3145,11 @@ function Canvas({ className }) {
3005
3145
  onPointerDown,
3006
3146
  onPointerMove,
3007
3147
  onPointerUp,
3008
- onPointerCancel: () => setGesture(null),
3148
+ onPointerCancel: endGesture,
3009
3149
  onDoubleClick,
3010
3150
  onContextMenu,
3011
3151
  children: /* @__PURE__ */ jsxs6("g", { transform: `translate(${v.panX} ${v.panY}) scale(${v.zoom})`, children: [
3012
- nodeToReact(defsNode(), "defs"),
3152
+ defsEl,
3013
3153
  /* @__PURE__ */ jsx8("rect", { x: px(2), y: px(3), width: sheet.w, height: sheet.h, fill: "black", opacity: 0.08 }),
3014
3154
  /* @__PURE__ */ jsx8("rect", { x: 0, y: 0, width: sheet.w, height: sheet.h, fill: "#fff", stroke: "rgba(0,0,0,.15)", strokeWidth: px(1) }),
3015
3155
  /* @__PURE__ */ jsx8(
@@ -3026,11 +3166,8 @@ function Canvas({ className }) {
3026
3166
  pointerEvents: "none"
3027
3167
  }
3028
3168
  ),
3029
- /* @__PURE__ */ jsxs6("g", { pointerEvents: "none", children: [
3030
- sheetLabelNodes(vdoc).map((n, i) => nodeToReact(n, `sheet-${i}`)),
3031
- visual.map((n, i) => nodeToReact(n, n.attrs["data-layer-id"] ?? i))
3032
- ] }),
3033
- /* @__PURE__ */ jsx8("g", { children: hit.map((n) => nodeToReact(n, n.attrs["data-hit-id"])) }),
3169
+ /* @__PURE__ */ jsx8("g", { pointerEvents: "none", children: drawingEls }),
3170
+ /* @__PURE__ */ jsx8("g", { children: hitEls }),
3034
3171
  /* @__PURE__ */ jsx8("g", { pointerEvents: "none", children: [...issueMap].map(([id, sev]) => {
3035
3172
  const loc = findItem(vdoc, id);
3036
3173
  if (!loc || !layerById[vdoc.layers[loc.layerIndex].id]?.visible) return null;
@@ -4982,7 +5119,7 @@ function HeaderBar({ onEmbed, onCancel, embedding, className }) {
4982
5119
  }
4983
5120
 
4984
5121
  // ../../src/patent-render/client/ChatDock.tsx
4985
- import { useEffect as useEffect2, useRef as useRef2, useState as useState6 } from "react";
5122
+ import { useEffect as useEffect2, useRef as useRef3, useState as useState6 } from "react";
4986
5123
  import {
4987
5124
  ArrowUp,
4988
5125
  Check,
@@ -5230,9 +5367,9 @@ function ChatDock({
5230
5367
  const collapsed = collapsedProp ?? collapsedLocal;
5231
5368
  const setCollapsed = (v) => onCollapsedChange ? onCollapsedChange(v) : setCollapsedLocal(v);
5232
5369
  const [dragOver, setDragOver] = useState6(false);
5233
- const scrollRef = useRef2(null);
5234
- const fileRef = useRef2(null);
5235
- const taRef = useRef2(null);
5370
+ const scrollRef = useRef3(null);
5371
+ const fileRef = useRef3(null);
5372
+ const taRef = useRef3(null);
5236
5373
  const running = status !== "idle";
5237
5374
  const empty = messages.length === 0;
5238
5375
  useEffect2(() => {
@@ -5389,7 +5526,7 @@ function ChatDock({
5389
5526
  import { PanelRightClose, PanelRightOpen } from "lucide-react";
5390
5527
 
5391
5528
  // ../../src/patent-render/client/layout.tsx
5392
- import { useCallback as useCallback3, useEffect as useEffect3, useRef as useRef3, useState as useState7 } from "react";
5529
+ import { useCallback as useCallback3, useEffect as useEffect3, useRef as useRef4, useState as useState7 } from "react";
5393
5530
  import { cn as cn24 } from "cn";
5394
5531
  import { jsx as jsx27 } from "react/jsx-runtime";
5395
5532
  var DEFAULT = { sideWidth: 288, sideOpen: true, split: 0.5, chatHeight: 220, chatOpen: true };
@@ -5398,7 +5535,7 @@ var LIMITS = { side: [220, 520], chat: [80, 560], split: [0.15, 0.85] };
5398
5535
  var clamp = (v, [lo, hi]) => Math.min(hi, Math.max(lo, v));
5399
5536
  function usePanelLayout() {
5400
5537
  const [layout, setLayout] = useState7(DEFAULT);
5401
- const loaded = useRef3(false);
5538
+ const loaded = useRef4(false);
5402
5539
  useEffect3(() => {
5403
5540
  try {
5404
5541
  const raw = localStorage.getItem(KEY);
@@ -5421,7 +5558,7 @@ function usePanelLayout() {
5421
5558
  return { layout, update };
5422
5559
  }
5423
5560
  function ResizeHandle({ axis, onDrag, onToggle, label, className }) {
5424
- const last = useRef3(null);
5561
+ const last = useRef4(null);
5425
5562
  const [active, setActive] = useState7(false);
5426
5563
  const down = (e) => {
5427
5564
  if (e.button !== 0) return;
@@ -5491,15 +5628,15 @@ function PatentRenderEditor(props) {
5491
5628
  }
5492
5629
  function PatentRenderShell({ chat, agentStatus = "idle", onEmbed, onCancel, onChange, className }) {
5493
5630
  const ed = useEditor();
5494
- const rootRef = useRef4(null);
5631
+ const rootRef = useRef5(null);
5495
5632
  const [embedding, setEmbedding] = useState8(false);
5496
5633
  const { layout, update } = usePanelLayout();
5497
- const asideRef = useRef4(null);
5634
+ const asideRef = useRef5(null);
5498
5635
  useShortcuts(rootRef);
5499
5636
  useEffect4(() => {
5500
5637
  ed.setAgent(agentStatus);
5501
5638
  }, [agentStatus]);
5502
- const first = useRef4(true);
5639
+ const first = useRef5(true);
5503
5640
  useEffect4(() => {
5504
5641
  if (first.current) {
5505
5642
  first.current = false;
@@ -5612,7 +5749,7 @@ function PatentRenderShell({ chat, agentStatus = "idle", onEmbed, onCancel, onCh
5612
5749
  }
5613
5750
  function useShortcuts(rootRef) {
5614
5751
  const ed = useEditor();
5615
- const edRef = useRef4(ed);
5752
+ const edRef = useRef5(ed);
5616
5753
  useEffect4(() => {
5617
5754
  edRef.current = ed;
5618
5755
  });
@@ -5688,7 +5825,7 @@ function useShortcuts(rootRef) {
5688
5825
  }
5689
5826
 
5690
5827
  // ../../src/patent-render/client/useAgentChat.ts
5691
- import { useCallback as useCallback4, useEffect as useEffect5, useMemo as useMemo4, useRef as useRef5, useState as useState9 } from "react";
5828
+ import { useCallback as useCallback4, useEffect as useEffect5, useMemo as useMemo4, useRef as useRef6, useState as useState9 } from "react";
5692
5829
  import { fetchServerSentEvents, useChat } from "@tanstack/ai-react";
5693
5830
 
5694
5831
  // ../../src/patent-render/protocol.ts
@@ -5727,13 +5864,13 @@ function friendlyError(e) {
5727
5864
  }
5728
5865
  function useAgentChat({ endpoint, context }) {
5729
5866
  const ed = useEditor();
5730
- const edRef = useRef5(ed);
5867
+ const edRef = useRef6(ed);
5731
5868
  useEffect5(() => {
5732
5869
  edRef.current = ed;
5733
5870
  });
5734
5871
  const [meta, setMeta] = useState9({});
5735
5872
  const [turn, setTurn] = useState9(0);
5736
- const turnRef = useRef5(0);
5873
+ const turnRef = useRef6(0);
5737
5874
  const updateMeta = useCallback4((fn) => {
5738
5875
  const turn2 = turnRef.current;
5739
5876
  setMeta((all) => ({ ...all, [turn2]: fn(all[turn2] ?? blankMeta()) }));
@@ -5844,12 +5981,12 @@ function PatentRender(props) {
5844
5981
  function AgentShell({ endpoint, context, onEmbed, onCancel, onChange, exportPng, className }) {
5845
5982
  const ed = useEditor();
5846
5983
  const agent = useAgentChat({ endpoint, context });
5847
- const chatRef = useRef6(agent.rawMessages);
5984
+ const chatRef = useRef7(agent.rawMessages);
5848
5985
  useEffect6(() => {
5849
5986
  chatRef.current = agent.rawMessages;
5850
5987
  }, [agent.rawMessages]);
5851
5988
  const withChat = (doc) => ({ ...doc, chat: chatRef.current });
5852
- const wasRunning = useRef6(false);
5989
+ const wasRunning = useRef7(false);
5853
5990
  useEffect6(() => {
5854
5991
  const running = agent.agentStatus !== "idle";
5855
5992
  if (wasRunning.current && !running) onChange?.(withChat(ed.state.doc));