@knapsack/tiptap-utils 4.100.0 → 4.100.1--canary.7985.eb739a3.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.
@@ -1,386 +0,0 @@
1
- import type { JSONContent } from '@tiptap/core';
2
-
3
- /**
4
- * A doc tiptap can always render, used only when the root node's own `type`
5
- * is unrecognized and nothing was preserved from it (mode `'salvage'` found
6
- * no text) - there's no parent to drop it from, so this is the one case
7
- * where some emptying can be unavoidable. Every other unrecognized
8
- * node/mark is handled in place, keeping all valid siblings intact.
9
- *
10
- * Handed out by reference to every caller hitting this fallback - frozen
11
- * for the same reason `findUnrecognizedTypesCached` freezes its cached
12
- * arrays (see doctor's detect-unrecognized-tiptap-content.ts): an
13
- * accidental downstream mutation must fail loudly instead of silently
14
- * corrupting this shared instance for every other block that reaches it.
15
- */
16
- const EMPTY_DOC: JSONContent = Object.freeze({
17
- type: 'doc',
18
- content: [{ type: 'paragraph' }],
19
- });
20
-
21
- /**
22
- * Node types whose `content` is inline (text runs), not block content - an
23
- * unrecognized child here is replaced with an inline node. Everywhere else
24
- * (doc, blockquote, list items, table cells, ...) a replacement needs its
25
- * own block-level node, since an inline node isn't valid block content.
26
- */
27
- const INLINE_CONTAINER_TYPES: ReadonlySet<string> = new Set([
28
- 'paragraph',
29
- 'heading',
30
- ]);
31
-
32
- const PLACEHOLDER_TYPES: ReadonlySet<string> = new Set([
33
- 'unrecognizedContentPlaceholder',
34
- 'unrecognizedContentPlaceholderBlock',
35
- ]);
36
-
37
- /** See `UnrecognizedContentPlaceholderRoot`'s doc comment for why this is kept distinct from `PLACEHOLDER_TYPES`. */
38
- const ROOT_PLACEHOLDER_TYPE = 'unrecognizedContentPlaceholderRoot';
39
-
40
- /**
41
- * A placeholder's `original` attr is plain HTML-attribute text, editable by
42
- * anyone who can paste HTML into the editor (tiptap's `parseHTML` accepts
43
- * it from clipboard content, not just content this module itself wrote) -
44
- * treat it as untrusted input, not a value only this module ever produces.
45
- * A generous cap on genuine concealed content, but bounds how much an
46
- * unrelated forged attribute can bloat storage.
47
- */
48
- const MAX_ORIGINAL_JSON_LENGTH = 100_000;
49
-
50
- /**
51
- * Parses `original`, returning `undefined` for anything malformed, oversized,
52
- * or absent - never throws. `undefined` is unambiguous as a "parse failed"
53
- * sentinel because a placeholder's `original` is always itself valid JSON
54
- * (an object or array), never the JSON value `undefined`.
55
- */
56
- function parseOriginal(raw: string | undefined): unknown {
57
- if (!raw || raw.length > MAX_ORIGINAL_JSON_LENGTH) return undefined;
58
- try {
59
- return JSON.parse(raw);
60
- } catch {
61
- return undefined;
62
- }
63
- }
64
-
65
- /**
66
- * The minimum shape `restoreConcealedContent` trusts enough to splice back
67
- * in - anything else is left as the inert, non-rendering placeholder
68
- * rather than guessed at. Checks the *whole* nested tree (every
69
- * `content`/`marks` entry, at every depth), not just the top node - a
70
- * forged `original` attr can be well-formed JSON with a valid-looking
71
- * `type` at the root while carrying garbage (a string instead of an array,
72
- * a number where a mark belongs) underneath, which would otherwise splice
73
- * structurally-invalid JSONContent into the persisted document. This
74
- * intentionally does NOT check that `type` names are recognized - a
75
- * genuinely concealed node's `type` is unrecognized by definition, and
76
- * restoring it is this function's entire purpose.
77
- */
78
- function isPlausibleJSONContent(value: unknown): value is JSONContent {
79
- if (typeof value !== 'object' || value === null || Array.isArray(value)) {
80
- return false;
81
- }
82
- const { type, content, marks } = value as {
83
- type?: unknown;
84
- content?: unknown;
85
- marks?: unknown;
86
- };
87
- if (typeof type !== 'string') return false;
88
- if (content !== undefined) {
89
- if (!Array.isArray(content) || !content.every(isPlausibleJSONContent)) {
90
- return false;
91
- }
92
- }
93
- if (marks !== undefined) {
94
- if (
95
- !Array.isArray(marks) ||
96
- !marks.every(
97
- (mark) =>
98
- typeof mark === 'object' &&
99
- mark !== null &&
100
- typeof (mark as { type?: unknown }).type === 'string',
101
- )
102
- ) {
103
- return false;
104
- }
105
- }
106
- return true;
107
- }
108
-
109
- /**
110
- * `'salvage'` (used for admins, and for Doctor's explicit Fix action):
111
- * unrecognized nodes are replaced with their plain-text content, visibly
112
- * flagged via an `unsupportedFormatting` node - an explicit, visible fix.
113
- *
114
- * `'conceal'` (used for everyone else): unrecognized content must not
115
- * render or be visible at all, but also must not be destroyed by an
116
- * unrelated edit elsewhere in the same document - only an admin's explicit
117
- * action should ever cause it to be dropped. Each unrecognized node is
118
- * replaced with an invisible `unrecognizedContentPlaceholder(Block)` node
119
- * carrying the exact original JSON in an opaque attr; `restoreConcealedContent`
120
- * splices it back in verbatim before a save is persisted.
121
- */
122
- export type UnrecognizedContentMode = 'salvage' | 'conceal';
123
-
124
- function extractPlainText(node: JSONContent): string {
125
- if (node.type === 'text') return node.text ?? '';
126
- return (node.content ?? []).map(extractPlainText).join('');
127
- }
128
-
129
- function isInlineContext(parentType: string | undefined): boolean {
130
- return !!parentType && INLINE_CONTAINER_TYPES.has(parentType);
131
- }
132
-
133
- /**
134
- * The stand-in for an unrecognized node, wrapped to be valid in its
135
- * parent's content model. In `'salvage'` mode this is the unstyled
136
- * plain-text content wrapped in an `unsupportedFormatting` node (null - the
137
- * node is dropped entirely - when there's no text to show). In `'conceal'`
138
- * mode this is always an invisible placeholder carrying the original node
139
- * losslessly, regardless of whether it has text.
140
- */
141
- function buildReplacement(
142
- node: JSONContent,
143
- parentType: string | undefined,
144
- mode: UnrecognizedContentMode,
145
- ): JSONContent | null {
146
- const inline = isInlineContext(parentType);
147
-
148
- if (mode === 'conceal') {
149
- return {
150
- type: inline
151
- ? 'unrecognizedContentPlaceholder'
152
- : 'unrecognizedContentPlaceholderBlock',
153
- attrs: { original: JSON.stringify([node]) },
154
- };
155
- }
156
-
157
- const text = extractPlainText(node);
158
- if (!text) return null;
159
- const notice: JSONContent = {
160
- type: 'unsupportedFormatting',
161
- content: [{ type: 'text', text }],
162
- };
163
- return inline ? notice : { type: 'paragraph', content: [notice] };
164
- }
165
-
166
- function collectUnrecognizedTypes(
167
- node: JSONContent,
168
- recognizedTypeNames: ReadonlySet<string>,
169
- found: Set<string>,
170
- ): void {
171
- if (node.type && !recognizedTypeNames.has(node.type)) {
172
- found.add(node.type);
173
- }
174
- node.marks?.forEach((mark) => {
175
- if (!recognizedTypeNames.has(mark.type)) {
176
- found.add(mark.type);
177
- }
178
- });
179
- node.content?.forEach((child) =>
180
- collectUnrecognizedTypes(child, recognizedTypeNames, found),
181
- );
182
- }
183
-
184
- /**
185
- * Walks a JSONContent tree (node.type, node.marks[].type at every level,
186
- * including nested `content` arrays) and returns the deduped list of type
187
- * names not present in `recognizedTypeNames`. Never calls
188
- * `schema.nodeFromJSON`/`createNodeFromContent` - cannot trigger tiptap's
189
- * destructive "empty the whole doc" fallback.
190
- */
191
- export function findUnrecognizedTiptapTypes(
192
- content: JSONContent | null | undefined,
193
- recognizedTypeNames: ReadonlySet<string>,
194
- ): string[] {
195
- if (!content) return [];
196
- const found = new Set<string>();
197
- collectUnrecognizedTypes(content, recognizedTypeNames, found);
198
- return [...found];
199
- }
200
-
201
- function cleanNode(
202
- node: JSONContent,
203
- recognizedTypeNames: ReadonlySet<string>,
204
- removed: Set<string>,
205
- mode: UnrecognizedContentMode,
206
- ): JSONContent {
207
- const cleaned: JSONContent = { ...node };
208
-
209
- if (node.marks) {
210
- const hasUnrecognizedMark = node.marks.some(
211
- (mark) => !recognizedTypeNames.has(mark.type),
212
- );
213
-
214
- // Conceal mode's guarantee is lossless until an admin explicitly fixes
215
- // it - dropping an unrecognized mark from `node.marks` below would
216
- // permanently destroy it on a non-admin's save. Instead conceal the
217
- // whole node (marks and all) behind the same placeholder mechanism
218
- // used for unrecognized node types - always the inline placeholder,
219
- // since marks only ever apply to inline/text nodes.
220
- if (hasUnrecognizedMark && mode === 'conceal') {
221
- node.marks.forEach((mark) => {
222
- if (!recognizedTypeNames.has(mark.type)) removed.add(mark.type);
223
- });
224
- return {
225
- type: 'unrecognizedContentPlaceholder',
226
- attrs: { original: JSON.stringify([node]) },
227
- };
228
- }
229
-
230
- const keptMarks = node.marks.filter((mark) => {
231
- const isRecognized = recognizedTypeNames.has(mark.type);
232
- if (!isRecognized) removed.add(mark.type);
233
- return isRecognized;
234
- });
235
- if (keptMarks.length > 0) {
236
- cleaned.marks = keptMarks;
237
- } else {
238
- delete cleaned.marks;
239
- }
240
- }
241
-
242
- if (node.content) {
243
- cleaned.content = node.content.flatMap((child) => {
244
- const isRecognized = !child.type || recognizedTypeNames.has(child.type);
245
- if (isRecognized) {
246
- return [cleanNode(child, recognizedTypeNames, removed, mode)];
247
- }
248
-
249
- removed.add(child.type as string);
250
- const replacement = buildReplacement(child, node.type, mode);
251
- return replacement ? [replacement] : [];
252
- });
253
- }
254
-
255
- return cleaned;
256
- }
257
-
258
- /**
259
- * Returns a new tree with the unrecognized nodes/marks handled per `mode`
260
- * (see `UnrecognizedContentMode`) - every recognized sibling/ancestor is
261
- * left untouched. Unrecognized marks are mode-dependent, like unrecognized
262
- * nodes: `'salvage'` drops the mark from the node's `marks` array, leaving
263
- * the text unstyled and visibly rendering; `'conceal'` preserves the mark
264
- * losslessly by concealing the whole marked node behind the same
265
- * placeholder mechanism used for unrecognized node types, since dropping
266
- * it would otherwise permanently destroy data conceal mode guarantees
267
- * survives until an admin explicitly acts. Only if the root node's own
268
- * `type` is unrecognized and nothing was preserved (salvage mode with no
269
- * text) does this fall back to an empty doc, since there's no parent to
270
- * replace it in place - reported via `removedTypes` either way, never
271
- * silent to the caller.
272
- */
273
- export function stripUnrecognizedTiptapContent(
274
- content: JSONContent | null | undefined,
275
- recognizedTypeNames: ReadonlySet<string>,
276
- { mode = 'salvage' }: { mode?: UnrecognizedContentMode } = {},
277
- ): { content: JSONContent | null | undefined; removedTypes: string[] } {
278
- if (!content) return { content, removedTypes: [] };
279
-
280
- if (content.type && !recognizedTypeNames.has(content.type)) {
281
- if (mode === 'conceal') {
282
- return {
283
- content: {
284
- type: 'doc',
285
- content: [
286
- {
287
- type: ROOT_PLACEHOLDER_TYPE,
288
- // The whole original root node (its own type/attrs included,
289
- // not just its children) - `restoreConcealedContent` returns
290
- // this verbatim in place of the synthetic wrapping `doc`.
291
- attrs: { original: JSON.stringify(content) },
292
- },
293
- ],
294
- },
295
- removedTypes: [content.type],
296
- };
297
- }
298
- const text = extractPlainText(content);
299
- return {
300
- content: text
301
- ? {
302
- type: 'doc',
303
- content: [
304
- {
305
- type: 'paragraph',
306
- content: [
307
- {
308
- type: 'unsupportedFormatting',
309
- content: [{ type: 'text', text }],
310
- },
311
- ],
312
- },
313
- ],
314
- }
315
- : EMPTY_DOC,
316
- removedTypes: [content.type],
317
- };
318
- }
319
-
320
- const removed = new Set<string>();
321
- const cleaned = cleanNode(content, recognizedTypeNames, removed, mode);
322
- return { content: cleaned, removedTypes: [...removed] };
323
- }
324
-
325
- /**
326
- * Reverses `stripUnrecognizedTiptapContent`'s `mode: 'conceal'` - splices
327
- * each `unrecognizedContentPlaceholder(Block)` node back into its exact
328
- * original JSON before a save is persisted, so the original unrecognized
329
- * content survives edits made anywhere else in the same document. A no-op
330
- * on content with no placeholders (e.g. anything produced in `'salvage'`
331
- * mode), so it's always safe to call unconditionally before saving.
332
- *
333
- * A placeholder's `original` attr is untrusted (see `parseOriginal`'s doc
334
- * comment) - anything that doesn't parse, or doesn't look like plausible
335
- * JSONContent, is left as the placeholder rather than spliced in. This
336
- * bounds a forged placeholder's damage to "stays invisibly inert" instead
337
- * of crashing the save or injecting arbitrary structure into the document;
338
- * it does not (and can't, without signing the payload) distinguish a
339
- * well-formed forged node from genuinely concealed content, since neither
340
- * carries any proof of where it came from.
341
- */
342
- export function restoreConcealedContent(content: JSONContent): JSONContent;
343
- export function restoreConcealedContent(
344
- content: JSONContent | null | undefined,
345
- ): JSONContent | null | undefined;
346
- export function restoreConcealedContent(
347
- content: JSONContent | null | undefined,
348
- ): JSONContent | null | undefined {
349
- if (!content?.content) return content;
350
-
351
- // The whole document was concealed (the root's own type was
352
- // unrecognized) - restore the original root node itself instead of
353
- // leaving it nested inside a synthetic `doc` it never actually had.
354
- const [onlyChild] = content.content;
355
- if (
356
- content.type === 'doc' &&
357
- content.content.length === 1 &&
358
- onlyChild.type === ROOT_PLACEHOLDER_TYPE
359
- ) {
360
- const restored = parseOriginal(onlyChild.attrs?.original);
361
- return isPlausibleJSONContent(restored) ? restored : content;
362
- }
363
-
364
- return {
365
- ...content,
366
- content: content.content.flatMap((child) => {
367
- if (child.type && PLACEHOLDER_TYPES.has(child.type)) {
368
- const restored = parseOriginal(child.attrs?.original);
369
- return Array.isArray(restored) && restored.every(isPlausibleJSONContent)
370
- ? restored
371
- : [child];
372
- }
373
- // A root placeholder that's no longer the doc's sole child (a sibling
374
- // was added before save) misses the fast path above. Splice the
375
- // original root node back in anyway - its type is still unrecognized,
376
- // so the next load re-conceals it and detection keeps reporting it,
377
- // rather than letting the raw (now-"recognized") placeholder type
378
- // persist to storage unnoticed.
379
- if (child.type === ROOT_PLACEHOLDER_TYPE) {
380
- const restored = parseOriginal(child.attrs?.original);
381
- return isPlausibleJSONContent(restored) ? [restored] : [child];
382
- }
383
- return [restoreConcealedContent(child)];
384
- }),
385
- };
386
- }
@@ -1,94 +0,0 @@
1
- import { Node, mergeAttributes } from '@tiptap/core';
2
-
3
- /**
4
- * `stripUnrecognizedTiptapContent`'s `mode: 'conceal'` (see
5
- * `find-unrecognized-content.ts`) substitutes one of these for an
6
- * unrecognized node - never a bare `text`/`unsupportedFormatting` node, so
7
- * nothing about the removed content renders. The original node's exact
8
- * JSON is round-tripped through the `original` attr (as a JSON string, so
9
- * its own possibly-unrecognized nested types never reach the schema) and
10
- * spliced back in verbatim by `restoreConcealedContent` before a save is
11
- * persisted - so an edit elsewhere in the same document never destroys it.
12
- * `selectable: false` keeps it out of normal selection; nothing renders so
13
- * there's nothing to click on regardless.
14
- */
15
- function addOriginalAttribute() {
16
- return {
17
- original: { default: '[]' },
18
- };
19
- }
20
-
21
- export const UnrecognizedContentPlaceholder = Node.create({
22
- name: 'unrecognizedContentPlaceholder',
23
- group: 'inline',
24
- inline: true,
25
- atom: true,
26
- selectable: false,
27
- addAttributes: addOriginalAttribute,
28
-
29
- parseHTML() {
30
- return [{ tag: 'span[data-unrecognized-content-placeholder]' }];
31
- },
32
- renderHTML({ HTMLAttributes }) {
33
- return [
34
- 'span',
35
- mergeAttributes(HTMLAttributes, {
36
- 'data-unrecognized-content-placeholder': '',
37
- style: 'display:none',
38
- }),
39
- ];
40
- },
41
- });
42
-
43
- export const UnrecognizedContentPlaceholderBlock = Node.create({
44
- name: 'unrecognizedContentPlaceholderBlock',
45
- group: 'block',
46
- atom: true,
47
- selectable: false,
48
- addAttributes: addOriginalAttribute,
49
-
50
- parseHTML() {
51
- return [{ tag: 'div[data-unrecognized-content-placeholder-block]' }];
52
- },
53
- renderHTML({ HTMLAttributes }) {
54
- return [
55
- 'div',
56
- mergeAttributes(HTMLAttributes, {
57
- 'data-unrecognized-content-placeholder-block': '',
58
- style: 'display:none',
59
- }),
60
- ];
61
- },
62
- });
63
-
64
- /**
65
- * Distinct from `UnrecognizedContentPlaceholderBlock` even though it's
66
- * schema-identical - this one is only ever the sole child of the
67
- * synthetic wrapping `doc` `stripUnrecognizedTiptapContent` builds when
68
- * the ROOT node's own type is unrecognized (there's no real parent to
69
- * hold a child placeholder in that case). The distinct name lets
70
- * `restoreConcealedContent` tell "the whole document was concealed" apart
71
- * from "one ordinary child among others was concealed" and restore the
72
- * original root type itself, rather than leaving it wrapped in a `doc` it
73
- * never actually had.
74
- */
75
- export const UnrecognizedContentPlaceholderRoot = Node.create({
76
- name: 'unrecognizedContentPlaceholderRoot',
77
- group: 'block',
78
- atom: true,
79
- selectable: false,
80
- addAttributes: addOriginalAttribute,
81
-
82
- parseHTML() {
83
- return [{ tag: 'div[data-unrecognized-content-placeholder-root]' }];
84
- },
85
- renderHTML({ HTMLAttributes }) {
86
- return [
87
- 'div',
88
- mergeAttributes(HTMLAttributes, {
89
- 'data-unrecognized-content-placeholder-root': '',
90
- style: 'display:none',
91
- }),
92
- ];
93
- },
94
- });
@@ -1,27 +0,0 @@
1
- import { Node, mergeAttributes } from '@tiptap/core';
2
-
3
- /**
4
- * Marks the plain-text stand-in `stripUnrecognizedTiptapContent` (see
5
- * `find-unrecognized-content.ts`) substitutes for a node/mark type the
6
- * editor doesn't recognize. Schema-only here (no rendering) - the live
7
- * editor extends this with a NodeView that shows a warning badge next to
8
- * the text (`apps/ui/app-ui/src/components/text-editor/unsupported-formatting.node.tsx`).
9
- */
10
- export const UnsupportedFormatting = Node.create({
11
- name: 'unsupportedFormatting',
12
- group: 'inline',
13
- inline: true,
14
- content: 'text*',
15
- selectable: true,
16
-
17
- parseHTML() {
18
- return [{ tag: 'span[data-unsupported-formatting]' }];
19
- },
20
- renderHTML({ HTMLAttributes }) {
21
- return [
22
- 'span',
23
- mergeAttributes(HTMLAttributes, { 'data-unsupported-formatting': '' }),
24
- 0,
25
- ];
26
- },
27
- });