Files
tiptap/packages/core/src/commands/setContent.ts
2021-04-26 23:43:32 +02:00

34 lines
963 B
TypeScript

import { TextSelection } from 'prosemirror-state'
import { ParseOptions } from 'prosemirror-model'
import createDocument from '../helpers/createDocument'
import { Command, RawCommands, Content } from '../types'
declare module '@tiptap/core' {
interface Commands {
setContent: {
/**
* Replace the whole document with new content.
*/
setContent: (
content: Content,
emitUpdate?: boolean,
parseOptions?: ParseOptions,
) => Command,
}
}
}
export const setContent: RawCommands['setContent'] = (content, emitUpdate = false, parseOptions = {}) => ({ tr, editor, dispatch }) => {
const { doc } = tr
const document = createDocument(content, editor.schema, parseOptions)
const selection = TextSelection.create(doc, 0, doc.content.size)
if (dispatch) {
tr.setSelection(selection)
.replaceSelectionWith(document, false)
.setMeta('preventUpdate', !emitUpdate)
}
return true
}