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

32 lines
775 B
TypeScript
Raw Normal View History

2020-09-21 05:44:38 +08:00
import { Command } from '../Editor'
2020-03-30 04:24:51 +08:00
import { TextSelection } from 'prosemirror-state'
type SetContentCommand = (
2020-04-22 05:22:27 +08:00
content: string,
emitUpdate?: Boolean,
parseOptions?: any,
2020-09-21 05:44:38 +08:00
) => Command
2020-04-22 05:22:27 +08:00
2020-03-30 04:24:51 +08:00
declare module '../Editor' {
interface Editor {
setContent: SetContentCommand,
2020-03-30 04:24:51 +08:00
}
}
2020-09-21 05:44:38 +08:00
export const setContent: SetContentCommand = (content = null, emitUpdate = false, parseOptions = {}) => ({ tr, editor }) => {
2020-03-30 05:06:37 +08:00
if (content === null) {
2020-09-21 05:44:38 +08:00
return false
2020-03-30 05:06:37 +08:00
}
2020-03-30 05:24:37 +08:00
2020-09-21 05:44:38 +08:00
const { createDocument } = editor
const { doc } = tr
2020-03-30 04:24:51 +08:00
const document = createDocument(content, parseOptions)
const selection = TextSelection.create(doc, 0, doc.content.size)
2020-09-21 05:44:38 +08:00
tr.setSelection(selection)
2020-03-30 04:24:51 +08:00
.replaceSelectionWith(document, false)
.setMeta('preventUpdate', !emitUpdate)
2020-09-21 05:44:38 +08:00
return true
2020-03-30 04:24:51 +08:00
}