@tiptap/extensions 3.27.2 → 3.27.4

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.
@@ -0,0 +1,93 @@
1
+ import type { Node } from '@tiptap/pm/model'
2
+
3
+ /**
4
+ * Resolves a document position to the `[from, to)` range of its containing
5
+ * top-level block node in absolute document positions.
6
+ */
7
+ export function resolveTopLevelRange(doc: Node, pos: number): { from: number; to: number } {
8
+ const resolved = doc.resolve(pos)
9
+
10
+ if (resolved.depth === 0) {
11
+ const node = resolved.nodeAfter ?? resolved.nodeBefore
12
+
13
+ if (!node) {
14
+ return { from: pos, to: pos }
15
+ }
16
+
17
+ const nodePos = resolved.nodeAfter ? pos : pos - node.nodeSize
18
+
19
+ return { from: nodePos, to: nodePos + node.nodeSize }
20
+ }
21
+
22
+ const topLevelPos = resolved.before(1)
23
+ const node = resolved.node(1)
24
+
25
+ return { from: topLevelPos, to: topLevelPos + node.nodeSize }
26
+ }
27
+
28
+ /**
29
+ * Converts an absolute document range to content-relative positions used by
30
+ * `Node#nodesBetween` and `Node#forEach` offsets.
31
+ */
32
+ export function toContentRelativeRange(
33
+ doc: Node,
34
+ range: { from: number; to: number },
35
+ ): { from: number; to: number } {
36
+ return {
37
+ from: Math.max(0, range.from - 1),
38
+ to: Math.min(doc.content.size, range.to - 1),
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Returns the top-level block ranges that intersect a document change range.
44
+ * Input `from`/`to` are absolute positions (e.g. from `getChangedRanges`).
45
+ * Returned ranges are content-relative, matching `Node#forEach` offsets.
46
+ */
47
+ export function getTopLevelBlocksInRange(
48
+ doc: Node,
49
+ from: number,
50
+ to: number,
51
+ ): Array<{ from: number; to: number }> {
52
+ const ranges: Array<{ from: number; to: number }> = []
53
+
54
+ doc.forEach((node, offset) => {
55
+ const nodeStart = offset
56
+ const nodeEnd = nodeStart + node.nodeSize
57
+ const absNodeStart = nodeStart + 1
58
+ const absNodeEnd = nodeEnd + 1
59
+
60
+ if (absNodeStart < to && absNodeEnd > from) {
61
+ ranges.push({ from: nodeStart, to: nodeEnd })
62
+ }
63
+ })
64
+
65
+ return ranges
66
+ }
67
+
68
+ /**
69
+ * Sorts ranges by start position and merges overlapping or adjacent ranges.
70
+ */
71
+ export function mergeRanges(
72
+ ranges: Array<{ from: number; to: number }>,
73
+ ): Array<{ from: number; to: number }> {
74
+ if (ranges.length === 0) {
75
+ return []
76
+ }
77
+
78
+ const sorted = [...ranges].sort((a, b) => a.from - b.from)
79
+ const merged: Array<{ from: number; to: number }> = [{ ...sorted[0] }]
80
+
81
+ for (let i = 1; i < sorted.length; i += 1) {
82
+ const last = merged[merged.length - 1]
83
+ const current = sorted[i]
84
+
85
+ if (current.from <= last.to) {
86
+ last.to = Math.max(last.to, current.to)
87
+ } else {
88
+ merged.push({ ...current })
89
+ }
90
+ }
91
+
92
+ return merged
93
+ }
@@ -1,15 +1,8 @@
1
- import { createStyleTag, Extension, isNodeSelection } from '@tiptap/core'
2
- import { Plugin, PluginKey } from '@tiptap/pm/state'
1
+ import { Extension, isNodeSelection, type Editor } from '@tiptap/core'
2
+ import { Plugin, PluginKey, type EditorState } from '@tiptap/pm/state'
3
+ import type { EditorView } from '@tiptap/pm/view'
3
4
  import { Decoration, DecorationSet } from '@tiptap/pm/view'
4
5
 
5
- const selectionStyle = `.ProseMirror:not(.ProseMirror-focused) *::selection {
6
- background: transparent;
7
- }
8
-
9
- .ProseMirror:not(.ProseMirror-focused) *::-moz-selection {
10
- background: transparent;
11
- }`
12
-
13
6
  export type SelectionOptions = {
14
7
  /**
15
8
  * The class name that should be added to the selected text.
@@ -20,7 +13,37 @@ export type SelectionOptions = {
20
13
  }
21
14
 
22
15
  /**
23
- * This extension allows you to add a class to the selected text.
16
+ * Whether the native browser selection should be cleared on blur and restored on focus.
17
+ * Only applies to non-empty text selections in an editable editor.
18
+ */
19
+ function shouldSyncDomSelection(state: EditorState, editor: Editor): boolean {
20
+ return !state.selection.empty && !isNodeSelection(state.selection) && editor.isEditable
21
+ }
22
+
23
+ /**
24
+ * Whether the selection decoration should be rendered to keep the selection
25
+ * visible while the editor is blurred (and not dragging).
26
+ */
27
+ function shouldPreserveSelection(state: EditorState, editor: Editor): boolean {
28
+ return shouldSyncDomSelection(state, editor) && !editor.isFocused && !editor.view.dragging
29
+ }
30
+
31
+ function clearDomSelection() {
32
+ window.getSelection()?.removeAllRanges()
33
+ }
34
+
35
+ /**
36
+ * Sync the native selection from the editor state.
37
+ * @see https://prosemirror.net/docs/ref/#view.EditorView.focus
38
+ */
39
+ function restoreDomSelection(view: EditorView) {
40
+ view.focus()
41
+ }
42
+
43
+ /**
44
+ * This extension allows you to add a class to the selected text when the editor is blurred.
45
+ * It clears the native browser selection on blur (so `::selection` styles do not overlap the
46
+ * decoration) and restores it when the editor is focused again.
24
47
  * @see https://www.tiptap.dev/api/extensions/selection
25
48
  */
26
49
  export const Selection = Extension.create<SelectionOptions>({
@@ -35,22 +58,12 @@ export const Selection = Extension.create<SelectionOptions>({
35
58
  addProseMirrorPlugins() {
36
59
  const { editor, options } = this
37
60
 
38
- if (editor.options.injectCSS && typeof document !== 'undefined') {
39
- createStyleTag(selectionStyle, editor.options.injectNonce, 'selection')
40
- }
41
-
42
61
  return [
43
62
  new Plugin({
44
63
  key: new PluginKey('selection'),
45
64
  props: {
46
65
  decorations(state) {
47
- if (
48
- state.selection.empty ||
49
- editor.isFocused ||
50
- !editor.isEditable ||
51
- isNodeSelection(state.selection) ||
52
- editor.view.dragging
53
- ) {
66
+ if (!shouldPreserveSelection(state, editor)) {
54
67
  return null
55
68
  }
56
69
 
@@ -60,6 +73,30 @@ export const Selection = Extension.create<SelectionOptions>({
60
73
  }),
61
74
  ])
62
75
  },
76
+ handleDOMEvents: {
77
+ blur(view) {
78
+ if (!shouldSyncDomSelection(view.state, editor)) {
79
+ return false
80
+ }
81
+
82
+ clearDomSelection()
83
+
84
+ return false
85
+ },
86
+ focus(view) {
87
+ if (!shouldSyncDomSelection(view.state, editor)) {
88
+ return false
89
+ }
90
+
91
+ requestAnimationFrame(() => {
92
+ if (!editor.isDestroyed && view.hasFocus()) {
93
+ restoreDomSelection(view)
94
+ }
95
+ })
96
+
97
+ return false
98
+ },
99
+ },
63
100
  },
64
101
  }),
65
102
  ]
@@ -1,38 +0,0 @@
1
- /**
2
- * Checks if an element is scrollable by testing its overflow properties.
3
- * Elements with `overflow: hidden` or `overflow: clip` are intentionally
4
- * excluded — they clip content but don't emit scroll events.
5
- */
6
- function isScrollable(el: HTMLElement): boolean {
7
- const style = getComputedStyle(el)
8
- const overflow = `${style.overflow} ${style.overflowY} ${style.overflowX}`
9
-
10
- return /auto|scroll|overlay/.test(overflow)
11
- }
12
-
13
- export function findScrollParent(element: HTMLElement): HTMLElement | Window {
14
- let el: HTMLElement | null = element
15
-
16
- while (el) {
17
- if (isScrollable(el)) {
18
- return el
19
- }
20
-
21
- // Check if we hit a Shadow DOM boundary. If so, jump to the shadow host
22
- // and continue traversing the light DOM.
23
- const parent = el.parentElement
24
- if (!parent) {
25
- const root = el.getRootNode()
26
- if (root instanceof ShadowRoot) {
27
- el = root.host as HTMLElement
28
- continue
29
- }
30
-
31
- return window
32
- }
33
-
34
- el = parent
35
- }
36
-
37
- return window
38
- }
@@ -1,74 +0,0 @@
1
- import type { EditorView } from '@tiptap/pm/view'
2
-
3
- import { VIEWPORT_OVERSCAN_PX } from '../constants.js'
4
-
5
- function getContainerRect(container: HTMLElement | Window): { top: number; bottom: number } {
6
- if (container === window) {
7
- return { top: 0, bottom: window.innerHeight }
8
- }
9
-
10
- return (container as HTMLElement).getBoundingClientRect()
11
- }
12
-
13
- /**
14
- * Computes the document positions bounding the currently visible viewport.
15
- */
16
- export function getViewportBoundaryPositions({
17
- view,
18
- scrollContainer,
19
- }: {
20
- view: EditorView
21
- scrollContainer?: HTMLElement | Window
22
- }): { top: number; bottom: number } | null {
23
- const editorRect = view.dom.getBoundingClientRect()
24
-
25
- // No usable layout — can't probe a coordinate inside the box.
26
- if (editorRect.width <= 0 || editorRect.height <= 0) {
27
- return null
28
- }
29
-
30
- const containerRect = scrollContainer
31
- ? getContainerRect(scrollContainer)
32
- : { top: 0, bottom: window.innerHeight }
33
-
34
- const visibleTop = Math.max(editorRect.top, containerRect.top) - VIEWPORT_OVERSCAN_PX
35
- const visibleBottom = Math.min(editorRect.bottom, containerRect.bottom) + VIEWPORT_OVERSCAN_PX
36
-
37
- if (visibleTop >= visibleBottom) {
38
- // Editor is scrolled fully out of its container so not measurable.
39
- return null
40
- }
41
-
42
- // Probe the start edge (left in LTR, right in RTL), clamped inside the box
43
- // so a too-narrow editor doesn't push the probe out.
44
- const minX = editorRect.left + 1
45
- const maxX = editorRect.right - 1
46
-
47
- if (minX > maxX) {
48
- return null
49
- }
50
-
51
- const isRTL = getComputedStyle(view.dom).direction === 'rtl'
52
- const targetX = isRTL ? editorRect.right - 2 : editorRect.left + 2
53
- const x = Math.min(Math.max(targetX, minX), maxX)
54
-
55
- // Clamp the probe y inside the box so the overscan doesn't push it past the
56
- // editor's own content (which would make `posAtCoords` null for no reason).
57
- const probeTop = Math.max(visibleTop + 2, editorRect.top + 1)
58
- const probeBottom = Math.min(visibleBottom - 2, editorRect.bottom - 1)
59
-
60
- if (probeTop > probeBottom) {
61
- return null
62
- }
63
-
64
- const topPos = view.posAtCoords({ left: x, top: probeTop })
65
- const bottomPos = view.posAtCoords({ left: x, top: probeBottom })
66
-
67
- // Null usually means occlusion (but can be benign). Either way it's
68
- // unreliable, so freeze the previous window instead of decorating the whole doc.
69
- if (!topPos || !bottomPos) {
70
- return null
71
- }
72
-
73
- return { top: topPos.pos, bottom: bottomPos.pos }
74
- }
@@ -1,28 +0,0 @@
1
- export function throttle<T extends (...args: any[]) => void>(
2
- fn: T,
3
- delay: number,
4
- ): { call: T; cancel: () => void } {
5
- let timer: ReturnType<typeof setTimeout> | null = null
6
-
7
- const call = ((...args: any[]) => {
8
- if (timer) {
9
- return
10
- }
11
-
12
- // Leading-edge: fire immediately, then prevent subsequent calls
13
- // until the timer fires and resets.
14
- fn(...args)
15
- timer = setTimeout(() => {
16
- timer = null
17
- }, delay)
18
- }) as T
19
-
20
- const cancel = () => {
21
- if (timer) {
22
- clearTimeout(timer)
23
- timer = null
24
- }
25
- }
26
-
27
- return { call, cancel }
28
- }
@@ -1,137 +0,0 @@
1
- import type { EditorState, PluginView, StateField, Transaction } from '@tiptap/pm/state'
2
- import type { EditorView } from '@tiptap/pm/view'
3
-
4
- import { PLUGIN_KEY } from '../constants.js'
5
- import type { ViewportState } from '../types.js'
6
- import { findScrollParent } from './findScrollParent.js'
7
- import { getViewportBoundaryPositions } from './getViewportBoundaryPositions.js'
8
-
9
- /**
10
- * The plugin `state` config that tracks the visible viewport boundaries so the
11
- * decoration callback only scans the nodes currently on screen.
12
- */
13
- export const viewportPluginState: StateField<ViewportState> = {
14
- /**
15
- * Initialises the viewport state with no known positions.
16
- * @returns The initial viewport state.
17
- */
18
- init(): ViewportState {
19
- return { topPos: null, bottomPos: null }
20
- },
21
-
22
- /**
23
- * Updates the viewport state from incoming transactions.
24
- * @param tr - The transaction being applied.
25
- * @param prev - The previous viewport state.
26
- * @returns The next viewport state.
27
- */
28
- apply(tr: Transaction, prev: ViewportState): ViewportState {
29
- const meta = tr.getMeta(PLUGIN_KEY) as
30
- | { positions?: { top: number; bottom: number } }
31
- | undefined
32
-
33
- if (meta?.positions) {
34
- return { topPos: meta.positions.top, bottomPos: meta.positions.bottom }
35
- }
36
-
37
- if (!tr.docChanged) {
38
- return prev
39
- }
40
-
41
- // Preserve last known viewport positions across transactions.
42
- // Without this, every keystroke resets back to a full document
43
- // scan, defeating the viewport optimisation.
44
- // Only map when we have actual positions — null means "no viewport
45
- // info yet" and should stay null to fall back to full doc scan.
46
- return {
47
- topPos: prev.topPos !== null ? tr.mapping.map(prev.topPos) : null,
48
- bottomPos: prev.bottomPos !== null ? tr.mapping.map(prev.bottomPos) : null,
49
- }
50
- },
51
- }
52
-
53
- /**
54
- * Creates the plugin `view` that recomputes the visible viewport on scroll and
55
- * document size changes, dispatching the result into the plugin state.
56
- * @param view - The editor view the plugin is attached to.
57
- * @returns A plugin view with `update` and `destroy` handlers.
58
- */
59
- export function createViewportPluginView(view: EditorView): PluginView {
60
- const scrollContainer = findScrollParent(view.dom)
61
-
62
- const computeAndDispatch = () => {
63
- const positions = getViewportBoundaryPositions({
64
- view,
65
- scrollContainer,
66
- })
67
-
68
- // Not measurable, keep the last good window frozen
69
- if (positions === null) {
70
- return
71
- }
72
-
73
- const prev = PLUGIN_KEY.getState(view.state)
74
- if (prev?.topPos === positions.top && prev?.bottomPos === positions.bottom) {
75
- return
76
- }
77
-
78
- const tr = view.state.tr.setMeta(PLUGIN_KEY, { positions })
79
- view.dispatch(tr)
80
- }
81
-
82
- // rAF-based scheduler with interval guard (150ms → ~6–7 Hz) used by
83
- // scroll events and update(). The overscan margin hides the extra
84
- // latency. When the guard blocks, the callback reschedules itself so
85
- // the trailing position is always captured.
86
- let frame: number | null = null
87
- let lastCompute = 0
88
- const MIN_SCROLL_INTERVAL = 150
89
-
90
- const scheduleFrame = () => {
91
- if (frame !== null) return
92
- frame = requestAnimationFrame(() => {
93
- frame = null
94
- const now = performance.now()
95
- if (now - lastCompute >= MIN_SCROLL_INTERVAL) {
96
- lastCompute = now
97
- computeAndDispatch()
98
- } else {
99
- scheduleFrame()
100
- }
101
- })
102
- }
103
-
104
- scrollContainer.addEventListener('scroll', scheduleFrame, { passive: true })
105
-
106
- // Recover a frozen window once the editor becomes usable again (e.g. a modal
107
- // closes): re-measure on size/visibility changes and when focus returns.
108
- const resizeObserver =
109
- typeof ResizeObserver !== 'undefined' ? new ResizeObserver(scheduleFrame) : null
110
- resizeObserver?.observe(view.dom)
111
-
112
- const intersectionObserver =
113
- typeof IntersectionObserver !== 'undefined' ? new IntersectionObserver(scheduleFrame) : null
114
- intersectionObserver?.observe(view.dom)
115
-
116
- view.dom.addEventListener('focus', scheduleFrame)
117
-
118
- // Fire once to populate initial viewport
119
- computeAndDispatch()
120
-
121
- return {
122
- update(_view: EditorView, prevState: EditorState) {
123
- if (view.state.doc.content.size !== prevState.doc.content.size) {
124
- scheduleFrame()
125
- }
126
- },
127
- destroy: () => {
128
- if (frame !== null) {
129
- cancelAnimationFrame(frame)
130
- }
131
- scrollContainer.removeEventListener('scroll', scheduleFrame)
132
- resizeObserver?.disconnect()
133
- intersectionObserver?.disconnect()
134
- view.dom.removeEventListener('focus', scheduleFrame)
135
- },
136
- }
137
- }