|
1 | 1 | import {html as _html} from 'very-small-parser/lib/html'; |
2 | 2 | import {fromHast as _fromHast} from 'very-small-parser/lib/html/json-ml/fromHast'; |
3 | 3 | import {SliceTypeName} from '../slice'; |
| 4 | +import {registry as defaultRegistry} from '../registry/registry'; |
4 | 5 | import type {JsonMlNode} from 'very-small-parser/lib/html/json-ml/types'; |
5 | 6 | import type {THtmlToken} from 'very-small-parser/lib/html/types'; |
6 | 7 | import type {PeritextMlNode} from '../block/types'; |
| 8 | +import type {SliceRegistry} from '../registry/SliceRegistry'; |
7 | 9 |
|
8 | | -export const fromJsonMl = (jsonml: JsonMlNode): PeritextMlNode => { |
| 10 | +export const fromJsonMl = (jsonml: JsonMlNode, registry: SliceRegistry = defaultRegistry): PeritextMlNode => { |
9 | 11 | if (typeof jsonml === 'string') return jsonml; |
10 | | - const [tag, attr = {}, ...children] = jsonml; |
11 | | - const type = SliceTypeName[tag as any] ?? tag; |
12 | | - const data = attr['data-attr'] !== void 0 ? JSON.parse(attr['data-attr']) : null; |
13 | | - // console.log('tag', tag); |
14 | | - // const namedTag = tag === '' ? tag : tag; |
15 | | - // const peritextTag = namedTag ?? (attr?.inline ? 'span' : 'div'); |
16 | | - // const peritextAttr = attr && attr['data-attr'] !== void 0 ? {data: JSON.parse(attr['data-attr'])} : null; |
17 | | - const peritextNode: PeritextMlNode = [type, {}]; |
18 | | - const length = children.length; |
19 | | - for (let i = 0; i < length; i++) peritextNode.push(fromJsonMl(children[i])); |
20 | | - return peritextNode; |
| 12 | + const tag = jsonml[0]; |
| 13 | + const length = jsonml.length; |
| 14 | + const node: PeritextMlNode = [tag, null]; |
| 15 | + for (let i = 2; i < length; i++) node.push(fromJsonMl(jsonml[i] as JsonMlNode, registry)); |
| 16 | + const res = registry.fromHtml(jsonml); |
| 17 | + if (res) { |
| 18 | + node[0] = res[0]; |
| 19 | + node[1] = res[1]; |
| 20 | + } else { |
| 21 | + node[0] = SliceTypeName[tag as any] ?? tag; |
| 22 | + const attr = jsonml[1] || {}; |
| 23 | + const data = attr['data-attr'] !== void 0 ? JSON.parse(attr['data-attr']) : null; |
| 24 | + const inline = attr['data-inline'] === 'true'; |
| 25 | + if (data || inline) node[1] = {data, inline}; |
| 26 | + } |
| 27 | + return node; |
21 | 28 | }; |
22 | 29 |
|
23 | | -export const fromHast = (hast: THtmlToken): PeritextMlNode => { |
| 30 | +export const fromHast = (hast: THtmlToken, registry?: SliceRegistry): PeritextMlNode => { |
24 | 31 | const jsonml = _fromHast(hast); |
25 | | - return fromJsonMl(jsonml); |
| 32 | + return fromJsonMl(jsonml, registry); |
26 | 33 | }; |
27 | 34 |
|
28 | | -export const fromHtml = (html: string): PeritextMlNode => { |
| 35 | +export const fromHtml = (html: string, registry?: SliceRegistry): PeritextMlNode => { |
29 | 36 | const hast = _html.parsef(html); |
30 | | - return fromHast(hast); |
| 37 | + return fromHast(hast, registry); |
31 | 38 | }; |
0 commit comments