-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcollab.js
More file actions
443 lines (406 loc) · 13.9 KB
/
collab.js
File metadata and controls
443 lines (406 loc) · 13.9 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
/*
* Copyright 2024 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
import {
prosemirrorToYXmlFragment, yDocToProsemirror,
} from 'y-prosemirror';
import { DOMParser, DOMSerializer } from 'prosemirror-model';
import { fromHtml } from 'hast-util-from-html';
import { matches } from 'hast-util-select';
import { getSchema } from './schema.js';
function convertSectionBreak(node) {
if (!node) return;
if (node.children) {
node.children.forEach(convertSectionBreak);
}
if (node.tagName === 'p' && node.children && node.children.length === 1) {
if (node.children[0].type === 'text' && node.children[0].value === '---') {
// eslint-disable-next-line no-param-reassign
node.children.length = 0;
// eslint-disable-next-line no-param-reassign
node.tagName = 'hr';
}
}
}
function divFilter(parent) {
return parent.children.filter((child) => child.tagName === 'div');
}
function blockToTable(child, children) {
children.push({
type: 'element', tagName: 'p', children: [], properties: {},
});
const classes = Array.from(child.properties.className);
const name = classes.shift();
const blockName = classes.length > 0 ? `${name} (${classes.join(', ')})` : name;
const rows = [...divFilter(child)];
const maxCols = rows.reduce((colCount, row) => {
const cols = divFilter(row);
return cols.length > colCount ? cols.length : colCount;
}, 0);
const table = {
type: 'element', tagName: 'table', children: [], properties: {},
};
if (child.properties.dataId) {
table.properties.dataId = child.properties.dataId;
}
children.push(table);
const headerRow = {
type: 'element', tagName: 'tr', children: [], properties: {},
};
const td = {
type: 'element', tagName: 'td', children: [{ type: 'text', value: blockName }], properties: { colSpan: maxCols },
};
headerRow.children.push(td);
table.children.push(headerRow);
rows.filter((row) => row.tagName === 'div').forEach((row) => {
const tr = {
type: 'element', tagName: 'tr', children: [], properties: {},
};
const cells = (row.children ? [...row.children] : [row]).filter((cell) => cell.type !== 'text' || (cell.value && cell.value.trim() !== '\n' && cell.value.trim() !== ''));
cells.forEach((cell, idx) => {
const tdi = {
type: 'element', tagName: 'td', children: [], properties: {},
};
if (cells.length < maxCols && idx === cells.length - 1) {
tdi.properties.colSpan = maxCols - idx;
}
tdi.children.push(cells[idx]);
tr.children.push(tdi);
});
table.children.push(tr);
});
children.push({
type: 'element', tagName: 'p', children: [], properties: {},
});
}
/**
* Recursively traverses a node tree and fixes image links by moving link attributes to img elements
*/
function fixImageLinks(node) {
if (!node) return node;
// Recursively process children first
if (node.children) {
node.children.forEach((child) => {
if (child.tagName === 'a' && child.children?.length > 0) {
const { href, title } = child.properties;
child.children.forEach((linkChild) => {
if (linkChild.tagName === 'picture') {
linkChild.children.forEach((pictureChild) => {
if (pictureChild.tagName === 'img') {
// eslint-disable-next-line no-param-reassign
pictureChild.properties = {
...pictureChild.properties,
href,
title,
};
}
});
} else if (linkChild.tagName === 'img') {
// eslint-disable-next-line no-param-reassign
linkChild.properties = {
...linkChild.properties,
href,
title,
};
}
});
} else {
fixImageLinks(child);
}
});
}
return node;
}
function removeComments(node) {
if (!node) return node;
// eslint-disable-next-line no-param-reassign
node.children = node.children?.filter((child) => child.type !== 'comment') || [];
node.children.forEach(removeComments);
return node;
}
export const EMPTY_DOC = '<body><header></header><main><div></div></main><footer></footer></body>';
export function aem2doc(html, ydoc) {
if (!html) {
// eslint-disable-next-line no-param-reassign
html = EMPTY_DOC;
}
const tree = fromHtml(html, { fragment: true });
const main = tree.children.find((child) => child.tagName === 'main') || { children: [] };
fixImageLinks(main);
removeComments(main);
(main.children || []).forEach((parent) => {
if (parent.tagName === 'div' && parent.children) {
const children = [];
let modified = false;
parent.children.forEach((child) => {
if (child.tagName === 'div' && child.properties.className?.length > 0) {
modified = true;
blockToTable(child, children);
} else if (child.tagName === 'da-loc-deleted' || child.tagName === 'da-loc-added') {
modified = true;
const locChildren = [];
child.children.forEach((locChild) => {
if (locChild.tagName === 'div' && locChild.properties.className?.length > 0) {
blockToTable(locChild, locChildren);
} else {
locChildren.push(locChild);
}
});
// eslint-disable-next-line no-param-reassign
child.children = locChildren;
children.push(child);
} else {
children.push(child);
}
});
if (modified) {
// eslint-disable-next-line no-param-reassign
parent.children = children;
}
}
});
convertSectionBreak(main);
let count = 0;
main.children = main.children.flatMap((node) => {
const result = [];
if (node.tagName === 'div') {
if (count > 0) {
result.push({
type: 'element', tagName: 'p', children: [], properties: {},
});
result.push({
type: 'element', tagName: 'hr', children: [], properties: {},
});
result.push({
type: 'element', tagName: 'p', children: [], properties: {},
});
result.push(...node.children);
} else {
result.push(node);
}
count += 1;
} else {
result.push(node);
}
return result;
});
const handler2 = {
get(target, prop) {
const source = target;
if (prop === 'firstChild') {
if (target.children.length === 0) return null;
for (let i = 0; i < target.children.length - 1; i += 1) {
source.children[i].nextSibling = new Proxy(target.children[i + 1], handler2);
if (i > 0) {
source.children[i].previousSibling = new Proxy(target.children[i - 1], handler2);
} else {
source.children[i].previousSibling = new Proxy(
target.children[target.children.length - 1],
handler2,
);
}
}
return new Proxy(target.children[0], handler2);
}
if (prop === 'nodeType') {
return target.type === 'text' ? 3 : 1;
}
if (prop === 'nodeValue') {
return target.value;
}
if (prop === 'nextSibling') {
return target.nextSibling;
}
if (prop === 'previousSibling') {
return target.previousSibling;
}
if (prop === 'nodeName') {
return target.tagName?.toUpperCase();
}
if (prop === 'matches') {
return (selector) => matches(selector, target);
}
if (prop === 'getAttribute') {
return (name) => {
// when `tree` is created using `fromHtml` in hast-util-from-html
// that then calls fromParse5 in hast-util-from-parse5
// which converts the `colspan`/`rowspan` attribute to `colSpan`/`rowSpan`
if (name === 'colspan') {
// eslint-disable-next-line no-param-reassign
name = 'colSpan';
}
if (name === 'rowspan') {
// eslint-disable-next-line no-param-reassign
name = 'rowSpan';
}
return target.properties ? target.properties[name] : undefined;
};
}
if (prop === 'hasAttribute') {
return (name) => target.properties && target.properties[name];
}
if (prop === 'style') {
return {};
}
return Reflect.get(target, prop);
},
};
const json = DOMParser.fromSchema(getSchema()).parse(new Proxy(main, handler2));
prosemirrorToYXmlFragment(json, ydoc.getXmlFragment('prosemirror'));
}
const getAttrString = (attributes) => Object.entries(attributes).map(([key, value]) => ` ${key}="${value}"`).join('');
function tohtml(node) {
const { attributes } = node;
let attrString = getAttrString(attributes);
if (!node.children || node.children.length === 0) {
if (node.type === 'text') {
return node.text;
}
if (node.type === 'p') return '';
if (node.type === 'img' && !attributes.loading) {
attrString += ' loading="lazy"';
}
if (node.type === 'img') {
const { href, src, title } = attributes;
if (attributes.href) {
delete attributes.href;
delete attributes.title;
attrString = getAttrString(attributes);
const titleStr = title ? ` title="${title}"` : '';
return `<a href="${href}"${titleStr}><picture><source srcset="${src}"><source srcset="${src}" media="(min-width: 600px)"><img${attrString}></picture></a>`;
}
return `<picture><source srcset="${src}"><source srcset="${src}" media="(min-width: 600px)"><img${attrString}></picture>`;
}
const result = node.type !== 'br' ? `<${node.type}${attrString}></${node.type}>` : `<${node.type}>`;
return result;
}
let { children } = node;
if (node.type === 'li') {
if (children.length === 1) {
if (children[0].type === 'p') {
children = children[0].children;
}
}
}
if (node.type === 'p') {
if (children.length === 1) {
if (children[0].type === 'img') {
return children.map((child) => tohtml(child)).join('');
}
}
}
return `<${node.type}${attrString}>${children.map((child) => tohtml(child)).join('')}</${node.type}>`;
}
function toBlockCSSClassNames(text) {
if (!text) return [];
const names = [];
const idx = text.lastIndexOf('(');
if (idx >= 0) {
names.push(text.substring(0, idx));
names.push(...text.substring(idx + 1).split(','));
} else {
names.push(text);
}
return names.map((name) => name
.toLowerCase()
.replace(/[^0-9a-z]+/g, '-')
.replace(/^-+/, '')
.replace(/-+$/, ''))
.filter((name) => !!name);
}
export function tableToBlock(child, fragment) {
const rows = child.children[0].children;
const nameRow = rows.shift();
const className = toBlockCSSClassNames(nameRow.children[0].children[0].children[0]?.text).join(' ');
const block = { type: 'div', attributes: { class: className }, children: [] };
const dataId = child?.attributes?.dataId;
if (dataId) block.attributes['data-id'] = dataId;
fragment.children.push(block);
rows.forEach((row) => {
const div = { type: 'div', attributes: {}, children: [] };
block.children.push(div);
row.children.forEach((col) => {
div.children.push({ type: 'div', attributes: {}, children: col.children });
});
});
}
export function doc2aem(ydoc) {
const schema = getSchema();
const json = yDocToProsemirror(schema, ydoc);
const fragment = { type: 'div', children: [], attributes: {} };
const handler3 = {
get(target, prop) {
const source = target;
if (prop === 'createDocumentFragment') {
return () => new Proxy(fragment, handler3);
}
if (prop === 'appendChild') {
return (node) => target.children.push(node);
}
if (prop === 'createElement') {
return (type) => new Proxy({ type, children: [], attributes: [] }, handler3);
}
if (prop === 'createTextNode') {
return (content) => new Proxy({ type: 'text', text: content, attributes: {} }, handler3);
}
if (prop === 'setAttribute') {
return (name, value) => {
source.attributes[name] = value;
};
}
return Reflect.get(target, prop);
},
};
DOMSerializer.fromSchema(schema)
.serializeFragment(json.content, { document: new Proxy({}, handler3) });
// convert table to blocks
const { children } = fragment;
fragment.children = [];
children.forEach((child) => {
if (child.type === 'table') {
tableToBlock(child, fragment);
} else if (child.type === 'da-loc-deleted' || child.type === 'da-loc-added') {
// eslint-disable-next-line no-param-reassign
delete child.attributes.contenteditable;
const locChildren = child.children;
// eslint-disable-next-line no-param-reassign
child.children = [];
locChildren.forEach((locChild) => {
if (locChild.type === 'table') {
tableToBlock(locChild, child);
} else {
child.children.push(locChild);
}
});
fragment.children.push(child);
} else {
fragment.children.push(child);
}
});
// convert sections
const section = { type: 'div', attributes: {}, children: [] };
const sections = [...fragment.children].reduce((acc, child) => {
if (child.type === 'hr') {
acc.push({ type: 'div', attributes: {}, children: [] });
} else {
acc[acc.length - 1].children.push(child);
}
return acc;
}, [section]);
const text = sections.map((s) => tohtml(s)).join('');
return `
<body>
<header></header>
<main>${text}</main>
<footer></footer>
</body>
`;
}