forked from Milkdown/milkdown
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
70 lines (59 loc) · 2.03 KB
/
main.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/* Copyright 2021, Milkdown by Mirone. */
import type { Editor } from '@milkdown/core'
import { editorViewCtx, parserCtx, serializerCtx } from '@milkdown/core'
import { Slice } from '@milkdown/prose/model'
import '@milkdown/theme-nord/style.css'
import './style.css'
const mapping = {
'preset-commonmark': () => import('./preset-commonmark'),
'preset-gfm': () => import('./preset-gfm'),
'plugin-listener': () => import('./plugin-listener'),
'plugin-clipboard': () => import('./plugin-clipboard'),
'plugin-math': () => import('./plugin-math'),
}
let editor: Editor | undefined
const main = async () => {
const url = new URL(location.href)
if (!url.hash)
return
const key = url.hash.slice(2) as keyof typeof mapping
const name = mapping[key]
if (!name)
throw new Error(`Cannot get target test container: ${key}`)
if (editor)
await editor.destroy()
const module = await name()
editor = await module.setup()
globalThis.__milkdown__ = editor
globalThis.__setMarkdown__ = (markdown: string) =>
editor!.action((ctx) => {
const view = ctx.get(editorViewCtx)
const parser = ctx.get(parserCtx)
const doc = parser(markdown)
if (!doc)
return
const state = view.state
view.dispatch(state.tr.replace(0, state.doc.content.size, new Slice(doc.content, 0, 0)))
})
globalThis.__getMarkdown__ = () =>
editor!.action((ctx) => {
const view = ctx.get(editorViewCtx)
const serializer = ctx.get(serializerCtx)
return serializer(view.state.doc)
})
globalThis.__inspect__ = () => editor!.inspect()
const logButton = document.querySelector<HTMLDivElement>('#log')
if (logButton) {
// eslint-disable-next-line no-console
logButton.onclick = () => console.log(globalThis.__getMarkdown__())
}
const inspectButton = document.querySelector<HTMLDivElement>('#inspect')
if (inspectButton) {
// eslint-disable-next-line no-console
inspectButton.onclick = () => console.log(globalThis.__inspect__())
}
}
main()
window.onhashchange = () => {
main()
}