Skip to content

Commit

Permalink
feat: add insertContent() command, deprecate insertText(), insertHTML…
Browse files Browse the repository at this point in the history
…() and insertNode()
  • Loading branch information
philippkuehn committed Apr 7, 2021
1 parent 63acc57 commit b8d9b7d
Show file tree
Hide file tree
Showing 21 changed files with 198 additions and 113 deletions.
4 changes: 2 additions & 2 deletions docs/src/demos/Guide/Content/ReadOnly/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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: ')
})
Expand All @@ -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: ')
})
Expand Down
12 changes: 6 additions & 6 deletions docs/src/demos/Nodes/Emoji/index.vue
Original file line number Diff line number Diff line change
@@ -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" />
Expand Down
39 changes: 24 additions & 15 deletions docs/src/docPages/api/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ addCommands() {

// Does work:
return chain()
.insertNode('timecode', attributes)
.insertText(' ')
.insertContent('foo!')
.insertContent('bar!')
.run()
},
}
Expand All @@ -60,7 +60,7 @@ editor
.focus()
.command(({ tr }) => {
// manipulate the transaction
tr.insertText('hey, that’s cool!')
tr.insertContent('hey, that’s cool!')

return true
})
Expand Down Expand Up @@ -91,7 +91,7 @@ Both calls would return `true` if it’s possible to apply the commands, and `fa

In order to make that work with your custom commands, don’t 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 }) => {
Expand Down Expand Up @@ -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 what’s 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 |
Expand Down Expand Up @@ -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()
```
Expand All @@ -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();
},
Expand Down
23 changes: 23 additions & 0 deletions docs/src/docPages/api/commands/insert-content.md
Original file line number Diff line number Diff line change
@@ -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',
},
],
})
```

13 changes: 0 additions & 13 deletions docs/src/docPages/api/commands/insert-html.md

This file was deleted.

13 changes: 0 additions & 13 deletions docs/src/docPages/api/commands/insert-node.md

This file was deleted.

12 changes: 0 additions & 12 deletions docs/src/docPages/api/commands/insert-text.md

This file was deleted.

1 change: 0 additions & 1 deletion docs/src/docPages/api/editor.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ Don’t 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. |
Expand Down
2 changes: 1 addition & 1 deletion docs/src/docPages/api/nodes/emoji.md
Original file line number Diff line number Diff line change
Expand Up @@ -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" />
10 changes: 2 additions & 8 deletions docs/src/links.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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>')
})
Expand Down
37 changes: 5 additions & 32 deletions packages/core/src/Editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -16,7 +16,6 @@ import ExtensionManager from './ExtensionManager'
import EventEmitter from './EventEmitter'
import {
EditorOptions,
Content,
CanCommands,
ChainedCommands,
SingleCommands,
Expand Down Expand Up @@ -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),
}),
})

Expand Down Expand Up @@ -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
Expand Down
35 changes: 35 additions & 0 deletions packages/core/src/commands/insertContent.ts
Original file line number Diff line number Diff line change
@@ -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
}
2 changes: 2 additions & 0 deletions packages/core/src/commands/insertHTML.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/commands/insertNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/commands/insertText.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
Loading

0 comments on commit b8d9b7d

Please sign in to comment.