Skip to content

Commit 594ed9a

Browse files
committed
feat(json-crdt-extensions): 🎸 harden HTML import
1 parent f117025 commit 594ed9a

File tree

3 files changed

+49
-3
lines changed

3 files changed

+49
-3
lines changed
Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,41 @@
1+
import {CommonSliceType} from '../../slice';
12
import {fromHtml} from '../import-html';
23

34
describe('.fromHtml()', () => {
45
it('a single paragraph', () => {
56
const html = '<p>Hello world</p>';
67
const peritextMl = fromHtml(html);
7-
console.log(peritextMl);
8-
// expect(peritextMl).toEqual(['p', null, 'Hello world']);
8+
expect(peritextMl).toEqual([
9+
'',
10+
null,
11+
[CommonSliceType.p, null, 'Hello world'],
12+
]);
13+
});
14+
15+
it('a paragraph with trailing text', () => {
16+
const html = '<p>Hello world</p> more text';
17+
const peritextMl = fromHtml(html);
18+
expect(peritextMl).toEqual([
19+
'',
20+
null,
21+
[CommonSliceType.p, null, 'Hello world'],
22+
' more text',
23+
]);
24+
});
25+
26+
it('text formatted as italic', () => {
27+
const html = '<p>Hello world</p>\n<p><em>italic</em> text, <i>more italic</i></p>';
28+
const peritextMl = fromHtml(html);
29+
expect(peritextMl).toEqual([
30+
'',
31+
null,
32+
[CommonSliceType.p, null, 'Hello world'],
33+
'\n',
34+
[CommonSliceType.p, null,
35+
[CommonSliceType.i, null, 'italic'],
36+
' text, ',
37+
[CommonSliceType.i, null, 'more italic'],
38+
],
39+
]);
940
});
1041
});

src/json-crdt-extensions/peritext/lazy/import-html.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,16 @@ export const fromJsonMl = (jsonml: JsonMlNode, registry: SliceRegistry = default
2020
} else {
2121
node[0] = SliceTypeName[tag as any] ?? tag;
2222
const attr = jsonml[1] || {};
23-
const data = attr['data-attr'] !== void 0 ? JSON.parse(attr['data-attr']) : null;
23+
let data = null;
24+
if (attr['data-attr'] !== void 0) {
25+
try {
26+
data = JSON.parse(attr['data-attr']);
27+
} catch {}
28+
}
2429
const inline = attr['data-inline'] === 'true';
2530
if (data || inline) node[1] = {data, inline};
2631
}
32+
if (typeof node[0] === 'number' && node[0] < 0 && node[1]) node[1].inline = true;
2733
return node;
2834
};
2935

src/json-crdt-extensions/peritext/registry/registry.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,12 @@ registry.add({
2929
}
3030
},
3131
});
32+
33+
registry.add({
34+
type: CommonSliceType.i,
35+
schema: s.con(undefined),
36+
fromHtml: {
37+
em: () => [CommonSliceType.i, null],
38+
i: () => [CommonSliceType.i, null],
39+
},
40+
});

0 commit comments

Comments
 (0)