tiptap/packages/core/src/helpers/getAttributesFromExtensions.ts

99 lines
2.4 KiB
TypeScript
Raw Normal View History

2020-10-22 05:55:14 +08:00
import splitExtensions from './splitExtensions'
2021-04-16 03:14:33 +08:00
import getExtensionField from './getExtensionField'
import {
2020-10-22 05:55:14 +08:00
Extensions,
GlobalAttributes,
Attributes,
Attribute,
ExtensionAttribute,
2021-04-16 03:14:33 +08:00
AnyConfig,
} from '../types'
2021-04-16 03:14:33 +08:00
import { NodeConfig, MarkConfig } from '..'
2020-10-27 20:19:23 +08:00
/**
* Get a list of all extension attributes defined in `addAttribute` and `addGlobalAttribute`.
* @param extensions List of extensions
*/
2021-01-28 16:50:17 +08:00
export default function getAttributesFromExtensions(extensions: Extensions): ExtensionAttribute[] {
2020-10-22 15:42:28 +08:00
const extensionAttributes: ExtensionAttribute[] = []
2020-10-22 05:55:14 +08:00
const { nodeExtensions, markExtensions } = splitExtensions(extensions)
const nodeAndMarkExtensions = [...nodeExtensions, ...markExtensions]
const defaultAttribute: Required<Attribute> = {
default: null,
rendered: true,
renderHTML: null,
parseHTML: null,
2021-01-29 02:56:35 +08:00
keepOnSplit: true,
}
2020-10-22 05:55:14 +08:00
extensions.forEach(extension => {
2021-04-16 03:14:33 +08:00
const context = {
2020-10-22 05:55:14 +08:00
options: extension.options,
2021-04-16 03:14:33 +08:00
}
const addGlobalAttributes = getExtensionField<AnyConfig['addGlobalAttributes']>(
extension,
'addGlobalAttributes',
context,
)
2020-10-22 05:55:14 +08:00
2021-04-16 03:14:33 +08:00
if (!addGlobalAttributes) {
2021-02-19 17:54:47 +08:00
return
}
2021-04-16 03:14:33 +08:00
// TODO: remove `as GlobalAttributes`
const globalAttributes = addGlobalAttributes() as GlobalAttributes
2020-10-22 05:55:14 +08:00
globalAttributes.forEach(globalAttribute => {
globalAttribute.types.forEach(type => {
2020-10-22 15:42:28 +08:00
Object
.entries(globalAttribute.attributes)
.forEach(([name, attribute]) => {
extensionAttributes.push({
type,
name,
attribute: {
...defaultAttribute,
...attribute,
},
})
2020-10-22 05:55:14 +08:00
})
})
})
})
nodeAndMarkExtensions.forEach(extension => {
2021-04-16 03:14:33 +08:00
const context = {
options: extension.options,
2021-04-16 03:14:33 +08:00
}
const addAttributes = getExtensionField<NodeConfig['addAttributes'] | MarkConfig['addAttributes']>(
extension,
'addAttributes',
context,
)
2021-04-16 03:14:33 +08:00
if (!addAttributes) {
2021-02-19 17:54:47 +08:00
return
}
2021-04-16 03:14:33 +08:00
// TODO: remove `as Attributes`
const attributes = addAttributes() as Attributes
2020-10-22 15:42:28 +08:00
Object
.entries(attributes)
.forEach(([name, attribute]) => {
extensionAttributes.push({
2021-04-16 03:14:33 +08:00
type: getExtensionField(extension, 'name'),
2020-10-22 15:42:28 +08:00
name,
attribute: {
...defaultAttribute,
...attribute,
},
})
})
})
2020-10-22 15:42:28 +08:00
return extensionAttributes
}