forked from TypeCellOS/BlockNote
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnodeToBlock.ts
More file actions
692 lines (632 loc) · 19.4 KB
/
Copy pathnodeToBlock.ts
File metadata and controls
692 lines (632 loc) · 19.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
import { Mark, Node, Schema, Slice } from "@tiptap/pm/model";
import type { Block } from "../../blocks/defaultBlocks.js";
import UniqueID from "../../extensions/tiptap-extensions/UniqueID/UniqueID.js";
import type {
BlockSchema,
CustomInlineContentConfig,
CustomInlineContentFromConfig,
InlineContent,
InlineContentFromConfig,
InlineContentSchema,
StyleSchema,
Styles,
TableCell,
TableContent,
} from "../../schema/index.js";
import {
isLinkInlineContent,
isStyledTextInlineContent,
} from "../../schema/inlineContent/types.js";
import { UnreachableCaseError } from "../../util/typescript.js";
import { getBlockInfoWithManualOffset } from "../getBlockInfoFromPos.js";
import {
getBlockCache,
getBlockSchema,
getInlineContentSchema,
getPmSchema,
getStyleSchema,
} from "../pmUtil.js";
/**
* Converts an internal (prosemirror) table node contentto a BlockNote Tablecontent
*/
export function contentNodeToTableContent<
I extends InlineContentSchema,
S extends StyleSchema,
>(contentNode: Node, inlineContentSchema: I, styleSchema: S) {
const ret: TableContent<I, S> = {
type: "tableContent",
columnWidths: [],
headerRows: undefined,
headerCols: undefined,
rows: [],
};
/**
* A matrix of boolean values indicating whether a cell is a header.
* The first index is the row index, the second index is the cell index.
*/
const headerMatrix: boolean[][] = [];
contentNode.content.forEach((rowNode, _offset, rowIndex) => {
const row: TableContent<I, S>["rows"][0] = {
cells: [],
};
if (rowIndex === 0) {
rowNode.content.forEach((cellNode) => {
let colWidth = cellNode.attrs.colwidth as null | undefined | number[];
if (colWidth === undefined || colWidth === null) {
colWidth = new Array(cellNode.attrs.colspan ?? 1).fill(undefined);
}
ret.columnWidths.push(...colWidth);
});
}
row.cells = rowNode.content.content.map((cellNode, cellIndex) => {
if (!headerMatrix[rowIndex]) {
headerMatrix[rowIndex] = [];
}
// Mark the cell as a header if it is a tableHeader node.
headerMatrix[rowIndex][cellIndex] = cellNode.type.name === "tableHeader";
// Convert cell content to inline content and merge adjacent styled text nodes
const content = cellNode.content.content
.map((child) =>
contentNodeToInlineContent(child, inlineContentSchema, styleSchema),
)
// The reason that we merge this content is that we allow table cells to contain multiple tableParagraph nodes
// So that we can leverage prosemirror-tables native merging
// If the schema only allowed a single tableParagraph node, then the merging would not work and cause prosemirror to fit the content into a new cell
.reduce(
(acc, contentPartial) => {
if (!acc.length) {
return contentPartial;
}
const last = acc[acc.length - 1];
const first = contentPartial[0];
// Only merge if the last and first content are both styled text nodes and have the same styles
if (
first &&
isStyledTextInlineContent(last) &&
isStyledTextInlineContent(first) &&
JSON.stringify(last.styles) === JSON.stringify(first.styles)
) {
// Join them together if they have the same styles
last.text += "\n" + first.text;
acc.push(...contentPartial.slice(1));
return acc;
}
acc.push(...contentPartial);
return acc;
},
[] as InlineContent<I, S>[],
);
return {
type: "tableCell",
content,
props: {
colspan: cellNode.attrs.colspan,
rowspan: cellNode.attrs.rowspan,
backgroundColor: cellNode.attrs.backgroundColor,
textColor: cellNode.attrs.textColor,
textAlignment: cellNode.attrs.textAlignment,
},
} satisfies TableCell<I, S>;
});
ret.rows.push(row);
});
for (let i = 0; i < headerMatrix.length; i++) {
if (headerMatrix[i]?.every((isHeader) => isHeader)) {
ret.headerRows = (ret.headerRows ?? 0) + 1;
}
}
for (let i = 0; i < headerMatrix[0]?.length; i++) {
if (headerMatrix?.every((row) => row[i])) {
ret.headerCols = (ret.headerCols ?? 0) + 1;
}
}
return ret;
}
/**
* Converts an internal (prosemirror) content node to a BlockNote InlineContent array.
*/
export function contentNodeToInlineContent<
I extends InlineContentSchema,
S extends StyleSchema,
>(contentNode: Node, inlineContentSchema: I, styleSchema: S) {
const content: InlineContent<any, S>[] = [];
let currentContent: InlineContent<any, S> | undefined = undefined;
// Most of the logic below is for handling links because in ProseMirror links are marks
// while in BlockNote links are a type of inline content
contentNode.content.forEach((node) => {
// hardBreak nodes do not have an InlineContent equivalent, instead we
// add a newline to the previous node.
if (node.type.name === "hardBreak") {
if (currentContent) {
// Current content exists.
if (isStyledTextInlineContent(currentContent)) {
// Current content is text.
currentContent.text += "\n";
} else if (isLinkInlineContent(currentContent)) {
// Current content is a link.
currentContent.content[currentContent.content.length - 1].text +=
"\n";
} else {
throw new Error("unexpected");
}
} else {
// Current content does not exist.
currentContent = {
type: "text",
text: "\n",
styles: {},
};
}
return;
}
if (node.type.name !== "link" && node.type.name !== "text") {
if (!inlineContentSchema[node.type.name]) {
// eslint-disable-next-line no-console
console.warn("unrecognized inline content type", node.type.name);
return;
}
if (currentContent) {
content.push(currentContent);
currentContent = undefined;
}
content.push(
nodeToCustomInlineContent(node, inlineContentSchema, styleSchema),
);
return;
}
const styles: Styles<S> = {};
let linkMark: Mark | undefined;
for (const mark of node.marks) {
if (mark.type.name === "link") {
linkMark = mark;
} else {
const config = styleSchema[mark.type.name];
if (!config) {
if (mark.type.spec.blocknoteIgnore) {
// at this point, we don't want to show certain marks (such as comments)
// in the BlockNote JSON output. These marks should be tagged with "blocknoteIgnore" in the spec
continue;
}
throw new Error(`style ${mark.type.name} not found in styleSchema`);
}
if (config.propSchema === "boolean") {
(styles as any)[config.type] = true;
} else if (config.propSchema === "string") {
(styles as any)[config.type] = mark.attrs.stringValue;
} else {
throw new UnreachableCaseError(config.propSchema);
}
}
}
// Parsing links and text.
// Current content exists.
if (currentContent) {
// Current content is text.
if (isStyledTextInlineContent(currentContent)) {
if (!linkMark) {
// Node is text (same type as current content).
if (
JSON.stringify(currentContent.styles) === JSON.stringify(styles)
) {
// Styles are the same.
currentContent.text += node.textContent;
} else {
// Styles are different.
content.push(currentContent);
currentContent = {
type: "text",
text: node.textContent,
styles,
};
}
} else {
// Node is a link (different type to current content).
content.push(currentContent);
currentContent = {
type: "link",
href: linkMark.attrs.href,
content: [
{
type: "text",
text: node.textContent,
styles,
},
],
};
}
} else if (isLinkInlineContent(currentContent)) {
// Current content is a link.
if (linkMark) {
// Node is a link (same type as current content).
// Link URLs are the same.
if (currentContent.href === linkMark.attrs.href) {
// Styles are the same.
if (
JSON.stringify(
currentContent.content[currentContent.content.length - 1]
.styles,
) === JSON.stringify(styles)
) {
currentContent.content[currentContent.content.length - 1].text +=
node.textContent;
} else {
// Styles are different.
currentContent.content.push({
type: "text",
text: node.textContent,
styles,
});
}
} else {
// Link URLs are different.
content.push(currentContent);
currentContent = {
type: "link",
href: linkMark.attrs.href,
content: [
{
type: "text",
text: node.textContent,
styles,
},
],
};
}
} else {
// Node is text (different type to current content).
content.push(currentContent);
currentContent = {
type: "text",
text: node.textContent,
styles,
};
}
} else {
// TODO
}
}
// Current content does not exist.
else {
// Node is text.
if (!linkMark) {
currentContent = {
type: "text",
text: node.textContent,
styles,
};
}
// Node is a link.
else {
currentContent = {
type: "link",
href: linkMark.attrs.href,
content: [
{
type: "text",
text: node.textContent,
styles,
},
],
};
}
}
});
if (currentContent) {
content.push(currentContent);
}
return content as InlineContent<I, S>[];
}
export function nodeToCustomInlineContent<
I extends InlineContentSchema,
S extends StyleSchema,
>(node: Node, inlineContentSchema: I, styleSchema: S): InlineContent<I, S> {
if (node.type.name === "text" || node.type.name === "link") {
throw new Error("unexpected");
}
const props: any = {};
const icConfig = inlineContentSchema[
node.type.name
] as CustomInlineContentConfig;
for (const [attr, value] of Object.entries(node.attrs)) {
if (!icConfig) {
throw Error("ic node is of an unrecognized type: " + node.type.name);
}
const propSchema = icConfig.propSchema;
if (attr in propSchema) {
props[attr] = value;
}
}
let content: CustomInlineContentFromConfig<any, any>["content"];
if (icConfig.content === "styled") {
content = contentNodeToInlineContent(
node,
inlineContentSchema,
styleSchema,
) as any; // TODO: is this safe? could we have Links here that are undesired?
} else {
content = undefined;
}
const ic = {
type: node.type.name,
props,
content,
} as InlineContentFromConfig<I[keyof I], S>;
return ic;
}
/**
* Convert a Prosemirror node to a BlockNote block.
*
* TODO: test changes
*/
export function nodeToBlock<
BSchema extends BlockSchema,
I extends InlineContentSchema,
S extends StyleSchema,
>(
node: Node,
schema: Schema,
blockSchema: BSchema = getBlockSchema(schema) as BSchema,
inlineContentSchema: I = getInlineContentSchema(schema) as I,
styleSchema: S = getStyleSchema(schema) as S,
blockCache = getBlockCache(schema),
): Block<BSchema, I, S> {
if (!node.type.isInGroup("bnBlock")) {
throw Error("Node should be a bnBlock, but is instead: " + node.type.name);
}
const cachedBlock = blockCache?.get(node);
if (cachedBlock) {
return cachedBlock;
}
const blockInfo = getBlockInfoWithManualOffset(node, 0);
let id = blockInfo.bnBlock.node.attrs.id;
// Only used for blocks converted from other formats.
if (id === null) {
id = UniqueID.options.generateID();
}
const blockSpec = blockSchema[blockInfo.blockNoteType];
if (!blockSpec) {
throw Error("Block is of an unrecognized type: " + blockInfo.blockNoteType);
}
const props: any = {};
for (const [attr, value] of Object.entries({
...node.attrs,
...(blockInfo.isBlockContainer ? blockInfo.blockContent.node.attrs : {}),
})) {
const propSchema = blockSpec.propSchema;
if (
attr in propSchema &&
!(propSchema[attr].default === undefined && value === undefined)
) {
props[attr] = value;
}
}
const blockConfig = blockSchema[blockInfo.blockNoteType];
const children: Block<BSchema, I, S>[] = [];
blockInfo.childContainer?.node.forEach((child) => {
children.push(
nodeToBlock(
child,
schema,
blockSchema,
inlineContentSchema,
styleSchema,
blockCache,
),
);
});
let content: Block<any, any, any>["content"];
if (blockConfig.content === "inline") {
if (!blockInfo.isBlockContainer) {
throw new Error("impossible");
}
content = contentNodeToInlineContent(
blockInfo.blockContent.node,
inlineContentSchema,
styleSchema,
);
} else if (blockConfig.content === "table") {
if (!blockInfo.isBlockContainer) {
throw new Error("impossible");
}
content = contentNodeToTableContent(
blockInfo.blockContent.node,
inlineContentSchema,
styleSchema,
);
} else if (blockConfig.content === "none") {
content = undefined;
} else {
throw new UnreachableCaseError(blockConfig.content);
}
const block = {
id,
type: blockConfig.type,
props,
content,
children,
} as Block<BSchema, I, S>;
blockCache?.set(node, block);
return block;
}
/**
* Convert a Prosemirror document to a BlockNote document (array of blocks)
*/
export function docToBlocks<
BSchema extends BlockSchema,
I extends InlineContentSchema,
S extends StyleSchema,
>(
doc: Node,
schema: Schema = getPmSchema(doc),
blockSchema: BSchema = getBlockSchema(schema) as BSchema,
inlineContentSchema: I = getInlineContentSchema(schema) as I,
styleSchema: S = getStyleSchema(schema) as S,
blockCache = getBlockCache(schema),
) {
const blocks: Block<BSchema, I, S>[] = [];
if (doc.firstChild) {
doc.firstChild.descendants((node) => {
blocks.push(
nodeToBlock(
node,
schema,
blockSchema,
inlineContentSchema,
styleSchema,
blockCache,
),
);
return false;
});
}
return blocks;
}
/**
*
* Parse a Prosemirror Slice into a BlockNote selection. The prosemirror schema looks like this:
*
* <blockGroup>
* <blockContainer> (main content of block)
* <p, heading, etc.>
* <blockGroup> (only if blocks has children)
* <blockContainer> (child block)
* <p, heading, etc.>
* </blockContainer>
* <blockContainer> (child block 2)
* <p, heading, etc.>
* </blockContainer>
* </blockContainer>
* </blockGroup>
* </blockGroup>
*
*/
export function prosemirrorSliceToSlicedBlocks<
BSchema extends BlockSchema,
I extends InlineContentSchema,
S extends StyleSchema,
>(
slice: Slice,
schema: Schema,
blockSchema: BSchema = getBlockSchema(schema) as BSchema,
inlineContentSchema: I = getInlineContentSchema(schema) as I,
styleSchema: S = getStyleSchema(schema) as S,
blockCache: WeakMap<Node, Block<BSchema, I, S>> = getBlockCache(schema),
): {
/**
* The blocks that are included in the selection.
*/
blocks: Block<BSchema, I, S>[];
/**
* If a block was "cut" at the start of the selection, this will be the id of the block that was cut.
*/
blockCutAtStart: string | undefined;
/**
* If a block was "cut" at the end of the selection, this will be the id of the block that was cut.
*/
blockCutAtEnd: string | undefined;
} {
// console.log(JSON.stringify(slice.toJSON()));
function processNode(
node: Node,
openStart: number,
openEnd: number,
): {
blocks: Block<BSchema, I, S>[];
blockCutAtStart: string | undefined;
blockCutAtEnd: string | undefined;
} {
if (node.type.name !== "blockGroup") {
throw new Error("unexpected");
}
const blocks: Block<BSchema, I, S>[] = [];
let blockCutAtStart: string | undefined;
let blockCutAtEnd: string | undefined;
node.forEach((blockContainer, _offset, index) => {
if (blockContainer.type.name !== "blockContainer") {
throw new Error("unexpected");
}
if (blockContainer.childCount === 0) {
return;
}
if (blockContainer.childCount === 0 || blockContainer.childCount > 2) {
throw new Error(
"unexpected, blockContainer.childCount: " + blockContainer.childCount,
);
}
const isFirstBlock = index === 0;
const isLastBlock = index === node.childCount - 1;
if (blockContainer.firstChild!.type.name === "blockGroup") {
// this is the parent where a selection starts within one of its children,
// e.g.:
// A
// ├── B
// selection starts within B, then this blockContainer is A, but we don't care about A
// so let's descend into B and continue processing
if (!isFirstBlock) {
throw new Error("unexpected");
}
const ret = processNode(
blockContainer.firstChild!,
Math.max(0, openStart - 1),
isLastBlock ? Math.max(0, openEnd - 1) : 0,
);
blockCutAtStart = ret.blockCutAtStart;
if (isLastBlock) {
blockCutAtEnd = ret.blockCutAtEnd;
}
blocks.push(...ret.blocks);
return;
}
const block = nodeToBlock(
blockContainer,
schema,
blockSchema,
inlineContentSchema,
styleSchema,
blockCache,
);
const childGroup =
blockContainer.childCount > 1 ? blockContainer.child(1) : undefined;
let childBlocks: Block<BSchema, I, S>[] = [];
if (childGroup) {
const ret = processNode(
childGroup,
0, // TODO: can this be anything other than 0?
isLastBlock ? Math.max(0, openEnd - 1) : 0,
);
childBlocks = ret.blocks;
if (isLastBlock) {
blockCutAtEnd = ret.blockCutAtEnd;
}
}
if (isLastBlock && !childGroup && openEnd > 1) {
blockCutAtEnd = block.id;
}
if (isFirstBlock && openStart > 1) {
blockCutAtStart = block.id;
}
blocks.push({
...(block as any),
children: childBlocks,
});
});
return { blocks, blockCutAtStart, blockCutAtEnd };
}
if (slice.content.childCount === 0) {
return {
blocks: [],
blockCutAtStart: undefined,
blockCutAtEnd: undefined,
};
}
if (slice.content.childCount !== 1) {
throw new Error(
"slice must be a single block, did you forget includeParents=true?",
);
}
return processNode(
slice.content.firstChild!,
Math.max(slice.openStart - 1, 0),
Math.max(slice.openEnd - 1, 0),
);
}