UNPKG

@tiptap/core

Version:

headless rich text editor

1 lines 413 kB
{"version":3,"sources":["../src/index.ts","../src/helpers/createChainableState.ts","../src/CommandManager.ts","../src/Editor.ts","../src/EventEmitter.ts","../src/ExtensionManager.ts","../src/helpers/combineTransactionSteps.ts","../src/helpers/createNodeFromContent.ts","../src/utilities/elementFromString.ts","../src/helpers/createDocument.ts","../src/helpers/defaultBlockAt.ts","../src/helpers/findChildren.ts","../src/helpers/findChildrenInRange.ts","../src/helpers/findParentNodeClosestToPos.ts","../src/helpers/findParentNode.ts","../src/helpers/getExtensionField.ts","../src/helpers/flattenExtensions.ts","../src/helpers/generateHTML.ts","../src/helpers/getHTMLFromFragment.ts","../src/helpers/getSchemaByResolvedExtensions.ts","../src/utilities/isFunction.ts","../src/utilities/callOrReturn.ts","../src/utilities/isEmptyObject.ts","../src/helpers/splitExtensions.ts","../src/helpers/getAttributesFromExtensions.ts","../src/utilities/mergeAttributes.ts","../src/helpers/getRenderedAttributes.ts","../src/utilities/fromString.ts","../src/helpers/injectExtensionAttributesToParseRule.ts","../src/utilities/findDuplicates.ts","../src/helpers/sortExtensions.ts","../src/helpers/resolveExtensions.ts","../src/helpers/getSchema.ts","../src/helpers/generateJSON.ts","../src/helpers/generateText.ts","../src/helpers/getTextBetween.ts","../src/helpers/getText.ts","../src/helpers/getTextSerializersFromSchema.ts","../src/helpers/getMarkType.ts","../src/helpers/getMarkAttributes.ts","../src/helpers/getNodeType.ts","../src/helpers/getNodeAttributes.ts","../src/helpers/getSchemaTypeNameByName.ts","../src/helpers/getAttributes.ts","../src/utilities/removeDuplicates.ts","../src/helpers/getChangedRanges.ts","../src/helpers/getDebugJSON.ts","../src/utilities/isRegExp.ts","../src/utilities/objectIncludes.ts","../src/helpers/getMarkRange.ts","../src/helpers/getMarksBetween.ts","../src/helpers/getNodeAtPosition.ts","../src/helpers/getSchemaTypeByName.ts","../src/helpers/getSplittedAttributes.ts","../src/helpers/getTextContentFromNodes.ts","../src/helpers/isMarkActive.ts","../src/helpers/isNodeActive.ts","../src/helpers/isActive.ts","../src/helpers/isAtEndOfNode.ts","../src/helpers/isAtStartOfNode.ts","../src/helpers/isExtensionRulesEnabled.ts","../src/helpers/isList.ts","../src/helpers/isNodeEmpty.ts","../src/helpers/isNodeSelection.ts","../src/helpers/isTextSelection.ts","../src/utilities/minMax.ts","../src/helpers/posToDOMRect.ts","../src/helpers/resolveFocusPosition.ts","../src/helpers/rewriteUnknownContent.ts","../src/helpers/selectionToInsertionEnd.ts","../src/InputRule.ts","../src/utilities/isPlainObject.ts","../src/utilities/mergeDeep.ts","../src/Extendable.ts","../src/Mark.ts","../src/PasteRule.ts","../src/utilities/isNumber.ts","../src/extensions/index.ts","../src/extensions/clipboardTextSerializer.ts","../src/Extension.ts","../src/commands/index.ts","../src/commands/blur.ts","../src/commands/clearContent.ts","../src/commands/clearNodes.ts","../src/commands/command.ts","../src/commands/createParagraphNear.ts","../src/commands/cut.ts","../src/commands/deleteCurrentNode.ts","../src/commands/deleteNode.ts","../src/commands/deleteRange.ts","../src/commands/deleteSelection.ts","../src/commands/enter.ts","../src/commands/exitCode.ts","../src/commands/extendMarkRange.ts","../src/commands/first.ts","../src/utilities/isAndroid.ts","../src/utilities/isiOS.ts","../src/commands/focus.ts","../src/commands/forEach.ts","../src/commands/insertContent.ts","../src/commands/insertContentAt.ts","../src/commands/join.ts","../src/commands/joinItemBackward.ts","../src/commands/joinItemForward.ts","../src/commands/joinTextblockBackward.ts","../src/commands/joinTextblockForward.ts","../src/utilities/isMacOS.ts","../src/commands/keyboardShortcut.ts","../src/commands/lift.ts","../src/commands/liftEmptyBlock.ts","../src/commands/liftListItem.ts","../src/commands/newlineInCode.ts","../src/utilities/deleteProps.ts","../src/commands/resetAttributes.ts","../src/commands/scrollIntoView.ts","../src/commands/selectAll.ts","../src/commands/selectNodeBackward.ts","../src/commands/selectNodeForward.ts","../src/commands/selectParentNode.ts","../src/commands/selectTextblockEnd.ts","../src/commands/selectTextblockStart.ts","../src/commands/setContent.ts","../src/commands/setMark.ts","../src/commands/setMeta.ts","../src/commands/setNode.ts","../src/commands/setNodeSelection.ts","../src/commands/setTextSelection.ts","../src/commands/sinkListItem.ts","../src/commands/splitBlock.ts","../src/commands/splitListItem.ts","../src/commands/toggleList.ts","../src/commands/toggleMark.ts","../src/commands/toggleNode.ts","../src/commands/toggleWrap.ts","../src/commands/undoInputRule.ts","../src/commands/unsetAllMarks.ts","../src/commands/unsetMark.ts","../src/commands/updateAttributes.ts","../src/commands/wrapIn.ts","../src/commands/wrapInList.ts","../src/extensions/commands.ts","../src/extensions/delete.ts","../src/extensions/drop.ts","../src/extensions/editable.ts","../src/extensions/focusEvents.ts","../src/extensions/keymap.ts","../src/extensions/paste.ts","../src/extensions/tabindex.ts","../src/NodePos.ts","../src/style.ts","../src/utilities/createStyleTag.ts","../src/inputRules/markInputRule.ts","../src/inputRules/nodeInputRule.ts","../src/inputRules/textblockTypeInputRule.ts","../src/inputRules/textInputRule.ts","../src/inputRules/wrappingInputRule.ts","../src/jsx-runtime.ts","../src/utilities/canInsertNode.ts","../src/utilities/escapeForRegEx.ts","../src/utilities/isString.ts","../src/MarkView.ts","../src/Node.ts","../src/NodeView.ts","../src/pasteRules/markPasteRule.ts","../src/pasteRules/nodePasteRule.ts","../src/pasteRules/textPasteRule.ts","../src/Tracker.ts"],"sourcesContent":["export * from './CommandManager.js'\nexport * from './Editor.js'\nexport * from './Extension.js'\nexport * as extensions from './extensions/index.js'\nexport * from './helpers/index.js'\nexport * from './InputRule.js'\nexport * from './inputRules/index.js'\nexport { createElement, Fragment, createElement as h } from './jsx-runtime.js'\nexport * from './Mark.js'\nexport * from './MarkView.js'\nexport * from './Node.js'\nexport * from './NodePos.js'\nexport * from './NodeView.js'\nexport * from './PasteRule.js'\nexport * from './pasteRules/index.js'\nexport * from './Tracker.js'\nexport * from './types.js'\nexport * from './utilities/index.js'\n\n// eslint-disable-next-line\nexport interface Commands<ReturnType = any> {}\n\n// eslint-disable-next-line\nexport interface Storage {}\n","import type { EditorState, Transaction } from '@tiptap/pm/state'\n\n/**\n * Takes a Transaction & Editor State and turns it into a chainable state object\n * @param config The transaction and state to create the chainable state from\n * @returns A chainable Editor state object\n */\nexport function createChainableState(config: { transaction: Transaction; state: EditorState }): EditorState {\n const { state, transaction } = config\n let { selection } = transaction\n let { doc } = transaction\n let { storedMarks } = transaction\n\n return {\n ...state,\n apply: state.apply.bind(state),\n applyTransaction: state.applyTransaction.bind(state),\n plugins: state.plugins,\n schema: state.schema,\n reconfigure: state.reconfigure.bind(state),\n toJSON: state.toJSON.bind(state),\n get storedMarks() {\n return storedMarks\n },\n get selection() {\n return selection\n },\n get doc() {\n return doc\n },\n get tr() {\n selection = transaction.selection\n doc = transaction.doc\n storedMarks = transaction.storedMarks\n\n return transaction\n },\n }\n}\n","import type { EditorState, Transaction } from '@tiptap/pm/state'\n\nimport type { Editor } from './Editor.js'\nimport { createChainableState } from './helpers/createChainableState.js'\nimport type { AnyCommands, CanCommands, ChainedCommands, CommandProps, SingleCommands } from './types.js'\n\nexport class CommandManager {\n editor: Editor\n\n rawCommands: AnyCommands\n\n customState?: EditorState\n\n constructor(props: { editor: Editor; state?: EditorState }) {\n this.editor = props.editor\n this.rawCommands = this.editor.extensionManager.commands\n this.customState = props.state\n }\n\n get hasCustomState(): boolean {\n return !!this.customState\n }\n\n get state(): EditorState {\n return this.customState || this.editor.state\n }\n\n get commands(): SingleCommands {\n const { rawCommands, editor, state } = this\n const { view } = editor\n const { tr } = state\n const props = this.buildProps(tr)\n\n return Object.fromEntries(\n Object.entries(rawCommands).map(([name, command]) => {\n const method = (...args: any[]) => {\n const callback = command(...args)(props)\n\n if (!tr.getMeta('preventDispatch') && !this.hasCustomState) {\n view.dispatch(tr)\n }\n\n return callback\n }\n\n return [name, method]\n }),\n ) as unknown as SingleCommands\n }\n\n get chain(): () => ChainedCommands {\n return () => this.createChain()\n }\n\n get can(): () => CanCommands {\n return () => this.createCan()\n }\n\n public createChain(startTr?: Transaction, shouldDispatch = true): ChainedCommands {\n const { rawCommands, editor, state } = this\n const { view } = editor\n const callbacks: boolean[] = []\n const hasStartTransaction = !!startTr\n const tr = startTr || state.tr\n\n const run = () => {\n if (!hasStartTransaction && shouldDispatch && !tr.getMeta('preventDispatch') && !this.hasCustomState) {\n view.dispatch(tr)\n }\n\n return callbacks.every(callback => callback === true)\n }\n\n const chain = {\n ...Object.fromEntries(\n Object.entries(rawCommands).map(([name, command]) => {\n const chainedCommand = (...args: never[]) => {\n const props = this.buildProps(tr, shouldDispatch)\n const callback = command(...args)(props)\n\n callbacks.push(callback)\n\n return chain\n }\n\n return [name, chainedCommand]\n }),\n ),\n run,\n } as unknown as ChainedCommands\n\n return chain\n }\n\n public createCan(startTr?: Transaction): CanCommands {\n const { rawCommands, state } = this\n const dispatch = false\n const tr = startTr || state.tr\n const props = this.buildProps(tr, dispatch)\n const formattedCommands = Object.fromEntries(\n Object.entries(rawCommands).map(([name, command]) => {\n return [name, (...args: never[]) => command(...args)({ ...props, dispatch: undefined })]\n }),\n ) as unknown as SingleCommands\n\n return {\n ...formattedCommands,\n chain: () => this.createChain(tr, dispatch),\n } as CanCommands\n }\n\n public buildProps(tr: Transaction, shouldDispatch = true): CommandProps {\n const { rawCommands, editor, state } = this\n const { view } = editor\n\n const props: CommandProps = {\n tr,\n editor,\n view,\n state: createChainableState({\n state,\n transaction: tr,\n }),\n dispatch: shouldDispatch ? () => undefined : undefined,\n chain: () => this.createChain(tr, shouldDispatch),\n can: () => this.createCan(tr),\n get commands() {\n return Object.fromEntries(\n Object.entries(rawCommands).map(([name, command]) => {\n return [name, (...args: never[]) => command(...args)(props)]\n }),\n ) as unknown as SingleCommands\n },\n }\n\n return props\n }\n}\n","/* eslint-disable @typescript-eslint/no-empty-object-type */\nimport type { MarkType, Node as ProseMirrorNode, NodeType, Schema } from '@tiptap/pm/model'\nimport type { Plugin, PluginKey, Transaction } from '@tiptap/pm/state'\nimport { EditorState } from '@tiptap/pm/state'\nimport { EditorView } from '@tiptap/pm/view'\n\nimport { CommandManager } from './CommandManager.js'\nimport { EventEmitter } from './EventEmitter.js'\nimport { ExtensionManager } from './ExtensionManager.js'\nimport {\n ClipboardTextSerializer,\n Commands,\n Delete,\n Drop,\n Editable,\n FocusEvents,\n Keymap,\n Paste,\n Tabindex,\n} from './extensions/index.js'\nimport { createDocument } from './helpers/createDocument.js'\nimport { getAttributes } from './helpers/getAttributes.js'\nimport { getHTMLFromFragment } from './helpers/getHTMLFromFragment.js'\nimport { getText } from './helpers/getText.js'\nimport { getTextSerializersFromSchema } from './helpers/getTextSerializersFromSchema.js'\nimport { isActive } from './helpers/isActive.js'\nimport { isNodeEmpty } from './helpers/isNodeEmpty.js'\nimport { resolveFocusPosition } from './helpers/resolveFocusPosition.js'\nimport type { Storage } from './index.js'\nimport { NodePos } from './NodePos.js'\nimport { style } from './style.js'\nimport type {\n CanCommands,\n ChainedCommands,\n DocumentType,\n EditorEvents,\n EditorOptions,\n NodeType as TNodeType,\n SingleCommands,\n TextSerializer,\n TextType as TTextType,\n} from './types.js'\nimport { createStyleTag } from './utilities/createStyleTag.js'\nimport { isFunction } from './utilities/isFunction.js'\n\nexport * as extensions from './extensions/index.js'\n\n// @ts-ignore\nexport interface TiptapEditorHTMLElement extends HTMLElement {\n editor?: Editor\n}\n\nexport class Editor extends EventEmitter<EditorEvents> {\n private commandManager!: CommandManager\n\n public extensionManager!: ExtensionManager\n\n private css: HTMLStyleElement | null = null\n\n public schema!: Schema\n\n private editorView: EditorView | null = null\n\n public isFocused = false\n\n private editorState!: EditorState\n\n /**\n * The editor is considered initialized after the `create` event has been emitted.\n */\n public isInitialized = false\n\n public extensionStorage: Storage = {} as Storage\n\n /**\n * A unique ID for this editor instance.\n */\n public instanceId = Math.random().toString(36).slice(2, 9)\n\n public options: EditorOptions = {\n element: typeof document !== 'undefined' ? document.createElement('div') : null,\n content: '',\n injectCSS: true,\n injectNonce: undefined,\n extensions: [],\n autofocus: false,\n editable: true,\n editorProps: {},\n parseOptions: {},\n coreExtensionOptions: {},\n enableInputRules: true,\n enablePasteRules: true,\n enableCoreExtensions: true,\n enableContentCheck: false,\n emitContentError: false,\n onBeforeCreate: () => null,\n onCreate: () => null,\n onUpdate: () => null,\n onSelectionUpdate: () => null,\n onTransaction: () => null,\n onFocus: () => null,\n onBlur: () => null,\n onDestroy: () => null,\n onContentError: ({ error }) => {\n throw error\n },\n onPaste: () => null,\n onDrop: () => null,\n onDelete: () => null,\n }\n\n constructor(options: Partial<EditorOptions> = {}) {\n super()\n this.setOptions(options)\n this.createExtensionManager()\n this.createCommandManager()\n this.createSchema()\n this.on('beforeCreate', this.options.onBeforeCreate)\n this.emit('beforeCreate', { editor: this })\n this.on('contentError', this.options.onContentError)\n this.on('create', this.options.onCreate)\n this.on('update', this.options.onUpdate)\n this.on('selectionUpdate', this.options.onSelectionUpdate)\n this.on('transaction', this.options.onTransaction)\n this.on('focus', this.options.onFocus)\n this.on('blur', this.options.onBlur)\n this.on('destroy', this.options.onDestroy)\n this.on('drop', ({ event, slice, moved }) => this.options.onDrop(event, slice, moved))\n this.on('paste', ({ event, slice }) => this.options.onPaste(event, slice))\n this.on('delete', this.options.onDelete)\n\n const initialDoc = this.createDoc()\n const selection = resolveFocusPosition(initialDoc, this.options.autofocus)\n\n // Set editor state immediately, so that it's available independently from the view\n this.editorState = EditorState.create({\n doc: initialDoc,\n schema: this.schema,\n selection: selection || undefined,\n })\n\n if (this.options.element) {\n this.mount(this.options.element)\n }\n }\n\n /**\n * Attach the editor to the DOM, creating a new editor view.\n */\n public mount(el: NonNullable<EditorOptions['element']> & {}) {\n if (typeof document === 'undefined') {\n throw new Error(\n `[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.`,\n )\n }\n this.createView(el)\n\n window.setTimeout(() => {\n if (this.isDestroyed) {\n return\n }\n\n this.commands.focus(this.options.autofocus)\n this.emit('create', { editor: this })\n this.isInitialized = true\n }, 0)\n }\n\n /**\n * Remove the editor from the DOM, but still allow remounting at a different point in time\n */\n public unmount() {\n if (this.editorView) {\n // Cleanup our reference to prevent circular references which caused memory leaks\n // @ts-ignore\n const dom = this.editorView.dom as TiptapEditorHTMLElement\n\n if (dom?.editor) {\n delete dom.editor\n }\n this.editorView.destroy()\n }\n this.editorView = null\n this.isInitialized = false\n this.css?.remove()\n this.css = null\n }\n\n /**\n * Returns the editor storage.\n */\n public get storage(): Storage {\n return this.extensionStorage\n }\n\n /**\n * An object of all registered commands.\n */\n public get commands(): SingleCommands {\n return this.commandManager.commands\n }\n\n /**\n * Create a command chain to call multiple commands at once.\n */\n public chain(): ChainedCommands {\n return this.commandManager.chain()\n }\n\n /**\n * Check if a command or a command chain can be executed. Without executing it.\n */\n public can(): CanCommands {\n return this.commandManager.can()\n }\n\n /**\n * Inject CSS styles.\n */\n private injectCSS(): void {\n if (this.options.injectCSS && typeof document !== 'undefined') {\n this.css = createStyleTag(style, this.options.injectNonce)\n }\n }\n\n /**\n * Update editor options.\n *\n * @param options A list of options\n */\n public setOptions(options: Partial<EditorOptions> = {}): void {\n this.options = {\n ...this.options,\n ...options,\n }\n\n if (!this.editorView || !this.state || this.isDestroyed) {\n return\n }\n\n if (this.options.editorProps) {\n this.view.setProps(this.options.editorProps)\n }\n\n this.view.updateState(this.state)\n }\n\n /**\n * Update editable state of the editor.\n */\n public setEditable(editable: boolean, emitUpdate = true): void {\n this.setOptions({ editable })\n\n if (emitUpdate) {\n this.emit('update', { editor: this, transaction: this.state.tr, appendedTransactions: [] })\n }\n }\n\n /**\n * Returns whether the editor is editable.\n */\n public get isEditable(): boolean {\n // since plugins are applied after creating the view\n // `editable` is always `true` for one tick.\n // that’s why we also have to check for `options.editable`\n return this.options.editable && this.view && this.view.editable\n }\n\n /**\n * Returns the editor state.\n */\n public get view(): EditorView {\n if (this.editorView) {\n return this.editorView\n }\n\n return new Proxy(\n {\n state: this.editorState,\n updateState: (state: EditorState): ReturnType<EditorView['updateState']> => {\n this.editorState = state\n },\n dispatch: (tr: Transaction): ReturnType<EditorView['dispatch']> => {\n this.editorState = this.state.apply(tr)\n },\n\n // Stub some commonly accessed properties to prevent errors\n composing: false,\n dragging: null,\n editable: true,\n isDestroyed: false,\n } as EditorView,\n {\n get: (obj, key) => {\n // Specifically always return the most recent editorState\n if (key === 'state') {\n return this.editorState\n }\n if (key in obj) {\n return Reflect.get(obj, key)\n }\n\n // We throw an error here, because we know the view is not available\n throw new Error(\n `[tiptap error]: The editor view is not available. Cannot access view['${key as string}']. The editor may not be mounted yet.`,\n )\n },\n },\n ) as EditorView\n }\n\n /**\n * Returns the editor state.\n */\n public get state(): EditorState {\n if (this.editorView) {\n this.editorState = this.view.state\n }\n\n return this.editorState\n }\n\n /**\n * Register a ProseMirror plugin.\n *\n * @param plugin A ProseMirror plugin\n * @param handlePlugins Control how to merge the plugin into the existing plugins.\n * @returns The new editor state\n */\n public registerPlugin(\n plugin: Plugin,\n handlePlugins?: (newPlugin: Plugin, plugins: Plugin[]) => Plugin[],\n ): EditorState {\n const plugins = isFunction(handlePlugins)\n ? handlePlugins(plugin, [...this.state.plugins])\n : [...this.state.plugins, plugin]\n\n const state = this.state.reconfigure({ plugins })\n\n this.view.updateState(state)\n\n return state\n }\n\n /**\n * Unregister a ProseMirror plugin.\n *\n * @param nameOrPluginKeyToRemove The plugins name\n * @returns The new editor state or undefined if the editor is destroyed\n */\n public unregisterPlugin(\n nameOrPluginKeyToRemove: string | PluginKey | (string | PluginKey)[],\n ): EditorState | undefined {\n if (this.isDestroyed) {\n return undefined\n }\n\n const prevPlugins = this.state.plugins\n let plugins = prevPlugins\n\n ;([] as (string | PluginKey)[]).concat(nameOrPluginKeyToRemove).forEach(nameOrPluginKey => {\n // @ts-ignore\n const name = typeof nameOrPluginKey === 'string' ? `${nameOrPluginKey}$` : nameOrPluginKey.key\n\n // @ts-ignore\n plugins = plugins.filter(plugin => !plugin.key.startsWith(name))\n })\n\n if (prevPlugins.length === plugins.length) {\n // No plugin was removed, so we don’t need to update the state\n return undefined\n }\n\n const state = this.state.reconfigure({\n plugins,\n })\n\n this.view.updateState(state)\n\n return state\n }\n\n /**\n * Creates an extension manager.\n */\n private createExtensionManager(): void {\n const coreExtensions = this.options.enableCoreExtensions\n ? [\n Editable,\n ClipboardTextSerializer.configure({\n blockSeparator: this.options.coreExtensionOptions?.clipboardTextSerializer?.blockSeparator,\n }),\n Commands,\n FocusEvents,\n Keymap,\n Tabindex,\n Drop,\n Paste,\n Delete,\n ].filter(ext => {\n if (typeof this.options.enableCoreExtensions === 'object') {\n return (\n this.options.enableCoreExtensions[ext.name as keyof typeof this.options.enableCoreExtensions] !== false\n )\n }\n return true\n })\n : []\n const allExtensions = [...coreExtensions, ...this.options.extensions].filter(extension => {\n return ['extension', 'node', 'mark'].includes(extension?.type)\n })\n\n this.extensionManager = new ExtensionManager(allExtensions, this)\n }\n\n /**\n * Creates an command manager.\n */\n private createCommandManager(): void {\n this.commandManager = new CommandManager({\n editor: this,\n })\n }\n\n /**\n * Creates a ProseMirror schema.\n */\n private createSchema(): void {\n this.schema = this.extensionManager.schema\n }\n\n /**\n * Creates the initial document.\n */\n private createDoc(): ProseMirrorNode {\n let doc: ProseMirrorNode\n\n try {\n doc = createDocument(this.options.content, this.schema, this.options.parseOptions, {\n errorOnInvalidContent: this.options.enableContentCheck,\n })\n } catch (e) {\n if (\n !(e instanceof Error) ||\n !['[tiptap error]: Invalid JSON content', '[tiptap error]: Invalid HTML content'].includes(e.message)\n ) {\n // Not the content error we were expecting\n throw e\n }\n this.emit('contentError', {\n editor: this,\n error: e as Error,\n disableCollaboration: () => {\n if (\n 'collaboration' in this.storage &&\n typeof this.storage.collaboration === 'object' &&\n this.storage.collaboration\n ) {\n ;(this.storage.collaboration as any).isDisabled = true\n }\n // To avoid syncing back invalid content, reinitialize the extensions without the collaboration extension\n this.options.extensions = this.options.extensions.filter(extension => extension.name !== 'collaboration')\n\n // Restart the initialization process by recreating the extension manager with the new set of extensions\n this.createExtensionManager()\n },\n })\n\n // Content is invalid, but attempt to create it anyway, stripping out the invalid parts\n doc = createDocument(this.options.content, this.schema, this.options.parseOptions, {\n errorOnInvalidContent: false,\n })\n }\n return doc\n }\n\n /**\n * Creates a ProseMirror view.\n */\n private createView(element: NonNullable<EditorOptions['element']> & {}): void {\n this.editorView = new EditorView(element, {\n ...this.options.editorProps,\n attributes: {\n // add `role=\"textbox\"` to the editor element\n role: 'textbox',\n ...this.options.editorProps?.attributes,\n },\n dispatchTransaction: this.dispatchTransaction.bind(this),\n state: this.editorState,\n })\n\n // `editor.view` is not yet available at this time.\n // Therefore we will add all plugins and node views directly afterwards.\n const newState = this.state.reconfigure({\n plugins: this.extensionManager.plugins,\n })\n\n this.view.updateState(newState)\n\n this.createNodeViews()\n this.prependClass()\n this.injectCSS()\n\n // Let’s store the editor instance in the DOM element.\n // So we’ll have access to it for tests.\n // @ts-ignore\n const dom = this.view.dom as TiptapEditorHTMLElement\n\n dom.editor = this\n }\n\n /**\n * Creates all node and mark views.\n */\n public createNodeViews(): void {\n if (this.view.isDestroyed) {\n return\n }\n\n this.view.setProps({\n markViews: this.extensionManager.markViews,\n nodeViews: this.extensionManager.nodeViews,\n })\n }\n\n /**\n * Prepend class name to element.\n */\n public prependClass(): void {\n this.view.dom.className = `tiptap ${this.view.dom.className}`\n }\n\n public isCapturingTransaction = false\n\n private capturedTransaction: Transaction | null = null\n\n public captureTransaction(fn: () => void) {\n this.isCapturingTransaction = true\n fn()\n this.isCapturingTransaction = false\n\n const tr = this.capturedTransaction\n\n this.capturedTransaction = null\n\n return tr\n }\n\n /**\n * The callback over which to send transactions (state updates) produced by the view.\n *\n * @param transaction An editor state transaction\n */\n private dispatchTransaction(transaction: Transaction): void {\n // if the editor / the view of the editor was destroyed\n // the transaction should not be dispatched as there is no view anymore.\n if (this.view.isDestroyed) {\n return\n }\n\n if (this.isCapturingTransaction) {\n if (!this.capturedTransaction) {\n this.capturedTransaction = transaction\n\n return\n }\n\n transaction.steps.forEach(step => this.capturedTransaction?.step(step))\n\n return\n }\n\n // Apply transaction and get resulting state and transactions\n const { state, transactions } = this.state.applyTransaction(transaction)\n const selectionHasChanged = !this.state.selection.eq(state.selection)\n const rootTrWasApplied = transactions.includes(transaction)\n const prevState = this.state\n\n this.emit('beforeTransaction', {\n editor: this,\n transaction,\n nextState: state,\n })\n\n // If transaction was filtered out, we can return early\n if (!rootTrWasApplied) {\n return\n }\n\n this.view.updateState(state)\n\n // Emit transaction event with appended transactions info\n this.emit('transaction', {\n editor: this,\n transaction,\n appendedTransactions: transactions.slice(1),\n })\n\n if (selectionHasChanged) {\n this.emit('selectionUpdate', {\n editor: this,\n transaction,\n })\n }\n\n // Only emit the latest between focus and blur events\n const mostRecentFocusTr = transactions.findLast(tr => tr.getMeta('focus') || tr.getMeta('blur'))\n const focus = mostRecentFocusTr?.getMeta('focus')\n const blur = mostRecentFocusTr?.getMeta('blur')\n\n if (focus) {\n this.emit('focus', {\n editor: this,\n event: focus.event,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n transaction: mostRecentFocusTr!,\n })\n }\n\n if (blur) {\n this.emit('blur', {\n editor: this,\n event: blur.event,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n transaction: mostRecentFocusTr!,\n })\n }\n\n // Compare states for update event\n if (\n transaction.getMeta('preventUpdate') ||\n !transactions.some(tr => tr.docChanged) ||\n prevState.doc.eq(state.doc)\n ) {\n return\n }\n\n this.emit('update', {\n editor: this,\n transaction,\n appendedTransactions: transactions.slice(1),\n })\n }\n\n /**\n * Get attributes of the currently selected node or mark.\n */\n public getAttributes(nameOrType: string | NodeType | MarkType): Record<string, any> {\n return getAttributes(this.state, nameOrType)\n }\n\n /**\n * Returns if the currently selected node or mark is active.\n *\n * @param name Name of the node or mark\n * @param attributes Attributes of the node or mark\n */\n public isActive(name: string, attributes?: {}): boolean\n public isActive(attributes: {}): boolean\n public isActive(nameOrAttributes: string, attributesOrUndefined?: {}): boolean {\n const name = typeof nameOrAttributes === 'string' ? nameOrAttributes : null\n\n const attributes = typeof nameOrAttributes === 'string' ? attributesOrUndefined : nameOrAttributes\n\n return isActive(this.state, name, attributes)\n }\n\n /**\n * Get the document as JSON.\n */\n public getJSON(): DocumentType<\n Record<string, any> | undefined,\n TNodeType<string, undefined | Record<string, any>, any, (TNodeType | TTextType)[]>[]\n > {\n return this.state.doc.toJSON()\n }\n\n /**\n * Get the document as HTML.\n */\n public getHTML(): string {\n return getHTMLFromFragment(this.state.doc.content, this.schema)\n }\n\n /**\n * Get the document as text.\n */\n public getText(options?: { blockSeparator?: string; textSerializers?: Record<string, TextSerializer> }): string {\n const { blockSeparator = '\\n\\n', textSerializers = {} } = options || {}\n\n return getText(this.state.doc, {\n blockSeparator,\n textSerializers: {\n ...getTextSerializersFromSchema(this.schema),\n ...textSerializers,\n },\n })\n }\n\n /**\n * Check if there is no content.\n */\n public get isEmpty(): boolean {\n return isNodeEmpty(this.state.doc)\n }\n\n /**\n * Destroy the editor.\n */\n public destroy(): void {\n this.emit('destroy')\n\n this.unmount()\n\n this.removeAllListeners()\n }\n\n /**\n * Check if the editor is already destroyed.\n */\n public get isDestroyed(): boolean {\n return this.editorView?.isDestroyed ?? true\n }\n\n public $node(selector: string, attributes?: { [key: string]: any }): NodePos | null {\n return this.$doc?.querySelector(selector, attributes) || null\n }\n\n public $nodes(selector: string, attributes?: { [key: string]: any }): NodePos[] | null {\n return this.$doc?.querySelectorAll(selector, attributes) || null\n }\n\n public $pos(pos: number) {\n const $pos = this.state.doc.resolve(pos)\n\n return new NodePos($pos, this)\n }\n\n get $doc() {\n return this.$pos(0)\n }\n}\n","type StringKeyOf<T> = Extract<keyof T, string>\ntype CallbackType<T extends Record<string, any>, EventName extends StringKeyOf<T>> = T[EventName] extends any[]\n ? T[EventName]\n : [T[EventName]]\ntype CallbackFunction<T extends Record<string, any>, EventName extends StringKeyOf<T>> = (\n ...props: CallbackType<T, EventName>\n) => any\n\nexport class EventEmitter<T extends Record<string, any>> {\n private callbacks: { [key: string]: Array<(...args: any[]) => void> } = {}\n\n public on<EventName extends StringKeyOf<T>>(event: EventName, fn: CallbackFunction<T, EventName>): this {\n if (!this.callbacks[event]) {\n this.callbacks[event] = []\n }\n\n this.callbacks[event].push(fn)\n\n return this\n }\n\n public emit<EventName extends StringKeyOf<T>>(event: EventName, ...args: CallbackType<T, EventName>): this {\n const callbacks = this.callbacks[event]\n\n if (callbacks) {\n callbacks.forEach(callback => callback.apply(this, args))\n }\n\n return this\n }\n\n public off<EventName extends StringKeyOf<T>>(event: EventName, fn?: CallbackFunction<T, EventName>): this {\n const callbacks = this.callbacks[event]\n\n if (callbacks) {\n if (fn) {\n this.callbacks[event] = callbacks.filter(callback => callback !== fn)\n } else {\n delete this.callbacks[event]\n }\n }\n\n return this\n }\n\n public once<EventName extends StringKeyOf<T>>(event: EventName, fn: CallbackFunction<T, EventName>): this {\n const onceFn = (...args: CallbackType<T, EventName>) => {\n this.off(event, onceFn)\n fn.apply(this, args)\n }\n\n return this.on(event, onceFn)\n }\n\n public removeAllListeners(): void {\n this.callbacks = {}\n }\n}\n","import { keymap } from '@tiptap/pm/keymap'\nimport type { Schema } from '@tiptap/pm/model'\nimport type { Plugin } from '@tiptap/pm/state'\nimport type { MarkViewConstructor, NodeViewConstructor } from '@tiptap/pm/view'\n\nimport type { Editor } from './Editor.js'\nimport {\n flattenExtensions,\n getAttributesFromExtensions,\n getExtensionField,\n getNodeType,\n getRenderedAttributes,\n getSchemaByResolvedExtensions,\n getSchemaTypeByName,\n isExtensionRulesEnabled,\n resolveExtensions,\n sortExtensions,\n splitExtensions,\n} from './helpers/index.js'\nimport { type MarkConfig, type NodeConfig, type Storage, getMarkType, updateMarkViewAttributes } from './index.js'\nimport type { InputRule } from './InputRule.js'\nimport { inputRulesPlugin } from './InputRule.js'\nimport { Mark } from './Mark.js'\nimport type { PasteRule } from './PasteRule.js'\nimport { pasteRulesPlugin } from './PasteRule.js'\nimport type { AnyConfig, Extensions, RawCommands } from './types.js'\nimport { callOrReturn } from './utilities/callOrReturn.js'\n\nexport class ExtensionManager {\n editor: Editor\n\n schema: Schema\n\n extensions: Extensions\n\n splittableMarks: string[] = []\n\n constructor(extensions: Extensions, editor: Editor) {\n this.editor = editor\n this.extensions = resolveExtensions(extensions)\n this.schema = getSchemaByResolvedExtensions(this.extensions, editor)\n this.setupExtensions()\n }\n\n static resolve = resolveExtensions\n\n static sort = sortExtensions\n\n static flatten = flattenExtensions\n\n /**\n * Get all commands from the extensions.\n * @returns An object with all commands where the key is the command name and the value is the command function\n */\n get commands(): RawCommands {\n return this.extensions.reduce((commands, extension) => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: this.editor.extensionStorage[extension.name as keyof Storage],\n editor: this.editor,\n type: getSchemaTypeByName(extension.name, this.schema),\n }\n\n const addCommands = getExtensionField<AnyConfig['addCommands']>(extension, 'addCommands', context)\n\n if (!addCommands) {\n return commands\n }\n\n return {\n ...commands,\n ...addCommands(),\n }\n }, {} as RawCommands)\n }\n\n /**\n * Get all registered Prosemirror plugins from the extensions.\n * @returns An array of Prosemirror plugins\n */\n get plugins(): Plugin[] {\n const { editor } = this\n\n // With ProseMirror, first plugins within an array are executed first.\n // In Tiptap, we provide the ability to override plugins,\n // so it feels more natural to run plugins at the end of an array first.\n // That’s why we have to reverse the `extensions` array and sort again\n // based on the `priority` option.\n const extensions = sortExtensions([...this.extensions].reverse())\n\n const inputRules: InputRule[] = []\n const pasteRules: PasteRule[] = []\n\n const allPlugins = extensions\n .map(extension => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: this.editor.extensionStorage[extension.name as keyof Storage],\n editor,\n type: getSchemaTypeByName(extension.name, this.schema),\n }\n\n const plugins: Plugin[] = []\n\n const addKeyboardShortcuts = getExtensionField<AnyConfig['addKeyboardShortcuts']>(\n extension,\n 'addKeyboardShortcuts',\n context,\n )\n\n let defaultBindings: Record<string, () => boolean> = {}\n\n // bind exit handling\n if (extension.type === 'mark' && getExtensionField<MarkConfig['exitable']>(extension, 'exitable', context)) {\n defaultBindings.ArrowRight = () => Mark.handleExit({ editor, mark: extension as Mark })\n }\n\n if (addKeyboardShortcuts) {\n const bindings = Object.fromEntries(\n Object.entries(addKeyboardShortcuts()).map(([shortcut, method]) => {\n return [shortcut, () => method({ editor })]\n }),\n )\n\n defaultBindings = { ...defaultBindings, ...bindings }\n }\n\n const keyMapPlugin = keymap(defaultBindings)\n\n plugins.push(keyMapPlugin)\n\n const addInputRules = getExtensionField<AnyConfig['addInputRules']>(extension, 'addInputRules', context)\n\n if (isExtensionRulesEnabled(extension, editor.options.enableInputRules) && addInputRules) {\n inputRules.push(...addInputRules())\n }\n\n const addPasteRules = getExtensionField<AnyConfig['addPasteRules']>(extension, 'addPasteRules', context)\n\n if (isExtensionRulesEnabled(extension, editor.options.enablePasteRules) && addPasteRules) {\n pasteRules.push(...addPasteRules())\n }\n\n const addProseMirrorPlugins = getExtensionField<AnyConfig['addProseMirrorPlugins']>(\n extension,\n 'addProseMirrorPlugins',\n context,\n )\n\n if (addProseMirrorPlugins) {\n const proseMirrorPlugins = addProseMirrorPlugins()\n\n plugins.push(...proseMirrorPlugins)\n }\n\n return plugins\n })\n .flat()\n\n return [\n inputRulesPlugin({\n editor,\n rules: inputRules,\n }),\n ...pasteRulesPlugin({\n editor,\n rules: pasteRules,\n }),\n ...allPlugins,\n ]\n }\n\n /**\n * Get all attributes from the extensions.\n * @returns An array of attributes\n */\n get attributes() {\n return getAttributesFromExtensions(this.extensions)\n }\n\n /**\n * Get all node views from the extensions.\n * @returns An object with all node views where the key is the node name and the value is the node view function\n */\n get nodeViews(): Record<string, NodeViewConstructor> {\n const { editor } = this\n const { nodeExtensions } = splitExtensions(this.extensions)\n\n return Object.fromEntries(\n nodeExtensions\n .filter(extension => !!getExtensionField(extension, 'addNodeView'))\n .map(extension => {\n const extensionAttributes = this.attributes.filter(attribute => attribute.type === extension.name)\n const context = {\n name: extension.name,\n options: extension.options,\n storage: this.editor.extensionStorage[extension.name as keyof Storage],\n editor,\n type: getNodeType(extension.name, this.schema),\n }\n const addNodeView = getExtensionField<NodeConfig['addNodeView']>(extension, 'addNodeView', context)\n\n if (!addNodeView) {\n return []\n }\n\n const nodeview: NodeViewConstructor = (node, view, getPos, decorations, innerDecorations) => {\n const HTMLAttributes = getRenderedAttributes(node, extensionAttributes)\n\n return addNodeView()({\n // pass-through\n node,\n view,\n getPos: getPos as () => number,\n decorations,\n innerDecorations,\n // tiptap-specific\n editor,\n extension,\n HTMLAttributes,\n })\n }\n\n return [extension.name, nodeview]\n }),\n )\n }\n\n get markViews(): Record<string, MarkViewConstructor> {\n const { editor } = this\n const { markExtensions } = splitExtensions(this.extensions)\n\n return Object.fromEntries(\n markExtensions\n .filter(extension => !!getExtensionField(extension, 'addMarkView'))\n .map(extension => {\n const extensionAttributes = this.attributes.filter(attribute => attribute.type === extension.name)\n const context = {\n name: extension.name,\n options: extension.options,\n storage: this.editor.extensionStorage[extension.name as keyof Storage],\n editor,\n type: getMarkType(extension.name, this.schema),\n }\n const addMarkView = getExtensionField<MarkConfig['addMarkView']>(extension, 'addMarkView', context)\n\n if (!addMarkView) {\n return []\n }\n\n const markView: MarkViewConstructor = (mark, view, inline) => {\n const HTMLAttributes = getRenderedAttributes(mark, extensionAttributes)\n\n return addMarkView()({\n // pass-through\n mark,\n view,\n inline,\n // tiptap-specific\n editor,\n extension,\n HTMLAttributes,\n updateAttributes: (attrs: Record<string, any>) => {\n updateMarkViewAttributes(mark, editor, attrs)\n },\n })\n }\n\n return [extension.name, markView]\n }),\n )\n }\n\n /**\n * Go through all extensions, create extension storages & setup marks\n * & bind editor event listener.\n */\n private setupExtensions() {\n const extensions = this.extensions\n // re-initialize the extension storage object instance\n this.editor.extensionStorage = Object.fromEntries(\n extensions.map(extension => [extension.name, extension.storage]),\n ) as unknown as Storage\n\n extensions.forEach(extension => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: this.editor.extensionStorage[extension.name as keyof Storage],\n editor: this.editor,\n type: getSchemaTypeByName(extension.name, this.schema),\n }\n\n if (extension.type === 'mark') {\n const keepOnSplit = callOrReturn(getExtensionField(extension, 'keepOnSplit', context)) ?? true\n\n if (keepOnSplit) {\n this.splittableMarks.push(extension.name)\n }\n }\n\n const onBeforeCreate = getExtensionField<AnyConfig['onBeforeCreate']>(extension, 'onBeforeCreate', context)\n const onCreate = getExtensionField<AnyConfig['onCreate']>(extension, 'onCreate', context)\n const onUpdate = getExtensionField<AnyConfig['onUpdate']>(extension, 'onUpdate', context)\n const onSelectionUpdate = getExtensionField<AnyConfig['onSelectionUpdate']>(\n extension,\n 'onSelectionUpdate',\n context,\n )\n const onTransaction = getExtensionField<AnyConfig['onTransaction']>(extension, 'onTransaction', context)\n const onFocus = getExtensionField<AnyConfig['onFocus']>(extension, 'onFocus', context)\n const onBlur = getExtensionField<AnyConfig['onBlur']>(extension, 'onBlur', context)\n const onDestroy = getExtensionField<AnyConfig['onDestroy']>(extension, 'onDestroy', context)\n\n if (onBeforeCreate) {\n this.editor.on('beforeCreate', onBeforeCreate)\n }\n\n if (onCreate) {\n this.editor.on('create', onCreate)\n }\n\n if (onUpdate) {\n this.editor.on('update', onUpdate)\n }\n\n if (onSelectionUpdate) {\n this.editor.on('selectionUpdate', onSelectionUpdate)\n }\n\n if (onTransaction) {\n this.editor.on('transaction', onTransaction)\n }\n\n if (onFocus) {\n this.editor.on('focus', onFocus)\n }\n\n if (onBlur) {\n this.editor.on('blur', onBlur)\n }\n\n if (onDestroy) {\n this.editor.on('destroy', onDestroy)\n }\n })\n }\n}\n","import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport type { Transaction } from '@tiptap/pm/state'\nimport { Transform } from '@tiptap/pm/transform'\n\n/**\n * Returns a new `Transform` based on all steps of the passed transactions.\n * @param oldDoc The Prosemirror node to start from\n * @param transactions The transactions to combine\n * @returns A new `Transform` with all steps of the passed transactions\n */\nexport function combineTransactionSteps(oldDoc: ProseMirrorNode, transactions: Transaction[]): Transform {\n const transform = new Transform(oldDoc)\n\n transactions.forEach(transaction => {\n transaction.steps.forEach(step => {\n transform.step(step)\n })\n })\n\n return transform\n}\n","import type { ParseOptions } from '@tiptap/pm/model'\nimport { DOMParser, Fragment, Node as ProseMirrorNode, Schema } from '@tiptap/pm/model'\n\nimport type { Content } from '../types.js'\nimport { elementFromString } from '../utilities/elementFromString.js'\n\nexport type CreateNodeFromContentOptions = {\n slice?: boolean\n parseOptions?: ParseOptions\n errorOnInvalidContent?: boolean\n}\n\n/**\n * Takes a JSON or HTML content and creates a Prosemirror node or fragment from it.\n * @param content The JSON or HTML content to create the node from\n * @param schema The Prosemirror schema to use for the node\n * @param options Options for the parser\n * @returns The created Prosemirror node or fragment\n */\nexport function createNodeFromContent(\n content: Content | ProseMirrorNode | Fragment,\n schema: Schema,\n options?: CreateNodeFromContentOptions,\n): ProseMirrorNode | Fragment {\n if (content instanceof ProseMirrorNode || content instanceof Fragment) {\n return content\n }\n options = {\n slice: true,\n parseOptions: {},\n ...options,\n }\n\n const isJSONContent = typeof content === 'object' && content !== null\n const isTextContent = typeof content === 'string'\n\n if (isJSONContent) {\n try {\n const isArrayContent = Array.isArray(content) && content.length > 0\n\n // if the JSON Content is an array of nodes, create a fragment for each node\n if (isArrayContent) {\n return Fragment.fromArray(content.map(item => schema.nodeFromJSON(item)))\n }\n\n const node = schema.nodeFromJSON(content)\n\n if (options.errorOnInvalidContent) {\n node.check()\n }\n\n return node\n } catch (error) {\n if (options.errorOnInvalidContent) {\n throw new Error('[tiptap error]: Invalid JSON content', { cause: error as Error })\n }\n\n console.warn('[tiptap warn]: Invalid content.', 'Passed value:', content, 'Error:', error)\n\n return createNodeFromContent('', schema, options)\n }\n }\n\n if (isTextContent) {\n // Check for invalid content\n if (options.errorOnInvalidContent) {\n let hasInvalidContent = false\n let invalidContent = ''\n\n // A copy of the current schema with a catch-all node at the end\n const contentCheckSchema = new Schema({\n topNode: schema.spec.topNode,\n marks: schema.spec.marks,\n // Prosemirror's schemas are executed such that: the last to execute, matches last\n // This means that we can add a catch-all node at the end of the schema to catch any content that we don't know how to handle\n nodes: schema.spec.nodes.append({\n __tiptap__private__unknown__catch__all__node: {\n content: 'inline*',\n group: 'block',\n parseDOM: [\n {\n tag: '*',\n getAttrs: e => {\n // If this is ever called, we know that the content has something that we don't know how to handle in the schema\n hasInvalidContent = true\n // Try to stringify the element for a more helpful error message\n invalidContent = typeof e === 'string' ? e : e.outerHTML\n return null\n