-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathinjectExtensionAttributesToParseRule.ts
More file actions
47 lines (39 loc) · 1.28 KB
/
injectExtensionAttributesToParseRule.ts
File metadata and controls
47 lines (39 loc) · 1.28 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
import type { ParseRule } from '@tiptap/pm/model'
import type { ExtensionAttribute } from '../types.js'
import { fromString } from '../utilities/fromString.js'
/**
* This function merges extension attributes into parserule attributes (`attrs` or `getAttrs`).
* Cancels when `getAttrs` returned `false`.
* @param parseRule ProseMirror ParseRule
* @param extensionAttributes List of attributes to inject
*/
export function injectExtensionAttributesToParseRule(
parseRule: ParseRule,
extensionAttributes: ExtensionAttribute[],
): ParseRule {
if ('style' in parseRule) {
return parseRule
}
return {
...parseRule,
getAttrs: (node: HTMLElement) => {
const oldAttributes = parseRule.getAttrs ? parseRule.getAttrs(node) : parseRule.attrs
if (oldAttributes === false) {
return false
}
const newAttributes = extensionAttributes.reduce((items, item) => {
const value = item.attribute.parseHTML
? item.attribute.parseHTML(node)
: fromString(node.getAttribute(item.name))
if (value === null || value === undefined || value === '') {
return items
}
return {
...items,
[item.name]: value,
}
}, {})
return { ...oldAttributes, ...newAttributes }
},
}
}