@tiptap/extensions 3.23.5 → 3.23.6

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.
@@ -1,11 +1,118 @@
1
1
  // src/placeholder/placeholder.ts
2
2
  import { Extension, isNodeEmpty } from "@tiptap/core";
3
3
  import { Plugin, PluginKey } from "@tiptap/pm/state";
4
- import { Decoration, DecorationSet } from "@tiptap/pm/view";
4
+ import { DecorationSet } from "@tiptap/pm/view";
5
+
6
+ // src/placeholder/utils/createPlaceholderDecoration.ts
7
+ import { Decoration } from "@tiptap/pm/view";
8
+ function createPlaceholderDecoration(options) {
9
+ const {
10
+ editor,
11
+ placeholder,
12
+ dataAttribute,
13
+ pos,
14
+ node,
15
+ isEmptyDoc,
16
+ hasAnchor,
17
+ classes: { emptyNode, emptyEditor }
18
+ } = options;
19
+ const classes = [emptyNode];
20
+ if (isEmptyDoc) {
21
+ classes.push(emptyEditor);
22
+ }
23
+ return Decoration.node(pos, pos + node.nodeSize, {
24
+ class: classes.join(" "),
25
+ [dataAttribute]: typeof placeholder === "function" ? placeholder({
26
+ editor,
27
+ node,
28
+ pos,
29
+ hasAnchor
30
+ }) : placeholder
31
+ });
32
+ }
33
+
34
+ // src/placeholder/utils/findScrollParent.ts
35
+ function isScrollable(el) {
36
+ const style = getComputedStyle(el);
37
+ const overflow = `${style.overflow} ${style.overflowY} ${style.overflowX}`;
38
+ return /auto|scroll|overlay/.test(overflow);
39
+ }
40
+ function findScrollParent(element) {
41
+ let el = element;
42
+ while (el) {
43
+ if (isScrollable(el)) {
44
+ return el;
45
+ }
46
+ const parent = el.parentElement;
47
+ if (!parent) {
48
+ const root = el.getRootNode();
49
+ if (root instanceof ShadowRoot) {
50
+ el = root.host;
51
+ continue;
52
+ }
53
+ return window;
54
+ }
55
+ el = parent;
56
+ }
57
+ return window;
58
+ }
59
+
60
+ // src/placeholder/utils/getViewportBoundaryPositions.ts
61
+ function getContainerRect(container) {
62
+ if (container === window) {
63
+ return { top: 0, bottom: window.innerHeight };
64
+ }
65
+ return container.getBoundingClientRect();
66
+ }
67
+ function getViewportBoundaryPositions({
68
+ doc,
69
+ view,
70
+ scrollContainer
71
+ }) {
72
+ const editorRect = view.dom.getBoundingClientRect();
73
+ const containerRect = scrollContainer ? getContainerRect(scrollContainer) : { top: 0, bottom: window.innerHeight };
74
+ const visibleTop = Math.max(editorRect.top, containerRect.top);
75
+ const visibleBottom = Math.min(editorRect.bottom, containerRect.bottom);
76
+ if (visibleTop >= visibleBottom) {
77
+ return { top: 0, bottom: doc.content.size };
78
+ }
79
+ const isRTL = getComputedStyle(view.dom).direction === "rtl";
80
+ const x = isRTL ? Math.max(editorRect.right - 2, editorRect.left + 2) : editorRect.left + 2;
81
+ const topPos = view.posAtCoords({ left: x, top: visibleTop + 2 });
82
+ const bottomPos = view.posAtCoords({ left: x, top: visibleBottom - 2 });
83
+ return {
84
+ top: topPos ? topPos.pos : 0,
85
+ bottom: bottomPos ? bottomPos.pos : doc.content.size
86
+ };
87
+ }
88
+
89
+ // src/placeholder/utils/throttle.ts
90
+ function throttle(fn, delay) {
91
+ let timer = null;
92
+ const call = ((...args) => {
93
+ if (timer) {
94
+ return;
95
+ }
96
+ fn(...args);
97
+ timer = setTimeout(() => {
98
+ timer = null;
99
+ }, delay);
100
+ });
101
+ const cancel = () => {
102
+ if (timer) {
103
+ clearTimeout(timer);
104
+ timer = null;
105
+ }
106
+ };
107
+ return { call, cancel };
108
+ }
109
+
110
+ // src/placeholder/placeholder.ts
5
111
  var DEFAULT_DATA_ATTRIBUTE = "placeholder";
6
112
  function preparePlaceholderAttribute(attr) {
7
113
  return attr.replace(/\s+/g, "-").replace(/[^a-zA-Z0-9-]/g, "").replace(/^[0-9-]+/, "").replace(/^-+/, "").toLowerCase();
8
114
  }
115
+ var PLUGIN_KEY = new PluginKey("tiptap__placeholder");
9
116
  var Placeholder = Extension.create({
10
117
  name: "placeholder",
11
118
  addOptions() {
@@ -23,40 +130,124 @@ var Placeholder = Extension.create({
23
130
  const dataAttribute = this.options.dataAttribute ? `data-${preparePlaceholderAttribute(this.options.dataAttribute)}` : `data-${DEFAULT_DATA_ATTRIBUTE}`;
24
131
  return [
25
132
  new Plugin({
26
- key: new PluginKey("placeholder"),
133
+ state: {
134
+ init() {
135
+ return {
136
+ // null means "no viewport info yet" — decoration callback falls
137
+ // back to full document scan until the scroll handler fires.
138
+ topPos: null,
139
+ bottomPos: null
140
+ };
141
+ },
142
+ apply(tr, prev) {
143
+ const meta = tr.getMeta(PLUGIN_KEY);
144
+ if (meta == null ? void 0 : meta.positions) {
145
+ return {
146
+ topPos: meta.positions.top,
147
+ bottomPos: meta.positions.bottom
148
+ };
149
+ }
150
+ if (!tr.docChanged) {
151
+ return prev;
152
+ }
153
+ return {
154
+ topPos: prev.topPos !== null ? tr.mapping.map(prev.topPos) : null,
155
+ bottomPos: prev.bottomPos !== null ? tr.mapping.map(prev.bottomPos) : null
156
+ };
157
+ }
158
+ },
159
+ key: PLUGIN_KEY,
160
+ view(view) {
161
+ const scrollContainer = findScrollParent(view.dom);
162
+ const computeAndDispatch = () => {
163
+ const positions = getViewportBoundaryPositions({
164
+ view,
165
+ doc: view.state.doc,
166
+ scrollContainer
167
+ });
168
+ const prev = PLUGIN_KEY.getState(view.state);
169
+ if (prev.topPos === positions.top && prev.bottomPos === positions.bottom) {
170
+ return;
171
+ }
172
+ const tr = view.state.tr.setMeta(PLUGIN_KEY, { positions }).setMeta("tiptap__viewportUpdate", true);
173
+ view.dispatch(tr);
174
+ };
175
+ const { call: throttledUpdate, cancel: cancelThrottle } = throttle(computeAndDispatch, 250);
176
+ const scrollParent = scrollContainer;
177
+ scrollParent.addEventListener("scroll", throttledUpdate, { passive: true });
178
+ computeAndDispatch();
179
+ return {
180
+ update(_, prevState) {
181
+ if (view.state.doc.content.size !== prevState.doc.content.size) {
182
+ computeAndDispatch();
183
+ }
184
+ },
185
+ destroy: () => {
186
+ cancelThrottle();
187
+ scrollParent.removeEventListener("scroll", throttledUpdate);
188
+ }
189
+ };
190
+ },
27
191
  props: {
28
192
  decorations: ({ doc, selection }) => {
193
+ var _a, _b;
29
194
  const active = this.editor.isEditable || !this.options.showOnlyWhenEditable;
30
- const { anchor } = selection;
31
- const decorations = [];
32
195
  if (!active) {
33
196
  return null;
34
197
  }
198
+ const { anchor } = selection;
199
+ const decorations = [];
35
200
  const isEmptyDoc = this.editor.isEmpty;
36
- doc.descendants((node, pos) => {
37
- const hasAnchor = anchor >= pos && anchor <= pos + node.nodeSize;
38
- const isEmpty = !node.isLeaf && isNodeEmpty(node);
39
- if (!node.type.isTextblock) {
40
- return this.options.includeChildren;
201
+ const useResolvedPath = this.options.showOnlyCurrent && !this.options.includeChildren;
202
+ if (useResolvedPath) {
203
+ const resolved = doc.resolve(anchor);
204
+ if (resolved.depth > 0) {
205
+ const node = resolved.node(1);
206
+ const nodeStart = resolved.before(1);
207
+ if (node.type.isTextblock && isNodeEmpty(node)) {
208
+ const hasAnchor = anchor >= nodeStart && anchor <= nodeStart + node.nodeSize;
209
+ const decoration = createPlaceholderDecoration({
210
+ node,
211
+ dataAttribute,
212
+ hasAnchor,
213
+ placeholder: this.options.placeholder,
214
+ classes: {
215
+ emptyEditor: this.options.emptyEditorClass,
216
+ emptyNode: this.options.emptyNodeClass
217
+ },
218
+ editor: this.editor,
219
+ isEmptyDoc,
220
+ pos: resolved.before(1)
221
+ });
222
+ decorations.push(decoration);
223
+ }
41
224
  }
42
- if ((hasAnchor || !this.options.showOnlyCurrent) && isEmpty) {
43
- const classes = [this.options.emptyNodeClass];
44
- if (isEmptyDoc) {
45
- classes.push(this.options.emptyEditorClass);
225
+ } else {
226
+ const pluginState = PLUGIN_KEY.getState(this.editor.state);
227
+ const from = (_a = pluginState.topPos) != null ? _a : 0;
228
+ const to = (_b = pluginState.bottomPos) != null ? _b : doc.content.size;
229
+ doc.nodesBetween(from, to, (node, pos) => {
230
+ const hasAnchor = anchor >= pos && anchor <= pos + node.nodeSize;
231
+ const isEmpty = !node.isLeaf && isNodeEmpty(node);
232
+ if (!node.type.isTextblock) {
233
+ return this.options.includeChildren;
46
234
  }
47
- const decoration = Decoration.node(pos, pos + node.nodeSize, {
48
- class: classes.join(" "),
49
- [dataAttribute]: typeof this.options.placeholder === "function" ? this.options.placeholder({
235
+ if ((hasAnchor || !this.options.showOnlyCurrent) && isEmpty) {
236
+ const decoration = createPlaceholderDecoration({
237
+ classes: { emptyEditor: this.options.emptyEditorClass, emptyNode: this.options.emptyNodeClass },
50
238
  editor: this.editor,
239
+ isEmptyDoc,
240
+ dataAttribute,
241
+ hasAnchor,
242
+ placeholder: this.options.placeholder,
51
243
  node,
52
- pos,
53
- hasAnchor
54
- }) : this.options.placeholder
55
- });
56
- decorations.push(decoration);
57
- }
58
- return this.options.includeChildren;
59
- });
244
+ pos
245
+ });
246
+ decorations.push(decoration);
247
+ }
248
+ return this.options.includeChildren;
249
+ });
250
+ }
60
251
  return DecorationSet.create(doc, decorations);
61
252
  }
62
253
  }
@@ -65,6 +256,7 @@ var Placeholder = Extension.create({
65
256
  }
66
257
  });
67
258
  export {
259
+ PLUGIN_KEY,
68
260
  Placeholder,
69
261
  preparePlaceholderAttribute
70
262
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/placeholder/placeholder.ts"],"sourcesContent":["import type { Editor } from '@tiptap/core'\nimport { Extension, isNodeEmpty } from '@tiptap/core'\nimport type { Node as ProsemirrorNode } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport { Decoration, DecorationSet } from '@tiptap/pm/view'\n\n/**\n * The default data attribute label\n */\nconst DEFAULT_DATA_ATTRIBUTE = 'placeholder'\n\n/**\n * Prepares the placeholder attribute by ensuring it is properly formatted.\n * @param attr - The placeholder attribute string.\n * @returns The prepared placeholder attribute string.\n */\nexport function preparePlaceholderAttribute(attr: string): string {\n return (\n attr\n // replace whitespace with dashes\n .replace(/\\s+/g, '-')\n // replace non-alphanumeric characters\n // or special chars like $, %, &, etc.\n // but not dashes\n .replace(/[^a-zA-Z0-9-]/g, '')\n // and replace any numeric character at the start\n .replace(/^[0-9-]+/, '')\n // and finally replace any stray, leading dashes\n .replace(/^-+/, '')\n .toLowerCase()\n )\n}\n\nexport interface PlaceholderOptions {\n /**\n * **The class name for the empty editor**\n * @default 'is-editor-empty'\n */\n emptyEditorClass: string\n\n /**\n * **The class name for empty nodes**\n * @default 'is-empty'\n */\n emptyNodeClass: string\n\n /**\n * **The data-attribute used for the placeholder label**\n * Will be prepended with `data-` and converted to kebab-case and cleaned of special characters.\n * @default 'placeholder'\n */\n dataAttribute: string\n\n /**\n * **The placeholder content**\n *\n * You can use a function to return a dynamic placeholder or a string.\n * @default 'Write something …'\n */\n placeholder:\n | ((PlaceholderProps: { editor: Editor; node: ProsemirrorNode; pos: number; hasAnchor: boolean }) => string)\n | string\n\n /**\n * **Checks if the placeholder should be only shown when the editor is editable.**\n *\n * If true, the placeholder will only be shown when the editor is editable.\n * If false, the placeholder will always be shown.\n * @default true\n */\n showOnlyWhenEditable: boolean\n\n /**\n * **Checks if the placeholder should be only shown when the current node is empty.**\n *\n * If true, the placeholder will only be shown when the current node is empty.\n * If false, the placeholder will be shown when any node is empty.\n * @default true\n */\n showOnlyCurrent: boolean\n\n /**\n * **Controls if the placeholder should be shown for all descendents.**\n *\n * If true, the placeholder will be shown for all descendents.\n * If false, the placeholder will only be shown for the current node.\n * @default false\n */\n includeChildren: boolean\n}\n\n/**\n * This extension allows you to add a placeholder to your editor.\n * A placeholder is a text that appears when the editor or a node is empty.\n * @see https://www.tiptap.dev/api/extensions/placeholder\n */\nexport const Placeholder = Extension.create<PlaceholderOptions>({\n name: 'placeholder',\n\n addOptions() {\n return {\n emptyEditorClass: 'is-editor-empty',\n emptyNodeClass: 'is-empty',\n dataAttribute: DEFAULT_DATA_ATTRIBUTE,\n placeholder: 'Write something …',\n showOnlyWhenEditable: true,\n showOnlyCurrent: true,\n includeChildren: false,\n }\n },\n\n addProseMirrorPlugins() {\n const dataAttribute = this.options.dataAttribute\n ? `data-${preparePlaceholderAttribute(this.options.dataAttribute)}`\n : `data-${DEFAULT_DATA_ATTRIBUTE}`\n\n return [\n new Plugin({\n key: new PluginKey('placeholder'),\n props: {\n decorations: ({ doc, selection }) => {\n const active = this.editor.isEditable || !this.options.showOnlyWhenEditable\n const { anchor } = selection\n const decorations: Decoration[] = []\n\n if (!active) {\n return null\n }\n\n const isEmptyDoc = this.editor.isEmpty\n\n doc.descendants((node, pos) => {\n const hasAnchor = anchor >= pos && anchor <= pos + node.nodeSize\n const isEmpty = !node.isLeaf && isNodeEmpty(node)\n\n if (!node.type.isTextblock) {\n return this.options.includeChildren\n }\n\n if ((hasAnchor || !this.options.showOnlyCurrent) && isEmpty) {\n const classes = [this.options.emptyNodeClass]\n\n if (isEmptyDoc) {\n classes.push(this.options.emptyEditorClass)\n }\n\n const decoration = Decoration.node(pos, pos + node.nodeSize, {\n class: classes.join(' '),\n [dataAttribute]:\n typeof this.options.placeholder === 'function'\n ? this.options.placeholder({\n editor: this.editor,\n node,\n pos,\n hasAnchor,\n })\n : this.options.placeholder,\n })\n\n decorations.push(decoration)\n }\n\n return this.options.includeChildren\n })\n\n return DecorationSet.create(doc, decorations)\n },\n },\n }),\n ]\n },\n})\n"],"mappings":";AACA,SAAS,WAAW,mBAAmB;AAEvC,SAAS,QAAQ,iBAAiB;AAClC,SAAS,YAAY,qBAAqB;AAK1C,IAAM,yBAAyB;AAOxB,SAAS,4BAA4B,MAAsB;AAChE,SACE,KAEG,QAAQ,QAAQ,GAAG,EAInB,QAAQ,kBAAkB,EAAE,EAE5B,QAAQ,YAAY,EAAE,EAEtB,QAAQ,OAAO,EAAE,EACjB,YAAY;AAEnB;AAiEO,IAAM,cAAc,UAAU,OAA2B;AAAA,EAC9D,MAAM;AAAA,EAEN,aAAa;AACX,WAAO;AAAA,MACL,kBAAkB;AAAA,MAClB,gBAAgB;AAAA,MAChB,eAAe;AAAA,MACf,aAAa;AAAA,MACb,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AAK,UAAU;AAAA,cAC7B;AAEA,qBAAO,KAAK,QAAQ;AAAA,YACtB,CAAC;AAED,mBAAO,cAAc,OAAO,KAAK,WAAW;AAAA,UAC9C;AAAA,QACF;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACF,CAAC;","names":[]}
1
+ {"version":3,"sources":["../../src/placeholder/placeholder.ts","../../src/placeholder/utils/createPlaceholderDecoration.ts","../../src/placeholder/utils/findScrollParent.ts","../../src/placeholder/utils/getViewportBoundaryPositions.ts","../../src/placeholder/utils/throttle.ts"],"sourcesContent":["import { Extension, isNodeEmpty } from '@tiptap/core'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport type { Decoration } from '@tiptap/pm/view'\nimport { DecorationSet } from '@tiptap/pm/view'\n\nimport type { PlaceholderOptions } from './types.js'\nimport { createPlaceholderDecoration } from './utils/createPlaceholderDecoration.js'\nimport { findScrollParent } from './utils/findScrollParent.js'\nimport { getViewportBoundaryPositions } from './utils/getViewportBoundaryPositions.js'\nimport { throttle } from './utils/throttle.js'\n\n/**\n * The default data attribute label\n */\nconst DEFAULT_DATA_ATTRIBUTE = 'placeholder'\n\n/**\n * Prepares the placeholder attribute by ensuring it is properly formatted.\n * @param attr - The placeholder attribute string.\n * @returns The prepared placeholder attribute string.\n */\nexport function preparePlaceholderAttribute(attr: string): string {\n return (\n attr\n // replace whitespace with dashes\n .replace(/\\s+/g, '-')\n // replace non-alphanumeric characters\n // or special chars like $, %, &, etc.\n // but not dashes\n .replace(/[^a-zA-Z0-9-]/g, '')\n // and replace any numeric character at the start\n .replace(/^[0-9-]+/, '')\n // and finally replace any stray, leading dashes\n .replace(/^-+/, '')\n .toLowerCase()\n )\n}\n\nexport const PLUGIN_KEY = new PluginKey('tiptap__placeholder')\n\n/**\n * This extension allows you to add a placeholder to your editor.\n * A placeholder is a text that appears when the editor or a node is empty.\n * @see https://www.tiptap.dev/api/extensions/placeholder\n */\nexport const Placeholder = Extension.create<PlaceholderOptions>({\n name: 'placeholder',\n\n addOptions() {\n return {\n emptyEditorClass: 'is-editor-empty',\n emptyNodeClass: 'is-empty',\n dataAttribute: DEFAULT_DATA_ATTRIBUTE,\n placeholder: 'Write something …',\n showOnlyWhenEditable: true,\n showOnlyCurrent: true,\n includeChildren: false,\n }\n },\n\n addProseMirrorPlugins() {\n const dataAttribute = this.options.dataAttribute\n ? `data-${preparePlaceholderAttribute(this.options.dataAttribute)}`\n : `data-${DEFAULT_DATA_ATTRIBUTE}`\n\n return [\n new Plugin({\n state: {\n init() {\n return {\n // null means \"no viewport info yet\" — decoration callback falls\n // back to full document scan until the scroll handler fires.\n topPos: null as number | null,\n bottomPos: null as number | null,\n }\n },\n apply(tr, prev) {\n const meta = tr.getMeta(PLUGIN_KEY) as { positions?: { top: number; bottom: number } } | undefined\n\n if (meta?.positions) {\n return {\n topPos: meta.positions.top,\n bottomPos: meta.positions.bottom,\n }\n }\n\n if (!tr.docChanged) {\n return prev\n }\n\n // Preserve last known viewport positions across transactions.\n // Without this, every keystroke resets back to a full document\n // scan, defeating the viewport optimisation.\n // Only map when we have actual positions — null means \"no viewport\n // info yet\" and should stay null to fall back to full doc scan.\n return {\n topPos: prev.topPos !== null ? tr.mapping.map(prev.topPos) : null,\n bottomPos: prev.bottomPos !== null ? tr.mapping.map(prev.bottomPos) : null,\n }\n },\n },\n key: PLUGIN_KEY,\n view(view) {\n const scrollContainer = findScrollParent(view.dom)\n\n const computeAndDispatch = () => {\n const positions = getViewportBoundaryPositions({\n view,\n doc: view.state.doc,\n scrollContainer,\n })\n\n const prev = PLUGIN_KEY.getState(view.state)\n if (prev.topPos === positions.top && prev.bottomPos === positions.bottom) {\n return\n }\n\n const tr = view.state.tr\n .setMeta(PLUGIN_KEY, { positions })\n // Flag this transaction so the update() method can detect\n // it and avoid re-entrant computation.\n .setMeta('tiptap__viewportUpdate', true)\n view.dispatch(tr)\n }\n\n const { call: throttledUpdate, cancel: cancelThrottle } = throttle(computeAndDispatch, 250)\n const scrollParent = scrollContainer\n\n scrollParent.addEventListener('scroll', throttledUpdate, { passive: true })\n\n // Fire once to populate initial viewport (bypass throttle)\n computeAndDispatch()\n\n return {\n update(_, prevState) {\n // Skip re-entry: the dispatch inside computeAndDispatch would\n // trigger this update again, but the doc didn't change so the\n // size guard catches that. The meta flag is an extra safeguard.\n if (view.state.doc.content.size !== prevState.doc.content.size) {\n computeAndDispatch()\n }\n },\n destroy: () => {\n cancelThrottle()\n scrollParent.removeEventListener('scroll', throttledUpdate)\n },\n }\n },\n props: {\n decorations: ({ doc, selection }) => {\n const active = this.editor.isEditable || !this.options.showOnlyWhenEditable\n\n if (!active) {\n return null\n }\n\n const { anchor } = selection\n const decorations: Decoration[] = []\n const isEmptyDoc = this.editor.isEmpty\n\n const useResolvedPath = this.options.showOnlyCurrent && !this.options.includeChildren\n\n if (useResolvedPath) {\n const resolved = doc.resolve(anchor)\n\n if (resolved.depth > 0) {\n const node = resolved.node(1)\n const nodeStart = resolved.before(1)\n\n if (node.type.isTextblock && isNodeEmpty(node)) {\n const hasAnchor = anchor >= nodeStart && anchor <= nodeStart + node.nodeSize\n const decoration = createPlaceholderDecoration({\n node,\n dataAttribute,\n hasAnchor,\n placeholder: this.options.placeholder,\n classes: {\n emptyEditor: this.options.emptyEditorClass,\n emptyNode: this.options.emptyNodeClass,\n },\n editor: this.editor,\n isEmptyDoc,\n pos: resolved.before(1),\n })\n\n decorations.push(decoration)\n }\n }\n } else {\n const pluginState = PLUGIN_KEY.getState(this.editor.state)\n const from = pluginState.topPos ?? 0\n const to = pluginState.bottomPos ?? doc.content.size\n\n doc.nodesBetween(from, to, (node, pos) => {\n const hasAnchor = anchor >= pos && anchor <= pos + node.nodeSize\n const isEmpty = !node.isLeaf && isNodeEmpty(node)\n\n if (!node.type.isTextblock) {\n return this.options.includeChildren\n }\n\n if ((hasAnchor || !this.options.showOnlyCurrent) && isEmpty) {\n const decoration = createPlaceholderDecoration({\n classes: { emptyEditor: this.options.emptyEditorClass, emptyNode: this.options.emptyNodeClass },\n editor: this.editor,\n isEmptyDoc,\n dataAttribute,\n hasAnchor,\n placeholder: this.options.placeholder,\n node,\n pos,\n })\n decorations.push(decoration)\n }\n\n return this.options.includeChildren\n })\n }\n\n return DecorationSet.create(doc, decorations)\n },\n },\n }),\n ]\n },\n})\n","import type { Editor } from '@tiptap/core'\nimport type { Node } from '@tiptap/pm/model'\nimport { Decoration } from '@tiptap/pm/view'\n\nimport type { PlaceholderOptions } from '../types.js'\n\n/**\n * Creates a ProseMirror node decoration that applies a placeholder\n * CSS class and data attribute to an empty node.\n * @param options.editor - The editor instance\n * @param options.pos - The position of the node in the document\n * @param options.node - The ProseMirror node\n * @param options.isEmptyDoc - Whether the entire document is empty\n * @param options.hasAnchor - Whether the selection anchor is within the node\n * @param options.dataAttribute - The data attribute name (e.g. `data-placeholder`)\n * @param options.classes - CSS classes for empty nodes and the empty editor\n * @param options.placeholder - The placeholder text or a function that returns it\n * @returns A ProseMirror node decoration with placeholder classes and data attribute\n */\nexport function createPlaceholderDecoration(options: {\n editor: Editor\n pos: number\n node: Node\n isEmptyDoc: boolean\n hasAnchor: boolean\n dataAttribute: string\n classes: {\n emptyEditor: PlaceholderOptions['emptyEditorClass']\n emptyNode: PlaceholderOptions['emptyNodeClass']\n }\n placeholder: PlaceholderOptions['placeholder']\n}) {\n const {\n editor,\n placeholder,\n dataAttribute,\n pos,\n node,\n isEmptyDoc,\n hasAnchor,\n classes: { emptyNode, emptyEditor },\n } = options\n const classes = [emptyNode]\n\n if (isEmptyDoc) {\n classes.push(emptyEditor)\n }\n\n return Decoration.node(pos, pos + node.nodeSize, {\n class: classes.join(' '),\n [dataAttribute]:\n typeof placeholder === 'function'\n ? placeholder({\n editor,\n node,\n pos,\n hasAnchor,\n })\n : placeholder,\n })\n}\n","/**\n * Checks if an element is scrollable by testing its overflow properties.\n * Elements with `overflow: hidden` or `overflow: clip` are intentionally\n * excluded — they clip content but don't emit scroll events.\n */\nfunction isScrollable(el: HTMLElement): boolean {\n const style = getComputedStyle(el)\n const overflow = `${style.overflow} ${style.overflowY} ${style.overflowX}`\n\n return /auto|scroll|overlay/.test(overflow)\n}\n\nexport function findScrollParent(element: HTMLElement): HTMLElement | Window {\n let el: HTMLElement | null = element\n\n while (el) {\n if (isScrollable(el)) {\n return el\n }\n\n // Check if we hit a Shadow DOM boundary. If so, jump to the shadow host\n // and continue traversing the light DOM.\n const parent = el.parentElement\n if (!parent) {\n const root = el.getRootNode()\n if (root instanceof ShadowRoot) {\n el = root.host as HTMLElement\n continue\n }\n\n return window\n }\n\n el = parent\n }\n\n return window\n}\n","import type { Node } from '@tiptap/pm/model'\nimport type { EditorView } from '@tiptap/pm/view'\n\nfunction getContainerRect(container: HTMLElement | Window): { top: number; bottom: number } {\n if (container === window) {\n return { top: 0, bottom: window.innerHeight }\n }\n\n return (container as HTMLElement).getBoundingClientRect()\n}\n\nexport function getViewportBoundaryPositions({\n doc,\n view,\n scrollContainer,\n}: {\n doc: Node\n view: EditorView\n scrollContainer?: HTMLElement | Window\n}) {\n const editorRect = view.dom.getBoundingClientRect()\n const containerRect = scrollContainer ? getContainerRect(scrollContainer) : { top: 0, bottom: window.innerHeight }\n\n const visibleTop = Math.max(editorRect.top, containerRect.top)\n const visibleBottom = Math.min(editorRect.bottom, containerRect.bottom)\n\n if (visibleTop >= visibleBottom) {\n // Editor is not visible — fall back to full document range\n return { top: 0, bottom: doc.content.size }\n }\n\n // Pick the x-coordinate based on text direction. In LTR the content\n // starts at the left edge; in RTL it starts at the right edge.\n // Clamp to ensure the coordinate stays inside the editor bounds.\n const isRTL = getComputedStyle(view.dom).direction === 'rtl'\n const x = isRTL ? Math.max(editorRect.right - 2, editorRect.left + 2) : editorRect.left + 2\n\n const topPos = view.posAtCoords({ left: x, top: visibleTop + 2 })\n const bottomPos = view.posAtCoords({ left: x, top: visibleBottom - 2 })\n\n return {\n top: topPos ? topPos.pos : 0,\n bottom: bottomPos ? bottomPos.pos : doc.content.size,\n }\n}\n","export function throttle<T extends (...args: any[]) => void>(fn: T, delay: number): { call: T; cancel: () => void } {\n let timer: ReturnType<typeof setTimeout> | null = null\n\n const call = ((...args: any[]) => {\n if (timer) {\n return\n }\n\n // Leading-edge: fire immediately, then prevent subsequent calls\n // until the timer fires and resets.\n fn(...args)\n timer = setTimeout(() => {\n timer = null\n }, delay)\n }) as T\n\n const cancel = () => {\n if (timer) {\n clearTimeout(timer)\n timer = null\n }\n }\n\n return { call, cancel }\n}\n"],"mappings":";AAAA,SAAS,WAAW,mBAAmB;AACvC,SAAS,QAAQ,iBAAiB;AAElC,SAAS,qBAAqB;;;ACD9B,SAAS,kBAAkB;AAiBpB,SAAS,4BAA4B,SAYzC;AACD,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAS,EAAE,WAAW,YAAY;AAAA,EACpC,IAAI;AACJ,QAAM,UAAU,CAAC,SAAS;AAE1B,MAAI,YAAY;AACd,YAAQ,KAAK,WAAW;AAAA,EAC1B;AAEA,SAAO,WAAW,KAAK,KAAK,MAAM,KAAK,UAAU;AAAA,IAC/C,OAAO,QAAQ,KAAK,GAAG;AAAA,IACvB,CAAC,aAAa,GACZ,OAAO,gBAAgB,aACnB,YAAY;AAAA,MACV;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC,IACD;AAAA,EACR,CAAC;AACH;;;ACvDA,SAAS,aAAa,IAA0B;AAC9C,QAAM,QAAQ,iBAAiB,EAAE;AACjC,QAAM,WAAW,GAAG,MAAM,QAAQ,IAAI,MAAM,SAAS,IAAI,MAAM,SAAS;AAExE,SAAO,sBAAsB,KAAK,QAAQ;AAC5C;AAEO,SAAS,iBAAiB,SAA4C;AAC3E,MAAI,KAAyB;AAE7B,SAAO,IAAI;AACT,QAAI,aAAa,EAAE,GAAG;AACpB,aAAO;AAAA,IACT;AAIA,UAAM,SAAS,GAAG;AAClB,QAAI,CAAC,QAAQ;AACX,Y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D,wBAAM,aAAa,4BAA4B;AAAA,oBAC7C,SAAS,EAAE,aAAa,KAAK,QAAQ,kBAAkB,WAAW,KAAK,QAAQ,eAAe;AAAA,oBAC9F,QAAQ,KAAK;AAAA,oBACb;AAAA,oBACA;AAAA,oBACA;AAAA,oBACA,aAAa,KAAK,QAAQ;AAAA,oBAC1B;AAAA,oBACA;AAAA,kBACF,CAAC;AACD,8BAAY,KAAK,UAAU;AAAA,gBAC7B;AAEA,uBAAO,KAAK,QAAQ;AAAA,cACtB,CAAC;AAAA,YACH;AAEA,mBAAO,cAAc,OAAO,KAAK,WAAW;AAAA,UAC9C;AAAA,QACF;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACF,CAAC;","names":[]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@tiptap/extensions",
3
3
  "description": "various extensions for tiptap",
4
- "version": "3.23.5",
4
+ "version": "3.23.6",
5
5
  "homepage": "https://tiptap.dev",
6
6
  "keywords": [
7
7
  "tiptap",
@@ -95,12 +95,12 @@
95
95
  "dist"
96
96
  ],
97
97
  "devDependencies": {
98
- "@tiptap/core": "^3.23.5",
99
- "@tiptap/pm": "^3.23.5"
98
+ "@tiptap/pm": "^3.23.6",
99
+ "@tiptap/core": "^3.23.6"
100
100
  },
101
101
  "peerDependencies": {
102
- "@tiptap/core": "3.23.5",
103
- "@tiptap/pm": "3.23.5"
102
+ "@tiptap/core": "3.23.6",
103
+ "@tiptap/pm": "3.23.6"
104
104
  },
105
105
  "repository": {
106
106
  "type": "git",
@@ -1 +1,2 @@
1
1
  export * from './placeholder.js'
2
+ export * from './types.js'
@@ -1,8 +1,13 @@
1
- import type { Editor } from '@tiptap/core'
2
1
  import { Extension, isNodeEmpty } from '@tiptap/core'
3
- import type { Node as ProsemirrorNode } from '@tiptap/pm/model'
4
2
  import { Plugin, PluginKey } from '@tiptap/pm/state'
5
- import { Decoration, DecorationSet } from '@tiptap/pm/view'
3
+ import type { Decoration } from '@tiptap/pm/view'
4
+ import { DecorationSet } from '@tiptap/pm/view'
5
+
6
+ import type { PlaceholderOptions } from './types.js'
7
+ import { createPlaceholderDecoration } from './utils/createPlaceholderDecoration.js'
8
+ import { findScrollParent } from './utils/findScrollParent.js'
9
+ import { getViewportBoundaryPositions } from './utils/getViewportBoundaryPositions.js'
10
+ import { throttle } from './utils/throttle.js'
6
11
 
7
12
  /**
8
13
  * The default data attribute label
@@ -31,63 +36,7 @@ export function preparePlaceholderAttribute(attr: string): string {
31
36
  )
32
37
  }
33
38
 
34
- export interface PlaceholderOptions {
35
- /**
36
- * **The class name for the empty editor**
37
- * @default 'is-editor-empty'
38
- */
39
- emptyEditorClass: string
40
-
41
- /**
42
- * **The class name for empty nodes**
43
- * @default 'is-empty'
44
- */
45
- emptyNodeClass: string
46
-
47
- /**
48
- * **The data-attribute used for the placeholder label**
49
- * Will be prepended with `data-` and converted to kebab-case and cleaned of special characters.
50
- * @default 'placeholder'
51
- */
52
- dataAttribute: string
53
-
54
- /**
55
- * **The placeholder content**
56
- *
57
- * You can use a function to return a dynamic placeholder or a string.
58
- * @default 'Write something …'
59
- */
60
- placeholder:
61
- | ((PlaceholderProps: { editor: Editor; node: ProsemirrorNode; pos: number; hasAnchor: boolean }) => string)
62
- | string
63
-
64
- /**
65
- * **Checks if the placeholder should be only shown when the editor is editable.**
66
- *
67
- * If true, the placeholder will only be shown when the editor is editable.
68
- * If false, the placeholder will always be shown.
69
- * @default true
70
- */
71
- showOnlyWhenEditable: boolean
72
-
73
- /**
74
- * **Checks if the placeholder should be only shown when the current node is empty.**
75
- *
76
- * If true, the placeholder will only be shown when the current node is empty.
77
- * If false, the placeholder will be shown when any node is empty.
78
- * @default true
79
- */
80
- showOnlyCurrent: boolean
81
-
82
- /**
83
- * **Controls if the placeholder should be shown for all descendents.**
84
- *
85
- * If true, the placeholder will be shown for all descendents.
86
- * If false, the placeholder will only be shown for the current node.
87
- * @default false
88
- */
89
- includeChildren: boolean
90
- }
39
+ export const PLUGIN_KEY = new PluginKey('tiptap__placeholder')
91
40
 
92
41
  /**
93
42
  * This extension allows you to add a placeholder to your editor.
@@ -116,52 +65,157 @@ export const Placeholder = Extension.create<PlaceholderOptions>({
116
65
 
117
66
  return [
118
67
  new Plugin({
119
- key: new PluginKey('placeholder'),
68
+ state: {
69
+ init() {
70
+ return {
71
+ // null means "no viewport info yet" — decoration callback falls
72
+ // back to full document scan until the scroll handler fires.
73
+ topPos: null as number | null,
74
+ bottomPos: null as number | null,
75
+ }
76
+ },
77
+ apply(tr, prev) {
78
+ const meta = tr.getMeta(PLUGIN_KEY) as { positions?: { top: number; bottom: number } } | undefined
79
+
80
+ if (meta?.positions) {
81
+ return {
82
+ topPos: meta.positions.top,
83
+ bottomPos: meta.positions.bottom,
84
+ }
85
+ }
86
+
87
+ if (!tr.docChanged) {
88
+ return prev
89
+ }
90
+
91
+ // Preserve last known viewport positions across transactions.
92
+ // Without this, every keystroke resets back to a full document
93
+ // scan, defeating the viewport optimisation.
94
+ // Only map when we have actual positions — null means "no viewport
95
+ // info yet" and should stay null to fall back to full doc scan.
96
+ return {
97
+ topPos: prev.topPos !== null ? tr.mapping.map(prev.topPos) : null,
98
+ bottomPos: prev.bottomPos !== null ? tr.mapping.map(prev.bottomPos) : null,
99
+ }
100
+ },
101
+ },
102
+ key: PLUGIN_KEY,
103
+ view(view) {
104
+ const scrollContainer = findScrollParent(view.dom)
105
+
106
+ const computeAndDispatch = () => {
107
+ const positions = getViewportBoundaryPositions({
108
+ view,
109
+ doc: view.state.doc,
110
+ scrollContainer,
111
+ })
112
+
113
+ const prev = PLUGIN_KEY.getState(view.state)
114
+ if (prev.topPos === positions.top && prev.bottomPos === positions.bottom) {
115
+ return
116
+ }
117
+
118
+ const tr = view.state.tr
119
+ .setMeta(PLUGIN_KEY, { positions })
120
+ // Flag this transaction so the update() method can detect
121
+ // it and avoid re-entrant computation.
122
+ .setMeta('tiptap__viewportUpdate', true)
123
+ view.dispatch(tr)
124
+ }
125
+
126
+ const { call: throttledUpdate, cancel: cancelThrottle } = throttle(computeAndDispatch, 250)
127
+ const scrollParent = scrollContainer
128
+
129
+ scrollParent.addEventListener('scroll', throttledUpdate, { passive: true })
130
+
131
+ // Fire once to populate initial viewport (bypass throttle)
132
+ computeAndDispatch()
133
+
134
+ return {
135
+ update(_, prevState) {
136
+ // Skip re-entry: the dispatch inside computeAndDispatch would
137
+ // trigger this update again, but the doc didn't change so the
138
+ // size guard catches that. The meta flag is an extra safeguard.
139
+ if (view.state.doc.content.size !== prevState.doc.content.size) {
140
+ computeAndDispatch()
141
+ }
142
+ },
143
+ destroy: () => {
144
+ cancelThrottle()
145
+ scrollParent.removeEventListener('scroll', throttledUpdate)
146
+ },
147
+ }
148
+ },
120
149
  props: {
121
150
  decorations: ({ doc, selection }) => {
122
151
  const active = this.editor.isEditable || !this.options.showOnlyWhenEditable
123
- const { anchor } = selection
124
- const decorations: Decoration[] = []
125
152
 
126
153
  if (!active) {
127
154
  return null
128
155
  }
129
156
 
157
+ const { anchor } = selection
158
+ const decorations: Decoration[] = []
130
159
  const isEmptyDoc = this.editor.isEmpty
131
160
 
132
- doc.descendants((node, pos) => {
133
- const hasAnchor = anchor >= pos && anchor <= pos + node.nodeSize
134
- const isEmpty = !node.isLeaf && isNodeEmpty(node)
135
-
136
- if (!node.type.isTextblock) {
137
- return this.options.includeChildren
161
+ const useResolvedPath = this.options.showOnlyCurrent && !this.options.includeChildren
162
+
163
+ if (useResolvedPath) {
164
+ const resolved = doc.resolve(anchor)
165
+
166
+ if (resolved.depth > 0) {
167
+ const node = resolved.node(1)
168
+ const nodeStart = resolved.before(1)
169
+
170
+ if (node.type.isTextblock && isNodeEmpty(node)) {
171
+ const hasAnchor = anchor >= nodeStart && anchor <= nodeStart + node.nodeSize
172
+ const decoration = createPlaceholderDecoration({
173
+ node,
174
+ dataAttribute,
175
+ hasAnchor,
176
+ placeholder: this.options.placeholder,
177
+ classes: {
178
+ emptyEditor: this.options.emptyEditorClass,
179
+ emptyNode: this.options.emptyNodeClass,
180
+ },
181
+ editor: this.editor,
182
+ isEmptyDoc,
183
+ pos: resolved.before(1),
184
+ })
185
+
186
+ decorations.push(decoration)
187
+ }
138
188
  }
189
+ } else {
190
+ const pluginState = PLUGIN_KEY.getState(this.editor.state)
191
+ const from = pluginState.topPos ?? 0
192
+ const to = pluginState.bottomPos ?? doc.content.size
139
193
 
140
- if ((hasAnchor || !this.options.showOnlyCurrent) && isEmpty) {
141
- const classes = [this.options.emptyNodeClass]
194
+ doc.nodesBetween(from, to, (node, pos) => {
195
+ const hasAnchor = anchor >= pos && anchor <= pos + node.nodeSize
196
+ const isEmpty = !node.isLeaf && isNodeEmpty(node)
142
197
 
143
- if (isEmptyDoc) {
144
- classes.push(this.options.emptyEditorClass)
198
+ if (!node.type.isTextblock) {
199
+ return this.options.includeChildren
145
200
  }
146
201
 
147
- const decoration = Decoration.node(pos, pos + node.nodeSize, {
148
- class: classes.join(' '),
149
- [dataAttribute]:
150
- typeof this.options.placeholder === 'function'
151
- ? this.options.placeholder({
152
- editor: this.editor,
153
- node,
154
- pos,
155
- hasAnchor,
156
- })
157
- : this.options.placeholder,
158
- })
159
-
160
- decorations.push(decoration)
161
- }
202
+ if ((hasAnchor || !this.options.showOnlyCurrent) && isEmpty) {
203
+ const decoration = createPlaceholderDecoration({
204
+ classes: { emptyEditor: this.options.emptyEditorClass, emptyNode: this.options.emptyNodeClass },
205
+ editor: this.editor,
206
+ isEmptyDoc,
207
+ dataAttribute,
208
+ hasAnchor,
209
+ placeholder: this.options.placeholder,
210
+ node,
211
+ pos,
212
+ })
213
+ decorations.push(decoration)
214
+ }
162
215
 
163
- return this.options.includeChildren
164
- })
216
+ return this.options.includeChildren
217
+ })
218
+ }
165
219
 
166
220
  return DecorationSet.create(doc, decorations)
167
221
  },