-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathhtml.ts
32 lines (23 loc) · 830 Bytes
/
html.ts
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
import { DOMParser, DOMSerializer, Schema } from 'prosemirror-model'
import { ProsemirrorTransformer } from './types'
export const createHTMLTransformer = <S extends Schema>(
schema: S
): ProsemirrorTransformer<string, S> => {
const parser = DOMParser.fromSchema(schema)
const serializer = DOMSerializer.fromSchema(schema)
return {
parse: (html) => {
const template = document.createElement('template')
template.innerHTML = html.trim()
if (!template.content?.firstChild) {
throw new Error('Error parsing HTML input')
}
return parser.parse(template.content)
},
serialize: (doc) => {
const template = document.createElement('template')
template.content.appendChild(serializer.serializeFragment(doc.content))
return template.innerHTML
},
}
}