-
-
Notifications
You must be signed in to change notification settings - Fork 432
/
Copy pathnode-view.ts
303 lines (257 loc) · 8.02 KB
/
node-view.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import type { EditorView, NodeView } from '@milkdown/prose/view'
import {
EditorView as CodeMirror,
type KeyBinding,
type ViewUpdate,
keymap as cmKeymap,
} from '@codemirror/view'
import type { Node } from '@milkdown/prose/model'
import { redo, undo } from '@milkdown/prose/history'
import { Compartment, EditorState } from '@codemirror/state'
import type { Line, SelectionRange } from '@codemirror/state'
import { exitCode } from '@milkdown/prose/commands'
import { TextSelection } from '@milkdown/prose/state'
import { createApp, ref, watchEffect, type App, type WatchHandle } from 'vue'
import type { CodeBlockConfig } from '../config'
import type { LanguageLoader } from './loader'
import { CodeBlock } from './components/code-block'
export class CodeMirrorBlock implements NodeView {
dom: HTMLElement
cm: CodeMirror
app: App
readonly = ref(false)
selected = ref(false)
language = ref('')
text = ref('')
private updating = false
private languageName: string = ''
private disposeSelectedWatcher: WatchHandle
private readonly languageConf: Compartment
private readonly readOnlyConf: Compartment
constructor(
public node: Node,
public view: EditorView,
public getPos: () => number | undefined,
public loader: LanguageLoader,
public config: CodeBlockConfig
) {
this.languageConf = new Compartment()
this.readOnlyConf = new Compartment()
this.cm = new CodeMirror({
doc: this.node.textContent,
root: this.view.root,
extensions: [
this.readOnlyConf.of(EditorState.readOnly.of(!this.view.editable)),
cmKeymap.of(this.codeMirrorKeymap()),
this.languageConf.of([]),
...config.extensions,
CodeMirror.updateListener.of(this.forwardUpdate),
],
})
this.app = this.createApp()
this.dom = this.createDom(this.app)
this.disposeSelectedWatcher = watchEffect(() => {
const isSelected = this.selected.value
if (isSelected) {
this.dom.classList.add('selected')
} else {
this.dom.classList.remove('selected')
}
})
this.updateLanguage()
}
private forwardUpdate = (update: ViewUpdate) => {
if (this.updating || !this.cm.hasFocus) return
let offset = (this.getPos() ?? 0) + 1
const { main } = update.state.selection
const selFrom = offset + main.from
const selTo = offset + main.to
const pmSel = this.view.state.selection
if (update.docChanged || pmSel.from !== selFrom || pmSel.to !== selTo) {
const tr = this.view.state.tr
update.changes.iterChanges((fromA, toA, fromB, toB, text) => {
if (text.length)
tr.replaceWith(
offset + fromA,
offset + toA,
this.view.state.schema.text(text.toString())
)
else tr.delete(offset + fromA, offset + toA)
offset += toB - fromB - (toA - fromA)
})
tr.setSelection(TextSelection.create(tr.doc, selFrom, selTo))
this.view.dispatch(tr)
}
}
private createApp = () => {
return createApp(CodeBlock, {
text: this.text,
selected: this.selected,
readonly: this.readonly,
codemirror: this.cm,
language: this.language,
getAllLanguages: this.getAllLanguages,
setLanguage: this.setLanguage,
config: this.config,
})
}
private createDom(app: App) {
const dom = document.createElement('div')
dom.className = 'milkdown-code-block'
this.text.value = this.node.textContent
app.mount(dom)
return dom
}
private updateLanguage() {
const languageName = this.node.attrs.language
if (languageName === this.languageName) return
this.language.value = languageName
const language = this.loader.load(languageName ?? '')
language.then((lang) => {
if (lang) {
this.cm.dispatch({
effects: this.languageConf.reconfigure(lang),
})
this.languageName = languageName
}
})
}
private codeMirrorKeymap = (): KeyBinding[] => {
const view = this.view
return [
{ key: 'ArrowUp', run: () => this.maybeEscape('line', -1) },
{ key: 'ArrowLeft', run: () => this.maybeEscape('char', -1) },
{ key: 'ArrowDown', run: () => this.maybeEscape('line', 1) },
{ key: 'ArrowRight', run: () => this.maybeEscape('char', 1) },
{
key: 'Mod-Enter',
run: () => {
if (!exitCode(view.state, view.dispatch)) return false
view.focus()
return true
},
},
{ key: 'Mod-z', run: () => undo(view.state, view.dispatch) },
{ key: 'Shift-Mod-z', run: () => redo(view.state, view.dispatch) },
{ key: 'Mod-y', run: () => redo(view.state, view.dispatch) },
{
key: 'Backspace',
run: () => {
const ranges = this.cm.state.selection.ranges
if (ranges.length > 1) return false
const selection = ranges[0]
if (selection && (!selection.empty || selection.anchor > 0))
return false
if (this.cm.state.doc.lines >= 2) return false
const state = this.view.state
const pos = this.getPos() ?? 0
const tr = state.tr.replaceWith(
pos,
pos + this.node.nodeSize,
state.schema.nodes.paragraph!.createChecked({}, this.node.content)
)
tr.setSelection(TextSelection.near(tr.doc.resolve(pos)))
this.view.dispatch(tr)
this.view.focus()
return true
},
},
]
}
private maybeEscape = (unit: 'line' | 'char', dir: -1 | 1): boolean => {
const { state } = this.cm
let main: SelectionRange | Line = state.selection.main
if (!main.empty) return false
if (unit === 'line') main = state.doc.lineAt(main.head)
if (dir < 0 ? main.from > 0 : main.to < state.doc.length) return false
const targetPos = (this.getPos() ?? 0) + (dir < 0 ? 0 : this.node.nodeSize)
const selection = TextSelection.near(
this.view.state.doc.resolve(targetPos),
dir
)
const tr = this.view.state.tr.setSelection(selection).scrollIntoView()
this.view.dispatch(tr)
this.view.focus()
return true
}
setSelection(anchor: number, head: number) {
if (!this.cm.dom.isConnected) return
this.cm.focus()
this.updating = true
this.cm.dispatch({ selection: { anchor, head } })
this.updating = false
}
update(node: Node) {
if (node.type !== this.node.type) return false
if (this.updating) return true
this.node = node
this.text.value = node.textContent
this.updateLanguage()
if (this.view.editable === this.cm.state.readOnly) {
this.cm.dispatch({
effects: this.readOnlyConf.reconfigure(
EditorState.readOnly.of(!this.view.editable)
),
})
}
const change = computeChange(this.cm.state.doc.toString(), node.textContent)
if (change) {
this.updating = true
this.cm.dispatch({
changes: { from: change.from, to: change.to, insert: change.text },
})
this.updating = false
}
return true
}
selectNode() {
this.selected.value = true
this.cm.focus()
}
deselectNode() {
this.selected.value = false
}
stopEvent() {
return true
}
destroy() {
this.app.unmount()
this.cm.destroy()
this.disposeSelectedWatcher()
}
setLanguage = (language: string) => {
this.view.dispatch(
this.view.state.tr.setNodeAttribute(
this.getPos() ?? 0,
'language',
language
)
)
}
getAllLanguages = () => {
return this.loader.getAll()
}
}
function computeChange(
oldVal: string,
newVal: string
): { from: number; to: number; text: string } | null {
if (oldVal === newVal) return null
let start = 0
let oldEnd = oldVal.length
let newEnd = newVal.length
while (
start < oldEnd &&
oldVal.charCodeAt(start) === newVal.charCodeAt(start)
)
++start
while (
oldEnd > start &&
newEnd > start &&
oldVal.charCodeAt(oldEnd - 1) === newVal.charCodeAt(newEnd - 1)
) {
oldEnd--
newEnd--
}
return { from: start, to: oldEnd, text: newVal.slice(start, newEnd) }
}