Skip to content

Commit

Permalink
feat: add updateSelection option to insertContentAt command
Browse files Browse the repository at this point in the history
  • Loading branch information
philippkuehn committed Oct 14, 2021
1 parent 4303637 commit 9f2c368
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
10 changes: 8 additions & 2 deletions packages/core/src/commands/insertContent.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CreateNodeFromContentOptions } from '../helpers/createNodeFromContent'
import { ParseOptions } from 'prosemirror-model'
import { RawCommands, Content } from '../types'

declare module '@tiptap/core' {
Expand All @@ -7,7 +7,13 @@ declare module '@tiptap/core' {
/**
* Insert a node or string of HTML at the current position.
*/
insertContent: (value: Content, options?: CreateNodeFromContentOptions) => ReturnType,
insertContent: (
value: Content,
options?: {
parseOptions: ParseOptions,
updateSelection: boolean,
},
) => ReturnType,
}
}
}
Expand Down
24 changes: 20 additions & 4 deletions packages/core/src/commands/insertContentAt.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import createNodeFromContent, { CreateNodeFromContentOptions } from '../helpers/createNodeFromContent'
import { ParseOptions } from 'prosemirror-model'
import createNodeFromContent from '../helpers/createNodeFromContent'
import selectionToInsertionEnd from '../helpers/selectionToInsertionEnd'
import {
RawCommands,
Expand All @@ -12,18 +13,31 @@ declare module '@tiptap/core' {
/**
* Insert a node or string of HTML at a specific position.
*/
insertContentAt: (position: number | Range, value: Content, options?: CreateNodeFromContentOptions) => ReturnType,
insertContentAt: (
position: number | Range,
value: Content,
options?: {
parseOptions: ParseOptions,
updateSelection: boolean,
},
) => ReturnType,
}
}
}

export const insertContentAt: RawCommands['insertContentAt'] = (position, value, options) => ({ tr, dispatch, editor }) => {
if (dispatch) {
options = {
parseOptions: {},
updateSelection: true,
...options,
}

const content = createNodeFromContent(value, editor.schema, {
parseOptions: {
preserveWhitespace: 'full',
...options.parseOptions,
},
...(options || {}),
})

// don’t dispatch an empty fragment because this can lead to strange errors
Expand All @@ -38,7 +52,9 @@ export const insertContentAt: RawCommands['insertContentAt'] = (position, value,
tr.replaceWith(from, to, content)

// set cursor at end of inserted content
selectionToInsertionEnd(tr, tr.steps.length - 1, 1)
if (options.updateSelection) {
selectionToInsertionEnd(tr, tr.steps.length - 1, 1)
}
}

return true
Expand Down

0 comments on commit 9f2c368

Please sign in to comment.