@tiptap/extension-find-and-replace 3.33.0 → 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.
Files changed (37) hide show
  1. package/dist/index.cjs +219 -79
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +25 -5
  4. package/dist/index.d.cts.map +1 -1
  5. package/dist/index.d.ts +25 -5
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +220 -80
  8. package/dist/index.js.map +1 -1
  9. package/package.json +5 -5
  10. package/src/find-and-replace.test.ts +293 -0
  11. package/src/find-and-replace.ts +52 -71
  12. package/src/plugin/plugin-state.ts +4 -0
  13. package/src/plugin/plugin.ts +1 -8
  14. package/src/search/group-continued-textblocks.ts +39 -0
  15. package/src/search/has-block-between.test.ts +27 -0
  16. package/src/search/has-block-between.ts +28 -0
  17. package/src/search/search.test.ts +100 -0
  18. package/src/search/search.ts +18 -9
  19. package/src/search/text-segments.ts +18 -11
  20. package/src/search/textblock-search.ts +13 -7
  21. package/src/search/types.ts +3 -2
  22. package/src/types.ts +16 -0
  23. package/src/utils/addContinuedTextblocks.test.ts +99 -0
  24. package/src/utils/addContinuedTextblocks.ts +74 -0
  25. package/src/utils/createState.ts +7 -2
  26. package/src/utils/findAdjacentTextblock.ts +14 -0
  27. package/src/utils/findNearestTextblock.ts +21 -0
  28. package/src/utils/getChangedTextblocks.test.ts +40 -0
  29. package/src/utils/getChangedTextblocks.ts +54 -6
  30. package/src/utils/getSearchCurrentIndex.ts +18 -1
  31. package/src/utils/keepsVisitedResult.ts +16 -0
  32. package/src/utils/refreshCurrentIndexState.ts +1 -0
  33. package/src/utils/refreshDocumentState.ts +17 -6
  34. package/src/utils/refreshState.ts +12 -0
  35. package/src/utils/resultInTextblocks.test.ts +25 -0
  36. package/src/utils/resultInTextblocks.ts +2 -2
  37. package/src/utils/updateState.ts +7 -8
@@ -0,0 +1,100 @@
1
+ import { describe, expect, it } from 'vite-plus/test'
2
+
3
+ import {
4
+ continuesNode,
5
+ createContinuedDoc,
6
+ paragraph,
7
+ } from '../../tests/utils/createContinuedDoc.js'
8
+ import { searchDocument } from './search.js'
9
+
10
+ const options = { caseSensitive: false, useRegex: false, wholeWord: false }
11
+
12
+ describe('searchDocument with continued textblocks', () => {
13
+ const doc = createContinuedDoc([
14
+ paragraph('find the '),
15
+ paragraph('phrase here', true),
16
+ paragraph('the'),
17
+ ])
18
+
19
+ it('does not join textblocks by default', () => {
20
+ expect(searchDocument(doc, 'the phrase', options)).toEqual([])
21
+ })
22
+
23
+ it('finds a match that runs into the continued textblock', () => {
24
+ expect(searchDocument(doc, 'the phrase', { ...options, continuesNode })).toEqual([
25
+ { from: 6, to: 18 },
26
+ ])
27
+ })
28
+
29
+ it('keeps a match that ends or starts at the boundary in its own textblock', () => {
30
+ expect(searchDocument(doc, 'the ', { ...options, continuesNode })).toEqual([
31
+ { from: 6, to: 10 },
32
+ ])
33
+ expect(searchDocument(doc, 'phrase', { ...options, continuesNode })).toEqual([
34
+ { from: 12, to: 18 },
35
+ ])
36
+ })
37
+
38
+ it('does not join a textblock that does not continue', () => {
39
+ expect(searchDocument(doc, 'herethe', { ...options, continuesNode })).toEqual([])
40
+ })
41
+
42
+ it('joins a chain of continued textblocks', () => {
43
+ const chain = createContinuedDoc([
44
+ paragraph('a lo'),
45
+ paragraph('n', true),
46
+ paragraph('g word', true),
47
+ ])
48
+
49
+ expect(searchDocument(chain, 'long', { ...options, continuesNode })).toEqual([
50
+ { from: 3, to: 11 },
51
+ ])
52
+ })
53
+
54
+ it('matches whole words across the boundary', () => {
55
+ const split = createContinuedDoc([paragraph('hel'), paragraph('lo hello', true)])
56
+ const results = searchDocument(split, 'hello', { ...options, wholeWord: true, continuesNode })
57
+
58
+ expect(results).toEqual([
59
+ { from: 1, to: 8 },
60
+ { from: 9, to: 14 },
61
+ ])
62
+ })
63
+
64
+ it('does not match across a hard break at the start of a continued textblock', () => {
65
+ const split = createContinuedDoc([
66
+ paragraph('one'),
67
+ {
68
+ type: 'paragraph',
69
+ attrs: { continued: true },
70
+ content: [{ type: 'hardBreak' }, { type: 'text', text: 'two' }],
71
+ },
72
+ ])
73
+
74
+ expect(searchDocument(split, 'onetwo', { ...options, continuesNode })).toEqual([])
75
+ expect(searchDocument(split, 'two', { ...options, continuesNode })).toEqual([
76
+ { from: 7, to: 10 },
77
+ ])
78
+ })
79
+
80
+ it('does not join continued textblocks with a block between them', () => {
81
+ const blocked = createContinuedDoc([
82
+ paragraph('find the '),
83
+ { type: 'horizontalRule' },
84
+ paragraph('phrase here', true),
85
+ ])
86
+
87
+ expect(searchDocument(blocked, 'the phrase', { ...options, continuesNode })).toEqual([])
88
+ })
89
+
90
+ it('joins continued textblocks in different parents', () => {
91
+ const nested = createContinuedDoc([
92
+ { type: 'blockquote', content: [paragraph('find the ')] },
93
+ { type: 'blockquote', content: [paragraph('phrase here', true)] },
94
+ ])
95
+
96
+ expect(searchDocument(nested, 'the phrase', { ...options, continuesNode })).toEqual([
97
+ { from: 7, to: 21 },
98
+ ])
99
+ })
100
+ })
@@ -1,7 +1,8 @@
1
- import type { Node } from '@tiptap/pm/model'
1
+ import type { Node as PMNode } from '@tiptap/pm/model'
2
2
 
3
+ import { groupContinuedTextblocks } from './group-continued-textblocks.js'
3
4
  import { createSearchRegex } from './regex.js'
4
- import { searchTextblock } from './textblock-search.js'
5
+ import { searchTextblockGroup } from './textblock-search.js'
5
6
  import type { SearchOptions, SearchResult, TextblockSearchTarget } from './types.js'
6
7
 
7
8
  export type { SearchOptions, SearchResult, TextblockSearchTarget } from './types.js'
@@ -9,15 +10,18 @@ export { createSearchRegex } from './regex.js'
9
10
 
10
11
  /**
11
12
  * Searches textblocks for a term and returns their matched ranges.
12
- * @param textblocks The textblocks and their document positions.
13
+ * Textblocks joined by `continuesNode` are searched as one text when `doc` is given.
14
+ * @param textblocks The textblocks and their document positions. Include every textblock of a continued chain.
13
15
  * @param term The search term, treated as regex source when `useRegex` is enabled.
14
- * @param options Case sensitivity, regex mode, and whole word matching.
16
+ * @param options Case sensitivity, regex mode, whole word matching, and continued textblocks.
17
+ * @param doc The document the textblocks are in. Needed to join continued textblocks.
15
18
  * @returns The list of matched ranges in textblock order.
16
19
  */
17
20
  export function searchTextblocks(
18
21
  textblocks: readonly TextblockSearchTarget[],
19
22
  term: string,
20
23
  options: SearchOptions,
24
+ doc?: PMNode,
21
25
  ): SearchResult[] {
22
26
  const regex = createSearchRegex(term, options)
23
27
 
@@ -25,18 +29,23 @@ export function searchTextblocks(
25
29
  return []
26
30
  }
27
31
 
28
- return textblocks.flatMap(({ node, pos }) => searchTextblock(regex, node, pos))
32
+ const groups = doc
33
+ ? groupContinuedTextblocks(doc, textblocks, options.continuesNode)
34
+ : textblocks.map(textblock => [textblock])
35
+
36
+ return groups.flatMap(group => searchTextblockGroup(regex, group))
29
37
  }
30
38
 
31
39
  /**
32
40
  * Searches all textblocks of a document for a term and returns the matched ranges.
33
- * Matches may span multiple text nodes (e.g. across marks), but never leave a textblock.
41
+ * Matches may span multiple text nodes (e.g. across marks), but only leave a textblock
42
+ * when `continuesNode` joins it with the next one.
34
43
  * @param doc The document to search in.
35
44
  * @param term The search term, treated as regex source when `useRegex` is enabled.
36
- * @param options Case sensitivity, regex mode, and whole word matching.
45
+ * @param options Case sensitivity, regex mode, whole word matching, and continued textblocks.
37
46
  * @returns The list of matched ranges in document order.
38
47
  */
39
- export function searchDocument(doc: Node, term: string, options: SearchOptions): SearchResult[] {
48
+ export function searchDocument(doc: PMNode, term: string, options: SearchOptions): SearchResult[] {
40
49
  const textblocks: TextblockSearchTarget[] = []
41
50
 
42
51
  doc.descendants((node, pos) => {
@@ -49,7 +58,7 @@ export function searchDocument(doc: Node, term: string, options: SearchOptions):
49
58
  return false
50
59
  })
51
60
 
52
- return searchTextblocks(textblocks, term, options)
61
+ return searchTextblocks(textblocks, term, options, doc)
53
62
  }
54
63
 
55
64
  /**
@@ -1,4 +1,4 @@
1
- import type { Node } from '@tiptap/pm/model'
1
+ import type { TextblockSearchTarget } from './types.js'
2
2
 
3
3
  interface TextSegment {
4
4
  isText: boolean
@@ -10,21 +10,23 @@ interface TextSegment {
10
10
 
11
11
  // Non-text inline nodes (hard break, mention, ...) contribute a placeholder
12
12
  // so matches never silently span across them.
13
- export function getTextSegments(textblock: Node, pos: number): TextSegment[] {
13
+ export function getTextSegments(textblocks: readonly TextblockSearchTarget[]): TextSegment[] {
14
14
  const segments: TextSegment[] = []
15
15
  let textOffset = 0
16
16
 
17
- textblock.forEach((child, offset) => {
18
- const text = child.isText ? (child.text ?? '') : '\n'
17
+ textblocks.forEach(({ node, pos }) => {
18
+ node.forEach((child, offset) => {
19
+ const text = child.isText ? (child.text ?? '') : '\n'
19
20
 
20
- segments.push({
21
- isText: child.isText,
22
- pos: pos + 1 + offset,
23
- length: child.nodeSize,
24
- text,
25
- textOffset,
21
+ segments.push({
22
+ isText: child.isText,
23
+ pos: pos + 1 + offset,
24
+ length: child.nodeSize,
25
+ text,
26
+ textOffset,
27
+ })
28
+ textOffset += text.length
26
29
  })
27
- textOffset += text.length
28
30
  })
29
31
 
30
32
  return segments
@@ -55,6 +57,11 @@ export function offsetToPos(segments: TextSegment[], offset: number): number {
55
57
  return segment ? segment.pos + Math.min(offset - segment.textOffset, segment.length) : 0
56
58
  }
57
59
 
60
+ // Resolve the last matched character, so an end at a textblock boundary stays in that textblock
61
+ export function endOffsetToPos(segments: TextSegment[], offset: number): number {
62
+ return offsetToPos(segments, offset - 1) + 1
63
+ }
64
+
58
65
  export function overlapsNonTextSegment(segments: TextSegment[], from: number, to: number): boolean {
59
66
  return segments.some(
60
67
  segment =>
@@ -1,12 +1,18 @@
1
- import type { Node } from '@tiptap/pm/model'
2
-
3
1
  import { findMatches } from './matches.js'
4
2
  import type { SearchRegex } from './regex.js'
5
- import { getTextSegments, offsetToPos, overlapsNonTextSegment } from './text-segments.js'
6
- import type { SearchResult } from './types.js'
3
+ import {
4
+ endOffsetToPos,
5
+ getTextSegments,
6
+ offsetToPos,
7
+ overlapsNonTextSegment,
8
+ } from './text-segments.js'
9
+ import type { SearchResult, TextblockSearchTarget } from './types.js'
7
10
 
8
- export function searchTextblock(regex: SearchRegex, textblock: Node, pos: number): SearchResult[] {
9
- const segments = getTextSegments(textblock, pos)
11
+ export function searchTextblockGroup(
12
+ regex: SearchRegex,
13
+ textblocks: readonly TextblockSearchTarget[],
14
+ ): SearchResult[] {
15
+ const segments = getTextSegments(textblocks)
10
16
  const text = segments.map(segment => segment.text).join('')
11
17
  const results: SearchResult[] = []
12
18
 
@@ -23,7 +29,7 @@ export function searchTextblock(regex: SearchRegex, textblock: Node, pos: number
23
29
 
24
30
  results.push({
25
31
  from: offsetToPos(segments, match.index),
26
- to: offsetToPos(segments, matchEnd),
32
+ to: endOffsetToPos(segments, matchEnd),
27
33
  })
28
34
  }
29
35
 
@@ -1,4 +1,4 @@
1
- import type { Node } from '@tiptap/pm/model'
1
+ import type { Node as PMNode } from '@tiptap/pm/model'
2
2
 
3
3
  export interface SearchResult {
4
4
  from: number
@@ -6,7 +6,7 @@ export interface SearchResult {
6
6
  }
7
7
 
8
8
  export interface TextblockSearchTarget {
9
- node: Node
9
+ node: PMNode
10
10
  pos: number
11
11
  }
12
12
 
@@ -14,4 +14,5 @@ export interface SearchOptions {
14
14
  caseSensitive: boolean
15
15
  useRegex: boolean
16
16
  wholeWord: boolean
17
+ continuesNode?: (node: PMNode) => boolean
17
18
  }
package/src/types.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { Node as ProseMirrorNode } from '@tiptap/pm/model'
2
+
1
3
  import type { SearchResult } from './search/search.js'
2
4
 
3
5
  export interface FindAndReplaceOptions {
@@ -32,6 +34,20 @@ export interface FindAndReplaceOptions {
32
34
  */
33
35
  wholeWord: boolean
34
36
 
37
+ /**
38
+ * Whether a textblock continues the textblock before it.
39
+ * Continued textblocks are searched as one text, so a match can start in one and end in the next.
40
+ * Textblocks with another block between them, like an image, are never joined.
41
+ * @param node The textblock to check.
42
+ * @returns `true` when the node continues the previous textblock.
43
+ * @default () => false
44
+ * @example
45
+ * FindAndReplace.configure({
46
+ * continuesNode: node => node.attrs.continued === true,
47
+ * })
48
+ */
49
+ continuesNode: (node: ProseMirrorNode) => boolean
50
+
35
51
  /**
36
52
  * Debounce delay in milliseconds applied to `setSearchTerm`.
37
53
  * Set to `0` to disable debouncing.
@@ -0,0 +1,99 @@
1
+ import { describe, expect, it } from 'vite-plus/test'
2
+
3
+ import {
4
+ continuesNode,
5
+ createContinuedDoc,
6
+ paragraph,
7
+ } from '../../tests/utils/createContinuedDoc.js'
8
+ import { addContinuedTextblocks } from './addContinuedTextblocks.js'
9
+ import type { TextblockRange } from './types.js'
10
+
11
+ const doc = createContinuedDoc([
12
+ paragraph('one'),
13
+ paragraph('two'),
14
+ paragraph('three', true),
15
+ paragraph('four', true),
16
+ paragraph('five'),
17
+ ])
18
+
19
+ function textblockAt(index: number): TextblockRange {
20
+ let pos = 0
21
+
22
+ for (let childIndex = 0; childIndex < index; childIndex += 1) {
23
+ pos += doc.child(childIndex).nodeSize
24
+ }
25
+
26
+ const node = doc.child(index)
27
+
28
+ return { node, pos, from: pos, to: pos + node.nodeSize }
29
+ }
30
+
31
+ function texts(textblocks: TextblockRange[]): string[] {
32
+ return textblocks.map(textblock => textblock.node.textContent)
33
+ }
34
+
35
+ describe('addContinuedTextblocks', () => {
36
+ it('keeps textblocks outside a chain as they are', () => {
37
+ expect(texts(addContinuedTextblocks(doc, [textblockAt(0)], continuesNode))).toEqual(['one'])
38
+ expect(texts(addContinuedTextblocks(doc, [textblockAt(4)], continuesNode))).toEqual(['five'])
39
+ })
40
+
41
+ it('adds the textblocks after the first textblock of a chain', () => {
42
+ expect(texts(addContinuedTextblocks(doc, [textblockAt(1)], continuesNode))).toEqual([
43
+ 'two',
44
+ 'three',
45
+ 'four',
46
+ ])
47
+ })
48
+
49
+ it('adds the textblocks before and after a continued textblock', () => {
50
+ expect(texts(addContinuedTextblocks(doc, [textblockAt(2)], continuesNode))).toEqual([
51
+ 'two',
52
+ 'three',
53
+ 'four',
54
+ ])
55
+ })
56
+
57
+ it('returns every textblock once in document order', () => {
58
+ const textblocks = [textblockAt(0), textblockAt(3), textblockAt(4)]
59
+
60
+ expect(texts(addContinuedTextblocks(doc, textblocks, continuesNode))).toEqual([
61
+ 'one',
62
+ 'two',
63
+ 'three',
64
+ 'four',
65
+ 'five',
66
+ ])
67
+ })
68
+
69
+ it('finds continued textblocks in other parents', () => {
70
+ const nested = createContinuedDoc([
71
+ { type: 'blockquote', content: [paragraph('one')] },
72
+ { type: 'blockquote', content: [paragraph('two', true)] },
73
+ ])
74
+ const continued = nested.child(1).child(0)
75
+ const [first] = addContinuedTextblocks(
76
+ nested,
77
+ [{ node: continued, pos: 8, from: 8, to: 8 + continued.nodeSize }],
78
+ continuesNode,
79
+ )
80
+
81
+ expect(first).toEqual({ node: nested.child(0).child(0), pos: 1, from: 1, to: 6 })
82
+ })
83
+
84
+ it('stops a chain at a block between two textblocks', () => {
85
+ const blocked = createContinuedDoc([
86
+ paragraph('one'),
87
+ { type: 'horizontalRule' },
88
+ paragraph('two', true),
89
+ ])
90
+ const continued = blocked.child(2)
91
+ const textblocks = addContinuedTextblocks(
92
+ blocked,
93
+ [{ node: continued, pos: 6, from: 6, to: 6 + continued.nodeSize }],
94
+ continuesNode,
95
+ )
96
+
97
+ expect(texts(textblocks)).toEqual(['two'])
98
+ })
99
+ })
@@ -0,0 +1,74 @@
1
+ import type { Node as PMNode } from '@tiptap/pm/model'
2
+
3
+ import { hasBlockBetween } from '../search/has-block-between.js'
4
+ import { findAdjacentTextblock } from './findAdjacentTextblock.js'
5
+ import type { TextblockRange } from './types.js'
6
+
7
+ function findJoinedTextblock(
8
+ doc: PMNode,
9
+ textblock: TextblockRange,
10
+ direction: 1 | -1,
11
+ continuesNode: (node: PMNode) => boolean,
12
+ ): TextblockRange | null {
13
+ const adjacent = findAdjacentTextblock(doc, textblock, direction)
14
+
15
+ if (!adjacent) {
16
+ return null
17
+ }
18
+
19
+ const [first, second] = direction === 1 ? [textblock, adjacent] : [adjacent, textblock]
20
+
21
+ if (!continuesNode(second.node) || hasBlockBetween(doc, first.to, second.from)) {
22
+ return null
23
+ }
24
+
25
+ return adjacent
26
+ }
27
+
28
+ function addChain(
29
+ doc: PMNode,
30
+ textblock: TextblockRange,
31
+ continuesNode: (node: PMNode) => boolean,
32
+ found: Map<number, TextblockRange>,
33
+ ): void {
34
+ let previous = findJoinedTextblock(doc, textblock, -1, continuesNode)
35
+
36
+ while (previous) {
37
+ found.set(previous.pos, previous)
38
+ previous = findJoinedTextblock(doc, previous, -1, continuesNode)
39
+ }
40
+
41
+ let next = findJoinedTextblock(doc, textblock, 1, continuesNode)
42
+
43
+ while (next) {
44
+ found.set(next.pos, next)
45
+ next = findJoinedTextblock(doc, next, 1, continuesNode)
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Adds the textblocks that are joined with the given ones by `continuesNode`.
51
+ * @param doc The document the textblocks are in.
52
+ * @param textblocks The textblocks in document order.
53
+ * @param continuesNode Whether a textblock continues the one before it.
54
+ * @returns The textblocks with their whole chains, in document order.
55
+ */
56
+ export function addContinuedTextblocks(
57
+ doc: PMNode,
58
+ textblocks: readonly TextblockRange[],
59
+ continuesNode: (node: PMNode) => boolean,
60
+ ): TextblockRange[] {
61
+ const found = new Map<number, TextblockRange>()
62
+
63
+ textblocks.forEach(textblock => {
64
+ // Its whole chain was already added
65
+ if (found.has(textblock.pos)) {
66
+ return
67
+ }
68
+
69
+ found.set(textblock.pos, textblock)
70
+ addChain(doc, textblock, continuesNode, found)
71
+ })
72
+
73
+ return [...found.values()].sort((first, second) => first.pos - second.pos)
74
+ }
@@ -1,4 +1,4 @@
1
- import type { Node } from '@tiptap/pm/model'
1
+ import type { Node as PMNode } from '@tiptap/pm/model'
2
2
 
3
3
  import type { FindAndReplaceOptions } from '../types.js'
4
4
  import type { FindAndReplacePluginState } from '../plugin/plugin-state.js'
@@ -6,7 +6,10 @@ import { searchDocument } from '../search/search.js'
6
6
 
7
7
  import { createDecorations } from './createDecorations.js'
8
8
 
9
- export function createState(doc: Node, options: FindAndReplaceOptions): FindAndReplacePluginState {
9
+ export function createState(
10
+ doc: PMNode,
11
+ options: FindAndReplaceOptions,
12
+ ): FindAndReplacePluginState {
10
13
  const results = searchDocument(doc, options.searchTerm, options)
11
14
  const currentIndex = results.length > 0 ? 0 : null
12
15
 
@@ -16,8 +19,10 @@ export function createState(doc: Node, options: FindAndReplaceOptions): FindAndR
16
19
  caseSensitive: options.caseSensitive,
17
20
  useRegex: options.useRegex,
18
21
  wholeWord: options.wholeWord,
22
+ continuesNode: options.continuesNode,
19
23
  results,
20
24
  currentIndex,
25
+ currentResultVisited: false,
21
26
  decorations: createDecorations(doc, results, currentIndex),
22
27
  }
23
28
  }
@@ -0,0 +1,14 @@
1
+ import type { Node as PMNode } from '@tiptap/pm/model'
2
+
3
+ import { findNearestTextblock } from './findNearestTextblock.js'
4
+ import type { TextblockRange } from './types.js'
5
+
6
+ export function findAdjacentTextblock(
7
+ doc: PMNode,
8
+ textblock: TextblockRange,
9
+ direction: 1 | -1,
10
+ ): TextblockRange | null {
11
+ const pos = direction === 1 ? textblock.to : textblock.from
12
+
13
+ return findNearestTextblock(doc, pos, direction)
14
+ }
@@ -0,0 +1,21 @@
1
+ import type { Node as PMNode } from '@tiptap/pm/model'
2
+ import { Selection } from '@tiptap/pm/state'
3
+
4
+ import type { TextblockRange } from './types.js'
5
+
6
+ export function findNearestTextblock(
7
+ doc: PMNode,
8
+ pos: number,
9
+ direction: 1 | -1,
10
+ ): TextblockRange | null {
11
+ const selection = Selection.findFrom(doc.resolve(pos), direction, true)
12
+
13
+ if (!selection) {
14
+ return null
15
+ }
16
+
17
+ const node = selection.$from.parent
18
+ const from = selection.$from.before()
19
+
20
+ return { node, pos: from, from, to: from + node.nodeSize }
21
+ }
@@ -0,0 +1,40 @@
1
+ import { Transform } from '@tiptap/pm/transform'
2
+ import { describe, expect, it } from 'vite-plus/test'
3
+
4
+ import { createContinuedDoc, paragraph } from '../../tests/utils/createContinuedDoc.js'
5
+ import { getChangedTextblocks } from './getChangedTextblocks.js'
6
+
7
+ describe('getChangedTextblocks', () => {
8
+ const doc = createContinuedDoc([paragraph('one'), paragraph('two'), paragraph('three')])
9
+
10
+ it('finds the textblocks around a text change', () => {
11
+ const transform = new Transform(doc).insert(7, doc.type.schema.text('x'))
12
+ const textblocks = getChangedTextblocks(transform.doc, transform)
13
+
14
+ expect(textblocks.map(textblock => textblock.node.textContent)).toEqual(['txwo'])
15
+ })
16
+
17
+ it('finds the textblocks in other parents around an inserted block', () => {
18
+ const nested = createContinuedDoc([
19
+ { type: 'blockquote', content: [paragraph('hel')] },
20
+ { type: 'blockquote', content: [paragraph('lo', true)] },
21
+ ])
22
+ const transform = new Transform(nested).insert(
23
+ 7,
24
+ nested.type.schema.nodes.horizontalRule.create(),
25
+ )
26
+ const textblocks = getChangedTextblocks(transform.doc, transform)
27
+
28
+ expect(textblocks.map(textblock => textblock.node.textContent)).toEqual(['hel', 'lo'])
29
+ })
30
+
31
+ it('finds a textblock whose attributes changed and the one before it', () => {
32
+ const transform = new Transform(doc).setNodeAttribute(5, 'continued', true)
33
+ const textblocks = getChangedTextblocks(transform.doc, transform)
34
+
35
+ expect(textblocks).toEqual([
36
+ { node: transform.doc.child(0), pos: 0, from: 0, to: 5 },
37
+ { node: transform.doc.child(1), pos: 5, from: 5, to: 10 },
38
+ ])
39
+ })
40
+ })
@@ -1,29 +1,77 @@
1
- import type { Node } from '@tiptap/pm/model'
2
- import type { Mapping } from '@tiptap/pm/transform'
1
+ import type { Node as PMNode } from '@tiptap/pm/model'
2
+ import type { Transform } from '@tiptap/pm/transform'
3
+ import { AttrStep } from '@tiptap/pm/transform'
3
4
 
5
+ import { findAdjacentTextblock } from './findAdjacentTextblock.js'
6
+ import { findNearestTextblock } from './findNearestTextblock.js'
4
7
  import type { TextblockRange } from './types.js'
5
8
 
6
- export function getChangedTextblocks(doc: Node, mapping: Mapping): TextblockRange[] {
9
+ function addTextblock(
10
+ textblocks: Map<number, TextblockRange>,
11
+ node: PMNode,
12
+ pos: number,
13
+ ): TextblockRange {
14
+ const textblock = { node, pos, from: pos, to: pos + node.nodeSize }
15
+
16
+ textblocks.set(pos, textblock)
17
+
18
+ return textblock
19
+ }
20
+
21
+ // Attribute steps change no ranges, but can join or split a textblock and the one before it
22
+ function addAttributeChanges(
23
+ doc: PMNode,
24
+ transform: Transform,
25
+ textblocks: Map<number, TextblockRange>,
26
+ ): void {
27
+ transform.steps.forEach((step, index) => {
28
+ if (!(step instanceof AttrStep)) {
29
+ return
30
+ }
31
+
32
+ const pos = transform.mapping.slice(index + 1).map(step.pos)
33
+ const node = doc.nodeAt(pos)
34
+
35
+ if (!node?.isTextblock) {
36
+ return
37
+ }
38
+
39
+ const textblock = addTextblock(textblocks, node, pos)
40
+ const previous = findAdjacentTextblock(doc, textblock, -1)
41
+
42
+ if (previous) {
43
+ textblocks.set(previous.pos, previous)
44
+ }
45
+ })
46
+ }
47
+
48
+ export function getChangedTextblocks(doc: PMNode, transform: Transform): TextblockRange[] {
49
+ const { mapping } = transform
7
50
  const textblocks = new Map<number, TextblockRange>()
8
51
 
9
52
  mapping.maps.forEach((stepMap, index) => {
10
53
  const remaining = mapping.slice(index + 1)
11
54
 
12
55
  stepMap.forEach((_oldStart, _oldEnd, newStart, newEnd) => {
13
- const from = Math.max(0, remaining.map(newStart, -1) - 1)
14
- const to = Math.min(doc.content.size, remaining.map(newEnd, 1) + 1)
56
+ // A change between two parents can join or split the textblocks inside them
57
+ const before = findNearestTextblock(doc, remaining.map(newStart, -1), -1)
58
+ const after = findNearestTextblock(doc, remaining.map(newEnd, 1), 1)
59
+ const from = before?.from ?? 0
60
+ const to = after?.to ?? doc.content.size
15
61
 
16
62
  doc.nodesBetween(from, to, (node, pos) => {
17
63
  if (!node.isTextblock) {
18
64
  return true
19
65
  }
20
66
 
21
- textblocks.set(pos, { node, pos, from: pos, to: pos + node.nodeSize })
67
+ addTextblock(textblocks, node, pos)
22
68
 
23
69
  return false
24
70
  })
25
71
  })
26
72
  })
27
73
 
74
+ addAttributeChanges(doc, transform, textblocks)
75
+
28
76
  return [...textblocks.values()].sort((first, second) => first.pos - second.pos)
29
77
  }