tiptap/packages/core/src/Editor.ts

430 lines
10 KiB
TypeScript
Raw Normal View History

2020-08-22 05:35:15 +08:00
import { EditorState, Plugin, Transaction } from 'prosemirror-state'
2020-09-24 06:29:05 +08:00
import { EditorView } from 'prosemirror-view'
2020-09-24 06:37:31 +08:00
import { Schema, DOMParser } from 'prosemirror-model'
2020-03-11 17:23:28 +08:00
import magicMethods from './utils/magicMethods'
2019-12-17 06:51:18 +08:00
import elementFromString from './utils/elementFromString'
2020-03-30 17:25:07 +08:00
import nodeIsActive from './utils/nodeIsActive'
2020-03-30 20:42:10 +08:00
import markIsActive from './utils/markIsActive'
2020-04-11 17:45:41 +08:00
import getNodeAttrs from './utils/getNodeAttrs'
2020-03-30 20:42:10 +08:00
import getMarkAttrs from './utils/getMarkAttrs'
2020-03-31 19:06:34 +08:00
import removeElement from './utils/removeElement'
2020-10-23 05:21:52 +08:00
import getSchemaTypeNameByName from './utils/getSchemaTypeNameByName'
2020-10-29 00:20:38 +08:00
import getHTMLFromFragment from './utils/getHTMLFromFragment'
2020-09-30 23:12:17 +08:00
import createStyleTag from './utils/createStyleTag'
2020-09-23 03:25:32 +08:00
import CommandManager from './CommandManager'
2020-03-06 04:05:01 +08:00
import ExtensionManager from './ExtensionManager'
2020-04-02 03:15:23 +08:00
import EventEmitter from './EventEmitter'
2020-10-23 04:40:40 +08:00
import { Extensions, UnionToIntersection, PickValue } from './types'
2020-10-23 16:44:30 +08:00
import * as extensions from './extensions'
2020-09-30 23:12:17 +08:00
import style from './style'
2020-08-21 05:25:55 +08:00
2020-09-21 05:19:27 +08:00
export type Command = (props: {
2020-09-22 21:22:24 +08:00
editor: Editor,
tr: Transaction,
commands: SingleCommands,
2020-11-02 21:29:58 +08:00
can: () => SingleCommands & { chain: () => ChainedCommands },
chain: () => ChainedCommands,
2020-09-22 05:17:30 +08:00
state: EditorState,
view: EditorView,
2020-11-02 21:46:18 +08:00
dispatch: ((args?: any) => any) | undefined,
2020-09-21 05:19:27 +08:00
}) => boolean
2020-04-11 04:59:09 +08:00
2020-09-23 05:34:18 +08:00
export type CommandSpec = (...args: any[]) => Command
export interface CommandsSpec {
[key: string]: CommandSpec
2020-04-02 20:34:07 +08:00
}
2019-12-17 06:20:05 +08:00
2020-10-23 04:40:40 +08:00
export interface AllExtensions {}
2020-09-22 03:40:44 +08:00
2020-10-23 16:48:10 +08:00
export type AllCommands = UnionToIntersection<ReturnType<PickValue<ReturnType<AllExtensions[keyof AllExtensions]>, 'addCommands'>>>
2020-09-22 16:49:38 +08:00
export type SingleCommands = {
2020-10-23 16:48:10 +08:00
[Item in keyof AllCommands]: AllCommands[Item] extends (...args: any[]) => any
? (...args: Parameters<AllCommands[Item]>) => boolean
2020-09-22 16:49:38 +08:00
: never
}
2020-09-22 03:40:44 +08:00
export type ChainedCommands = {
2020-10-23 16:48:10 +08:00
[Item in keyof AllCommands]: AllCommands[Item] extends (...args: any[]) => any
? (...args: Parameters<AllCommands[Item]>) => ChainedCommands
2020-09-22 03:40:44 +08:00
: never
} & {
run: () => boolean
}
2020-04-11 04:59:09 +08:00
2020-09-22 03:40:44 +08:00
type EditorContent = string | JSON | null
2020-09-12 00:06:13 +08:00
interface HTMLElement {
editor?: Editor
}
2020-04-14 16:13:27 +08:00
interface EditorOptions {
2020-04-27 05:21:27 +08:00
element: Element,
2020-08-22 03:01:41 +08:00
content: EditorContent,
2020-10-23 16:44:30 +08:00
extensions: Extensions,
2020-08-22 03:53:45 +08:00
injectCSS: boolean,
2020-08-22 03:01:41 +08:00
autoFocus: 'start' | 'end' | number | boolean | null,
2020-08-22 03:53:45 +08:00
editable: boolean,
2019-12-08 07:16:44 +08:00
}
2019-12-17 06:20:05 +08:00
2020-09-22 16:49:38 +08:00
declare module './Editor' {
interface Editor extends SingleCommands {}
}
2020-03-11 17:02:47 +08:00
@magicMethods
2020-03-06 06:59:48 +08:00
export class Editor extends EventEmitter {
2019-12-08 07:16:44 +08:00
2020-08-18 16:06:08 +08:00
private proxy!: Editor
2020-09-24 06:29:05 +08:00
2020-09-23 03:25:32 +08:00
private commandManager!: CommandManager
2020-09-24 06:29:05 +08:00
2020-08-18 15:36:37 +08:00
private extensionManager!: ExtensionManager
2020-09-24 06:29:05 +08:00
2020-08-18 15:36:37 +08:00
private css!: HTMLStyleElement
2020-09-24 06:29:05 +08:00
2020-08-18 15:36:37 +08:00
public schema!: Schema
2020-09-24 06:29:05 +08:00
2020-08-18 15:36:37 +08:00
public view!: EditorView
2020-09-24 06:29:05 +08:00
2020-08-18 15:36:37 +08:00
public selection = { from: 0, to: 0 }
2020-09-24 06:29:05 +08:00
2020-08-22 04:08:54 +08:00
public isFocused = false
2020-09-24 06:29:05 +08:00
2020-08-18 15:41:31 +08:00
public options: EditorOptions = {
2020-04-11 20:33:58 +08:00
element: document.createElement('div'),
2020-03-05 05:40:08 +08:00
content: '',
injectCSS: true,
2020-03-06 03:30:58 +08:00
extensions: [],
2020-08-21 23:44:02 +08:00
autoFocus: false,
2020-08-22 03:53:45 +08:00
editable: true,
2020-03-05 05:40:08 +08:00
}
2020-08-11 22:57:11 +08:00
2020-04-14 16:13:27 +08:00
constructor(options: Partial<EditorOptions> = {}) {
2020-03-06 06:59:48 +08:00
super()
2020-03-05 05:40:08 +08:00
this.options = { ...this.options, ...options }
2020-08-22 05:43:08 +08:00
this.on('createdProxy', this.init)
2020-04-01 04:17:54 +08:00
}
2020-08-11 22:57:11 +08:00
2020-08-22 05:35:15 +08:00
/**
* This method is called after the proxy is initialized.
*/
2020-04-01 04:17:54 +08:00
private init() {
2020-09-23 14:59:21 +08:00
this.createCommandManager()
2020-03-06 04:49:53 +08:00
this.createExtensionManager()
this.createSchema()
this.createView()
2020-09-30 23:12:17 +08:00
this.injectCSS()
2020-09-03 21:11:55 +08:00
2020-10-03 03:57:46 +08:00
window.setTimeout(() => this.proxy.focus(this.options.autoFocus), 0)
2019-12-08 07:16:44 +08:00
}
2020-08-22 05:35:15 +08:00
/**
* A magic method to call commands.
2020-09-03 21:11:55 +08:00
*
2020-08-22 05:35:15 +08:00
* @param name The name of the command
*/
2020-09-24 15:35:18 +08:00
// eslint-disable-next-line
2020-08-18 15:36:37 +08:00
private __get(name: string) {
2020-09-23 03:25:32 +08:00
return this.commandManager.runSingleCommand(name)
2020-09-21 05:19:27 +08:00
}
2020-09-23 03:25:32 +08:00
/**
* Create a command chain to call multiple commands at once.
*/
2020-09-21 05:19:27 +08:00
public chain() {
2020-09-23 03:25:32 +08:00
return this.commandManager.createChain()
2020-09-22 00:40:32 +08:00
}
2020-11-03 00:18:12 +08:00
/**
* Check if a command or a command chain can be executed. Without executing it.
*/
public can() {
return this.commandManager.createCan()
}
2020-09-30 23:12:17 +08:00
/**
* Inject CSS styles.
*/
private injectCSS() {
if (this.options.injectCSS && document) {
this.css = createStyleTag(style)
}
}
2020-08-22 05:35:15 +08:00
/**
* Update editor options.
2020-09-03 21:11:55 +08:00
*
2020-08-22 05:35:15 +08:00
* @param options A list of options
*/
2020-08-22 03:53:45 +08:00
public setOptions(options: Partial<EditorOptions> = {}) {
this.options = { ...this.options, ...options }
2020-10-01 04:43:58 +08:00
if (this.view && this.state && !this.isDestroyed) {
2020-08-22 03:53:45 +08:00
this.view.updateState(this.state)
}
}
2020-09-03 21:11:55 +08:00
2020-08-22 05:35:15 +08:00
/**
* Returns whether the editor is editable.
*/
2020-08-22 04:08:54 +08:00
public get isEditable() {
return this.view && this.view.editable
}
2020-08-22 05:35:15 +08:00
/**
* Returns the editor state.
*/
2020-03-29 07:21:28 +08:00
public get state() {
return this.view.state
}
2020-08-22 05:35:15 +08:00
/**
* Register a list of commands.
2020-09-03 21:11:55 +08:00
*
2020-08-22 05:35:15 +08:00
* @param commands A list of commands
*/
2020-09-23 05:34:18 +08:00
public registerCommands(commands: CommandsSpec) {
2020-08-22 03:44:34 +08:00
Object
.entries(commands)
.forEach(([name, command]) => this.registerCommand(name, command))
}
2020-08-22 05:35:15 +08:00
/**
* Register a command.
2020-09-03 21:11:55 +08:00
*
2020-08-22 05:35:15 +08:00
* @param name The name of your command
* @param callback The method of your command
*/
2020-09-23 05:34:18 +08:00
public registerCommand(name: string, callback: CommandSpec): Editor {
2020-09-23 14:59:21 +08:00
this.commandManager.registerCommand(name, callback)
2020-09-21 05:19:27 +08:00
2020-03-11 17:02:47 +08:00
return this.proxy
2020-03-11 06:19:41 +08:00
}
2020-08-22 05:35:15 +08:00
/**
* Register a ProseMirror plugin.
2020-09-03 21:11:55 +08:00
*
2020-08-22 05:35:15 +08:00
* @param plugin A ProseMirror plugin
* @param handlePlugins Control how to merge the plugin into the existing plugins.
*/
2020-09-24 06:29:05 +08:00
public registerPlugin(plugin: Plugin, handlePlugins?: (newPlugin: Plugin, plugins: Plugin[]) => Plugin[]) {
const plugins = typeof handlePlugins === 'function'
? handlePlugins(plugin, this.state.plugins)
: [plugin, ...this.state.plugins]
2020-04-11 03:43:23 +08:00
const state = this.state.reconfigure({ plugins })
2020-04-11 03:43:23 +08:00
this.view.updateState(state)
}
2020-08-22 05:35:15 +08:00
/**
* Unregister a ProseMirror plugin.
2020-09-03 21:11:55 +08:00
*
2020-08-22 05:35:15 +08:00
* @param name The plugins name
*/
2020-04-11 04:55:14 +08:00
public unregisterPlugin(name: string) {
const state = this.state.reconfigure({
// @ts-ignore
plugins: this.state.plugins.filter(plugin => !plugin.key.startsWith(`${name}$`)),
})
this.view.updateState(state)
}
2020-08-22 05:35:15 +08:00
/**
* Creates an extension manager.
*/
2020-03-06 04:49:53 +08:00
private createExtensionManager() {
2020-10-23 16:44:30 +08:00
const coreExtensions = Object.entries(extensions).map(([, extension]) => extension())
2020-11-03 06:26:41 +08:00
const allExtensions = [...this.options.extensions, ...coreExtensions]
2020-10-23 16:44:30 +08:00
this.extensionManager = new ExtensionManager(allExtensions, this.proxy)
2019-12-08 07:16:44 +08:00
}
2020-09-23 03:25:32 +08:00
/**
* Creates an command manager.
*/
private createCommandManager() {
2020-09-23 14:59:21 +08:00
this.commandManager = new CommandManager(this.proxy)
2020-09-23 03:25:32 +08:00
}
2020-08-22 05:35:15 +08:00
/**
* Creates a ProseMirror schema.
*/
2020-03-06 04:05:01 +08:00
private createSchema() {
2020-09-10 06:09:05 +08:00
this.schema = this.extensionManager.schema
2020-03-06 04:05:01 +08:00
}
2020-08-22 05:35:15 +08:00
/**
* Creates a ProseMirror view.
*/
2019-12-08 07:16:44 +08:00
private createView() {
2020-04-11 20:33:58 +08:00
this.view = new EditorView(this.options.element, {
2020-11-04 22:31:42 +08:00
dispatchTransaction: this.dispatchTransaction.bind(this),
2020-03-06 04:49:53 +08:00
state: EditorState.create({
doc: this.createDocument(this.options.content),
}),
})
// `editor.view` is not yet available at this time.
2020-11-04 22:31:42 +08:00
// Therefore we will add all plugins and node views directly afterwards.
const newState = this.state.reconfigure({
plugins: this.extensionManager.plugins,
})
this.view.updateState(newState)
this.view.setProps({
2020-04-24 15:32:37 +08:00
nodeViews: this.extensionManager.nodeViews,
2019-12-08 07:16:44 +08:00
})
2020-09-12 00:06:13 +08:00
// Lets store the editor instance in the DOM element.
// So well have access to it for tests.
2020-09-12 00:06:13 +08:00
const dom = this.view.dom as HTMLElement
dom.editor = this.proxy
2019-12-08 07:16:44 +08:00
}
2020-08-22 05:35:15 +08:00
/**
* Creates a ProseMirror document.
*/
2020-03-30 04:24:51 +08:00
public createDocument = (content: EditorContent, parseOptions: any = {}): any => {
2020-03-29 07:21:28 +08:00
if (content && typeof content === 'object') {
2020-03-29 07:11:10 +08:00
try {
return this.schema.nodeFromJSON(content)
} catch (error) {
console.warn('[tiptap warn]: Invalid content.', 'Passed value:', content, 'Error:', error)
return this.createDocument('')
}
}
2019-12-08 07:16:44 +08:00
if (typeof content === 'string') {
2019-12-17 06:51:18 +08:00
return DOMParser
.fromSchema(this.schema)
2020-03-05 05:47:50 +08:00
.parse(elementFromString(content), parseOptions)
2019-12-08 07:16:44 +08:00
}
2020-03-29 07:21:28 +08:00
return this.createDocument('')
}
2020-08-22 05:35:15 +08:00
/**
* Store the current selection.
*/
2020-03-29 07:21:28 +08:00
private storeSelection() {
const { from, to } = this.state.selection
this.selection = { from, to }
2019-12-08 07:16:44 +08:00
}
2020-08-22 05:35:15 +08:00
/**
* The callback over which to send transactions (state updates) produced by the view.
2020-09-03 21:11:55 +08:00
*
2020-08-22 05:35:15 +08:00
* @param transaction An editor state transaction
*/
private dispatchTransaction(transaction: Transaction) {
2020-03-05 05:40:08 +08:00
const state = this.state.apply(transaction)
this.view.updateState(state)
2020-03-29 07:21:28 +08:00
this.storeSelection()
2020-03-30 03:04:56 +08:00
this.emit('transaction', { transaction })
2020-08-11 22:57:11 +08:00
2019-12-08 07:16:44 +08:00
if (!transaction.docChanged || transaction.getMeta('preventUpdate')) {
return
}
2020-03-30 03:04:56 +08:00
this.emit('update', { transaction })
2019-12-08 07:16:44 +08:00
}
2019-12-17 06:51:18 +08:00
2020-08-22 05:35:15 +08:00
/**
* Get attributes of the currently selected node.
2020-09-03 21:11:55 +08:00
*
2020-08-22 05:35:15 +08:00
* @param name Name of the node
*/
2020-04-11 17:45:41 +08:00
public getNodeAttrs(name: string) {
return getNodeAttrs(this.state, this.schema.nodes[name])
}
2020-08-22 05:35:15 +08:00
/**
* Get attributes of the currently selected mark.
2020-09-03 21:11:55 +08:00
*
2020-08-22 05:35:15 +08:00
* @param name Name of the mark
*/
2020-04-02 03:41:53 +08:00
public getMarkAttrs(name: string) {
2020-03-31 18:53:52 +08:00
return getMarkAttrs(this.state, this.schema.marks[name])
}
2020-03-30 20:49:48 +08:00
2020-08-22 05:35:15 +08:00
/**
* Returns if the currently selected node or mark is active.
2020-09-03 21:11:55 +08:00
*
2020-08-22 05:35:15 +08:00
* @param name Name of the node or mark
* @param attrs Attributes of the node or mark
*/
2020-04-02 03:41:53 +08:00
public isActive(name: string, attrs = {}) {
2020-10-23 05:21:52 +08:00
const schemaType = getSchemaTypeNameByName(name, this.schema)
2020-03-30 20:49:48 +08:00
2020-03-31 18:53:52 +08:00
if (schemaType === 'node') {
return nodeIsActive(this.state, this.schema.nodes[name], attrs)
2020-09-24 06:29:05 +08:00
} if (schemaType === 'mark') {
2020-10-05 23:12:57 +08:00
return markIsActive(this.state, this.schema.marks[name], attrs)
2020-03-31 18:53:52 +08:00
}
2020-03-30 20:42:10 +08:00
2020-03-31 18:53:52 +08:00
return false
2020-03-06 04:49:53 +08:00
}
2020-03-09 06:25:48 +08:00
// public setParentComponent(component = null) {
// if (!component) {
// return
// }
// this.view.setProps({
// nodeViews: this.initNodeViews({
// parent: component,
// extensions: [
// ...this.builtInExtensions,
// ...this.options.extensions,
// ],
// }),
// })
// }
2020-08-22 05:35:15 +08:00
/**
* Get the document as JSON.
*/
public getJSON() {
2020-03-04 17:21:48 +08:00
return this.state.doc.toJSON()
}
2020-08-22 05:35:15 +08:00
/**
* Get the document as HTML.
*/
public getHTML() {
2020-10-29 00:20:38 +08:00
return getHTMLFromFragment(this.state.doc, this.schema)
2020-03-04 17:21:48 +08:00
}
2020-03-05 04:45:49 +08:00
2020-10-23 20:28:25 +08:00
/**
* Check if there is no content.
*/
public isEmpty() {
return !this.state.doc.textContent.length
}
2020-08-22 05:35:15 +08:00
/**
* Destroy the editor.
*/
2020-03-05 04:45:49 +08:00
public destroy() {
2020-03-31 19:07:57 +08:00
if (this.view) {
this.view.destroy()
2020-03-05 04:45:49 +08:00
}
2020-03-06 06:59:48 +08:00
this.removeAllListeners()
2020-03-31 19:06:34 +08:00
removeElement(this.css)
2020-03-05 04:45:49 +08:00
}
2020-09-24 06:29:05 +08:00
2020-10-01 04:43:58 +08:00
/**
* Check if the editor is already destroyed.
*/
private get isDestroyed() {
// @ts-ignore
return !this.view?.docView
}
2019-12-08 07:16:44 +08:00
}