-
Notifications
You must be signed in to change notification settings - Fork 35
/
math-nodeview.ts
338 lines (287 loc) · 10.4 KB
/
math-nodeview.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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
/*---------------------------------------------------------
* Author: Benjamin R. Bray
* License: MIT (see LICENSE in project root for details)
*--------------------------------------------------------*/
// prosemirror imports
import { Node as ProseNode } from "prosemirror-model";
import { EditorState, Transaction, TextSelection, NodeSelection, PluginKey } from "prosemirror-state";
import { NodeView, EditorView, Decoration } from "prosemirror-view";
import { StepMap } from "prosemirror-transform";
import { keymap } from "prosemirror-keymap";
import { newlineInCode, chainCommands, deleteSelection, liftEmptyBlock, Command } from "prosemirror-commands";
// katex
import katex, { ParseError, KatexOptions } from "katex";
import { nudgeCursorBackCmd, nudgeCursorForwardCmd } from "./commands/move-cursor-cmd";
import { collapseMathCmd } from "./commands/collapse-math-cmd";
import { IMathPluginState } from "./math-plugin";
//// INLINE MATH NODEVIEW //////////////////////////////////
export interface ICursorPosObserver {
/** indicates on which side cursor should appear when this node is selected */
cursorSide: "start" | "end";
/** */
updateCursorPos(state: EditorState): void;
}
interface IMathViewOptions {
/** Dom element name to use for this NodeView */
tagName?: string;
/** Whether to render this node as display or inline math. */
katexOptions?:KatexOptions;
}
export class MathView implements NodeView, ICursorPosObserver {
// nodeview params
private _node: ProseNode;
private _outerView: EditorView;
private _getPos: (() => number);
// nodeview dom
dom: HTMLElement;
private _mathRenderElt: HTMLElement | undefined;
private _mathSrcElt: HTMLElement | undefined;
private _innerView: EditorView | undefined;
// internal state
cursorSide: "start" | "end";
private _katexOptions: KatexOptions;
private _tagName: string;
private _isEditing: boolean;
private _onDestroy: (() => void) | undefined;
private _mathPluginKey: PluginKey<IMathPluginState>;
// == Lifecycle ===================================== //
/**
* @param onDestroy Callback for when this NodeView is destroyed.
* This NodeView should unregister itself from the list of ICursorPosObservers.
*
* Math Views support the following options:
* @option displayMode If TRUE, will render math in display mode, otherwise in inline mode.
* @option tagName HTML tag name to use for this NodeView. If none is provided,
* will use the node name with underscores converted to hyphens.
*/
constructor(
node: ProseNode,
view: EditorView,
getPos: (() => number),
options: IMathViewOptions = {},
mathPluginKey: PluginKey<IMathPluginState>,
onDestroy?: (() => void)
) {
// store arguments
this._node = node;
this._outerView = view;
this._getPos = getPos;
this._onDestroy = onDestroy && onDestroy.bind(this);
this._mathPluginKey = mathPluginKey;
// editing state
this.cursorSide = "start";
this._isEditing = false;
// options
this._katexOptions = Object.assign({ globalGroup: true, throwOnError: false }, options.katexOptions);
this._tagName = options.tagName || this._node.type.name.replace("_", "-");
// create dom representation of nodeview
this.dom = document.createElement(this._tagName);
this.dom.classList.add("math-node");
this._mathRenderElt = document.createElement("span");
this._mathRenderElt.textContent = "";
this._mathRenderElt.classList.add("math-render");
this.dom.appendChild(this._mathRenderElt);
this._mathSrcElt = document.createElement("span");
this._mathSrcElt.classList.add("math-src");
this.dom.appendChild(this._mathSrcElt);
// ensure
this.dom.addEventListener("click", () => this.ensureFocus());
// render initial content
this.renderMath();
}
destroy() {
// close the inner editor without rendering
this.closeEditor(false);
// clean up dom elements
if (this._mathRenderElt) {
this._mathRenderElt.remove();
delete this._mathRenderElt;
}
if (this._mathSrcElt) {
this._mathSrcElt.remove();
delete this._mathSrcElt;
}
this.dom.remove();
}
/**
* Ensure focus on the inner editor whenever this node has focus.
* This helps to prevent accidental deletions of math blocks.
*/
ensureFocus() {
if (this._innerView && this._outerView.hasFocus()) {
this._innerView.focus();
}
}
// == Updates ======================================= //
update(node: ProseNode, decorations: Decoration[]) {
if (!node.sameMarkup(this._node)) return false
this._node = node;
if (this._innerView) {
let state = this._innerView.state;
let start = node.content.findDiffStart(state.doc.content)
if (start != null) {
let diff = node.content.findDiffEnd(state.doc.content as any);
if (diff) {
let { a: endA, b: endB } = diff;
let overlap = start - Math.min(endA, endB)
if (overlap > 0) { endA += overlap; endB += overlap }
this._innerView.dispatch(
state.tr
.replace(start, endB, node.slice(start, endA))
.setMeta("fromOutside", true))
}
}
}
if (!this._isEditing) {
this.renderMath();
}
return true;
}
updateCursorPos(state: EditorState): void {
const pos = this._getPos();
const size = this._node.nodeSize;
const inPmSelection =
(state.selection.from < pos + size)
&& (pos < state.selection.to);
if (!inPmSelection) {
this.cursorSide = (pos < state.selection.from) ? "end" : "start";
}
}
// == Events ===================================== //
selectNode() {
if (!this._outerView.editable) { return; }
this.dom.classList.add("ProseMirror-selectednode");
if (!this._isEditing) { this.openEditor(); }
}
deselectNode() {
this.dom.classList.remove("ProseMirror-selectednode");
if (this._isEditing) { this.closeEditor(); }
}
stopEvent(event: Event): boolean {
return (this._innerView !== undefined)
&& (event.target !== undefined)
&& this._innerView.dom.contains(event.target as Node);
}
ignoreMutation() { return true; }
// == Rendering ===================================== //
renderMath() {
if (!this._mathRenderElt) { return; }
// get tex string to render
let content = this._node.content.content;
let texString = "";
if (content.length > 0 && content[0].textContent !== null) {
texString = content[0].textContent.trim();
}
// empty math?
if (texString.length < 1) {
this.dom.classList.add("empty-math");
// clear rendered math, since this node is in an invalid state
while(this._mathRenderElt.firstChild){ this._mathRenderElt.firstChild.remove(); }
// do not render empty math
return;
} else {
this.dom.classList.remove("empty-math");
}
// render katex, but fail gracefully
try {
katex.render(texString, this._mathRenderElt, this._katexOptions);
this._mathRenderElt.classList.remove("parse-error");
this.dom.setAttribute("title", "");
} catch (err) {
if (err instanceof ParseError) {
console.error(err);
this._mathRenderElt.classList.add("parse-error");
this.dom.setAttribute("title", err.toString());
} else {
throw err;
}
}
}
// == Inner Editor ================================== //
dispatchInner(tr: Transaction) {
if (!this._innerView) { return; }
let { state, transactions } = this._innerView.state.applyTransaction(tr)
this._innerView.updateState(state)
if (!tr.getMeta("fromOutside")) {
let outerTr = this._outerView.state.tr, offsetMap = StepMap.offset(this._getPos() + 1)
for (let i = 0; i < transactions.length; i++) {
let steps = transactions[i].steps
for (let j = 0; j < steps.length; j++) {
let mapped = steps[j].map(offsetMap);
if (!mapped) { throw Error("step discarded!"); }
outerTr.step(mapped)
}
}
if (outerTr.docChanged) this._outerView.dispatch(outerTr)
}
}
openEditor() {
if (this._innerView) { throw Error("inner view should not exist!"); }
// create a nested ProseMirror view
this._innerView = new EditorView(this._mathSrcElt, {
state: EditorState.create({
doc: this._node,
plugins: [keymap({
"Tab": (state, dispatch) => {
if(dispatch){ dispatch(state.tr.insertText("\t")); }
return true;
},
"Backspace": chainCommands(deleteSelection, (state, dispatch, tr_inner) => {
// default backspace behavior for non-empty selections
if(!state.selection.empty) { return false; }
// default backspace behavior when math node is non-empty
if(this._node.textContent.length > 0){ return false; }
// otherwise, we want to delete the empty math node and focus the outer view
this._outerView.dispatch(this._outerView.state.tr.insertText(""));
this._outerView.focus();
return true;
}),
"Ctrl-Backspace" : (state, dispatch, tr_inner) => {
// delete math node and focus the outer view
this._outerView.dispatch(this._outerView.state.tr.insertText(""));
this._outerView.focus();
return true;
},
"Enter": chainCommands(newlineInCode, collapseMathCmd(this._outerView, +1, false)),
"Ctrl-Enter" : collapseMathCmd(this._outerView, +1, false),
"ArrowLeft" : collapseMathCmd(this._outerView, -1, true),
"ArrowRight" : collapseMathCmd(this._outerView, +1, true),
"ArrowUp" : collapseMathCmd(this._outerView, -1, true),
"ArrowDown" : collapseMathCmd(this._outerView, +1, true),
})]
}),
dispatchTransaction: this.dispatchInner.bind(this)
})
// focus element
let innerState = this._innerView.state;
this._innerView.focus();
// request outer cursor position before math node was selected
let maybePos = this._mathPluginKey.getState(this._outerView.state)?.prevCursorPos;
if(maybePos === null || maybePos === undefined) {
console.error("[prosemirror-math] Error: Unable to fetch math plugin state from key.");
}
let prevCursorPos: number = maybePos ?? 0;
// compute position that cursor should appear within the expanded math node
let innerPos = (prevCursorPos <= this._getPos()) ? 0 : this._node.nodeSize - 2;
this._innerView.dispatch(
innerState.tr.setSelection(
TextSelection.create(innerState.doc, innerPos)
)
);
this._isEditing = true;
}
/**
* Called when the inner ProseMirror editor should close.
*
* @param render Optionally update the rendered math after closing. (which
* is generally what we want to do, since the user is done editing!)
*/
closeEditor(render: boolean = true) {
if (this._innerView) {
this._innerView.destroy();
this._innerView = undefined;
}
if (render) { this.renderMath(); }
this._isEditing = false;
}
}