-
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
createNodeFromContent.ts
52 lines (43 loc) · 1.41 KB
/
createNodeFromContent.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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import {
DOMParser,
Fragment,
Node as ProseMirrorNode,
ParseOptions,
Schema,
} from '@tiptap/pm/model'
import { Content } from '../types.js'
import { elementFromString } from '../utilities/elementFromString.js'
export type CreateNodeFromContentOptions = {
slice?: boolean
parseOptions?: ParseOptions
}
export function createNodeFromContent(
content: Content,
schema: Schema,
options?: CreateNodeFromContentOptions,
): ProseMirrorNode | Fragment {
options = {
slice: true,
parseOptions: {},
...options,
}
if (typeof content === 'object' && content !== null) {
try {
if (Array.isArray(content) && content.length > 0) {
return Fragment.fromArray(content.map(item => schema.nodeFromJSON(item)))
}
return schema.nodeFromJSON(content)
} catch (error) {
console.warn('[tiptap warn]: Invalid content.', 'Passed value:', content, 'Error:', error)
return createNodeFromContent('', schema, options)
}
}
if (typeof content === 'string') {
content = content.split('\n').map(part => part.trim()).join('') // we need to remove new lines since the parser will add breaks
const parser = DOMParser.fromSchema(schema)
return options.slice
? parser.parseSlice(elementFromString(content), options.parseOptions).content
: parser.parse(elementFromString(content), options.parseOptions)
}
return createNodeFromContent('', schema, options)
}