feat: add insertContent() command, deprecate insertText(), insertHTML() and insertNode()

This commit is contained in:
Philipp Kühn
2021-04-07 11:53:37 +02:00
parent 63acc57305
commit b8d9b7d4c7
21 changed files with 198 additions and 113 deletions

View File

@@ -6,7 +6,7 @@ context('/demos/Guide/Content/ReadOnly', () => {
it('should be read-only', () => {
cy.get('.ProseMirror').then(([{ editor }]) => {
editor.setEditable(false)
editor.commands.insertText('Edited: ')
editor.commands.insertContent('Edited: ')
cy.get('.ProseMirror p:first').should('not.contain', 'Edited: ')
})
@@ -15,7 +15,7 @@ context('/demos/Guide/Content/ReadOnly', () => {
it('should be editable', () => {
cy.get('.ProseMirror').then(([{ editor }]) => {
editor.setEditable(true)
editor.commands.insertText('Edited: ')
editor.commands.insertContent('Edited: ')
cy.get('.ProseMirror p:first').should('contain', 'Edited: ')
})

View File

@@ -1,21 +1,21 @@
<template>
<div v-if="editor">
<button @click="editor.chain().focus(). insertText('✨').run()">
<button @click="editor.chain().focus().insertContent('✨').run()">
</button>
<button @click="editor.chain().focus(). insertText('😅').run()">
<button @click="editor.chain().focus().insertContent('😅').run()">
😅
</button>
<button @click="editor.chain().focus(). insertText('🎉').run()">
<button @click="editor.chain().focus().insertContent('🎉').run()">
🎉
</button>
<button @click="editor.chain().focus(). insertText('💖').run()">
<button @click="editor.chain().focus().insertContent('💖').run()">
💖
</button>
<button @click="editor.chain().focus(). insertText('👀').run()">
<button @click="editor.chain().focus().insertContent('👀').run()">
👀
</button>
<button @click="editor.chain().focus(). insertText('👍️').run()">
<button @click="editor.chain().focus().insertContent('👍️').run()">
👍
</button>
<editor-content :editor="editor" />

View File

@@ -43,8 +43,8 @@ addCommands() {
// Does work:
return chain()
.insertNode('timecode', attributes)
.insertText(' ')
.insertContent('foo!')
.insertContent('bar!')
.run()
},
}
@@ -60,7 +60,7 @@ editor
.focus()
.command(({ tr }) => {
// manipulate the transaction
tr.insertText('hey, thats cool!')
tr.insertContent('hey, thats cool!')
return true
})
@@ -91,7 +91,7 @@ Both calls would return `true` if its possible to apply the commands, and `fa
In order to make that work with your custom commands, dont forget to return `true` or `false`.
For some of your own commands, you probably want to work with the raw [transaction](/api/concept). To make them work with `.can()` you should check if the transaction should be dispatched. Here is how we do that within `.insertText()`:
For some of your own commands, you probably want to work with the raw [transaction](/api/concept). To make them work with `.can()` you should check if the transaction should be dispatched. Here is how you can create a simple `.insertText()` command:
```js
export default (value: string): Command => ({ tr, dispatch }) => {
@@ -148,13 +148,11 @@ commands.first([
Have a look at all of the core commands listed below. They should give you a good first impression of whats possible.
### Content
| Command | Description | Links |
| --------------- | ------------------------------------------------ | ----------------------------------- |
| .clearContent() | Clear the whole document. | [More](/api/commands/clear-content) |
| .insertHTML() | Insert a string of HTML at the current position. | [More](/api/commands/insert-html) |
| .insertNode() | Insert a node at the current position. | [More](/api/commands/insert-node) |
| .insertText() | Insert a string of text at the current position. | [More](/api/commands/insert-text) |
| .setContent() | Replace the whole document with new content. | [More](/api/commands/set-content) |
| Command | Description | Links |
| ---------------- | -------------------------------------------------------- | ------------------------------------ |
| .clearContent() | Clear the whole document. | [More](/api/commands/clear-content) |
| .insertContent() | Insert a node or string of HTML at the current position. | [More](/api/commands/insert-content) |
| .setContent() | Replace the whole document with new content. | [More](/api/commands/set-content) |
### Nodes & Marks
| Command | Description |
@@ -220,13 +218,13 @@ this.editor
.chain()
.focus()
.createParagraphNear()
.insertText(text)
.insertContent(text)
.setBlockquote()
.insertHTML('<p></p>')
.insertContent('<p></p>')
.createParagraphNear()
.unsetBlockquote()
.createParagraphNear()
.insertHTML('<p></p>')
.insertContent('<p></p>')
.run()
```
@@ -237,7 +235,18 @@ addCommands() {
insertTimecode: attributes => ({ chain }) => {
return chain()
.focus()
.insertNode('timecode', attributes)
.insertContent({
type: 'heading',
attrs: {
level: 2,
},
content: [
{
type: 'text',
text: 'heading',
},
],
})
.insertText(' ')
.run();
},

View File

@@ -0,0 +1,23 @@
# insertContent
## Parameters
## Usage
```js
this.editor.commands.insertContent('text')
this.editor.commands.insertContent('<p>HTML</p>')
this.editor.commands.insertContent({
type: 'heading',
attrs: {
level: 2,
},
content: [
{
type: 'text',
text: 'nested nodes',
},
],
})
```

View File

@@ -1,13 +0,0 @@
# insertHTML
See also: [insertText](/api/commands/insert-text), [insertNode](/api/commands/insert-node)
## Parameters
## Usage
```js
this.editor.commands.insertHTML('<p>Example text</p>')
```

View File

@@ -1,13 +0,0 @@
# insertNode
See also: [insertHTML](/api/commands/insert-html), [insertText](/api/commands/insert-text)
## Parameters
## Usage
```js
this.editor.commands.insertNode('paragraph')
```

View File

@@ -1,12 +0,0 @@
# insertText
See also: [insertHTML](/api/commands/insert-html), [insertNode](/api/commands/insert-node)
## Parameters
## Usage
```js
this.editor.commands.insertText('Example text')
```

View File

@@ -14,7 +14,6 @@ Dont confuse methods with [commands](/api/commands). Commands are used to cha
| --------------------- | ----------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
| `can()` | - | Check if a command or a command chain can be executed. Without executing it. |
| `chain()` | - | Create a command chain to call multiple commands at once. |
| `createDocument()` | `content` EditorContent<br>`parseOptions` | Creates a ProseMirror document. |
| `destroy()` | | Stops the editor instance and unbinds all events. |
| `getHTML()` | | Returns the current content as HTML. |
| `getJSON()` | | Returns the current content as JSON. |

View File

@@ -13,7 +13,7 @@ We need your support to maintain, update, support and develop tiptap 2. If you
You can use any emoji picker, or build your own. Just use [commands](/api/commands) to insert the picked emojis.
```js
this.editor.chain().focus().insertText('✨').run()
this.editor.chain().focus().insertContent('✨').run()
```
<demo name="Nodes/Emoji" />

View File

@@ -136,14 +136,8 @@
- title: clearContent
link: /api/commands/clear-content
type: draft
- title: insertHTML
link: /api/commands/insert-html
type: draft
- title: insertNode
link: /api/commands/insert-node
type: draft
- title: insertText
link: /api/commands/insert-text
- title: insertContent
link: /api/commands/insert-content
type: draft
- title: setContent
link: /api/commands/set-content

View File

@@ -1,23 +1,23 @@
context('insertHTML', () => {
context('insertContent', () => {
before(() => {
cy.visit('/demos/Examples/Default/Vue')
})
it('returns true for the insertHTML command', () => {
it('returns true for the insertContent command', () => {
cy.get('.ProseMirror').then(([{ editor }]) => {
editor.commands.setContent('<p>Example Text</p>')
const command = editor.commands.insertHTML('<p>Cindy Lauper</p>')
const command = editor.commands.insertContent('<p>Cindy Lauper</p>')
expect(command).to.be.eq(true)
})
})
it('appends the content when using the insertHTML command', () => {
it('appends the content when using the insertContent command', () => {
cy.get('.ProseMirror').then(([{ editor }]) => {
editor.commands.setContent('<p>Example Text</p>')
editor.commands.insertHTML('<p>Cindy Lauper</p>')
editor.commands.insertContent('<p>Cindy Lauper</p>')
expect(editor.getHTML()).to.be.eq('<p>Example Text</p><p>Cindy Lauper</p>')
})

View File

@@ -2,12 +2,12 @@ import {
EditorState, Plugin, PluginKey, Transaction,
} from 'prosemirror-state'
import { EditorView } from 'prosemirror-view'
import { Schema, DOMParser, Node } from 'prosemirror-model'
import elementFromString from './utilities/elementFromString'
import { Schema } from 'prosemirror-model'
import getNodeAttributes from './helpers/getNodeAttributes'
import getMarkAttributes from './helpers/getMarkAttributes'
import isActive from './helpers/isActive'
import removeElement from './utilities/removeElement'
import createDocument from './helpers/createDocument'
import getHTMLFromFragment from './helpers/getHTMLFromFragment'
import isNodeEmpty from './helpers/isNodeEmpty'
import createStyleTag from './utilities/createStyleTag'
@@ -16,7 +16,6 @@ import ExtensionManager from './ExtensionManager'
import EventEmitter from './EventEmitter'
import {
EditorOptions,
Content,
CanCommands,
ChainedCommands,
SingleCommands,
@@ -233,11 +232,13 @@ export class Editor extends EventEmitter {
* Creates a ProseMirror view.
*/
private createView(): void {
console.log(this.schema.topNodeType)
this.view = new EditorView(this.options.element, {
...this.options.editorProps,
dispatchTransaction: this.dispatchTransaction.bind(this),
state: EditorState.create({
doc: this.createDocument(this.options.content),
doc: createDocument(this.options.content, this.schema, this.options.parseOptions),
}),
})
@@ -275,34 +276,6 @@ export class Editor extends EventEmitter {
})
}
/**
* Creates a ProseMirror document.
*/
public createDocument = (content: Content, parseOptions = this.options.parseOptions): Node => {
if (content && typeof content === 'object') {
try {
return this.schema.nodeFromJSON(content)
} catch (error) {
console.warn(
'[tiptap warn]: Invalid content.',
'Passed value:',
content,
'Error:',
error,
)
return this.createDocument('')
}
}
if (typeof content === 'string') {
return DOMParser
.fromSchema(this.schema)
.parse(elementFromString(content), parseOptions)
}
return this.createDocument('')
}
public isCapturingTransaction = false
private capturedTransaction: Transaction | null = null

View File

@@ -0,0 +1,35 @@
import createNodeFromContent from '../helpers/createNodeFromContent'
import selectionToInsertionEnd from '../helpers/selectionToInsertionEnd'
import { Command, RawCommands, Content } from '../types'
declare module '@tiptap/core' {
interface Commands {
insertContent: {
/**
* Insert a node or string of HTML at the current position.
*/
insertContent: (value: Content) => Command,
}
}
}
export const insertContent: RawCommands['insertContent'] = value => ({ tr, dispatch, editor }) => {
if (dispatch) {
const content = createNodeFromContent(value, editor.schema)
if (typeof content === 'string') {
tr.insertText(content)
return true
}
if (!tr.selection.empty) {
tr.deleteSelection()
}
tr.insert(tr.selection.anchor, content)
selectionToInsertionEnd(tr, tr.steps.length - 1, -1)
}
return true
}

View File

@@ -15,6 +15,8 @@ declare module '@tiptap/core' {
}
export const insertHTML: RawCommands['insertHTML'] = value => ({ tr, state, dispatch }) => {
console.warn('[tiptap warn]: insertHTML() is deprecated. please use insertContent() instead.')
const { selection } = tr
const element = elementFromString(value)
const slice = DOMParser.fromSchema(state.schema).parseSlice(element)

View File

@@ -14,6 +14,8 @@ declare module '@tiptap/core' {
}
export const insertNode: RawCommands['insertNode'] = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {
console.warn('[tiptap warn]: insertNode() is deprecated. please use insertContent() instead.')
const { selection } = tr
const type = getNodeType(typeOrName, state.schema)

View File

@@ -12,6 +12,8 @@ declare module '@tiptap/core' {
}
export const insertText: RawCommands['insertText'] = value => ({ tr, dispatch }) => {
console.warn('[tiptap warn]: insertText() is deprecated. please use insertContent() instead.')
if (dispatch) {
tr.insertText(value)
}

View File

@@ -1,5 +1,11 @@
import { TextSelection } from 'prosemirror-state'
import { AnyObject, Command, RawCommands } from '../types'
import createDocument from '../helpers/createDocument'
import {
AnyObject,
Command,
RawCommands,
Content,
} from '../types'
declare module '@tiptap/core' {
interface Commands {
@@ -7,15 +13,18 @@ declare module '@tiptap/core' {
/**
* Replace the whole document with new content.
*/
setContent: (content: string, emitUpdate?: Boolean, parseOptions?: AnyObject) => Command,
setContent: (
content: Content,
emitUpdate?: Boolean,
parseOptions?: AnyObject,
) => Command,
}
}
}
export const setContent: RawCommands['setContent'] = (content, emitUpdate = false, parseOptions = {}) => ({ tr, editor, dispatch }) => {
const { createDocument } = editor
const { doc } = tr
const document = createDocument(content, parseOptions)
const document = createDocument(content, editor.schema, parseOptions)
const selection = TextSelection.create(doc, 0, doc.content.size)
if (dispatch) {

View File

@@ -11,6 +11,7 @@ import * as exitCode from '../commands/exitCode'
import * as extendMarkRange from '../commands/extendMarkRange'
import * as first from '../commands/first'
import * as focus from '../commands/focus'
import * as insertContent from '../commands/insertContent'
import * as insertHTML from '../commands/insertHTML'
import * as insertNode from '../commands/insertNode'
import * as insertText from '../commands/insertText'
@@ -58,6 +59,7 @@ export { exitCode }
export { extendMarkRange }
export { first }
export { focus }
export { insertContent }
export { insertHTML }
export { insertNode }
export { insertText }
@@ -110,6 +112,7 @@ export const Commands = Extension.create({
...extendMarkRange,
...first,
...focus,
...insertContent,
...insertHTML,
...insertNode,
...insertText,

View File

@@ -0,0 +1,13 @@
import { Schema, Node as ProseMirrorNode } from 'prosemirror-model'
import { AnyObject } from '../types'
import createNodeFromContent from './createNodeFromContent'
export type Content = string | JSON | null
export default function createDocument(
content: Content,
schema: Schema,
parseOptions: AnyObject = {},
): ProseMirrorNode {
return createNodeFromContent(content, schema, { slice: false, parseOptions }) as ProseMirrorNode
}

View File

@@ -0,0 +1,59 @@
import {
Schema,
DOMParser,
Node as ProseMirrorNode,
Fragment,
} from 'prosemirror-model'
import elementFromString from '../utilities/elementFromString'
import { AnyObject } from '../types'
export type Content = string | JSON | null
export type CreateNodeFromContentOptions = {
slice?: boolean,
parseOptions?: AnyObject,
}
export default function createNodeFromContent(
content: Content,
schema: Schema,
options?: CreateNodeFromContentOptions,
): string | ProseMirrorNode | Fragment {
options = {
slice: true,
parseOptions: {},
...options,
}
if (content && typeof content === 'object') {
try {
return schema.nodeFromJSON(content)
} catch (error) {
console.warn(
'[tiptap warn]: Invalid content.',
'Passed value:',
content,
'Error:',
error,
)
return createNodeFromContent('', schema, options)
}
}
if (typeof content === 'string') {
const isHTML = content.trim().startsWith('<') && content.trim().endsWith('>')
if (isHTML || !options.slice) {
const parser = DOMParser.fromSchema(schema)
return options.slice
? parser.parseSlice(elementFromString(content), options.parseOptions).content
: parser.parse(elementFromString(content), options.parseOptions)
}
return content
}
return createNodeFromContent('', schema, options)
}

View File

@@ -20,7 +20,7 @@ export const Mention = Node.create<MentionOptions>({
.chain()
.focus()
.replaceRange(range, 'mention', props)
.insertText(' ')
.insertContent(' ')
.run()
},
allow: ({ editor, range }) => {