-
-
Notifications
You must be signed in to change notification settings - Fork 426
/
Copy pathreplace-all.ts
45 lines (40 loc) · 1.07 KB
/
replace-all.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import type { Ctx } from '@milkdown/ctx'
import {
editorStateOptionsCtx,
editorViewCtx,
parserCtx,
prosePluginsCtx,
schemaCtx,
} from '@milkdown/core'
import { Slice } from '@milkdown/prose/model'
import { EditorState } from '@milkdown/prose/state'
/// Replace all content of the editor with markdown string.
/// If flush is true, the editor state will be re-created.
export function replaceAll(markdown: string, flush = false) {
return (ctx: Ctx): void => {
const view = ctx.get(editorViewCtx)
const parser = ctx.get(parserCtx)
const doc = parser(markdown)
if (!doc) return
if (!flush) {
const { state } = view
return view.dispatch(
state.tr.replace(
0,
state.doc.content.size,
new Slice(doc.content, 0, 0)
)
)
}
const schema = ctx.get(schemaCtx)
const options = ctx.get(editorStateOptionsCtx)
const plugins = ctx.get(prosePluginsCtx)
const state = EditorState.create({
schema,
doc,
plugins,
...options,
})
view.updateState(state)
}
}