@aglyn/besigner-ui 1.0.0-beta.283 → 1.0.0-beta.284

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/besigner-ui",
3
- "version": "1.0.0-beta.283",
3
+ "version": "1.0.0-beta.284",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,22 +25,22 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.0.0-beta.283",
29
- "@aglyn/aglyn-markdown-editor": "1.0.0-beta.283",
30
- "@aglyn/aglyn-node-renderer": "1.0.0-beta.283",
31
- "@aglyn/besigner": "1.0.0-beta.283",
32
- "@aglyn/shared-data-enums": "1.0.0-beta.283",
33
- "@aglyn/shared-data-mdi": "1.0.0-beta.283",
34
- "@aglyn/shared-data-types": "1.0.0-beta.283",
35
- "@aglyn/shared-svg-icons": "1.0.0-beta.283",
36
- "@aglyn/shared-ui-json-editor": "1.0.0-beta.283",
37
- "@aglyn/shared-ui-jsx": "1.0.0-beta.283",
38
- "@aglyn/shared-ui-jsx-forms": "1.0.0-beta.283",
39
- "@aglyn/shared-ui-snackstack": "1.0.0-beta.283",
40
- "@aglyn/shared-ui-theme": "1.0.0-beta.283",
41
- "@aglyn/shared-util-dom": "1.0.0-beta.283",
42
- "@aglyn/shared-util-tools": "1.0.0-beta.283",
43
- "@aglyn/shared-util-vendor": "1.0.0-beta.283",
28
+ "@aglyn/aglyn": "1.0.0-beta.284",
29
+ "@aglyn/aglyn-markdown-editor": "1.0.0-beta.284",
30
+ "@aglyn/aglyn-node-renderer": "1.0.0-beta.284",
31
+ "@aglyn/besigner": "1.0.0-beta.284",
32
+ "@aglyn/shared-data-enums": "1.0.0-beta.284",
33
+ "@aglyn/shared-data-mdi": "1.0.0-beta.284",
34
+ "@aglyn/shared-data-types": "1.0.0-beta.284",
35
+ "@aglyn/shared-svg-icons": "1.0.0-beta.284",
36
+ "@aglyn/shared-ui-json-editor": "1.0.0-beta.284",
37
+ "@aglyn/shared-ui-jsx": "1.0.0-beta.284",
38
+ "@aglyn/shared-ui-jsx-forms": "1.0.0-beta.284",
39
+ "@aglyn/shared-ui-snackstack": "1.0.0-beta.284",
40
+ "@aglyn/shared-ui-theme": "1.0.0-beta.284",
41
+ "@aglyn/shared-util-dom": "1.0.0-beta.284",
42
+ "@aglyn/shared-util-tools": "1.0.0-beta.284",
43
+ "@aglyn/shared-util-vendor": "1.0.0-beta.284",
44
44
  "@dnd-kit/core": "^6.3.1",
45
45
  "@dnd-kit/utilities": "^3.2.2",
46
46
  "@react-aria/utils": "^3.34.1",
@@ -22,7 +22,7 @@ import { Box, Button, IconButton, Paper, useTheme } from "@mui/material";
22
22
  import isEqual from "lodash-es/isEqual.js";
23
23
  import { toJS } from "mobx";
24
24
  import { observer } from "mobx-react-lite";
25
- import { useCallback, useEffect, useRef, useState } from "react";
25
+ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
26
26
  import { clampToViewport, useAnchoredRect } from "../hooks/use-anchored-rect.js";
27
27
  import useInsertTokenOptions from "../hooks/use-insert-token-options.js";
28
28
  import { addCaretStops, beginInPlaceEdit, selectionOf, withoutCaretStops } from "../utils/in-place-edit-surface.js";
@@ -30,6 +30,7 @@ import { inlineTextEdit } from "../utils/inline-text-edit.store.js";
30
30
  import { RICH_COMMANDS, richTextCommandGroups } from "../utils/rich-text-commands.js";
31
31
  import { richTextToPlain, sanitizeRichText, textToHtml } from "../utils/sanitize-rich-text.js";
32
32
  import { createTokenPillElement, materializeTokenPillsInElement, readTokenSegmentsFromDom, replacePillsWithTokenText, TOKEN_PILL_ATTR } from "../utils/token-editable-dom.js";
33
+ import { isNearSelectionHandle, isTouchPointer, placeDockedToolbar, prefersTouchEditing, readVisibleArea, selectionEndBoxes, TouchPressTracker } from "../utils/touch-text-edit.js";
33
34
  import { parseTokenSegments, resolveTokenLabel, serializeTokenSegments } from "../utils/token-segments.js";
34
35
  import { InsertTokenMenu } from "./insert-token-menu.component.js";
35
36
  import { paintTokenPills, TokenPillPopover, tokenPillContainerSx } from "./token-pill.component.js";
@@ -166,6 +167,23 @@ import { paintTokenPills, TokenPillPopover, tokenPillContainerSx } from "./token
166
167
  const savedRangeRef = useRef(null);
167
168
  const [insertMenu, setInsertMenu] = useState(null);
168
169
  const [pillMenu, setPillMenu] = useState(null);
170
+ /**
171
+ * Whether the edit is being made with a finger (AGL-4069).
172
+ *
173
+ * Decided by the input itself, not by the screen size: the latest press
174
+ * anywhere on the page says which kind of pointer is in use, and a device
175
+ * whose main pointer is coarse starts out as touch before any press has
176
+ * been seen. A touch edit keeps its toolbar in the visible area, above
177
+ * the keyboard, and ends only on a real tap — see `touch-text-edit.ts`.
178
+ * A mouse keeps the behaviour it always had.
179
+ */ const lastPressWasTouchRef = useRef(undefined);
180
+ const [touchMode, setTouchMode] = useState(false);
181
+ const touchModeRef = useRef(touchMode);
182
+ touchModeRef.current = touchMode;
183
+ /** The part of the page the author can see, while a touch edit is open. */ const [visibleArea, setVisibleArea] = useState(undefined);
184
+ const toolbarRef = useRef(null);
185
+ const [toolbarHeight, setToolbarHeight] = useState(0);
186
+ /** The selection as a toolbar press found it, to act on if a tap loses it. */ const toolbarRangeRef = useRef(null);
169
187
  // Same context walk as the attributes panel (AGL-583) — the edited
170
188
  // node is known, so dataset-item / entry groups resolve identically.
171
189
  const { options: insertOptions, labelContext } = useInsertTokenOptions(node);
@@ -200,6 +218,77 @@ import { paintTokenPills, TokenPillPopover, tokenPillContainerSx } from "./token
200
218
  }, [
201
219
  rich
202
220
  ]);
221
+ // Which kind of pointer pressed last, read wherever on the page it pressed:
222
+ // a press inside the closed canvas still reaches the document, retargeted.
223
+ useEffect(()=>{
224
+ const notePress = (event)=>{
225
+ const touch = isTouchPointer(event);
226
+ lastPressWasTouchRef.current = touch;
227
+ if (inlineTextEdit.node && touch !== touchModeRef.current) {
228
+ setTouchMode(touch);
229
+ }
230
+ };
231
+ document.addEventListener('pointerdown', notePress, true);
232
+ return ()=>document.removeEventListener('pointerdown', notePress, true);
233
+ }, []);
234
+ // Settled once per edit, from the press that opened it.
235
+ useEffect(()=>{
236
+ var _lastPressWasTouchRef_current;
237
+ if (!node) return;
238
+ setTouchMode((_lastPressWasTouchRef_current = lastPressWasTouchRef.current) != null ? _lastPressWasTouchRef_current : prefersTouchEditing(typeof window === 'undefined' ? undefined : window));
239
+ }, [
240
+ node
241
+ ]);
242
+ /**
243
+ * Follows the visible area while a touch edit is open (AGL-4069). The
244
+ * keyboard opening, iOS panning the page to keep the caret in view, and a
245
+ * pinch all move the VISUAL viewport, which fires neither a window scroll
246
+ * nor a window resize.
247
+ */ useEffect(()=>{
248
+ if (!node || !touchMode || typeof window === 'undefined') {
249
+ setVisibleArea(undefined);
250
+ return;
251
+ }
252
+ const update = ()=>setVisibleArea(readVisibleArea(window));
253
+ update();
254
+ const visual = window.visualViewport;
255
+ visual == null ? void 0 : visual.addEventListener('resize', update, {
256
+ passive: true
257
+ });
258
+ visual == null ? void 0 : visual.addEventListener('scroll', update, {
259
+ passive: true
260
+ });
261
+ window.addEventListener('resize', update, {
262
+ passive: true
263
+ });
264
+ window.addEventListener('scroll', update, {
265
+ passive: true,
266
+ capture: true
267
+ });
268
+ return ()=>{
269
+ visual == null ? void 0 : visual.removeEventListener('resize', update);
270
+ visual == null ? void 0 : visual.removeEventListener('scroll', update);
271
+ window.removeEventListener('resize', update);
272
+ window.removeEventListener('scroll', update, {
273
+ capture: true
274
+ });
275
+ };
276
+ }, [
277
+ node,
278
+ touchMode
279
+ ]);
280
+ // The docked toolbar's own height decides where its bottom edge goes.
281
+ useLayoutEffect(()=>{
282
+ var _ref;
283
+ var _toolbarRef_current;
284
+ const height = (_ref = (_toolbarRef_current = toolbarRef.current) == null ? void 0 : _toolbarRef_current.offsetHeight) != null ? _ref : 0;
285
+ if (height !== toolbarHeight) setToolbarHeight(height);
286
+ }, [
287
+ node,
288
+ touchMode,
289
+ visibleArea,
290
+ toolbarHeight
291
+ ]);
203
292
  /**
204
293
  * Opens the edit: builds the content once, and puts it in the canvas
205
294
  * leaf itself wherever that is possible (AGL-2486).
@@ -426,16 +515,45 @@ import { paintTokenPills, TokenPillPopover, tokenPillContainerSx } from "./token
426
515
  committedRef.current = true;
427
516
  inlineTextEdit.close();
428
517
  }, []);
429
- const handleEditableBlur = useCallback(()=>{
518
+ /**
519
+ * A mouse edit commits when the text loses focus. A touch edit does not
520
+ * (AGL-4069): on a phone focus comes and goes for reasons that are not
521
+ * the author leaving — the keyboard's own bar, its Done key, the edit
522
+ * menu — and the edit there ends on a real tap away, Escape or Done.
523
+ */ const handleEditableBlur = useCallback(()=>{
430
524
  if (menuOpenRef.current) return;
525
+ if (touchModeRef.current) return;
431
526
  commit();
432
527
  }, [
433
528
  commit
434
529
  ]);
530
+ /**
531
+ * Ends a touch edit and lets go of the text (AGL-4069). On a phone the
532
+ * keyboard and the edit menu stay up for as long as the text holds focus
533
+ * and a selection, and the element given back is no longer editable — so
534
+ * both would be left hanging over a page the author has finished with.
535
+ */ const commitAndRelease = useCallback(()=>{
536
+ const editable = activeEditable();
537
+ commit();
538
+ if (!editable) return;
539
+ const selection = selectionOf(editable);
540
+ if (selection && selection.rangeCount > 0 && editable.contains(selection.getRangeAt(0).commonAncestorContainer)) {
541
+ selection.removeAllRanges();
542
+ }
543
+ const focused = editable.ownerDocument.activeElement;
544
+ if (focused instanceof HTMLElement && editable.contains(focused)) {
545
+ focused.blur();
546
+ }
547
+ }, [
548
+ activeEditable,
549
+ commit
550
+ ]);
435
551
  // Latest `commit` for the document listener below, which must not
436
552
  // re-register on every render just to stay current.
437
553
  const commitRef = useRef(commit);
438
554
  commitRef.current = commit;
555
+ const commitAndReleaseRef = useRef(commitAndRelease);
556
+ commitAndReleaseRef.current = commitAndRelease;
439
557
  /**
440
558
  * Wires the editing handlers onto the LEAF while it is the surface.
441
559
  *
@@ -506,6 +624,21 @@ import { paintTokenPills, TokenPillPopover, tokenPillContainerSx } from "./token
506
624
  * they are. The portalled insert picker and pill popover ARE outside the
507
625
  * overlay in the DOM, and are covered by the same `menuOpenRef` stand-down
508
626
  * that already guards commit-on-blur (AGL-586).
627
+ *
628
+ * A FINGER is judged when it lifts, not when it lands (AGL-4069). The
629
+ * selection handles iOS hangs off the ends of selected text sit over the
630
+ * elements next to it, so the touch that grabs one to select more words
631
+ * lands outside the text — and ending the edit there closed the keyboard
632
+ * under an author who was only extending a selection. On touch the press
633
+ * is followed to its end: a still, quick tap ends the edit (or, on the
634
+ * element being edited, places the caret), while a drag, a hold, a press
635
+ * within reach of a selection handle, or a touch the browser takes over
636
+ * for a scroll or a handle drag (`pointercancel`) leaves it open. Inside
637
+ * the canvas the press is also kept from the elements under it until
638
+ * then: a leaf would select itself on the spot, which is not a tap's
639
+ * business until it is known to be one. The tap's own mouse events,
640
+ * which a phone sends after the finger lifts, still select what was
641
+ * tapped — after the edit has ended, as a click does.
509
642
  */ useEffect(()=>{
510
643
  var _inPlaceRef_current;
511
644
  if (!node) return;
@@ -524,6 +657,8 @@ import { paintTokenPills, TokenPillPopover, tokenPillContainerSx } from "./token
524
657
  const overlay = overlayRef.current;
525
658
  return Boolean(overlay == null ? void 0 : overlay.contains(target));
526
659
  };
660
+ /** The touch being followed, and what a tap would mean for it. */ const press = new TouchPressTracker();
661
+ let pressOnEditedLeaf = false;
527
662
  const handlePointerDownAway = (event)=>{
528
663
  var _inPlaceRef_current;
529
664
  if (menuOpenRef.current) return;
@@ -542,14 +677,44 @@ import { paintTokenPills, TokenPillPopover, tokenPillContainerSx } from "./token
542
677
  // it used to read as a click away and close the edit.
543
678
  const live = (_inPlaceRef_current = inPlaceRef.current) == null ? void 0 : _inPlaceRef_current.element;
544
679
  const leaf = live == null ? void 0 : live.closest(LEAF_STAMP_SELECTOR);
545
- if (live && leaf && target instanceof Element && target.closest(LEAF_STAMP_SELECTOR) === leaf) {
680
+ const onEditedLeaf = Boolean(live && leaf && target instanceof Element && target.closest(LEAF_STAMP_SELECTOR) === leaf);
681
+ if (isTouchPointer(event)) {
682
+ const pointer = event;
683
+ const nearHandle = Boolean(live && isNearSelectionHandle({
684
+ x: pointer.clientX,
685
+ y: pointer.clientY
686
+ }, selectionEndBoxes(selectionOf(live))));
687
+ press.down(pointer, nearHandle);
688
+ pressOnEditedLeaf = onEditedLeaf;
689
+ // Inside the canvas only: chrome outside it keeps its own presses.
690
+ if (root && root !== document && event.currentTarget === root) {
691
+ event.stopPropagation();
692
+ }
693
+ return;
694
+ }
695
+ if (onEditedLeaf && live) {
546
696
  event.preventDefault();
547
697
  placeCaretAtNearEnd(live, event);
548
698
  return;
549
699
  }
550
700
  commitRef.current();
551
701
  };
702
+ const handlePointerMove = (event)=>press.move(event);
703
+ const handlePointerCancel = (event)=>press.cancel(event);
704
+ const handlePointerUp = (event)=>{
705
+ var _inPlaceRef_current;
706
+ if (press.up(event) !== 'tap') return;
707
+ const live = (_inPlaceRef_current = inPlaceRef.current) == null ? void 0 : _inPlaceRef_current.element;
708
+ if (pressOnEditedLeaf && live) {
709
+ placeCaretAtNearEnd(live, event);
710
+ return;
711
+ }
712
+ commitAndReleaseRef.current();
713
+ };
552
714
  document.addEventListener('pointerdown', handlePointerDownAway, true);
715
+ document.addEventListener('pointermove', handlePointerMove, true);
716
+ document.addEventListener('pointerup', handlePointerUp, true);
717
+ document.addEventListener('pointercancel', handlePointerCancel, true);
553
718
  // Second listener, INSIDE the shadow root, for the clicks the first one
554
719
  // is blind to — including a click on the very element being edited,
555
720
  // which must move the caret rather than end the edit.
@@ -558,6 +723,9 @@ import { paintTokenPills, TokenPillPopover, tokenPillContainerSx } from "./token
558
723
  }
559
724
  return ()=>{
560
725
  document.removeEventListener('pointerdown', handlePointerDownAway, true);
726
+ document.removeEventListener('pointermove', handlePointerMove, true);
727
+ document.removeEventListener('pointerup', handlePointerUp, true);
728
+ document.removeEventListener('pointercancel', handlePointerCancel, true);
561
729
  if (root && root !== document) {
562
730
  root.removeEventListener('pointerdown', handlePointerDownAway, true);
563
731
  }
@@ -641,22 +809,64 @@ import { paintTokenPills, TokenPillPopover, tokenPillContainerSx } from "./token
641
809
  const keepFocus = useCallback((event)=>{
642
810
  event.preventDefault();
643
811
  }, []);
812
+ /**
813
+ * Notes the selection a toolbar press starts from. A tap on a phone can
814
+ * move focus, and the selection with it, before the button's click runs;
815
+ * the command must still apply to the words that were selected.
816
+ */ const noteToolbarSelection = useCallback(()=>{
817
+ const editable = activeEditable();
818
+ const selection = editable ? selectionOf(editable) : null;
819
+ const range = selection && selection.rangeCount > 0 ? selection.getRangeAt(0) : null;
820
+ toolbarRangeRef.current = range && editable && editable.contains(range.startContainer) && editable.contains(range.endContainer) ? range.cloneRange() : null;
821
+ }, [
822
+ activeEditable
823
+ ]);
824
+ /** Puts the noted selection back if the press lost it. */ const restoreToolbarSelection = useCallback(()=>{
825
+ const editable = activeEditable();
826
+ const saved = toolbarRangeRef.current;
827
+ toolbarRangeRef.current = null;
828
+ if (!editable || !saved) return;
829
+ const selection = selectionOf(editable);
830
+ const current = selection && selection.rangeCount > 0 ? selection.getRangeAt(0) : null;
831
+ if (current && editable.contains(current.commonAncestorContainer)) return;
832
+ editable.focus();
833
+ const again = selectionOf(editable);
834
+ if (!again) return;
835
+ again.removeAllRanges();
836
+ again.addRange(saved);
837
+ }, [
838
+ activeEditable
839
+ ]);
644
840
  const exec = useCallback((command)=>()=>{
645
841
  var _activeEditable;
842
+ restoreToolbarSelection();
646
843
  // ExecCommand is deprecated but universally supported and keeps this
647
844
  // dependency-free; the output is normalized by the sanitizer anyway.
648
845
  document.execCommand(command);
649
846
  (_activeEditable = activeEditable()) == null ? void 0 : _activeEditable.focus();
650
847
  }, [
651
- activeEditable
848
+ activeEditable,
849
+ restoreToolbarSelection
652
850
  ]);
653
851
  const handleLink = useCallback(()=>{
654
852
  var _activeEditable;
853
+ restoreToolbarSelection();
854
+ const saved = (()=>{
855
+ const editable = activeEditable();
856
+ const selection = editable ? selectionOf(editable) : null;
857
+ return selection && selection.rangeCount > 0 ? selection.getRangeAt(0).cloneRange() : null;
858
+ })();
655
859
  const url = window.prompt('Link URL (https://…)');
656
- if (url) document.execCommand('createLink', false, url);
860
+ // The prompt takes focus; the link goes on the words it was asked for.
861
+ if (url) {
862
+ toolbarRangeRef.current = saved;
863
+ restoreToolbarSelection();
864
+ document.execCommand('createLink', false, url);
865
+ }
657
866
  (_activeEditable = activeEditable()) == null ? void 0 : _activeEditable.focus();
658
867
  }, [
659
- activeEditable
868
+ activeEditable,
869
+ restoreToolbarSelection
660
870
  ]);
661
871
  /** Pill clicks (delegated): offer Replace/Remove (AGL-586). */ const handleEditableClick = useCallback((event)=>{
662
872
  const pill = event.target.closest == null ? void 0 : event.target.closest.call(event.target, `[${TOKEN_PILL_ATTR}]`);
@@ -757,6 +967,8 @@ import { paintTokenPills, TokenPillPopover, tokenPillContainerSx } from "./token
757
967
  pillMenu,
758
968
  closeMenus
759
969
  ]);
970
+ // Fingers get the larger target.
971
+ const toolSize = (t)=>t.spacing(touchMode ? 5 : 3.5);
760
972
  const insertButton = /*#__PURE__*/ _jsx(IconButton, {
761
973
  size: "small",
762
974
  title: "Insert data",
@@ -764,8 +976,8 @@ import { paintTokenPills, TokenPillPopover, tokenPillContainerSx } from "./token
764
976
  onMouseDown: keepFocus,
765
977
  onClick: handleInsertOpen,
766
978
  sx: {
767
- width: 28,
768
- height: 28,
979
+ width: toolSize,
980
+ height: toolSize,
769
981
  borderRadius: 0.5
770
982
  },
771
983
  children: /*#__PURE__*/ _jsx(MdiIcon, {
@@ -815,6 +1027,21 @@ import { paintTokenPills, TokenPillPopover, tokenPillContainerSx } from "./token
815
1027
  const minWidth = Math.max(live.width, 120);
816
1028
  const TOOLBAR_CLEARANCE = 48;
817
1029
  const KEEP_VISIBLE = 80;
1030
+ // A finger's toolbar docks to the visible area, clear of the keyboard and
1031
+ // of the edit menu iOS puts by the selection (AGL-4069); a mouse's hangs
1032
+ // just above the text, as it always has.
1033
+ const docked = touchMode && visibleArea ? placeDockedToolbar(live, visibleArea, toolbarHeight, parseFloat(theme.spacing(1)) || 0) : undefined;
1034
+ const toolbarSx = docked ? {
1035
+ position: 'fixed',
1036
+ top: docked.top,
1037
+ left: docked.left,
1038
+ maxWidth: docked.maxWidth,
1039
+ overflowX: 'auto'
1040
+ } : {
1041
+ position: 'absolute',
1042
+ top: -40,
1043
+ left: 0
1044
+ };
818
1045
  return /*#__PURE__*/ _jsxs(Box, {
819
1046
  ref: overlayRef,
820
1047
  "data-aglyn": "overlay:inline-text-editor",
@@ -828,17 +1055,18 @@ import { paintTokenPills, TokenPillPopover, tokenPillContainerSx } from "./token
828
1055
  },
829
1056
  children: [
830
1057
  /*#__PURE__*/ _jsxs(Paper, {
1058
+ ref: toolbarRef,
831
1059
  elevation: 4,
832
- sx: {
833
- position: 'absolute',
834
- top: -40,
835
- left: 0,
1060
+ "data-aglyn": "overlay:inline-text-toolbar",
1061
+ "data-docked": docked == null ? void 0 : docked.edge,
1062
+ onPointerDownCapture: noteToolbarSelection,
1063
+ sx: _extends({}, toolbarSx, {
836
1064
  px: 0.5,
837
1065
  py: 0.25,
838
1066
  display: 'flex',
839
1067
  gap: 0.25,
840
1068
  alignItems: 'center'
841
- },
1069
+ }),
842
1070
  children: [
843
1071
  rich ? RICH_COMMANDS.filter(({ group })=>commandGroups.has(group)).map(({ command, label, title })=>/*#__PURE__*/ _jsx(IconButton, {
844
1072
  size: "small",
@@ -846,8 +1074,8 @@ import { paintTokenPills, TokenPillPopover, tokenPillContainerSx } from "./token
846
1074
  onMouseDown: keepFocus,
847
1075
  onClick: exec(command),
848
1076
  sx: {
849
- width: 28,
850
- height: 28,
1077
+ width: toolSize,
1078
+ height: toolSize,
851
1079
  fontSize: 13,
852
1080
  fontWeight: 700,
853
1081
  fontStyle: command === 'italic' ? 'italic' : undefined,
@@ -862,8 +1090,8 @@ import { paintTokenPills, TokenPillPopover, tokenPillContainerSx } from "./token
862
1090
  onMouseDown: keepFocus,
863
1091
  onClick: handleLink,
864
1092
  sx: {
865
- width: 28,
866
- height: 28,
1093
+ width: toolSize,
1094
+ height: toolSize,
867
1095
  fontSize: 13,
868
1096
  borderRadius: 0.5
869
1097
  },
@@ -874,7 +1102,7 @@ import { paintTokenPills, TokenPillPopover, tokenPillContainerSx } from "./token
874
1102
  size: "small",
875
1103
  color: "primary",
876
1104
  onMouseDown: keepFocus,
877
- onClick: commit,
1105
+ onClick: touchMode ? commitAndRelease : commit,
878
1106
  children: 'Done'
879
1107
  })
880
1108
  ]
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/besigner/feature/designer/src/lib/components/inline-text-editor.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type * as Aglyn from '@aglyn/aglyn'\nimport {\n canvas,\n FEATURE_FLAG,\n REUSABLE_INSTANCE_PROP_HTML_KEY,\n REUSABLE_INSTANCE_PROP_VALUES_KEY,\n RICH_TEXT_COMMANDS,\n} from '@aglyn/aglyn'\nimport { mdiCodeBraces } from '@aglyn/shared-data-mdi'\nimport { MdiIcon } from '@aglyn/shared-ui-jsx'\nimport { Box, Button, IconButton, Paper, useTheme } from '@mui/material'\nimport type { Theme } from '@mui/material/styles'\nimport type { SystemStyleObject } from '@mui/system'\nimport isEqual from 'lodash-es/isEqual.js'\nimport { toJS } from 'mobx'\nimport { observer } from 'mobx-react-lite'\nimport {\n type KeyboardEvent,\n type MouseEvent,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from 'react'\nimport { clampToViewport, useAnchoredRect } from '../hooks/use-anchored-rect'\nimport useInsertTokenOptions from '../hooks/use-insert-token-options'\nimport {\n addCaretStops,\n beginInPlaceEdit,\n type InPlaceEditSurface,\n selectionOf,\n withoutCaretStops,\n} from '../utils/in-place-edit-surface'\nimport { inlineTextEdit } from '../utils/inline-text-edit.store'\nimport {\n RICH_COMMANDS,\n richTextCommandGroups,\n} from '../utils/rich-text-commands'\nimport {\n richTextToPlain,\n sanitizeRichText,\n textToHtml,\n} from '../utils/sanitize-rich-text'\nimport {\n createTokenPillElement,\n materializeTokenPillsInElement,\n readTokenSegmentsFromDom,\n replacePillsWithTokenText,\n TOKEN_PILL_ATTR,\n} from '../utils/token-editable-dom'\nimport {\n parseTokenSegments,\n resolveTokenLabel,\n serializeTokenSegments,\n} from '../utils/token-segments'\nimport { InsertTokenMenu } from './insert-token-menu.component'\nimport {\n paintTokenPills,\n TokenPillPopover,\n tokenPillContainerSx,\n} from './token-pill.component'\n\n/** The stamp `Leaf` puts on every element it renders. */\nconst LEAF_STAMP_SELECTOR = '[data-aglyn^=\"leaf:\"]'\n\n/**\n * Puts the caret at whichever end of `editable` is nearer a press beside it:\n * the start for a press before its first line, the end otherwise.\n */\nfunction placeCaretAtNearEnd(\n editable: HTMLElement,\n press: { clientX: number; clientY: number },\n): void {\n const lines = Array.from(editable.getClientRects())\n const first = lines[0]\n const atStart = Boolean(\n first &&\n (press.clientY < first.top ||\n (press.clientY <= first.bottom && press.clientX < first.left)),\n )\n editable.focus()\n const selection = selectionOf(editable)\n if (!selection) return\n const range = editable.ownerDocument.createRange()\n range.selectNodeContents(editable)\n range.collapse(atStart)\n selection.removeAllRanges()\n selection.addRange(range)\n}\n\n/** Stands in while no edit is open, so the anchor hook can run every render. */\nconst EMPTY_RECT = { left: 0, top: 0, width: 0, height: 0 }\n\n/**\n * The fallback editor, for an edit with no element to type into — opened\n * with no anchor, or on an anchor already detached from the document.\n *\n * Deliberately OPAQUE. It floats over content that cannot re-flow with it,\n * and a see-through surface in that position is what drew two texts over\n * each other; covering what it stands on is honest, blending with it is not.\n * Everything else edits the canvas leaf itself and needs no surface here.\n */\nconst BOXED_SURFACE_SX = {\n p: 0.5,\n bgcolor: 'background.paper',\n color: 'text.primary',\n border: '2px solid',\n borderColor: 'tertiary.main',\n borderRadius: 0.5,\n outline: 'none',\n boxShadow: 4,\n}\n\n\n/**\n * Fixed-position overlay that edits a node's text in place, opened by\n * double-clicking a `textEditable` element in the canvas (see\n * DraggableDroppable). Plain components edit through a pill-capable\n * contentEditable line (Enter or blur commits, Shift+Enter breaks a line,\n * Escape cancels). Components flagged `richTextEditable` (AGL-54) get a\n * contentEditable surface with a basic formatting toolbar; the commit\n * sanitizes the markup through an allowlist and stores it in the `html`\n * prop with `children` kept as the plain-text fallback. Either mode\n * commits ONCE through `Aglyn.canvas.updateNodeProps` (a single undo entry).\n *\n * Binding pills (AGL-586): stored `{{...}}` tokens render as named,\n * colored, atomic pills in BOTH modes when the editor opens; the toolbar's\n * {x} button opens the same grouped insert picker as the attributes panel\n * (assembled from this node's ancestor context) and drops a pill at the\n * caret; clicking a pill offers Replace/Remove. Commits serialize pills\n * back to raw token syntax — names shown, ids stored.\n *\n * Instance prop overrides (AGL-1304): opened with a `propTarget`, the same\n * surface edits a component instance's `propValues[propName]` instead of a\n * node's `children` — the double-clicked leaf is a GRAFTED preview node,\n * not a canvas node, so the commit rides the instance. Always the plain\n * surface (prop values substitute as strings), the same single\n * `updateNodeProps` commit (one undo entry, and the same node-changed\n * signal co-editing's shadow diff already mirrors), and an emptied commit\n * REMOVES the override so the component's own copy returns — exactly what\n * clearing the Attributes field does.\n */\nexport const InlineTextEditorComponent = observer(\n function InlineTextEditorComponent() {\n const node = inlineTextEdit.node\n const rect = inlineTextEdit.rect\n const propTarget = inlineTextEdit.propTarget\n // Follows the element as the canvas scrolls or resizes (AGL-1644). Called\n // unconditionally, above the `!node || !rect` bail-out further down, so the\n // hook order is stable whether or not an edit is open.\n const anchor = inlineTextEdit.anchor\n const live = useAnchoredRect(anchor, rect ?? EMPTY_RECT)\n /**\n * Whether the canvas leaf ITSELF is the editing surface (AGL-2486).\n *\n * When it is, this component renders only the toolbar: there is no\n * second rectangle to keep in sync with the text, so the text cannot\n * move or restyle when editing begins and the layout re-flows because\n * the element really did grow. That is the\n * transparent-if-and-only-if-reserved invariant satisfied by\n * construction rather than by a check.\n *\n * When it is not — no element to type into — the opaque fallback\n * overlay is used instead.\n */\n const [inPlaceActive, setInPlaceActive] = useState(false)\n const overlayRef = useRef<HTMLElement>(null)\n const plainRef = useRef<HTMLDivElement>(null)\n const richRef = useRef<HTMLDivElement>(null)\n // Distinguish commit-blur (Enter already committed) from cancel paths.\n const committedRef = useRef(false)\n /**\n * Whether the surface has been BUILT from the node yet (AGL-2486).\n *\n * The editable is populated and focused on a `requestAnimationFrame`, so\n * between opening and that frame it is an empty box holding no caret.\n * Committing then reads emptiness as an author's deletion and writes\n * `children: ''` — the element's text is gone from the canvas, the\n * co-editing mirror publishes it, and every joiner gets the blank.\n * Measured exactly that way against screen `yFjgqiG2wm`: node\n * `XlqFJTz4ej` (\"Be first through the door\") went to `children: ''` from\n * a double-click and a click-away, with nothing typed. A background tab\n * makes it certain rather than rare — `requestAnimationFrame` does not\n * run in one at all, so the surface NEVER seeds and every click-away is\n * a wipe.\n *\n * Nothing can be lost by refusing: a surface that was never built holds\n * no caret and no typing.\n */\n const seededRef = useRef(false)\n /** The canvas leaf while it IS the editing surface — see beginInPlaceEdit. */\n const inPlaceRef = useRef<InPlaceEditSurface | undefined>(undefined)\n /**\n * Latest handlers for the listeners bound onto the leaf. They are bound\n * once per edit, so they must not close over a stale render.\n */\n const handlersRef = useRef({\n keyDown: (_e: KeyboardEvent<HTMLDivElement>) => undefined as void,\n richKeyDown: (_e: KeyboardEvent<HTMLDivElement>) => undefined as void,\n blur: () => undefined as void,\n click: (_e: MouseEvent<HTMLDivElement>) => undefined as void,\n mouseDown: (_e: MouseEvent<HTMLDivElement>) => undefined as void,\n })\n // The insert picker / pill popover take focus (portal + autofocus\n // search) — commit-on-blur must stand down while one is open, or the\n // editor would commit and close under the open menu (AGL-586).\n const menuOpenRef = useRef(false)\n const savedRangeRef = useRef<Range | null>(null)\n const [insertMenu, setInsertMenu] = useState<{\n anchorEl: HTMLElement\n replacePill: HTMLElement | null\n } | null>(null)\n const [pillMenu, setPillMenu] = useState<HTMLElement | null>(null)\n\n // Same context walk as the attributes panel (AGL-583) — the edited\n // node is known, so dataset-item / entry groups resolve identically.\n const { options: insertOptions, labelContext } =\n useInsertTokenOptions(node)\n const labelContextRef = useRef(labelContext)\n labelContextRef.current = labelContext\n // The CONSOLE theme, read here in the console's document: pills drawn in\n // the canvas are painted with it — see `paintTokenPills`.\n const theme = useTheme()\n const themeRef = useRef(theme)\n themeRef.current = theme\n\n // A prop edit is formatted when every element the prop fills draws\n // markup (decided where the edit opens): its markup rides the instance's\n // own `propHtml`, as a node's rides `html`.\n const rich = propTarget\n ? Boolean(propTarget.rich)\n : ((node?.componentSchema?.flags?.richTextEditable ??\n FEATURE_FLAG.DISABLED) &\n FEATURE_FLAG.ENABLED) !==\n 0\n\n // What THIS component's schema allows (AGL-2557); a schema that names\n // nothing allows everything, which is what leaves Typography alone. For a\n // prop edit that is the schema of the element the prop fills.\n const commandGroups = richTextCommandGroups(\n propTarget ? propTarget.schema : node?.componentSchema,\n )\n /**\n * The surface may hold phrasing content only.\n *\n * Derived from the allowance rather than declared beside it: a component\n * that can take neither a list nor a link is one whose element admits no\n * block and no nested control, and that single fact is what the commit\n * sanitizer, the Enter key and the toolbar all need. Two ways to say it\n * would eventually say two different things.\n */\n const phrasingOnly =\n rich &&\n !commandGroups.has(RICH_TEXT_COMMANDS.LIST) &&\n !commandGroups.has(RICH_TEXT_COMMANDS.LINK)\n\n const activeEditable = useCallback(\n () =>\n inPlaceRef.current?.element ??\n (rich ? richRef.current : plainRef.current),\n [rich],\n )\n\n /**\n * Opens the edit: builds the content once, and puts it in the canvas\n * leaf itself wherever that is possible (AGL-2486).\n *\n * The builder is shared deliberately. In-place and the fallback overlay\n * must show the SAME thing — the same pills, the same markup, the same\n * plain-text seed — or the two paths would drift into two editors.\n */\n useEffect(() => {\n if (!node) return\n committedRef.current = false\n menuOpenRef.current = false\n savedRangeRef.current = null\n seededRef.current = false\n const props = { ...node.props, ...node.resolvedProps } as any\n const text = propTarget\n ? propTarget.initialText\n : typeof props?.children === 'string'\n ? (props.children as string)\n : ''\n const resolve = (token: string) =>\n resolveTokenLabel(token, labelContextRef.current)\n\n const markup = propTarget ? propTarget.initialHtml : props?.html\n const build = (target: HTMLElement) => {\n if (rich) {\n const initial =\n typeof markup === 'string' && markup\n ? markup\n : textToHtml(text)\n target.innerHTML = initial\n // Raw {{tokens}} in the stored markup become pills (AGL-586).\n materializeTokenPillsInElement(target, resolve)\n paintTokenPills(target, themeRef.current)\n addCaretStops(target)\n return\n }\n // Plain mode: text nodes + pills, then the browser owns the DOM.\n target.textContent = ''\n for (const segment of parseTokenSegments(text)) {\n if (segment.type === 'token') {\n target.appendChild(\n createTokenPillElement(\n target.ownerDocument,\n segment.token ?? segment.value,\n resolve(segment.token ?? segment.value),\n ),\n )\n } else {\n target.appendChild(target.ownerDocument.createTextNode(segment.value))\n }\n }\n paintTokenPills(target, themeRef.current)\n addCaretStops(target)\n }\n\n // The element itself, whenever there is one to edit.\n const surface = beginInPlaceEdit(anchor, build)\n if (surface) {\n inPlaceRef.current = surface\n seededRef.current = true\n setInPlaceActive(true)\n surface.element.focus()\n const selection = surface.selection()\n if (selection) {\n const range = surface.element.ownerDocument.createRange()\n range.selectNodeContents(surface.element)\n // Caret at the end, never select-all: the author double-clicked a\n // word to edit it, and replacing the lot on the next keystroke is\n // how a heading gets destroyed by a typo.\n range.collapse(false)\n selection.removeAllRanges()\n selection.addRange(range)\n }\n return () => {\n surface.dispose()\n inPlaceRef.current = undefined\n setInPlaceActive(false)\n }\n }\n\n // No element to edit — the OPAQUE overlay. Built on a frame because\n // the surface it writes into has not rendered yet, which is the race\n // `seededRef` exists for.\n setInPlaceActive(false)\n const raf = requestAnimationFrame(() => {\n const editable = rich ? richRef.current : plainRef.current\n if (!editable) return\n build(editable)\n editable.focus()\n const selection = window.getSelection()\n if (selection) {\n const range = document.createRange()\n range.selectNodeContents(editable)\n if (rich) range.collapse(false)\n selection.removeAllRanges()\n selection.addRange(range)\n }\n seededRef.current = true\n })\n return () => cancelAnimationFrame(raf)\n }, [node, rich, propTarget, anchor])\n\n /**\n * Writes `next` only when it is a different document (AGL-2486).\n *\n * Closing this editor is not by itself an edit. Every branch below\n * rebuilds the WHOLE props object from the surface's DOM, so a commit\n * that changed nothing still produced a fresh object — an undo entry, a\n * node-changed signal, and a co-editing mirror publish, all for an edit\n * the author never made. The mirror is the expensive one: it is cleared\n * only by a successful save, so an unsaved no-op is replayed into every\n * joiner's canvas for `COEDIT_MIRROR_MAX_AGE_MS` (seven days) and each\n * of them opens a document that reads dirty with nothing to see.\n */\n const commitProps = useCallback(\n (node: Aglyn.NodeSchema<any>, next: Record<string, unknown>) => {\n if (isEqual(toJS(node.props), next)) return\n canvas.updateNodeProps(node, next as never)\n },\n [],\n )\n\n const commit = useCallback(() => {\n if (committedRef.current) return\n committedRef.current = true\n const current = inlineTextEdit.node\n // An unbuilt surface is not an emptied one (AGL-2486) — close, do not\n // write. See `seededRef`.\n /**\n * Collected first, WRITTEN LAST (AGL-2486).\n *\n * The markup this computes is correct; the hazard is that it can be\n * undone a moment later. Ending the edit restores the element's\n * original child nodes — deliberately, by reference, so React's fibers\n * keep pointing at live nodes — and that restore must not run in the\n * effect cleanup, i.e. AFTER `updateNodeProps` has already told React\n * to re-render the leaf. In that order React paints the new text and\n * the parked ORIGINAL nodes then go back over the top of it, so an\n * edit reads as never having taken.\n *\n * Worst for formatted text, which is how it was found: a node with\n * `html` renders through `dangerouslySetInnerHTML`, so React does not\n * track those children at all and never corrects them afterwards. The\n * canvas kept the pre-edit markup, the store held the new value, and\n * the break came back every time — until \"Remove formatting\" dropped\n * `html` and the plain `children` finally showed.\n *\n * So the element is given back BEFORE the store is written, and the\n * write is the last thing that happens. React then re-renders onto a\n * subtree that is exactly where it left it.\n */\n let nextWrite: Record<string, unknown> | undefined\n if (current && seededRef.current) {\n // UpdateNodeProps REPLACES the props object — spread the existing\n // props so variant/component/etc. survive the text edit.\n const surface = activeEditable()\n // The surface read once, as the plain reading and — for formatted\n // text — the markup beside it.\n let plain: string | undefined\n let markup: string | undefined\n if (rich && surface) {\n // Pills serialize back to raw tokens BEFORE sanitizing (the\n // sanitizer strips attributes, and pill labels must never\n // reach storage) — on a clone, the live DOM stays intact.\n const clone = surface.cloneNode(true) as HTMLElement\n replacePillsWithTokenText(clone)\n // The toolbar offers no block command on a phrasing-only surface,\n // but a PASTE can still carry one in, and the renderer would strip\n // it — so the commit strips it first and what is stored is what\n // the page will draw.\n const sanitized = withoutCaretStops(\n sanitizeRichText(clone.innerHTML, { phrasingOnly }),\n )\n plain = richTextToPlain(sanitized)\n if (/<[a-z]/i.test(sanitized)) markup = sanitized\n } else if (surface) {\n plain = withoutCaretStops(\n serializeTokenSegments(readTokenSegmentsFromDom(surface)),\n )\n // An emptied contentEditable leaves a stray <br> behind.\n if (plain === '\\n') plain = ''\n }\n const target = inlineTextEdit.propTarget\n if (plain !== undefined && target) {\n // Instance prop override (AGL-1304): the edit rides the\n // INSTANCE's nested propValues, never the grafted leaf (which\n // is not a canvas node). An emptied value REMOVES the key —\n // the graft treats '' as unset anyway, and a cleared override\n // must read as clean, exactly like the style-override layer.\n // Formatting rides `propHtml` beside it, and goes with it.\n const values = {\n ...(current.props?.[\n REUSABLE_INSTANCE_PROP_VALUES_KEY\n ] as Record<string, unknown> | undefined),\n }\n const formatted = {\n ...(current.props?.[\n REUSABLE_INSTANCE_PROP_HTML_KEY\n ] as Record<string, unknown> | undefined),\n }\n if (plain === '') delete values[target.propName]\n else values[target.propName] = plain\n if (plain !== '' && markup) formatted[target.propName] = markup\n else delete formatted[target.propName]\n const nextProps: Record<string, unknown> = {\n ...current.props,\n [REUSABLE_INSTANCE_PROP_VALUES_KEY]: values,\n [REUSABLE_INSTANCE_PROP_HTML_KEY]: formatted,\n }\n // The LAST override cleared: drop the container too, so the\n // stored instance is byte-identical to one never overridden.\n if (!Object.keys(values).length) {\n delete nextProps[REUSABLE_INSTANCE_PROP_VALUES_KEY]\n }\n if (!Object.keys(formatted).length) {\n delete nextProps[REUSABLE_INSTANCE_PROP_HTML_KEY]\n }\n nextWrite = toJS(nextProps) as Record<string, unknown>\n } else if (plain !== undefined && rich) {\n const nextProps: Record<string, unknown> = {\n ...toJS(current.props),\n children: plain,\n }\n // ABSENT, not `''`, when there is no markup (AGL-2486). The\n // renderer gates on `typeof html === 'string' && Boolean(html)`,\n // so the two are the same document to everything that draws it —\n // but `isInitialSame` compares serialized node maps with\n // `isEqual`, and there the empty key is a difference. Writing it\n // onto a node that never had one is what put SAVE on the header\n // of a screen nobody had touched.\n if (markup) nextProps['html'] = markup\n else delete nextProps['html']\n nextWrite = nextProps\n } else if (plain !== undefined) {\n nextWrite = {\n ...toJS(current.props),\n children: plain,\n }\n }\n }\n // Give the element back to React BEFORE the write — see `nextWrite`.\n inPlaceRef.current?.dispose()\n inPlaceRef.current = undefined\n if (current && nextWrite) commitProps(current, nextWrite)\n inlineTextEdit.close()\n }, [rich, phrasingOnly, commitProps, activeEditable])\n\n const cancel = useCallback(() => {\n committedRef.current = true\n inlineTextEdit.close()\n }, [])\n\n const handleEditableBlur = useCallback(() => {\n if (menuOpenRef.current) return\n commit()\n }, [commit])\n\n // Latest `commit` for the document listener below, which must not\n // re-register on every render just to stay current.\n const commitRef = useRef(commit)\n commitRef.current = commit\n\n /**\n * Wires the editing handlers onto the LEAF while it is the surface.\n *\n * Imperatively, because the element belongs to the canvas renderer and\n * not to this component's JSX — the same reason `contentEditable` is set\n * as a DOM property. Registered once per edit and torn down with it.\n *\n * No `input` handler is needed any more, and that absence is the point:\n * the element being typed into IS the element being laid out, so the\n * card, the row and the siblings re-flow on their own. The stand-in that\n * used to reproduce that effect for an overlay is gone with the overlay.\n */\n useEffect(() => {\n const surface = inPlaceActive ? inPlaceRef.current : undefined\n const element = surface?.element\n if (!element) return\n const onKeyDown = (event: Event) =>\n (rich ? handlersRef.current.richKeyDown : handlersRef.current.keyDown)(\n event as unknown as KeyboardEvent<HTMLDivElement>,\n )\n const onBlur = () => handlersRef.current.blur()\n const onClick = (event: Event) =>\n handlersRef.current.click(\n event as unknown as MouseEvent<HTMLDivElement>,\n )\n const onMouseDown = (event: Event) =>\n handlersRef.current.mouseDown(\n event as unknown as MouseEvent<HTMLDivElement>,\n )\n element.addEventListener('keydown', onKeyDown)\n element.addEventListener('blur', onBlur)\n element.addEventListener('click', onClick)\n element.addEventListener('mousedown', onMouseDown)\n return () => {\n element.removeEventListener('keydown', onKeyDown)\n element.removeEventListener('blur', onBlur)\n element.removeEventListener('click', onClick)\n element.removeEventListener('mousedown', onMouseDown)\n }\n }, [inPlaceActive, rich])\n\n /**\n * Click-away commits, because on this canvas blur never arrives\n * (AGL-2486).\n *\n * `commit()` used to be reachable from a click only through `onBlur`,\n * and a click on another element cannot produce one: `DraggableDroppable`\n * registers `mousedown` AND `pointerdown` on every leaf and both begin\n * `e.preventDefault(); e.stopPropagation()`. Preventing a mousedown's\n * default suppresses the focus change it would have caused, so the\n * editable keeps focus and stays open — while the same handler runs\n * `Besigner.focus.handleNodeSelection(node, …)` and moves the selection\n * out from under it. Clicking out \"just selects other elements rather\n * than applying\", and the edit sits in a surface the author has already\n * mentally left. This repo has recorded that exact shape once before:\n * an attribute that commits on blur, discarded by selecting the next\n * node, with the canvas still looking right.\n *\n * A CAPTURE-phase listener on the document is what reaches the commit\n * first: capture runs from the document down, so it is ahead of the\n * leaf's own bubble-phase listener and ahead of the `preventDefault`\n * that would have swallowed the blur. It calls the SAME `commit()` the\n * Done button does — one commit path, one undo entry, and the same\n * no-op guard, rather than a second route into the document.\n *\n * The click is deliberately NOT consumed: committing and then letting\n * the canvas select what was clicked is what every other design tool\n * does, and it is what the author asked for by clicking there.\n *\n * `pointerdown`, not `mousedown`: it is the first of the pair, and\n * `preventDefault` on it suppresses the mouse events that follow, so a\n * `mousedown` listener would never run for a touch or pen edit.\n *\n * Targets inside the canvas retarget to its CLOSED shadow host, which is\n * not inside this overlay, so `contains` reads them as outside — which\n * they are. The portalled insert picker and pill popover ARE outside the\n * overlay in the DOM, and are covered by the same `menuOpenRef` stand-down\n * that already guards commit-on-blur (AGL-586).\n */\n useEffect(() => {\n if (!node) return\n const editing = inPlaceRef.current?.element\n const root = editing?.getRootNode() as ShadowRoot | Document | undefined\n const host =\n root && 'host' in root ? (root as ShadowRoot).host : undefined\n\n const isInsideTheEditor = (target: Node | null): boolean => {\n if (!target) return false\n // Read LIVE, never the value captured when this effect ran: a click\n // inside the text is the author placing a caret, and getting that\n // wrong tears the surface down and rebuilds it on every click, which\n // looks exactly like a caret that will not move.\n const live = inPlaceRef.current?.element\n if (live?.contains(target)) return true\n const overlay = overlayRef.current\n return Boolean(overlay?.contains(target))\n }\n\n const handlePointerDownAway = (event: Event) => {\n if (menuOpenRef.current) return\n const target = event.target as Node | null\n // Inside the CLOSED canvas root, an event seen from the document has\n // already been retargeted to the host, so it cannot say whether the\n // click landed on the text being edited or beside it. The listener on\n // the root itself sees the real target and has already decided; this\n // one must not overrule it with a guess.\n if (host && target === host) return\n if (isInsideTheEditor(target)) return\n // A press on the element being edited, beside the text: the text is\n // an inline run as wide as its words (a lone token is a few\n // characters), and the rest of the line is the element around it.\n // That is where an author clicks to put the caret after a token, and\n // it used to read as a click away and close the edit.\n const live = inPlaceRef.current?.element\n const leaf = live?.closest(LEAF_STAMP_SELECTOR)\n if (\n live &&\n leaf &&\n target instanceof Element &&\n target.closest(LEAF_STAMP_SELECTOR) === leaf\n ) {\n event.preventDefault()\n placeCaretAtNearEnd(live, event as PointerEvent)\n return\n }\n commitRef.current()\n }\n\n document.addEventListener('pointerdown', handlePointerDownAway, true)\n // Second listener, INSIDE the shadow root, for the clicks the first one\n // is blind to — including a click on the very element being edited,\n // which must move the caret rather than end the edit.\n if (root && root !== document) {\n root.addEventListener('pointerdown', handlePointerDownAway, true)\n }\n return () => {\n document.removeEventListener('pointerdown', handlePointerDownAway, true)\n if (root && root !== document) {\n root.removeEventListener('pointerdown', handlePointerDownAway, true)\n }\n }\n }, [node, inPlaceActive])\n\n const insertPlainNewline = useCallback(() => {\n const editable = activeEditable()\n const selection = editable ? selectionOf(editable) : null\n if (!selection || selection.rangeCount === 0) return\n const range = selection.getRangeAt(0)\n range.deleteContents()\n const newline = document.createTextNode('\\n')\n range.insertNode(newline)\n range.setStartAfter(newline)\n range.collapse(true)\n selection.removeAllRanges()\n selection.addRange(range)\n }, [activeEditable])\n\n const handleKeyDown = useCallback(\n (event: KeyboardEvent<HTMLDivElement>) => {\n if (event.key === 'Escape') {\n event.preventDefault()\n // An open menu closes first, as Escape does everywhere else; the\n // edit it was opened from stays.\n if (menuOpenRef.current) {\n setInsertMenu(null)\n setPillMenu(null)\n menuOpenRef.current = false\n return\n }\n cancel()\n } else if (event.key === 'Enter' && !event.shiftKey) {\n event.preventDefault()\n commit()\n } else if (event.key === 'Enter') {\n // Browsers fork contentEditable into <div>s on Enter — insert\n // the newline ourselves so reads stay text + pills only.\n event.preventDefault()\n insertPlainNewline()\n }\n },\n [cancel, commit, insertPlainNewline],\n )\n\n const handleRichKeyDown = useCallback(\n (event: KeyboardEvent<HTMLDivElement>) => {\n if (event.key === 'Escape') {\n event.preventDefault()\n // An open menu closes first, as Escape does everywhere else; the\n // edit it was opened from stays.\n if (menuOpenRef.current) {\n setInsertMenu(null)\n setPillMenu(null)\n menuOpenRef.current = false\n return\n }\n cancel()\n } else if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {\n event.preventDefault()\n commit()\n } else if (event.key === 'Enter' && phrasingOnly && !event.shiftKey) {\n // A phrasing-only surface is a control's LABEL — a button, a link,\n // an accordion header. Enter there means \"done\", the same as it\n // does on the plain surface; a browser would otherwise fork the\n // contentEditable into `<div>`s, which is exactly the markup this\n // surface may not hold. Shift+Enter still breaks the line, and a\n // `<br>` is phrasing content.\n event.preventDefault()\n commit()\n }\n },\n [cancel, commit, phrasingOnly],\n )\n\n // Keep the selection inside the editable surface while clicking tools.\n const keepFocus = useCallback((event: MouseEvent) => {\n event.preventDefault()\n }, [])\n\n const exec = useCallback(\n (command: string) => () => {\n // ExecCommand is deprecated but universally supported and keeps this\n // dependency-free; the output is normalized by the sanitizer anyway.\n document.execCommand(command)\n activeEditable()?.focus()\n },\n [activeEditable],\n )\n\n const handleLink = useCallback(() => {\n const url = window.prompt('Link URL (https://…)')\n if (url) document.execCommand('createLink', false, url)\n activeEditable()?.focus()\n }, [activeEditable])\n\n /** Pill clicks (delegated): offer Replace/Remove (AGL-586). */\n const handleEditableClick = useCallback(\n (event: MouseEvent<HTMLDivElement>) => {\n const pill = (event.target as HTMLElement).closest?.(\n `[${TOKEN_PILL_ATTR}]`,\n ) as HTMLElement | null\n if (!pill || !event.currentTarget.contains(pill)) return\n menuOpenRef.current = true\n setPillMenu(pill)\n },\n [],\n )\n\n // Pills are non-editable islands — a mousedown on one would move\n // focus out of the editable and trigger commit-on-blur.\n const handleEditableMouseDown = useCallback(\n (event: MouseEvent<HTMLDivElement>) => {\n const pill = (event.target as HTMLElement).closest?.(\n `[${TOKEN_PILL_ATTR}]`,\n )\n if (pill) event.preventDefault()\n },\n [],\n )\n\n handlersRef.current = {\n keyDown: handleKeyDown,\n richKeyDown: handleRichKeyDown,\n blur: handleEditableBlur,\n click: handleEditableClick,\n mouseDown: handleEditableMouseDown,\n }\n\n /** The toolbar {x}: captures the live selection, opens the picker. */\n const handleInsertOpen = useCallback(\n (event: MouseEvent<HTMLElement>) => {\n const editable = activeEditable()\n const selection = editable ? selectionOf(editable) : null\n const range =\n selection && selection.rangeCount > 0\n ? selection.getRangeAt(0)\n : null\n savedRangeRef.current =\n range &&\n editable &&\n editable.contains(range.startContainer) &&\n editable.contains(range.endContainer)\n ? range.cloneRange()\n : null\n menuOpenRef.current = true\n setInsertMenu({ anchorEl: event.currentTarget, replacePill: null })\n },\n [activeEditable],\n )\n\n const closeMenus = useCallback(() => {\n setInsertMenu(null)\n setPillMenu(null)\n menuOpenRef.current = false\n activeEditable()?.focus()\n }, [activeEditable])\n\n const handleInsertPick = useCallback(\n (token: string) => {\n const editable = activeEditable()\n const replacePill = insertMenu?.replacePill ?? null\n setInsertMenu(null)\n menuOpenRef.current = false\n if (!editable) return\n const pill = createTokenPillElement(\n document,\n token,\n resolveTokenLabel(token, labelContextRef.current),\n )\n if (replacePill && editable.contains(replacePill)) {\n replacePill.replaceWith(pill)\n } else {\n const range = savedRangeRef.current\n if (\n range &&\n editable.contains(range.startContainer) &&\n editable.contains(range.endContainer)\n ) {\n range.deleteContents()\n range.insertNode(pill)\n } else {\n editable.appendChild(pill)\n }\n }\n savedRangeRef.current = null\n paintTokenPills(editable, themeRef.current)\n addCaretStops(editable)\n editable.focus()\n // Caret lands just after the pill, ready to keep typing.\n const selection = selectionOf(editable)\n if (selection) {\n const after = document.createRange()\n after.setStartAfter(pill)\n after.collapse(true)\n selection.removeAllRanges()\n selection.addRange(after)\n }\n },\n [activeEditable, insertMenu],\n )\n\n const handlePillReplace = useCallback(() => {\n const pill = pillMenu\n setPillMenu(null)\n if (!pill) {\n menuOpenRef.current = false\n return\n }\n // Keep menuOpenRef up — the insert picker opens next.\n setInsertMenu({ anchorEl: pill, replacePill: pill })\n }, [pillMenu])\n\n const handlePillRemove = useCallback(() => {\n pillMenu?.remove()\n closeMenus()\n }, [pillMenu, closeMenus])\n\n const insertButton = (\n <IconButton\n size=\"small\"\n title=\"Insert data\"\n aria-label=\"Insert data token\"\n onMouseDown={keepFocus}\n onClick={handleInsertOpen}\n sx={{ width: 28, height: 28, borderRadius: 0.5 }}\n >\n <MdiIcon path={mdiCodeBraces.path} fontSize=\"small\" />\n </IconButton>\n )\n\n if (!node || !rect) return null\n\n // Read at render, which `useAnchoredRect` makes safe: it re-renders on\n // every scroll and resize, so these are never a stale snapshot. The toolbar\n // sits 40px ABOVE the surface, so the top margin has to clear it or the\n // controls go off-screen while the editable stays on it.\n const viewportWidth =\n typeof window === 'undefined' ? Infinity : window.innerWidth\n const viewportHeight =\n typeof window === 'undefined' ? Infinity : window.innerHeight\n // The fallback overlay is ALWAYS the opaque box (AGL-2486). It exists\n // only for an edit with no element to type into, and an element that is\n // not there cannot re-flow — so a see-through surface over it would be\n // exactly what the invariant forbids. In-place editing needs no surface\n // here at all: the leaf is the surface, and this component renders only\n // the toolbar.\n //\n // Built as plain records and cast ONCE, the way `tokenPillContainerSx`\n // is: MUI's `sx` union cannot absorb a computed spread and reports every\n // neighbouring key as the error instead.\n const surfaceSx: Record<string, unknown> = BOXED_SURFACE_SX\n const richSurfaceSx = {\n width: '100%',\n minHeight: live.height,\n boxSizing: 'border-box',\n font: 'inherit',\n ...surfaceSx,\n '& a': { pointerEvents: 'none' },\n ...tokenPillContainerSx,\n } as SystemStyleObject<Theme>\n const plainSurfaceSx = {\n width: '100%',\n minHeight: live.height,\n boxSizing: 'border-box',\n font: 'inherit',\n ...surfaceSx,\n // After the anchor's type, never from it: `pre-wrap` is what makes a\n // Shift+Enter newline visible while typing.\n whiteSpace: 'pre-wrap',\n wordBreak: 'break-word',\n ...tokenPillContainerSx,\n } as SystemStyleObject<Theme>\n const minWidth = Math.max(live.width, 120)\n const TOOLBAR_CLEARANCE = 48\n const KEEP_VISIBLE = 80\n\n return (\n <Box\n ref={overlayRef}\n data-aglyn=\"overlay:inline-text-editor\"\n sx={{\n position: 'fixed',\n left: clampToViewport(live.left, minWidth, viewportWidth),\n top: clampToViewport(\n live.top,\n KEEP_VISIBLE,\n viewportHeight,\n TOOLBAR_CLEARANCE,\n ),\n minWidth,\n maxWidth: '90vw',\n zIndex: (theme) => theme.zIndex.modal,\n }}\n >\n {/* The toolbar survives in-place editing — B / I / U, lists, link\n and the {} token control are the reason this editor exists at\n all, and it is chrome, not text, so it stays an overlay above\n the run being edited rather than inside it. */}\n <Paper\n elevation={4}\n sx={{\n position: 'absolute',\n top: -40,\n left: 0,\n px: 0.5,\n py: 0.25,\n display: 'flex',\n gap: 0.25,\n alignItems: 'center',\n }}\n >\n {rich\n ? RICH_COMMANDS.filter(({ group }) =>\n commandGroups.has(group),\n ).map(({ command, label, title }) => (\n <IconButton\n key={command}\n size=\"small\"\n title={title}\n onMouseDown={keepFocus}\n onClick={exec(command)}\n sx={{\n width: 28,\n height: 28,\n fontSize: 13,\n fontWeight: 700,\n fontStyle: command === 'italic' ? 'italic' : undefined,\n textDecoration:\n command === 'underline' ? 'underline' : undefined,\n borderRadius: 0.5,\n }}\n >\n {label}\n </IconButton>\n ))\n : null}\n {rich && commandGroups.has(RICH_TEXT_COMMANDS.LINK) ? (\n <IconButton\n size=\"small\"\n title=\"Insert link\"\n onMouseDown={keepFocus}\n onClick={handleLink}\n sx={{ width: 28, height: 28, fontSize: 13, borderRadius: 0.5 }}\n >\n {'\\u{1F517}'}\n </IconButton>\n ) : null}\n {insertButton}\n <Button\n size=\"small\"\n color=\"primary\"\n onMouseDown={keepFocus}\n onClick={commit}\n >\n {'Done'}\n </Button>\n </Paper>\n {/* No surface at all when the leaf is the surface (AGL-2486). */}\n {inPlaceActive ? null : rich ? (\n <Box\n ref={richRef}\n contentEditable\n suppressContentEditableWarning\n role=\"textbox\"\n aria-label=\"Edit rich text\"\n onKeyDown={handleRichKeyDown}\n onBlur={handleEditableBlur}\n onClick={handleEditableClick}\n onMouseDown={handleEditableMouseDown}\n sx={richSurfaceSx}\n />\n ) : (\n <Box\n ref={plainRef}\n contentEditable\n suppressContentEditableWarning\n role=\"textbox\"\n aria-label=\"Edit text\"\n onKeyDown={handleKeyDown}\n onBlur={handleEditableBlur}\n onClick={handleEditableClick}\n onMouseDown={handleEditableMouseDown}\n sx={plainSurfaceSx}\n />\n )}\n <InsertTokenMenu\n anchorEl={insertMenu?.anchorEl ?? null}\n open={Boolean(insertMenu)}\n onClose={closeMenus}\n options={insertOptions}\n onInsert={handleInsertPick}\n />\n <TokenPillPopover\n anchorEl={pillMenu}\n token={pillMenu?.getAttribute(TOKEN_PILL_ATTR) ?? ''}\n onClose={closeMenus}\n onReplace={handlePillReplace}\n onRemove={handlePillRemove}\n />\n </Box>\n )\n },\n)\nInlineTextEditorComponent.displayName = 'InlineTextEditorComponent'\n\nexport default InlineTextEditorComponent\n"],"names":["canvas","FEATURE_FLAG","REUSABLE_INSTANCE_PROP_HTML_KEY","REUSABLE_INSTANCE_PROP_VALUES_KEY","RICH_TEXT_COMMANDS","mdiCodeBraces","MdiIcon","Box","Button","IconButton","Paper","useTheme","isEqual","toJS","observer","useCallback","useEffect","useRef","useState","clampToViewport","useAnchoredRect","useInsertTokenOptions","addCaretStops","beginInPlaceEdit","selectionOf","withoutCaretStops","inlineTextEdit","RICH_COMMANDS","richTextCommandGroups","richTextToPlain","sanitizeRichText","textToHtml","createTokenPillElement","materializeTokenPillsInElement","readTokenSegmentsFromDom","replacePillsWithTokenText","TOKEN_PILL_ATTR","parseTokenSegments","resolveTokenLabel","serializeTokenSegments","InsertTokenMenu","paintTokenPills","TokenPillPopover","tokenPillContainerSx","LEAF_STAMP_SELECTOR","placeCaretAtNearEnd","editable","press","lines","Array","from","getClientRects","first","atStart","Boolean","clientY","top","bottom","clientX","left","focus","selection","range","ownerDocument","createRange","selectNodeContents","collapse","removeAllRanges","addRange","EMPTY_RECT","width","height","BOXED_SURFACE_SX","p","bgcolor","color","border","borderColor","borderRadius","outline","boxShadow","InlineTextEditorComponent","node","rect","propTarget","anchor","live","inPlaceActive","setInPlaceActive","overlayRef","plainRef","richRef","committedRef","seededRef","inPlaceRef","undefined","handlersRef","keyDown","_e","richKeyDown","blur","click","mouseDown","menuOpenRef","savedRangeRef","insertMenu","setInsertMenu","pillMenu","setPillMenu","options","insertOptions","labelContext","labelContextRef","current","theme","themeRef","rich","componentSchema","flags","richTextEditable","DISABLED","ENABLED","commandGroups","schema","phrasingOnly","has","LIST","LINK","activeEditable","element","props","resolvedProps","text","initialText","children","resolve","token","markup","initialHtml","html","build","target","initial","innerHTML","textContent","segment","type","appendChild","value","createTextNode","surface","dispose","raf","requestAnimationFrame","window","getSelection","document","cancelAnimationFrame","commitProps","next","updateNodeProps","commit","nextWrite","plain","clone","cloneNode","sanitized","test","values","formatted","propName","nextProps","Object","keys","length","close","cancel","handleEditableBlur","commitRef","onKeyDown","event","onBlur","onClick","onMouseDown","addEventListener","removeEventListener","editing","root","getRootNode","host","isInsideTheEditor","contains","overlay","handlePointerDownAway","leaf","closest","Element","preventDefault","insertPlainNewline","rangeCount","getRangeAt","deleteContents","newline","insertNode","setStartAfter","handleKeyDown","key","shiftKey","handleRichKeyDown","metaKey","ctrlKey","keepFocus","exec","command","execCommand","handleLink","url","prompt","handleEditableClick","pill","currentTarget","handleEditableMouseDown","handleInsertOpen","startContainer","endContainer","cloneRange","anchorEl","replacePill","closeMenus","handleInsertPick","replaceWith","after","handlePillReplace","handlePillRemove","remove","insertButton","size","title","aria-label","sx","path","fontSize","viewportWidth","Infinity","innerWidth","viewportHeight","innerHeight","surfaceSx","richSurfaceSx","minHeight","boxSizing","font","pointerEvents","plainSurfaceSx","whiteSpace","wordBreak","minWidth","Math","max","TOOLBAR_CLEARANCE","KEEP_VISIBLE","ref","data-aglyn","position","maxWidth","zIndex","modal","elevation","px","py","display","gap","alignItems","filter","group","map","label","fontWeight","fontStyle","textDecoration","contentEditable","suppressContentEditableWarning","role","open","onClose","onInsert","getAttribute","onReplace","onRemove","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;;AAGD,SACEA,MAAM,EACNC,YAAY,EACZC,+BAA+B,EAC/BC,iCAAiC,EACjCC,kBAAkB,QACb,eAAc;AACrB,SAASC,aAAa,QAAQ,yBAAwB;AACtD,SAASC,OAAO,QAAQ,uBAAsB;AAC9C,SAASC,GAAG,EAAEC,MAAM,EAAEC,UAAU,EAAEC,KAAK,E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AAW6B;gBACX3B,QAAQJ;gBACRK,SAASoC;gBACTnC,aAAasC;gBACbkB,IAAIS;+BAGN,KAACjP;gBACC8P,KAAK3K;gBACL8L,eAAe;gBACfC,8BAA8B;gBAC9BC,MAAK;gBACL5C,cAAW;gBACX3D,WAAW0B;gBACXxB,QAAQJ;gBACRK,SAASoC;gBACTnC,aAAasC;gBACbkB,IAAIc;;0BAGR,KAACrN;gBACC0L,QAAQ,WAAEzH,8BAAAA,WAAYyH,QAAQ,oBAAI;gBAClCyD,MAAMrO,QAAQmD;gBACdmL,SAASxD;gBACTvH,SAASC;gBACT+K,UAAUxD;;0BAEZ,KAAC3L;gBACCwL,UAAUvH;gBACV6B,KAAK,WAAE7B,4BAAAA,SAAUmL,YAAY,CAAC1P,oCAAoB;gBAClDwP,SAASxD;gBACT2D,WAAWvD;gBACXwD,UAAUvD;;;;AAIlB,GACD;AACDxJ,0BAA0BgN,WAAW,GAAG;AAExC,eAAehN,0BAAyB"}
1
+ {"version":3,"sources":["../../../../../../../../libs/besigner/feature/designer/src/lib/components/inline-text-editor.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type * as Aglyn from '@aglyn/aglyn'\nimport {\n canvas,\n FEATURE_FLAG,\n REUSABLE_INSTANCE_PROP_HTML_KEY,\n REUSABLE_INSTANCE_PROP_VALUES_KEY,\n RICH_TEXT_COMMANDS,\n} from '@aglyn/aglyn'\nimport { mdiCodeBraces } from '@aglyn/shared-data-mdi'\nimport { MdiIcon } from '@aglyn/shared-ui-jsx'\nimport { Box, Button, IconButton, Paper, useTheme } from '@mui/material'\nimport type { Theme } from '@mui/material/styles'\nimport type { SystemStyleObject } from '@mui/system'\nimport isEqual from 'lodash-es/isEqual.js'\nimport { toJS } from 'mobx'\nimport { observer } from 'mobx-react-lite'\nimport {\n type KeyboardEvent,\n type MouseEvent,\n useCallback,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n} from 'react'\nimport { clampToViewport, useAnchoredRect } from '../hooks/use-anchored-rect'\nimport useInsertTokenOptions from '../hooks/use-insert-token-options'\nimport {\n addCaretStops,\n beginInPlaceEdit,\n type InPlaceEditSurface,\n selectionOf,\n withoutCaretStops,\n} from '../utils/in-place-edit-surface'\nimport { inlineTextEdit } from '../utils/inline-text-edit.store'\nimport {\n RICH_COMMANDS,\n richTextCommandGroups,\n} from '../utils/rich-text-commands'\nimport {\n richTextToPlain,\n sanitizeRichText,\n textToHtml,\n} from '../utils/sanitize-rich-text'\nimport {\n createTokenPillElement,\n materializeTokenPillsInElement,\n readTokenSegmentsFromDom,\n replacePillsWithTokenText,\n TOKEN_PILL_ATTR,\n} from '../utils/token-editable-dom'\nimport {\n isNearSelectionHandle,\n isTouchPointer,\n placeDockedToolbar,\n prefersTouchEditing,\n readVisibleArea,\n selectionEndBoxes,\n TouchPressTracker,\n type VisibleArea,\n} from '../utils/touch-text-edit'\nimport {\n parseTokenSegments,\n resolveTokenLabel,\n serializeTokenSegments,\n} from '../utils/token-segments'\nimport { InsertTokenMenu } from './insert-token-menu.component'\nimport {\n paintTokenPills,\n TokenPillPopover,\n tokenPillContainerSx,\n} from './token-pill.component'\n\n/** The stamp `Leaf` puts on every element it renders. */\nconst LEAF_STAMP_SELECTOR = '[data-aglyn^=\"leaf:\"]'\n\n/**\n * Puts the caret at whichever end of `editable` is nearer a press beside it:\n * the start for a press before its first line, the end otherwise.\n */\nfunction placeCaretAtNearEnd(\n editable: HTMLElement,\n press: { clientX: number; clientY: number },\n): void {\n const lines = Array.from(editable.getClientRects())\n const first = lines[0]\n const atStart = Boolean(\n first &&\n (press.clientY < first.top ||\n (press.clientY <= first.bottom && press.clientX < first.left)),\n )\n editable.focus()\n const selection = selectionOf(editable)\n if (!selection) return\n const range = editable.ownerDocument.createRange()\n range.selectNodeContents(editable)\n range.collapse(atStart)\n selection.removeAllRanges()\n selection.addRange(range)\n}\n\n/** Stands in while no edit is open, so the anchor hook can run every render. */\nconst EMPTY_RECT = { left: 0, top: 0, width: 0, height: 0 }\n\n/**\n * The fallback editor, for an edit with no element to type into — opened\n * with no anchor, or on an anchor already detached from the document.\n *\n * Deliberately OPAQUE. It floats over content that cannot re-flow with it,\n * and a see-through surface in that position is what drew two texts over\n * each other; covering what it stands on is honest, blending with it is not.\n * Everything else edits the canvas leaf itself and needs no surface here.\n */\nconst BOXED_SURFACE_SX = {\n p: 0.5,\n bgcolor: 'background.paper',\n color: 'text.primary',\n border: '2px solid',\n borderColor: 'tertiary.main',\n borderRadius: 0.5,\n outline: 'none',\n boxShadow: 4,\n}\n\n\n/**\n * Fixed-position overlay that edits a node's text in place, opened by\n * double-clicking a `textEditable` element in the canvas (see\n * DraggableDroppable). Plain components edit through a pill-capable\n * contentEditable line (Enter or blur commits, Shift+Enter breaks a line,\n * Escape cancels). Components flagged `richTextEditable` (AGL-54) get a\n * contentEditable surface with a basic formatting toolbar; the commit\n * sanitizes the markup through an allowlist and stores it in the `html`\n * prop with `children` kept as the plain-text fallback. Either mode\n * commits ONCE through `Aglyn.canvas.updateNodeProps` (a single undo entry).\n *\n * Binding pills (AGL-586): stored `{{...}}` tokens render as named,\n * colored, atomic pills in BOTH modes when the editor opens; the toolbar's\n * {x} button opens the same grouped insert picker as the attributes panel\n * (assembled from this node's ancestor context) and drops a pill at the\n * caret; clicking a pill offers Replace/Remove. Commits serialize pills\n * back to raw token syntax — names shown, ids stored.\n *\n * Instance prop overrides (AGL-1304): opened with a `propTarget`, the same\n * surface edits a component instance's `propValues[propName]` instead of a\n * node's `children` — the double-clicked leaf is a GRAFTED preview node,\n * not a canvas node, so the commit rides the instance. Always the plain\n * surface (prop values substitute as strings), the same single\n * `updateNodeProps` commit (one undo entry, and the same node-changed\n * signal co-editing's shadow diff already mirrors), and an emptied commit\n * REMOVES the override so the component's own copy returns — exactly what\n * clearing the Attributes field does.\n */\nexport const InlineTextEditorComponent = observer(\n function InlineTextEditorComponent() {\n const node = inlineTextEdit.node\n const rect = inlineTextEdit.rect\n const propTarget = inlineTextEdit.propTarget\n // Follows the element as the canvas scrolls or resizes (AGL-1644). Called\n // unconditionally, above the `!node || !rect` bail-out further down, so the\n // hook order is stable whether or not an edit is open.\n const anchor = inlineTextEdit.anchor\n const live = useAnchoredRect(anchor, rect ?? EMPTY_RECT)\n /**\n * Whether the canvas leaf ITSELF is the editing surface (AGL-2486).\n *\n * When it is, this component renders only the toolbar: there is no\n * second rectangle to keep in sync with the text, so the text cannot\n * move or restyle when editing begins and the layout re-flows because\n * the element really did grow. That is the\n * transparent-if-and-only-if-reserved invariant satisfied by\n * construction rather than by a check.\n *\n * When it is not — no element to type into — the opaque fallback\n * overlay is used instead.\n */\n const [inPlaceActive, setInPlaceActive] = useState(false)\n const overlayRef = useRef<HTMLElement>(null)\n const plainRef = useRef<HTMLDivElement>(null)\n const richRef = useRef<HTMLDivElement>(null)\n // Distinguish commit-blur (Enter already committed) from cancel paths.\n const committedRef = useRef(false)\n /**\n * Whether the surface has been BUILT from the node yet (AGL-2486).\n *\n * The editable is populated and focused on a `requestAnimationFrame`, so\n * between opening and that frame it is an empty box holding no caret.\n * Committing then reads emptiness as an author's deletion and writes\n * `children: ''` — the element's text is gone from the canvas, the\n * co-editing mirror publishes it, and every joiner gets the blank.\n * Measured exactly that way against screen `yFjgqiG2wm`: node\n * `XlqFJTz4ej` (\"Be first through the door\") went to `children: ''` from\n * a double-click and a click-away, with nothing typed. A background tab\n * makes it certain rather than rare — `requestAnimationFrame` does not\n * run in one at all, so the surface NEVER seeds and every click-away is\n * a wipe.\n *\n * Nothing can be lost by refusing: a surface that was never built holds\n * no caret and no typing.\n */\n const seededRef = useRef(false)\n /** The canvas leaf while it IS the editing surface — see beginInPlaceEdit. */\n const inPlaceRef = useRef<InPlaceEditSurface | undefined>(undefined)\n /**\n * Latest handlers for the listeners bound onto the leaf. They are bound\n * once per edit, so they must not close over a stale render.\n */\n const handlersRef = useRef({\n keyDown: (_e: KeyboardEvent<HTMLDivElement>) => undefined as void,\n richKeyDown: (_e: KeyboardEvent<HTMLDivElement>) => undefined as void,\n blur: () => undefined as void,\n click: (_e: MouseEvent<HTMLDivElement>) => undefined as void,\n mouseDown: (_e: MouseEvent<HTMLDivElement>) => undefined as void,\n })\n // The insert picker / pill popover take focus (portal + autofocus\n // search) — commit-on-blur must stand down while one is open, or the\n // editor would commit and close under the open menu (AGL-586).\n const menuOpenRef = useRef(false)\n const savedRangeRef = useRef<Range | null>(null)\n const [insertMenu, setInsertMenu] = useState<{\n anchorEl: HTMLElement\n replacePill: HTMLElement | null\n } | null>(null)\n const [pillMenu, setPillMenu] = useState<HTMLElement | null>(null)\n /**\n * Whether the edit is being made with a finger (AGL-4069).\n *\n * Decided by the input itself, not by the screen size: the latest press\n * anywhere on the page says which kind of pointer is in use, and a device\n * whose main pointer is coarse starts out as touch before any press has\n * been seen. A touch edit keeps its toolbar in the visible area, above\n * the keyboard, and ends only on a real tap — see `touch-text-edit.ts`.\n * A mouse keeps the behaviour it always had.\n */\n const lastPressWasTouchRef = useRef<boolean | undefined>(undefined)\n const [touchMode, setTouchMode] = useState(false)\n const touchModeRef = useRef(touchMode)\n touchModeRef.current = touchMode\n /** The part of the page the author can see, while a touch edit is open. */\n const [visibleArea, setVisibleArea] = useState<VisibleArea | undefined>(\n undefined,\n )\n const toolbarRef = useRef<HTMLDivElement>(null)\n const [toolbarHeight, setToolbarHeight] = useState(0)\n /** The selection as a toolbar press found it, to act on if a tap loses it. */\n const toolbarRangeRef = useRef<Range | null>(null)\n\n // Same context walk as the attributes panel (AGL-583) — the edited\n // node is known, so dataset-item / entry groups resolve identically.\n const { options: insertOptions, labelContext } =\n useInsertTokenOptions(node)\n const labelContextRef = useRef(labelContext)\n labelContextRef.current = labelContext\n // The CONSOLE theme, read here in the console's document: pills drawn in\n // the canvas are painted with it — see `paintTokenPills`.\n const theme = useTheme()\n const themeRef = useRef(theme)\n themeRef.current = theme\n\n // A prop edit is formatted when every element the prop fills draws\n // markup (decided where the edit opens): its markup rides the instance's\n // own `propHtml`, as a node's rides `html`.\n const rich = propTarget\n ? Boolean(propTarget.rich)\n : ((node?.componentSchema?.flags?.richTextEditable ??\n FEATURE_FLAG.DISABLED) &\n FEATURE_FLAG.ENABLED) !==\n 0\n\n // What THIS component's schema allows (AGL-2557); a schema that names\n // nothing allows everything, which is what leaves Typography alone. For a\n // prop edit that is the schema of the element the prop fills.\n const commandGroups = richTextCommandGroups(\n propTarget ? propTarget.schema : node?.componentSchema,\n )\n /**\n * The surface may hold phrasing content only.\n *\n * Derived from the allowance rather than declared beside it: a component\n * that can take neither a list nor a link is one whose element admits no\n * block and no nested control, and that single fact is what the commit\n * sanitizer, the Enter key and the toolbar all need. Two ways to say it\n * would eventually say two different things.\n */\n const phrasingOnly =\n rich &&\n !commandGroups.has(RICH_TEXT_COMMANDS.LIST) &&\n !commandGroups.has(RICH_TEXT_COMMANDS.LINK)\n\n const activeEditable = useCallback(\n () =>\n inPlaceRef.current?.element ??\n (rich ? richRef.current : plainRef.current),\n [rich],\n )\n\n // Which kind of pointer pressed last, read wherever on the page it pressed:\n // a press inside the closed canvas still reaches the document, retargeted.\n useEffect(() => {\n const notePress = (event: Event) => {\n const touch = isTouchPointer(event)\n lastPressWasTouchRef.current = touch\n if (inlineTextEdit.node && touch !== touchModeRef.current) {\n setTouchMode(touch)\n }\n }\n document.addEventListener('pointerdown', notePress, true)\n return () => document.removeEventListener('pointerdown', notePress, true)\n }, [])\n\n // Settled once per edit, from the press that opened it.\n useEffect(() => {\n if (!node) return\n setTouchMode(\n lastPressWasTouchRef.current ??\n prefersTouchEditing(typeof window === 'undefined' ? undefined : window),\n )\n }, [node])\n\n /**\n * Follows the visible area while a touch edit is open (AGL-4069). The\n * keyboard opening, iOS panning the page to keep the caret in view, and a\n * pinch all move the VISUAL viewport, which fires neither a window scroll\n * nor a window resize.\n */\n useEffect(() => {\n if (!node || !touchMode || typeof window === 'undefined') {\n setVisibleArea(undefined)\n return\n }\n const update = () => setVisibleArea(readVisibleArea(window))\n update()\n const visual = window.visualViewport\n visual?.addEventListener('resize', update, { passive: true })\n visual?.addEventListener('scroll', update, { passive: true })\n window.addEventListener('resize', update, { passive: true })\n window.addEventListener('scroll', update, { passive: true, capture: true })\n return () => {\n visual?.removeEventListener('resize', update)\n visual?.removeEventListener('scroll', update)\n window.removeEventListener('resize', update)\n window.removeEventListener('scroll', update, { capture: true })\n }\n }, [node, touchMode])\n\n // The docked toolbar's own height decides where its bottom edge goes.\n useLayoutEffect(() => {\n const height = toolbarRef.current?.offsetHeight ?? 0\n if (height !== toolbarHeight) setToolbarHeight(height)\n }, [node, touchMode, visibleArea, toolbarHeight])\n\n /**\n * Opens the edit: builds the content once, and puts it in the canvas\n * leaf itself wherever that is possible (AGL-2486).\n *\n * The builder is shared deliberately. In-place and the fallback overlay\n * must show the SAME thing — the same pills, the same markup, the same\n * plain-text seed — or the two paths would drift into two editors.\n */\n useEffect(() => {\n if (!node) return\n committedRef.current = false\n menuOpenRef.current = false\n savedRangeRef.current = null\n seededRef.current = false\n const props = { ...node.props, ...node.resolvedProps } as any\n const text = propTarget\n ? propTarget.initialText\n : typeof props?.children === 'string'\n ? (props.children as string)\n : ''\n const resolve = (token: string) =>\n resolveTokenLabel(token, labelContextRef.current)\n\n const markup = propTarget ? propTarget.initialHtml : props?.html\n const build = (target: HTMLElement) => {\n if (rich) {\n const initial =\n typeof markup === 'string' && markup\n ? markup\n : textToHtml(text)\n target.innerHTML = initial\n // Raw {{tokens}} in the stored markup become pills (AGL-586).\n materializeTokenPillsInElement(target, resolve)\n paintTokenPills(target, themeRef.current)\n addCaretStops(target)\n return\n }\n // Plain mode: text nodes + pills, then the browser owns the DOM.\n target.textContent = ''\n for (const segment of parseTokenSegments(text)) {\n if (segment.type === 'token') {\n target.appendChild(\n createTokenPillElement(\n target.ownerDocument,\n segment.token ?? segment.value,\n resolve(segment.token ?? segment.value),\n ),\n )\n } else {\n target.appendChild(target.ownerDocument.createTextNode(segment.value))\n }\n }\n paintTokenPills(target, themeRef.current)\n addCaretStops(target)\n }\n\n // The element itself, whenever there is one to edit.\n const surface = beginInPlaceEdit(anchor, build)\n if (surface) {\n inPlaceRef.current = surface\n seededRef.current = true\n setInPlaceActive(true)\n surface.element.focus()\n const selection = surface.selection()\n if (selection) {\n const range = surface.element.ownerDocument.createRange()\n range.selectNodeContents(surface.element)\n // Caret at the end, never select-all: the author double-clicked a\n // word to edit it, and replacing the lot on the next keystroke is\n // how a heading gets destroyed by a typo.\n range.collapse(false)\n selection.removeAllRanges()\n selection.addRange(range)\n }\n return () => {\n surface.dispose()\n inPlaceRef.current = undefined\n setInPlaceActive(false)\n }\n }\n\n // No element to edit — the OPAQUE overlay. Built on a frame because\n // the surface it writes into has not rendered yet, which is the race\n // `seededRef` exists for.\n setInPlaceActive(false)\n const raf = requestAnimationFrame(() => {\n const editable = rich ? richRef.current : plainRef.current\n if (!editable) return\n build(editable)\n editable.focus()\n const selection = window.getSelection()\n if (selection) {\n const range = document.createRange()\n range.selectNodeContents(editable)\n if (rich) range.collapse(false)\n selection.removeAllRanges()\n selection.addRange(range)\n }\n seededRef.current = true\n })\n return () => cancelAnimationFrame(raf)\n }, [node, rich, propTarget, anchor])\n\n /**\n * Writes `next` only when it is a different document (AGL-2486).\n *\n * Closing this editor is not by itself an edit. Every branch below\n * rebuilds the WHOLE props object from the surface's DOM, so a commit\n * that changed nothing still produced a fresh object — an undo entry, a\n * node-changed signal, and a co-editing mirror publish, all for an edit\n * the author never made. The mirror is the expensive one: it is cleared\n * only by a successful save, so an unsaved no-op is replayed into every\n * joiner's canvas for `COEDIT_MIRROR_MAX_AGE_MS` (seven days) and each\n * of them opens a document that reads dirty with nothing to see.\n */\n const commitProps = useCallback(\n (node: Aglyn.NodeSchema<any>, next: Record<string, unknown>) => {\n if (isEqual(toJS(node.props), next)) return\n canvas.updateNodeProps(node, next as never)\n },\n [],\n )\n\n const commit = useCallback(() => {\n if (committedRef.current) return\n committedRef.current = true\n const current = inlineTextEdit.node\n // An unbuilt surface is not an emptied one (AGL-2486) — close, do not\n // write. See `seededRef`.\n /**\n * Collected first, WRITTEN LAST (AGL-2486).\n *\n * The markup this computes is correct; the hazard is that it can be\n * undone a moment later. Ending the edit restores the element's\n * original child nodes — deliberately, by reference, so React's fibers\n * keep pointing at live nodes — and that restore must not run in the\n * effect cleanup, i.e. AFTER `updateNodeProps` has already told React\n * to re-render the leaf. In that order React paints the new text and\n * the parked ORIGINAL nodes then go back over the top of it, so an\n * edit reads as never having taken.\n *\n * Worst for formatted text, which is how it was found: a node with\n * `html` renders through `dangerouslySetInnerHTML`, so React does not\n * track those children at all and never corrects them afterwards. The\n * canvas kept the pre-edit markup, the store held the new value, and\n * the break came back every time — until \"Remove formatting\" dropped\n * `html` and the plain `children` finally showed.\n *\n * So the element is given back BEFORE the store is written, and the\n * write is the last thing that happens. React then re-renders onto a\n * subtree that is exactly where it left it.\n */\n let nextWrite: Record<string, unknown> | undefined\n if (current && seededRef.current) {\n // UpdateNodeProps REPLACES the props object — spread the existing\n // props so variant/component/etc. survive the text edit.\n const surface = activeEditable()\n // The surface read once, as the plain reading and — for formatted\n // text — the markup beside it.\n let plain: string | undefined\n let markup: string | undefined\n if (rich && surface) {\n // Pills serialize back to raw tokens BEFORE sanitizing (the\n // sanitizer strips attributes, and pill labels must never\n // reach storage) — on a clone, the live DOM stays intact.\n const clone = surface.cloneNode(true) as HTMLElement\n replacePillsWithTokenText(clone)\n // The toolbar offers no block command on a phrasing-only surface,\n // but a PASTE can still carry one in, and the renderer would strip\n // it — so the commit strips it first and what is stored is what\n // the page will draw.\n const sanitized = withoutCaretStops(\n sanitizeRichText(clone.innerHTML, { phrasingOnly }),\n )\n plain = richTextToPlain(sanitized)\n if (/<[a-z]/i.test(sanitized)) markup = sanitized\n } else if (surface) {\n plain = withoutCaretStops(\n serializeTokenSegments(readTokenSegmentsFromDom(surface)),\n )\n // An emptied contentEditable leaves a stray <br> behind.\n if (plain === '\\n') plain = ''\n }\n const target = inlineTextEdit.propTarget\n if (plain !== undefined && target) {\n // Instance prop override (AGL-1304): the edit rides the\n // INSTANCE's nested propValues, never the grafted leaf (which\n // is not a canvas node). An emptied value REMOVES the key —\n // the graft treats '' as unset anyway, and a cleared override\n // must read as clean, exactly like the style-override layer.\n // Formatting rides `propHtml` beside it, and goes with it.\n const values = {\n ...(current.props?.[\n REUSABLE_INSTANCE_PROP_VALUES_KEY\n ] as Record<string, unknown> | undefined),\n }\n const formatted = {\n ...(current.props?.[\n REUSABLE_INSTANCE_PROP_HTML_KEY\n ] as Record<string, unknown> | undefined),\n }\n if (plain === '') delete values[target.propName]\n else values[target.propName] = plain\n if (plain !== '' && markup) formatted[target.propName] = markup\n else delete formatted[target.propName]\n const nextProps: Record<string, unknown> = {\n ...current.props,\n [REUSABLE_INSTANCE_PROP_VALUES_KEY]: values,\n [REUSABLE_INSTANCE_PROP_HTML_KEY]: formatted,\n }\n // The LAST override cleared: drop the container too, so the\n // stored instance is byte-identical to one never overridden.\n if (!Object.keys(values).length) {\n delete nextProps[REUSABLE_INSTANCE_PROP_VALUES_KEY]\n }\n if (!Object.keys(formatted).length) {\n delete nextProps[REUSABLE_INSTANCE_PROP_HTML_KEY]\n }\n nextWrite = toJS(nextProps) as Record<string, unknown>\n } else if (plain !== undefined && rich) {\n const nextProps: Record<string, unknown> = {\n ...toJS(current.props),\n children: plain,\n }\n // ABSENT, not `''`, when there is no markup (AGL-2486). The\n // renderer gates on `typeof html === 'string' && Boolean(html)`,\n // so the two are the same document to everything that draws it —\n // but `isInitialSame` compares serialized node maps with\n // `isEqual`, and there the empty key is a difference. Writing it\n // onto a node that never had one is what put SAVE on the header\n // of a screen nobody had touched.\n if (markup) nextProps['html'] = markup\n else delete nextProps['html']\n nextWrite = nextProps\n } else if (plain !== undefined) {\n nextWrite = {\n ...toJS(current.props),\n children: plain,\n }\n }\n }\n // Give the element back to React BEFORE the write — see `nextWrite`.\n inPlaceRef.current?.dispose()\n inPlaceRef.current = undefined\n if (current && nextWrite) commitProps(current, nextWrite)\n inlineTextEdit.close()\n }, [rich, phrasingOnly, commitProps, activeEditable])\n\n const cancel = useCallback(() => {\n committedRef.current = true\n inlineTextEdit.close()\n }, [])\n\n /**\n * A mouse edit commits when the text loses focus. A touch edit does not\n * (AGL-4069): on a phone focus comes and goes for reasons that are not\n * the author leaving — the keyboard's own bar, its Done key, the edit\n * menu — and the edit there ends on a real tap away, Escape or Done.\n */\n const handleEditableBlur = useCallback(() => {\n if (menuOpenRef.current) return\n if (touchModeRef.current) return\n commit()\n }, [commit])\n\n /**\n * Ends a touch edit and lets go of the text (AGL-4069). On a phone the\n * keyboard and the edit menu stay up for as long as the text holds focus\n * and a selection, and the element given back is no longer editable — so\n * both would be left hanging over a page the author has finished with.\n */\n const commitAndRelease = useCallback(() => {\n const editable = activeEditable()\n commit()\n if (!editable) return\n const selection = selectionOf(editable)\n if (\n selection &&\n selection.rangeCount > 0 &&\n editable.contains(selection.getRangeAt(0).commonAncestorContainer)\n ) {\n selection.removeAllRanges()\n }\n const focused = editable.ownerDocument.activeElement\n if (focused instanceof HTMLElement && editable.contains(focused)) {\n focused.blur()\n }\n }, [activeEditable, commit])\n\n // Latest `commit` for the document listener below, which must not\n // re-register on every render just to stay current.\n const commitRef = useRef(commit)\n commitRef.current = commit\n const commitAndReleaseRef = useRef(commitAndRelease)\n commitAndReleaseRef.current = commitAndRelease\n\n /**\n * Wires the editing handlers onto the LEAF while it is the surface.\n *\n * Imperatively, because the element belongs to the canvas renderer and\n * not to this component's JSX — the same reason `contentEditable` is set\n * as a DOM property. Registered once per edit and torn down with it.\n *\n * No `input` handler is needed any more, and that absence is the point:\n * the element being typed into IS the element being laid out, so the\n * card, the row and the siblings re-flow on their own. The stand-in that\n * used to reproduce that effect for an overlay is gone with the overlay.\n */\n useEffect(() => {\n const surface = inPlaceActive ? inPlaceRef.current : undefined\n const element = surface?.element\n if (!element) return\n const onKeyDown = (event: Event) =>\n (rich ? handlersRef.current.richKeyDown : handlersRef.current.keyDown)(\n event as unknown as KeyboardEvent<HTMLDivElement>,\n )\n const onBlur = () => handlersRef.current.blur()\n const onClick = (event: Event) =>\n handlersRef.current.click(\n event as unknown as MouseEvent<HTMLDivElement>,\n )\n const onMouseDown = (event: Event) =>\n handlersRef.current.mouseDown(\n event as unknown as MouseEvent<HTMLDivElement>,\n )\n element.addEventListener('keydown', onKeyDown)\n element.addEventListener('blur', onBlur)\n element.addEventListener('click', onClick)\n element.addEventListener('mousedown', onMouseDown)\n return () => {\n element.removeEventListener('keydown', onKeyDown)\n element.removeEventListener('blur', onBlur)\n element.removeEventListener('click', onClick)\n element.removeEventListener('mousedown', onMouseDown)\n }\n }, [inPlaceActive, rich])\n\n /**\n * Click-away commits, because on this canvas blur never arrives\n * (AGL-2486).\n *\n * `commit()` used to be reachable from a click only through `onBlur`,\n * and a click on another element cannot produce one: `DraggableDroppable`\n * registers `mousedown` AND `pointerdown` on every leaf and both begin\n * `e.preventDefault(); e.stopPropagation()`. Preventing a mousedown's\n * default suppresses the focus change it would have caused, so the\n * editable keeps focus and stays open — while the same handler runs\n * `Besigner.focus.handleNodeSelection(node, …)` and moves the selection\n * out from under it. Clicking out \"just selects other elements rather\n * than applying\", and the edit sits in a surface the author has already\n * mentally left. This repo has recorded that exact shape once before:\n * an attribute that commits on blur, discarded by selecting the next\n * node, with the canvas still looking right.\n *\n * A CAPTURE-phase listener on the document is what reaches the commit\n * first: capture runs from the document down, so it is ahead of the\n * leaf's own bubble-phase listener and ahead of the `preventDefault`\n * that would have swallowed the blur. It calls the SAME `commit()` the\n * Done button does — one commit path, one undo entry, and the same\n * no-op guard, rather than a second route into the document.\n *\n * The click is deliberately NOT consumed: committing and then letting\n * the canvas select what was clicked is what every other design tool\n * does, and it is what the author asked for by clicking there.\n *\n * `pointerdown`, not `mousedown`: it is the first of the pair, and\n * `preventDefault` on it suppresses the mouse events that follow, so a\n * `mousedown` listener would never run for a touch or pen edit.\n *\n * Targets inside the canvas retarget to its CLOSED shadow host, which is\n * not inside this overlay, so `contains` reads them as outside — which\n * they are. The portalled insert picker and pill popover ARE outside the\n * overlay in the DOM, and are covered by the same `menuOpenRef` stand-down\n * that already guards commit-on-blur (AGL-586).\n *\n * A FINGER is judged when it lifts, not when it lands (AGL-4069). The\n * selection handles iOS hangs off the ends of selected text sit over the\n * elements next to it, so the touch that grabs one to select more words\n * lands outside the text — and ending the edit there closed the keyboard\n * under an author who was only extending a selection. On touch the press\n * is followed to its end: a still, quick tap ends the edit (or, on the\n * element being edited, places the caret), while a drag, a hold, a press\n * within reach of a selection handle, or a touch the browser takes over\n * for a scroll or a handle drag (`pointercancel`) leaves it open. Inside\n * the canvas the press is also kept from the elements under it until\n * then: a leaf would select itself on the spot, which is not a tap's\n * business until it is known to be one. The tap's own mouse events,\n * which a phone sends after the finger lifts, still select what was\n * tapped — after the edit has ended, as a click does.\n */\n useEffect(() => {\n if (!node) return\n const editing = inPlaceRef.current?.element\n const root = editing?.getRootNode() as ShadowRoot | Document | undefined\n const host =\n root && 'host' in root ? (root as ShadowRoot).host : undefined\n\n const isInsideTheEditor = (target: Node | null): boolean => {\n if (!target) return false\n // Read LIVE, never the value captured when this effect ran: a click\n // inside the text is the author placing a caret, and getting that\n // wrong tears the surface down and rebuilds it on every click, which\n // looks exactly like a caret that will not move.\n const live = inPlaceRef.current?.element\n if (live?.contains(target)) return true\n const overlay = overlayRef.current\n return Boolean(overlay?.contains(target))\n }\n\n /** The touch being followed, and what a tap would mean for it. */\n const press = new TouchPressTracker()\n let pressOnEditedLeaf = false\n\n const handlePointerDownAway = (event: Event) => {\n if (menuOpenRef.current) return\n const target = event.target as Node | null\n // Inside the CLOSED canvas root, an event seen from the document has\n // already been retargeted to the host, so it cannot say whether the\n // click landed on the text being edited or beside it. The listener on\n // the root itself sees the real target and has already decided; this\n // one must not overrule it with a guess.\n if (host && target === host) return\n if (isInsideTheEditor(target)) return\n // A press on the element being edited, beside the text: the text is\n // an inline run as wide as its words (a lone token is a few\n // characters), and the rest of the line is the element around it.\n // That is where an author clicks to put the caret after a token, and\n // it used to read as a click away and close the edit.\n const live = inPlaceRef.current?.element\n const leaf = live?.closest(LEAF_STAMP_SELECTOR)\n const onEditedLeaf = Boolean(\n live &&\n leaf &&\n target instanceof Element &&\n target.closest(LEAF_STAMP_SELECTOR) === leaf,\n )\n if (isTouchPointer(event)) {\n const pointer = event as PointerEvent\n const nearHandle = Boolean(\n live &&\n isNearSelectionHandle(\n { x: pointer.clientX, y: pointer.clientY },\n selectionEndBoxes(selectionOf(live)),\n ),\n )\n press.down(pointer, nearHandle)\n pressOnEditedLeaf = onEditedLeaf\n // Inside the canvas only: chrome outside it keeps its own presses.\n if (root && root !== document && event.currentTarget === root) {\n event.stopPropagation()\n }\n return\n }\n if (onEditedLeaf && live) {\n event.preventDefault()\n placeCaretAtNearEnd(live, event as PointerEvent)\n return\n }\n commitRef.current()\n }\n const handlePointerMove = (event: Event) =>\n press.move(event as PointerEvent)\n const handlePointerCancel = (event: Event) =>\n press.cancel(event as PointerEvent)\n const handlePointerUp = (event: Event) => {\n if (press.up(event as PointerEvent) !== 'tap') return\n const live = inPlaceRef.current?.element\n if (pressOnEditedLeaf && live) {\n placeCaretAtNearEnd(live, event as PointerEvent)\n return\n }\n commitAndReleaseRef.current()\n }\n\n document.addEventListener('pointerdown', handlePointerDownAway, true)\n document.addEventListener('pointermove', handlePointerMove, true)\n document.addEventListener('pointerup', handlePointerUp, true)\n document.addEventListener('pointercancel', handlePointerCancel, true)\n // Second listener, INSIDE the shadow root, for the clicks the first one\n // is blind to — including a click on the very element being edited,\n // which must move the caret rather than end the edit.\n if (root && root !== document) {\n root.addEventListener('pointerdown', handlePointerDownAway, true)\n }\n return () => {\n document.removeEventListener('pointerdown', handlePointerDownAway, true)\n document.removeEventListener('pointermove', handlePointerMove, true)\n document.removeEventListener('pointerup', handlePointerUp, true)\n document.removeEventListener('pointercancel', handlePointerCancel, true)\n if (root && root !== document) {\n root.removeEventListener('pointerdown', handlePointerDownAway, true)\n }\n }\n }, [node, inPlaceActive])\n\n const insertPlainNewline = useCallback(() => {\n const editable = activeEditable()\n const selection = editable ? selectionOf(editable) : null\n if (!selection || selection.rangeCount === 0) return\n const range = selection.getRangeAt(0)\n range.deleteContents()\n const newline = document.createTextNode('\\n')\n range.insertNode(newline)\n range.setStartAfter(newline)\n range.collapse(true)\n selection.removeAllRanges()\n selection.addRange(range)\n }, [activeEditable])\n\n const handleKeyDown = useCallback(\n (event: KeyboardEvent<HTMLDivElement>) => {\n if (event.key === 'Escape') {\n event.preventDefault()\n // An open menu closes first, as Escape does everywhere else; the\n // edit it was opened from stays.\n if (menuOpenRef.current) {\n setInsertMenu(null)\n setPillMenu(null)\n menuOpenRef.current = false\n return\n }\n cancel()\n } else if (event.key === 'Enter' && !event.shiftKey) {\n event.preventDefault()\n commit()\n } else if (event.key === 'Enter') {\n // Browsers fork contentEditable into <div>s on Enter — insert\n // the newline ourselves so reads stay text + pills only.\n event.preventDefault()\n insertPlainNewline()\n }\n },\n [cancel, commit, insertPlainNewline],\n )\n\n const handleRichKeyDown = useCallback(\n (event: KeyboardEvent<HTMLDivElement>) => {\n if (event.key === 'Escape') {\n event.preventDefault()\n // An open menu closes first, as Escape does everywhere else; the\n // edit it was opened from stays.\n if (menuOpenRef.current) {\n setInsertMenu(null)\n setPillMenu(null)\n menuOpenRef.current = false\n return\n }\n cancel()\n } else if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {\n event.preventDefault()\n commit()\n } else if (event.key === 'Enter' && phrasingOnly && !event.shiftKey) {\n // A phrasing-only surface is a control's LABEL — a button, a link,\n // an accordion header. Enter there means \"done\", the same as it\n // does on the plain surface; a browser would otherwise fork the\n // contentEditable into `<div>`s, which is exactly the markup this\n // surface may not hold. Shift+Enter still breaks the line, and a\n // `<br>` is phrasing content.\n event.preventDefault()\n commit()\n }\n },\n [cancel, commit, phrasingOnly],\n )\n\n // Keep the selection inside the editable surface while clicking tools.\n const keepFocus = useCallback((event: MouseEvent) => {\n event.preventDefault()\n }, [])\n\n /**\n * Notes the selection a toolbar press starts from. A tap on a phone can\n * move focus, and the selection with it, before the button's click runs;\n * the command must still apply to the words that were selected.\n */\n const noteToolbarSelection = useCallback(() => {\n const editable = activeEditable()\n const selection = editable ? selectionOf(editable) : null\n const range =\n selection && selection.rangeCount > 0 ? selection.getRangeAt(0) : null\n toolbarRangeRef.current =\n range &&\n editable &&\n editable.contains(range.startContainer) &&\n editable.contains(range.endContainer)\n ? range.cloneRange()\n : null\n }, [activeEditable])\n\n /** Puts the noted selection back if the press lost it. */\n const restoreToolbarSelection = useCallback(() => {\n const editable = activeEditable()\n const saved = toolbarRangeRef.current\n toolbarRangeRef.current = null\n if (!editable || !saved) return\n const selection = selectionOf(editable)\n const current =\n selection && selection.rangeCount > 0 ? selection.getRangeAt(0) : null\n if (current && editable.contains(current.commonAncestorContainer)) return\n editable.focus()\n const again = selectionOf(editable)\n if (!again) return\n again.removeAllRanges()\n again.addRange(saved)\n }, [activeEditable])\n\n const exec = useCallback(\n (command: string) => () => {\n restoreToolbarSelection()\n // ExecCommand is deprecated but universally supported and keeps this\n // dependency-free; the output is normalized by the sanitizer anyway.\n document.execCommand(command)\n activeEditable()?.focus()\n },\n [activeEditable, restoreToolbarSelection],\n )\n\n const handleLink = useCallback(() => {\n restoreToolbarSelection()\n const saved = (() => {\n const editable = activeEditable()\n const selection = editable ? selectionOf(editable) : null\n return selection && selection.rangeCount > 0\n ? selection.getRangeAt(0).cloneRange()\n : null\n })()\n const url = window.prompt('Link URL (https://…)')\n // The prompt takes focus; the link goes on the words it was asked for.\n if (url) {\n toolbarRangeRef.current = saved\n restoreToolbarSelection()\n document.execCommand('createLink', false, url)\n }\n activeEditable()?.focus()\n }, [activeEditable, restoreToolbarSelection])\n\n /** Pill clicks (delegated): offer Replace/Remove (AGL-586). */\n const handleEditableClick = useCallback(\n (event: MouseEvent<HTMLDivElement>) => {\n const pill = (event.target as HTMLElement).closest?.(\n `[${TOKEN_PILL_ATTR}]`,\n ) as HTMLElement | null\n if (!pill || !event.currentTarget.contains(pill)) return\n menuOpenRef.current = true\n setPillMenu(pill)\n },\n [],\n )\n\n // Pills are non-editable islands — a mousedown on one would move\n // focus out of the editable and trigger commit-on-blur.\n const handleEditableMouseDown = useCallback(\n (event: MouseEvent<HTMLDivElement>) => {\n const pill = (event.target as HTMLElement).closest?.(\n `[${TOKEN_PILL_ATTR}]`,\n )\n if (pill) event.preventDefault()\n },\n [],\n )\n\n handlersRef.current = {\n keyDown: handleKeyDown,\n richKeyDown: handleRichKeyDown,\n blur: handleEditableBlur,\n click: handleEditableClick,\n mouseDown: handleEditableMouseDown,\n }\n\n /** The toolbar {x}: captures the live selection, opens the picker. */\n const handleInsertOpen = useCallback(\n (event: MouseEvent<HTMLElement>) => {\n const editable = activeEditable()\n const selection = editable ? selectionOf(editable) : null\n const range =\n selection && selection.rangeCount > 0\n ? selection.getRangeAt(0)\n : null\n savedRangeRef.current =\n range &&\n editable &&\n editable.contains(range.startContainer) &&\n editable.contains(range.endContainer)\n ? range.cloneRange()\n : null\n menuOpenRef.current = true\n setInsertMenu({ anchorEl: event.currentTarget, replacePill: null })\n },\n [activeEditable],\n )\n\n const closeMenus = useCallback(() => {\n setInsertMenu(null)\n setPillMenu(null)\n menuOpenRef.current = false\n activeEditable()?.focus()\n }, [activeEditable])\n\n const handleInsertPick = useCallback(\n (token: string) => {\n const editable = activeEditable()\n const replacePill = insertMenu?.replacePill ?? null\n setInsertMenu(null)\n menuOpenRef.current = false\n if (!editable) return\n const pill = createTokenPillElement(\n document,\n token,\n resolveTokenLabel(token, labelContextRef.current),\n )\n if (replacePill && editable.contains(replacePill)) {\n replacePill.replaceWith(pill)\n } else {\n const range = savedRangeRef.current\n if (\n range &&\n editable.contains(range.startContainer) &&\n editable.contains(range.endContainer)\n ) {\n range.deleteContents()\n range.insertNode(pill)\n } else {\n editable.appendChild(pill)\n }\n }\n savedRangeRef.current = null\n paintTokenPills(editable, themeRef.current)\n addCaretStops(editable)\n editable.focus()\n // Caret lands just after the pill, ready to keep typing.\n const selection = selectionOf(editable)\n if (selection) {\n const after = document.createRange()\n after.setStartAfter(pill)\n after.collapse(true)\n selection.removeAllRanges()\n selection.addRange(after)\n }\n },\n [activeEditable, insertMenu],\n )\n\n const handlePillReplace = useCallback(() => {\n const pill = pillMenu\n setPillMenu(null)\n if (!pill) {\n menuOpenRef.current = false\n return\n }\n // Keep menuOpenRef up — the insert picker opens next.\n setInsertMenu({ anchorEl: pill, replacePill: pill })\n }, [pillMenu])\n\n const handlePillRemove = useCallback(() => {\n pillMenu?.remove()\n closeMenus()\n }, [pillMenu, closeMenus])\n\n // Fingers get the larger target.\n const toolSize = (t: Theme) => t.spacing(touchMode ? 5 : 3.5)\n\n const insertButton = (\n <IconButton\n size=\"small\"\n title=\"Insert data\"\n aria-label=\"Insert data token\"\n onMouseDown={keepFocus}\n onClick={handleInsertOpen}\n sx={{ width: toolSize, height: toolSize, borderRadius: 0.5 }}\n >\n <MdiIcon path={mdiCodeBraces.path} fontSize=\"small\" />\n </IconButton>\n )\n\n if (!node || !rect) return null\n\n // Read at render, which `useAnchoredRect` makes safe: it re-renders on\n // every scroll and resize, so these are never a stale snapshot. The toolbar\n // sits 40px ABOVE the surface, so the top margin has to clear it or the\n // controls go off-screen while the editable stays on it.\n const viewportWidth =\n typeof window === 'undefined' ? Infinity : window.innerWidth\n const viewportHeight =\n typeof window === 'undefined' ? Infinity : window.innerHeight\n // The fallback overlay is ALWAYS the opaque box (AGL-2486). It exists\n // only for an edit with no element to type into, and an element that is\n // not there cannot re-flow — so a see-through surface over it would be\n // exactly what the invariant forbids. In-place editing needs no surface\n // here at all: the leaf is the surface, and this component renders only\n // the toolbar.\n //\n // Built as plain records and cast ONCE, the way `tokenPillContainerSx`\n // is: MUI's `sx` union cannot absorb a computed spread and reports every\n // neighbouring key as the error instead.\n const surfaceSx: Record<string, unknown> = BOXED_SURFACE_SX\n const richSurfaceSx = {\n width: '100%',\n minHeight: live.height,\n boxSizing: 'border-box',\n font: 'inherit',\n ...surfaceSx,\n '& a': { pointerEvents: 'none' },\n ...tokenPillContainerSx,\n } as SystemStyleObject<Theme>\n const plainSurfaceSx = {\n width: '100%',\n minHeight: live.height,\n boxSizing: 'border-box',\n font: 'inherit',\n ...surfaceSx,\n // After the anchor's type, never from it: `pre-wrap` is what makes a\n // Shift+Enter newline visible while typing.\n whiteSpace: 'pre-wrap',\n wordBreak: 'break-word',\n ...tokenPillContainerSx,\n } as SystemStyleObject<Theme>\n const minWidth = Math.max(live.width, 120)\n const TOOLBAR_CLEARANCE = 48\n const KEEP_VISIBLE = 80\n // A finger's toolbar docks to the visible area, clear of the keyboard and\n // of the edit menu iOS puts by the selection (AGL-4069); a mouse's hangs\n // just above the text, as it always has.\n const docked =\n touchMode && visibleArea\n ? placeDockedToolbar(\n live,\n visibleArea,\n toolbarHeight,\n parseFloat(theme.spacing(1)) || 0,\n )\n : undefined\n const toolbarSx = docked\n ? {\n position: 'fixed',\n top: docked.top,\n left: docked.left,\n maxWidth: docked.maxWidth,\n overflowX: 'auto',\n }\n : { position: 'absolute', top: -40, left: 0 }\n\n return (\n <Box\n ref={overlayRef}\n data-aglyn=\"overlay:inline-text-editor\"\n sx={{\n position: 'fixed',\n left: clampToViewport(live.left, minWidth, viewportWidth),\n top: clampToViewport(\n live.top,\n KEEP_VISIBLE,\n viewportHeight,\n TOOLBAR_CLEARANCE,\n ),\n minWidth,\n maxWidth: '90vw',\n zIndex: (theme) => theme.zIndex.modal,\n }}\n >\n {/* The toolbar survives in-place editing — B / I / U, lists, link\n and the {} token control are the reason this editor exists at\n all, and it is chrome, not text, so it stays an overlay above\n the run being edited rather than inside it. */}\n <Paper\n ref={toolbarRef}\n elevation={4}\n data-aglyn=\"overlay:inline-text-toolbar\"\n data-docked={docked?.edge}\n onPointerDownCapture={noteToolbarSelection}\n sx={\n {\n ...toolbarSx,\n px: 0.5,\n py: 0.25,\n display: 'flex',\n gap: 0.25,\n alignItems: 'center',\n } as SystemStyleObject<Theme>\n }\n >\n {rich\n ? RICH_COMMANDS.filter(({ group }) =>\n commandGroups.has(group),\n ).map(({ command, label, title }) => (\n <IconButton\n key={command}\n size=\"small\"\n title={title}\n onMouseDown={keepFocus}\n onClick={exec(command)}\n sx={{\n width: toolSize,\n height: toolSize,\n fontSize: 13,\n fontWeight: 700,\n fontStyle: command === 'italic' ? 'italic' : undefined,\n textDecoration:\n command === 'underline' ? 'underline' : undefined,\n borderRadius: 0.5,\n }}\n >\n {label}\n </IconButton>\n ))\n : null}\n {rich && commandGroups.has(RICH_TEXT_COMMANDS.LINK) ? (\n <IconButton\n size=\"small\"\n title=\"Insert link\"\n onMouseDown={keepFocus}\n onClick={handleLink}\n sx={{\n width: toolSize,\n height: toolSize,\n fontSize: 13,\n borderRadius: 0.5,\n }}\n >\n {'\\u{1F517}'}\n </IconButton>\n ) : null}\n {insertButton}\n <Button\n size=\"small\"\n color=\"primary\"\n onMouseDown={keepFocus}\n onClick={touchMode ? commitAndRelease : commit}\n >\n {'Done'}\n </Button>\n </Paper>\n {/* No surface at all when the leaf is the surface (AGL-2486). */}\n {inPlaceActive ? null : rich ? (\n <Box\n ref={richRef}\n contentEditable\n suppressContentEditableWarning\n role=\"textbox\"\n aria-label=\"Edit rich text\"\n onKeyDown={handleRichKeyDown}\n onBlur={handleEditableBlur}\n onClick={handleEditableClick}\n onMouseDown={handleEditableMouseDown}\n sx={richSurfaceSx}\n />\n ) : (\n <Box\n ref={plainRef}\n contentEditable\n suppressContentEditableWarning\n role=\"textbox\"\n aria-label=\"Edit text\"\n onKeyDown={handleKeyDown}\n onBlur={handleEditableBlur}\n onClick={handleEditableClick}\n onMouseDown={handleEditableMouseDown}\n sx={plainSurfaceSx}\n />\n )}\n <InsertTokenMenu\n anchorEl={insertMenu?.anchorEl ?? null}\n open={Boolean(insertMenu)}\n onClose={closeMenus}\n options={insertOptions}\n onInsert={handleInsertPick}\n />\n <TokenPillPopover\n anchorEl={pillMenu}\n token={pillMenu?.getAttribute(TOKEN_PILL_ATTR) ?? ''}\n onClose={closeMenus}\n onReplace={handlePillReplace}\n onRemove={handlePillRemove}\n />\n </Box>\n )\n },\n)\nInlineTextEditorComponent.displayName = 'InlineTextEditorComponent'\n\nexport default InlineTextEditorComponent\n"],"names":["canvas","FEATURE_FLAG","REUSABLE_INSTANCE_PROP_HTML_KEY","REUSABLE_INSTANCE_PROP_VALUES_KEY","RICH_TEXT_COMMANDS","mdiCodeBraces","MdiIcon","Box","Button","IconButton","Paper","useTheme","isEqual","toJS","observer","useCallback","useEffect","useLayoutEffect","useRef","useState","clampToViewport","useAnchoredRect","useInsertTokenOptions","addCaretStops","beginInPlaceEdit","selectionOf","withoutCaretStops","inlineTextEdit","RICH_COMMANDS","richTextCommandGroups","richTextToPlain","sanitizeRichText","textToHtml","createTokenPillElement","materializeTokenPillsInElement","readTokenSegmentsFromDom","replacePillsWithTokenText","TOKEN_PILL_ATTR","isNearSelectionHandle","isTouchPointer","placeDockedToolbar","prefersTouchEditing","readVisibleArea","selectionEndBoxes","TouchPressTracker","parseTokenSegments","resolveTokenLabel","serializeTokenSegments","InsertTokenMenu","paintTokenPills","TokenPillPopover","tokenPillContainerSx","LEAF_STAMP_SELECTOR","placeCaretAtNearEnd","editable","press","lines","Array","from","getClientRects","first","atStart","Boolean","clientY","top","bottom","clientX","left","focus","selection","range","ownerDocument","createRange","selectNodeContents","collapse","removeAllRanges","addRange","EMPTY_RECT","width","height","BOXED_SURFACE_SX","p","bgcolor","color","border","borderColor","borderRadius","outline","boxShadow","InlineTextEditorComponent","node","rect","propTarget","anchor","live","inPlaceActive","setInPlaceActive","overlayRef","plainRef","richRef","committedRef","seededRef","inPlaceRef","undefined","handlersRef","keyDown","_e","richKeyDown","blur","click","mouseDown","menuOpenRef","savedRangeRef","insertMenu","setInsertMenu","pillMenu","setPillMenu","lastPressWasTouchRef","touchMode","setTouchMode","touchModeRef","current","visibleArea","setVisibleArea","toolbarRef","toolbarHeight","setToolbarHeight","toolbarRangeRef","options","insertOptions","labelContext","labelContextRef","theme","themeRef","rich","componentSchema","flags","richTextEditable","DISABLED","ENABLED","commandGroups","schema","phrasingOnly","has","LIST","LINK","activeEditable","element","notePress","event","touch","document","addEventListener","removeEventListener","window","update","visual","visualViewport","passive","capture","offsetHeight","props","resolvedProps","text","initialText","children","resolve","token","markup","initialHtml","html","build","target","initial","innerHTML","textContent","segment","type","appendChild","value","createTextNode","surface","dispose","raf","requestAnimationFrame","getSelection","cancelAnimationFrame","commitProps","next","updateNodeProps","commit","nextWrite","plain","clone","cloneNode","sanitized","test","values","formatted","propName","nextProps","Object","keys","length","close","cancel","handleEditableBlur","commitAndRelease","rangeCount","contains","getRangeAt","commonAncestorContainer","focused","activeElement","HTMLElement","commitRef","commitAndReleaseRef","onKeyDown","onBlur","onClick","onMouseDown","editing","root","getRootNode","host","isInsideTheEditor","overlay","pressOnEditedLeaf","handlePointerDownAway","leaf","closest","onEditedLeaf","Element","pointer","nearHandle","x","y","down","currentTarget","stopPropagation","preventDefault","handlePointerMove","move","handlePointerCancel","handlePointerUp","up","insertPlainNewline","deleteContents","newline","insertNode","setStartAfter","handleKeyDown","key","shiftKey","handleRichKeyDown","metaKey","ctrlKey","keepFocus","noteToolbarSelection","startContainer","endContainer","cloneRange","restoreToolbarSelection","saved","again","exec","command","execCommand","handleLink","url","prompt","handleEditableClick","pill","handleEditableMouseDown","handleInsertOpen","anchorEl","replacePill","closeMenus","handleInsertPick","replaceWith","after","handlePillReplace","handlePillRemove","remove","toolSize","t","spacing","insertButton","size","title","aria-label","sx","path","fontSize","viewportWidth","Infinity","innerWidth","viewportHeight","innerHeight","surfaceSx","richSurfaceSx","minHeight","boxSizing","font","pointerEvents","plainSurfaceSx","whiteSpace","wordBreak","minWidth","Math","max","TOOLBAR_CLEARANCE","KEEP_VISIBLE","docked","parseFloat","toolbarSx","position","maxWidth","overflowX","ref","data-aglyn","zIndex","modal","elevation","data-docked","edge","onPointerDownCapture","px","py","display","gap","alignItems","filter","group","map","label","fontWeight","fontStyle","textDecoration","contentEditable","suppressContentEditableWarning","role","open","onClose","onInsert","getAttribute","onReplace","onRemove","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;;AAGD,SACEA,MAAM,EACNC,YAAY,EACZC,+BAA+B,EAC/BC,iCAAiC,EACjCC,kBAAkB,QACb,eAAc;AACrB,SAASC,aAAa,QAAQ,yBAAwB;AACtD,SAASC,OAAO,QAAQ,uBAAsB;AAC9C,SAASC,GAAG,EAAEC,MAAM,EAAEC,UAAU,EAAEC,KAAK,EAAEC,QAAQ,QAAQ,gBAAe;AAGxE,OAAOC,aAAa,uBAAsB;AAC1C,SAASC,IAAI,QAAQ,OAAM;AAC3B,SAASC,QAAQ,QAAQ,kBAAiB;AAC1C,SAGEC,WAAW,EACXC,SAAS,EACTC,eAAe,EACfC,MAAM,EACNC,QAAQ,QACH,QAAO;AACd,SAASC,eAAe,EAAEC,eAAe,QAAQ,gCAA4B;AAC7E,OAAOC,2BAA2B,uCAAmC;AACrE,SACEC,aAAa,EACbC,gBAAgB,EAEhBC,WAAW,EACXC,iBAAiB,QACZ,oCAAgC;AACvC,SAASC,cAAc,QAAQ,qCAAiC;AAChE,SACEC,aAAa,EACbC,qBAAqB,QAChB,iCAA6B;AACpC,SACEC,eAAe,EACfC,gBAAgB,EAChBC,UAAU,QACL,iCAA6B;AACpC,SACEC,sBAAsB,EACtBC,8BAA8B,EAC9BC,wBAAwB,EACxBC,yBAAyB,EACzBC,eAAe,QACV,iCAA6B;AACpC,SACEC,qBAAqB,EACrBC,cAAc,EACdC,kBAAkB,EAClBC,mBAAmB,EACnBC,e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8B;gBAC9BC,MAAK;gBACLnD,cAAW;gBACXzE,WAAWkC;gBACXjC,QAAQZ;gBACRa,SAASoD;gBACTnD,aAAaqD;gBACbkB,IAAIc;;0BAGR,KAACjQ;gBACCmO,QAAQ,WAAElK,8BAAAA,WAAYkK,QAAQ,oBAAI;gBAClCmE,MAAMxR,QAAQmD;gBACdsO,SAASlE;gBACTrJ,SAASC;gBACTuN,UAAUlE;;0BAEZ,KAACpO;gBACCiO,UAAUhK;gBACVoD,KAAK,WAAEpD,4BAAAA,SAAUsO,YAAY,CAACpT,oCAAoB;gBAClDkT,SAASlE;gBACTqE,WAAWjE;gBACXkE,UAAUjE;;;;AAIlB,GACD;AACDjM,0BAA0BmQ,WAAW,GAAG;AAExC,eAAenQ,0BAAyB"}
@@ -0,0 +1,126 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * The rules for editing canvas text in place with a finger (AGL-4069).
19
+ *
20
+ * A mouse ends an edit the moment it presses somewhere else, and that is
21
+ * right for a mouse: a press is a decision. A finger's press is not. On a
22
+ * phone the same touch can become a tap, a scroll, a long press that selects
23
+ * a word, or a drag of one of the selection handles iOS hangs off the ends of
24
+ * the selected text. Those handles sit OUTSIDE the text, over whatever is
25
+ * next to it, so the press that grabs one lands on another element. Ending
26
+ * the edit on that press is what closed the keyboard under an author who was
27
+ * only selecting more words.
28
+ *
29
+ * So on touch the decision waits for the finger to come up, and only a real
30
+ * tap ends the edit: down and up close together in place and time, not on a
31
+ * selection handle, and not taken over by the browser (a scroll or a handle
32
+ * drag cancels the pointer).
33
+ */
34
+ /** The furthest a finger may slide and still be tapping, in px. */
35
+ export declare const TOUCH_TAP_SLOP_PX = 10;
36
+ /** The longest a press may last and still be a tap, in ms; longer is a hold. */
37
+ export declare const TOUCH_TAP_MAX_MS = 500;
38
+ /**
39
+ * How far from either end of the selection a press counts as reaching for a
40
+ * selection handle, in px. iOS draws the knob a few points past the text and
41
+ * takes touches well around it.
42
+ */
43
+ export declare const SELECTION_HANDLE_REACH_PX = 32;
44
+ /** A pointer event's input kind, as the edit's exit rules see it. */
45
+ export declare function isTouchPointer(event: Event): boolean;
46
+ /** Whether the device's main pointer is a finger (a phone or a tablet). */
47
+ export declare function prefersTouchEditing(win: Window | undefined): boolean;
48
+ interface Point {
49
+ x: number;
50
+ y: number;
51
+ }
52
+ interface Box {
53
+ left: number;
54
+ top: number;
55
+ width: number;
56
+ height: number;
57
+ }
58
+ /**
59
+ * The boxes of a selection's two ends — where iOS hangs its handles. A
60
+ * collapsed selection (a caret) has no handles, so none.
61
+ */
62
+ export declare function selectionEndBoxes(selection: Selection | null): Box[];
63
+ /** Whether `point` is within reach of a selection handle. */
64
+ export declare function isNearSelectionHandle(point: Point, ends: Box[], reach?: number): boolean;
65
+ /** What became of a touch that started outside the text being edited. */
66
+ export type TouchPressOutcome = 'tap' | 'not-a-tap';
67
+ /**
68
+ * Follows ONE touch from down to up and says whether it was a real tap.
69
+ *
70
+ * Fed raw pointer events; ignores every pointer but the one it started with.
71
+ * `onHandle` presses — a touch that came down within reach of a selection
72
+ * handle — never count as taps, even when they do not move: lifting a finger
73
+ * off a handle is not a request to stop editing.
74
+ */
75
+ export declare class TouchPressTracker {
76
+ private press;
77
+ /** Starts following `event`'s pointer. A press near a handle is not followed. */
78
+ down(event: PointerEvent, nearHandle: boolean): void;
79
+ move(event: PointerEvent): void;
80
+ /** The browser took the touch over (a scroll, a handle drag): no tap. */
81
+ cancel(event?: PointerEvent): void;
82
+ /** The finger came up; whether that made a tap. Ends the follow. */
83
+ up(event: PointerEvent): TouchPressOutcome | undefined;
84
+ get following(): boolean;
85
+ }
86
+ /** The part of the page the author can actually see, in fixed coordinates. */
87
+ export interface VisibleArea {
88
+ left: number;
89
+ top: number;
90
+ width: number;
91
+ height: number;
92
+ }
93
+ /**
94
+ * The visible area: the visual viewport where the browser has one.
95
+ *
96
+ * On a phone the on-screen keyboard covers the bottom of the LAYOUT viewport
97
+ * without shrinking it, and iOS pans the page under it to keep the caret in
98
+ * view. `position: fixed` is laid out against the layout viewport, so an
99
+ * overlay placed by `innerHeight` can sit behind the keyboard or above the
100
+ * top of the screen. The visual viewport is the part that is really showing;
101
+ * its offsets put it in the same coordinates `position: fixed` uses.
102
+ */
103
+ export declare function readVisibleArea(win: Window | undefined): VisibleArea;
104
+ export interface DockedToolbarPlacement {
105
+ /** Which edge of the visible area the toolbar sits on. */
106
+ edge: 'top' | 'bottom';
107
+ left: number;
108
+ top: number;
109
+ maxWidth: number;
110
+ }
111
+ /**
112
+ * Where the text toolbar goes while a finger edits: docked to an edge of the
113
+ * visible area — just above the keyboard, unless the text being edited is
114
+ * down there, and then the top.
115
+ *
116
+ * Not above the text, where a mouse finds it. iOS puts its own Cut / Copy /
117
+ * Paste menu right there, over anything the page draws, so a toolbar
118
+ * hanging off the top of the text is hidden whenever the author selects a
119
+ * word — which is exactly when they want Bold. Above the keyboard is where a
120
+ * phone's formatting bar lives, it is clear of that menu (iOS hangs the menu
121
+ * next to the selection, and the selection is in the text), and the bottom
122
+ * of the visible area IS the top of the keyboard, so the bar is never
123
+ * behind it. It moves to the top only when it would cover the text itself.
124
+ */
125
+ export declare function placeDockedToolbar(text: Box, area: VisibleArea, toolbarHeight: number, gap: number): DockedToolbarPlacement;
126
+ export {};
@@ -0,0 +1,188 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ /**
17
+ * The rules for editing canvas text in place with a finger (AGL-4069).
18
+ *
19
+ * A mouse ends an edit the moment it presses somewhere else, and that is
20
+ * right for a mouse: a press is a decision. A finger's press is not. On a
21
+ * phone the same touch can become a tap, a scroll, a long press that selects
22
+ * a word, or a drag of one of the selection handles iOS hangs off the ends of
23
+ * the selected text. Those handles sit OUTSIDE the text, over whatever is
24
+ * next to it, so the press that grabs one lands on another element. Ending
25
+ * the edit on that press is what closed the keyboard under an author who was
26
+ * only selecting more words.
27
+ *
28
+ * So on touch the decision waits for the finger to come up, and only a real
29
+ * tap ends the edit: down and up close together in place and time, not on a
30
+ * selection handle, and not taken over by the browser (a scroll or a handle
31
+ * drag cancels the pointer).
32
+ */ /** The furthest a finger may slide and still be tapping, in px. */ export const TOUCH_TAP_SLOP_PX = 10;
33
+ /** The longest a press may last and still be a tap, in ms; longer is a hold. */ export const TOUCH_TAP_MAX_MS = 500;
34
+ /**
35
+ * How far from either end of the selection a press counts as reaching for a
36
+ * selection handle, in px. iOS draws the knob a few points past the text and
37
+ * takes touches well around it.
38
+ */ export const SELECTION_HANDLE_REACH_PX = 32;
39
+ /** A pointer event's input kind, as the edit's exit rules see it. */ export function isTouchPointer(event) {
40
+ const type = event.pointerType;
41
+ return type === 'touch' || type === 'pen';
42
+ }
43
+ /** Whether the device's main pointer is a finger (a phone or a tablet). */ export function prefersTouchEditing(win) {
44
+ if (!win || typeof win.matchMedia !== 'function') return false;
45
+ try {
46
+ return win.matchMedia('(pointer: coarse)').matches;
47
+ } catch (unused) {
48
+ return false;
49
+ }
50
+ }
51
+ function distanceToBox(point, box) {
52
+ const dx = Math.max(box.left - point.x, 0, point.x - (box.left + box.width));
53
+ const dy = Math.max(box.top - point.y, 0, point.y - (box.top + box.height));
54
+ return Math.hypot(dx, dy);
55
+ }
56
+ /**
57
+ * The boxes of a selection's two ends — where iOS hangs its handles. A
58
+ * collapsed selection (a caret) has no handles, so none.
59
+ */ export function selectionEndBoxes(selection) {
60
+ if (!selection || selection.rangeCount === 0 || selection.isCollapsed) {
61
+ return [];
62
+ }
63
+ const range = selection.getRangeAt(0);
64
+ if (typeof range.getClientRects !== 'function') return [];
65
+ const rects = Array.from(range.getClientRects()).filter((rect)=>rect.width > 0 || rect.height > 0);
66
+ if (!rects.length) return [];
67
+ const first = rects[0];
68
+ const last = rects[rects.length - 1];
69
+ return [
70
+ {
71
+ left: first.left,
72
+ top: first.top,
73
+ width: 0,
74
+ height: first.height
75
+ },
76
+ {
77
+ left: last.left + last.width,
78
+ top: last.top,
79
+ width: 0,
80
+ height: last.height
81
+ }
82
+ ];
83
+ }
84
+ /** Whether `point` is within reach of a selection handle. */ export function isNearSelectionHandle(point, ends, reach = SELECTION_HANDLE_REACH_PX) {
85
+ return ends.some((end)=>distanceToBox(point, end) <= reach);
86
+ }
87
+ /**
88
+ * Follows ONE touch from down to up and says whether it was a real tap.
89
+ *
90
+ * Fed raw pointer events; ignores every pointer but the one it started with.
91
+ * `onHandle` presses — a touch that came down within reach of a selection
92
+ * handle — never count as taps, even when they do not move: lifting a finger
93
+ * off a handle is not a request to stop editing.
94
+ */ export class TouchPressTracker {
95
+ /** Starts following `event`'s pointer. A press near a handle is not followed. */ down(event, nearHandle) {
96
+ this.press = nearHandle ? undefined : {
97
+ id: event.pointerId,
98
+ x: event.clientX,
99
+ y: event.clientY,
100
+ at: event.timeStamp,
101
+ moved: false
102
+ };
103
+ }
104
+ move(event) {
105
+ const press = this.press;
106
+ if (!press || event.pointerId !== press.id) return;
107
+ if (Math.hypot(event.clientX - press.x, event.clientY - press.y) > TOUCH_TAP_SLOP_PX) {
108
+ press.moved = true;
109
+ }
110
+ }
111
+ /** The browser took the touch over (a scroll, a handle drag): no tap. */ cancel(event) {
112
+ if (event && this.press && event.pointerId !== this.press.id) return;
113
+ this.press = undefined;
114
+ }
115
+ /** The finger came up; whether that made a tap. Ends the follow. */ up(event) {
116
+ const press = this.press;
117
+ if (!press || event.pointerId !== press.id) return undefined;
118
+ this.press = undefined;
119
+ const moved = press.moved || Math.hypot(event.clientX - press.x, event.clientY - press.y) > TOUCH_TAP_SLOP_PX;
120
+ const held = event.timeStamp - press.at > TOUCH_TAP_MAX_MS;
121
+ return moved || held ? 'not-a-tap' : 'tap';
122
+ }
123
+ get following() {
124
+ return Boolean(this.press);
125
+ }
126
+ constructor(){
127
+ this.press = undefined;
128
+ }
129
+ }
130
+ /**
131
+ * The visible area: the visual viewport where the browser has one.
132
+ *
133
+ * On a phone the on-screen keyboard covers the bottom of the LAYOUT viewport
134
+ * without shrinking it, and iOS pans the page under it to keep the caret in
135
+ * view. `position: fixed` is laid out against the layout viewport, so an
136
+ * overlay placed by `innerHeight` can sit behind the keyboard or above the
137
+ * top of the screen. The visual viewport is the part that is really showing;
138
+ * its offsets put it in the same coordinates `position: fixed` uses.
139
+ */ export function readVisibleArea(win) {
140
+ if (!win) return {
141
+ left: 0,
142
+ top: 0,
143
+ width: Infinity,
144
+ height: Infinity
145
+ };
146
+ const visual = win.visualViewport;
147
+ if (visual) {
148
+ return {
149
+ left: visual.offsetLeft,
150
+ top: visual.offsetTop,
151
+ width: visual.width,
152
+ height: visual.height
153
+ };
154
+ }
155
+ return {
156
+ left: 0,
157
+ top: 0,
158
+ width: win.innerWidth,
159
+ height: win.innerHeight
160
+ };
161
+ }
162
+ /**
163
+ * Where the text toolbar goes while a finger edits: docked to an edge of the
164
+ * visible area — just above the keyboard, unless the text being edited is
165
+ * down there, and then the top.
166
+ *
167
+ * Not above the text, where a mouse finds it. iOS puts its own Cut / Copy /
168
+ * Paste menu right there, over anything the page draws, so a toolbar
169
+ * hanging off the top of the text is hidden whenever the author selects a
170
+ * word — which is exactly when they want Bold. Above the keyboard is where a
171
+ * phone's formatting bar lives, it is clear of that menu (iOS hangs the menu
172
+ * next to the selection, and the selection is in the text), and the bottom
173
+ * of the visible area IS the top of the keyboard, so the bar is never
174
+ * behind it. It moves to the top only when it would cover the text itself.
175
+ */ export function placeDockedToolbar(text, area, toolbarHeight, gap) {
176
+ const covers = (top)=>text.top < top + toolbarHeight + gap && text.top + text.height > top - gap;
177
+ const bottom = area.top + area.height - toolbarHeight - gap;
178
+ const top = area.top + gap;
179
+ const edge = covers(bottom) && !covers(top) ? 'top' : 'bottom';
180
+ return {
181
+ edge,
182
+ left: area.left + gap,
183
+ top: Math.max(area.top, edge === 'top' ? top : bottom),
184
+ maxWidth: Math.max(0, area.width - gap * 2)
185
+ };
186
+ }
187
+
188
+ //# sourceMappingURL=touch-text-edit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/besigner/feature/designer/src/lib/utils/touch-text-edit.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The rules for editing canvas text in place with a finger (AGL-4069).\n *\n * A mouse ends an edit the moment it presses somewhere else, and that is\n * right for a mouse: a press is a decision. A finger's press is not. On a\n * phone the same touch can become a tap, a scroll, a long press that selects\n * a word, or a drag of one of the selection handles iOS hangs off the ends of\n * the selected text. Those handles sit OUTSIDE the text, over whatever is\n * next to it, so the press that grabs one lands on another element. Ending\n * the edit on that press is what closed the keyboard under an author who was\n * only selecting more words.\n *\n * So on touch the decision waits for the finger to come up, and only a real\n * tap ends the edit: down and up close together in place and time, not on a\n * selection handle, and not taken over by the browser (a scroll or a handle\n * drag cancels the pointer).\n */\n\n/** The furthest a finger may slide and still be tapping, in px. */\nexport const TOUCH_TAP_SLOP_PX = 10\n\n/** The longest a press may last and still be a tap, in ms; longer is a hold. */\nexport const TOUCH_TAP_MAX_MS = 500\n\n/**\n * How far from either end of the selection a press counts as reaching for a\n * selection handle, in px. iOS draws the knob a few points past the text and\n * takes touches well around it.\n */\nexport const SELECTION_HANDLE_REACH_PX = 32\n\n/** A pointer event's input kind, as the edit's exit rules see it. */\nexport function isTouchPointer(event: Event): boolean {\n const type = (event as PointerEvent).pointerType\n return type === 'touch' || type === 'pen'\n}\n\n/** Whether the device's main pointer is a finger (a phone or a tablet). */\nexport function prefersTouchEditing(win: Window | undefined): boolean {\n if (!win || typeof win.matchMedia !== 'function') return false\n try {\n return win.matchMedia('(pointer: coarse)').matches\n } catch {\n return false\n }\n}\n\ninterface Point {\n x: number\n y: number\n}\n\ninterface Box {\n left: number\n top: number\n width: number\n height: number\n}\n\nfunction distanceToBox(point: Point, box: Box): number {\n const dx = Math.max(box.left - point.x, 0, point.x - (box.left + box.width))\n const dy = Math.max(box.top - point.y, 0, point.y - (box.top + box.height))\n return Math.hypot(dx, dy)\n}\n\n/**\n * The boxes of a selection's two ends — where iOS hangs its handles. A\n * collapsed selection (a caret) has no handles, so none.\n */\nexport function selectionEndBoxes(selection: Selection | null): Box[] {\n if (!selection || selection.rangeCount === 0 || selection.isCollapsed) {\n return []\n }\n const range = selection.getRangeAt(0)\n if (typeof range.getClientRects !== 'function') return []\n const rects = Array.from(range.getClientRects()).filter(\n (rect) => rect.width > 0 || rect.height > 0,\n )\n if (!rects.length) return []\n const first = rects[0]\n const last = rects[rects.length - 1]\n return [\n { left: first.left, top: first.top, width: 0, height: first.height },\n {\n left: last.left + last.width,\n top: last.top,\n width: 0,\n height: last.height,\n },\n ]\n}\n\n/** Whether `point` is within reach of a selection handle. */\nexport function isNearSelectionHandle(\n point: Point,\n ends: Box[],\n reach = SELECTION_HANDLE_REACH_PX,\n): boolean {\n return ends.some((end) => distanceToBox(point, end) <= reach)\n}\n\n/** What became of a touch that started outside the text being edited. */\nexport type TouchPressOutcome = 'tap' | 'not-a-tap'\n\n/**\n * Follows ONE touch from down to up and says whether it was a real tap.\n *\n * Fed raw pointer events; ignores every pointer but the one it started with.\n * `onHandle` presses — a touch that came down within reach of a selection\n * handle — never count as taps, even when they do not move: lifting a finger\n * off a handle is not a request to stop editing.\n */\nexport class TouchPressTracker {\n private press:\n | { id: number; x: number; y: number; at: number; moved: boolean }\n | undefined = undefined\n\n /** Starts following `event`'s pointer. A press near a handle is not followed. */\n down(event: PointerEvent, nearHandle: boolean): void {\n this.press = nearHandle\n ? undefined\n : {\n id: event.pointerId,\n x: event.clientX,\n y: event.clientY,\n at: event.timeStamp,\n moved: false,\n }\n }\n\n move(event: PointerEvent): void {\n const press = this.press\n if (!press || event.pointerId !== press.id) return\n if (\n Math.hypot(event.clientX - press.x, event.clientY - press.y) >\n TOUCH_TAP_SLOP_PX\n ) {\n press.moved = true\n }\n }\n\n /** The browser took the touch over (a scroll, a handle drag): no tap. */\n cancel(event?: PointerEvent): void {\n if (event && this.press && event.pointerId !== this.press.id) return\n this.press = undefined\n }\n\n /** The finger came up; whether that made a tap. Ends the follow. */\n up(event: PointerEvent): TouchPressOutcome | undefined {\n const press = this.press\n if (!press || event.pointerId !== press.id) return undefined\n this.press = undefined\n const moved =\n press.moved ||\n Math.hypot(event.clientX - press.x, event.clientY - press.y) >\n TOUCH_TAP_SLOP_PX\n const held = event.timeStamp - press.at > TOUCH_TAP_MAX_MS\n return moved || held ? 'not-a-tap' : 'tap'\n }\n\n get following(): boolean {\n return Boolean(this.press)\n }\n}\n\n/** The part of the page the author can actually see, in fixed coordinates. */\nexport interface VisibleArea {\n left: number\n top: number\n width: number\n height: number\n}\n\n/**\n * The visible area: the visual viewport where the browser has one.\n *\n * On a phone the on-screen keyboard covers the bottom of the LAYOUT viewport\n * without shrinking it, and iOS pans the page under it to keep the caret in\n * view. `position: fixed` is laid out against the layout viewport, so an\n * overlay placed by `innerHeight` can sit behind the keyboard or above the\n * top of the screen. The visual viewport is the part that is really showing;\n * its offsets put it in the same coordinates `position: fixed` uses.\n */\nexport function readVisibleArea(win: Window | undefined): VisibleArea {\n if (!win) return { left: 0, top: 0, width: Infinity, height: Infinity }\n const visual = win.visualViewport\n if (visual) {\n return {\n left: visual.offsetLeft,\n top: visual.offsetTop,\n width: visual.width,\n height: visual.height,\n }\n }\n return { left: 0, top: 0, width: win.innerWidth, height: win.innerHeight }\n}\n\nexport interface DockedToolbarPlacement {\n /** Which edge of the visible area the toolbar sits on. */\n edge: 'top' | 'bottom'\n left: number\n top: number\n maxWidth: number\n}\n\n/**\n * Where the text toolbar goes while a finger edits: docked to an edge of the\n * visible area — just above the keyboard, unless the text being edited is\n * down there, and then the top.\n *\n * Not above the text, where a mouse finds it. iOS puts its own Cut / Copy /\n * Paste menu right there, over anything the page draws, so a toolbar\n * hanging off the top of the text is hidden whenever the author selects a\n * word — which is exactly when they want Bold. Above the keyboard is where a\n * phone's formatting bar lives, it is clear of that menu (iOS hangs the menu\n * next to the selection, and the selection is in the text), and the bottom\n * of the visible area IS the top of the keyboard, so the bar is never\n * behind it. It moves to the top only when it would cover the text itself.\n */\nexport function placeDockedToolbar(\n text: Box,\n area: VisibleArea,\n toolbarHeight: number,\n gap: number,\n): DockedToolbarPlacement {\n const covers = (top: number) =>\n text.top < top + toolbarHeight + gap && text.top + text.height > top - gap\n const bottom = area.top + area.height - toolbarHeight - gap\n const top = area.top + gap\n const edge = covers(bottom) && !covers(top) ? 'top' : 'bottom'\n return {\n edge,\n left: area.left + gap,\n top: Math.max(area.top, edge === 'top' ? top : bottom),\n maxWidth: Math.max(0, area.width - gap * 2),\n }\n}\n"],"names":["TOUCH_TAP_SLOP_PX","TOUCH_TAP_MAX_MS","SELECTION_HANDLE_REACH_PX","isTouchPointer","event","type","pointerType","prefersTouchEditing","win","matchMedia","matches","distanceToBox","point","box","dx","Math","max","left","x","width","dy","top","y","height","hypot","selectionEndBoxes","selection","rangeCount","isCollapsed","range","getRangeAt","getClientRects","rects","Array","from","filter","rect","length","first","last","isNearSelectionHandle","ends","reach","some","end","TouchPressTracker","down","nearHandle","press","undefined","id","pointerId","clientX","clientY","at","timeStamp","moved","move","cancel","up","held","following","Boolean","readVisibleArea","Infinity","visual","visualViewport","offsetLeft","offsetTop","innerWidth","innerHeight","placeDockedToolbar","text","area","toolbarHeight","gap","covers","bottom","edge","maxWidth"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;CAgBC,GAED,iEAAiE,GACjE,OAAO,MAAMA,oBAAoB,GAAE;AAEnC,8EAA8E,GAC9E,OAAO,MAAMC,mBAAmB,IAAG;AAEnC;;;;CAIC,GACD,OAAO,MAAMC,4BAA4B,GAAE;AAE3C,mEAAmE,GACnE,OAAO,SAASC,eAAeC,KAAY;IACzC,MAAMC,OAAO,AAACD,MAAuBE,WAAW;IAChD,OAAOD,SAAS,WAAWA,SAAS;AACtC;AAEA,yEAAyE,GACzE,OAAO,SAASE,oBAAoBC,GAAuB;IACzD,IAAI,CAACA,OAAO,OAAOA,IAAIC,UAAU,KAAK,YAAY,OAAO;IACzD,IAAI;QACF,OAAOD,IAAIC,UAAU,CAAC,qBAAqBC,OAAO;IACpD,EAAE,eAAM;QACN,OAAO;IACT;AACF;AAcA,SAASC,cAAcC,KAAY,EAAEC,GAAQ;IAC3C,MAAMC,KAAKC,KAAKC,GAAG,CAACH,IAAII,IAAI,GAAGL,MAAMM,CAAC,EAAE,GAAGN,MAAMM,CAAC,GAAIL,CAAAA,IAAII,IAAI,GAAGJ,IAAIM,KAAK,AAAD;IACzE,MAAMC,KAAKL,KAAKC,GAAG,CAACH,IAAIQ,GAAG,GAAGT,MAAMU,CAAC,EAAE,GAAGV,MAAMU,CAAC,GAAIT,CAAAA,IAAIQ,GA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