@tiptap/extension-find-and-replace 3.33.1 → 3.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { Extension } from "@tiptap/core";
2
- import { Plugin, PluginKey, TextSelection } from "@tiptap/pm/state";
2
+ import { Plugin, PluginKey, Selection, TextSelection } from "@tiptap/pm/state";
3
3
  import { RE2JS } from "re2js";
4
4
  import { Decoration, DecorationSet } from "@tiptap/pm/view";
5
+ import { AttrStep } from "@tiptap/pm/transform";
5
6
  //#region src/state/debounced-search-state.ts
6
7
  const debouncedSearchState = /* @__PURE__ */ new WeakMap();
7
8
  function getDebouncedSearchState(editor) {
@@ -47,6 +48,50 @@ const style = `.find-and-replace-result {
47
48
  }
48
49
  `;
49
50
  //#endregion
51
+ //#region src/search/has-block-between.ts
52
+ /**
53
+ * Checks if a whole node lies between two positions.
54
+ * Nodes that only open or close in the range, like the parents of two textblocks, do not count.
55
+ * @param doc The document to check.
56
+ * @param from The start of the range.
57
+ * @param to The end of the range.
58
+ * @returns Whether a node lies fully inside the range.
59
+ */
60
+ function hasBlockBetween(doc, from, to) {
61
+ let found = false;
62
+ doc.nodesBetween(from, to, (node, pos) => {
63
+ if (found) return false;
64
+ if (pos >= from && pos + node.nodeSize <= to) {
65
+ found = true;
66
+ return false;
67
+ }
68
+ return true;
69
+ });
70
+ return found;
71
+ }
72
+ //#endregion
73
+ //#region src/search/group-continued-textblocks.ts
74
+ /**
75
+ * Groups textblocks that continue the textblock before them in the list.
76
+ * @param doc The document the textblocks are in.
77
+ * @param textblocks Whole chains of continued textblocks in document order.
78
+ * @param continuesNode Whether a textblock continues the one before it.
79
+ * @returns The groups to search as one text each.
80
+ */
81
+ function groupContinuedTextblocks(doc, textblocks, continuesNode = () => false) {
82
+ const groups = [];
83
+ textblocks.forEach((textblock) => {
84
+ const group = groups.at(-1);
85
+ const previous = group === null || group === void 0 ? void 0 : group.at(-1);
86
+ if (group && previous && continuesNode(textblock.node) && !hasBlockBetween(doc, previous.pos + previous.node.nodeSize, textblock.pos)) {
87
+ group.push(textblock);
88
+ return;
89
+ }
90
+ groups.push([textblock]);
91
+ });
92
+ return groups;
93
+ }
94
+ //#endregion
50
95
  //#region src/search/regex.ts
51
96
  const escapeRegExp = (value) => {
52
97
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -111,20 +156,22 @@ function findMatches(regex, text) {
111
156
  }
112
157
  //#endregion
113
158
  //#region src/search/text-segments.ts
114
- function getTextSegments(textblock, pos) {
159
+ function getTextSegments(textblocks) {
115
160
  const segments = [];
116
161
  let textOffset = 0;
117
- textblock.forEach((child, offset) => {
118
- var _child$text;
119
- const text = child.isText ? (_child$text = child.text) !== null && _child$text !== void 0 ? _child$text : "" : "\n";
120
- segments.push({
121
- isText: child.isText,
122
- pos: pos + 1 + offset,
123
- length: child.nodeSize,
124
- text,
125
- textOffset
162
+ textblocks.forEach(({ node, pos }) => {
163
+ node.forEach((child, offset) => {
164
+ var _child$text;
165
+ const text = child.isText ? (_child$text = child.text) !== null && _child$text !== void 0 ? _child$text : "" : "\n";
166
+ segments.push({
167
+ isText: child.isText,
168
+ pos: pos + 1 + offset,
169
+ length: child.nodeSize,
170
+ text,
171
+ textOffset
172
+ });
173
+ textOffset += text.length;
126
174
  });
127
- textOffset += text.length;
128
175
  });
129
176
  return segments;
130
177
  }
@@ -144,13 +191,16 @@ function offsetToPos(segments, offset) {
144
191
  const segment = findOffsetSegment(segments, offset);
145
192
  return segment ? segment.pos + Math.min(offset - segment.textOffset, segment.length) : 0;
146
193
  }
194
+ function endOffsetToPos(segments, offset) {
195
+ return offsetToPos(segments, offset - 1) + 1;
196
+ }
147
197
  function overlapsNonTextSegment(segments, from, to) {
148
198
  return segments.some((segment) => !segment.isText && from < segment.textOffset + segment.text.length && to > segment.textOffset);
149
199
  }
150
200
  //#endregion
151
201
  //#region src/search/textblock-search.ts
152
- function searchTextblock(regex, textblock, pos) {
153
- const segments = getTextSegments(textblock, pos);
202
+ function searchTextblockGroup(regex, textblocks) {
203
+ const segments = getTextSegments(textblocks);
154
204
  const text = segments.map((segment) => segment.text).join("");
155
205
  const results = [];
156
206
  for (const match of findMatches(regex, text)) {
@@ -159,7 +209,7 @@ function searchTextblock(regex, textblock, pos) {
159
209
  if (overlapsNonTextSegment(segments, match.index, matchEnd)) continue;
160
210
  results.push({
161
211
  from: offsetToPos(segments, match.index),
162
- to: offsetToPos(segments, matchEnd)
212
+ to: endOffsetToPos(segments, matchEnd)
163
213
  });
164
214
  }
165
215
  return results;
@@ -168,22 +218,25 @@ function searchTextblock(regex, textblock, pos) {
168
218
  //#region src/search/search.ts
169
219
  /**
170
220
  * Searches textblocks for a term and returns their matched ranges.
171
- * @param textblocks The textblocks and their document positions.
221
+ * Textblocks joined by `continuesNode` are searched as one text when `doc` is given.
222
+ * @param textblocks The textblocks and their document positions. Include every textblock of a continued chain.
172
223
  * @param term The search term, treated as regex source when `useRegex` is enabled.
173
- * @param options Case sensitivity, regex mode, and whole word matching.
224
+ * @param options Case sensitivity, regex mode, whole word matching, and continued textblocks.
225
+ * @param doc The document the textblocks are in. Needed to join continued textblocks.
174
226
  * @returns The list of matched ranges in textblock order.
175
227
  */
176
- function searchTextblocks(textblocks, term, options) {
228
+ function searchTextblocks(textblocks, term, options, doc) {
177
229
  const regex = createSearchRegex(term, options);
178
230
  if (!regex) return [];
179
- return textblocks.flatMap(({ node, pos }) => searchTextblock(regex, node, pos));
231
+ return (doc ? groupContinuedTextblocks(doc, textblocks, options.continuesNode) : textblocks.map((textblock) => [textblock])).flatMap((group) => searchTextblockGroup(regex, group));
180
232
  }
181
233
  /**
182
234
  * Searches all textblocks of a document for a term and returns the matched ranges.
183
- * Matches may span multiple text nodes (e.g. across marks), but never leave a textblock.
235
+ * Matches may span multiple text nodes (e.g. across marks), but only leave a textblock
236
+ * when `continuesNode` joins it with the next one.
184
237
  * @param doc The document to search in.
185
238
  * @param term The search term, treated as regex source when `useRegex` is enabled.
186
- * @param options Case sensitivity, regex mode, and whole word matching.
239
+ * @param options Case sensitivity, regex mode, whole word matching, and continued textblocks.
187
240
  * @returns The list of matched ranges in document order.
188
241
  */
189
242
  function searchDocument(doc, term, options) {
@@ -196,7 +249,7 @@ function searchDocument(doc, term, options) {
196
249
  });
197
250
  return false;
198
251
  });
199
- return searchTextblocks(textblocks, term, options);
252
+ return searchTextblocks(textblocks, term, options, doc);
200
253
  }
201
254
  /**
202
255
  * Finds the index of the first result at or after a position, wrapping around
@@ -233,6 +286,7 @@ function createState(doc, options) {
233
286
  caseSensitive: options.caseSensitive,
234
287
  useRegex: options.useRegex,
235
288
  wholeWord: options.wholeWord,
289
+ continuesNode: options.continuesNode,
236
290
  results,
237
291
  currentIndex,
238
292
  currentResultVisited: false,
@@ -276,11 +330,11 @@ function resultInTextblocks(result, textblocks) {
276
330
  while (start <= end) {
277
331
  const index = Math.floor((start + end) / 2);
278
332
  const textblock = textblocks[index];
279
- if (result.from < textblock.from) {
333
+ if (result.to <= textblock.from) {
280
334
  end = index - 1;
281
335
  continue;
282
336
  }
283
- if (result.to > textblock.to) {
337
+ if (result.from >= textblock.to) {
284
338
  start = index + 1;
285
339
  continue;
286
340
  }
@@ -390,26 +444,102 @@ function refreshCurrentIndexState(previousState, state, doc, meta) {
390
444
  };
391
445
  }
392
446
  //#endregion
447
+ //#region src/utils/findNearestTextblock.ts
448
+ function findNearestTextblock(doc, pos, direction) {
449
+ const selection = Selection.findFrom(doc.resolve(pos), direction, true);
450
+ if (!selection) return null;
451
+ const node = selection.$from.parent;
452
+ const from = selection.$from.before();
453
+ return {
454
+ node,
455
+ pos: from,
456
+ from,
457
+ to: from + node.nodeSize
458
+ };
459
+ }
460
+ //#endregion
461
+ //#region src/utils/findAdjacentTextblock.ts
462
+ function findAdjacentTextblock(doc, textblock, direction) {
463
+ return findNearestTextblock(doc, direction === 1 ? textblock.to : textblock.from, direction);
464
+ }
465
+ //#endregion
466
+ //#region src/utils/addContinuedTextblocks.ts
467
+ function findJoinedTextblock(doc, textblock, direction, continuesNode) {
468
+ const adjacent = findAdjacentTextblock(doc, textblock, direction);
469
+ if (!adjacent) return null;
470
+ const [first, second] = direction === 1 ? [textblock, adjacent] : [adjacent, textblock];
471
+ if (!continuesNode(second.node) || hasBlockBetween(doc, first.to, second.from)) return null;
472
+ return adjacent;
473
+ }
474
+ function addChain(doc, textblock, continuesNode, found) {
475
+ let previous = findJoinedTextblock(doc, textblock, -1, continuesNode);
476
+ while (previous) {
477
+ found.set(previous.pos, previous);
478
+ previous = findJoinedTextblock(doc, previous, -1, continuesNode);
479
+ }
480
+ let next = findJoinedTextblock(doc, textblock, 1, continuesNode);
481
+ while (next) {
482
+ found.set(next.pos, next);
483
+ next = findJoinedTextblock(doc, next, 1, continuesNode);
484
+ }
485
+ }
486
+ /**
487
+ * Adds the textblocks that are joined with the given ones by `continuesNode`.
488
+ * @param doc The document the textblocks are in.
489
+ * @param textblocks The textblocks in document order.
490
+ * @param continuesNode Whether a textblock continues the one before it.
491
+ * @returns The textblocks with their whole chains, in document order.
492
+ */
493
+ function addContinuedTextblocks(doc, textblocks, continuesNode) {
494
+ const found = /* @__PURE__ */ new Map();
495
+ textblocks.forEach((textblock) => {
496
+ if (found.has(textblock.pos)) return;
497
+ found.set(textblock.pos, textblock);
498
+ addChain(doc, textblock, continuesNode, found);
499
+ });
500
+ return [...found.values()].sort((first, second) => first.pos - second.pos);
501
+ }
502
+ //#endregion
393
503
  //#region src/utils/getChangedTextblocks.ts
394
- function getChangedTextblocks(doc, mapping) {
504
+ function addTextblock(textblocks, node, pos) {
505
+ const textblock = {
506
+ node,
507
+ pos,
508
+ from: pos,
509
+ to: pos + node.nodeSize
510
+ };
511
+ textblocks.set(pos, textblock);
512
+ return textblock;
513
+ }
514
+ function addAttributeChanges(doc, transform, textblocks) {
515
+ transform.steps.forEach((step, index) => {
516
+ if (!(step instanceof AttrStep)) return;
517
+ const pos = transform.mapping.slice(index + 1).map(step.pos);
518
+ const node = doc.nodeAt(pos);
519
+ if (!(node === null || node === void 0 ? void 0 : node.isTextblock)) return;
520
+ const previous = findAdjacentTextblock(doc, addTextblock(textblocks, node, pos), -1);
521
+ if (previous) textblocks.set(previous.pos, previous);
522
+ });
523
+ }
524
+ function getChangedTextblocks(doc, transform) {
525
+ const { mapping } = transform;
395
526
  const textblocks = /* @__PURE__ */ new Map();
396
527
  mapping.maps.forEach((stepMap, index) => {
397
528
  const remaining = mapping.slice(index + 1);
398
529
  stepMap.forEach((_oldStart, _oldEnd, newStart, newEnd) => {
399
- const from = Math.max(0, remaining.map(newStart, -1) - 1);
400
- const to = Math.min(doc.content.size, remaining.map(newEnd, 1) + 1);
530
+ var _before$from, _after$to;
531
+ const before = findNearestTextblock(doc, remaining.map(newStart, -1), -1);
532
+ const after = findNearestTextblock(doc, remaining.map(newEnd, 1), 1);
533
+ const from = (_before$from = before === null || before === void 0 ? void 0 : before.from) !== null && _before$from !== void 0 ? _before$from : 0;
534
+ const to = (_after$to = after === null || after === void 0 ? void 0 : after.to) !== null && _after$to !== void 0 ? _after$to : doc.content.size;
401
535
  doc.nodesBetween(from, to, (node, pos) => {
402
536
  if (!node.isTextblock) return true;
403
- textblocks.set(pos, {
404
- node,
405
- pos,
406
- from: pos,
407
- to: pos + node.nodeSize
408
- });
537
+ addTextblock(textblocks, node, pos);
409
538
  return false;
410
539
  });
411
540
  });
412
541
  });
542
+ addAttributeChanges(doc, transform, textblocks);
413
543
  return [...textblocks.values()].sort((first, second) => first.pos - second.pos);
414
544
  }
415
545
  //#endregion
@@ -454,9 +584,10 @@ function mergeResults(first, second) {
454
584
  }
455
585
  //#endregion
456
586
  //#region src/utils/refreshDocumentState.ts
457
- function refreshDocumentState(previousState, state, doc, meta, mapping) {
458
- const textblocks = getChangedTextblocks(doc, mapping);
459
- const results = mergeResults(mapResults(previousState.results, mapping).filter((result) => !resultInTextblocks(result, textblocks)), searchTextblocks(textblocks, state.searchTerm, state));
587
+ function refreshDocumentState(previousState, state, doc, meta, transform) {
588
+ const { mapping } = transform;
589
+ const textblocks = addContinuedTextblocks(doc, getChangedTextblocks(doc, transform), state.continuesNode);
590
+ const results = mergeResults(mapResults(previousState.results, mapping).filter((result) => !resultInTextblocks(result, textblocks)), searchTextblocks(textblocks, state.searchTerm, state, doc));
460
591
  const currentIndex = resolveCurrentIndex(previousState, results, meta, true, mapping);
461
592
  const previousCurrent = previousState.currentIndex === null ? null : mapResult(previousState.results[previousState.currentIndex], mapping);
462
593
  const current = currentIndex === null ? null : results[currentIndex];
@@ -499,9 +630,9 @@ function touchesSearch(meta) {
499
630
  }
500
631
  //#endregion
501
632
  //#region src/utils/updateState.ts
502
- function updateState(previousState, state, doc, meta, docChanged, mapping) {
503
- if (touchesSearch(meta)) return refreshState(previousState, state, doc, meta, docChanged, mapping);
504
- if (docChanged) return refreshDocumentState(previousState, state, doc, meta, mapping);
633
+ function updateState(previousState, state, doc, meta, transform) {
634
+ if (touchesSearch(meta)) return refreshState(previousState, state, doc, meta, transform.docChanged, transform.mapping);
635
+ if (transform.docChanged) return refreshDocumentState(previousState, state, doc, meta, transform);
505
636
  if (hasCurrentIndex(meta)) return refreshCurrentIndexState(previousState, state, doc, meta);
506
637
  return state;
507
638
  }
@@ -524,7 +655,7 @@ const FindAndReplacePlugin = (options, onCreate) => {
524
655
  return updateState(state, {
525
656
  ...state,
526
657
  ...meta
527
- }, newState.doc, meta, tr.docChanged, tr.mapping);
658
+ }, newState.doc, meta, tr);
528
659
  }
529
660
  },
530
661
  props: { decorations(state) {
@@ -649,11 +780,7 @@ function getPendingAwarePluginState(state, pendingTerm) {
649
780
  const pluginState = FindAndReplacePluginKey.getState(state);
650
781
  if (!pluginState) return null;
651
782
  if (pendingTerm === null) return pluginState.results.length === 0 ? null : pluginState;
652
- const results = searchDocument(state.doc, pendingTerm, {
653
- caseSensitive: pluginState.caseSensitive,
654
- useRegex: pluginState.useRegex,
655
- wholeWord: pluginState.wholeWord
656
- });
783
+ const results = searchDocument(state.doc, pendingTerm, pluginState);
657
784
  if (results.length === 0) return null;
658
785
  return {
659
786
  ...pluginState,
@@ -684,13 +811,9 @@ function selectResult(tr, result, index) {
684
811
  tr.scrollIntoView();
685
812
  }
686
813
  function replaceResult(tr, pluginState, result) {
687
- const { searchTerm, replaceTerm, caseSensitive, useRegex, wholeWord } = pluginState;
814
+ const { searchTerm, replaceTerm } = pluginState;
688
815
  tr.insertText(replaceTerm, result.from, result.to);
689
- const results = searchDocument(tr.doc, searchTerm, {
690
- caseSensitive,
691
- useRegex,
692
- wholeWord
693
- });
816
+ const results = searchDocument(tr.doc, searchTerm, pluginState);
694
817
  const nextIndex = findNextIndex(results, result.from + replaceTerm.length);
695
818
  if (nextIndex === null) {
696
819
  mergePluginMeta(tr, { currentIndex: null });
@@ -707,6 +830,7 @@ const FindAndReplace = Extension.create({
707
830
  caseSensitive: false,
708
831
  useRegex: false,
709
832
  wholeWord: false,
833
+ continuesNode: () => false,
710
834
  searchDebounceMs: 250,
711
835
  injectCSS: true,
712
836
  injectNonce: void 0