@replohq/canopy-sdk 0.5.0 → 0.6.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 (33) hide show
  1. package/_vendor/replo-utils/lib/geometry.d.ts +18 -0
  2. package/_vendor/replo-utils/lib/geometry.mjs +9 -0
  3. package/_vendor/schemas/agentTools/customIntegrations/loaders/product.mjs +1 -1
  4. package/_vendor/schemas/errors.d.ts +1 -1
  5. package/_vendor/schemas/errors.mjs +6 -2
  6. package/_vendor/schemas/generated/selectMode.d.ts +8 -2
  7. package/_vendor/schemas/objectType.mjs +1 -1
  8. package/_vendor/schemas/registry.d.ts +187 -9
  9. package/_vendor/schemas/selectMode.d.ts +41 -2
  10. package/_vendor/schemas/selectMode.mjs +12 -3
  11. package/{chunk-77XUQJHY.mjs → chunk-ZLOHRRSZ.mjs} +96 -1
  12. package/editor/ClientErrorBoundary.d.ts +6 -3
  13. package/editor/ClientErrorBoundary.js +18 -5
  14. package/editor/ClientErrorBoundary.js.map +2 -2
  15. package/editor/NextErrorReporter.d.ts +1 -0
  16. package/editor/NextErrorReporter.js +63 -0
  17. package/editor/NextErrorReporter.js.map +7 -0
  18. package/editor/select-mode/hooks/useSelectModeController.js +2 -1
  19. package/editor/select-mode/hooks/useSelectModeController.js.map +2 -2
  20. package/editor/select-mode/hooks/useSelectionInteractions.d.ts +3 -3
  21. package/editor/select-mode/hooks/useSelectionInteractions.js +54 -16
  22. package/editor/select-mode/hooks/useSelectionInteractions.js.map +2 -2
  23. package/editor/select-mode/interactions/selectionGeometry.d.ts +37 -12
  24. package/editor/select-mode/interactions/selectionGeometry.js +52 -24
  25. package/editor/select-mode/interactions/selectionGeometry.js.map +2 -2
  26. package/editor/select-mode/selectionFrame.d.ts +26 -7
  27. package/editor/select-mode/selectionFrame.js +58 -34
  28. package/editor/select-mode/selectionFrame.js.map +2 -2
  29. package/editor/select-mode/symbolicate.js +32 -1
  30. package/editor/select-mode/symbolicate.js.map +2 -2
  31. package/package.json +1 -1
  32. package/providers/replo-provider.js +11 -7
  33. package/providers/replo-provider.js.map +2 -2
@@ -0,0 +1,63 @@
1
+ "use client";
2
+ import * as React from "react";
3
+ const ERROR_SELECTOR = '[data-next-badge][data-error="true"], [data-nextjs-dialog]';
4
+ function NextErrorReporter() {
5
+ React.useEffect(() => {
6
+ let lastStatus = null;
7
+ let shadowObserver = null;
8
+ let observedRoot = null;
9
+ const post = (status) => {
10
+ if (status === lastStatus) {
11
+ return;
12
+ }
13
+ lastStatus = status;
14
+ window.parent.postMessage(
15
+ {
16
+ type: "replo:preview:status",
17
+ status,
18
+ route: window.location.pathname
19
+ },
20
+ "*"
21
+ );
22
+ };
23
+ const syncOverlayState = () => {
24
+ const portal = document.getElementsByTagName("nextjs-portal")[0];
25
+ if (!(portal instanceof HTMLElement)) {
26
+ post("ok");
27
+ return;
28
+ }
29
+ const root = portal.shadowRoot;
30
+ if (root && root !== observedRoot) {
31
+ shadowObserver?.disconnect();
32
+ shadowObserver = new MutationObserver(syncOverlayState);
33
+ shadowObserver.observe(root, {
34
+ childList: true,
35
+ subtree: true,
36
+ attributes: true,
37
+ attributeFilter: ["data-error"]
38
+ });
39
+ observedRoot = root;
40
+ }
41
+ const showingError = Boolean(
42
+ portal.shadowRoot?.querySelector(ERROR_SELECTOR)
43
+ );
44
+ portal.style.display = showingError ? "none" : "";
45
+ post(showingError ? "error" : "ok");
46
+ };
47
+ const lightObserver = new MutationObserver(syncOverlayState);
48
+ lightObserver.observe(document.documentElement, {
49
+ childList: true,
50
+ subtree: true
51
+ });
52
+ syncOverlayState();
53
+ return () => {
54
+ lightObserver.disconnect();
55
+ shadowObserver?.disconnect();
56
+ };
57
+ }, []);
58
+ return null;
59
+ }
60
+ export {
61
+ NextErrorReporter
62
+ };
63
+ //# sourceMappingURL=NextErrorReporter.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../editor/NextErrorReporter.tsx"],
4
+ "sourcesContent": ["\"use client\";\n\nimport * as React from \"react\";\n\n/**\n * NOTE (Max, 2026-06-10): This component sends post messages to its embedder (website-builder miniapp)\n * so that it can render a loading / error UI if there's an error on this page.\n *\n * Ideally, we wouldn't need any update to canopy-sdk to achieve this: the miniapp would just read the\n * iframe's content and detect whenever there's a nextjs error overlay.\n * But the preview runs cross-origin from the editor, so the editor can't read the iframe's\n * DOM (browser security).\n *\n * This component has observers that detect when the nextjs error overlay appears or\n * disappears, and sends a post message with a status:\n * - `status`: \"error\" while Next's dev overlay reports an error (build or runtime)\n * - `status`: \"ok\" otherwise. Cleared by Fast Refresh on a fix, so it's also the\n * recovery signal (agent fixed the error, so it's the error -> ok transition)\n *\n * It also hides Next's dev error overlay (`<nextjs-portal>`) at the source the\n * instant an error appears, so the red bubble never paints \u2014 the MutationObserver\n * callback runs as a microtask before paint. `data-error` stays queryable while\n * hidden, so detection is unaffected;\n *\n * The overlay lives in `<nextjs-portal>`'s shadow root, which Next can recreate,\n * so we re-attach the shadow observer whenever it hands us a new root. No polling.\n *\n * This must be mounted OUTSIDE the error boundary (see ReploProvider) so it keeps\n * reporting while the boundary is caught (and showing its neutral cover).\n *\n * I'm unsatisfied with this approach: observing for the nextjs-portal is brittle and ugly.\n * Ideally, the ClientErrorBoundary, which hooks into the render cycle, in componentDidCatch, would\n * just report a post message to the miniapp. I prototyped that, the error detection works\n * great (ok -> error transition).\n * But the error -> ok transition doesn't work for Server components (it only does for Client\n * components). Here's a slack thread with me <> Gabe on it:\n * https://replohq.slack.com/archives/C03AACVP08Y/p1781154057832689?thread_ts=1781029224.564489&cid=C03AACVP08Y.\n */\nconst ERROR_SELECTOR =\n '[data-next-badge][data-error=\"true\"], [data-nextjs-dialog]';\n\ntype PreviewStatus = \"ok\" | \"error\";\n\nexport function NextErrorReporter() {\n // eslint-disable-next-line replo/no-use-effect -- Observes Next's dev error overlay (a shadow-DOM node outside React's tree) and relays its state to the cross-origin embedder. No React alternative applies.\n React.useEffect(() => {\n let lastStatus: PreviewStatus | null = null;\n let shadowObserver: MutationObserver | null = null;\n let observedRoot: ShadowRoot | null = null;\n\n const post = (status: PreviewStatus) => {\n if (status === lastStatus) {\n return;\n }\n lastStatus = status;\n window.parent.postMessage(\n {\n type: \"replo:preview:status\",\n status,\n route: window.location.pathname,\n },\n \"*\",\n );\n };\n\n // NOTE (Max, 2026-06-10): Reads the dev overlay's current error state and\n // propagates it \u2014 re-attach the shadow observer to the live root, hide the\n // portal while erroring, and post ok/error up to the editor. Runs on init and\n // on every observed DOM mutation.\n const syncOverlayState = () => {\n const portal = document.getElementsByTagName(\"nextjs-portal\")[0];\n if (!(portal instanceof HTMLElement)) {\n post(\"ok\");\n return;\n }\n // NOTE (Max, 2026-06-10): Re-attach whenever Next hands us a fresh shadow\n // root, else we'd keep watching a detached one after the overlay is\n // recreated.\n const root = portal.shadowRoot;\n if (root && root !== observedRoot) {\n shadowObserver?.disconnect();\n shadowObserver = new MutationObserver(syncOverlayState);\n shadowObserver.observe(root, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: [\"data-error\"],\n });\n observedRoot = root;\n }\n const showingError = Boolean(\n portal.shadowRoot?.querySelector(ERROR_SELECTOR),\n );\n // NOTE (Max, 2026-06-10): Hide the dev overlay at the source so the red\n // bubble never paints.\n portal.style.display = showingError ? \"none\" : \"\";\n post(showingError ? \"error\" : \"ok\");\n };\n\n // NOTE (Max, 2026-06-10): Catches the portal being added/removed in the light\n // DOM; the re-attached shadow observer catches in-overlay changes.\n const lightObserver = new MutationObserver(syncOverlayState);\n lightObserver.observe(document.documentElement, {\n childList: true,\n subtree: true,\n });\n syncOverlayState();\n\n return () => {\n lightObserver.disconnect();\n shadowObserver?.disconnect();\n };\n }, []);\n\n return null;\n}\n"],
5
+ "mappings": ";AAEA,YAAY,WAAW;AAoCvB,MAAM,iBACJ;AAIK,SAAS,oBAAoB;AAElC,QAAM,UAAU,MAAM;AACpB,QAAI,aAAmC;AACvC,QAAI,iBAA0C;AAC9C,QAAI,eAAkC;AAEtC,UAAM,OAAO,CAAC,WAA0B;AACtC,UAAI,WAAW,YAAY;AACzB;AAAA,MACF;AACA,mBAAa;AACb,aAAO,OAAO;AAAA,QACZ;AAAA,UACE,MAAM;AAAA,UACN;AAAA,UACA,OAAO,OAAO,SAAS;AAAA,QACzB;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAMA,UAAM,mBAAmB,MAAM;AAC7B,YAAM,SAAS,SAAS,qBAAqB,eAAe,EAAE,CAAC;AAC/D,UAAI,EAAE,kBAAkB,cAAc;AACpC,aAAK,IAAI;AACT;AAAA,MACF;AAIA,YAAM,OAAO,OAAO;AACpB,UAAI,QAAQ,SAAS,cAAc;AACjC,wBAAgB,WAAW;AAC3B,yBAAiB,IAAI,iBAAiB,gBAAgB;AACtD,uBAAe,QAAQ,MAAM;AAAA,UAC3B,WAAW;AAAA,UACX,SAAS;AAAA,UACT,YAAY;AAAA,UACZ,iBAAiB,CAAC,YAAY;AAAA,QAChC,CAAC;AACD,uBAAe;AAAA,MACjB;AACA,YAAM,eAAe;AAAA,QACnB,OAAO,YAAY,cAAc,cAAc;AAAA,MACjD;AAGA,aAAO,MAAM,UAAU,eAAe,SAAS;AAC/C,WAAK,eAAe,UAAU,IAAI;AAAA,IACpC;AAIA,UAAM,gBAAgB,IAAI,iBAAiB,gBAAgB;AAC3D,kBAAc,QAAQ,SAAS,iBAAiB;AAAA,MAC9C,WAAW;AAAA,MACX,SAAS;AAAA,IACX,CAAC;AACD,qBAAiB;AAEjB,WAAO,MAAM;AACX,oBAAc,WAAW;AACzB,sBAAgB,WAAW;AAAA,IAC7B;AAAA,EACF,GAAG,CAAC,CAAC;AAEL,SAAO;AACT;",
6
+ "names": []
7
+ }
@@ -9,7 +9,8 @@ function resetInteractionSession({
9
9
  window.parent.postMessage(
10
10
  {
11
11
  type: "replo:select:dragRectUpdated",
12
- rect: null
12
+ dragRect: null,
13
+ selectionRects: []
13
14
  },
14
15
  "*"
15
16
  );
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../editor/select-mode/hooks/useSelectModeController.ts"],
4
- "sourcesContent": ["import type {\n DisplayMode,\n SelectModeSelectionType,\n} from \"schemas/generated/selectMode\";\nimport type { SelectModeInteractionSession } from \"../selectModeSession\";\n\nimport { useCallback, useRef, useState } from \"react\";\n\nimport { hideSelectionFrame } from \"../selectionFrame\";\nimport { IDLE_SESSION } from \"../selectModeSession\";\n\n/**\n * Tear down any in-progress drag/selection. Re-used by both the\n * display-mode flip-out path (defensive: belt-and-braces with the\n * parent's `setSelectionType(\"none\")` push) and by the explicit\n * `setSelectionType(\"none\")` path below.\n */\nfunction resetInteractionSession({\n interactionSessionRef,\n}: {\n interactionSessionRef: React.MutableRefObject<SelectModeInteractionSession>;\n}) {\n const currentSession = interactionSessionRef.current;\n if (currentSession.type === \"drag\" && currentSession.hasExceededThreshold) {\n window.parent.postMessage(\n {\n type: \"replo:select:dragRectUpdated\",\n rect: null,\n },\n \"*\",\n );\n }\n hideSelectionFrame();\n interactionSessionRef.current = IDLE_SESSION;\n}\n\nexport function useSelectModeController() {\n const [displayMode, setDisplayModeState] = useState<DisplayMode>(\"browse\");\n const displayModeRef = useRef<DisplayMode>(\"browse\");\n const interactionSessionRef =\n useRef<SelectModeInteractionSession>(IDLE_SESSION);\n\n // The parent is authoritative for \"is there a current selection?\". Canopy\n // originates selections via pointer events, posts them up, agent-ui\n // mirrors `selection.type` into `agentUiState`, and the result is pushed\n // back down here. When the parent says `none` (panel dismissed / submit /\n // exit selection mode) we tear down the in-iframe frame; the matching\n // commit-side paths are in `useSelectionInteractions`.\n const setSelectionType = useCallback(\n (selectionType: SelectModeSelectionType) => {\n if (selectionType === \"none\") {\n resetInteractionSession({ interactionSessionRef });\n }\n },\n [],\n );\n\n const setDisplayMode = useCallback((nextDisplayMode: DisplayMode) => {\n if (\n displayModeRef.current === \"selection\" &&\n nextDisplayMode !== \"selection\"\n ) {\n resetInteractionSession({ interactionSessionRef });\n }\n\n displayModeRef.current = nextDisplayMode;\n setDisplayModeState(nextDisplayMode);\n }, []);\n\n return {\n displayMode,\n interactionSessionRef,\n setDisplayMode,\n setSelectionType,\n };\n}\n"],
5
- "mappings": "AAMA,SAAS,aAAa,QAAQ,gBAAgB;AAE9C,SAAS,0BAA0B;AACnC,SAAS,oBAAoB;AAQ7B,SAAS,wBAAwB;AAAA,EAC/B;AACF,GAEG;AACD,QAAM,iBAAiB,sBAAsB;AAC7C,MAAI,eAAe,SAAS,UAAU,eAAe,sBAAsB;AACzE,WAAO,OAAO;AAAA,MACZ;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,MACR;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACA,qBAAmB;AACnB,wBAAsB,UAAU;AAClC;AAEO,SAAS,0BAA0B;AACxC,QAAM,CAAC,aAAa,mBAAmB,IAAI,SAAsB,QAAQ;AACzE,QAAM,iBAAiB,OAAoB,QAAQ;AACnD,QAAM,wBACJ,OAAqC,YAAY;AAQnD,QAAM,mBAAmB;AAAA,IACvB,CAAC,kBAA2C;AAC1C,UAAI,kBAAkB,QAAQ;AAC5B,gCAAwB,EAAE,sBAAsB,CAAC;AAAA,MACnD;AAAA,IACF;AAAA,IACA,CAAC;AAAA,EACH;AAEA,QAAM,iBAAiB,YAAY,CAAC,oBAAiC;AACnE,QACE,eAAe,YAAY,eAC3B,oBAAoB,aACpB;AACA,8BAAwB,EAAE,sBAAsB,CAAC;AAAA,IACnD;AAEA,mBAAe,UAAU;AACzB,wBAAoB,eAAe;AAAA,EACrC,GAAG,CAAC,CAAC;AAEL,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import type {\n DisplayMode,\n SelectModeSelectionType,\n} from \"schemas/generated/selectMode\";\nimport type { SelectModeInteractionSession } from \"../selectModeSession\";\n\nimport { useCallback, useRef, useState } from \"react\";\n\nimport { hideSelectionFrame } from \"../selectionFrame\";\nimport { IDLE_SESSION } from \"../selectModeSession\";\n\n/**\n * Tear down any in-progress drag/selection. Re-used by both the\n * display-mode flip-out path (defensive: belt-and-braces with the\n * parent's `setSelectionType(\"none\")` push) and by the explicit\n * `setSelectionType(\"none\")` path below.\n */\nfunction resetInteractionSession({\n interactionSessionRef,\n}: {\n interactionSessionRef: React.MutableRefObject<SelectModeInteractionSession>;\n}) {\n const currentSession = interactionSessionRef.current;\n if (currentSession.type === \"drag\" && currentSession.hasExceededThreshold) {\n window.parent.postMessage(\n {\n type: \"replo:select:dragRectUpdated\",\n dragRect: null,\n selectionRects: [],\n },\n \"*\",\n );\n }\n hideSelectionFrame();\n interactionSessionRef.current = IDLE_SESSION;\n}\n\nexport function useSelectModeController() {\n const [displayMode, setDisplayModeState] = useState<DisplayMode>(\"browse\");\n const displayModeRef = useRef<DisplayMode>(\"browse\");\n const interactionSessionRef =\n useRef<SelectModeInteractionSession>(IDLE_SESSION);\n\n // The parent is authoritative for \"is there a current selection?\". Canopy\n // originates selections via pointer events, posts them up, agent-ui\n // mirrors `selection.type` into `agentUiState`, and the result is pushed\n // back down here. When the parent says `none` (panel dismissed / submit /\n // exit selection mode) we tear down the in-iframe frame; the matching\n // commit-side paths are in `useSelectionInteractions`.\n const setSelectionType = useCallback(\n (selectionType: SelectModeSelectionType) => {\n if (selectionType === \"none\") {\n resetInteractionSession({ interactionSessionRef });\n }\n },\n [],\n );\n\n const setDisplayMode = useCallback((nextDisplayMode: DisplayMode) => {\n if (\n displayModeRef.current === \"selection\" &&\n nextDisplayMode !== \"selection\"\n ) {\n resetInteractionSession({ interactionSessionRef });\n }\n\n displayModeRef.current = nextDisplayMode;\n setDisplayModeState(nextDisplayMode);\n }, []);\n\n return {\n displayMode,\n interactionSessionRef,\n setDisplayMode,\n setSelectionType,\n };\n}\n"],
5
+ "mappings": "AAMA,SAAS,aAAa,QAAQ,gBAAgB;AAE9C,SAAS,0BAA0B;AACnC,SAAS,oBAAoB;AAQ7B,SAAS,wBAAwB;AAAA,EAC/B;AACF,GAEG;AACD,QAAM,iBAAiB,sBAAsB;AAC7C,MAAI,eAAe,SAAS,UAAU,eAAe,sBAAsB;AACzE,WAAO,OAAO;AAAA,MACZ;AAAA,QACE,MAAM;AAAA,QACN,UAAU;AAAA,QACV,gBAAgB,CAAC;AAAA,MACnB;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACA,qBAAmB;AACnB,wBAAsB,UAAU;AAClC;AAEO,SAAS,0BAA0B;AACxC,QAAM,CAAC,aAAa,mBAAmB,IAAI,SAAsB,QAAQ;AACzE,QAAM,iBAAiB,OAAoB,QAAQ;AACnD,QAAM,wBACJ,OAAqC,YAAY;AAQnD,QAAM,mBAAmB;AAAA,IACvB,CAAC,kBAA2C;AAC1C,UAAI,kBAAkB,QAAQ;AAC5B,gCAAwB,EAAE,sBAAsB,CAAC;AAAA,MACnD;AAAA,IACF;AAAA,IACA,CAAC;AAAA,EACH;AAEA,QAAM,iBAAiB,YAAY,CAAC,oBAAiC;AACnE,QACE,eAAe,YAAY,eAC3B,oBAAoB,aACpB;AACA,8BAAwB,EAAE,sBAAsB,CAAC;AAAA,IACnD;AAEA,mBAAe,UAAU;AACzB,wBAAoB,eAAe;AAAA,EACrC,GAAG,CAAC,CAAC;AAEL,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -13,9 +13,9 @@ import type { SelectModeInteractionSession } from "../selectModeSession";
13
13
  * accidental drag still resolves as a click.
14
14
  * - On `pointerup` we either:
15
15
  * - resolve as an `ELEMENT_SELECTED` (single click / sub-threshold drag)
16
- * - resolve as an `AREA_SELECTED` (drag past threshold), running
17
- * `getElementsInRect` on the final rectangle to enumerate which
18
- * descendants the user enclosed.
16
+ * - resolve as an `AREA_SELECTED` (drag past threshold), filtering the
17
+ * candidates snapshotted at drag start against the final rectangle to
18
+ * enumerate which descendants the user enclosed.
19
19
  * - During an active drag a `requestAnimationFrame` loop keeps the rect in
20
20
  * sync with the page scroll so the rectangle visually "sticks" to the
21
21
  * page rather than the viewport.
@@ -4,14 +4,16 @@ import {
4
4
  getNearestSelectableElement
5
5
  } from "../descriptor/elementDescriptor";
6
6
  import {
7
+ collectDragCandidates,
8
+ getCandidatesInSelection,
7
9
  getDocumentScrollOffset,
8
10
  getDragPositionFromClient,
9
11
  getElementAnchor,
10
- getElementsInRect,
11
12
  getPageRectFromViewportRect,
13
+ getViewportRectFromPageRect,
12
14
  getViewportSelectionRect
13
15
  } from "../interactions/selectionGeometry";
14
- import { showSelectionFrame } from "../selectionFrame";
16
+ import { showSelectionFrame, showSelectionFrames } from "../selectionFrame";
15
17
  import { IDLE_SESSION } from "../selectModeSession";
16
18
  import { symbolicateSelectedElement } from "../symbolicate";
17
19
  async function maybeSymbolicate(data) {
@@ -26,6 +28,7 @@ function useSelectionInteractions({
26
28
  return;
27
29
  }
28
30
  let dragAnimationFrameId = null;
31
+ let dragCandidates = [];
29
32
  const stopDragAnimation = () => {
30
33
  if (dragAnimationFrameId === null) {
31
34
  return;
@@ -33,18 +36,22 @@ function useSelectionInteractions({
33
36
  cancelAnimationFrame(dragAnimationFrameId);
34
37
  dragAnimationFrameId = null;
35
38
  };
36
- const resetDragState = () => {
39
+ const resetDragState = ({
40
+ notifyParentDragCleared = true
41
+ } = {}) => {
37
42
  const currentSession = interactionSessionRef.current;
38
43
  stopDragAnimation();
39
- if (currentSession.type === "drag" && currentSession.hasExceededThreshold) {
44
+ if (notifyParentDragCleared && currentSession.type === "drag" && currentSession.hasExceededThreshold) {
40
45
  window.parent.postMessage(
41
46
  {
42
47
  type: "replo:select:dragRectUpdated",
43
- rect: null
48
+ dragRect: null,
49
+ selectionRects: []
44
50
  },
45
51
  "*"
46
52
  );
47
53
  }
54
+ dragCandidates = [];
48
55
  interactionSessionRef.current = IDLE_SESSION;
49
56
  };
50
57
  const postCurrentDragRect = () => {
@@ -66,10 +73,25 @@ function useSelectionInteractions({
66
73
  hasExceededThreshold: true
67
74
  };
68
75
  }
76
+ const selectionPageRect = getPageRectFromViewportRect({
77
+ rect,
78
+ scrollOffset: session.scrollOffset
79
+ });
80
+ const selectionRects = getCandidatesInSelection({
81
+ candidates: dragCandidates,
82
+ selectionPageRect
83
+ }).map((candidate) => ({
84
+ id: candidate.id,
85
+ rect: getViewportRectFromPageRect({
86
+ rect: candidate.pageRect,
87
+ scrollOffset: session.scrollOffset
88
+ })
89
+ }));
69
90
  window.parent.postMessage(
70
91
  {
71
92
  type: "replo:select:dragRectUpdated",
72
- rect
93
+ dragRect: rect,
94
+ selectionRects
73
95
  },
74
96
  "*"
75
97
  );
@@ -117,6 +139,7 @@ function useSelectionInteractions({
117
139
  scrollOffset,
118
140
  hasExceededThreshold: false
119
141
  };
142
+ dragCandidates = collectDragCandidates(scrollOffset);
120
143
  if (dragAnimationFrameId === null) {
121
144
  dragAnimationFrameId = requestAnimationFrame(syncDragRectToViewport);
122
145
  }
@@ -191,7 +214,8 @@ function useSelectionInteractions({
191
214
  const dragStart = snapshot.type === "drag" ? snapshot.dragStart : null;
192
215
  const dragCurrent = snapshot.type === "drag" ? snapshot.dragCurrent : null;
193
216
  const scrollOffset = snapshot.type === "drag" ? snapshot.scrollOffset : getDocumentScrollOffset();
194
- resetDragState();
217
+ const candidates = dragCandidates;
218
+ resetDragState({ notifyParentDragCleared: false });
195
219
  if (!dragStart || snapshot.type !== "drag") {
196
220
  const targetElement = event.target;
197
221
  if (!(targetElement instanceof Element)) {
@@ -220,24 +244,38 @@ function useSelectionInteractions({
220
244
  });
221
245
  return;
222
246
  }
223
- const items = getElementsInRect(selectionRect).map((element) => {
224
- return buildElementDescriptor({
225
- element,
226
- clickPosition: getElementAnchor({ element, selectionRect })
227
- });
228
- });
229
247
  const pageRect = getPageRectFromViewportRect({
230
248
  rect: selectionRect,
231
249
  scrollOffset
232
250
  });
251
+ const selectedCandidates = getCandidatesInSelection({
252
+ candidates,
253
+ selectionPageRect: pageRect
254
+ });
255
+ const items = selectedCandidates.map((candidate) => {
256
+ return buildElementDescriptor({
257
+ element: candidate.element,
258
+ clickPosition: getElementAnchor({
259
+ element: candidate.element,
260
+ selectionRect
261
+ })
262
+ });
263
+ });
233
264
  interactionSessionRef.current = {
234
265
  type: "area",
235
266
  pageRect,
236
267
  items
237
268
  };
238
- showSelectionFrame({
239
- variant: "area",
240
- pageRect
269
+ showSelectionFrames({
270
+ frames: selectedCandidates.map((candidate) => ({
271
+ variant: "area",
272
+ pageRect: {
273
+ x: candidate.pageRect.x,
274
+ y: candidate.pageRect.y,
275
+ width: candidate.pageRect.width,
276
+ height: candidate.pageRect.height
277
+ }
278
+ }))
241
279
  });
242
280
  void Promise.all(items.map(maybeSymbolicate)).then(
243
281
  (symbolicatedItems) => {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../editor/select-mode/hooks/useSelectionInteractions.ts"],
4
- "sourcesContent": ["import type { MutableRefObject } from \"react\";\nimport type { DisplayMode, SelectableData } from \"schemas/generated/selectMode\";\nimport type { SelectModeInteractionSession } from \"../selectModeSession\";\n\nimport { useEffect } from \"react\";\n\nimport {\n buildElementDescriptor,\n getNearestSelectableElement,\n} from \"../descriptor/elementDescriptor\";\nimport {\n getDocumentScrollOffset,\n getDragPositionFromClient,\n getElementAnchor,\n getElementsInRect,\n getPageRectFromViewportRect,\n getViewportSelectionRect,\n} from \"../interactions/selectionGeometry\";\nimport { showSelectionFrame } from \"../selectionFrame\";\nimport { IDLE_SESSION } from \"../selectModeSession\";\nimport { symbolicateSelectedElement } from \"../symbolicate\";\n\n// React fibers carry only Turbopack chunk paths; resolving them to the\n// user's source file is async and only meaningful for \"react-element\"\n// kinds. Plan selectables already point at the right thing.\nasync function maybeSymbolicate(data: SelectableData): Promise<SelectableData> {\n return data.kind === \"react-element\"\n ? symbolicateSelectedElement(data)\n : data;\n}\n\n/**\n * Owns the iframe-side pointer interactions that drive selection:\n *\n * - On `pointerdown` we open a `drag` session (storing both client + page\n * coords plus the current scroll offset). We don't yet know if this will\n * become a click or an actual drag.\n * - On `pointermove` we update the drag rect and post `DRAG_RECT_UPDATED`\n * to the parent so the live drag rectangle can render. We only flip\n * `hasExceededThreshold` once the rect grows past 6\u00D76 px so that a tiny\n * accidental drag still resolves as a click.\n * - On `pointerup` we either:\n * - resolve as an `ELEMENT_SELECTED` (single click / sub-threshold drag)\n * - resolve as an `AREA_SELECTED` (drag past threshold), running\n * `getElementsInRect` on the final rectangle to enumerate which\n * descendants the user enclosed.\n * - During an active drag a `requestAnimationFrame` loop keeps the rect in\n * sync with the page scroll so the rectangle visually \"sticks\" to the\n * page rather than the viewport.\n *\n * We capture-listen and `preventDefault`/`stopPropagation` clicks so the\n * underlying page can't navigate or trigger handlers while the user is\n * working in selection mode.\n *\n * @author Kevin O'Connell 2026-04-17\n */\nexport function useSelectionInteractions({\n displayMode,\n interactionSessionRef,\n}: {\n displayMode: DisplayMode;\n interactionSessionRef: MutableRefObject<SelectModeInteractionSession>;\n}) {\n // eslint-disable-next-line replo/no-use-effect -- Legacy effect - may or may not be necessary\n useEffect(() => {\n if (displayMode !== \"selection\") {\n return;\n }\n\n let dragAnimationFrameId: number | null = null;\n\n const stopDragAnimation = () => {\n if (dragAnimationFrameId === null) {\n return;\n }\n\n cancelAnimationFrame(dragAnimationFrameId);\n dragAnimationFrameId = null;\n };\n\n const resetDragState = () => {\n const currentSession = interactionSessionRef.current;\n\n stopDragAnimation();\n\n if (\n currentSession.type === \"drag\" &&\n currentSession.hasExceededThreshold\n ) {\n window.parent.postMessage(\n {\n type: \"replo:select:dragRectUpdated\",\n rect: null,\n },\n \"*\",\n );\n }\n\n interactionSessionRef.current = IDLE_SESSION;\n };\n\n const postCurrentDragRect = () => {\n const session = interactionSessionRef.current;\n if (session.type !== \"drag\") {\n return;\n }\n\n const rect = getViewportSelectionRect({\n dragStart: session.dragStart,\n dragCurrent: session.dragCurrent,\n scrollOffset: session.scrollOffset,\n });\n\n if (\n rect.width <= 6 &&\n rect.height <= 6 &&\n !session.hasExceededThreshold\n ) {\n return;\n }\n\n if (!session.hasExceededThreshold) {\n interactionSessionRef.current = {\n ...session,\n hasExceededThreshold: true,\n };\n }\n\n window.parent.postMessage(\n {\n type: \"replo:select:dragRectUpdated\",\n rect,\n },\n \"*\",\n );\n };\n\n const syncDragRectToViewport = () => {\n const session = interactionSessionRef.current;\n if (session.type !== \"drag\") {\n dragAnimationFrameId = null;\n return;\n }\n\n const nextScrollOffset = getDocumentScrollOffset();\n const nextDragCurrent = getDragPositionFromClient({\n clientX: session.dragCurrent.clientX,\n clientY: session.dragCurrent.clientY,\n scrollOffset: nextScrollOffset,\n });\n\n if (\n nextDragCurrent.pageX !== session.dragCurrent.pageX ||\n nextDragCurrent.pageY !== session.dragCurrent.pageY\n ) {\n interactionSessionRef.current = {\n ...session,\n dragCurrent: nextDragCurrent,\n scrollOffset: nextScrollOffset,\n };\n postCurrentDragRect();\n } else {\n interactionSessionRef.current = {\n ...session,\n scrollOffset: nextScrollOffset,\n };\n }\n\n dragAnimationFrameId = requestAnimationFrame(syncDragRectToViewport);\n };\n\n const handlePointerDown = (event: PointerEvent) => {\n event.preventDefault();\n event.stopPropagation();\n\n const scrollOffset = getDocumentScrollOffset();\n const dragStart = getDragPositionFromClient({\n clientX: event.clientX,\n clientY: event.clientY,\n scrollOffset,\n });\n interactionSessionRef.current = {\n type: \"drag\",\n dragStart,\n dragCurrent: dragStart,\n scrollOffset,\n hasExceededThreshold: false,\n };\n\n if (dragAnimationFrameId === null) {\n dragAnimationFrameId = requestAnimationFrame(syncDragRectToViewport);\n }\n };\n\n const handlePointerMove = (event: PointerEvent) => {\n const session = interactionSessionRef.current;\n if (session.type !== \"drag\") {\n return;\n }\n\n interactionSessionRef.current = {\n ...session,\n dragCurrent: getDragPositionFromClient({\n clientX: event.clientX,\n clientY: event.clientY,\n scrollOffset: getDocumentScrollOffset(),\n }),\n };\n postCurrentDragRect();\n };\n\n const handleViewportChangeDuringDrag = () => {\n const session = interactionSessionRef.current;\n if (session.type !== \"drag\" || dragAnimationFrameId !== null) {\n return;\n }\n\n dragAnimationFrameId = requestAnimationFrame(syncDragRectToViewport);\n };\n\n const commitElementSelection = ({\n targetElement,\n pointerEvent,\n }: {\n targetElement: Element;\n pointerEvent: PointerEvent;\n }) => {\n const selectionElement =\n getNearestSelectableElement(targetElement) ?? targetElement;\n const targetRect = selectionElement.getBoundingClientRect();\n const data = buildElementDescriptor({\n element: selectionElement,\n clickPosition: {\n x: pointerEvent.clientX,\n y: pointerEvent.clientY,\n },\n });\n interactionSessionRef.current = {\n type: \"element\",\n element: selectionElement,\n clickPosition: {\n x: pointerEvent.clientX - targetRect.left,\n y: pointerEvent.clientY - targetRect.top,\n },\n data,\n };\n\n // Paint the in-iframe selection frame synchronously for instant\n // feedback \u2014 symbolicate is a network roundtrip and we don't want\n // the visual selection to wait on it.\n const scrollOffset = getDocumentScrollOffset();\n showSelectionFrame({\n variant: \"element\",\n pageRect: {\n x: targetRect.left + scrollOffset.left,\n y: targetRect.top + scrollOffset.top,\n width: targetRect.width,\n height: targetRect.height,\n },\n });\n\n // Resolve compiled Turbopack chunk paths to the original `.tsx` paths\n // via Next.js's dev-only `/__nextjs_original-stack-frames` endpoint\n // before posting. Without this the parent receives a chunk URL and\n // the agent prompt points at bundled output instead of user source.\n void maybeSymbolicate(data).then((symbolicated) => {\n window.parent.postMessage(\n {\n type: \"replo:select:elementSelected\",\n data: symbolicated,\n },\n \"*\",\n );\n });\n };\n\n const handlePointerUp = (event: PointerEvent) => {\n const snapshot = interactionSessionRef.current;\n const wasDragging =\n snapshot.type === \"drag\" ? snapshot.hasExceededThreshold : false;\n const dragStart = snapshot.type === \"drag\" ? snapshot.dragStart : null;\n const dragCurrent =\n snapshot.type === \"drag\" ? snapshot.dragCurrent : null;\n const scrollOffset =\n snapshot.type === \"drag\"\n ? snapshot.scrollOffset\n : getDocumentScrollOffset();\n\n resetDragState();\n\n if (!dragStart || snapshot.type !== \"drag\") {\n const targetElement = event.target;\n if (!(targetElement instanceof Element)) {\n return;\n }\n\n commitElementSelection({\n targetElement,\n pointerEvent: event,\n });\n return;\n }\n\n const resolvedDragCurrent = dragCurrent ?? dragStart;\n const selectionRect = getViewportSelectionRect({\n dragStart,\n dragCurrent: resolvedDragCurrent,\n scrollOffset,\n });\n\n if (!wasDragging) {\n const targetElement = event.target;\n if (!(targetElement instanceof Element)) {\n return;\n }\n\n commitElementSelection({\n targetElement,\n pointerEvent: event,\n });\n return;\n }\n\n const items = getElementsInRect(selectionRect).map((element) => {\n return buildElementDescriptor({\n element,\n clickPosition: getElementAnchor({ element, selectionRect }),\n });\n });\n\n const pageRect = getPageRectFromViewportRect({\n rect: selectionRect,\n scrollOffset,\n });\n\n interactionSessionRef.current = {\n type: \"area\",\n pageRect,\n items,\n };\n\n showSelectionFrame({\n variant: \"area\",\n pageRect,\n });\n\n void Promise.all(items.map(maybeSymbolicate)).then(\n (symbolicatedItems) => {\n window.parent.postMessage(\n {\n type: \"replo:select:areaSelected\",\n rect: selectionRect,\n items: symbolicatedItems,\n },\n \"*\",\n );\n },\n );\n };\n\n const handleClick = (event: MouseEvent) => {\n event.preventDefault();\n event.stopPropagation();\n };\n\n const handlePointerCancel = () => {\n resetDragState();\n };\n\n const handleWindowBlur = () => {\n resetDragState();\n };\n\n document.addEventListener(\"pointerdown\", handlePointerDown, true);\n document.addEventListener(\"pointermove\", handlePointerMove, true);\n document.addEventListener(\"pointerup\", handlePointerUp, true);\n document.addEventListener(\"pointercancel\", handlePointerCancel, true);\n document.addEventListener(\"click\", handleClick, true);\n document.addEventListener(\"scroll\", handleViewportChangeDuringDrag, true);\n window.addEventListener(\"blur\", handleWindowBlur);\n window.addEventListener(\"resize\", handleViewportChangeDuringDrag);\n\n return () => {\n document.removeEventListener(\"pointerdown\", handlePointerDown, true);\n document.removeEventListener(\"pointermove\", handlePointerMove, true);\n document.removeEventListener(\"pointerup\", handlePointerUp, true);\n document.removeEventListener(\"pointercancel\", handlePointerCancel, true);\n document.removeEventListener(\"click\", handleClick, true);\n document.removeEventListener(\n \"scroll\",\n handleViewportChangeDuringDrag,\n true,\n );\n window.removeEventListener(\"blur\", handleWindowBlur);\n window.removeEventListener(\"resize\", handleViewportChangeDuringDrag);\n resetDragState();\n };\n }, [displayMode, interactionSessionRef]);\n}\n"],
5
- "mappings": "AAIA,SAAS,iBAAiB;AAE1B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,0BAA0B;AACnC,SAAS,oBAAoB;AAC7B,SAAS,kCAAkC;AAK3C,eAAe,iBAAiB,MAA+C;AAC7E,SAAO,KAAK,SAAS,kBACjB,2BAA2B,IAAI,IAC/B;AACN;AA2BO,SAAS,yBAAyB;AAAA,EACvC;AAAA,EACA;AACF,GAGG;AAED,YAAU,MAAM;AACd,QAAI,gBAAgB,aAAa;AAC/B;AAAA,IACF;AAEA,QAAI,uBAAsC;AAE1C,UAAM,oBAAoB,MAAM;AAC9B,UAAI,yBAAyB,MAAM;AACjC;AAAA,MACF;AAEA,2BAAqB,oBAAoB;AACzC,6BAAuB;AAAA,IACzB;AAEA,UAAM,iBAAiB,MAAM;AAC3B,YAAM,iBAAiB,sBAAsB;AAE7C,wBAAkB;AAElB,UACE,eAAe,SAAS,UACxB,eAAe,sBACf;AACA,eAAO,OAAO;AAAA,UACZ;AAAA,YACE,MAAM;AAAA,YACN,MAAM;AAAA,UACR;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAEA,4BAAsB,UAAU;AAAA,IAClC;AAEA,UAAM,sBAAsB,MAAM;AAChC,YAAM,UAAU,sBAAsB;AACtC,UAAI,QAAQ,SAAS,QAAQ;AAC3B;AAAA,MACF;AAEA,YAAM,OAAO,yBAAyB;AAAA,QACpC,WAAW,QAAQ;AAAA,QACnB,aAAa,QAAQ;AAAA,QACrB,cAAc,QAAQ;AAAA,MACxB,CA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Content": ["import type { MutableRefObject } from \"react\";\nimport type { DisplayMode, SelectableData } from \"schemas/generated/selectMode\";\nimport type { DragCandidate } from \"../interactions/selectionGeometry\";\nimport type { SelectModeInteractionSession } from \"../selectModeSession\";\n\nimport { useEffect } from \"react\";\n\nimport {\n buildElementDescriptor,\n getNearestSelectableElement,\n} from \"../descriptor/elementDescriptor\";\nimport {\n collectDragCandidates,\n getCandidatesInSelection,\n getDocumentScrollOffset,\n getDragPositionFromClient,\n getElementAnchor,\n getPageRectFromViewportRect,\n getViewportRectFromPageRect,\n getViewportSelectionRect,\n} from \"../interactions/selectionGeometry\";\nimport { showSelectionFrame, showSelectionFrames } from \"../selectionFrame\";\nimport { IDLE_SESSION } from \"../selectModeSession\";\nimport { symbolicateSelectedElement } from \"../symbolicate\";\n\n// React fibers carry only Turbopack chunk paths; resolving them to the\n// user's source file is async and only meaningful for \"react-element\"\n// kinds. Plan selectables already point at the right thing.\nasync function maybeSymbolicate(data: SelectableData): Promise<SelectableData> {\n return data.kind === \"react-element\"\n ? symbolicateSelectedElement(data)\n : data;\n}\n\n/**\n * Owns the iframe-side pointer interactions that drive selection:\n *\n * - On `pointerdown` we open a `drag` session (storing both client + page\n * coords plus the current scroll offset). We don't yet know if this will\n * become a click or an actual drag.\n * - On `pointermove` we update the drag rect and post `DRAG_RECT_UPDATED`\n * to the parent so the live drag rectangle can render. We only flip\n * `hasExceededThreshold` once the rect grows past 6\u00D76 px so that a tiny\n * accidental drag still resolves as a click.\n * - On `pointerup` we either:\n * - resolve as an `ELEMENT_SELECTED` (single click / sub-threshold drag)\n * - resolve as an `AREA_SELECTED` (drag past threshold), filtering the\n * candidates snapshotted at drag start against the final rectangle to\n * enumerate which descendants the user enclosed.\n * - During an active drag a `requestAnimationFrame` loop keeps the rect in\n * sync with the page scroll so the rectangle visually \"sticks\" to the\n * page rather than the viewport.\n *\n * We capture-listen and `preventDefault`/`stopPropagation` clicks so the\n * underlying page can't navigate or trigger handlers while the user is\n * working in selection mode.\n *\n * @author Kevin O'Connell 2026-04-17\n */\nexport function useSelectionInteractions({\n displayMode,\n interactionSessionRef,\n}: {\n displayMode: DisplayMode;\n interactionSessionRef: MutableRefObject<SelectModeInteractionSession>;\n}) {\n // eslint-disable-next-line replo/no-use-effect -- Legacy effect - may or may not be necessary\n useEffect(() => {\n if (displayMode !== \"selection\") {\n return;\n }\n\n let dragAnimationFrameId: number | null = null;\n // Snapshot of the page's meaningful elements + their page rects, taken\n // once when a drag begins so per-move hit-testing avoids a full-DOM scan.\n let dragCandidates: DragCandidate[] = [];\n\n const stopDragAnimation = () => {\n if (dragAnimationFrameId === null) {\n return;\n }\n\n cancelAnimationFrame(dragAnimationFrameId);\n dragAnimationFrameId = null;\n };\n\n // `notifyParentDragCleared` posts a null drag rect so the parent tears\n // down the live drag overlay. The area-commit path suppresses it: the\n // parent maps a null drag rect to `selection = none`, which round-trips\n // back as `setSelectionType(\"none\")` and wipes the in-iframe frames we're\n // about to paint. The follow-up `areaSelected` supersedes the drag overlay\n // on its own, so the null post is pure collateral damage there.\n const resetDragState = ({\n notifyParentDragCleared = true,\n }: { notifyParentDragCleared?: boolean } = {}) => {\n const currentSession = interactionSessionRef.current;\n\n stopDragAnimation();\n\n if (\n notifyParentDragCleared &&\n currentSession.type === \"drag\" &&\n currentSession.hasExceededThreshold\n ) {\n window.parent.postMessage(\n {\n type: \"replo:select:dragRectUpdated\",\n dragRect: null,\n selectionRects: [],\n },\n \"*\",\n );\n }\n\n dragCandidates = [];\n interactionSessionRef.current = IDLE_SESSION;\n };\n\n const postCurrentDragRect = () => {\n const session = interactionSessionRef.current;\n if (session.type !== \"drag\") {\n return;\n }\n\n const rect = getViewportSelectionRect({\n dragStart: session.dragStart,\n dragCurrent: session.dragCurrent,\n scrollOffset: session.scrollOffset,\n });\n\n if (\n rect.width <= 6 &&\n rect.height <= 6 &&\n !session.hasExceededThreshold\n ) {\n return;\n }\n\n if (!session.hasExceededThreshold) {\n interactionSessionRef.current = {\n ...session,\n hasExceededThreshold: true,\n };\n }\n\n // Cheap hit-test against the candidates we snapshotted at drag start,\n // projected back to viewport coords so the parent can paint a live\n // highlight on each element the drag will capture. No DOM scan here.\n const selectionPageRect = getPageRectFromViewportRect({\n rect,\n scrollOffset: session.scrollOffset,\n });\n const selectionRects = getCandidatesInSelection({\n candidates: dragCandidates,\n selectionPageRect,\n }).map((candidate) => ({\n id: candidate.id,\n rect: getViewportRectFromPageRect({\n rect: candidate.pageRect,\n scrollOffset: session.scrollOffset,\n }),\n }));\n\n window.parent.postMessage(\n {\n type: \"replo:select:dragRectUpdated\",\n dragRect: rect,\n selectionRects,\n },\n \"*\",\n );\n };\n\n const syncDragRectToViewport = () => {\n const session = interactionSessionRef.current;\n if (session.type !== \"drag\") {\n dragAnimationFrameId = null;\n return;\n }\n\n const nextScrollOffset = getDocumentScrollOffset();\n const nextDragCurrent = getDragPositionFromClient({\n clientX: session.dragCurrent.clientX,\n clientY: session.dragCurrent.clientY,\n scrollOffset: nextScrollOffset,\n });\n\n if (\n nextDragCurrent.pageX !== session.dragCurrent.pageX ||\n nextDragCurrent.pageY !== session.dragCurrent.pageY\n ) {\n interactionSessionRef.current = {\n ...session,\n dragCurrent: nextDragCurrent,\n scrollOffset: nextScrollOffset,\n };\n postCurrentDragRect();\n } else {\n interactionSessionRef.current = {\n ...session,\n scrollOffset: nextScrollOffset,\n };\n }\n\n dragAnimationFrameId = requestAnimationFrame(syncDragRectToViewport);\n };\n\n const handlePointerDown = (event: PointerEvent) => {\n event.preventDefault();\n event.stopPropagation();\n\n const scrollOffset = getDocumentScrollOffset();\n const dragStart = getDragPositionFromClient({\n clientX: event.clientX,\n clientY: event.clientY,\n scrollOffset,\n });\n interactionSessionRef.current = {\n type: \"drag\",\n dragStart,\n dragCurrent: dragStart,\n scrollOffset,\n hasExceededThreshold: false,\n };\n dragCandidates = collectDragCandidates(scrollOffset);\n\n if (dragAnimationFrameId === null) {\n dragAnimationFrameId = requestAnimationFrame(syncDragRectToViewport);\n }\n };\n\n const handlePointerMove = (event: PointerEvent) => {\n const session = interactionSessionRef.current;\n if (session.type !== \"drag\") {\n return;\n }\n\n interactionSessionRef.current = {\n ...session,\n dragCurrent: getDragPositionFromClient({\n clientX: event.clientX,\n clientY: event.clientY,\n scrollOffset: getDocumentScrollOffset(),\n }),\n };\n postCurrentDragRect();\n };\n\n const handleViewportChangeDuringDrag = () => {\n const session = interactionSessionRef.current;\n if (session.type !== \"drag\" || dragAnimationFrameId !== null) {\n return;\n }\n\n dragAnimationFrameId = requestAnimationFrame(syncDragRectToViewport);\n };\n\n const commitElementSelection = ({\n targetElement,\n pointerEvent,\n }: {\n targetElement: Element;\n pointerEvent: PointerEvent;\n }) => {\n const selectionElement =\n getNearestSelectableElement(targetElement) ?? targetElement;\n const targetRect = selectionElement.getBoundingClientRect();\n const data = buildElementDescriptor({\n element: selectionElement,\n clickPosition: {\n x: pointerEvent.clientX,\n y: pointerEvent.clientY,\n },\n });\n interactionSessionRef.current = {\n type: \"element\",\n element: selectionElement,\n clickPosition: {\n x: pointerEvent.clientX - targetRect.left,\n y: pointerEvent.clientY - targetRect.top,\n },\n data,\n };\n\n // Paint the in-iframe selection frame synchronously for instant\n // feedback \u2014 symbolicate is a network roundtrip and we don't want\n // the visual selection to wait on it.\n const scrollOffset = getDocumentScrollOffset();\n showSelectionFrame({\n variant: \"element\",\n pageRect: {\n x: targetRect.left + scrollOffset.left,\n y: targetRect.top + scrollOffset.top,\n width: targetRect.width,\n height: targetRect.height,\n },\n });\n\n // Resolve compiled Turbopack chunk paths to the original `.tsx` paths\n // via Next.js's dev-only `/__nextjs_original-stack-frames` endpoint\n // before posting. Without this the parent receives a chunk URL and\n // the agent prompt points at bundled output instead of user source.\n void maybeSymbolicate(data).then((symbolicated) => {\n window.parent.postMessage(\n {\n type: \"replo:select:elementSelected\",\n data: symbolicated,\n },\n \"*\",\n );\n });\n };\n\n const handlePointerUp = (event: PointerEvent) => {\n const snapshot = interactionSessionRef.current;\n const wasDragging =\n snapshot.type === \"drag\" ? snapshot.hasExceededThreshold : false;\n const dragStart = snapshot.type === \"drag\" ? snapshot.dragStart : null;\n const dragCurrent =\n snapshot.type === \"drag\" ? snapshot.dragCurrent : null;\n const scrollOffset =\n snapshot.type === \"drag\"\n ? snapshot.scrollOffset\n : getDocumentScrollOffset();\n // `resetDragState` clears `dragCandidates`, so grab them first \u2014 the\n // final committed set is the same cached candidates the live preview\n // used, so preview and result never disagree.\n const candidates = dragCandidates;\n\n // Suppress the null drag-rect post: if this resolves to an area\n // selection it would otherwise flash the parent to `selection = none`\n // and wipe the frames we paint below. Click/empty-drag paths don't\n // depend on it (a sub-threshold drag never posted a rect to clear).\n resetDragState({ notifyParentDragCleared: false });\n\n if (!dragStart || snapshot.type !== \"drag\") {\n const targetElement = event.target;\n if (!(targetElement instanceof Element)) {\n return;\n }\n\n commitElementSelection({\n targetElement,\n pointerEvent: event,\n });\n return;\n }\n\n const resolvedDragCurrent = dragCurrent ?? dragStart;\n const selectionRect = getViewportSelectionRect({\n dragStart,\n dragCurrent: resolvedDragCurrent,\n scrollOffset,\n });\n\n if (!wasDragging) {\n const targetElement = event.target;\n if (!(targetElement instanceof Element)) {\n return;\n }\n\n commitElementSelection({\n targetElement,\n pointerEvent: event,\n });\n return;\n }\n\n const pageRect = getPageRectFromViewportRect({\n rect: selectionRect,\n scrollOffset,\n });\n\n const selectedCandidates = getCandidatesInSelection({\n candidates,\n selectionPageRect: pageRect,\n });\n const items = selectedCandidates.map((candidate) => {\n return buildElementDescriptor({\n element: candidate.element,\n clickPosition: getElementAnchor({\n element: candidate.element,\n selectionRect,\n }),\n });\n });\n\n interactionSessionRef.current = {\n type: \"area\",\n pageRect,\n items,\n };\n\n // Highlight each captured element so the committed area selection\n // \"sticks\" inside the iframe \u2014 matching how a single click stays\n // outlined \u2014 rather than drawing one faint box over the drag region.\n showSelectionFrames({\n frames: selectedCandidates.map((candidate) => ({\n variant: \"area\" as const,\n pageRect: {\n x: candidate.pageRect.x,\n y: candidate.pageRect.y,\n width: candidate.pageRect.width,\n height: candidate.pageRect.height,\n },\n })),\n });\n\n void Promise.all(items.map(maybeSymbolicate)).then(\n (symbolicatedItems) => {\n window.parent.postMessage(\n {\n type: \"replo:select:areaSelected\",\n rect: selectionRect,\n items: symbolicatedItems,\n },\n \"*\",\n );\n },\n );\n };\n\n const handleClick = (event: MouseEvent) => {\n event.preventDefault();\n event.stopPropagation();\n };\n\n const handlePointerCancel = () => {\n resetDragState();\n };\n\n const handleWindowBlur = () => {\n resetDragState();\n };\n\n document.addEventListener(\"pointerdown\", handlePointerDown, true);\n document.addEventListener(\"pointermove\", handlePointerMove, true);\n document.addEventListener(\"pointerup\", handlePointerUp, true);\n document.addEventListener(\"pointercancel\", handlePointerCancel, true);\n document.addEventListener(\"click\", handleClick, true);\n document.addEventListener(\"scroll\", handleViewportChangeDuringDrag, true);\n window.addEventListener(\"blur\", handleWindowBlur);\n window.addEventListener(\"resize\", handleViewportChangeDuringDrag);\n\n return () => {\n document.removeEventListener(\"pointerdown\", handlePointerDown, true);\n document.removeEventListener(\"pointermove\", handlePointerMove, true);\n document.removeEventListener(\"pointerup\", handlePointerUp, true);\n document.removeEventListener(\"pointercancel\", handlePointerCancel, true);\n document.removeEventListener(\"click\", handleClick, true);\n document.removeEventListener(\n \"scroll\",\n handleViewportChangeDuringDrag,\n true,\n );\n window.removeEventListener(\"blur\", handleWindowBlur);\n window.removeEventListener(\"resize\", handleViewportChangeDuringDrag);\n resetDragState();\n };\n }, [displayMode, interactionSessionRef]);\n}\n"],
5
+ "mappings": "AAKA,SAAS,iBAAiB;AAE1B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB,2BAA2B;AACxD,SAAS,oBAAoB;AAC7B,SAAS,kCAAkC;AAK3C,eAAe,iBAAiB,MAA+C;AAC7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AoB,eAAe,mBAAmB,IAAI;AACnE,eAAS,oBAAoB,eAAe,mBAAmB,IAAI;AACnE,eAAS,oBAAoB,aAAa,iBAAiB,IAAI;AAC/D,eAAS,oBAAoB,iBAAiB,qBAAqB,IAAI;AACvE,eAAS,oBAAoB,SAAS,aAAa,IAAI;AACvD,eAAS;AAAA,QACP;AAAA,QACA;AAAA,QACA;AAAA,MACF;AACA,aAAO,oBAAoB,QAAQ,gBAAgB;AACnD,aAAO,oBAAoB,UAAU,8BAA8B;AACnE,qBAAe;AAAA,IACjB;AAAA,EACF,GAAG,CAAC,aAAa,qBAAqB,CAAC;AACzC;",
6
6
  "names": []
7
7
  }
@@ -47,20 +47,45 @@ export declare function getViewportRectFromPageRect({ rect, scrollOffset, }: {
47
47
  scrollOffset: ScrollOffset;
48
48
  }): SelectModeBoundingRect;
49
49
  /**
50
- * Returns the visible elements whose bounding rect is fully contained
51
- * (within `SELECTION_TOLERANCE_PX`) by the user-drawn
52
- * `selectionRect`.
53
- *
54
- * After containment filtering we de-duplicate ancestor wrappers that
55
- * share the same bounds as one of their descendants — without this we'd
56
- * emit both `<div>` and its only child `<button>` for a selection that
57
- * visually contains a single button. We keep the descendant (the more
58
- * specific element) by dropping any ancestor that has a same-bounds
59
- * descendant in `candidates`.
50
+ * A drag captures an element when their boxes overlap (within
51
+ * `tolerancePx`) — but NOT when the drag sits entirely inside the
52
+ * element. The latter case is the user dragging *within* a large
53
+ * container (a section, `<main>`, `<body>`) to lasso its children; the
54
+ * container itself isn't a thing they're trying to select, so we drop it.
55
+ */
56
+ export declare function doesRectIntersectSelection({ elementRect, selectionRect, tolerancePx, }: {
57
+ elementRect: SelectModeBoundingRect;
58
+ selectionRect: SelectModeBoundingRect;
59
+ tolerancePx: number;
60
+ }): boolean;
61
+ export type DragCandidate = {
62
+ id: string;
63
+ element: Element;
64
+ pageRect: SelectModeBoundingRect;
65
+ };
66
+ /**
67
+ * Snapshots every meaningful element and its page rect when a drag begins.
68
+ * Each candidate gets a stable id so the parent overlay can key its
69
+ * live highlights without remounting them as the drag moves.
70
+ */
71
+ export declare function collectDragCandidates(scrollOffset: ScrollOffset): DragCandidate[];
72
+ /**
73
+ * Cheap per-move hit-test against the pre-collected candidates: keep the
74
+ * ones whose page rect overlaps the selection (excluding any that wholly
75
+ * enclose it), then collapse any fully-covered parent/children group down
76
+ * to just the parent (see `collapseFullyCoveredChildren`). Does no DOM
77
+ * queries or re-measures of geometry — the only DOM reads are cheap
78
+ * parent/child structural lookups.
60
79
  *
61
- * @author Kevin O'Connell 2026-04-17
80
+ * Because the collapse depends on which siblings are currently captured,
81
+ * elements legitimately move in and out of the result as the drag grows or
82
+ * shrinks: a child drops out the moment the drag swallows its last sibling
83
+ * (the parent takes over), and reappears if the drag retreats.
62
84
  */
63
- export declare function getElementsInRect(selectionRect: SelectModeBoundingRect): Element[];
85
+ export declare function getCandidatesInSelection({ candidates, selectionPageRect, }: {
86
+ candidates: DragCandidate[];
87
+ selectionPageRect: SelectModeBoundingRect;
88
+ }): DragCandidate[];
64
89
  /**
65
90
  * Picks a "click position" for an element that fell inside an area
66
91
  * selection. We use the corner of the element nearest the top-left of the
@@ -1,3 +1,5 @@
1
+ import { isIntersecting, isRectEnclosing } from "../../../_vendor/replo-utils/lib/geometry.mjs";
2
+ import { v4 as uuidv4 } from "uuid";
1
3
  const SELECTION_TOLERANCE_PX = 4;
2
4
  function normalizeSelectionRect({
3
5
  startX,
@@ -81,48 +83,72 @@ function getViewportRectFromPageRect({
81
83
  bottom: rect.bottom - scrollOffset.top
82
84
  };
83
85
  }
84
- function isMeaningfulElement(element) {
86
+ function isMeaningfulElement(element, elementRect) {
85
87
  const tagName = element.tagName.toLowerCase();
86
88
  if (["html", "body", "script", "style", "meta", "link"].includes(tagName)) {
87
89
  return false;
88
90
  }
89
- const elementRect = element.getBoundingClientRect();
90
91
  if (elementRect.width < 4 || elementRect.height < 4) {
91
92
  return false;
92
93
  }
93
94
  return true;
94
95
  }
95
- function isRectContainedWithinSelection({
96
+ function doesRectIntersectSelection({
96
97
  elementRect,
97
98
  selectionRect,
98
99
  tolerancePx
99
100
  }) {
100
- return elementRect.left >= selectionRect.left - tolerancePx && elementRect.right <= selectionRect.right + tolerancePx && elementRect.top >= selectionRect.top - tolerancePx && elementRect.bottom <= selectionRect.bottom + tolerancePx;
101
+ return isIntersecting(elementRect, selectionRect, { tolerance: tolerancePx }) && !isRectEnclosing(elementRect, selectionRect);
101
102
  }
102
- function getElementsInRect(selectionRect) {
103
- const candidates = Array.from(document.querySelectorAll("*")).filter(isMeaningfulElement).map((element) => {
104
- return {
103
+ function collectDragCandidates(scrollOffset) {
104
+ const candidates = [];
105
+ for (const element of Array.from(document.querySelectorAll("*"))) {
106
+ const viewportRect = getElementBoundingRect(element);
107
+ if (!isMeaningfulElement(element, viewportRect)) {
108
+ continue;
109
+ }
110
+ candidates.push({
111
+ id: uuidv4(),
105
112
  element,
106
- elementRect: element.getBoundingClientRect()
107
- };
108
- }).filter(({ elementRect }) => {
109
- return isRectContainedWithinSelection({
110
- elementRect,
111
- selectionRect,
112
- tolerancePx: SELECTION_TOLERANCE_PX
113
+ pageRect: getPageRectFromViewportRect({
114
+ rect: viewportRect,
115
+ scrollOffset
116
+ })
113
117
  });
118
+ }
119
+ return candidates;
120
+ }
121
+ function collapseFullyCoveredChildren({
122
+ candidates,
123
+ selected
124
+ }) {
125
+ const candidateElements = new Set(
126
+ candidates.map((candidate) => candidate.element)
127
+ );
128
+ const selectedElements = new Set(
129
+ selected.map((candidate) => candidate.element)
130
+ );
131
+ return selected.filter((candidate) => {
132
+ const parent = candidate.element.parentElement;
133
+ if (!parent || !selectedElements.has(parent)) {
134
+ return true;
135
+ }
136
+ const everyCandidateChildSelected = Array.from(parent.children).filter((child) => candidateElements.has(child)).every((child) => selectedElements.has(child));
137
+ return !everyCandidateChildSelected;
114
138
  });
115
- return candidates.filter(({ element, elementRect }, index, allCandidates) => {
116
- return !allCandidates.some((otherCandidate, otherIndex) => {
117
- if (index === otherIndex) {
118
- return false;
119
- }
120
- const sameBounds = Math.abs(otherCandidate.elementRect.left - elementRect.left) < 1 && Math.abs(otherCandidate.elementRect.top - elementRect.top) < 1 && Math.abs(otherCandidate.elementRect.width - elementRect.width) < 1 && Math.abs(otherCandidate.elementRect.height - elementRect.height) < 1;
121
- return sameBounds && element.contains(otherCandidate.element) && element !== otherCandidate.element;
139
+ }
140
+ function getCandidatesInSelection({
141
+ candidates,
142
+ selectionPageRect
143
+ }) {
144
+ const intersecting = candidates.filter((candidate) => {
145
+ return doesRectIntersectSelection({
146
+ elementRect: candidate.pageRect,
147
+ selectionRect: selectionPageRect,
148
+ tolerancePx: SELECTION_TOLERANCE_PX
122
149
  });
123
- }).map(({ element }) => {
124
- return element;
125
150
  });
151
+ return collapseFullyCoveredChildren({ candidates, selected: intersecting });
126
152
  }
127
153
  function getElementAnchor({
128
154
  element,
@@ -148,11 +174,13 @@ function getElementBoundingRect(element) {
148
174
  };
149
175
  }
150
176
  export {
177
+ collectDragCandidates,
178
+ doesRectIntersectSelection,
179
+ getCandidatesInSelection,
151
180
  getDocumentScrollOffset,
152
181
  getDragPositionFromClient,
153
182
  getElementAnchor,
154
183
  getElementBoundingRect,
155
- getElementsInRect,
156
184
  getPageRectFromViewportRect,
157
185
  getViewportRectFromPageRect,
158
186
  getViewportSelectionRect