@stll/folio-react 0.34.0 → 0.34.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -30,6 +30,7 @@ import { blockSdtAttrsToSdtProperties, findBlockSdtMatch, findBlockSdtMatches, r
30
30
  import { setContentControlContentBlocksTr } from "@stll/folio-core/prosemirror/commands/contentControlsBlockFill";
31
31
  import { insertPageBreak } from "@stll/folio-core/prosemirror/commands/pageBreak";
32
32
  import { CLIPBOARD_READ_ERROR_EVENT, buildPlainTextSlice, pastePlainTextSlice } from "@stll/folio-core/prosemirror/commands/pastePlainText";
33
+ import { clearPendingComment, commentIdsNamedIn, commentRecordsOf, commentThreadIds, commitCommentThread, deleteCommentThread, editCommentRecords, markPendingComment, recordingCommentsView, subscribeCommentRecords, syncCommentRecords } from "@stll/folio-core/prosemirror/commentRecords";
33
34
  import { proseDocToBlocks } from "@stll/folio-core/prosemirror/conversion/fromProseDoc";
34
35
  import { executeEditorCommand, executeFirstEditorCommand } from "@stll/folio-core/prosemirror/executeEditorCommand";
35
36
  import { ExtensionManager } from "@stll/folio-core/prosemirror/extensions/ExtensionManager";
@@ -54,6 +55,7 @@ import { onFontsLoaded } from "@stll/folio-core/utils/fontLoader";
54
55
  import { collectHeadings } from "@stll/folio-core/utils/headingCollector";
55
56
  import { DEFAULT_OUTLINE_DEPTH, filterHeadingsByDepth } from "@stll/folio-core/utils/outlineDepth";
56
57
  import { resolveOutlineHeadings } from "@stll/folio-core/utils/outlineHeadings";
58
+ import { PAINTED_START_SELECTOR, hasPaintedStart, paintedStartSelector, readPaintedEnd, readPaintedStart, readPaintedTableStart } from "@stll/folio-core/utils/paintedPositions";
57
59
  import { readBlobText } from "@stll/folio-core/utils/textEncoding";
58
60
  import { formatPx, pixelsToTwips, pointsToHalfPoints, twipsToPixels as twipsToPixels$1 } from "@stll/folio-core/utils/units";
59
61
  import { HistoryManager, classifyHistoryShortcut } from "@stll/folio-core/managers/HistoryManager";
@@ -61,7 +63,7 @@ import { TableSelectionManager } from "@stll/folio-core/managers/TableSelectionM
61
63
  import { ZOOM_MAX, ZOOM_MIN, ZOOM_STEP } from "@stll/folio-core/utils/zoom";
62
64
  import { createPortal } from "react-dom";
63
65
  import { panic } from "better-result";
64
- import { NodeSelection, Selection, TextSelection as TextSelection$1 } from "prosemirror-state";
66
+ import { NodeSelection, TextSelection as TextSelection$1 } from "prosemirror-state";
65
67
  import { CellSelection } from "prosemirror-tables";
66
68
  import { createFolioAIEditSnapshot as createFolioAIEditSnapshot$1 } from "@stll/folio-core/ai-edits/snapshot";
67
69
  import { createFolioEditorEmitter } from "@stll/folio-core/controller/folioEditorEvents";
@@ -79,7 +81,7 @@ import { templatePreviewDirtyRange } from "@stll/folio-core/layout-bridge/conver
79
81
  import { clickToPositionDom, getCaretPositionFromDom, getSelectionRectsFromDom } from "@stll/folio-core/layout-bridge/dom/clickToPositionDom";
80
82
  import { findBodyPmAnchor, findBodyPmAnchors, findBodyPmSpans } from "@stll/folio-core/layout-bridge/dom/findBodyPmSpans";
81
83
  import { clickToPositionInHfSlot, findHfSlotForTarget, findHfSlotKindForTarget } from "@stll/folio-core/layout-bridge/dom/findHfPmSpans";
82
- import { resetImeCaretAnchor, syncImeCaretAnchor } from "@stll/folio-core/layout-bridge/dom/imeCaretAnchor";
84
+ import { HIDDEN_EDITOR_WRAPPER_CLASS, resetImeCaretAnchor, syncImeCaretAnchor } from "@stll/folio-core/layout-bridge/dom/imeCaretAnchor";
83
85
  import { findNoteStoryForTarget } from "@stll/folio-core/layout-bridge/dom/noteStoryDom";
84
86
  import { measurePaintedSpanRange } from "@stll/folio-core/layout-bridge/dom/textStreamDom";
85
87
  import { clickToPosition } from "@stll/folio-core/layout-bridge/engine/clickToPosition";
@@ -96,10 +98,11 @@ import { collectRunFontsAtPmPositions, measureDirectiveGutter, projectRangesToRe
96
98
  import { isReadOnlyEditKey } from "@stll/folio-core/paged-layout/readOnlyEditAttempt";
97
99
  import { getPageScrollTarget } from "@stll/folio-core/paged-layout/scrollNavigation";
98
100
  import { PAGES_CONTAINER_CLASS, scrollPagesToPmPosition } from "@stll/folio-core/paged-layout/scrollToPmPosition";
101
+ import { FOLIO_INPUT_HIDDEN_ATTRIBUTE } from "@stll/folio-core/paged-layout/selectionViewportRect";
99
102
  import { resizeColumnPair } from "@stll/folio-core/paged-layout/tableColumnResize";
100
103
  import { tableInsertButtonOffset } from "@stll/folio-core/paged-layout/tableInsertButtonGeometry";
101
104
  import { commitImageFloatMove, commitImageInlineMove, commitImageResize, isFloatingImage } from "@stll/folio-core/prosemirror/imageCommit";
102
- import { MIN_ROW_HEIGHT_TWIPS, clampRowResizeDelta, commitColumnResize, commitRightEdgeResize, commitRowResize } from "@stll/folio-core/prosemirror/tableResize";
105
+ import { MIN_ROW_HEIGHT_TWIPS, clampRowResizeDelta, columnResizeCommand, rightEdgeResizeCommand, rowResizeCommand } from "@stll/folio-core/prosemirror/tableResize";
103
106
  import { dispatchEditorTextInput } from "@stll/folio-core/prosemirror/textInput";
104
107
  import { findStartPosForParaId } from "@stll/folio-core/prosemirror/utils/findParagraphByParaId";
105
108
  import { resolveHeaderFooterSelectionGeometry } from "@stll/folio-core/render-dom/HeaderFooterSelectionOverlay";
@@ -136,6 +139,81 @@ import { onDocumentPointerDown } from "@stll/folio-core/utils/documentPointerDow
136
139
  import { COMMENT_ANCHOR_SELECTOR, commentAnchorIds } from "@stll/folio-core/render-dom/commentAnchorAttributes";
137
140
  import { isValidHexId } from "@stll/folio-core/utils/hexId";
138
141
  import { createRoot } from "react-dom/client";
142
+ // src/hooks/keepEqual.ts
143
+ /**
144
+ * State the editor host writes while the user types: caret and selection
145
+ * geometry, overlay rectangles, toolbar formatting. Most writes carry a value
146
+ * equal to the one already held (another empty rectangle list, the same
147
+ * caret), and every React commit with the editor focused reads the editor's
148
+ * whole DOM to save the selection. A write that changes nothing must not
149
+ * commit, so these states keep the value they hold when the next one is
150
+ * equal to it.
151
+ */
152
+ const isPlainObject = (value) => {
153
+ const prototype = Object.getPrototypeOf(value);
154
+ return prototype === Object.prototype || prototype === null;
155
+ };
156
+ /**
157
+ * Whether two values hold the same data: primitives by `Object.is`, arrays,
158
+ * maps, sets and plain objects by their contents. Other objects (DOM nodes,
159
+ * class instances, functions) only when they are the same object.
160
+ */
161
+ const structurallyEqual = (left, right) => {
162
+ if (Object.is(left, right)) return true;
163
+ if (typeof left !== "object" || typeof right !== "object" || left === null || right === null) return false;
164
+ if (Array.isArray(left) || Array.isArray(right)) {
165
+ if (!Array.isArray(left) || !Array.isArray(right)) return false;
166
+ return left.length === right.length && left.every((item, index) => structurallyEqual(item, right[index]));
167
+ }
168
+ if (left instanceof Map || right instanceof Map) {
169
+ if (!(left instanceof Map) || !(right instanceof Map)) return false;
170
+ if (left.size !== right.size) return false;
171
+ for (const [key, value] of left) if (!right.has(key) || !structurallyEqual(value, right.get(key))) return false;
172
+ return true;
173
+ }
174
+ if (left instanceof Set || right instanceof Set) {
175
+ if (!(left instanceof Set) || !(right instanceof Set)) return false;
176
+ if (left.size !== right.size) return false;
177
+ for (const value of left) if (!right.has(value)) return false;
178
+ return true;
179
+ }
180
+ if (!isPlainObject(left) || !isPlainObject(right)) return false;
181
+ const leftKeys = Object.keys(left);
182
+ const rightKeys = Object.keys(right);
183
+ return leftKeys.length === rightKeys.length && leftKeys.every((key) => Object.hasOwn(right, key) && structurallyEqual(Reflect.get(left, key), Reflect.get(right, key)));
184
+ };
185
+ /**
186
+ * The next value of a state that keeps its current value when the next one
187
+ * is equal to it,
188
+ * so an unchanged write never re-renders or commits.
189
+ */
190
+ function keepEqual(previous, next) {
191
+ const resolved = typeof next === "function" ? next(previous) : next;
192
+ return structurallyEqual(previous, resolved) ? previous : resolved;
193
+ }
194
+ /**
195
+ * `useState` for state the editor host writes while the user types: the
196
+ * setter keeps the current value when the next one is equal to it. The
197
+ * update runs through React's own state queue, which drops an unchanged
198
+ * value before it schedules a render.
199
+ */
200
+ function useEqualState(initial) {
201
+ const $ = c(3);
202
+ const [value, setValue] = useState(initial);
203
+ let t0;
204
+ if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
205
+ t0 = (next) => setValue((previous) => keepEqual(previous, next));
206
+ $[0] = t0;
207
+ } else t0 = $[0];
208
+ const setIfChanged = t0;
209
+ let t1;
210
+ if ($[1] !== value) {
211
+ t1 = [value, setIfChanged];
212
+ $[1] = value;
213
+ $[2] = t1;
214
+ } else t1 = $[2];
215
+ return t1;
216
+ }
139
217
  // src/hooks/useHistory.ts
140
218
  /**
141
219
  * History hook for undo/redo functionality
@@ -242,7 +320,7 @@ function useDocumentHistory(document, t0) {
242
320
  $[1] = t1;
243
321
  } else t1 = $[1];
244
322
  const options = t1;
245
- const isEqual = _temp$17;
323
+ const isEqual = _temp$16;
246
324
  let t2;
247
325
  if ($[2] !== options) {
248
326
  t2 = {
@@ -254,7 +332,7 @@ function useDocumentHistory(document, t0) {
254
332
  } else t2 = $[3];
255
333
  return useHistory(document, t2);
256
334
  }
257
- function _temp$17(a, b) {
335
+ function _temp$16(a, b) {
258
336
  if (a === b) return true;
259
337
  const aPackage = a?.package;
260
338
  const bPackage = b?.package;
@@ -604,7 +682,7 @@ const HOST_STYLES = {
604
682
  zIndex: -1,
605
683
  pointerEvents: "none"
606
684
  };
607
- const HiddenHeaderFooterPMs = memo(forwardRef(function HiddenHeaderFooterPMs({ document, readOnly, styles, theme, onTransaction, experimentalSession, getCanonicalApi, onSessionRefusal }, ref) {
685
+ const HiddenHeaderFooterPMs = memo(forwardRef(function HiddenHeaderFooterPMs({ document, readOnly, styles, theme, onTransaction, experimentalSession, getCanonicalApi, readCanonicalDocument, onSessionRefusal }, ref) {
608
686
  const hostRef = useRef(null);
609
687
  const documentRef = useRef(document);
610
688
  const readOnlyRef = useRef(readOnly);
@@ -612,6 +690,7 @@ const HiddenHeaderFooterPMs = memo(forwardRef(function HiddenHeaderFooterPMs({ d
612
690
  const themeRef = useRef(theme);
613
691
  const onTransactionRef = useRef(onTransaction);
614
692
  const canonicalApiRef = useRef(getCanonicalApi);
693
+ const readCanonicalDocumentRef = useRef(readCanonicalDocument);
615
694
  const sessionRef = useRef(experimentalSession);
616
695
  const refusalRef = useRef(onSessionRefusal);
617
696
  const managerRef = useRef(null);
@@ -622,6 +701,7 @@ const HiddenHeaderFooterPMs = memo(forwardRef(function HiddenHeaderFooterPMs({ d
622
701
  themeRef.current = theme;
623
702
  onTransactionRef.current = onTransaction;
624
703
  canonicalApiRef.current = getCanonicalApi;
704
+ readCanonicalDocumentRef.current = readCanonicalDocument;
625
705
  sessionRef.current = experimentalSession;
626
706
  refusalRef.current = onSessionRefusal;
627
707
  managerRef.current ??= createHeaderFooterEditorManager({
@@ -631,6 +711,7 @@ const HiddenHeaderFooterPMs = memo(forwardRef(function HiddenHeaderFooterPMs({ d
631
711
  getStyles: () => stylesRef.current,
632
712
  getTheme: () => themeRef.current,
633
713
  getCanonicalApi: () => canonicalApiRef.current?.() ?? null,
714
+ readCanonicalDocument: () => readCanonicalDocumentRef.current(),
634
715
  getExperimentalSession: () => sessionRef.current,
635
716
  onSessionRefusal: (reason, ground, error) => refusalRef.current?.(reason, ground, error),
636
717
  onTransaction: ({ rId, kind, view, docChanged, selectionChanged }) => {
@@ -645,6 +726,7 @@ const HiddenHeaderFooterPMs = memo(forwardRef(function HiddenHeaderFooterPMs({ d
645
726
  theme,
646
727
  onTransaction,
647
728
  getCanonicalApi,
729
+ readCanonicalDocument,
648
730
  experimentalSession,
649
731
  onSessionRefusal
650
732
  ]);
@@ -697,14 +779,15 @@ const hostStyle = {
697
779
  };
698
780
  const EMPTY_PLUGINS$1 = [];
699
781
  const NoteStoryEditor = forwardRef(function NoteStoryEditor(t0, ref) {
700
- const $ = c(44);
701
- const { document, experimentalSession, getCanonicalApi, onSessionRefusal, onActiveChange, onDocumentChange, onStoryChange, plugins, styles, suggestionAuthor, suggestionModeActive, theme } = t0;
782
+ const $ = c(45);
783
+ const { document, experimentalSession, getCanonicalApi, readCanonicalDocument, onSessionRefusal, onActiveChange, onDocumentChange, onStoryChange, plugins, styles, suggestionAuthor, suggestionModeActive, theme } = t0;
702
784
  const t = useTranslations("folio");
703
785
  const resolvedPlugins = plugins ?? EMPTY_PLUGINS$1;
704
786
  const isSuggestionModeActive = suggestionModeActive ?? false;
705
787
  const hostRef = useRef(null);
706
788
  const documentRef = useRef(document);
707
789
  const canonicalApiRef = useRef(getCanonicalApi);
790
+ const readCanonicalDocumentRef = useRef(readCanonicalDocument);
708
791
  const sessionRef = useRef(experimentalSession);
709
792
  const refusalRef = useRef(onSessionRefusal);
710
793
  const stylesRef = useRef(styles);
@@ -717,10 +800,11 @@ const NoteStoryEditor = forwardRef(function NoteStoryEditor(t0, ref) {
717
800
  const managerRef = useRef(null);
718
801
  let t1;
719
802
  let t2;
720
- if ($[0] !== active || $[1] !== document || $[2] !== experimentalSession || $[3] !== getCanonicalApi || $[4] !== onActiveChange || $[5] !== onDocumentChange || $[6] !== onSessionRefusal || $[7] !== onStoryChange || $[8] !== resolvedPlugins || $[9] !== styles || $[10] !== theme) {
803
+ if ($[0] !== active || $[1] !== document || $[2] !== experimentalSession || $[3] !== getCanonicalApi || $[4] !== onActiveChange || $[5] !== onDocumentChange || $[6] !== onSessionRefusal || $[7] !== onStoryChange || $[8] !== readCanonicalDocument || $[9] !== resolvedPlugins || $[10] !== styles || $[11] !== theme) {
721
804
  t1 = () => {
722
805
  documentRef.current = document;
723
806
  canonicalApiRef.current = getCanonicalApi;
807
+ readCanonicalDocumentRef.current = readCanonicalDocument;
724
808
  sessionRef.current = experimentalSession;
725
809
  refusalRef.current = onSessionRefusal;
726
810
  stylesRef.current = styles;
@@ -736,20 +820,22 @@ const NoteStoryEditor = forwardRef(function NoteStoryEditor(t0, ref) {
736
820
  getStyles: () => stylesRef.current,
737
821
  getTheme: () => themeRef.current,
738
822
  getCanonicalApi: () => canonicalApiRef.current?.() ?? null,
823
+ readCanonicalDocument: () => readCanonicalDocumentRef.current(),
739
824
  getExperimentalSession: () => sessionRef.current,
740
825
  onSessionRefusal: (reason, ground, error) => refusalRef.current?.(reason, ground, error),
741
826
  onTransaction: (t3) => {
742
827
  const { docChanged, selectionChanged, view } = t3;
743
828
  if (docChanged) {
744
- const current = canonicalApiRef.current?.()?.getCanonicalDocument() ?? documentRef.current;
745
- if (current) onDocumentChangeRef.current(managerRef.current?.snapshotDocument(current) ?? current);
829
+ const manager = managerRef.current;
830
+ const current = readCanonicalDocumentRef.current() ?? documentRef.current;
831
+ if (current) onDocumentChangeRef.current(manager ? manager.snapshotDocument(current) : canonicalApiRef.current?.()?.getCanonicalDocument() ?? current);
746
832
  }
747
833
  onStoryChangeRef.current(view, docChanged, selectionChanged);
748
834
  }
749
835
  });
750
- const manager = managerRef.current;
751
- manager.sync();
752
- if (active && !manager?.getActive()) {
836
+ const manager_0 = managerRef.current;
837
+ manager_0.sync();
838
+ if (active && !manager_0?.getActive()) {
753
839
  setActive(null);
754
840
  onActiveChangeRef.current(null);
755
841
  }
@@ -759,6 +845,7 @@ const NoteStoryEditor = forwardRef(function NoteStoryEditor(t0, ref) {
759
845
  document,
760
846
  experimentalSession,
761
847
  getCanonicalApi,
848
+ readCanonicalDocument,
762
849
  onActiveChange,
763
850
  onDocumentChange,
764
851
  onSessionRefusal,
@@ -775,63 +862,64 @@ const NoteStoryEditor = forwardRef(function NoteStoryEditor(t0, ref) {
775
862
  $[5] = onDocumentChange;
776
863
  $[6] = onSessionRefusal;
777
864
  $[7] = onStoryChange;
778
- $[8] = resolvedPlugins;
779
- $[9] = styles;
780
- $[10] = theme;
781
- $[11] = t1;
782
- $[12] = t2;
865
+ $[8] = readCanonicalDocument;
866
+ $[9] = resolvedPlugins;
867
+ $[10] = styles;
868
+ $[11] = theme;
869
+ $[12] = t1;
870
+ $[13] = t2;
783
871
  } else {
784
- t1 = $[11];
785
- t2 = $[12];
872
+ t1 = $[12];
873
+ t2 = $[13];
786
874
  }
787
875
  useEffect(t1, t2);
788
876
  let t3;
789
877
  let t4;
790
- if ($[13] !== isSuggestionModeActive || $[14] !== suggestionAuthor) {
878
+ if ($[14] !== isSuggestionModeActive || $[15] !== suggestionAuthor) {
791
879
  t3 = () => {
792
- const manager_0 = managerRef.current;
793
- if (!manager_0) return;
794
- for (const story of manager_0.listStories()) {
795
- const view_0 = manager_0.getView(story);
880
+ const manager_1 = managerRef.current;
881
+ if (!manager_1) return;
882
+ for (const story of manager_1.listStories()) {
883
+ const view_0 = manager_1.getView(story);
796
884
  if (view_0) setSuggestionMode(isSuggestionModeActive, view_0.state, view_0.dispatch, suggestionAuthor);
797
885
  }
798
886
  };
799
887
  t4 = [isSuggestionModeActive, suggestionAuthor];
800
- $[13] = isSuggestionModeActive;
801
- $[14] = suggestionAuthor;
802
- $[15] = t3;
803
- $[16] = t4;
888
+ $[14] = isSuggestionModeActive;
889
+ $[15] = suggestionAuthor;
890
+ $[16] = t3;
891
+ $[17] = t4;
804
892
  } else {
805
- t3 = $[15];
806
- t4 = $[16];
893
+ t3 = $[16];
894
+ t4 = $[17];
807
895
  }
808
896
  useEffect(t3, t4);
809
897
  let t5;
810
898
  let t6;
811
- if ($[17] === Symbol.for("react.memo_cache_sentinel")) {
899
+ if ($[18] === Symbol.for("react.memo_cache_sentinel")) {
812
900
  t5 = () => () => {
813
901
  managerRef.current?.destroy();
814
902
  };
815
903
  t6 = [];
816
- $[17] = t5;
817
- $[18] = t6;
904
+ $[18] = t5;
905
+ $[19] = t6;
818
906
  } else {
819
- t5 = $[17];
820
- t6 = $[18];
907
+ t5 = $[18];
908
+ t6 = $[19];
821
909
  }
822
910
  useEffect(t5, t6);
823
911
  let t7;
824
- if ($[19] === Symbol.for("react.memo_cache_sentinel")) {
912
+ if ($[20] === Symbol.for("react.memo_cache_sentinel")) {
825
913
  t7 = () => {
826
914
  managerRef.current?.activate(null);
827
915
  setActive(null);
828
916
  onActiveChangeRef.current(null);
829
917
  };
830
- $[19] = t7;
831
- } else t7 = $[19];
918
+ $[20] = t7;
919
+ } else t7 = $[20];
832
920
  const closeEditor = t7;
833
921
  let t8;
834
- if ($[20] !== isSuggestionModeActive || $[21] !== suggestionAuthor) {
922
+ if ($[21] !== isSuggestionModeActive || $[22] !== suggestionAuthor) {
835
923
  t8 = () => ({
836
924
  close: closeEditor,
837
925
  getActiveView: () => {
@@ -848,63 +936,63 @@ const NoteStoryEditor = forwardRef(function NoteStoryEditor(t0, ref) {
848
936
  },
849
937
  snapshotDocument: (current_0) => managerRef.current?.snapshotDocument(current_0) ?? current_0
850
938
  });
851
- $[20] = isSuggestionModeActive;
852
- $[21] = suggestionAuthor;
853
- $[22] = t8;
854
- } else t8 = $[22];
939
+ $[21] = isSuggestionModeActive;
940
+ $[22] = suggestionAuthor;
941
+ $[23] = t8;
942
+ } else t8 = $[23];
855
943
  useImperativeHandle(ref, t8);
856
944
  let t9;
857
- if ($[23] !== active || $[24] !== t) {
945
+ if ($[24] !== active || $[25] !== t) {
858
946
  t9 = active ? t(active.kind === "footnote" ? "dialogs.footnoteProperties.footnotes" : "dialogs.footnoteProperties.endnotes") : "";
859
- $[23] = active;
860
- $[24] = t;
861
- $[25] = t9;
862
- } else t9 = $[25];
947
+ $[24] = active;
948
+ $[25] = t;
949
+ $[26] = t9;
950
+ } else t9 = $[26];
863
951
  const title = t9;
864
952
  const t10 = active ? "block" : "none";
865
953
  let t11;
866
- if ($[26] !== t10) {
954
+ if ($[27] !== t10) {
867
955
  t11 = {
868
956
  ...panelStyle,
869
957
  display: t10
870
958
  };
871
- $[26] = t10;
872
- $[27] = t11;
873
- } else t11 = $[27];
959
+ $[27] = t10;
960
+ $[28] = t11;
961
+ } else t11 = $[28];
874
962
  let t12;
875
- if ($[28] === Symbol.for("react.memo_cache_sentinel")) {
963
+ if ($[29] === Symbol.for("react.memo_cache_sentinel")) {
876
964
  t12 = (event) => {
877
965
  if (event.key !== "Escape") return;
878
966
  event.preventDefault();
879
967
  event.stopPropagation();
880
968
  closeEditor();
881
969
  };
882
- $[28] = t12;
883
- } else t12 = $[28];
970
+ $[29] = t12;
971
+ } else t12 = $[29];
884
972
  let t13;
885
- if ($[29] !== title) {
973
+ if ($[30] !== title) {
886
974
  t13 = /* @__PURE__ */ jsx("span", { children: title });
887
- $[29] = title;
888
- $[30] = t13;
889
- } else t13 = $[30];
975
+ $[30] = title;
976
+ $[31] = t13;
977
+ } else t13 = $[31];
890
978
  let t14;
891
- if ($[31] !== t) {
979
+ if ($[32] !== t) {
892
980
  t14 = t("common.closeDialog");
893
- $[31] = t;
894
- $[32] = t14;
895
- } else t14 = $[32];
981
+ $[32] = t;
982
+ $[33] = t14;
983
+ } else t14 = $[33];
896
984
  let t15;
897
- if ($[33] === Symbol.for("react.memo_cache_sentinel")) {
985
+ if ($[34] === Symbol.for("react.memo_cache_sentinel")) {
898
986
  t15 = {
899
987
  border: 0,
900
988
  background: "transparent",
901
989
  color: "inherit",
902
990
  cursor: "pointer"
903
991
  };
904
- $[33] = t15;
905
- } else t15 = $[33];
992
+ $[34] = t15;
993
+ } else t15 = $[34];
906
994
  let t16;
907
- if ($[34] !== t14) {
995
+ if ($[35] !== t14) {
908
996
  t16 = /* @__PURE__ */ jsx("button", {
909
997
  type: "button",
910
998
  "aria-label": t14,
@@ -912,40 +1000,40 @@ const NoteStoryEditor = forwardRef(function NoteStoryEditor(t0, ref) {
912
1000
  style: t15,
913
1001
  children: "×"
914
1002
  });
915
- $[34] = t14;
916
- $[35] = t16;
917
- } else t16 = $[35];
1003
+ $[35] = t14;
1004
+ $[36] = t16;
1005
+ } else t16 = $[36];
918
1006
  let t17;
919
- if ($[36] !== t13 || $[37] !== t16) {
1007
+ if ($[37] !== t13 || $[38] !== t16) {
920
1008
  t17 = /* @__PURE__ */ jsxs("div", {
921
1009
  style: headerStyle,
922
1010
  children: [t13, t16]
923
1011
  });
924
- $[36] = t13;
925
- $[37] = t16;
926
- $[38] = t17;
927
- } else t17 = $[38];
1012
+ $[37] = t13;
1013
+ $[38] = t16;
1014
+ $[39] = t17;
1015
+ } else t17 = $[39];
928
1016
  let t18;
929
- if ($[39] === Symbol.for("react.memo_cache_sentinel")) {
1017
+ if ($[40] === Symbol.for("react.memo_cache_sentinel")) {
930
1018
  t18 = /* @__PURE__ */ jsx("div", {
931
1019
  ref: hostRef,
932
1020
  style: hostStyle
933
1021
  });
934
- $[39] = t18;
935
- } else t18 = $[39];
1022
+ $[40] = t18;
1023
+ } else t18 = $[40];
936
1024
  let t19;
937
- if ($[40] !== t11 || $[41] !== t17 || $[42] !== title) {
1025
+ if ($[41] !== t11 || $[42] !== t17 || $[43] !== title) {
938
1026
  t19 = /* @__PURE__ */ jsxs("aside", {
939
1027
  style: t11,
940
1028
  "aria-label": title,
941
1029
  onKeyDown: t12,
942
1030
  children: [t17, t18]
943
1031
  });
944
- $[40] = t11;
945
- $[41] = t17;
946
- $[42] = title;
947
- $[43] = t19;
948
- } else t19 = $[43];
1032
+ $[41] = t11;
1033
+ $[42] = t17;
1034
+ $[43] = title;
1035
+ $[44] = t19;
1036
+ } else t19 = $[44];
949
1037
  return t19;
950
1038
  });
951
1039
  NoteStoryEditor.displayName = "NoteStoryEditor";
@@ -1012,7 +1100,7 @@ const AISuggestionRectsOverlay = (t0) => {
1012
1100
  if (groups.length === 0) return null;
1013
1101
  let t1;
1014
1102
  if ($[0] !== groups) {
1015
- t1 = groups.map(_temp$16);
1103
+ t1 = groups.map(_temp$15);
1016
1104
  $[0] = groups;
1017
1105
  $[1] = t1;
1018
1106
  } else t1 = $[1];
@@ -1028,7 +1116,7 @@ const AISuggestionRectsOverlay = (t0) => {
1028
1116
  } else t2 = $[3];
1029
1117
  return t2;
1030
1118
  };
1031
- function _temp$16(t0) {
1119
+ function _temp$15(t0) {
1032
1120
  const { suggestion, rects, focused, font } = t0;
1033
1121
  const replacementAnchor = rects.at(-1);
1034
1122
  const showReplacement = focused && suggestion.suggestedText.length > 0 && replacementAnchor !== void 0;
@@ -1492,7 +1580,8 @@ const HiddenProseMirror = forwardRef((props, ref) => {
1492
1580
  useImperativeHandle(ref, () => ({
1493
1581
  ...managerRef.current.api,
1494
1582
  getHostElement: () => hostRef.current,
1495
- isCanonicalComposing: () => managerRef.current?.isCanonicalComposing() ?? false
1583
+ isCanonicalComposing: () => managerRef.current?.isCanonicalComposing() ?? false,
1584
+ readCanonicalDocument: () => managerRef.current?.readCanonicalDocument() ?? null
1496
1585
  }), []);
1497
1586
  if (hasCollaboration && collaborationModulesError) {
1498
1587
  let detail = "unknown error";
@@ -1501,7 +1590,7 @@ const HiddenProseMirror = forwardRef((props, ref) => {
1501
1590
  panic(`Failed to load collaboration editor modules. Reload the document to retry. Cause: ${detail}`);
1502
1591
  }
1503
1592
  return /* @__PURE__ */ jsx("div", {
1504
- className: "paged-editor__hidden-pm-wrapper",
1593
+ className: HIDDEN_EDITOR_WRAPPER_CLASS,
1505
1594
  style: HIDDEN_WRAPPER_STYLES,
1506
1595
  children: /* @__PURE__ */ jsx("div", {
1507
1596
  ref: hostRef,
@@ -2115,7 +2204,7 @@ const PassageHighlightOverlay = (t0) => {
2115
2204
  if (rects.length === 0) return null;
2116
2205
  let t1;
2117
2206
  if ($[0] !== rects) {
2118
- t1 = rects.map(_temp$15);
2207
+ t1 = rects.map(_temp$14);
2119
2208
  $[0] = rects;
2120
2209
  $[1] = t1;
2121
2210
  } else t1 = $[1];
@@ -2131,7 +2220,7 @@ const PassageHighlightOverlay = (t0) => {
2131
2220
  } else t2 = $[3];
2132
2221
  return t2;
2133
2222
  };
2134
- function _temp$15(rect, idx) {
2223
+ function _temp$14(rect, idx) {
2135
2224
  return /* @__PURE__ */ jsx("span", {
2136
2225
  className: "folio-passage-highlight",
2137
2226
  style: {
@@ -2262,10 +2351,11 @@ const SelectionRectangle = (t0) => {
2262
2351
  * Renders selection highlights and caret cursor over the paginated document.
2263
2352
  * Should be positioned as a child of the pages container with relative positioning.
2264
2353
  */
2265
- const SelectionOverlay = ({ selectionRects, caretPosition, isFocused, caretColor = DEFAULT_CARET_COLOR, selectionColor = DEFAULT_SELECTION_COLOR, caretWidth = DEFAULT_CARET_WIDTH, blinkInterval = DEFAULT_BLINK_INTERVAL, markCaretRect = false }) => {
2354
+ const SelectionOverlay = ({ selectionRects, caretPosition, isFocused, caretColor = DEFAULT_CARET_COLOR, selectionColor = DEFAULT_SELECTION_COLOR, caretWidth = DEFAULT_CARET_WIDTH, blinkInterval = DEFAULT_BLINK_INTERVAL, markCaretRect = false, overlayRef }) => {
2266
2355
  const hasRangeSelection = selectionRects.length > 0;
2267
2356
  const hasCollapsedSelection = caretPosition !== null && !hasRangeSelection;
2268
2357
  return /* @__PURE__ */ jsxs("div", {
2358
+ ref: overlayRef,
2269
2359
  style: overlayStyles$1,
2270
2360
  "data-testid": "selection-overlay",
2271
2361
  children: [hasRangeSelection && selectionRects.map((rect, index) => /* @__PURE__ */ jsx(SelectionRectangle, {
@@ -2638,6 +2728,20 @@ const DOCUMENT_CHANGE_NOTIFY_DELAY = 250;
2638
2728
  /** Keep the visual caret hidden briefly while typed content relayouts. */
2639
2729
  const SELECTION_REVEAL_AFTER_INPUT_DELAY = 120;
2640
2730
  /**
2731
+ * Hide the selection overlay while typed content lays out again. It is a DOM
2732
+ * write, not a state change: a keystroke must not render the editor, since
2733
+ * every commit with the editor focused reads its whole DOM.
2734
+ */
2735
+ const hideSelectionOverlay = (overlay) => {
2736
+ overlay?.setAttribute(FOLIO_INPUT_HIDDEN_ATTRIBUTE, "");
2737
+ overlay?.style.setProperty("visibility", "hidden");
2738
+ };
2739
+ const showSelectionOverlay = (overlay) => {
2740
+ if (!overlay?.hasAttribute(FOLIO_INPUT_HIDDEN_ATTRIBUTE)) return;
2741
+ overlay.removeAttribute(FOLIO_INPUT_HIDDEN_ATTRIBUTE);
2742
+ overlay.style.removeProperty("visibility");
2743
+ };
2744
+ /**
2641
2745
  * Readability floor for the autocomplete ghost width: with the caret at the
2642
2746
  * right content boundary, an unfloored width plus `overflow-wrap: anywhere`
2643
2747
  * would wrap the suggestion into a one-character-wide vertical column. Near
@@ -2766,7 +2870,7 @@ const createPagedRuntime = (emitter) => {
2766
2870
  };
2767
2871
  };
2768
2872
  function HfCaretOverlay(t0) {
2769
- const $ = c(21);
2873
+ const $ = c(23);
2770
2874
  const { selection, getSurface, zoom } = t0;
2771
2875
  let t1;
2772
2876
  if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
@@ -2776,18 +2880,18 @@ function HfCaretOverlay(t0) {
2776
2880
  };
2777
2881
  $[0] = t1;
2778
2882
  } else t1 = $[0];
2779
- const [caretProjection, setCaretProjection] = useState(t1);
2883
+ const [caretProjection, setCaretProjection] = useEqualState(t1);
2780
2884
  const { caret, pagesContainer: portalTarget } = caretProjection;
2781
2885
  let t2;
2782
2886
  if ($[1] === Symbol.for("react.memo_cache_sentinel")) {
2783
2887
  t2 = [];
2784
2888
  $[1] = t2;
2785
2889
  } else t2 = $[1];
2786
- const [rangeRects, setRangeRects] = useState(t2);
2890
+ const [rangeRects, setRangeRects] = useEqualState(t2);
2787
2891
  const { rId, kind, from, to, pageNumber } = selection;
2788
2892
  let t3;
2789
2893
  let t4;
2790
- if ($[2] !== from || $[3] !== getSurface || $[4] !== kind || $[5] !== pageNumber || $[6] !== rId || $[7] !== to || $[8] !== zoom) {
2894
+ if ($[2] !== from || $[3] !== getSurface || $[4] !== kind || $[5] !== pageNumber || $[6] !== rId || $[7] !== setCaretProjection || $[8] !== setRangeRects || $[9] !== to || $[10] !== zoom) {
2791
2895
  t3 = () => {
2792
2896
  const { pagesContainer, hiddenHost } = getSurface(rId);
2793
2897
  if (!pagesContainer) return;
@@ -2854,31 +2958,35 @@ function HfCaretOverlay(t0) {
2854
2958
  to,
2855
2959
  pageNumber,
2856
2960
  getSurface,
2857
- zoom
2961
+ zoom,
2962
+ setCaretProjection,
2963
+ setRangeRects
2858
2964
  ];
2859
2965
  $[2] = from;
2860
2966
  $[3] = getSurface;
2861
2967
  $[4] = kind;
2862
2968
  $[5] = pageNumber;
2863
2969
  $[6] = rId;
2864
- $[7] = to;
2865
- $[8] = zoom;
2866
- $[9] = t3;
2867
- $[10] = t4;
2970
+ $[7] = setCaretProjection;
2971
+ $[8] = setRangeRects;
2972
+ $[9] = to;
2973
+ $[10] = zoom;
2974
+ $[11] = t3;
2975
+ $[12] = t4;
2868
2976
  } else {
2869
- t3 = $[9];
2870
- t4 = $[10];
2977
+ t3 = $[11];
2978
+ t4 = $[12];
2871
2979
  }
2872
2980
  useEffect(t3, t4);
2873
2981
  if (!portalTarget) return null;
2874
2982
  let t5;
2875
- if ($[11] !== rangeRects) {
2876
- t5 = rangeRects.map(_temp$14);
2877
- $[11] = rangeRects;
2878
- $[12] = t5;
2879
- } else t5 = $[12];
2983
+ if ($[13] !== rangeRects) {
2984
+ t5 = rangeRects.map(_temp$13);
2985
+ $[13] = rangeRects;
2986
+ $[14] = t5;
2987
+ } else t5 = $[14];
2880
2988
  let t6;
2881
- if ($[13] !== caret) {
2989
+ if ($[15] !== caret) {
2882
2990
  t6 = caret && /* @__PURE__ */ jsx("div", {
2883
2991
  "data-testid": "hf-caret",
2884
2992
  style: {
@@ -2893,26 +3001,26 @@ function HfCaretOverlay(t0) {
2893
3001
  animation: "folio-caret-blink 1060ms steps(1, end) infinite"
2894
3002
  }
2895
3003
  });
2896
- $[13] = caret;
2897
- $[14] = t6;
2898
- } else t6 = $[14];
3004
+ $[15] = caret;
3005
+ $[16] = t6;
3006
+ } else t6 = $[16];
2899
3007
  let t7;
2900
- if ($[15] !== t5 || $[16] !== t6) {
3008
+ if ($[17] !== t5 || $[18] !== t6) {
2901
3009
  t7 = /* @__PURE__ */ jsxs(Fragment, { children: [t5, t6] });
2902
- $[15] = t5;
2903
- $[16] = t6;
2904
- $[17] = t7;
2905
- } else t7 = $[17];
3010
+ $[17] = t5;
3011
+ $[18] = t6;
3012
+ $[19] = t7;
3013
+ } else t7 = $[19];
2906
3014
  let t8;
2907
- if ($[18] !== portalTarget || $[19] !== t7) {
3015
+ if ($[20] !== portalTarget || $[21] !== t7) {
2908
3016
  t8 = createPortal(t7, portalTarget);
2909
- $[18] = portalTarget;
2910
- $[19] = t7;
2911
- $[20] = t8;
2912
- } else t8 = $[20];
3017
+ $[20] = portalTarget;
3018
+ $[21] = t7;
3019
+ $[22] = t8;
3020
+ } else t8 = $[22];
2913
3021
  return t8;
2914
3022
  }
2915
- function _temp$14(r, i) {
3023
+ function _temp$13(r, i) {
2916
3024
  return /* @__PURE__ */ jsx("div", {
2917
3025
  "data-testid": "hf-selection-rect",
2918
3026
  style: {
@@ -2997,12 +3105,12 @@ function describeInvalidHighlightMarks(doc) {
2997
3105
  return invalidHighlights.join("; ");
2998
3106
  }
2999
3107
  const RemoteSelectionOverlay = (t0) => {
3000
- const $ = c(21);
3108
+ const $ = c(22);
3001
3109
  const { blocks, layout, measures, getPagesContainer, remoteSelection, zoom } = t0;
3002
- const [geometry, setGeometry] = useState(null);
3110
+ const [geometry, setGeometry] = useEqualState(null);
3003
3111
  let t1;
3004
3112
  let t2;
3005
- if ($[0] !== blocks || $[1] !== getPagesContainer || $[2] !== layout || $[3] !== measures || $[4] !== remoteSelection.anchor || $[5] !== remoteSelection.head || $[6] !== zoom) {
3113
+ if ($[0] !== blocks || $[1] !== getPagesContainer || $[2] !== layout || $[3] !== measures || $[4] !== remoteSelection.anchor || $[5] !== remoteSelection.head || $[6] !== setGeometry || $[7] !== zoom) {
3006
3114
  t1 = () => {
3007
3115
  let cancelled = false;
3008
3116
  loadSelectionGeometry().then((t3) => {
@@ -3047,7 +3155,8 @@ const RemoteSelectionOverlay = (t0) => {
3047
3155
  getPagesContainer,
3048
3156
  remoteSelection.anchor,
3049
3157
  remoteSelection.head,
3050
- zoom
3158
+ zoom,
3159
+ setGeometry
3051
3160
  ];
3052
3161
  $[0] = blocks;
3053
3162
  $[1] = getPagesContainer;
@@ -3055,19 +3164,20 @@ const RemoteSelectionOverlay = (t0) => {
3055
3164
  $[3] = measures;
3056
3165
  $[4] = remoteSelection.anchor;
3057
3166
  $[5] = remoteSelection.head;
3058
- $[6] = zoom;
3059
- $[7] = t1;
3060
- $[8] = t2;
3167
+ $[6] = setGeometry;
3168
+ $[7] = zoom;
3169
+ $[8] = t1;
3170
+ $[9] = t2;
3061
3171
  } else {
3062
- t1 = $[7];
3063
- t2 = $[8];
3172
+ t1 = $[8];
3173
+ t2 = $[9];
3064
3174
  }
3065
3175
  useEffect(t1, t2);
3066
3176
  if (!geometry) return null;
3067
3177
  const { caretPosition: caretPosition_0, selectionRects } = geometry;
3068
3178
  const t3 = `color-mix(in srgb, ${remoteSelection.color} 24%, transparent)`;
3069
3179
  let t4;
3070
- if ($[9] !== caretPosition_0 || $[10] !== remoteSelection.color || $[11] !== selectionRects || $[12] !== t3) {
3180
+ if ($[10] !== caretPosition_0 || $[11] !== remoteSelection.color || $[12] !== selectionRects || $[13] !== t3) {
3071
3181
  t4 = /* @__PURE__ */ jsx(SelectionOverlay, {
3072
3182
  blinkInterval: 0,
3073
3183
  caretColor: remoteSelection.color,
@@ -3077,14 +3187,14 @@ const RemoteSelectionOverlay = (t0) => {
3077
3187
  selectionColor: t3,
3078
3188
  selectionRects
3079
3189
  });
3080
- $[9] = caretPosition_0;
3081
- $[10] = remoteSelection.color;
3082
- $[11] = selectionRects;
3083
- $[12] = t3;
3084
- $[13] = t4;
3085
- } else t4 = $[13];
3190
+ $[10] = caretPosition_0;
3191
+ $[11] = remoteSelection.color;
3192
+ $[12] = selectionRects;
3193
+ $[13] = t3;
3194
+ $[14] = t4;
3195
+ } else t4 = $[14];
3086
3196
  let t5;
3087
- if ($[14] !== caretPosition_0 || $[15] !== remoteSelection.color || $[16] !== remoteSelection.name) {
3197
+ if ($[15] !== caretPosition_0 || $[16] !== remoteSelection.color || $[17] !== remoteSelection.name) {
3088
3198
  t5 = caretPosition_0 && /* @__PURE__ */ jsx("div", {
3089
3199
  className: "pointer-events-none absolute z-20 rounded-sm px-1 py-0.5 text-[10px] leading-none shadow-sm",
3090
3200
  style: {
@@ -3095,18 +3205,18 @@ const RemoteSelectionOverlay = (t0) => {
3095
3205
  },
3096
3206
  children: remoteSelection.name
3097
3207
  });
3098
- $[14] = caretPosition_0;
3099
- $[15] = remoteSelection.color;
3100
- $[16] = remoteSelection.name;
3101
- $[17] = t5;
3102
- } else t5 = $[17];
3208
+ $[15] = caretPosition_0;
3209
+ $[16] = remoteSelection.color;
3210
+ $[17] = remoteSelection.name;
3211
+ $[18] = t5;
3212
+ } else t5 = $[18];
3103
3213
  let t6;
3104
- if ($[18] !== t4 || $[19] !== t5) {
3214
+ if ($[19] !== t4 || $[20] !== t5) {
3105
3215
  t6 = /* @__PURE__ */ jsxs(Fragment, { children: [t4, t5] });
3106
- $[18] = t4;
3107
- $[19] = t5;
3108
- $[20] = t6;
3109
- } else t6 = $[20];
3216
+ $[19] = t4;
3217
+ $[20] = t5;
3218
+ $[21] = t6;
3219
+ } else t6 = $[21];
3110
3220
  return t6;
3111
3221
  };
3112
3222
  const pagesContainerStyles = {
@@ -3327,9 +3437,13 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
3327
3437
  const queuedInputBeforeHiddenEditorRef = useRef([]);
3328
3438
  const pendingInitialFontReadyLayoutRef = useRef(false);
3329
3439
  const [isFocused, setIsFocused] = useState(false);
3330
- const [selectionRects, setSelectionRects] = useState([]);
3331
- const [caretPosition, setCaretPosition] = useState(null);
3332
- const [anonymizationRectGroups, setAnonymizationRectGroups] = useState([]);
3440
+ const [selectionRects, setSelectionRects] = useEqualState([]);
3441
+ const [caretPosition, setCaretPositionState] = useEqualState(null);
3442
+ /** The selection overlay, hidden without a render while typing. */
3443
+ const selectionOverlayRef = useRef(null);
3444
+ /** The caret the overlay last painted. */
3445
+ const committedCaretRef = useRef(null);
3446
+ const [anonymizationRectGroups, setAnonymizationRectGroups] = useEqualState([]);
3333
3447
  const anonymizationMatchesRef = useRef([]);
3334
3448
  const [anonymizationOverlayRequestGate] = useState(createLatestRequestGate);
3335
3449
  const autocompleteSuggestionRef = useRef({
@@ -3339,16 +3453,16 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
3339
3453
  requestId: null
3340
3454
  });
3341
3455
  const [autocompleteOverlayRequestGate] = useState(createLatestRequestGate);
3342
- const [autocompleteCaret, setAutocompleteCaret] = useState(null);
3343
- const [autocompleteText, setAutocompleteText] = useState("");
3456
+ const [autocompleteCaret, setAutocompleteCaret] = useEqualState(null);
3457
+ const [autocompleteText, setAutocompleteText] = useEqualState("");
3344
3458
  const [autocompleteIsStreaming, setAutocompleteIsStreaming] = useState(false);
3345
- const [directiveProjection, setDirectiveProjection] = useState({
3459
+ const [directiveProjection, setDirectiveProjection] = useEqualState({
3346
3460
  groups: [],
3347
3461
  ranges: []
3348
3462
  });
3349
3463
  const directiveRectGroups = directiveProjection.groups;
3350
- const [directiveGutter, setDirectiveGutter] = useState(null);
3351
- const [directiveCaretPos, setDirectiveCaretPos] = useState(null);
3464
+ const [directiveGutter, setDirectiveGutter] = useEqualState(null);
3465
+ const [directiveCaretPos, setDirectiveCaretPos] = useEqualState(null);
3352
3466
  const directivesRef = useRef([]);
3353
3467
  const [directivesOverlayRequestGate] = useState(createLatestRequestGate);
3354
3468
  const templatePreviewRef = useRef({
@@ -3356,18 +3470,32 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
3356
3470
  hidden: EMPTY_TEMPLATE_PREVIEW_HIDDEN,
3357
3471
  mode: "plain"
3358
3472
  });
3359
- const [aiSuggestionRectGroups, setAiSuggestionRectGroups] = useState([]);
3473
+ const [aiSuggestionRectGroups, setAiSuggestionRectGroups] = useEqualState([]);
3360
3474
  const aiSuggestionsRef = useRef({
3361
3475
  suggestions: EMPTY_AI_SUGGESTIONS,
3362
3476
  focusedId: null
3363
3477
  });
3364
3478
  const [aiSuggestionsOverlayRequestGate] = useState(createLatestRequestGate);
3365
3479
  const passageHighlightRangeRef = useRef(null);
3366
- const [passageHighlightRects, setPassageHighlightRects] = useState([]);
3480
+ const [passageHighlightRects, setPassageHighlightRects] = useEqualState([]);
3367
3481
  const [passageHighlightOverlayRequestGate] = useState(createLatestRequestGate);
3368
- const [remoteSelections, setRemoteSelections] = useState([]);
3482
+ const [remoteSelections, setRemoteSelections] = useEqualState([]);
3369
3483
  const suppressSelectionOverlayRef = useRef(false);
3370
3484
  const revealSelectionOverlayTimerRef = useRef(null);
3485
+ /**
3486
+ * Write the caret. While typed content lays out again the overlay is
3487
+ * hidden instead of cleared, so a keystroke renders nothing for it; the
3488
+ * first caret written after that shows the overlay again, once the caret
3489
+ * it holds is the one painted.
3490
+ */
3491
+ const setCaretPosition = useCallback((next) => {
3492
+ setCaretPositionState(next);
3493
+ if (!suppressSelectionOverlayRef.current && structurallyEqual(committedCaretRef.current, next)) showSelectionOverlay(selectionOverlayRef.current);
3494
+ }, [setCaretPositionState]);
3495
+ useLayoutEffect(() => {
3496
+ committedCaretRef.current = caretPosition;
3497
+ if (!suppressSelectionOverlayRef.current) showSelectionOverlay(selectionOverlayRef.current);
3498
+ }, [caretPosition]);
3371
3499
  const [selectionOverlayRequestGate] = useState(createLatestRequestGate);
3372
3500
  const validPrecomputedInitialState = useMemo(() => {
3373
3501
  if (shouldCreateHiddenEditorView || collaboration !== void 0 || !document) return null;
@@ -3390,7 +3518,7 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
3390
3518
  useLayoutEffect(() => {
3391
3519
  precomputedInitialStateRef.current = validPrecomputedInitialState;
3392
3520
  }, [validPrecomputedInitialState]);
3393
- const [selectedImageInfo, setSelectedImageInfo] = useState(null);
3521
+ const [selectedImageInfo, setSelectedImageInfo] = useEqualState(null);
3394
3522
  const isImageInteractingRef = useRef(false);
3395
3523
  /** Build ImageSelectionInfo from a DOM element with data-pm-start */
3396
3524
  const buildImageSelectionInfo = useCallback((el, pmPos) => {
@@ -3494,7 +3622,7 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
3494
3622
  const cellDragOverflowXRef = useRef(null);
3495
3623
  const cellDragContentEndRef = useRef(null);
3496
3624
  const CELL_SELECT_OVERFLOW_PX = 5;
3497
- const [tableInsertButton, setTableInsertButton] = useState(null);
3625
+ const [tableInsertButton, setTableInsertButton] = useEqualState(null);
3498
3626
  const tableInsertHideTimerRef = useRef(null);
3499
3627
  const clearTableInsertTimer = useCallback(() => {
3500
3628
  if (tableInsertHideTimerRef.current) {
@@ -3763,8 +3891,8 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
3763
3891
  const body = hiddenPMRef.current?.getState()?.doc;
3764
3892
  if (newDoc && body && !usesCanonicalSession(experimentalSession, CANONICAL_GAP.save)) newDoc = noteFollower.reconcile(newDoc, body);
3765
3893
  if (newDoc) {
3766
- onDocumentChangeRef.current?.(usesCanonicalSession(experimentalSession, CANONICAL_GAP.save) ? cloneDocumentWithParagraphPropertySources(newDoc) : newDoc);
3767
- folioEmitterRef.current.emit("docChange", usesCanonicalSession(experimentalSession, CANONICAL_GAP.authorityRouting) ? cloneDocumentWithParagraphPropertySources(newDoc) : newDoc);
3894
+ onDocumentChangeRef.current?.(newDoc);
3895
+ folioEmitterRef.current.emit("docChange", newDoc);
3768
3896
  }
3769
3897
  };
3770
3898
  flush();
@@ -3773,6 +3901,7 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
3773
3901
  noteFollower,
3774
3902
  getActiveEditorStory
3775
3903
  ]);
3904
+ const readCanonicalDocument = useCallback(() => hiddenPMRef.current?.readCanonicalDocument() ?? null, []);
3776
3905
  const scheduleDocumentChangeNotification = useCallback(() => {
3777
3906
  if (documentChangeNotifyTimerRef.current !== null) window.clearTimeout(documentChangeNotifyTimerRef.current);
3778
3907
  documentChangeNotifyTimerRef.current = window.setTimeout(() => {
@@ -3850,13 +3979,7 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
3850
3979
  });
3851
3980
  }
3852
3981
  if (suppressSelectionOverlayRef.current) {
3853
- setCaretPosition(null);
3854
3982
  setSelectionRects([]);
3855
- syncImeCaretAnchor({
3856
- hiddenHost: hiddenPMRef.current?.getHostElement(),
3857
- editorView: hiddenPMRef.current?.getView(),
3858
- visibleCaret: null
3859
- });
3860
3983
  return;
3861
3984
  }
3862
3985
  if (pagesContainerRef.current) {
@@ -3870,9 +3993,8 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
3870
3993
  });
3871
3994
  const allCells = htmlQueryAll(pagesContainerRef.current, ".layout-table-cell");
3872
3995
  for (const cellEl of allCells) {
3873
- const pmStartAttr = cellEl.dataset["pmStart"];
3874
- if (pmStartAttr !== void 0) {
3875
- const pmPos_1 = Number(pmStartAttr);
3996
+ const pmPos_1 = readPaintedStart(cellEl);
3997
+ if (pmPos_1 !== void 0) {
3876
3998
  for (const [start, end] of selectedRanges) if (pmPos_1 >= start && pmPos_1 < end) {
3877
3999
  cellEl.classList.add("layout-table-cell-selected");
3878
4000
  break;
@@ -4005,7 +4127,10 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
4005
4127
  getCaretFromDom,
4006
4128
  selectionOverlayRequestGate,
4007
4129
  zoom,
4008
- markupView
4130
+ markupView,
4131
+ setSelectionRects,
4132
+ setCaretPosition,
4133
+ setDirectiveCaretPos
4009
4134
  ]);
4010
4135
  useLayoutEffect(() => {
4011
4136
  runtime.commitSelectionUpdate(updateSelectionOverlay);
@@ -4107,7 +4232,8 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
4107
4232
  layout,
4108
4233
  blocks,
4109
4234
  measures,
4110
- zoom
4235
+ zoom,
4236
+ setAnonymizationRectGroups
4111
4237
  ]);
4112
4238
  const updateAutocompleteOverlay = useCallback(() => {
4113
4239
  const requestIsLatest = autocompleteOverlayRequestGate.begin();
@@ -4157,7 +4283,9 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
4157
4283
  layout,
4158
4284
  blocks,
4159
4285
  measures,
4160
- zoom
4286
+ zoom,
4287
+ setAutocompleteText,
4288
+ setAutocompleteCaret
4161
4289
  ]);
4162
4290
  const updateDirectivesOverlay = useCallback(() => {
4163
4291
  const isCurrentRequest_2 = directivesOverlayRequestGate.begin();
@@ -4191,7 +4319,9 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
4191
4319
  layout,
4192
4320
  blocks,
4193
4321
  measures,
4194
- zoom
4322
+ zoom,
4323
+ setDirectiveProjection,
4324
+ setDirectiveGutter
4195
4325
  ]);
4196
4326
  const updateAISuggestionsOverlay = useCallback(() => {
4197
4327
  const isCurrentRequest_3 = aiSuggestionsOverlayRequestGate.begin();
@@ -4229,7 +4359,8 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
4229
4359
  layout,
4230
4360
  blocks,
4231
4361
  measures,
4232
- zoom
4362
+ zoom,
4363
+ setAiSuggestionRectGroups
4233
4364
  ]);
4234
4365
  const updatePassageHighlightOverlay = useCallback(() => {
4235
4366
  const isCurrentRequest_4 = passageHighlightOverlayRequestGate.begin();
@@ -4255,7 +4386,8 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
4255
4386
  layout,
4256
4387
  blocks,
4257
4388
  measures,
4258
- zoom
4389
+ zoom,
4390
+ setPassageHighlightRects
4259
4391
  ]);
4260
4392
  const setPassageHighlightImpl = useCallback((range_3) => {
4261
4393
  passageHighlightRangeRef.current = range_3;
@@ -4265,11 +4397,15 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
4265
4397
  return;
4266
4398
  }
4267
4399
  updatePassageHighlightOverlay();
4268
- }, [passageHighlightOverlayRequestGate, updatePassageHighlightOverlay]);
4400
+ }, [
4401
+ passageHighlightOverlayRequestGate,
4402
+ updatePassageHighlightOverlay,
4403
+ setPassageHighlightRects
4404
+ ]);
4269
4405
  const hideSelectionOverlayDuringInput = useCallback((state_4) => {
4270
4406
  selectionOverlayRequestGate.invalidate();
4271
4407
  suppressSelectionOverlayRef.current = true;
4272
- setCaretPosition(null);
4408
+ hideSelectionOverlay(selectionOverlayRef.current);
4273
4409
  setSelectionRects([]);
4274
4410
  if (revealSelectionOverlayTimerRef.current !== null) window.clearTimeout(revealSelectionOverlayTimerRef.current);
4275
4411
  revealSelectionOverlayTimerRef.current = window.setTimeout(() => {
@@ -4277,7 +4413,11 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
4277
4413
  suppressSelectionOverlayRef.current = false;
4278
4414
  updateSelectionOverlay(hiddenPMRef.current?.getState() ?? state_4);
4279
4415
  }, SELECTION_REVEAL_AFTER_INPUT_DELAY);
4280
- }, [selectionOverlayRequestGate, updateSelectionOverlay]);
4416
+ }, [
4417
+ selectionOverlayRequestGate,
4418
+ updateSelectionOverlay,
4419
+ setSelectionRects
4420
+ ]);
4281
4421
  useEffect(() => () => {
4282
4422
  selectionOverlayRequestGate.invalidate();
4283
4423
  anonymizationOverlayRequestGate.invalidate();
@@ -4357,6 +4497,7 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
4357
4497
  scheduleLayout,
4358
4498
  scheduleDocumentChangeNotification,
4359
4499
  hideSelectionOverlayDuringInput,
4500
+ setPassageHighlightRects,
4360
4501
  updateSelectionOverlay,
4361
4502
  updateAnonymizationOverlay,
4362
4503
  updateAutocompleteOverlay,
@@ -4381,7 +4522,7 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
4381
4522
  * state; the HF blocks are pulled from the HF PM via
4382
4523
  * `renderHfFromContentOrPm` on the next layout tick.
4383
4524
  */
4384
- const [hfCaretSelection, setHfCaretSelection] = useState(null);
4525
+ const [hfCaretSelection, setHfCaretSelection] = useEqualState(null);
4385
4526
  const [previousHfEditMode, setPreviousHfEditMode] = useState(hfEditMode);
4386
4527
  if (previousHfEditMode !== hfEditMode) {
4387
4528
  setPreviousHfEditMode(hfEditMode);
@@ -4414,7 +4555,8 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
4414
4555
  scheduleLayout,
4415
4556
  ensureHiddenEditorView,
4416
4557
  experimentalSession,
4417
- scheduleDocumentChangeNotification
4558
+ scheduleDocumentChangeNotification,
4559
+ setHfCaretSelection
4418
4560
  ]);
4419
4561
  const handleNoteStoryTransaction = useCallback((view_4, docChanged_1, selectionChanged_0) => {
4420
4562
  if (docChanged_1) scheduleLayout();
@@ -4428,9 +4570,9 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
4428
4570
  }
4429
4571
  }, [scheduleLayout]);
4430
4572
  const handleNoteDocumentChange = useCallback((updated) => {
4431
- onDocumentChangeRef.current?.(usesCanonicalSession(experimentalSession, CANONICAL_GAP.authorityRouting) ? cloneDocumentWithParagraphPropertySources(updated) : updated);
4432
- folioEmitterRef.current.emit("docChange", usesCanonicalSession(experimentalSession, CANONICAL_GAP.authorityRouting) ? cloneDocumentWithParagraphPropertySources(updated) : updated);
4433
- }, [experimentalSession]);
4573
+ onDocumentChangeRef.current?.(updated);
4574
+ folioEmitterRef.current.emit("docChange", updated);
4575
+ }, []);
4434
4576
  const dragSurfaceModeRef = useRef(hfEditMode);
4435
4577
  useEffect(() => {
4436
4578
  if (dragSurfaceModeRef.current === hfEditMode) return;
@@ -4468,7 +4610,10 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
4468
4610
  }, [
4469
4611
  updateSelectionOverlay,
4470
4612
  buildImageSelectionInfo,
4471
- syncCoordinator
4613
+ syncCoordinator,
4614
+ setSelectionRects,
4615
+ setCaretPosition,
4616
+ setSelectedImageInfo
4472
4617
  ]);
4473
4618
  /**
4474
4619
  * Get PM position from mouse coordinates using DOM-based detection.
@@ -4547,7 +4692,7 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
4547
4692
  "layout-image",
4548
4693
  "layout-page-floating-image"
4549
4694
  ];
4550
- const isImageContainer = (el_1) => !!el_1.dataset["pmStart"] && IMAGE_CONTAINER_CLASSES.some((c) => el_1.classList.contains(c));
4695
+ const isImageContainer = (el_1) => hasPaintedStart(el_1) && IMAGE_CONTAINER_CLASSES.some((c) => el_1.classList.contains(c));
4551
4696
  if (target.tagName === "IMG" && target.classList.contains("layout-run-image")) return target;
4552
4697
  if (target.tagName === "IMG" && target.parentElement && isImageContainer(target.parentElement)) return target.parentElement;
4553
4698
  if (isImageContainer(target)) return target;
@@ -4750,7 +4895,7 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
4750
4895
  target_1.classList.add("dragging");
4751
4896
  const colIndex = Number.parseInt(target_1.dataset["columnIndex"] ?? "0", 10);
4752
4897
  resizeColumnIndexRef.current = colIndex;
4753
- resizeTablePmStartRef.current = Number.parseInt(target_1.dataset["tablePmStart"] ?? "0", 10);
4898
+ resizeTablePmStartRef.current = readPaintedTableStart(target_1) ?? 0;
4754
4899
  const view_10 = resizeViewForRead;
4755
4900
  if (view_10) {
4756
4901
  const $pos_1 = view_10.state.doc.resolve(resizeTablePmStartRef.current + 1);
@@ -4783,7 +4928,7 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
4783
4928
  target_1.classList.add("dragging");
4784
4929
  const rowIndex = Number.parseInt(target_1.dataset["rowIndex"] ?? "0", 10);
4785
4930
  resizeRowIndexRef.current = rowIndex;
4786
- resizeRowTablePmStartRef.current = Number.parseInt(target_1.dataset["tablePmStart"] ?? "0", 10);
4931
+ resizeRowTablePmStartRef.current = readPaintedTableStart(target_1) ?? 0;
4787
4932
  const view_11 = resizeViewForRead;
4788
4933
  if (view_11) {
4789
4934
  const $pos_2 = view_11.state.doc.resolve(resizeRowTablePmStartRef.current + 1);
@@ -4818,7 +4963,7 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
4818
4963
  target_1.classList.add("dragging");
4819
4964
  const colIndex_0 = Number.parseInt(target_1.dataset["columnIndex"] ?? "0", 10);
4820
4965
  resizeRightEdgeColIndexRef.current = colIndex_0;
4821
- resizeRightEdgePmStartRef.current = Number.parseInt(target_1.dataset["tablePmStart"] ?? "0", 10);
4966
+ resizeRightEdgePmStartRef.current = readPaintedTableStart(target_1) ?? 0;
4822
4967
  const view_12 = resizeViewForRead;
4823
4968
  if (view_12) {
4824
4969
  const $pos_3 = view_12.state.doc.resolve(resizeRightEdgePmStartRef.current + 1);
@@ -4837,9 +4982,9 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
4837
4982
  if (!readOnly && imageEl) {
4838
4983
  e.preventDefault();
4839
4984
  e.stopPropagation();
4840
- const pmStart = imageEl.dataset["pmStart"];
4985
+ const pmStart = readPaintedStart(imageEl);
4841
4986
  if (pmStart !== void 0) {
4842
- const pos_1 = Number.parseInt(pmStart, 10);
4987
+ const pos_1 = pmStart;
4843
4988
  const hfSlot = hfEditMode ? findHfSlotForTarget(imageEl) : null;
4844
4989
  const hfView_0 = hfSlot ? hfPMsRef.current?.getView(hfSlot.rId) : null;
4845
4990
  if (hfView_0) {
@@ -4877,7 +5022,11 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
4877
5022
  queueHiddenEditorSelection,
4878
5023
  buildImageSelectionInfo,
4879
5024
  findImageElement,
4880
- findCellPosInDoc
5025
+ findCellPosInDoc,
5026
+ setSelectionRects,
5027
+ setCaretPosition,
5028
+ setSelectedImageInfo,
5029
+ setTableInsertButton
4881
5030
  ]);
4882
5031
  const { updateMousePosition: updateDragScroll, stopAutoScroll: stopDragAutoScroll } = useDragAutoScroll({
4883
5032
  pagesContainerRef,
@@ -5018,25 +5167,29 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
5018
5167
  * Handle mouseup - end drag selection.
5019
5168
  */
5020
5169
  const handleMouseUp = useCallback(() => {
5170
+ const runTableResize = (command) => {
5171
+ const surface = resizingHfSurfaceRef.current;
5172
+ resizingHfSurfaceRef.current = null;
5173
+ if (surface) {
5174
+ const view_13 = hfPMsRef.current?.getView(surface.rId);
5175
+ if (view_13) command(view_13.state, (tr) => view_13.dispatch(tr), view_13);
5176
+ return;
5177
+ }
5178
+ hiddenPMRef.current?.executeCommand(command);
5179
+ };
5021
5180
  if (isResizingColumnRef.current) {
5022
5181
  isResizingColumnRef.current = false;
5023
5182
  if (resizeHandleRef.current) {
5024
5183
  resizeHandleRef.current.classList.remove("dragging");
5025
5184
  resizeHandleRef.current = null;
5026
5185
  }
5027
- const view_13 = (resizingHfSurfaceRef.current ? hfPMsRef.current?.getView(resizingHfSurfaceRef.current.rId) : hiddenPMRef.current?.getView()) ?? null;
5028
- resizingHfSurfaceRef.current = null;
5029
- if (view_13) {
5030
- const pmStart_0 = resizeTablePmStartRef.current;
5031
- const colIdx = resizeColumnIndexRef.current;
5032
- const { left: newLeft, right: newRight } = resizeOrigWidthsRef.current;
5033
- commitColumnResize(view_13, {
5034
- pmStart: pmStart_0,
5035
- colIdx,
5036
- newLeft,
5037
- newRight
5038
- });
5039
- }
5186
+ const { left: newLeft, right: newRight } = resizeOrigWidthsRef.current;
5187
+ runTableResize(columnResizeCommand({
5188
+ pmStart: resizeTablePmStartRef.current,
5189
+ colIdx: resizeColumnIndexRef.current,
5190
+ newLeft,
5191
+ newRight
5192
+ }));
5040
5193
  return;
5041
5194
  }
5042
5195
  if (isResizingRowRef.current) {
@@ -5045,18 +5198,11 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
5045
5198
  resizeRowHandleRef.current.classList.remove("dragging");
5046
5199
  resizeRowHandleRef.current = null;
5047
5200
  }
5048
- const view_14 = (resizingHfSurfaceRef.current ? hfPMsRef.current?.getView(resizingHfSurfaceRef.current.rId) : hiddenPMRef.current?.getView()) ?? null;
5049
- resizingHfSurfaceRef.current = null;
5050
- if (view_14) {
5051
- const pmStart_1 = resizeRowTablePmStartRef.current;
5052
- const rowIdx = resizeRowIndexRef.current;
5053
- const newHeight = resizeRowOrigHeightRef.current;
5054
- commitRowResize(view_14, {
5055
- pmStart: pmStart_1,
5056
- rowIdx,
5057
- newHeight
5058
- });
5059
- }
5201
+ runTableResize(rowResizeCommand({
5202
+ pmStart: resizeRowTablePmStartRef.current,
5203
+ rowIdx: resizeRowIndexRef.current,
5204
+ newHeight: resizeRowOrigHeightRef.current
5205
+ }));
5060
5206
  return;
5061
5207
  }
5062
5208
  if (isResizingRightEdgeRef.current) {
@@ -5065,18 +5211,11 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
5065
5211
  resizeRightEdgeHandleRef.current.classList.remove("dragging");
5066
5212
  resizeRightEdgeHandleRef.current = null;
5067
5213
  }
5068
- const view_15 = (resizingHfSurfaceRef.current ? hfPMsRef.current?.getView(resizingHfSurfaceRef.current.rId) : hiddenPMRef.current?.getView()) ?? null;
5069
- resizingHfSurfaceRef.current = null;
5070
- if (view_15) {
5071
- const pmStart_2 = resizeRightEdgePmStartRef.current;
5072
- const colIdx_0 = resizeRightEdgeColIndexRef.current;
5073
- const newWidth_0 = resizeRightEdgeOrigWidthRef.current;
5074
- commitRightEdgeResize(view_15, {
5075
- pmStart: pmStart_2,
5076
- colIdx: colIdx_0,
5077
- newWidth: newWidth_0
5078
- });
5079
- }
5214
+ runTableResize(rightEdgeResizeCommand({
5215
+ pmStart: resizeRightEdgePmStartRef.current,
5216
+ colIdx: resizeRightEdgeColIndexRef.current,
5217
+ newWidth: resizeRightEdgeOrigWidthRef.current
5218
+ }));
5080
5219
  return;
5081
5220
  }
5082
5221
  isDraggingRef.current = false;
@@ -5162,7 +5301,7 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
5162
5301
  if (!viewportEl) return;
5163
5302
  const viewportRect = viewportEl.getBoundingClientRect();
5164
5303
  /** Extract PM position from a cell element */
5165
- const getCellPmPos = (el_2) => el_2 ? Number(el_2.dataset["pmStart"]) || 0 : 0;
5304
+ const getCellPmPos = (el_2) => el_2 ? readPaintedStart(el_2) || 0 : 0;
5166
5305
  if (nearLeftEdge) for (const row of rows) {
5167
5306
  const rowRect = row.getBoundingClientRect();
5168
5307
  if (mouseY >= rowRect.top && mouseY <= rowRect.bottom) {
@@ -5205,7 +5344,8 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
5205
5344
  }, [
5206
5345
  readOnly,
5207
5346
  clearTableInsertTimer,
5208
- zoom
5347
+ zoom,
5348
+ setTableInsertButton
5209
5349
  ]);
5210
5350
  /**
5211
5351
  * Handle table insert button click — set selection to target cell, then insert.
@@ -5214,16 +5354,16 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
5214
5354
  e_2.preventDefault();
5215
5355
  e_2.stopPropagation();
5216
5356
  if (!tableInsertButton || !hiddenPMRef.current) return;
5217
- const view_16 = hiddenPMRef.current.getView();
5218
- if (!view_16) return;
5357
+ const view_14 = hiddenPMRef.current.getView();
5358
+ if (!view_14) return;
5219
5359
  const { type, cellPmPos } = tableInsertButton;
5220
- const tr = view_16.state.tr.setSelection(TextSelection$1.create(view_16.state.doc, cellPmPos + 1));
5221
- view_16.dispatch(tr);
5222
- if (type === "row") addRowBelow(view_16.state, view_16.dispatch);
5223
- else addColumnRight(view_16.state, view_16.dispatch);
5360
+ const tr_0 = view_14.state.tr.setSelection(TextSelection$1.create(view_14.state.doc, cellPmPos + 1));
5361
+ view_14.dispatch(tr_0);
5362
+ if (type === "row") addRowBelow(view_14.state, view_14.dispatch);
5363
+ else addColumnRight(view_14.state, view_14.dispatch);
5224
5364
  setTableInsertButton(null);
5225
5365
  hiddenPMRef.current.focus();
5226
- }, [tableInsertButton]);
5366
+ }, [tableInsertButton, setTableInsertButton]);
5227
5367
  /**
5228
5368
  * Handle click on pages container (for double-click word selection).
5229
5369
  */
@@ -5247,10 +5387,10 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
5247
5387
  if (href.startsWith("#")) {
5248
5388
  const bookmarkName = href.slice(1);
5249
5389
  if (bookmarkName && hiddenPMRef.current) {
5250
- const view_17 = hiddenPMRef.current.getView();
5251
- if (view_17) {
5390
+ const view_15 = hiddenPMRef.current.getView();
5391
+ if (view_15) {
5252
5392
  const targetPos = { value: null };
5253
- view_17.state.doc.descendants((node_5, pos_2) => {
5393
+ view_15.state.doc.descendants((node_5, pos_2) => {
5254
5394
  if (targetPos.value !== null) return false;
5255
5395
  if (node_5.type.name === "paragraph") {
5256
5396
  if (node_5.attrs["bookmarks"]?.some((b) => b.name === bookmarkName)) {
@@ -5339,9 +5479,9 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
5339
5479
  if (e_3.detail === 2 && hiddenPMRef.current) {
5340
5480
  const pmPos_12 = getPositionFromMouse(e_3.clientX, e_3.clientY);
5341
5481
  if (pmPos_12 !== null) {
5342
- const view_18 = hiddenPMRef.current.getView();
5343
- if (view_18) {
5344
- const { doc: doc_0 } = view_18.state;
5482
+ const view_16 = hiddenPMRef.current.getView();
5483
+ if (view_16) {
5484
+ const { doc: doc_0 } = view_16.state;
5345
5485
  const $pos_6 = doc_0.resolve(pmPos_12);
5346
5486
  const parent_0 = $pos_6.parent;
5347
5487
  if (parent_0.isTextblock) {
@@ -5367,9 +5507,9 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
5367
5507
  if (e_3.detail === 3 && hiddenPMRef.current) {
5368
5508
  const pmPos_13 = getPositionFromMouse(e_3.clientX, e_3.clientY);
5369
5509
  if (pmPos_13 !== null) {
5370
- const view_19 = hiddenPMRef.current.getView();
5371
- if (view_19) {
5372
- const { doc: doc_1 } = view_19.state;
5510
+ const view_17 = hiddenPMRef.current.getView();
5511
+ if (view_17) {
5512
+ const { doc: doc_1 } = view_17.state;
5373
5513
  const $pos_7 = doc_1.resolve(pmPos_13);
5374
5514
  const paragraphStart = $pos_7.start($pos_7.depth);
5375
5515
  const paragraphEnd = $pos_7.end($pos_7.depth);
@@ -5416,9 +5556,9 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
5416
5556
  }
5417
5557
  }
5418
5558
  }
5419
- const view_20 = hiddenPMRef.current?.getView();
5420
- if (!view_20) return;
5421
- const { from: from_5, to: to_5 } = view_20.state.selection;
5559
+ const view_18 = hiddenPMRef.current?.getView();
5560
+ if (!view_18) return;
5561
+ const { from: from_5, to: to_5 } = view_18.state.selection;
5422
5562
  const pmPos_15 = getPositionFromMouse(e_4.clientX, e_4.clientY);
5423
5563
  if (pmPos_15 !== null && (from_5 === to_5 || pmPos_15 < from_5 || pmPos_15 > to_5)) {
5424
5564
  hiddenPMRef.current?.setSelection(pmPos_15);
@@ -5458,10 +5598,10 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
5458
5598
  /**
5459
5599
  * Handle image resize from the overlay.
5460
5600
  */
5461
- const handleImageResize = useCallback((pmPos_16, newWidth_1, newHeight_0) => {
5462
- const view_21 = hiddenPMRef.current?.getView();
5463
- if (!view_21) return;
5464
- const committed = commitImageResize(view_21, pmPos_16, newWidth_1, newHeight_0);
5601
+ const handleImageResize = useCallback((pmPos_16, newWidth_0, newHeight) => {
5602
+ const view_19 = hiddenPMRef.current?.getView();
5603
+ if (!view_19) return;
5604
+ const committed = commitImageResize(view_19, pmPos_16, newWidth_0, newHeight);
5465
5605
  if (committed !== null) hiddenPMRef.current?.setNodeSelection(committed);
5466
5606
  }, []);
5467
5607
  /**
@@ -5481,10 +5621,10 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
5481
5621
  * to the drop position determined by mouse coordinates.
5482
5622
  */
5483
5623
  const handleImageDragMove = useCallback((pmPos_17, clientX_1, clientY_1) => {
5484
- const view_22 = hiddenPMRef.current?.getView();
5485
- if (!view_22) return;
5624
+ const view_20 = hiddenPMRef.current?.getView();
5625
+ if (!view_20) return;
5486
5626
  try {
5487
- const node_8 = view_22.state.doc.nodeAt(pmPos_17);
5627
+ const node_8 = view_20.state.doc.nodeAt(pmPos_17);
5488
5628
  if (!node_8 || node_8.type.name !== "image") return;
5489
5629
  let committed_0 = null;
5490
5630
  if (isFloatingImage(node_8)) {
@@ -5509,11 +5649,11 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
5509
5649
  const PIXELS_TO_EMU = 9525;
5510
5650
  const hOffsetEmu = Math.round(dropX * PIXELS_TO_EMU);
5511
5651
  const vOffsetEmu = Math.round(dropY * PIXELS_TO_EMU);
5512
- committed_0 = commitImageFloatMove(view_22, pmPos_17, hOffsetEmu, vOffsetEmu);
5652
+ committed_0 = commitImageFloatMove(view_20, pmPos_17, hOffsetEmu, vOffsetEmu);
5513
5653
  } else {
5514
5654
  const dropPos = getPositionFromMouse(clientX_1, clientY_1);
5515
5655
  if (dropPos === null) return;
5516
- committed_0 = commitImageInlineMove(view_22, pmPos_17, dropPos);
5656
+ committed_0 = commitImageInlineMove(view_20, pmPos_17, dropPos);
5517
5657
  }
5518
5658
  if (committed_0 !== null) hiddenPMRef.current?.setNodeSelection(committed_0);
5519
5659
  } catch {}
@@ -5536,8 +5676,8 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
5536
5676
  }
5537
5677
  if (readOnly) {
5538
5678
  if ((e_7.metaKey || e_7.ctrlKey) && e_7.key.toLowerCase() === "a" || e_7.shiftKey && /^(?:Arrow(?:Left|Right|Up|Down)|Home|End|PageUp|PageDown)$/u.test(e_7.key)) {
5539
- const view_23 = hiddenPMRef.current?.getView();
5540
- if (view_23?.someProp("handleKeyDown", (handler) => handler(view_23, e_7.nativeEvent)) ?? false) {
5679
+ const view_21 = hiddenPMRef.current?.getView();
5680
+ if (view_21?.someProp("handleKeyDown", (handler) => handler(view_21, e_7.nativeEvent)) ?? false) {
5541
5681
  e_7.preventDefault();
5542
5682
  return;
5543
5683
  }
@@ -5549,11 +5689,11 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
5549
5689
  return;
5550
5690
  }
5551
5691
  if (e_7.target instanceof HTMLElement && e_7.target.closest("[data-hf-r-id], [data-note-kind][data-note-id]")) return;
5552
- let view_24 = hiddenPMRef.current?.getView();
5553
- if (!view_24) {
5692
+ let view_22 = hiddenPMRef.current?.getView();
5693
+ if (!view_22) {
5554
5694
  ensureHiddenEditorView({ sync: true });
5555
- view_24 = hiddenPMRef.current?.getView();
5556
- if (view_24) {
5695
+ view_22 = hiddenPMRef.current?.getView();
5696
+ if (view_22) {
5557
5697
  if (isPlainTextInputEvent(e_7)) {
5558
5698
  e_7.preventDefault();
5559
5699
  queueHiddenEditorTextInput(e_7.key);
@@ -5576,7 +5716,7 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
5576
5716
  }
5577
5717
  return;
5578
5718
  }
5579
- if (pendingHiddenEditorSelectionRef.current || queuedInputBeforeHiddenEditorRef.current.length > 0) applyPendingHiddenEditorInput(view_24);
5719
+ if (pendingHiddenEditorSelectionRef.current || queuedInputBeforeHiddenEditorRef.current.length > 0) applyPendingHiddenEditorInput(view_22);
5580
5720
  if (!hiddenPMRef.current?.isFocused()) focusHiddenEditor();
5581
5721
  if (["PageUp", "PageDown"].includes(e_7.key) && !e_7.metaKey && !e_7.ctrlKey) {}
5582
5722
  if (e_7.key === "Home" && (e_7.metaKey || e_7.ctrlKey)) {
@@ -5660,20 +5800,20 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
5660
5800
  /**
5661
5801
  * Run initial layout when document or view changes.
5662
5802
  */
5663
- const handleEditorViewReady = useCallback((view_25) => {
5664
- onEditorViewReadyRef.current?.(view_25);
5665
- anonymizationMatchesRef.current = anonymizationDecorationsKey.getState(view_25.state)?.matches ?? [];
5666
- const initialSuggestion = autocompleteSuggestionKey.getState(view_25.state)?.suggestion;
5803
+ const handleEditorViewReady = useCallback((view_23) => {
5804
+ onEditorViewReadyRef.current?.(view_23);
5805
+ anonymizationMatchesRef.current = anonymizationDecorationsKey.getState(view_23.state)?.matches ?? [];
5806
+ const initialSuggestion = autocompleteSuggestionKey.getState(view_23.state)?.suggestion;
5667
5807
  if (initialSuggestion !== void 0) autocompleteSuggestionRef.current = initialSuggestion;
5668
5808
  updateAutocompleteOverlay();
5669
- directivesRef.current = templateDirectivesKey.getState(view_25.state)?.ranges ?? [];
5670
- const previewState = templatePreviewValuesKey.getState(view_25.state);
5809
+ directivesRef.current = templateDirectivesKey.getState(view_23.state)?.ranges ?? [];
5810
+ const previewState = templatePreviewValuesKey.getState(view_23.state);
5671
5811
  templatePreviewRef.current = {
5672
5812
  entries: previewState?.entries ?? EMPTY_TEMPLATE_PREVIEW_ENTRIES,
5673
5813
  hidden: previewState?.hidden ?? EMPTY_TEMPLATE_PREVIEW_HIDDEN,
5674
5814
  mode: previewState?.preview?.mode ?? "plain"
5675
5815
  };
5676
- const aiState = aiSuggestionDecorationsKey.getState(view_25.state);
5816
+ const aiState = aiSuggestionDecorationsKey.getState(view_23.state);
5677
5817
  aiSuggestionsRef.current = {
5678
5818
  suggestions: aiState?.suggestions ?? EMPTY_AI_SUGGESTIONS,
5679
5819
  focusedId: aiState?.focusedId ?? null
@@ -5681,17 +5821,17 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
5681
5821
  const focusReadyView = () => {
5682
5822
  if (readOnly || !shouldFocusHiddenEditorOnReadyRef.current) return;
5683
5823
  requestAnimationFrame(() => {
5684
- if (hiddenPMRef.current?.getView() !== view_25) return;
5685
- applyPendingHiddenEditorInput(view_25);
5686
- view_25.focus();
5824
+ if (hiddenPMRef.current?.getView() !== view_23) return;
5825
+ applyPendingHiddenEditorInput(view_23);
5826
+ view_23.focus();
5687
5827
  refreshBodyImeCaretAnchor();
5688
5828
  setIsFocused(true);
5689
5829
  });
5690
5830
  };
5691
- if (layoutSessionRef.current.lastPmDoc?.eq(view_25.state.doc) && layoutSessionRef.current.lastMeasureInputs?.markupView === markupView && layoutSessionRef.current.lastMeasureInputs?.showCommentHighlights === (showCommentHighlights && markupView !== "no-markup" && markupView !== "original")) {
5831
+ if (layoutSessionRef.current.lastPmDoc?.eq(view_23.state.doc) && layoutSessionRef.current.lastMeasureInputs?.markupView === markupView && layoutSessionRef.current.lastMeasureInputs?.showCommentHighlights === (showCommentHighlights && markupView !== "no-markup" && markupView !== "original")) {
5692
5832
  const lastPreview = layoutSessionRef.current.lastTemplatePreview;
5693
- if (templatePreviewRef.current.mode !== lastPreview.mode || templatePreviewDirtyRange(lastPreview, templatePreviewRef.current) !== null) runLayoutPipeline$1(view_25.state, { reason: "manual" });
5694
- updateSelectionOverlay(view_25.state);
5833
+ if (templatePreviewRef.current.mode !== lastPreview.mode || templatePreviewDirtyRange(lastPreview, templatePreviewRef.current) !== null) runLayoutPipeline$1(view_23.state, { reason: "manual" });
5834
+ updateSelectionOverlay(view_23.state);
5695
5835
  updateAnonymizationOverlay();
5696
5836
  updateDirectivesOverlay();
5697
5837
  updateAISuggestionsOverlay();
@@ -5710,13 +5850,13 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
5710
5850
  const runAfterFontWait_0 = () => {
5711
5851
  pendingInitialFontReadyLayoutRef.current = false;
5712
5852
  const currentView_0 = hiddenPMRef.current?.getView();
5713
- if (currentView_0 !== view_25) return;
5853
+ if (currentView_0 !== view_23) return;
5714
5854
  recordLayoutPhase("initial", "initial-fonts", performance.now() - fontWaitStartedAt_0);
5715
5855
  resetCanvasContext();
5716
5856
  clearAllCaches();
5717
5857
  runInitialLayout(currentView_0);
5718
5858
  };
5719
- waitForInitialLayoutFonts(document, view_25.state.doc).then(runAfterFontWait_0, runAfterFontWait_0);
5859
+ waitForInitialLayoutFonts(document, view_23.state.doc).then(runAfterFontWait_0, runAfterFontWait_0);
5720
5860
  focusReadyView();
5721
5861
  }, [
5722
5862
  applyPendingHiddenEditorInput,
@@ -5775,11 +5915,11 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
5775
5915
  measuredFontSet: () => layoutSessionRef.current.lastMeasureInputs?.fontSet ?? null,
5776
5916
  relayout: () => {
5777
5917
  if (pendingInitialFontReadyLayoutRef.current) return;
5778
- const view_26 = hiddenPMRef.current?.getView();
5779
- const state_7 = view_26?.state ?? layoutSessionRef.current.lastEditorState;
5918
+ const view_24 = hiddenPMRef.current?.getView();
5919
+ const state_7 = view_24?.state ?? layoutSessionRef.current.lastEditorState;
5780
5920
  if (!state_7) return;
5781
5921
  runLayoutPipelineRef.current(state_7, { reason: "font-ready" });
5782
- if (view_26) runtime.updateSelection(view_26.state);
5922
+ if (view_24) runtime.updateSelection(view_24.state);
5783
5923
  }
5784
5924
  }), [runtime]);
5785
5925
  const embeddedFontBuffer = document?.originalBuffer ?? null;
@@ -5795,12 +5935,12 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
5795
5935
  registered = faces;
5796
5936
  if (faces.length === 0 && familyMap.size === 0) return;
5797
5937
  layoutSessionRef.current.embeddedFontFamilyMap = new Map(familyMap);
5798
- const view_27 = hiddenPMRef.current?.getView();
5799
- if (!view_27) return;
5938
+ const view_25 = hiddenPMRef.current?.getView();
5939
+ if (!view_25) return;
5800
5940
  resetCanvasContext();
5801
5941
  clearAllCaches();
5802
- runLayoutPipelineRef.current(view_27.state, { reason: "font-ready" });
5803
- runtime.updateSelection(view_27.state);
5942
+ runLayoutPipelineRef.current(view_25.state, { reason: "font-ready" });
5943
+ runtime.updateSelection(view_25.state);
5804
5944
  });
5805
5945
  return () => {
5806
5946
  cancelled_1 = true;
@@ -5813,12 +5953,12 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
5813
5953
  const lifecycle = new FontFaceLifecycle(removeFontFaces);
5814
5954
  hostFontLifecycleRef.current = lifecycle;
5815
5955
  const remeasureForFontChange = () => {
5816
- const view_28 = hiddenPMRef.current?.getView();
5817
- if (!view_28) return;
5956
+ const view_26 = hiddenPMRef.current?.getView();
5957
+ if (!view_26) return;
5818
5958
  resetCanvasContext();
5819
5959
  clearAllCaches();
5820
- runLayoutPipelineRef.current(view_28.state, { reason: "font-ready" });
5821
- runtime.updateSelection(view_28.state);
5960
+ runLayoutPipelineRef.current(view_26.state, { reason: "font-ready" });
5961
+ runtime.updateSelection(view_26.state);
5822
5962
  };
5823
5963
  const unsubscribe = lifecycle.subscribe(remeasureForFontChange);
5824
5964
  return () => {
@@ -5917,15 +6057,15 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
5917
6057
  setIsFocused(true);
5918
6058
  },
5919
6059
  blur() {
5920
- const view_29 = getActiveEditorStory().view;
5921
- if (view_29?.hasFocus() && view_29.dom instanceof HTMLElement) view_29.dom.blur();
6060
+ const view_27 = getActiveEditorStory().view;
6061
+ if (view_27?.hasFocus() && view_27.dom instanceof HTMLElement) view_27.dom.blur();
5922
6062
  setIsFocused(false);
5923
6063
  },
5924
6064
  isFocused() {
5925
6065
  return getActiveEditorStory().view?.hasFocus() ?? false;
5926
6066
  },
5927
- dispatch(tr_0) {
5928
- folioEditor.dispatch(tr_0);
6067
+ dispatch(tr_1) {
6068
+ folioEditor.dispatch(tr_1);
5929
6069
  },
5930
6070
  undo() {
5931
6071
  const target_5 = getActiveEditorStory();
@@ -5985,12 +6125,12 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
5985
6125
  let bestNumber = null;
5986
6126
  let bestStart = Number.NEGATIVE_INFINITY;
5987
6127
  for (const shell_0 of shells) {
5988
- const anchors = shell_0.querySelectorAll("[data-pm-start]");
6128
+ const anchors = shell_0.querySelectorAll(PAINTED_START_SELECTOR);
5989
6129
  if (anchors.length === 0) continue;
5990
6130
  let pageStart = Number.POSITIVE_INFINITY;
5991
6131
  let pageEnd = Number.NEGATIVE_INFINITY;
5992
6132
  for (const el_3 of anchors) {
5993
- const pm = Number(el_3.dataset["pmStart"]);
6133
+ const pm = readPaintedStart(el_3) ?? NaN;
5994
6134
  if (!Number.isFinite(pm)) continue;
5995
6135
  if (pm < pageStart) pageStart = pm;
5996
6136
  if (pm > pageEnd) pageEnd = pm;
@@ -6123,6 +6263,7 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
6123
6263
  readOnly,
6124
6264
  onTransaction: handleHfPmTransaction,
6125
6265
  getCanonicalApi,
6266
+ readCanonicalDocument,
6126
6267
  onSessionRefusal: handleSessionRefusal,
6127
6268
  ...!usesCanonicalSession(experimentalSession, CANONICAL_GAP.authorityRouting) ? {} : { experimentalSession },
6128
6269
  ...styles !== void 0 ? { styles } : {},
@@ -6133,6 +6274,7 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
6133
6274
  document,
6134
6275
  onActiveChange: handleActiveNoteStoryChange,
6135
6276
  getCanonicalApi,
6277
+ readCanonicalDocument,
6136
6278
  onSessionRefusal: handleSessionRefusal,
6137
6279
  ...!usesCanonicalSession(experimentalSession, CANONICAL_GAP.authorityRouting) ? {} : { experimentalSession },
6138
6280
  onDocumentChange: handleNoteDocumentChange,
@@ -6211,7 +6353,8 @@ const PagedEditor = forwardRef(function PagedEditor(props, ref) {
6211
6353
  caretPosition: hfEditMode || noteStoryActive ? null : caretPosition,
6212
6354
  isFocused,
6213
6355
  pageGap,
6214
- markCaretRect: true
6356
+ markCaretRect: true,
6357
+ overlayRef: selectionOverlayRef
6215
6358
  }),
6216
6359
  hfCaretSelection && /* @__PURE__ */ jsx(HfCaretOverlay, {
6217
6360
  selection: hfCaretSelection,
@@ -6301,6 +6444,7 @@ function resolveCommentCreationRange({ docSize, capturedRange, currentRange, sav
6301
6444
  })();
6302
6445
  return range ? clampCommentMarkRange(docSize, range) : null;
6303
6446
  }
6447
+ // src/components/commentsHelpers.ts
6304
6448
  /** Stable empty anchor positions Map used as the initial state. */
6305
6449
  const EMPTY_ANCHOR_POSITIONS = /* @__PURE__ */ new Map();
6306
6450
  function getCommentAuthorKey(author) {
@@ -6318,8 +6462,8 @@ function findSelectionYPosition(scrollContainer, parentEl, pmPos) {
6318
6462
  const pagesEl = scrollContainer.querySelector(".paged-editor__pages");
6319
6463
  if (!pagesEl) return null;
6320
6464
  for (const el of findBodyPmAnchors(pagesEl)) {
6321
- const pmStart = Number(el.dataset["pmStart"]);
6322
- const pmEnd = Number(el.dataset["pmEnd"]);
6465
+ const pmStart = readPaintedStart(el) ?? NaN;
6466
+ const pmEnd = readPaintedEnd(el) ?? NaN;
6323
6467
  if (pmPos >= pmStart && pmPos <= pmEnd) return el.getBoundingClientRect().top - scrollContainer.getBoundingClientRect().top + scrollContainer.scrollTop;
6324
6468
  }
6325
6469
  return null;
@@ -6370,23 +6514,6 @@ function countOpenCommentThreads(comments) {
6370
6514
  }
6371
6515
  return count;
6372
6516
  }
6373
- function applyCommentMarkRange(view, range, commentId, options) {
6374
- const commentMark = view.state.schema.marks["comment"];
6375
- const safeRange = clampCommentMarkRange(view.state.doc.content.size, range);
6376
- if (!commentMark || !safeRange) return false;
6377
- let tr = view.state.tr;
6378
- if (options?.replacePending) tr = tr.removeMark(safeRange.from, safeRange.to, commentMark.create({ commentId: -1 }));
6379
- tr = tr.addMark(safeRange.from, safeRange.to, commentMark.create({ commentId }));
6380
- if (options?.selectEnd) tr = tr.setSelection(Selection.near(tr.doc.resolve(safeRange.to), -1));
6381
- view.dispatch(tr);
6382
- return true;
6383
- }
6384
- function removePendingCommentMarkRange(view, range) {
6385
- const commentMark = view.state.schema.marks["comment"];
6386
- const safeRange = clampCommentMarkRange(view.state.doc.content.size, range);
6387
- if (!commentMark || !safeRange) return;
6388
- view.dispatch(view.state.tr.removeMark(safeRange.from, safeRange.to, commentMark.create({ commentId: -1 })));
6389
- }
6390
6517
  // src/components/ContentControlWidgetsOverlay.tsx
6391
6518
  /** Thin React renderer for the shared content-control widget controller. */
6392
6519
  function ContentControlWidgetsOverlay(t0) {
@@ -6517,7 +6644,7 @@ function ContentControlWidgetsOverlay(t0) {
6517
6644
  "aria-label": t11,
6518
6645
  style,
6519
6646
  className: "bg-popover text-popover-foreground min-w-[10rem] rounded-md border p-1 shadow-md",
6520
- onPointerDown: _temp$13,
6647
+ onPointerDown: _temp$12,
6521
6648
  children: [t12, t13]
6522
6649
  })
6523
6650
  }), document.body);
@@ -6529,7 +6656,7 @@ function ContentControlWidgetsOverlay(t0) {
6529
6656
  } else t14 = $[31];
6530
6657
  return t14;
6531
6658
  }
6532
- function _temp$13(event) {
6659
+ function _temp$12(event) {
6533
6660
  return event.stopPropagation();
6534
6661
  }
6535
6662
  function ContentControlDropdownItem(t0) {
@@ -6641,7 +6768,7 @@ function useFindReplace$1(hookOptions) {
6641
6768
  let t6;
6642
6769
  if ($[8] === Symbol.for("react.memo_cache_sentinel")) {
6643
6770
  t6 = () => {
6644
- setState(_temp$12);
6771
+ setState(_temp$11);
6645
6772
  };
6646
6773
  $[8] = t6;
6647
6774
  } else t6 = $[8];
@@ -6649,7 +6776,7 @@ function useFindReplace$1(hookOptions) {
6649
6776
  let t7;
6650
6777
  if ($[9] === Symbol.for("react.memo_cache_sentinel")) {
6651
6778
  t7 = () => {
6652
- setState(_temp2$6);
6779
+ setState(_temp2$5);
6653
6780
  };
6654
6781
  $[9] = t7;
6655
6782
  } else t7 = $[9];
@@ -6799,13 +6926,13 @@ function useFindReplace$1(hookOptions) {
6799
6926
  } else t17 = $[27];
6800
6927
  return t17;
6801
6928
  }
6802
- function _temp2$6(prev_2) {
6929
+ function _temp2$5(prev_2) {
6803
6930
  return {
6804
6931
  ...prev_2,
6805
6932
  ...prev_2.dialog.status === "closed" ? openDialogState(prev_2.lastMode) : closedDialogState(prev_2.lastMode)
6806
6933
  };
6807
6934
  }
6808
- function _temp$12(prev_1) {
6935
+ function _temp$11(prev_1) {
6809
6936
  return {
6810
6937
  ...prev_1,
6811
6938
  ...closedDialogState(prev_1.lastMode)
@@ -6968,7 +7095,7 @@ const DocumentOutline = (t0) => {
6968
7095
  const controlMinimumStyle = t4;
6969
7096
  let t5;
6970
7097
  if ($[4] !== headings) {
6971
- t5 = headings.map(_temp$11);
7098
+ t5 = headings.map(_temp$10);
6972
7099
  $[4] = headings;
6973
7100
  $[5] = t5;
6974
7101
  } else t5 = $[5];
@@ -7280,7 +7407,7 @@ const DocumentOutline = (t0) => {
7280
7407
  } else t30 = $[92];
7281
7408
  return t30;
7282
7409
  };
7283
- function _temp$11(heading) {
7410
+ function _temp$10(heading) {
7284
7411
  const item = {
7285
7412
  id: heading.id,
7286
7413
  label: heading.text,
@@ -7677,7 +7804,7 @@ function NotificationContainer(t0) {
7677
7804
  if ($[0] !== notifications || $[1] !== onDismiss) {
7678
7805
  t3 = Symbol.for("react.early_return_sentinel");
7679
7806
  bb0: {
7680
- const visibleNotifications = notifications.filter(_temp$10);
7807
+ const visibleNotifications = notifications.filter(_temp$9);
7681
7808
  if (visibleNotifications.length === 0) {
7682
7809
  t3 = null;
7683
7810
  break bb0;
@@ -7717,7 +7844,7 @@ function NotificationContainer(t0) {
7717
7844
  } else t4 = $[9];
7718
7845
  return t4;
7719
7846
  }
7720
- function _temp$10(n) {
7847
+ function _temp$9(n) {
7721
7848
  return !n.dismissed;
7722
7849
  }
7723
7850
  const SEVERITY_STYLES = {
@@ -8157,7 +8284,7 @@ function AlignmentButtons({ value = "left", onChange, disabled = false }) {
8157
8284
  function AlignmentOption(t0) {
8158
8285
  const $ = c(16);
8159
8286
  const { PopoverClose, option, selected, onChange } = t0;
8160
- const handleMouseDown = _temp$9;
8287
+ const handleMouseDown = _temp$8;
8161
8288
  let t1;
8162
8289
  if ($[0] !== onChange || $[1] !== option.value) {
8163
8290
  t1 = () => onChange?.(option.value);
@@ -8211,7 +8338,7 @@ function AlignmentOption(t0) {
8211
8338
  } else t8 = $[15];
8212
8339
  return t8;
8213
8340
  }
8214
- function _temp$9(event) {
8341
+ function _temp$8(event) {
8215
8342
  return event.preventDefault();
8216
8343
  }
8217
8344
  // src/components/ui/FontPicker.tsx
@@ -9425,14 +9552,14 @@ const useActiveHeading = (container, headings) => {
9425
9552
  const threshold = container.scrollTop + container.clientHeight / 2;
9426
9553
  const offsets = [];
9427
9554
  for (const el of anchors) {
9428
- const pm = Number(el.dataset.pmStart);
9555
+ const pm = readPaintedStart(el) ?? NaN;
9429
9556
  if (!Number.isFinite(pm)) continue;
9430
9557
  offsets.push({
9431
9558
  pm,
9432
9559
  top: el.getBoundingClientRect().top - containerTop + container.scrollTop
9433
9560
  });
9434
9561
  }
9435
- offsets.sort(_temp$8);
9562
+ offsets.sort(_temp$7);
9436
9563
  let next = null;
9437
9564
  for (const heading of headings) {
9438
9565
  const candidate = offsets.find((offset) => offset.pm >= heading.pmPos);
@@ -9482,7 +9609,7 @@ const useActiveHeading = (container, headings) => {
9482
9609
  } else t3 = $[6];
9483
9610
  return t3;
9484
9611
  };
9485
- function _temp$8(a, b) {
9612
+ function _temp$7(a, b) {
9486
9613
  return a.pm - b.pm;
9487
9614
  }
9488
9615
  // src/components/selectionDetection.ts
@@ -10680,8 +10807,8 @@ const useHyperlinkHandlers = (t0) => {
10680
10807
  $[0] = t1;
10681
10808
  } else t1 = $[0];
10682
10809
  const handleHyperlinkClick = t1;
10683
- const handleHyperlinkPopupNavigate = _temp$7;
10684
- const handleHyperlinkPopupCopy = _temp2$5;
10810
+ const handleHyperlinkPopupNavigate = _temp$6;
10811
+ const handleHyperlinkPopupCopy = _temp2$4;
10685
10812
  let t2;
10686
10813
  if ($[1] !== focusActiveEditor || $[2] !== getActiveEditorView) {
10687
10814
  t2 = (displayText, href_1) => {
@@ -10742,14 +10869,14 @@ const useHyperlinkHandlers = (t0) => {
10742
10869
  } else t5 = $[12];
10743
10870
  return t5;
10744
10871
  };
10745
- function _temp$7(href) {
10872
+ function _temp$6(href) {
10746
10873
  const safeHref = sanitizeExternalUrl(href);
10747
10874
  if (safeHref) {
10748
10875
  const anchor = anchorTargetAttrs(void 0);
10749
10876
  window.open(safeHref, anchor.target, windowFeaturesFor(anchor));
10750
10877
  }
10751
10878
  }
10752
- function _temp2$5(href_0) {
10879
+ function _temp2$4(href_0) {
10753
10880
  navigator.clipboard.writeText(href_0);
10754
10881
  }
10755
10882
  // src/components/hooks/useImageHandlers.ts
@@ -10765,7 +10892,7 @@ const useImageHandlers = (t0) => {
10765
10892
  if (!file) return;
10766
10893
  const view = getActiveEditorView();
10767
10894
  if (!view) return;
10768
- insertImageFromFile(view, file, focusActiveEditor).catch(_temp$6);
10895
+ insertImageFromFile(view, file, focusActiveEditor).catch(_temp$5);
10769
10896
  e.target.value = "";
10770
10897
  };
10771
10898
  $[0] = focusActiveEditor;
@@ -10858,7 +10985,7 @@ const useImageHandlers = (t0) => {
10858
10985
  } else t7 = $[27];
10859
10986
  return t7;
10860
10987
  };
10861
- function _temp$6() {}
10988
+ function _temp$5() {}
10862
10989
  // src/components/hooks/useKeyboardShortcuts.ts
10863
10990
  /**
10864
10991
  * Page-level keyboard shortcuts:
@@ -10938,7 +11065,7 @@ function useKeyboardShortcuts(t0) {
10938
11065
  const handleKeyDown = (e_0) => {
10939
11066
  if (!isKeydownInShortcutScope(e_0, {
10940
11067
  scope,
10941
- roots: callbacksRef.current.roots.map(_temp$5)
11068
+ roots: callbacksRef.current.roots.map(_temp$4)
10942
11069
  })) return;
10943
11070
  const editorDom = pagedEditorRef.current?.getView()?.dom;
10944
11071
  switch (classifyEditorKeydown(e_0, {
@@ -10976,7 +11103,7 @@ function useKeyboardShortcuts(t0) {
10976
11103
  }
10977
11104
  useEffect(t3, t4);
10978
11105
  }
10979
- function _temp$5(root) {
11106
+ function _temp$4(root) {
10980
11107
  return root.current;
10981
11108
  }
10982
11109
  // src/components/hooks/usePanelLayout.ts
@@ -11092,7 +11219,7 @@ function useZoomAndPageInfo(t0) {
11092
11219
  t2 = () => {
11093
11220
  if (scrollFadeTimerRef.current) clearTimeout(scrollFadeTimerRef.current);
11094
11221
  scrollFadeTimerRef.current = setTimeout(() => {
11095
- setScrollPageInfo(_temp$4);
11222
+ setScrollPageInfo(_temp$3);
11096
11223
  }, PAGE_INFO_FADE_MS);
11097
11224
  };
11098
11225
  $[1] = t2;
@@ -11104,7 +11231,7 @@ function useZoomAndPageInfo(t0) {
11104
11231
  const layout = pagedEditorRef.current?.getLayout();
11105
11232
  if (!layout) return;
11106
11233
  const info = computeScrollPageInfo({
11107
- pageHeights: layout.pages.map(_temp2$4),
11234
+ pageHeights: layout.pages.map(_temp2$3),
11108
11235
  scrollTop: scrollContainer.scrollTop,
11109
11236
  clientHeight: scrollContainer.clientHeight,
11110
11237
  zoom: zoomRef.current,
@@ -11289,10 +11416,10 @@ function useZoomAndPageInfo(t0) {
11289
11416
  } else t13 = $[28];
11290
11417
  return t13;
11291
11418
  }
11292
- function _temp2$4(page) {
11419
+ function _temp2$3(page) {
11293
11420
  return page.size.h;
11294
11421
  }
11295
- function _temp$4(prev) {
11422
+ function _temp$3(prev) {
11296
11423
  return {
11297
11424
  ...prev,
11298
11425
  visible: false
@@ -11342,15 +11469,26 @@ const labelStyle = {
11342
11469
  fontWeight: 500,
11343
11470
  letterSpacing: .3
11344
11471
  };
11345
- const InlineHeaderFooterEditor = forwardRef(function InlineHeaderFooterEditor({ position, targetElement, parentElement, getActiveView, onClose, onRemove }, ref) {
11472
+ const InlineHeaderFooterEditor = forwardRef(function InlineHeaderFooterEditor({ position, targetSelector, parentElement, getActiveView, onClose, onRemove }, ref) {
11346
11473
  const t = useTranslations("folio");
11347
11474
  const [showOptions, setShowOptions] = useState(false);
11348
11475
  const optionsRef = useRef(null);
11349
- const [overlayPos, setOverlayPos] = useState(null);
11476
+ const [overlayPos, setOverlayPos] = useEqualState(null);
11350
11477
  useEffect(() => {
11478
+ let observed = null;
11479
+ const resizeObserver = new ResizeObserver(() => {
11480
+ computePosition();
11481
+ });
11351
11482
  const computePosition = () => {
11483
+ const target = parentElement.querySelector(targetSelector);
11484
+ if (target !== observed) {
11485
+ if (observed !== null) resizeObserver.unobserve(observed);
11486
+ if (target !== null) resizeObserver.observe(target);
11487
+ observed = target;
11488
+ }
11489
+ if (target === null) return;
11352
11490
  const parentRect = parentElement.getBoundingClientRect();
11353
- const targetRect = targetElement.getBoundingClientRect();
11491
+ const targetRect = target.getBoundingClientRect();
11354
11492
  setOverlayPos({
11355
11493
  top: targetRect.top - parentRect.top + parentElement.scrollTop,
11356
11494
  left: targetRect.left - parentRect.left + parentElement.scrollLeft,
@@ -11359,17 +11497,21 @@ const InlineHeaderFooterEditor = forwardRef(function InlineHeaderFooterEditor({
11359
11497
  });
11360
11498
  };
11361
11499
  computePosition();
11362
- const resizeObserver = new ResizeObserver(computePosition);
11363
- resizeObserver.observe(targetElement);
11500
+ parentElement.addEventListener(PAINTER_PAINTED_EVENT, computePosition);
11364
11501
  const scrollParent = parentElement.closest("[style*=\"overflow\"]") || parentElement;
11365
11502
  scrollParent.addEventListener("scroll", computePosition);
11366
11503
  window.addEventListener("resize", computePosition);
11367
11504
  return () => {
11368
11505
  resizeObserver.disconnect();
11506
+ parentElement.removeEventListener(PAINTER_PAINTED_EVENT, computePosition);
11369
11507
  scrollParent.removeEventListener("scroll", computePosition);
11370
11508
  window.removeEventListener("resize", computePosition);
11371
11509
  };
11372
- }, [targetElement, parentElement]);
11510
+ }, [
11511
+ parentElement,
11512
+ targetSelector,
11513
+ setOverlayPos
11514
+ ]);
11373
11515
  const getActiveViewRef = useRef(getActiveView);
11374
11516
  useLayoutEffect(() => {
11375
11517
  getActiveViewRef.current = getActiveView;
@@ -11507,7 +11649,7 @@ function OptionsMenu(t0) {
11507
11649
  if ($[3] !== setShowOptions) {
11508
11650
  t3 = (e) => {
11509
11651
  e.stopPropagation();
11510
- setShowOptions(_temp$3);
11652
+ setShowOptions(_temp$2);
11511
11653
  };
11512
11654
  $[3] = setShowOptions;
11513
11655
  $[4] = t3;
@@ -11524,7 +11666,7 @@ function OptionsMenu(t0) {
11524
11666
  type: "button",
11525
11667
  className: "hf-options-button",
11526
11668
  onClick: t3,
11527
- onMouseDown: _temp2$3,
11669
+ onMouseDown: _temp2$2,
11528
11670
  children: [t4, " ▾"]
11529
11671
  });
11530
11672
  $[7] = t3;
@@ -11598,10 +11740,10 @@ function OptionsMenu(t0) {
11598
11740
  } else t7 = $[21];
11599
11741
  return t7;
11600
11742
  }
11601
- function _temp2$3(e_0) {
11743
+ function _temp2$2(e_0) {
11602
11744
  return e_0.stopPropagation();
11603
11745
  }
11604
- function _temp$3(prev) {
11746
+ function _temp$2(prev) {
11605
11747
  return !prev;
11606
11748
  }
11607
11749
  // src/components/toolbarUtils.ts
@@ -11738,7 +11880,7 @@ function PanelToggles(t0) {
11738
11880
  className: t5,
11739
11881
  "data-testid": "toolbar-comments-toggle",
11740
11882
  onClick: onToggleComments,
11741
- onMouseDown: _temp2$2,
11883
+ onMouseDown: _temp2$1,
11742
11884
  title: commentsLabel,
11743
11885
  type: "button",
11744
11886
  children: [
@@ -11759,7 +11901,7 @@ function PanelToggles(t0) {
11759
11901
  if ($[24] !== t3 || $[25] !== t9) {
11760
11902
  t10 = /* @__PURE__ */ jsxs("div", {
11761
11903
  className: "flex shrink-0 items-center gap-0.5",
11762
- onMouseUp: _temp$2,
11904
+ onMouseUp: _temp$1,
11763
11905
  children: [t3, t9]
11764
11906
  });
11765
11907
  $[24] = t3;
@@ -11768,10 +11910,10 @@ function PanelToggles(t0) {
11768
11910
  } else t10 = $[26];
11769
11911
  return t10;
11770
11912
  }
11771
- function _temp2$2(event_0) {
11913
+ function _temp2$1(event_0) {
11772
11914
  return event_0.preventDefault();
11773
11915
  }
11774
- function _temp$2(event) {
11916
+ function _temp$1(event) {
11775
11917
  return event.stopPropagation();
11776
11918
  }
11777
11919
  // src/components/selectionFormattingBuilder.ts
@@ -12564,7 +12706,7 @@ function HyperlinkPopupContent(t0) {
12564
12706
  if (mode === "edit") {
12565
12707
  let t11;
12566
12708
  if ($[22] === Symbol.for("react.memo_cache_sentinel")) {
12567
- t11 = containedHandler(_temp$1);
12709
+ t11 = containedHandler(_temp);
12568
12710
  $[22] = t11;
12569
12711
  } else t11 = $[22];
12570
12712
  let t12;
@@ -12696,7 +12838,7 @@ function HyperlinkPopupContent(t0) {
12696
12838
  }
12697
12839
  let t11;
12698
12840
  if ($[54] === Symbol.for("react.memo_cache_sentinel")) {
12699
- t11 = containedHandler(_temp2$1);
12841
+ t11 = containedHandler(_temp2);
12700
12842
  $[54] = t11;
12701
12843
  } else t11 = $[54];
12702
12844
  let t12;
@@ -12830,10 +12972,10 @@ function HyperlinkPopupContent(t0) {
12830
12972
  } else t24 = $[86];
12831
12973
  return t24;
12832
12974
  }
12833
- function _temp2$1(e_4) {
12975
+ function _temp2(e_4) {
12834
12976
  return e_4.stopPropagation();
12835
12977
  }
12836
- function _temp$1(e_1) {
12978
+ function _temp(e_1) {
12837
12979
  return e_1.stopPropagation();
12838
12980
  }
12839
12981
  // src/components/ui/table-styles.ts
@@ -13582,137 +13724,112 @@ function sanitizeControlledComments(comments) {
13582
13724
  }
13583
13725
  return sanitized;
13584
13726
  }
13585
- function useFolioComments(t0) {
13586
- const $ = c(81);
13587
- const { doc, autoOpenReviewSidebar, anchorPositions, editorContentRef, commentsProp, onCommentsChange, committedComments } = t0;
13727
+ /** The records as the list the hook hands out, copied once per change. */
13728
+ const listOf = (records) => [...records];
13729
+ function useFolioComments({ doc, autoOpenReviewSidebar, anchorPositions, editorContentRef, commentsProp, onCommentsChange, committedComments, bodyView = null }) {
13588
13730
  const [showCommentsSidebar, setShowCommentsSidebar] = useState(false);
13589
13731
  const [visibleCommentAuthors, setVisibleCommentAuthors] = useState(null);
13590
13732
  const [activeCommentId, setActiveCommentId] = useState(null);
13591
- let t1;
13592
- if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
13593
- t1 = [];
13594
- $[0] = t1;
13595
- } else t1 = $[0];
13596
- const [internalComments, setInternalComments] = useState(t1);
13597
- let t2;
13598
- if ($[1] !== commentsProp) {
13599
- t2 = commentsProp !== void 0 ? sanitizeControlledComments(commentsProp) : void 0;
13600
- $[1] = commentsProp;
13601
- $[2] = t2;
13602
- } else t2 = $[2];
13603
- const sanitizedCommentsProp = t2;
13733
+ const [internalComments, setInternalComments] = useState([]);
13734
+ const sanitizedCommentsProp = useMemo(() => commentsProp !== void 0 ? sanitizeControlledComments(commentsProp) : void 0, [commentsProp]);
13604
13735
  const commentsMode = sanitizedCommentsProp === void 0 ? "uncontrolled" : "controlled";
13736
+ const commentsModeRef = useRef(commentsMode);
13737
+ useLayoutEffect(() => {
13738
+ commentsModeRef.current = commentsMode;
13739
+ }, [commentsMode]);
13605
13740
  const isControlledComments = commentsMode === "controlled";
13606
- const comments = sanitizedCommentsProp ?? internalComments;
13607
- let t3;
13608
- if ($[3] !== comments || $[4] !== doc?.package.document.comments) {
13609
- t3 = () => {
13610
- for (const { id } of doc?.package.document.comments ?? []) seedCommentIdAbove(id);
13611
- for (const { id: id_0 } of comments) seedCommentIdAbove(id_0);
13612
- };
13613
- $[3] = comments;
13614
- $[4] = doc?.package.document.comments;
13615
- $[5] = t3;
13616
- } else t3 = $[5];
13617
- let t4;
13618
- if ($[6] !== comments || $[7] !== doc) {
13619
- t4 = [comments, doc];
13620
- $[6] = comments;
13621
- $[7] = doc;
13622
- $[8] = t4;
13623
- } else t4 = $[8];
13624
- useLayoutEffect(t3, t4);
13741
+ const subscribeRecords = useCallback((notify) => bodyView ? subscribeCommentRecords(bodyView, notify) : () => void 0, [bodyView]);
13742
+ const readRecords = useCallback(() => bodyView ? commentRecordsOf(bodyView.state) : null, [bodyView]);
13743
+ const recordsSnapshot = useSyncExternalStore(subscribeRecords, readRecords, readRecords);
13744
+ const records = useMemo(() => recordsSnapshot === null ? null : listOf(recordsSnapshot), [recordsSnapshot]);
13745
+ const comments = sanitizedCommentsProp ?? records ?? internalComments;
13746
+ useLayoutEffect(() => {
13747
+ for (const { id } of doc?.package.document.comments ?? []) seedCommentIdAbove(id);
13748
+ for (const { id: id_0 } of comments) seedCommentIdAbove(id_0);
13749
+ }, [comments, doc]);
13625
13750
  const commentsDirtyRef = useRef(false);
13626
- let t5;
13627
- if ($[9] === Symbol.for("react.memo_cache_sentinel")) {
13628
- t5 = () => commentsDirtyRef.current;
13629
- $[9] = t5;
13630
- } else t5 = $[9];
13631
- const getCommentsDirty = t5;
13632
- let t6;
13633
- if ($[10] === Symbol.for("react.memo_cache_sentinel")) {
13634
- t6 = (dirty) => {
13635
- commentsDirtyRef.current = dirty;
13636
- };
13637
- $[10] = t6;
13638
- } else t6 = $[10];
13639
- const setCommentsDirty = t6;
13751
+ const getCommentsDirty = useCallback(() => commentsDirtyRef.current, []);
13752
+ const setCommentsDirty = useCallback((dirty) => {
13753
+ commentsDirtyRef.current = dirty;
13754
+ }, []);
13640
13755
  const commentsRef = useRef(comments);
13641
- let t7;
13642
- let t8;
13643
- if ($[11] !== comments) {
13644
- t7 = () => {
13645
- commentsRef.current = comments;
13646
- };
13647
- t8 = [comments];
13648
- $[11] = comments;
13649
- $[12] = t7;
13650
- $[13] = t8;
13651
- } else {
13652
- t7 = $[12];
13653
- t8 = $[13];
13654
- }
13655
- useLayoutEffect(t7, t8);
13756
+ useLayoutEffect(() => {
13757
+ commentsRef.current = comments;
13758
+ }, [comments]);
13656
13759
  const readonlyCommentsRef = commentsRef;
13657
13760
  const onCommentsChangeRef = useRef(onCommentsChange);
13658
- let t10;
13659
- let t9;
13660
- if ($[14] !== onCommentsChange) {
13661
- t9 = () => {
13662
- onCommentsChangeRef.current = onCommentsChange;
13663
- };
13664
- t10 = [onCommentsChange];
13665
- $[14] = onCommentsChange;
13666
- $[15] = t10;
13667
- $[16] = t9;
13668
- } else {
13669
- t10 = $[15];
13670
- t9 = $[16];
13671
- }
13672
- useLayoutEffect(t9, t10);
13673
- let t11;
13674
- if ($[17] !== doc?.package.document.comments) {
13675
- t11 = (text, author, parentId) => {
13676
- for (const { id: id_1 } of doc?.package.document.comments ?? []) seedCommentIdAbove(id_1);
13677
- for (const { id: id_2 } of commentsRef.current) seedCommentIdAbove(id_2);
13678
- return createComment(text, author, parentId);
13679
- };
13680
- $[17] = doc?.package.document.comments;
13681
- $[18] = t11;
13682
- } else t11 = $[18];
13683
- const createComment$1 = t11;
13684
- let t12;
13685
- if ($[19] !== commentsMode) {
13686
- t12 = (next) => {
13687
- const resolved = typeof next === "function" ? next(commentsRef.current) : next;
13688
- if (resolved === commentsRef.current) return;
13689
- bb75: switch (commentsMode) {
13690
- case "controlled": break bb75;
13691
- case "uncontrolled":
13692
- for (const { id: id_3 } of resolved) seedCommentIdAbove(id_3);
13693
- commentsRef.current = resolved;
13694
- setInternalComments(resolved);
13695
- break bb75;
13696
- default: return commentsMode;
13697
- }
13698
- onCommentsChangeRef.current?.(resolved);
13761
+ useLayoutEffect(() => {
13762
+ onCommentsChangeRef.current = onCommentsChange;
13763
+ }, [onCommentsChange]);
13764
+ const bodyViewRef = useRef(bodyView);
13765
+ useLayoutEffect(() => {
13766
+ bodyViewRef.current = bodyView;
13767
+ }, [bodyView]);
13768
+ useLayoutEffect(() => {
13769
+ if (!bodyView) return;
13770
+ return subscribeCommentRecords(bodyView, (next, origin) => {
13771
+ if (next === null) return;
13772
+ const list = listOf(next);
13773
+ for (const { id: id_1 } of list) seedCommentIdAbove(id_1);
13774
+ if (commentsModeRef.current === "uncontrolled") commentsRef.current = list;
13775
+ if (origin === "sync") return;
13776
+ commentsDirtyRef.current = true;
13777
+ onCommentsChangeRef.current?.(list);
13778
+ });
13779
+ }, [bodyView]);
13780
+ const comparedRef = useRef(null);
13781
+ useLayoutEffect(() => {
13782
+ if (!bodyView || sanitizedCommentsProp === void 0 || records === null) {
13783
+ comparedRef.current = null;
13784
+ return;
13785
+ }
13786
+ const compared = comparedRef.current;
13787
+ if (compared?.prop === sanitizedCommentsProp && compared.records === records) return;
13788
+ comparedRef.current = {
13789
+ prop: sanitizedCommentsProp,
13790
+ records
13699
13791
  };
13700
- $[19] = commentsMode;
13701
- $[20] = t12;
13702
- } else t12 = $[20];
13703
- const setComments = t12;
13792
+ if (JSON.stringify(records) === JSON.stringify(sanitizedCommentsProp)) return;
13793
+ const transaction = syncCommentRecords(bodyView.state, sanitizedCommentsProp);
13794
+ if (transaction) bodyView.dispatch(transaction);
13795
+ });
13796
+ const createComment$1 = useCallback((text, author, parentId) => {
13797
+ for (const { id: id_2 } of doc?.package.document.comments ?? []) seedCommentIdAbove(id_2);
13798
+ for (const { id: id_3 } of commentsRef.current) seedCommentIdAbove(id_3);
13799
+ return createComment(text, author, parentId);
13800
+ }, [doc]);
13801
+ const setComments = useCallback((next_0) => {
13802
+ const resolved = typeof next_0 === "function" ? next_0(commentsRef.current) : next_0;
13803
+ if (resolved === commentsRef.current) return;
13804
+ const view = bodyViewRef.current;
13805
+ if (view && commentRecordsOf(view.state) !== null) {
13806
+ const transaction_0 = editCommentRecords(view.state, resolved);
13807
+ if (transaction_0) view.dispatch(transaction_0);
13808
+ return;
13809
+ }
13810
+ switch (commentsMode) {
13811
+ case "controlled": break;
13812
+ case "uncontrolled":
13813
+ for (const { id: id_4 } of resolved) seedCommentIdAbove(id_4);
13814
+ commentsRef.current = resolved;
13815
+ setInternalComments(resolved);
13816
+ break;
13817
+ default: return commentsMode;
13818
+ }
13819
+ onCommentsChangeRef.current?.(resolved);
13820
+ }, [commentsMode]);
13704
13821
  const [isAddingComment, setIsAddingComment] = useState(false);
13705
- const [commentSelectionRange, setCommentSelectionRange] = useState(null);
13822
+ const [commentSelectionRange, setCommentSelectionRange] = useEqualState(null);
13706
13823
  const [addCommentYPosition, setAddCommentYPosition] = useState(null);
13707
- const [floatingCommentBtn, setFloatingCommentBtn] = useState(null);
13824
+ const [floatingCommentBtn, setFloatingCommentBtn] = useEqualState(null);
13708
13825
  const [commentsLoaded, setCommentsLoaded] = useState(false);
13709
13826
  const [loadedCommentsNotification, setLoadedCommentsNotification] = useState(null);
13710
- let t13;
13711
- if ($[21] === Symbol.for("react.memo_cache_sentinel")) {
13712
- t13 = () => setCommentsLoaded(false);
13713
- $[21] = t13;
13714
- } else t13 = $[21];
13715
- const resetLoadedComments = t13;
13827
+ const resetLoadedComments = useCallback(() => setCommentsLoaded(false), []);
13828
+ /** Forget the list for a document about to load; its state brings its own. */
13829
+ const resetComments = useCallback(() => {
13830
+ commentsRef.current = [];
13831
+ setInternalComments([]);
13832
+ }, []);
13716
13833
  const bodyComments = committedComments ?? doc?.package.document.comments;
13717
13834
  if (!commentsLoaded && !(committedComments == null && isControlledComments) && bodyComments && bodyComments.length > 0) {
13718
13835
  setCommentsLoaded(true);
@@ -13725,37 +13842,17 @@ function useFolioComments(t0) {
13725
13842
  setActiveCommentId(null);
13726
13843
  if (autoOpenReviewSidebar && countOpenCommentThreads(bodyComments) > 0) setShowCommentsSidebar(true);
13727
13844
  }
13728
- let t14;
13729
- if ($[22] !== onCommentsChange) {
13730
- t14 = (loaded) => onCommentsChange?.(loaded);
13731
- $[22] = onCommentsChange;
13732
- $[23] = t14;
13733
- } else t14 = $[23];
13734
- const notifyLoadedComments = useEffectEvent(t14);
13845
+ const notifyLoadedComments = useEffectEvent((loaded) => onCommentsChange?.(loaded));
13735
13846
  const lastLoadedNotificationRef = useRef(null);
13736
- let t15;
13737
- if ($[24] !== loadedCommentsNotification || $[25] !== notifyLoadedComments) {
13738
- t15 = () => {
13739
- if (loadedCommentsNotification === null || lastLoadedNotificationRef.current === loadedCommentsNotification) return;
13740
- lastLoadedNotificationRef.current = loadedCommentsNotification;
13741
- notifyLoadedComments(loadedCommentsNotification.comments);
13742
- };
13743
- $[24] = loadedCommentsNotification;
13744
- $[25] = notifyLoadedComments;
13745
- $[26] = t15;
13746
- } else t15 = $[26];
13747
- let t16;
13748
- if ($[27] !== loadedCommentsNotification) {
13749
- t16 = [loadedCommentsNotification];
13750
- $[27] = loadedCommentsNotification;
13751
- $[28] = t16;
13752
- } else t16 = $[28];
13753
- useEffect(t15, t16);
13847
+ useEffect(() => {
13848
+ if (loadedCommentsNotification === null || lastLoadedNotificationRef.current === loadedCommentsNotification) return;
13849
+ lastLoadedNotificationRef.current = loadedCommentsNotification;
13850
+ notifyLoadedComments(loadedCommentsNotification.comments);
13851
+ }, [loadedCommentsNotification]);
13754
13852
  const listedComments = committedComments ?? comments;
13755
- let authors;
13756
- if ($[29] !== listedComments) {
13853
+ const commentAuthors = useMemo(() => {
13757
13854
  const seen = /* @__PURE__ */ new Set();
13758
- authors = [];
13855
+ const authors = [];
13759
13856
  for (const comment of listedComments) {
13760
13857
  const commentAuthor = getCommentAuthorKey(comment.author);
13761
13858
  if (!seen.has(commentAuthor)) {
@@ -13763,207 +13860,111 @@ function useFolioComments(t0) {
13763
13860
  authors.push(commentAuthor);
13764
13861
  }
13765
13862
  }
13766
- $[29] = listedComments;
13767
- $[30] = authors;
13768
- } else authors = $[30];
13769
- const commentAuthors = authors;
13770
- let t17;
13771
- if ($[31] !== commentAuthors || $[32] !== visibleCommentAuthors) {
13772
- t17 = visibleCommentAuthors ?? new Set(commentAuthors);
13773
- $[31] = commentAuthors;
13774
- $[32] = visibleCommentAuthors;
13775
- $[33] = t17;
13776
- } else t17 = $[33];
13777
- const visibleCommentAuthorSet = t17;
13778
- let t18;
13779
- if ($[34] === Symbol.for("react.memo_cache_sentinel")) {
13780
- t18 = [-1];
13781
- $[34] = t18;
13782
- } else t18 = $[34];
13783
- let ids;
13784
- if ($[35] !== listedComments || $[36] !== visibleCommentAuthorSet) {
13785
- ids = new Set(t18);
13863
+ return authors;
13864
+ }, [listedComments]);
13865
+ const visibleCommentAuthorSet = useMemo(() => visibleCommentAuthors ?? new Set(commentAuthors), [visibleCommentAuthors, commentAuthors]);
13866
+ const visibleCommentIds = useMemo(() => {
13867
+ const ids = /* @__PURE__ */ new Set([-1]);
13786
13868
  for (const comment_0 of listedComments) if (visibleCommentAuthorSet.has(getCommentAuthorKey(comment_0.author))) ids.add(comment_0.id);
13787
- $[35] = listedComments;
13788
- $[36] = visibleCommentAuthorSet;
13789
- $[37] = ids;
13790
- } else ids = $[37];
13791
- const visibleCommentIds = ids;
13792
- let visibleRootIds;
13793
- if ($[38] !== listedComments || $[39] !== visibleCommentIds) {
13794
- visibleRootIds = /* @__PURE__ */ new Set();
13869
+ return ids;
13870
+ }, [listedComments, visibleCommentAuthorSet]);
13871
+ const visibleComments = useMemo(() => {
13872
+ const visibleRootIds = /* @__PURE__ */ new Set();
13795
13873
  for (const comment_1 of listedComments) {
13796
13874
  const parentId_0 = getCommentParentId$1(comment_1);
13797
13875
  if (parentId_0 === null || parentId_0 === void 0 || !visibleCommentIds.has(comment_1.id)) continue;
13798
13876
  visibleRootIds.add(parentId_0);
13799
13877
  }
13800
- $[38] = listedComments;
13801
- $[39] = visibleCommentIds;
13802
- $[40] = visibleRootIds;
13803
- } else visibleRootIds = $[40];
13804
- let t19;
13805
- if ($[41] !== listedComments || $[42] !== visibleCommentIds || $[43] !== visibleRootIds) {
13806
- let t20;
13807
- if ($[45] !== visibleCommentIds || $[46] !== visibleRootIds) {
13808
- t20 = (comment_2) => {
13809
- const parentId_1 = getCommentParentId$1(comment_2);
13810
- if (parentId_1 !== null && parentId_1 !== void 0) return visibleCommentIds.has(comment_2.id);
13811
- return visibleCommentIds.has(comment_2.id) || visibleRootIds.has(comment_2.id);
13812
- };
13813
- $[45] = visibleCommentIds;
13814
- $[46] = visibleRootIds;
13815
- $[47] = t20;
13816
- } else t20 = $[47];
13817
- t19 = listedComments.filter(t20);
13818
- $[41] = listedComments;
13819
- $[42] = visibleCommentIds;
13820
- $[43] = visibleRootIds;
13821
- $[44] = t19;
13822
- } else t19 = $[44];
13823
- const visibleComments = t19;
13878
+ return listedComments.filter((comment_2) => {
13879
+ const parentId_1 = getCommentParentId$1(comment_2);
13880
+ if (parentId_1 !== null && parentId_1 !== void 0) return visibleCommentIds.has(comment_2.id);
13881
+ return visibleCommentIds.has(comment_2.id) || visibleRootIds.has(comment_2.id);
13882
+ });
13883
+ }, [listedComments, visibleCommentIds]);
13824
13884
  const activeCommentVisible = activeCommentId !== null && visibleCommentIds.has(activeCommentId);
13825
13885
  if (activeCommentId !== null && !activeCommentVisible) setActiveCommentId(null);
13826
- let t20;
13827
- if ($[48] !== activeCommentId || $[49] !== editorContentRef || $[50] !== visibleCommentIds) {
13828
- t20 = () => {
13829
- const root = editorContentRef.current;
13830
- if (!root) return;
13831
- const nodes = root.querySelectorAll(`.layout-run-text${COMMENT_ANCHOR_SELECTOR}`);
13832
- for (const node of nodes) {
13833
- const commentIds = commentAnchorIds(node).map(_temp);
13834
- if (!commentIds.some((commentId) => commentId === -1 || visibleCommentIds.has(commentId))) {
13835
- node.style.backgroundColor = "transparent";
13836
- node.style.borderBottom = "2px solid transparent";
13837
- node.style.boxShadow = "none";
13838
- delete node.dataset["activeComment"];
13839
- continue;
13840
- }
13841
- if (activeCommentId !== null && commentIds.includes(activeCommentId)) {
13842
- node.style.backgroundColor = "var(--doc-comment-active-bg, rgba(255, 212, 0, 0.22))";
13843
- node.style.borderBottom = "1px solid var(--doc-comment-active-border, rgba(180, 130, 0, 0.62))";
13844
- node.style.boxShadow = "none";
13845
- node.dataset.activeComment = "true";
13846
- continue;
13847
- }
13848
- node.style.backgroundColor = "var(--doc-comment-bg, rgba(255, 212, 0, 0.08))";
13849
- node.style.borderBottom = "1px solid var(--doc-comment-border, rgba(180, 130, 0, 0.24))";
13886
+ const syncCommentHighlightStyles = useCallback(() => {
13887
+ const root = editorContentRef.current;
13888
+ if (!root) return;
13889
+ const nodes = root.querySelectorAll(`.layout-run-text${COMMENT_ANCHOR_SELECTOR}`);
13890
+ for (const node of nodes) {
13891
+ const commentIds = commentAnchorIds(node).map((id_5) => Number.parseInt(id_5, 10));
13892
+ if (!commentIds.some((commentId) => commentId === -1 || visibleCommentIds.has(commentId))) {
13893
+ node.style.backgroundColor = "transparent";
13894
+ node.style.borderBottom = "2px solid transparent";
13850
13895
  node.style.boxShadow = "none";
13851
13896
  delete node.dataset["activeComment"];
13897
+ continue;
13852
13898
  }
13853
- };
13854
- $[48] = activeCommentId;
13855
- $[49] = editorContentRef;
13856
- $[50] = visibleCommentIds;
13857
- $[51] = t20;
13858
- } else t20 = $[51];
13859
- const syncCommentHighlightStyles = t20;
13860
- const highlightLayoutCommit = useEffectEvent(_temp2);
13861
- let t21;
13862
- if ($[52] !== anchorPositions || $[53] !== highlightLayoutCommit || $[54] !== syncCommentHighlightStyles) {
13863
- t21 = () => {
13864
- highlightLayoutCommit(anchorPositions, syncCommentHighlightStyles);
13865
- };
13866
- $[52] = anchorPositions;
13867
- $[53] = highlightLayoutCommit;
13868
- $[54] = syncCommentHighlightStyles;
13869
- $[55] = t21;
13870
- } else t21 = $[55];
13871
- let t22;
13872
- if ($[56] !== anchorPositions || $[57] !== syncCommentHighlightStyles) {
13873
- t22 = [syncCommentHighlightStyles, anchorPositions];
13874
- $[56] = anchorPositions;
13875
- $[57] = syncCommentHighlightStyles;
13876
- $[58] = t22;
13877
- } else t22 = $[58];
13878
- useLayoutEffect(t21, t22);
13879
- const scheduleHighlightCommit = useEffectEvent(_temp3);
13880
- let t23;
13881
- if ($[59] !== comments || $[60] !== scheduleHighlightCommit || $[61] !== syncCommentHighlightStyles) {
13882
- t23 = () => scheduleHighlightCommit(comments, syncCommentHighlightStyles);
13883
- $[59] = comments;
13884
- $[60] = scheduleHighlightCommit;
13885
- $[61] = syncCommentHighlightStyles;
13886
- $[62] = t23;
13887
- } else t23 = $[62];
13888
- let t24;
13889
- if ($[63] !== comments || $[64] !== syncCommentHighlightStyles) {
13890
- t24 = [comments, syncCommentHighlightStyles];
13891
- $[63] = comments;
13892
- $[64] = syncCommentHighlightStyles;
13893
- $[65] = t24;
13894
- } else t24 = $[65];
13895
- useEffect(t23, t24);
13896
- let t25;
13897
- if ($[66] !== activeCommentId || $[67] !== addCommentYPosition || $[68] !== commentAuthors || $[69] !== commentSelectionRange || $[70] !== comments || $[71] !== createComment$1 || $[72] !== floatingCommentBtn || $[73] !== isAddingComment || $[74] !== isControlledComments || $[75] !== setComments || $[76] !== showCommentsSidebar || $[77] !== syncCommentHighlightStyles || $[78] !== visibleCommentAuthorSet || $[79] !== visibleComments) {
13898
- t25 = {
13899
- comments,
13900
- setComments,
13901
- createComment: createComment$1,
13902
- isControlledComments,
13903
- commentsRef: readonlyCommentsRef,
13904
- getCommentsDirty,
13905
- setCommentsDirty,
13906
- resetLoadedComments,
13907
- showCommentsSidebar,
13908
- setShowCommentsSidebar,
13909
- setVisibleCommentAuthors,
13910
- activeCommentId,
13911
- setActiveCommentId,
13912
- isAddingComment,
13913
- setIsAddingComment,
13914
- commentSelectionRange,
13915
- setCommentSelectionRange,
13916
- addCommentYPosition,
13917
- setAddCommentYPosition,
13918
- floatingCommentBtn,
13919
- setFloatingCommentBtn,
13920
- commentAuthors,
13921
- visibleCommentAuthorSet,
13922
- visibleComments,
13923
- syncCommentHighlightStyles
13924
- };
13925
- $[66] = activeCommentId;
13926
- $[67] = addCommentYPosition;
13927
- $[68] = commentAuthors;
13928
- $[69] = commentSelectionRange;
13929
- $[70] = comments;
13930
- $[71] = createComment$1;
13931
- $[72] = floatingCommentBtn;
13932
- $[73] = isAddingComment;
13933
- $[74] = isControlledComments;
13934
- $[75] = setComments;
13935
- $[76] = showCommentsSidebar;
13936
- $[77] = syncCommentHighlightStyles;
13937
- $[78] = visibleCommentAuthorSet;
13938
- $[79] = visibleComments;
13939
- $[80] = t25;
13940
- } else t25 = $[80];
13941
- return t25;
13942
- }
13943
- function _temp3(_comments, sync_0) {
13944
- sync_0();
13945
- let secondFrame = null;
13946
- const firstFrame = requestAnimationFrame(() => {
13899
+ if (activeCommentId !== null && commentIds.includes(activeCommentId)) {
13900
+ node.style.backgroundColor = "var(--doc-comment-active-bg, rgba(255, 212, 0, 0.22))";
13901
+ node.style.borderBottom = "1px solid var(--doc-comment-active-border, rgba(180, 130, 0, 0.62))";
13902
+ node.style.boxShadow = "none";
13903
+ node.dataset["activeComment"] = "true";
13904
+ continue;
13905
+ }
13906
+ node.style.backgroundColor = "var(--doc-comment-bg, rgba(255, 212, 0, 0.08))";
13907
+ node.style.borderBottom = "1px solid var(--doc-comment-border, rgba(180, 130, 0, 0.24))";
13908
+ node.style.boxShadow = "none";
13909
+ delete node.dataset["activeComment"];
13910
+ }
13911
+ }, [
13912
+ visibleCommentIds,
13913
+ activeCommentId,
13914
+ editorContentRef
13915
+ ]);
13916
+ const highlightLayoutCommit = useEffectEvent((_positions, sync) => sync());
13917
+ useLayoutEffect(() => {
13918
+ highlightLayoutCommit(anchorPositions, syncCommentHighlightStyles);
13919
+ }, [syncCommentHighlightStyles, anchorPositions]);
13920
+ const scheduleHighlightCommit = useEffectEvent((_comments, sync_0) => {
13947
13921
  sync_0();
13948
- secondFrame = requestAnimationFrame(sync_0);
13922
+ let secondFrame = null;
13923
+ const firstFrame = requestAnimationFrame(() => {
13924
+ sync_0();
13925
+ secondFrame = requestAnimationFrame(sync_0);
13926
+ });
13927
+ const timeout = setTimeout(sync_0, 120);
13928
+ return () => {
13929
+ cancelAnimationFrame(firstFrame);
13930
+ if (secondFrame !== null) cancelAnimationFrame(secondFrame);
13931
+ clearTimeout(timeout);
13932
+ };
13949
13933
  });
13950
- const timeout = setTimeout(sync_0, 120);
13951
- return () => {
13952
- cancelAnimationFrame(firstFrame);
13953
- if (secondFrame !== null) cancelAnimationFrame(secondFrame);
13954
- clearTimeout(timeout);
13934
+ useEffect(() => scheduleHighlightCommit(comments, syncCommentHighlightStyles), [comments, syncCommentHighlightStyles]);
13935
+ return {
13936
+ comments,
13937
+ setComments,
13938
+ createComment: createComment$1,
13939
+ isControlledComments,
13940
+ commentsRef: readonlyCommentsRef,
13941
+ getCommentsDirty,
13942
+ setCommentsDirty,
13943
+ resetLoadedComments,
13944
+ resetComments,
13945
+ showCommentsSidebar,
13946
+ setShowCommentsSidebar,
13947
+ setVisibleCommentAuthors,
13948
+ activeCommentId,
13949
+ setActiveCommentId,
13950
+ isAddingComment,
13951
+ setIsAddingComment,
13952
+ commentSelectionRange,
13953
+ setCommentSelectionRange,
13954
+ addCommentYPosition,
13955
+ setAddCommentYPosition,
13956
+ floatingCommentBtn,
13957
+ setFloatingCommentBtn,
13958
+ commentAuthors,
13959
+ visibleCommentAuthorSet,
13960
+ visibleComments,
13961
+ syncCommentHighlightStyles
13955
13962
  };
13956
13963
  }
13957
- function _temp2(_positions, sync) {
13958
- return sync();
13959
- }
13960
- function _temp(id_4) {
13961
- return Number.parseInt(id_4, 10);
13962
- }
13963
13964
  // src/components/DocxEditor.tsx
13964
13965
  /** No headings to track while the outline is not shown. */
13965
13966
  const NO_HEADINGS = [];
13966
- const CommentsSidebar = lazy(() => import("./CommentsSidebar-4XdScjMH.js").then((m) => ({ default: m.CommentsSidebar })));
13967
+ const CommentsSidebar = lazy(() => import("./CommentsSidebar-myF8qhju.js").then((m) => ({ default: m.CommentsSidebar })));
13967
13968
  const TextContextMenu = lazy(() => import("./TextContextMenu-jOBgICwD.js").then((m) => ({ default: m.TextContextMenu })));
13968
13969
  const loadAttemptSelectiveSave = async () => {
13969
13970
  const { attemptSelectiveSave } = await import("@stll/folio-core/docx/selectiveSave");
@@ -13982,15 +13983,6 @@ const DISPLAY_MODE_LABEL_KEYS = {
13982
13983
  };
13983
13984
  const preventMouseDownDefault = (event) => event.preventDefault();
13984
13985
  let documentOperationUndoHandleCursor = Date.now();
13985
- /**
13986
- * The comments a batch's applied operations own. A run whose result the
13987
- * save-time check refused allocated comments nothing in the document names;
13988
- * they stay out of the comment list.
13989
- */
13990
- const appliedOperationComments = (created, applied) => {
13991
- const appliedIds = new Set(applied.map(({ commentId }) => commentId));
13992
- return created.filter((comment) => appliedIds.has(comment.id));
13993
- };
13994
13986
  function isDisplayMode(value) {
13995
13987
  return typeof value === "string" && DISPLAY_MODES.some((mode) => mode === value);
13996
13988
  }
@@ -14017,7 +14009,7 @@ const EMPTY_SELECTION_FORMATTING = {};
14017
14009
  function areTableContextsEqual(a, b) {
14018
14010
  if (a === b) return true;
14019
14011
  if (!a || !b) return false;
14020
- return a.isInTable === b.isInTable && a.table === b.table && a.tablePos === b.tablePos && a.rowIndex === b.rowIndex && a.columnIndex === b.columnIndex && a.rowCount === b.rowCount && a.columnCount === b.columnCount && a.hasMultiCellSelection === b.hasMultiCellSelection && a.canSplitCell === b.canSplitCell && a.cellBorderColor === b.cellBorderColor && a.cellBackgroundColor === b.cellBackgroundColor;
14012
+ return a.isInTable === b.isInTable && a.table?.attrs === b.table?.attrs && a.tablePos === b.tablePos && a.rowIndex === b.rowIndex && a.columnIndex === b.columnIndex && a.rowCount === b.rowCount && a.columnCount === b.columnCount && a.hasMultiCellSelection === b.hasMultiCellSelection && a.canSplitCell === b.canSplitCell && a.cellBorderColor === b.cellBorderColor && a.cellBackgroundColor === b.cellBackgroundColor;
14021
14013
  }
14022
14014
  /** Structural equality for the image context surfaced to the toolbar. */
14023
14015
  function areImageContextsEqual(a, b) {
@@ -14029,7 +14021,7 @@ function areImageContextsEqual(a, b) {
14029
14021
  function areActiveTrackedChangesEqual(a, b) {
14030
14022
  if (a === b) return true;
14031
14023
  if (!a || !b) return false;
14032
- return a.type === b.type && a.author === b.author && a.date === b.date && a.from === b.from && a.to === b.to && a.heldByLock.accept === b.heldByLock.accept && a.heldByLock.reject === b.heldByLock.reject;
14024
+ return a.type === b.type && a.author === b.author && a.date === b.date && a.heldByLock.accept === b.heldByLock.accept && a.heldByLock.reject === b.heldByLock.reject;
14033
14025
  }
14034
14026
  const assignRef = (ref, value) => {
14035
14027
  ref.current = value;
@@ -14108,14 +14100,14 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
14108
14100
  const [rulerVisible, setRulerVisible] = useState(showRulerProp);
14109
14101
  const toggleRuler = useCallback(() => setRulerVisible((visible) => !visible), []);
14110
14102
  const [showOutline, setShowOutline] = useState(showOutlineProp);
14111
- const [outlineHeadings, setHeadingInfos] = useState([]);
14112
- const [, setTrackedChangeEntries] = useState([]);
14103
+ const [outlineHeadings, setHeadingInfos] = useEqualState([]);
14104
+ const [, setTrackedChangeEntries] = useEqualState([]);
14113
14105
  const trackedChangesRef = useRef([]);
14114
14106
  const setTrackedChanges = useCallback((entries) => {
14115
14107
  trackedChangesRef.current = entries;
14116
14108
  setTrackedChangeEntries(entries);
14117
- }, []);
14118
- const [anchorPositions, setAnchorPositions] = useState(EMPTY_ANCHOR_POSITIONS);
14109
+ }, [setTrackedChangeEntries]);
14110
+ const [anchorPositions, setAnchorPositions] = useEqualState(EMPTY_ANCHOR_POSITIONS);
14119
14111
  const { editingMode, readOnly, readOnlyReason, trackChangesOn, toggleTrackChanges, displayMode, setDisplayMode } = useEditorMode({
14120
14112
  modeProp,
14121
14113
  onModeChange,
@@ -14290,6 +14282,7 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
14290
14282
  };
14291
14283
  }, [onEditorViewReady, reportEditorViewReady]);
14292
14284
  const [bodyViewEpoch, setBodyViewEpoch] = useState(0);
14285
+ const [bodyEditorView, setBodyEditorView] = useState(null);
14293
14286
  const syncSuggestionMode = useCallback((view_2) => {
14294
14287
  const active = editingMode === "suggesting";
14295
14288
  const current = suggestionModeKey.getState(view_2.state);
@@ -14301,6 +14294,7 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
14301
14294
  syncCanonicalMode();
14302
14295
  }
14303
14296
  reportEditorViewReady(view_3);
14297
+ setBodyEditorView(view_3);
14304
14298
  setBodyViewEpoch((epoch) => epoch + 1);
14305
14299
  }, [
14306
14300
  reportEditorViewReady,
@@ -14327,7 +14321,11 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
14327
14321
  };
14328
14322
  refresh(pagedEditor.getLayout());
14329
14323
  return pagedEditor.getEditor().on("layoutComplete", refresh);
14330
- }, [showOutline, bodyViewEpoch]);
14324
+ }, [
14325
+ showOutline,
14326
+ bodyViewEpoch,
14327
+ setHeadingInfos
14328
+ ]);
14331
14329
  const [editorController, setEditorController] = useState(null);
14332
14330
  const attachPagedEditor = useCallback((editor) => {
14333
14331
  assignRef(pagedEditorRef, editor);
@@ -14405,14 +14403,15 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
14405
14403
  const canonicalCommentsSerialized = useMemo(() => canonicalComments === null ? null : JSON.stringify(canonicalComments), [canonicalComments]);
14406
14404
  const canonicalCommentsSnapshotRef = useRef(canonicalCommentsSerialized);
14407
14405
  const lastControlledCommentsRef = useRef(void 0);
14408
- const { comments: legacyComments, createComment, setComments, commentsRef, getCommentsDirty, setCommentsDirty, resetLoadedComments, showCommentsSidebar, setShowCommentsSidebar, setVisibleCommentAuthors, activeCommentId, setActiveCommentId, isAddingComment, setIsAddingComment, commentSelectionRange, setCommentSelectionRange, addCommentYPosition, setAddCommentYPosition, floatingCommentBtn, setFloatingCommentBtn, commentAuthors, visibleCommentAuthorSet, visibleComments, syncCommentHighlightStyles } = useFolioComments({
14406
+ const { comments: legacyComments, createComment, setComments, commentsRef, getCommentsDirty, setCommentsDirty, resetLoadedComments, resetComments, showCommentsSidebar, setShowCommentsSidebar, setVisibleCommentAuthors, activeCommentId, setActiveCommentId, isAddingComment, setIsAddingComment, commentSelectionRange, setCommentSelectionRange, addCommentYPosition, setAddCommentYPosition, floatingCommentBtn, setFloatingCommentBtn, commentAuthors, visibleCommentAuthorSet, visibleComments, syncCommentHighlightStyles } = useFolioComments({
14409
14407
  doc: canonicalComments === null ? history.state : null,
14410
14408
  autoOpenReviewSidebar,
14411
14409
  anchorPositions,
14412
14410
  editorContentRef,
14413
14411
  commentsProp,
14414
14412
  onCommentsChange,
14415
- committedComments: canonicalComments
14413
+ committedComments: canonicalComments,
14414
+ bodyView: bodyEditorView
14416
14415
  });
14417
14416
  const comments = canonicalComments ?? legacyComments;
14418
14417
  const commentDraftMode = usesCanonicalSession(experimentalSession, CANONICAL_GAP.authorityRouting) ? "canonical" : "prosemirror";
@@ -14442,7 +14441,7 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
14442
14441
  onZoomChange: setZoomWithViewportAnchor,
14443
14442
  keyboardShortcuts: "none"
14444
14443
  });
14445
- const [bodyHistoryAvailability, setBodyHistoryAvailability] = useState({
14444
+ const [bodyHistoryAvailability, setBodyHistoryAvailability] = useEqualState({
14446
14445
  canRedo: false,
14447
14446
  canUndo: false
14448
14447
  });
@@ -14460,7 +14459,7 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
14460
14459
  canUndo,
14461
14460
  canRedo
14462
14461
  });
14463
- }, []);
14462
+ }, [setBodyHistoryAvailability]);
14464
14463
  const { hfEditPosition, setHfEditPosition, hfEditIsFirstPage, headerContent, footerContent, firstPageHeaderContent, firstPageFooterContent, activeHeaderRId, activeFooterRId, activeFirstHeaderRId, activeFirstFooterRId, effectiveSectionProperties, handleHeaderFooterDoubleClick, handleBodyClick, handleRemoveHeaderFooter } = useHeaderFooterEditor({
14465
14464
  history,
14466
14465
  pushDocument,
@@ -14585,7 +14584,7 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
14585
14584
  });
14586
14585
  setCommentsDirty(false);
14587
14586
  resetLoadedComments();
14588
- setComments([]);
14587
+ resetComments();
14589
14588
  setTrackedChanges([]);
14590
14589
  setVisibleCommentAuthors(null);
14591
14590
  setActiveCommentId(null);
@@ -14605,16 +14604,18 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
14605
14604
  }, [
14606
14605
  setCommentsDirty,
14607
14606
  resetLoadedComments,
14607
+ resetComments,
14608
14608
  setActiveCommentId,
14609
14609
  setAddCommentYPosition,
14610
14610
  setCommentSelectionRange,
14611
- setComments,
14612
14611
  setTrackedChanges,
14613
14612
  setFloatingCommentBtn,
14614
14613
  setHfEditPosition,
14615
14614
  setIsAddingComment,
14616
14615
  setShowCommentsSidebar,
14617
- setVisibleCommentAuthors
14616
+ setVisibleCommentAuthors,
14617
+ setHeadingInfos,
14618
+ setAnchorPositions
14618
14619
  ]),
14619
14620
  setDocumentLoadState: useCallback((documentLoad) => {
14620
14621
  setState((prev_0) => ({
@@ -14724,7 +14725,8 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
14724
14725
  flushBag(doc_0.package.headers);
14725
14726
  flushBag(doc_0.package.footers);
14726
14727
  }
14727
- return withHostCommentThreads(doc_0, commentsRef.current);
14728
+ const editorDoc = pagedEditorRef.current?.getView()?.state.doc;
14729
+ return withHostCommentThreads(doc_0, commentsRef.current, { anchoredInEditor: editorDoc ? commentIdsNamedIn(editorDoc) : null });
14728
14730
  }, [commentsRef, experimentalSession]);
14729
14731
  const applyCanonicalComment = useCallback((request) => {
14730
14732
  return getCanonicalApi()?.applyCanonicalComment(request) ?? null;
@@ -14897,7 +14899,13 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
14897
14899
  };
14898
14900
  }
14899
14901
  const pmImageCtx = view_8 ? detectImageContext(view_8.state) : null;
14900
- const trackedChange = view_8 ? detectActiveTrackedChange(view_8.state) : null;
14902
+ const detectedChange = view_8 ? detectActiveTrackedChange(view_8.state) : null;
14903
+ const trackedChange = detectedChange === null ? null : {
14904
+ type: detectedChange.type,
14905
+ author: detectedChange.author,
14906
+ date: detectedChange.date,
14907
+ heldByLock: detectedChange.heldByLock
14908
+ };
14901
14909
  if (!selectionState) {
14902
14910
  setFloatingCommentBtn(null);
14903
14911
  setState((prev_1) => {
@@ -15756,10 +15764,10 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
15756
15764
  to: to_5
15757
15765
  });
15758
15766
  if (commentDraftMode === "prosemirror") {
15759
- if (!applyCommentMarkRange(view_13, {
15767
+ if (!markPendingComment(view_13, {
15760
15768
  from: from_5,
15761
15769
  to: to_5
15762
- }, -1, { selectEnd: true })) break;
15770
+ }, { selectEnd: true })) break;
15763
15771
  }
15764
15772
  setAddCommentYPosition(commentY);
15765
15773
  setShowCommentsSidebar(true);
@@ -15977,7 +15985,7 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
15977
15985
  serializeCurrentDocx
15978
15986
  ]);
15979
15987
  const handleEditorError = useCallback((error_1) => {
15980
- if (CanonicalSessionRefusalError.is(error_1)) toast(canonicalRefusalNotice(error_1.ground, error_1.message, t));
15988
+ if (CanonicalSessionRefusalError.is(error_1)) toast(canonicalRefusalNotice(error_1.ground, t));
15981
15989
  onError?.(error_1);
15982
15990
  }, [onError, t]);
15983
15991
  useImperativeHandle(ref, () => ({
@@ -16082,13 +16090,13 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
16082
16090
  return canonical_1;
16083
16091
  }
16084
16092
  const existingUndoEntry = documentOperationUndoEntriesRef.current.at(-1);
16085
- if (existingUndoEntry && (!view_22.state.doc.eq(existingUndoEntry.afterState.doc) || canonicalJson(commentsRef.current) !== existingUndoEntry.commentsAfterJson)) documentOperationUndoEntriesRef.current.length = 0;
16086
- const commentsBefore = commentsRef.current;
16093
+ if (existingUndoEntry && (!view_22.state.doc.eq(existingUndoEntry.afterState.doc) || canonicalJson(commentRecordsOf(view_22.state)) !== existingUndoEntry.commentsAfterJson)) documentOperationUndoEntriesRef.current.length = 0;
16087
16094
  const createdComments = [];
16095
+ const recordingView = recordingCommentsView(view_22, createdComments);
16088
16096
  const operationView = {
16089
16097
  state: view_22.state,
16090
16098
  dispatch: (transaction) => {
16091
- view_22.dispatch(closeHistory(transaction));
16099
+ recordingView.dispatch(closeHistory(transaction));
16092
16100
  operationView.state = view_22.state;
16093
16101
  }
16094
16102
  };
@@ -16117,14 +16125,10 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
16117
16125
  author: operationAuthor,
16118
16126
  activeSuggestionIds
16119
16127
  });
16120
- const batchComments = appliedOperationComments(createdComments, result_3.applied);
16121
- const commentsAfter = batchComments.length > 0 ? [...commentsRef.current, ...batchComments] : commentsRef.current;
16122
- if (batchComments.length > 0) replaceComments(commentsAfter);
16123
16128
  if (result_3.undoHandle !== null) documentOperationUndoEntriesRef.current.push({
16124
16129
  undoHandle: result_3.undoHandle,
16125
16130
  afterState: view_22.state,
16126
- commentsBefore,
16127
- commentsAfterJson: canonicalJson(commentsAfter)
16131
+ commentsAfterJson: canonicalJson(commentRecordsOf(view_22.state))
16128
16132
  });
16129
16133
  return result_3;
16130
16134
  },
@@ -16150,7 +16154,7 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
16150
16154
  undoHandle,
16151
16155
  reason: "unknownHandle"
16152
16156
  };
16153
- if (!view_23.state.doc.eq(entry_3.afterState.doc) || canonicalJson(commentsRef.current) !== entry_3.commentsAfterJson) return {
16157
+ if (!view_23.state.doc.eq(entry_3.afterState.doc) || canonicalJson(commentRecordsOf(view_23.state)) !== entry_3.commentsAfterJson) return {
16154
16158
  status: "rejected",
16155
16159
  undoHandle,
16156
16160
  reason: "documentChanged"
@@ -16160,7 +16164,6 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
16160
16164
  undoHandle,
16161
16165
  reason: "documentChanged"
16162
16166
  };
16163
- replaceComments(entry_3.commentsBefore);
16164
16167
  entries_0.pop();
16165
16168
  requestAnimationFrame(refreshBodyHistoryAvailability);
16166
16169
  return {
@@ -16202,7 +16205,7 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
16202
16205
  const createdComments_0 = [];
16203
16206
  const { applied: applied_0, skipped: skipped_0 } = applyFolioDocumentOperations({
16204
16207
  undefinedReferences: undefinedReferences_0,
16205
- view: view_24,
16208
+ view: recordingCommentsView(view_24, createdComments_0),
16206
16209
  snapshot: snapshot_2,
16207
16210
  batch: {
16208
16211
  version: FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION,
@@ -16216,8 +16219,6 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
16216
16219
  return comment_0.id;
16217
16220
  }
16218
16221
  });
16219
- const batchComments_0 = appliedOperationComments(createdComments_0, applied_0);
16220
- if (batchComments_0.length > 0) updateComments((currentComments_0) => [...currentComments_0, ...batchComments_0]);
16221
16222
  if (mode === "suggested") pendingSuggestionRegistryRef.current.recordApplied({
16222
16223
  snapshot: snapshot_2,
16223
16224
  story: { type: "main" },
@@ -16390,7 +16391,7 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
16390
16391
  const createdComments_1 = [];
16391
16392
  const result_4 = applyFolioDocumentOperations({
16392
16393
  undefinedReferences: "refuse",
16393
- view: view_35,
16394
+ view: recordingCommentsView(view_35, createdComments_1),
16394
16395
  snapshot: snapshot_6,
16395
16396
  batch: {
16396
16397
  version: FOLIO_DOCUMENT_OPERATION_CONTRACT_VERSION,
@@ -16404,8 +16405,6 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
16404
16405
  return comment_1.id;
16405
16406
  }
16406
16407
  });
16407
- const appliedComments = appliedOperationComments(createdComments_1, result_4.applied);
16408
- if (appliedComments.length > 0) updateComments((currentComments_1) => [...currentComments_1, ...appliedComments]);
16409
16408
  return {
16410
16409
  applied: result_4.applied,
16411
16410
  skipped: result_4.skipped
@@ -16879,11 +16878,19 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
16879
16878
  notifyReadonlyEditAttempt();
16880
16879
  return;
16881
16880
  }
16882
- updateComments((previous_2) => previous_2.filter((comment_3) => comment_3.id !== id_2 && comment_3.parentId !== id_2));
16881
+ const view_55 = pagedEditorRef.current?.getView();
16882
+ if (view_55 && commentRecordsOf(view_55.state) !== null) {
16883
+ const deleted = deleteCommentThread(view_55.state, id_2);
16884
+ if (deleted) view_55.dispatch(deleted);
16885
+ } else {
16886
+ const thread = commentThreadIds(commentsRef.current, id_2);
16887
+ updateComments((previous_2) => previous_2.filter((comment_3) => !thread.has(comment_3.id)));
16888
+ }
16883
16889
  if (activeCommentId === id_2) setActiveCommentId(null);
16884
16890
  }, [
16885
16891
  activeCommentId,
16886
16892
  applyCanonicalComment,
16893
+ commentsRef,
16887
16894
  notifyReadonlyEditAttempt,
16888
16895
  readOnly,
16889
16896
  setActiveCommentId,
@@ -16913,8 +16920,8 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
16913
16920
  updateComments
16914
16921
  ]);
16915
16922
  const handleAddComment = useCallback((addText) => {
16916
- const view_55 = pagedEditorRef.current?.getView();
16917
- if (!view_55 || !commentSelectionRange) return false;
16923
+ const view_56 = pagedEditorRef.current?.getView();
16924
+ if (!view_56 || !commentSelectionRange) return false;
16918
16925
  const result_6 = applyCanonicalComment({
16919
16926
  type: "create",
16920
16927
  text: addText,
@@ -16945,7 +16952,7 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
16945
16952
  return false;
16946
16953
  }
16947
16954
  const comment_4 = createComment(addText, author);
16948
- if (!applyCommentMarkRange(view_55, commentSelectionRange, comment_4.id, { replacePending: true })) return false;
16955
+ if (!commitCommentThread(view_56, commentSelectionRange, comment_4)) return false;
16949
16956
  const commentAuthor_2 = getCommentAuthorKey(comment_4.author);
16950
16957
  setVisibleCommentAuthors((current_2) => {
16951
16958
  if (current_2 === null) return null;
@@ -16954,7 +16961,6 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
16954
16961
  return next_2;
16955
16962
  });
16956
16963
  setActiveCommentId(comment_4.id);
16957
- updateComments((previous_4) => [...previous_4, comment_4]);
16958
16964
  pagedEditorRef.current?.relayout();
16959
16965
  requestAnimationFrame(() => {
16960
16966
  syncCommentHighlightStyles();
@@ -16976,8 +16982,7 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
16976
16982
  setCommentSelectionRange,
16977
16983
  setIsAddingComment,
16978
16984
  setVisibleCommentAuthors,
16979
- syncCommentHighlightStyles,
16980
- updateComments
16985
+ syncCommentHighlightStyles
16981
16986
  ]);
16982
16987
  const handleTrackedChangeReply = useCallback((revisionId_2, text_7) => {
16983
16988
  if (applyCanonicalComment({
@@ -16994,7 +16999,7 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
16994
16999
  notifyReadonlyEditAttempt();
16995
17000
  return;
16996
17001
  }
16997
- updateComments((previous_5) => [...previous_5, createComment(text_7, author, revisionId_2)]);
17002
+ updateComments((previous_4) => [...previous_4, createComment(text_7, author, revisionId_2)]);
16998
17003
  }, [
16999
17004
  applyCanonicalComment,
17000
17005
  author,
@@ -17004,8 +17009,8 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
17004
17009
  updateComments
17005
17010
  ]);
17006
17011
  const handleCancelAddComment = useCallback(() => {
17007
- const view_56 = pagedEditorRef.current?.getView();
17008
- if (view_56 && commentSelectionRange && commentDraftMode === "prosemirror") removePendingCommentMarkRange(view_56, commentSelectionRange);
17012
+ const view_57 = pagedEditorRef.current?.getView();
17013
+ if (view_57 && commentSelectionRange && commentDraftMode === "prosemirror") clearPendingComment(view_57, commentSelectionRange);
17009
17014
  setIsAddingComment(false);
17010
17015
  setCommentSelectionRange(null);
17011
17016
  setAddCommentYPosition(null);
@@ -17022,23 +17027,23 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
17022
17027
  })?.revisionId ?? null;
17023
17028
  }, []);
17024
17029
  const handleSidebarAcceptChange = useCallback((from_17, to_17) => {
17025
- const view_57 = pagedEditorRef.current?.getView();
17026
- if (!view_57) return;
17030
+ const view_58 = pagedEditorRef.current?.getView();
17031
+ if (!view_58) return;
17027
17032
  const revisionId_3 = resolveSidebarChangeRevisionId(from_17, to_17);
17028
17033
  if (revisionId_3 === null) return;
17029
17034
  const editor_9 = pagedEditorRef.current?.getEditor();
17030
17035
  if (editor_9?.getCanonicalDocument()) editor_9.resolveCanonicalRevisions([revisionId_3], "accept");
17031
- else acceptAIEditRevision(revisionId_3)(view_57.state, view_57.dispatch);
17036
+ else acceptAIEditRevision(revisionId_3)(view_58.state, view_58.dispatch);
17032
17037
  extractTrackedChanges();
17033
17038
  }, [extractTrackedChanges, resolveSidebarChangeRevisionId]);
17034
17039
  const handleSidebarRejectChange = useCallback((from_18, to_18) => {
17035
- const view_58 = pagedEditorRef.current?.getView();
17036
- if (!view_58) return;
17040
+ const view_59 = pagedEditorRef.current?.getView();
17041
+ if (!view_59) return;
17037
17042
  const revisionId_4 = resolveSidebarChangeRevisionId(from_18, to_18);
17038
17043
  if (revisionId_4 === null) return;
17039
17044
  const editor_10 = pagedEditorRef.current?.getEditor();
17040
17045
  if (editor_10?.getCanonicalDocument()) editor_10.resolveCanonicalRevisions([revisionId_4], "reject");
17041
- else rejectAIEditRevision(revisionId_4)(view_58.state, view_58.dispatch);
17046
+ else rejectAIEditRevision(revisionId_4)(view_59.state, view_59.dispatch);
17042
17047
  extractTrackedChanges();
17043
17048
  }, [extractTrackedChanges, resolveSidebarChangeRevisionId]);
17044
17049
  const commentsPageWidth = history.state?.package.document.finalSectionProperties?.pageWidth;
@@ -17162,7 +17167,7 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
17162
17167
  attempts++;
17163
17168
  const container_0 = scrollContainerRef.current;
17164
17169
  if (!container_0) return;
17165
- const element_1 = container_0.querySelector(`.layout-page-content [data-pm-start="${String(pmPos)}"]`);
17170
+ const element_1 = container_0.querySelector(`.layout-page-content ${paintedStartSelector(pmPos)}`);
17166
17171
  if (element_1) {
17167
17172
  delete element_1.dataset["folioOutlineFlash"];
17168
17173
  element_1.offsetWidth;
@@ -17188,8 +17193,8 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
17188
17193
  }, [readOnly]);
17189
17194
  const closeTableProperties = useCallback(() => setTablePropsOpen(false), []);
17190
17195
  const applyTableProperties = useCallback((props_0) => {
17191
- const view_59 = getActiveEditorView();
17192
- if (view_59) setTableProperties(props_0)(view_59.state, view_59.dispatch);
17196
+ const view_60 = getActiveEditorView();
17197
+ if (view_60) setTableProperties(props_0)(view_60.state, view_60.dispatch);
17193
17198
  }, [getActiveEditorView]);
17194
17199
  const closeImagePosition = useCallback(() => setImagePositionOpen(false), [setImagePositionOpen]);
17195
17200
  const closeImageProperties = useCallback(() => setImagePropsOpen(false), [setImagePropsOpen]);
@@ -17197,8 +17202,8 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
17197
17202
  const closeFootnoteProperties = useCallback(() => setFootnotePropsOpen(false), []);
17198
17203
  const closeInsertSymbol = useCallback(() => setShowInsertSymbol(false), []);
17199
17204
  const insertSymbol = useCallback((symbol) => {
17200
- const view_60 = getActiveEditorView();
17201
- if (view_60) view_60.dispatch(view_60.state.tr.insertText(symbol).scrollIntoView());
17205
+ const view_61 = getActiveEditorView();
17206
+ if (view_61) view_61.dispatch(view_61.state.tr.insertText(symbol).scrollIntoView());
17202
17207
  }, [getActiveEditorView]);
17203
17208
  const imagePropertiesCurrentData = useMemo(() => buildImagePropertiesData(state.pmImageContext), [state.pmImageContext]);
17204
17209
  const { close: closeFindDialog } = findReplace;
@@ -17289,8 +17294,8 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
17289
17294
  ]);
17290
17295
  const closeNumberingValueDialog = useCallback(() => setNumberingValueDialogOpen(false), []);
17291
17296
  const applyNumberingValue = useCallback((value_0) => {
17292
- const view_61 = getActiveEditorView();
17293
- if (view_61) setNumberingValue(value_0)(view_61.state, view_61.dispatch);
17297
+ const view_62 = getActiveEditorView();
17298
+ if (view_62) setNumberingValue(value_0)(view_62.state, view_62.dispatch);
17294
17299
  }, [getActiveEditorView]);
17295
17300
  const numberingValueDialog = useMemo(() => ({
17296
17301
  isOpen: numberingValueDialogOpen,
@@ -17594,8 +17599,8 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
17594
17599
  onMouseDown: (e_1) => {
17595
17600
  e_1.preventDefault();
17596
17601
  e_1.stopPropagation();
17597
- const view_62 = pagedEditorRef.current?.getView();
17598
- if (!view_62) {
17602
+ const view_63 = pagedEditorRef.current?.getView();
17603
+ if (!view_63) {
17599
17604
  setFloatingCommentBtn(null);
17600
17605
  return;
17601
17606
  }
@@ -17603,9 +17608,9 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
17603
17608
  from: floatingCommentBtn.from,
17604
17609
  to: floatingCommentBtn.to
17605
17610
  };
17606
- const currentSelection = view_62.state.selection;
17611
+ const currentSelection = view_63.state.selection;
17607
17612
  const safeRange = resolveCommentCreationRange({
17608
- docSize: view_62.state.doc.content.size,
17613
+ docSize: view_63.state.doc.content.size,
17609
17614
  capturedRange,
17610
17615
  currentRange: {
17611
17616
  from: currentSelection.from,
@@ -17620,7 +17625,7 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
17620
17625
  }
17621
17626
  setCommentSelectionRange(safeRange);
17622
17627
  if (commentDraftMode === "prosemirror") {
17623
- if (!applyCommentMarkRange(view_62, safeRange, -1, { selectEnd: true })) {
17628
+ if (!markPendingComment(view_63, safeRange, { selectEnd: true })) {
17624
17629
  setCommentSelectionRange(null);
17625
17630
  setFloatingCommentBtn(null);
17626
17631
  return;
@@ -17677,13 +17682,12 @@ const DocxEditor = forwardRef(function DocxEditor({ accessibleName, documentBuff
17677
17682
  if (hfEditPosition === "header") return headerContent;
17678
17683
  return footerContent;
17679
17684
  })()) return null;
17680
- const targetEl = editorContentElement?.querySelector(hfEditPosition === "header" ? ".layout-page-header" : ".layout-page-footer");
17681
17685
  const parentEl_0 = editorContentElement;
17682
- if (!targetEl || !parentEl_0) return null;
17686
+ if (!parentEl_0) return null;
17683
17687
  return /* @__PURE__ */ jsx(InlineHeaderFooterEditor, {
17684
17688
  ref: hfEditorRef,
17685
17689
  position: hfEditPosition,
17686
- targetElement: targetEl,
17690
+ targetSelector: hfEditPosition === "header" ? ".layout-page-header" : ".layout-page-footer",
17687
17691
  parentElement: parentEl_0,
17688
17692
  getActiveView: getActiveHfView,
17689
17693
  onClose: handleBodyClick,