tiptap/packages/core/src/Extension.ts

109 lines
2.1 KiB
TypeScript
Raw Normal View History

2020-10-22 18:34:49 +08:00
import { Plugin } from 'prosemirror-state'
2020-10-22 15:14:24 +08:00
import { Editor } from './Editor'
2020-10-22 05:55:14 +08:00
import { GlobalAttributes } from './types'
2020-11-14 16:23:47 +08:00
export interface ExtensionSpec<Options = any, Commands = {}> {
2020-10-23 16:59:26 +08:00
/**
* Name
*/
name?: string,
2020-10-22 18:34:49 +08:00
/**
* Default options
*/
2020-10-21 21:17:05 +08:00
defaultOptions?: Options,
2020-10-22 18:34:49 +08:00
/**
* Global attributes
*/
2020-10-23 05:21:52 +08:00
addGlobalAttributes?: (this: {
options: Options,
}) => GlobalAttributes,
2020-10-22 18:34:49 +08:00
/**
* Commands
*/
2020-10-22 17:14:44 +08:00
addCommands?: (this: {
2020-10-21 21:17:05 +08:00
options: Options,
2020-10-22 15:14:24 +08:00
editor: Editor,
}) => Commands,
2020-10-22 18:34:49 +08:00
/**
* Keyboard shortcuts
*/
2020-10-22 17:14:44 +08:00
addKeyboardShortcuts?: (this: {
2020-10-22 15:42:28 +08:00
options: Options,
editor: Editor,
}) => {
[key: string]: any
},
2020-10-22 18:34:49 +08:00
/**
* Input rules
*/
addInputRules?: (this: {
options: Options,
editor: Editor,
}) => any[],
/**
* Paste rules
*/
addPasteRules?: (this: {
options: Options,
editor: Editor,
}) => any[],
/**
* ProseMirror plugins
*/
addProseMirrorPlugins?: (this: {
options: Options,
editor: Editor,
}) => Plugin[],
2020-10-21 21:17:05 +08:00
}
2020-09-24 06:29:05 +08:00
2020-11-16 06:25:25 +08:00
export class Extension<Options = any, Commands = any> {
config: Required<ExtensionSpec> = {
name: 'extension',
defaultOptions: {},
addGlobalAttributes: () => [],
addCommands: () => ({}),
addKeyboardShortcuts: () => ({}),
addInputRules: () => [],
addPasteRules: () => [],
addProseMirrorPlugins: () => [],
}
2020-09-09 05:44:45 +08:00
2020-11-16 06:25:25 +08:00
options!: Options
constructor(config: ExtensionSpec<Options, Commands>) {
this.config = {
...this.config,
2020-10-21 21:17:05 +08:00
...config,
2020-11-16 06:25:25 +08:00
}
this.options = this.config.defaultOptions
2020-09-09 05:44:45 +08:00
}
2020-11-16 06:25:25 +08:00
static create<O, C>(config: ExtensionSpec<O, C>) {
return new Extension<O, C>(config)
}
2020-04-13 20:03:39 +08:00
2020-11-16 06:25:25 +08:00
set(options: Options) {
this.options = {
...this.config.defaultOptions,
...options,
2020-10-21 21:17:05 +08:00
}
2020-11-16 16:43:17 +08:00
return this
2019-12-17 06:20:05 +08:00
}
2020-11-16 06:25:25 +08:00
extend<ExtendedOptions = Options, ExtendedCommands = Commands>(extendedConfig: Partial<ExtensionSpec<ExtendedOptions, ExtendedCommands>>) {
return new Extension<ExtendedOptions, ExtendedCommands>({
...this.config,
...extendedConfig,
} as ExtensionSpec<ExtendedOptions, ExtendedCommands>)
}
2019-12-17 06:20:05 +08:00
}