tiptap/packages/core/src/commands/setContent.ts

29 lines
845 B
TypeScript
Raw Normal View History

2020-11-05 05:38:52 +08:00
import { TextSelection } from 'prosemirror-state'
2021-02-17 01:36:37 +08:00
import { AnyObject, Command, RawCommands } from '../types'
2020-11-05 05:38:52 +08:00
2021-02-11 01:05:02 +08:00
declare module '@tiptap/core' {
2021-02-17 01:39:37 +08:00
interface Commands {
2021-02-16 18:27:58 +08:00
setContent: {
/**
* Replace the whole document with new content.
*/
setContent: (content: string, emitUpdate?: Boolean, parseOptions?: AnyObject) => Command,
}
2021-02-11 01:05:02 +08:00
}
}
2021-02-17 01:36:37 +08:00
export const setContent: RawCommands['setContent'] = (content, emitUpdate = false, parseOptions = {}) => ({ tr, editor, dispatch }) => {
2020-11-05 05:38:52 +08:00
const { createDocument } = editor
const { doc } = tr
const document = createDocument(content, parseOptions)
const selection = TextSelection.create(doc, 0, doc.content.size)
if (dispatch) {
tr.setSelection(selection)
.replaceSelectionWith(document, false)
.setMeta('preventUpdate', !emitUpdate)
}
return true
}