json-joy
Version:
Collection of libraries for building collaborative editing apps.
93 lines • 3.14 kB
JavaScript
import { LeafBlock, Peritext } from '../peritext';
import { ExtensionId } from '../constants';
import { MNEMONIC } from './constants';
import { ExtNode } from '../../json-crdt/extensions/ExtNode';
import { Slice } from '../peritext/slice/Slice';
export class ProseMirrorNode extends ExtNode {
data;
txt;
constructor(data) {
super(data);
this.data = data;
this.txt = new Peritext(data.doc, this.text(), this.slices());
}
text() {
return this.data.get(0);
}
slices() {
return this.data.get(1);
}
// ------------------------------------------------------------------ ExtNode
extId = ExtensionId.prosemirror;
name() {
return MNEMONIC;
}
_view = null;
_viewHash = -1;
toPM(block) {
const content = [];
const node = { type: block.tag() + '' };
if (block instanceof LeafBlock) {
for (let iterator = block.texts0(), inline; (inline = iterator());) {
const text = inline.text();
if (!text)
continue;
const textNode = {
type: 'text',
text,
};
const slices = inline.p1.layers;
const length = slices.length;
if (length > 0) {
const marks = [];
for (let i = 0; i < length; i++) {
const slice = slices[i];
if (slice instanceof Slice) {
const tag = slice.type() + '';
const data = slice.data();
const mark = { type: tag };
if (data && typeof data === 'object' && !Array.isArray(data))
mark.attrs = data;
marks.push(mark);
}
}
textNode.marks = marks;
}
content.push(textNode);
}
}
else {
const children = block.children;
const length = children.length;
for (let i = 0; i < length; i++)
content.push(this.toPM(children[i]));
}
if (content.length)
node.content = content;
const data = block.attr();
if (data && typeof data === 'object') {
for (const _ in data) {
node.attrs = data;
break;
}
}
return node;
}
view() {
const { txt } = this;
const hash = txt.refresh();
if (this._view && hash === this._viewHash)
return this._view;
const content = [];
const node = { type: 'doc', content };
const block = txt.blocks.root;
const children = block.children;
const length = children.length;
for (let i = 0; i < length; i++)
content.push(this.toPM(children[i]));
this._viewHash = hash;
this._view = node;
return node;
}
}
//# sourceMappingURL=ProseMirrorNode.js.map