@bitbindle/prosemirror-view 0.0.0-stage → 1.44.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1518 @@
1
+ import {DOMSerializer, Fragment, Mark, Node, TagParseRule} from "prosemirror-model"
2
+ import {TextSelection} from "prosemirror-state"
3
+
4
+ import {domIndex, DOMNode, isElt, isText, contains} from "./dom"
5
+ import * as browser from "./browser"
6
+ import {Decoration, DecorationSource, WidgetConstructor, WidgetType, NodeType} from "./decoration"
7
+ import {EditorView} from "./index"
8
+
9
+ declare global {
10
+ interface Node {
11
+ /// @internal
12
+ pmViewDesc?: ViewDesc
13
+ }
14
+ }
15
+
16
+ /// A ViewMutationRecord represents a DOM
17
+ /// [mutation](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver)
18
+ /// or a selection change happens within the view. When the change is
19
+ /// a selection change, the record will have a `type` property of
20
+ /// `"selection"` (which doesn't occur for native mutation records).
21
+ export type ViewMutationRecord = MutationRecord | { type: "selection", target: DOMNode }
22
+
23
+ /// By default, document nodes are rendered using the result of the
24
+ /// [`toDOM`](#model.NodeSpec.toDOM) method of their spec, and managed
25
+ /// entirely by the editor. For some use cases, such as embedded
26
+ /// node-specific editing interfaces, you want more control over
27
+ /// the behavior of a node's in-editor representation, and need to
28
+ /// [define](#view.EditorProps.nodeViews) a custom node view.
29
+ ///
30
+ /// Objects returned as node views must conform to this interface.
31
+ export interface NodeView {
32
+ /// The outer DOM node that represents the document node.
33
+ dom: HTMLElement
34
+
35
+ /// The DOM node that should hold the node's content. Only meaningful
36
+ /// if the node view also defines a `dom` property and if its node
37
+ /// type is not a leaf node type. When this is present, ProseMirror
38
+ /// will take care of rendering the node's children into it. When it
39
+ /// is not present, the node view itself is responsible for rendering
40
+ /// (or deciding not to render) its child nodes.
41
+ contentDOM?: HTMLElement | null
42
+
43
+ /// When given, this will be called when the view is updating
44
+ /// itself. It will be given a node, an array of active decorations
45
+ /// around the node (which are automatically drawn, and the node
46
+ /// view may ignore if it isn't interested in them), and a
47
+ /// [decoration source](#view.DecorationSource) that represents any
48
+ /// decorations that apply to the content of the node (which again
49
+ /// may be ignored). It should return true if it was able to update
50
+ /// to that node, and false otherwise. If the node view has a
51
+ /// `contentDOM` property (or no `dom` property), updating its child
52
+ /// nodes will be handled by ProseMirror.
53
+ update?: (node: Node, decorations: readonly Decoration[], innerDecorations: DecorationSource) => boolean
54
+
55
+ /// By default, `update` will only be called when a node of the same
56
+ /// node type appears in this view's position. When you set this to
57
+ /// true, it will be called for any node, making it possible to have
58
+ /// a node view that representsmultiple types of nodes. You will
59
+ /// need to check the type of the nodes you get in `update` and
60
+ /// return `false` for types you cannot handle.
61
+ multiType?: boolean
62
+
63
+ /// Can be used to override the way the node's selected status (as a
64
+ /// node selection) is displayed.
65
+ selectNode?: () => void
66
+
67
+ /// When defining a `selectNode` method, you should also provide a
68
+ /// `deselectNode` method to remove the effect again.
69
+ deselectNode?: () => void
70
+
71
+ /// This will be called to handle setting the selection inside the
72
+ /// node. The `anchor` and `head` positions are relative to the start
73
+ /// of the node. By default, a DOM selection will be created between
74
+ /// the DOM positions corresponding to those positions, but if you
75
+ /// override it you can do something else.
76
+ setSelection?: (anchor: number, head: number, root: Document | ShadowRoot) => void
77
+
78
+ /// Can be used to prevent the editor view from trying to handle some
79
+ /// or all DOM events that bubble up from the node view. Events for
80
+ /// which this returns true are not handled by the editor.
81
+ stopEvent?: (event: Event) => boolean
82
+
83
+ /// Called when a [mutation](#view.ViewMutationRecord) happens within the
84
+ /// view. Return false if the editor should re-read the selection or re-parse
85
+ /// the range around the mutation, true if it can safely be ignored.
86
+ ignoreMutation?: (mutation: ViewMutationRecord) => boolean
87
+
88
+ /// Called when the node view is removed from the editor or the whole
89
+ /// editor is destroyed.
90
+ destroy?: () => void
91
+ }
92
+
93
+ /// By default, document marks are rendered using the result of the
94
+ /// [`toDOM`](#model.MarkSpec.toDOM) method of their spec, and managed entirely
95
+ /// by the editor. For some use cases, you want more control over the behavior
96
+ /// of a mark's in-editor representation, and need to
97
+ /// [define](#view.EditorProps.markViews) a custom mark view.
98
+ ///
99
+ /// Objects returned as mark views must conform to this interface.
100
+ export interface MarkView {
101
+ /// The outer DOM node that represents the document node.
102
+ dom: HTMLElement
103
+
104
+ /// The DOM node that should hold the mark's content. When this is not
105
+ /// present, the `dom` property is used as the content DOM.
106
+ contentDOM?: HTMLElement | null
107
+
108
+ /// When given, this is called when the view is updating itself. It
109
+ /// will be given a mark (of the same type as the current one). When it
110
+ /// returns true, the existing DOM is kept and reused (its content is
111
+ /// still managed by ProseMirror); when it returns false, the mark view
112
+ /// is rebuilt.
113
+ update?: (mark: Mark) => boolean
114
+
115
+ /// Called when a [mutation](#view.ViewMutationRecord) happens within the
116
+ /// view. Return false if the editor should re-read the selection or re-parse
117
+ /// the range around the mutation, true if it can safely be ignored.
118
+ ignoreMutation?: (mutation: ViewMutationRecord) => boolean
119
+
120
+
121
+ /// Called when the mark view is removed from the editor or the whole
122
+ /// editor is destroyed.
123
+ destroy?: () => void
124
+ }
125
+
126
+ // View descriptions are data structures that describe the DOM that is
127
+ // used to represent the editor's content. They are used for:
128
+ //
129
+ // - Incremental redrawing when the document changes
130
+ //
131
+ // - Figuring out what part of the document a given DOM position
132
+ // corresponds to
133
+ //
134
+ // - Wiring in custom implementations of the editing interface for a
135
+ // given node
136
+ //
137
+ // They form a doubly-linked mutable tree, starting at `view.docView`.
138
+
139
+ // Bit field used to track DOM damage to a view structure or its
140
+ // content.
141
+ export const enum Damage {
142
+ None = 0,
143
+ Child = 1, // At least one child has some kind of damage
144
+ ChildList = 2, // Nodes have been added or removed in the child list, or a mark was damaged
145
+ Structure = 4, // The node's own structure or that of a wrapping decoration has been damaged
146
+ Text = 8 // The text content of a text node was changed
147
+ }
148
+
149
+ // Superclass for the various kinds of descriptions. Defines their
150
+ // basic structure and shared methods.
151
+ export class ViewDesc {
152
+ damage = Damage.None
153
+ declare node: Node | null
154
+
155
+ constructor(
156
+ public parent: ViewDesc | undefined,
157
+ public children: ViewDesc[],
158
+ public dom: DOMNode,
159
+ // This is the node that holds the child views. It may be null for
160
+ // descs that don't have children.
161
+ public contentDOM: HTMLElement | null
162
+ ) {
163
+ // An expando property on the DOM node provides a link back to its
164
+ // description.
165
+ dom.pmViewDesc = this
166
+ }
167
+
168
+ // Used to check whether a given description corresponds to a
169
+ // widget/mark/node.
170
+ matchesWidget(widget: Decoration) { return false }
171
+ matchesMark(mark: Mark) { return false }
172
+ matchesNode(node: Node, outerDeco: readonly Decoration[], innerDeco: DecorationSource) { return false }
173
+ matchesHack(nodeName: string) { return false }
174
+
175
+ // When parsing in-editor content (in domchange.js), we allow
176
+ // descriptions to determine the parse rules that should be used to
177
+ // parse them.
178
+ parseRule(addedNodes?: readonly DOMNode[]): Omit<TagParseRule, "tag"> | null { return null }
179
+
180
+ // Used by the editor's event handler to ignore events that come
181
+ // from certain descs.
182
+ stopEvent(event: Event) { return false }
183
+
184
+ // The size of the content represented by this desc.
185
+ get size() {
186
+ let size = 0
187
+ for (let i = 0; i < this.children.length; i++) size += this.children[i].size
188
+ return size
189
+ }
190
+
191
+ // For block nodes, this represents the space taken up by their
192
+ // start/end tokens.
193
+ get border() { return 0 }
194
+
195
+ destroy() {
196
+ this.parent = undefined
197
+ if (this.dom.pmViewDesc == this) this.dom.pmViewDesc = undefined
198
+ for (let i = 0; i < this.children.length; i++)
199
+ this.children[i].destroy()
200
+ }
201
+
202
+ posBeforeChild(child: ViewDesc): number {
203
+ for (let i = 0, pos = this.posAtStart;; i++) {
204
+ let cur = this.children[i]
205
+ if (cur == child) return pos
206
+ pos += cur.size
207
+ }
208
+ }
209
+
210
+ get posBefore() {
211
+ return this.parent!.posBeforeChild(this)
212
+ }
213
+
214
+ get posAtStart() {
215
+ return this.parent ? this.parent.posBeforeChild(this) + this.border : 0
216
+ }
217
+
218
+ get posAfter() {
219
+ return this.posBefore + this.size
220
+ }
221
+
222
+ get posAtEnd() {
223
+ return this.posAtStart + this.size - 2 * this.border
224
+ }
225
+
226
+ localPosFromDOM(dom: DOMNode, offset: number, bias: number): number {
227
+ // If the DOM position is in the content, use the child desc after
228
+ // it to figure out a position.
229
+ if (this.contentDOM && contains(this.contentDOM, dom)) {
230
+ if (bias < 0) {
231
+ let domBefore, desc: ViewDesc | undefined
232
+ if (dom == this.contentDOM) {
233
+ domBefore = dom.childNodes[offset - 1]
234
+ } else {
235
+ while (dom.parentNode != this.contentDOM) dom = dom.parentNode!
236
+ domBefore = dom.previousSibling
237
+ }
238
+ while (domBefore && !((desc = domBefore.pmViewDesc) && desc.parent == this)) domBefore = domBefore.previousSibling
239
+ return domBefore ? this.posBeforeChild(desc!) + desc!.size : this.posAtStart
240
+ } else {
241
+ let domAfter, desc: ViewDesc | undefined
242
+ if (dom == this.contentDOM) {
243
+ domAfter = dom.childNodes[offset]
244
+ } else {
245
+ while (dom.parentNode != this.contentDOM) dom = dom.parentNode!
246
+ domAfter = dom.nextSibling
247
+ }
248
+ while (domAfter && !((desc = domAfter.pmViewDesc) && desc.parent == this)) domAfter = domAfter.nextSibling
249
+ return domAfter ? this.posBeforeChild(desc!) : this.posAtEnd
250
+ }
251
+ }
252
+ // Otherwise, use various heuristics, falling back on the bias
253
+ // parameter, to determine whether to return the position at the
254
+ // start or at the end of this view desc.
255
+ let atEnd
256
+ if (dom == this.dom && this.contentDOM) {
257
+ atEnd = offset > domIndex(this.contentDOM)
258
+ } else if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM)) {
259
+ let rel = dom.compareDocumentPosition(this.contentDOM)
260
+ if (rel & 16) { // this.contentDOM is inside dom
261
+ atEnd = offset > Array.from(dom.childNodes).findIndex(n => n.contains(this.contentDOM))
262
+ } else { // Check if after or before
263
+ atEnd = !(rel & 4)
264
+ }
265
+ } else if (this.dom.firstChild) {
266
+ if (offset == 0) for (let search = dom;; search = search.parentNode!) {
267
+ if (search == this.dom) { atEnd = false; break }
268
+ if (search.previousSibling) break
269
+ }
270
+ if (atEnd == null && offset == dom.childNodes.length) for (let search = dom;; search = search.parentNode!) {
271
+ if (search == this.dom) { atEnd = true; break }
272
+ if (search.nextSibling) break
273
+ }
274
+ }
275
+ return (atEnd == null ? bias > 0 : atEnd) ? this.posAtEnd : this.posAtStart
276
+ }
277
+
278
+ // Scan up the dom finding the first desc that is a descendant of
279
+ // this one.
280
+ nearestDesc(dom: DOMNode): ViewDesc | undefined
281
+ nearestDesc(dom: DOMNode, onlyNodes: true): NodeViewDesc | undefined
282
+ nearestDesc(dom: DOMNode, onlyNodes: boolean = false) {
283
+ for (let first = true, cur: DOMNode | null = dom; cur; cur = cur.parentNode) {
284
+ let desc = this.getDesc(cur), nodeDOM
285
+ if (desc && (!onlyNodes || desc.node)) {
286
+ // If dom is outside of this desc's nodeDOM, don't count it.
287
+ if (first && (nodeDOM = (desc as NodeViewDesc).nodeDOM) &&
288
+ !(isElt(nodeDOM) ? contains(nodeDOM, dom) : nodeDOM == dom))
289
+ first = false
290
+ else
291
+ return desc
292
+ }
293
+ }
294
+ }
295
+
296
+ getDesc(dom: DOMNode) {
297
+ let desc = dom.pmViewDesc
298
+ for (let cur: ViewDesc | undefined = desc; cur; cur = cur.parent) if (cur == this) return desc
299
+ }
300
+
301
+ posFromDOM(dom: DOMNode, offset: number, bias: number) {
302
+ for (let scan: DOMNode | null = dom; scan; scan = scan.parentNode) {
303
+ let desc = this.getDesc(scan)
304
+ if (desc) return desc.localPosFromDOM(dom, offset, bias)
305
+ }
306
+ return -1
307
+ }
308
+
309
+ // Find the desc for the node after the given pos, if any. (When a
310
+ // parent node overrode rendering, there might not be one.)
311
+ descAt(pos: number): NodeViewDesc | undefined {
312
+ for (let i = 0, offset = 0; i < this.children.length; i++) {
313
+ let child = this.children[i], end = offset + child.size
314
+ if (offset == pos && end != offset) {
315
+ while (!child.border && child.children.length) {
316
+ for (let i = 0; i < child.children.length; i++) {
317
+ let inner = child.children[i]
318
+ if (inner.size) { child = inner; break }
319
+ }
320
+ }
321
+ return child as NodeViewDesc
322
+ }
323
+ if (pos < end) return child.descAt(pos - offset - child.border)
324
+ offset = end
325
+ }
326
+ }
327
+
328
+ domFromPos(pos: number, side: number): {node: DOMNode, offset: number, atom?: number} {
329
+ if (!this.contentDOM) return {node: this.dom, offset: 0, atom: pos + 1}
330
+ // First find the position in the child array
331
+ let i = 0, offset = 0
332
+ for (let curPos = 0; i < this.children.length; i++) {
333
+ let child = this.children[i], end = curPos + child.size
334
+ if (end > pos) { offset = pos - curPos; break }
335
+ curPos = end
336
+ }
337
+ // If this points into the middle of a child, call through
338
+ if (offset) return this.children[i].domFromPos(offset - this.children[i].border, side)
339
+ // Go back if there were any zero-length widgets with side >= 0 before this point
340
+ for (; i > 0; i--) {
341
+ let prev = this.children[i - 1]
342
+ if (prev.size || !(prev instanceof BufferHackViewDesc || prev instanceof WidgetViewDesc && prev.side >= 0))
343
+ break
344
+ }
345
+ // Scan towards the first useable node
346
+ if (side <= 0) {
347
+ let prev, enter = true
348
+ for (;; i--, enter = false) {
349
+ prev = i ? this.children[i - 1] : null
350
+ if (!prev || prev.dom.parentNode == this.contentDOM) break
351
+ }
352
+ if (prev && side && enter && !prev.border && !prev.domAtom) return prev.domFromPos(prev.size, side)
353
+ return {node: this.contentDOM, offset: prev ? domIndex(prev.dom) + 1 : 0}
354
+ } else {
355
+ let next, enter = true
356
+ for (;; i++, enter = false) {
357
+ next = i < this.children.length ? this.children[i] : null
358
+ if (!next || next.dom.parentNode == this.contentDOM) break
359
+ }
360
+ if (next && enter && !next.border && !next.domAtom) return next.domFromPos(0, side)
361
+ return {node: this.contentDOM, offset: next ? domIndex(next.dom) : this.contentDOM.childNodes.length}
362
+ }
363
+ }
364
+
365
+ // Used to find a DOM range in a single parent for a given changed
366
+ // range.
367
+ parseRange(
368
+ from: number, to: number, base = 0
369
+ ): {node: DOMNode, from: number, to: number, fromOffset: number, toOffset: number} {
370
+ if (this.children.length == 0)
371
+ return {node: this.contentDOM!, from, to, fromOffset: 0, toOffset: this.contentDOM!.childNodes.length}
372
+
373
+ let fromOffset = -1, toOffset = -1
374
+ for (let offset = base, i = 0;; i++) {
375
+ let child = this.children[i], end = offset + child.size
376
+ if (fromOffset == -1 && from <= end) {
377
+ let childBase = offset + child.border
378
+ // FIXME maybe descend mark views to parse a narrower range?
379
+ if (from >= childBase && to <= end - child.border && child.node &&
380
+ child.contentDOM && this.contentDOM!.contains(child.contentDOM))
381
+ return child.parseRange(from, to, childBase)
382
+
383
+ from = offset
384
+ for (let j = i; j > 0; j--) {
385
+ let prev = this.children[j - 1]
386
+ if (prev.size && prev.dom.parentNode == this.contentDOM && !prev.emptyChildAt(1)) {
387
+ fromOffset = domIndex(prev.dom) + 1
388
+ break
389
+ }
390
+ from -= prev.size
391
+ }
392
+ if (fromOffset == -1) fromOffset = 0
393
+ }
394
+ if (fromOffset > -1 && (end > to || i == this.children.length - 1)) {
395
+ to = end
396
+ for (let j = i + 1; j < this.children.length; j++) {
397
+ let next = this.children[j]
398
+ if (next.size && next.dom.parentNode == this.contentDOM && !next.emptyChildAt(-1)) {
399
+ toOffset = domIndex(next.dom)
400
+ break
401
+ }
402
+ to += next.size
403
+ }
404
+ if (toOffset == -1) toOffset = this.contentDOM!.childNodes.length
405
+ break
406
+ }
407
+ offset = end
408
+ }
409
+ return {node: this.contentDOM!, from, to, fromOffset, toOffset}
410
+ }
411
+
412
+ emptyChildAt(side: number): boolean {
413
+ if (this.border || !this.contentDOM || !this.children.length) return false
414
+ let child = this.children[side < 0 ? 0 : this.children.length - 1]
415
+ return child.size == 0 || child.emptyChildAt(side)
416
+ }
417
+
418
+ domAfterPos(pos: number): DOMNode {
419
+ let {node, offset} = this.domFromPos(pos, 0)
420
+ if (!isElt(node) || offset == node.childNodes.length)
421
+ throw new RangeError("No node after pos " + pos)
422
+ return node.childNodes[offset]
423
+ }
424
+
425
+ ignoreMutation(mutation: ViewMutationRecord): boolean {
426
+ return !this.contentDOM && mutation.type != "selection"
427
+ }
428
+
429
+ get contentLost() {
430
+ return this.contentDOM && this.contentDOM != this.dom && !this.dom.contains(this.contentDOM)
431
+ }
432
+
433
+ markDamage(damage: Damage) {
434
+ if (damage) {
435
+ this.damage |= damage
436
+ this.markParentDamage()
437
+ }
438
+ }
439
+
440
+ markParentDamage() {
441
+ for (let cur: ViewDesc = this;;) {
442
+ let {parent} = cur
443
+ if (!parent || (parent.damage & Damage.Child)) break
444
+ parent.damage |= Damage.Child
445
+ cur = parent
446
+ }
447
+ }
448
+
449
+ get domAtom() { return false }
450
+
451
+ get ignoreForCoords() { return false }
452
+
453
+ get ignoreForSelection() { return false }
454
+
455
+ isText(text: string) { return false }
456
+ }
457
+
458
+ // A widget desc represents a widget decoration, which is a DOM node
459
+ // drawn between the document nodes.
460
+ class WidgetViewDesc extends ViewDesc {
461
+ constructor(parent: ViewDesc, readonly widget: Decoration, view: EditorView, pos: number) {
462
+ let self: WidgetViewDesc, dom = (widget.type as any).toDOM as WidgetConstructor
463
+ if (typeof dom == "function") dom = dom(view, () => {
464
+ if (!self) return pos
465
+ if (self.parent) return self.parent.posBeforeChild(self)
466
+ })
467
+ if (!widget.type.spec.raw) {
468
+ let elt = isElt(dom) ? dom : document.createElement("span")
469
+ if (elt != dom) { elt.appendChild(dom); dom = elt }
470
+ if (!elt.hasAttribute("contenteditable"))
471
+ elt.contentEditable = "false"
472
+ elt.classList.add("ProseMirror-widget")
473
+ }
474
+ super(parent, [], dom, null)
475
+ this.widget = widget
476
+ self = this
477
+ }
478
+
479
+ matchesWidget(widget: Decoration) {
480
+ return !this.damage && widget.type.eq(this.widget.type)
481
+ }
482
+
483
+ parseRule() { return {ignore: true} }
484
+
485
+ stopEvent(event: Event) {
486
+ let stop = this.widget.spec.stopEvent
487
+ return stop ? stop(event) : false
488
+ }
489
+
490
+ ignoreMutation(mutation: ViewMutationRecord) {
491
+ return mutation.type != "selection" || this.widget.spec.ignoreSelection
492
+ }
493
+
494
+ destroy() {
495
+ this.widget.type.destroy(this.dom)
496
+ super.destroy()
497
+ }
498
+
499
+ get domAtom() { return true }
500
+
501
+ get ignoreForSelection() { return !!this.widget.type.spec.relaxedSide }
502
+
503
+ get side() { return (this.widget.type as any).side as number }
504
+ }
505
+
506
+ class CompositionViewDesc extends ViewDesc {
507
+ constructor(parent: ViewDesc, dom: DOMNode, readonly textDOM: Text, readonly text: string) {
508
+ super(parent, [], dom, null)
509
+ }
510
+
511
+ get size() { return this.text.length }
512
+
513
+ localPosFromDOM(dom: DOMNode, offset: number) {
514
+ if (dom != this.textDOM) return this.posAtStart + (offset ? this.size : 0)
515
+ return this.posAtStart + offset
516
+ }
517
+
518
+ domFromPos(pos: number) {
519
+ return {node: this.textDOM, offset: pos}
520
+ }
521
+
522
+ ignoreMutation(mut: ViewMutationRecord) {
523
+ return mut.type === "characterData" && mut.target.nodeValue == mut.oldValue
524
+ }
525
+ }
526
+
527
+ // A mark desc represents a mark. May have multiple children,
528
+ // depending on how the mark is split. Note that marks are drawn using
529
+ // a fixed nesting order, for simplicity and predictability, so in
530
+ // some cases they will be split more often than would appear
531
+ // necessary.
532
+ class MarkViewDesc extends ViewDesc {
533
+ constructor(parent: ViewDesc, public mark: Mark, dom: HTMLElement, contentDOM: HTMLElement, readonly spec: MarkView) {
534
+ super(parent, [], dom, contentDOM)
535
+ }
536
+
537
+ static create(parent: ViewDesc, mark: Mark, inline: boolean, view: EditorView) {
538
+ let custom = view.nodeViews[mark.type.name]
539
+ let spec: {dom: HTMLElement, contentDOM?: HTMLElement} = custom && (custom as any)(mark, view, inline)
540
+ if (!spec || !spec.dom)
541
+ spec = (DOMSerializer.renderSpec as any)(document, mark.type.spec.toDOM!(mark, inline), null, mark.attrs) as any
542
+ return new MarkViewDesc(parent, mark, spec.dom, spec.contentDOM || spec.dom as HTMLElement, spec)
543
+ }
544
+
545
+ parseRule() {
546
+ if ((this.damage & Damage.Structure) || this.mark.type.spec.reparseInView) return null
547
+ return {mark: this.mark.type.name, attrs: this.mark.attrs, contentElement: this.contentDOM!}
548
+ }
549
+
550
+ matchesMark(mark: Mark) { return !(this.damage & Damage.Structure) && this.mark.eq(mark) }
551
+
552
+ markDamage(damage: Damage) {
553
+ this.damage |= damage
554
+ this.parent?.markDamage(Damage.ChildList)
555
+ }
556
+
557
+ slice(from: number, to: number, view: EditorView) {
558
+ let copy = MarkViewDesc.create(this.parent!, this.mark, true, view)
559
+ let nodes = this.children, size = this.size
560
+ if (to < size) nodes = replaceNodes(nodes, to, size, view)
561
+ if (from > 0) nodes = replaceNodes(nodes, 0, from, view)
562
+ for (let i = 0; i < nodes.length; i++) nodes[i].parent = copy
563
+ copy.children = nodes
564
+ return copy
565
+ }
566
+
567
+ ignoreMutation(mutation: ViewMutationRecord) {
568
+ return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation)
569
+ }
570
+
571
+ destroy() {
572
+ if (this.spec.destroy) this.spec.destroy()
573
+ super.destroy()
574
+ }
575
+ }
576
+
577
+ // Node view descs are the main, most common type of view desc, and
578
+ // correspond to an actual node in the document. Unlike mark descs,
579
+ // they populate their child array themselves.
580
+ export class NodeViewDesc extends ViewDesc {
581
+ constructor(
582
+ parent: ViewDesc | undefined,
583
+ public node: Node,
584
+ public outerDeco: readonly Decoration[],
585
+ public innerDeco: DecorationSource,
586
+ dom: DOMNode,
587
+ contentDOM: HTMLElement | null,
588
+ readonly nodeDOM: DOMNode,
589
+ ) {
590
+ super(parent, [], dom, contentDOM)
591
+ }
592
+
593
+ // By default, a node is rendered using the `toDOM` method from the
594
+ // node type spec. But client code can use the `nodeViews` spec to
595
+ // supply a custom node view, which can influence various aspects of
596
+ // the way the node works.
597
+ //
598
+ // (Using subclassing for this was intentionally decided against,
599
+ // since it'd require exposing a whole slew of finicky
600
+ // implementation details to the user code that they probably will
601
+ // never need.)
602
+ static create(parent: ViewDesc | undefined, node: Node, outerDeco: readonly Decoration[],
603
+ innerDeco: DecorationSource, view: EditorView, pos: number) {
604
+ let custom = view.nodeViews[node.type.name], descObj: ViewDesc
605
+ let spec: NodeView | undefined = custom && (custom as any)(node, view, () => {
606
+ // (This is a function that allows the custom view to find its
607
+ // own position)
608
+ if (!descObj) return pos
609
+ if (descObj.parent) return descObj.parent.posBeforeChild(descObj)
610
+ }, outerDeco, innerDeco)
611
+
612
+ let dom: DOMNode | undefined = spec && spec.dom, contentDOM = spec && spec.contentDOM
613
+ if (node.isText) {
614
+ if (!dom) dom = document.createTextNode(node.text!)
615
+ else if (!isText(dom)) throw new RangeError("Text must be rendered as a DOM text node")
616
+ } else if (!dom) {
617
+ let spec = (DOMSerializer.renderSpec as any)(document, node.type.spec.toDOM!(node), null, node.attrs)
618
+ ;({dom, contentDOM} = spec as {dom: HTMLElement, contentDOM?: HTMLElement})
619
+ }
620
+ if (!contentDOM && !node.isText && dom.nodeName != "BR") { // Chrome gets confused by <br contenteditable=false>
621
+ if (!(dom as HTMLElement).hasAttribute("contenteditable")) (dom as HTMLElement).contentEditable = "false"
622
+ if (node.type.spec.draggable) (dom as HTMLElement).draggable = true
623
+ }
624
+
625
+ let nodeDOM = dom
626
+ dom = applyOuterDeco(dom, outerDeco, node)
627
+
628
+ if (spec)
629
+ return descObj = new CustomNodeViewDesc(parent, node, outerDeco, innerDeco, dom as HTMLElement, contentDOM || null,
630
+ nodeDOM as HTMLElement, spec)
631
+ else if (node.isText)
632
+ return new TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM)
633
+ else
634
+ return new NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM)
635
+ }
636
+
637
+ parseRule(addedNodes?: readonly DOMNode[]) {
638
+ // Experimental kludge to allow opt-in re-parsing of nodes
639
+ if (this.node.type.spec.reparseInView) return null
640
+ // FIXME the assumption that this can always return the current
641
+ // attrs means that if the user somehow manages to change the
642
+ // attrs in the dom, that won't be picked up. Not entirely sure
643
+ // whether this is a problem
644
+ let rule: Omit<TagParseRule, "tag"> = {node: this.node.type.name, attrs: this.node.attrs}
645
+ if (this.node.type.whitespace == "pre") rule.preserveWhitespace = "full"
646
+ if (!this.contentDOM) {
647
+ rule.getContent = () => this.node.content
648
+ } else if (!this.contentLost) {
649
+ rule.contentElement = this.contentDOM
650
+ } else {
651
+ // Chrome likes to randomly recreate parent nodes when
652
+ // backspacing things. When that happens, this tries to find the
653
+ // new parent.
654
+ for (let i = this.children.length - 1; i >= 0; i--) {
655
+ let child = this.children[i]
656
+ if (this.dom.contains(child.dom.parentNode)) {
657
+ rule.contentElement = child.dom.parentNode as HTMLElement
658
+ break
659
+ }
660
+ }
661
+ if (!rule.contentElement) {
662
+ let found = addedNodes &&
663
+ addedNodes.find(n => isElt(n) && addedNodes.indexOf(n.parentNode!) < 0 && this.dom.contains(n))
664
+ if (found)
665
+ rule.contentElement = found as HTMLElement
666
+ else
667
+ rule.getContent = () => Fragment.empty
668
+ }
669
+ }
670
+ return rule
671
+ }
672
+
673
+ matchesNode(node: Node, outerDeco: readonly Decoration[], innerDeco: DecorationSource) {
674
+ return !this.damage && node.eq(this.node) &&
675
+ sameOuterDeco(outerDeco, this.outerDeco) && innerDeco.eq(this.innerDeco)
676
+ }
677
+
678
+ get size() { return this.node.nodeSize }
679
+
680
+ get border() { return this.node.isLeaf ? 0 : 1 }
681
+
682
+ // Syncs `this.children` to match `this.node.content` and the local
683
+ // decorations, possibly introducing nesting for marks. Then, in a
684
+ // separate step, syncs the DOM inside `this.contentDOM` to
685
+ // `this.children`.
686
+ updateChildren(view: EditorView, pos: number) {
687
+ let inline = this.node.inlineContent, off = pos
688
+ let composition = view.composing ? this.localCompositionInfo(view, pos) : null
689
+ let localComposition = composition && composition.pos > -1 ? composition : null
690
+ let compositionInChild = composition && composition.pos < 0
691
+ let updater = new ViewTreeUpdater(this, localComposition && localComposition.node, view)
692
+ let addBuffers = this.node.inlineContent, atBufferPos = addBuffers && this.node.isBlock
693
+ iterDeco(this.node, this.innerDeco, (widget, i, insideNode) => {
694
+ if (widget.spec.marks)
695
+ updater.syncToMarks(widget.spec.marks, inline, view, i)
696
+ else if ((widget.type as WidgetType).side >= 0 && !insideNode)
697
+ updater.syncToMarks(i == this.node.childCount ? Mark.none : this.node.child(i).marks, inline, view, i)
698
+ // If the next node is a desc matching this widget, reuse it,
699
+ // otherwise insert the widget as a new view desc.
700
+ updater.placeWidget(widget, view, off)
701
+ }, (child, outerDeco, innerDeco, i) => {
702
+ // Make sure the wrapping mark descs match the node's marks.
703
+ updater.syncToMarks(child.marks, inline, view, i)
704
+ if (atBufferPos && child.isAtom && !child.isText) updater.addHackNode("IMG", updater.top)
705
+ // Try several strategies for drawing this node
706
+ let compIndex
707
+ if (updater.findNodeMatch(child, outerDeco, innerDeco, i)) {
708
+ // Found precise match with existing node view
709
+ } else if (compositionInChild && view.state.selection.from > off &&
710
+ view.state.selection.to < off + child.nodeSize &&
711
+ (compIndex = updater.findIndexWithChild(composition!.node)) > -1 &&
712
+ updater.updateNodeAt(child, outerDeco, innerDeco, compIndex, view, off)) {
713
+ // Updated the specific node that holds the composition
714
+ } else if (updater.updateNextNode(child, outerDeco, innerDeco, view, i, off)) {
715
+ // Could update an existing node to reflect this node
716
+ } else {
717
+ // Add it as a new view
718
+ updater.addNode(child, outerDeco, innerDeco, view, off)
719
+ }
720
+ off += child.nodeSize
721
+ if (addBuffers) atBufferPos = child.isAtom && !child.isText
722
+ })
723
+ // Drop all remaining descs after the current position.
724
+ updater.syncToMarks([], inline, view, 0)
725
+ if (this.node.isTextblock) updater.addTextblockHacks()
726
+ updater.destroyRest()
727
+
728
+ // Sync the DOM if anything changed
729
+ if (updater.changed || (this.damage & Damage.ChildList)) {
730
+ // May have to protect focused DOM from being changed if a composition is active
731
+ if (localComposition) this.protectLocalComposition(view, localComposition)
732
+ renderDescs(this.contentDOM!, this.children, view)
733
+ if (browser.ios) iosHacks(this.dom as HTMLElement)
734
+ }
735
+ }
736
+
737
+ localCompositionInfo(view: EditorView, pos: number): {node: Text, pos: number, text: string} | null {
738
+ // Only do something if both the selection and a focused text node
739
+ // are inside of this node
740
+ let {from, to} = view.state.selection
741
+ if (!(view.state.selection instanceof TextSelection) || from < pos || to > pos + this.node.content.size) return null
742
+ let textNode = view.input.compositionNode
743
+ if (!textNode || !this.dom.contains(textNode.parentNode)) return null
744
+
745
+ if (this.node.inlineContent) {
746
+ // Find the text in the focused node in the node, stop if it's not
747
+ // there (may have been modified through other means, in which
748
+ // case it should overwritten)
749
+ let text = textNode.nodeValue!
750
+ let textPos = findTextInFragment(this.node.content, text, from - pos, to - pos)
751
+ return textPos < 0 ? null : {node: textNode, pos: textPos, text}
752
+ } else {
753
+ return {node: textNode, pos: -1, text: ""}
754
+ }
755
+ }
756
+
757
+ protectLocalComposition(view: EditorView, {node, pos, text}: {node: Text, pos: number, text: string}) {
758
+ // The node is already part of a local view desc, leave it there
759
+ if (this.getDesc(node)) return
760
+
761
+ // Create a composition view for the orphaned nodes
762
+ let topNode: DOMNode = node
763
+ for (;; topNode = topNode.parentNode!) {
764
+ if (topNode.parentNode == this.contentDOM) break
765
+ while (topNode.previousSibling) topNode.parentNode!.removeChild(topNode.previousSibling)
766
+ while (topNode.nextSibling) topNode.parentNode!.removeChild(topNode.nextSibling)
767
+ if (topNode.pmViewDesc) topNode.pmViewDesc = undefined
768
+ }
769
+ let desc = new CompositionViewDesc(this, topNode, node, text)
770
+ view.input.compositionNodes.push(desc)
771
+
772
+ // Patch up this.children to contain the composition view
773
+ this.children = replaceNodes(this.children, pos, pos + text.length, view, desc)
774
+ }
775
+
776
+ // If this desc must be updated to match the given node decoration,
777
+ // do so and return true. pos is the position before the node, or -1
778
+ // for the document.
779
+ update(node: Node, outerDeco: readonly Decoration[], innerDeco: DecorationSource, view: EditorView, pos: number) {
780
+ if ((this.damage & Damage.Structure) || !node.sameMarkup(this.node)) return false
781
+ this.updateInner(node, outerDeco, innerDeco, view, pos)
782
+ return true
783
+ }
784
+
785
+ updateInner(node: Node, outerDeco: readonly Decoration[], innerDeco: DecorationSource, view: EditorView, pos: number) {
786
+ this.updateOuterDeco(outerDeco)
787
+ this.node = node
788
+ this.innerDeco = innerDeco
789
+ if (this.contentDOM) this.updateChildren(view, pos + 1)
790
+ this.damage = Damage.None
791
+ }
792
+
793
+ updateOuterDeco(outerDeco: readonly Decoration[]) {
794
+ if (sameOuterDeco(outerDeco, this.outerDeco)) return
795
+ let needsWrap = !isElt(this.nodeDOM)
796
+ let oldDOM = this.dom
797
+ this.dom = patchOuterDeco(this.dom, this.nodeDOM,
798
+ computeOuterDeco(this.outerDeco, this.node, needsWrap),
799
+ computeOuterDeco(outerDeco, this.node, needsWrap))
800
+ if (this.dom != oldDOM) {
801
+ oldDOM.pmViewDesc = undefined
802
+ this.dom.pmViewDesc = this
803
+ }
804
+ this.outerDeco = outerDeco
805
+ }
806
+
807
+ // Mark this node as being the selected node.
808
+ selectNode() {
809
+ if (isElt(this.nodeDOM)) {
810
+ this.nodeDOM.classList.add("ProseMirror-selectednode")
811
+ if (this.contentDOM || !this.node.type.spec.draggable) this.nodeDOM.draggable = true
812
+ }
813
+ }
814
+
815
+ // Remove selected node marking from this node.
816
+ deselectNode() {
817
+ if (isElt(this.nodeDOM)) {
818
+ this.nodeDOM.classList.remove("ProseMirror-selectednode")
819
+ if (this.contentDOM || !this.node.type.spec.draggable) this.nodeDOM.removeAttribute("draggable")
820
+ }
821
+ }
822
+
823
+ get domAtom() { return this.node.isAtom }
824
+ }
825
+
826
+ // Create a view desc for the top-level document node, to be exported
827
+ // and used by the view class.
828
+ export function docViewDesc(
829
+ doc: Node, outerDeco: readonly Decoration[], innerDeco: DecorationSource,
830
+ dom: HTMLElement, view: EditorView, prevOuterDeco?: readonly Decoration[]
831
+ ): NodeViewDesc {
832
+ if (!prevOuterDeco) applyOuterDeco(dom, outerDeco, doc)
833
+ else patchOuterDeco(dom, dom, computeOuterDeco(prevOuterDeco, doc, false), computeOuterDeco(outerDeco, doc, false))
834
+ let docView = new NodeViewDesc(undefined, doc, outerDeco, innerDeco, dom, dom, dom)
835
+ if (docView.contentDOM) docView.updateChildren(view, 0)
836
+ return docView
837
+ }
838
+
839
+ export class TextViewDesc extends NodeViewDesc {
840
+ constructor(parent: ViewDesc | undefined, node: Node, outerDeco: readonly Decoration[],
841
+ innerDeco: DecorationSource, dom: DOMNode, nodeDOM: DOMNode) {
842
+ super(parent, node, outerDeco, innerDeco, dom, null, nodeDOM)
843
+ }
844
+
845
+ parseRule() {
846
+ let skip = this.nodeDOM.parentNode
847
+ while (skip && skip != this.dom && !(skip as any).pmIsDeco) skip = skip.parentNode
848
+ return {skip: (skip || true) as any}
849
+ }
850
+
851
+ update(node: Node, outerDeco: readonly Decoration[], innerDeco: DecorationSource, view: EditorView) {
852
+ if ((this.damage & Damage.Structure) || (this.damage && !this.inParent()) ||
853
+ !node.sameMarkup(this.node)) return false
854
+ this.updateOuterDeco(outerDeco)
855
+ if (((this.damage & Damage.Text) || node.text != this.node.text) && node.text != this.nodeDOM.nodeValue) {
856
+ this.nodeDOM.nodeValue = node.text!
857
+ if (view.trackWrites == this.nodeDOM) view.trackWrites = null
858
+ }
859
+ this.node = node
860
+ this.damage = Damage.None
861
+ return true
862
+ }
863
+
864
+ inParent() {
865
+ let parentDOM = this.parent!.contentDOM
866
+ for (let n: DOMNode | null = this.nodeDOM; n; n = n.parentNode) if (n == parentDOM) return true
867
+ return false
868
+ }
869
+
870
+ domFromPos(pos: number) {
871
+ return {node: this.nodeDOM, offset: pos}
872
+ }
873
+
874
+ localPosFromDOM(dom: DOMNode, offset: number, bias: number) {
875
+ if (dom == this.nodeDOM) return this.posAtStart + Math.min(offset, this.node.text!.length)
876
+ return super.localPosFromDOM(dom, offset, bias)
877
+ }
878
+
879
+ ignoreMutation(mutation: ViewMutationRecord) {
880
+ return false
881
+ }
882
+
883
+ slice(from: number, to: number, _view?: EditorView) {
884
+ let node = this.node.cut(from, to), dom = document.createTextNode(node.text!)
885
+ return new TextViewDesc(this.parent, node, this.outerDeco, this.innerDeco, dom, dom)
886
+ }
887
+
888
+ get domAtom() { return false }
889
+
890
+ isText(text: string) { return this.node.text == text }
891
+ }
892
+
893
+ // A dummy desc used to tag extra BR or IMG nodes created to work
894
+ // around contentEditable terribleness.
895
+ class BufferHackViewDesc extends ViewDesc {
896
+ parseRule() { return {ignore: true} }
897
+ matchesHack(nodeName: string) { return !this.damage && this.dom.nodeName == nodeName }
898
+ get domAtom() { return true }
899
+ get ignoreForCoords() { return this.dom.nodeName == "IMG" }
900
+ }
901
+
902
+ // A separate subclass is used for customized node views, so that the
903
+ // extra checks only have to be made for nodes that are actually
904
+ // customized.
905
+ export class CustomNodeViewDesc extends NodeViewDesc {
906
+ constructor(parent: ViewDesc | undefined, node: Node, outerDeco: readonly Decoration[], innerDeco: DecorationSource,
907
+ dom: HTMLElement, contentDOM: HTMLElement | null, nodeDOM: HTMLElement, readonly spec: NodeView) {
908
+ super(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM)
909
+ }
910
+
911
+ // A custom `update` method gets to decide whether the update goes
912
+ // through. If it does, and there's a `contentDOM` node, our logic
913
+ // updates the children.
914
+ update(node: Node, outerDeco: readonly Decoration[], innerDeco: DecorationSource, view: EditorView, pos: number) {
915
+ if (this.damage & Damage.Structure) return false
916
+ if (this.spec.update && (this.node.type == node.type || this.spec.multiType)) {
917
+ let result = this.spec.update(node, outerDeco, innerDeco)
918
+ if (result) this.updateInner(node, outerDeco, innerDeco, view, pos)
919
+ return result
920
+ } else if (!this.contentDOM && !node.isLeaf) {
921
+ return false
922
+ } else {
923
+ return super.update(node, outerDeco, innerDeco, view, pos)
924
+ }
925
+ }
926
+
927
+ selectNode() {
928
+ this.spec.selectNode ? this.spec.selectNode() : super.selectNode()
929
+ }
930
+
931
+ deselectNode() {
932
+ this.spec.deselectNode ? this.spec.deselectNode() : super.deselectNode()
933
+ }
934
+
935
+ destroy() {
936
+ if (this.spec.destroy) this.spec.destroy()
937
+ super.destroy()
938
+ }
939
+
940
+ stopEvent(event: Event) {
941
+ return this.spec.stopEvent ? this.spec.stopEvent(event) : false
942
+ }
943
+
944
+ ignoreMutation(mutation: ViewMutationRecord) {
945
+ return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation)
946
+ }
947
+ }
948
+
949
+ // Sync the content of the given DOM node with the nodes associated
950
+ // with the given array of view descs, recursing into mark descs
951
+ // because this should sync the subtree for a whole node at a time.
952
+ function renderDescs(parentDOM: HTMLElement, descs: readonly ViewDesc[], view: EditorView) {
953
+ let dom = parentDOM.firstChild, written = false
954
+ for (let i = 0; i < descs.length; i++) {
955
+ let desc = descs[i], childDOM = desc.dom
956
+ if (childDOM.parentNode == parentDOM) {
957
+ while (childDOM != dom) { dom = rm(dom!); written = true }
958
+ dom = dom.nextSibling
959
+ } else {
960
+ written = true
961
+ parentDOM.insertBefore(childDOM, dom)
962
+ }
963
+ if (desc instanceof MarkViewDesc) {
964
+ let pos = dom ? dom.previousSibling : parentDOM.lastChild
965
+ renderDescs(desc.contentDOM!, desc.children, view)
966
+ dom = pos ? pos.nextSibling : parentDOM.firstChild
967
+ }
968
+ }
969
+ while (dom) { dom = rm(dom); written = true }
970
+ if (written && view.trackWrites == parentDOM) view.trackWrites = null
971
+ }
972
+
973
+ type OuterDecoLevel = {[attr: string]: string}
974
+
975
+ const OuterDecoLevel: {new (nodeName?: string): OuterDecoLevel} = function(this: any, nodeName?: string) {
976
+ if (nodeName) this.nodeName = nodeName
977
+ } as any
978
+ OuterDecoLevel.prototype = Object.create(null)
979
+
980
+ const noDeco = [new OuterDecoLevel]
981
+
982
+ function computeOuterDeco(outerDeco: readonly Decoration[], node: Node, needsWrap: boolean) {
983
+ if (outerDeco.length == 0) return noDeco
984
+
985
+ let top = needsWrap ? noDeco[0] : new OuterDecoLevel, result = [top]
986
+
987
+ for (let i = 0; i < outerDeco.length; i++) {
988
+ let attrs = (outerDeco[i].type as NodeType).attrs
989
+ if (!attrs) continue
990
+ if (attrs.nodeName)
991
+ result.push(top = new OuterDecoLevel(attrs.nodeName))
992
+
993
+ for (let name in attrs) {
994
+ let val = attrs[name]
995
+ if (val == null) continue
996
+ if (needsWrap && result.length == 1)
997
+ result.push(top = new OuterDecoLevel(node.isInline ? "span" : "div"))
998
+ if (name == "class") top.class = (top.class ? top.class + " " : "") + val
999
+ else if (name == "style") top.style = (top.style ? top.style + ";" : "") + val
1000
+ else if (name != "nodeName") top[name] = val
1001
+ }
1002
+ }
1003
+
1004
+ return result
1005
+ }
1006
+
1007
+ function patchOuterDeco(outerDOM: DOMNode, nodeDOM: DOMNode,
1008
+ prevComputed: readonly OuterDecoLevel[], curComputed: readonly OuterDecoLevel[]) {
1009
+ // Shortcut for trivial case
1010
+ if (prevComputed == noDeco && curComputed == noDeco) return nodeDOM
1011
+
1012
+ let curDOM = nodeDOM
1013
+ for (let i = 0; i < curComputed.length; i++) {
1014
+ let deco = curComputed[i], prev = prevComputed[i]
1015
+ if (i) {
1016
+ let parent: DOMNode | null
1017
+ if (prev && prev.nodeName == deco.nodeName && curDOM != outerDOM &&
1018
+ (parent = curDOM.parentNode) && parent.nodeName!.toLowerCase() == deco.nodeName) {
1019
+ curDOM = parent
1020
+ } else {
1021
+ parent = document.createElement(deco.nodeName)
1022
+ ;(parent as any).pmIsDeco = true
1023
+ parent.appendChild(curDOM)
1024
+ prev = noDeco[0]
1025
+ curDOM = parent
1026
+ }
1027
+ }
1028
+ patchAttributes(curDOM as HTMLElement, prev || noDeco[0], deco)
1029
+ }
1030
+ return curDOM
1031
+ }
1032
+
1033
+ function patchAttributes(dom: HTMLElement, prev: {[name: string]: string}, cur: {[name: string]: string}) {
1034
+ for (let name in prev)
1035
+ if (name != "class" && name != "style" && name != "nodeName" && !(name in cur))
1036
+ dom.removeAttribute(name)
1037
+ for (let name in cur)
1038
+ if (name != "class" && name != "style" && name != "nodeName" && cur[name] != prev[name])
1039
+ dom.setAttribute(name, cur[name])
1040
+ if (prev.class != cur.class) {
1041
+ let prevList = prev.class ? prev.class.split(" ").filter(Boolean) : []
1042
+ let curList = cur.class ? cur.class.split(" ").filter(Boolean) : []
1043
+ for (let i = 0; i < prevList.length; i++) if (curList.indexOf(prevList[i]) == -1)
1044
+ dom.classList.remove(prevList[i])
1045
+ for (let i = 0; i < curList.length; i++) if (prevList.indexOf(curList[i]) == -1)
1046
+ dom.classList.add(curList[i])
1047
+ if (dom.classList.length == 0)
1048
+ dom.removeAttribute("class")
1049
+ }
1050
+ if (prev.style != cur.style) {
1051
+ if (prev.style) {
1052
+ let prop = /\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g, m
1053
+ while (m = prop.exec(prev.style))
1054
+ dom.style.removeProperty(m[1])
1055
+ }
1056
+ if (cur.style)
1057
+ dom.style.cssText += cur.style
1058
+ }
1059
+ }
1060
+
1061
+ function applyOuterDeco(dom: DOMNode, deco: readonly Decoration[], node: Node) {
1062
+ return patchOuterDeco(dom, dom, noDeco, computeOuterDeco(deco, node, !isElt(dom)))
1063
+ }
1064
+
1065
+ function sameOuterDeco(a: readonly Decoration[], b: readonly Decoration[]) {
1066
+ if (a.length != b.length) return false
1067
+ for (let i = 0; i < a.length; i++) if (!a[i].type.eq(b[i].type)) return false
1068
+ return true
1069
+ }
1070
+
1071
+ // Remove a DOM node and return its next sibling.
1072
+ function rm(dom: DOMNode) {
1073
+ let next = dom.nextSibling
1074
+ dom.parentNode!.removeChild(dom)
1075
+ return next
1076
+ }
1077
+
1078
+ // Helper class for incrementally updating a tree of mark descs and
1079
+ // the widget and node descs inside of them.
1080
+ class ViewTreeUpdater {
1081
+ // Index into `this.top`'s child array, represents the current
1082
+ // update position.
1083
+ index = 0
1084
+ // When entering a mark, the current top and index are pushed
1085
+ // onto this.
1086
+ stack: (ViewDesc | number)[] = []
1087
+ // Tracks whether anything was changed
1088
+ changed = false
1089
+ preMatch: {index: number, matched: Map<ViewDesc, number>, matches: readonly ViewDesc[]}
1090
+ top: ViewDesc
1091
+
1092
+ constructor(top: NodeViewDesc, readonly lock: DOMNode | null, private readonly view: EditorView) {
1093
+ this.top = top
1094
+ this.preMatch = preMatch(top.node.content, top)
1095
+ }
1096
+
1097
+ // Destroy and remove the children between the given indices in
1098
+ // `this.top`.
1099
+ destroyBetween(start: number, end: number) {
1100
+ if (start == end) return
1101
+ for (let i = start; i < end; i++) this.top.children[i].destroy()
1102
+ this.top.children.splice(start, end - start)
1103
+ this.changed = true
1104
+ }
1105
+
1106
+ // Destroy all remaining children in `this.top`.
1107
+ destroyRest() {
1108
+ this.destroyBetween(this.index, this.top.children.length)
1109
+ }
1110
+
1111
+ // Sync the current stack of mark descs with the given array of
1112
+ // marks, reusing existing mark descs when possible.
1113
+ syncToMarks(marks: readonly Mark[], inline: boolean, view: EditorView, parentIndex: number) {
1114
+ let keep = 0, depth = this.stack.length >> 1
1115
+ let maxKeep = Math.min(depth, marks.length)
1116
+ while (keep < maxKeep &&
1117
+ (keep == depth - 1 ? this.top : this.stack[(keep + 1) << 1] as ViewDesc)
1118
+ .matchesMark(marks[keep]) && marks[keep].type.spec.spanning !== false)
1119
+ keep++
1120
+
1121
+ while (keep < depth) {
1122
+ this.destroyRest()
1123
+ this.top.damage = Damage.None
1124
+ this.index = this.stack.pop() as number
1125
+ this.top = this.stack.pop() as ViewDesc
1126
+ depth--
1127
+ }
1128
+ while (depth < marks.length) {
1129
+ this.stack.push(this.top, this.index + 1)
1130
+ let found = -1, scanTo = this.top.children.length
1131
+ if (parentIndex < this.preMatch.index) scanTo = Math.min(this.index + 3, scanTo)
1132
+ for (let i = this.index; i < scanTo; i++) {
1133
+ let next = this.top.children[i]
1134
+ if (next.matchesMark(marks[depth]) && !this.isLocked(next.dom)) { found = i; break }
1135
+ }
1136
+ // When nothing matches, try to update the mark view at this position
1137
+ // in place, so a custom mark view can adapt to a changed mark without
1138
+ // re-creating its DOM.
1139
+ if (found < 0 && this.index < this.top.children.length) {
1140
+ let cur = this.top.children[this.index]
1141
+ if (cur instanceof MarkViewDesc && !(cur.damage & Damage.Structure) &&
1142
+ cur.mark.type == marks[depth].type && cur.spec.update &&
1143
+ !this.isLocked(cur.dom) && cur.spec.update(marks[depth])) {
1144
+ cur.mark = marks[depth]
1145
+ found = this.index
1146
+ this.changed = true
1147
+ }
1148
+ }
1149
+ if (found > -1) {
1150
+ if (found > this.index) {
1151
+ this.changed = true
1152
+ this.destroyBetween(this.index, found)
1153
+ }
1154
+ this.top = this.top.children[this.index]
1155
+ } else {
1156
+ let markDesc = MarkViewDesc.create(this.top, marks[depth], inline, view)
1157
+ this.top.children.splice(this.index, 0, markDesc)
1158
+ this.top = markDesc
1159
+ this.changed = true
1160
+ }
1161
+ this.index = 0
1162
+ depth++
1163
+ }
1164
+ }
1165
+
1166
+ // Try to find a node desc matching the given data. Skip over it and
1167
+ // return true when successful.
1168
+ findNodeMatch(node: Node, outerDeco: readonly Decoration[], innerDeco: DecorationSource, index: number): boolean {
1169
+ let found = -1, targetDesc
1170
+ if (index >= this.preMatch.index &&
1171
+ (targetDesc = this.preMatch.matches[index - this.preMatch.index]).parent == this.top &&
1172
+ targetDesc.matchesNode(node, outerDeco, innerDeco)) {
1173
+ found = this.top.children.indexOf(targetDesc, this.index)
1174
+ } else {
1175
+ for (let i = this.index, e = Math.min(this.top.children.length, i + 5); i < e; i++) {
1176
+ let child = this.top.children[i]
1177
+ if (child.matchesNode(node, outerDeco, innerDeco) && !this.preMatch.matched.has(child)) {
1178
+ found = i
1179
+ break
1180
+ }
1181
+ }
1182
+ }
1183
+ if (found < 0) return false
1184
+ this.destroyBetween(this.index, found)
1185
+ this.index++
1186
+ return true
1187
+ }
1188
+
1189
+ updateNodeAt(node: Node, outerDeco: readonly Decoration[], innerDeco: DecorationSource,
1190
+ index: number, view: EditorView, pos: number) {
1191
+ let child = this.top.children[index] as NodeViewDesc
1192
+ if ((child.damage & Damage.Structure) && child.dom == child.contentDOM) child.damage = Damage.ChildList
1193
+ if (!child.update(node, outerDeco, innerDeco, view, pos)) return false
1194
+ this.destroyBetween(this.index, index)
1195
+ this.index++
1196
+ return true
1197
+ }
1198
+
1199
+ findIndexWithChild(domNode: DOMNode) {
1200
+ for (;;) {
1201
+ let parent = domNode.parentNode
1202
+ if (!parent) return -1
1203
+ if (parent == this.top.contentDOM) {
1204
+ let desc = domNode.pmViewDesc
1205
+ if (desc) for (let i = this.index; i < this.top.children.length; i++) {
1206
+ if (this.top.children[i] == desc) return i
1207
+ }
1208
+ return -1
1209
+ }
1210
+ domNode = parent
1211
+ }
1212
+ }
1213
+
1214
+ // Try to update the next node, if any, to the given data. Checks
1215
+ // pre-matches to avoid overwriting nodes that could still be used.
1216
+ updateNextNode(node: Node, outerDeco: readonly Decoration[], innerDeco: DecorationSource,
1217
+ view: EditorView, index: number, pos: number): boolean {
1218
+ for (let i = this.index; i < this.top.children.length; i++) {
1219
+ let next = this.top.children[i]
1220
+ if (next instanceof NodeViewDesc) {
1221
+ let preMatch = this.preMatch.matched.get(next)
1222
+ if (preMatch != null && preMatch != index) return false
1223
+ let nextDOM = next.dom, updated
1224
+
1225
+ // Can't update if nextDOM is or contains this.lock, except if
1226
+ // it's a text node whose content already matches the new text
1227
+ // and whose decorations match the new ones.
1228
+ let locked = this.isLocked(nextDOM) &&
1229
+ !(node.isText && next.node && next.node.isText && next.nodeDOM.nodeValue == node.text &&
1230
+ !(next.damage & Damage.Structure) && sameOuterDeco(outerDeco, next.outerDeco))
1231
+ if (!locked && next.update(node, outerDeco, innerDeco, view, pos)) {
1232
+ this.destroyBetween(this.index, i)
1233
+ if (next.dom != nextDOM) this.changed = true
1234
+ this.index++
1235
+ return true
1236
+ } else if (!locked && (updated = this.recreateWrapper(next, node, outerDeco, innerDeco, view, pos))) {
1237
+ this.destroyBetween(this.index, i)
1238
+ this.top.children[this.index] = updated
1239
+ if (updated.contentDOM) {
1240
+ updated.damage |= Damage.ChildList
1241
+ updated.updateChildren(view, pos + 1)
1242
+ updated.damage = Damage.None
1243
+ }
1244
+ this.changed = true
1245
+ this.index++
1246
+ return true
1247
+ }
1248
+ break
1249
+ }
1250
+ }
1251
+ return false
1252
+ }
1253
+
1254
+ // When a node with content is replaced by a different node with
1255
+ // identical content, move over its children.
1256
+ recreateWrapper(next: NodeViewDesc, node: Node, outerDeco: readonly Decoration[], innerDeco: DecorationSource,
1257
+ view: EditorView, pos: number) {
1258
+ if ((next.damage & (Damage.ChildList | Damage.Child)) || node.isAtom || !next.children.length ||
1259
+ !next.node.content.eq(node.content) ||
1260
+ !sameOuterDeco(outerDeco, next.outerDeco) || !innerDeco.eq(next.innerDeco)) return null
1261
+ let wrapper = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos)
1262
+ if (wrapper.contentDOM) {
1263
+ wrapper.children = next.children
1264
+ next.children = []
1265
+ for (let ch of wrapper.children) ch.parent = wrapper
1266
+ }
1267
+ next.destroy()
1268
+ return wrapper
1269
+ }
1270
+
1271
+ // Insert the node as a newly created node desc.
1272
+ addNode(node: Node, outerDeco: readonly Decoration[], innerDeco: DecorationSource, view: EditorView, pos: number) {
1273
+ let desc = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos)
1274
+ if (desc.contentDOM) desc.updateChildren(view, pos + 1)
1275
+ this.top.children.splice(this.index++, 0, desc)
1276
+ this.changed = true
1277
+ }
1278
+
1279
+ placeWidget(widget: Decoration, view: EditorView, pos: number) {
1280
+ let next = this.index < this.top.children.length ? this.top.children[this.index] : null
1281
+ if (next && next.matchesWidget(widget) &&
1282
+ (widget == (next as WidgetViewDesc).widget || !(next as any).widget.type.toDOM.parentNode)) {
1283
+ this.index++
1284
+ } else {
1285
+ let desc = new WidgetViewDesc(this.top, widget, view, pos)
1286
+ this.top.children.splice(this.index++, 0, desc)
1287
+ this.changed = true
1288
+ }
1289
+ }
1290
+
1291
+ // Make sure a textblock looks and behaves correctly in
1292
+ // contentEditable.
1293
+ addTextblockHacks() {
1294
+ let lastChild = this.top.children[this.index - 1], parent = this.top
1295
+ while (lastChild instanceof MarkViewDesc) {
1296
+ parent = lastChild
1297
+ lastChild = parent.children[parent.children.length - 1]
1298
+ }
1299
+
1300
+ if (!lastChild || // Empty textblock
1301
+ !(lastChild instanceof TextViewDesc) ||
1302
+ /\n$/.test(lastChild.node.text!) ||
1303
+ (this.view.requiresGeckoHackNode && /\s$/.test(lastChild.node.text!))) {
1304
+ // Avoid bugs in Safari's cursor drawing (#1165) and Chrome's mouse selection (#1152)
1305
+ if ((browser.safari || browser.chrome) && lastChild && (lastChild.dom as HTMLElement).contentEditable == "false")
1306
+ this.addHackNode("IMG", parent)
1307
+ this.addHackNode("BR", this.top)
1308
+ }
1309
+ }
1310
+
1311
+ addHackNode(nodeName: string, parent: ViewDesc) {
1312
+ if (parent == this.top && this.index < parent.children.length && parent.children[this.index].matchesHack(nodeName)) {
1313
+ this.index++
1314
+ } else {
1315
+ let dom = document.createElement(nodeName)
1316
+ if (nodeName == "IMG") {
1317
+ dom.className = "ProseMirror-separator"
1318
+ ;(dom as HTMLImageElement).alt = ""
1319
+ }
1320
+ if (nodeName == "BR") dom.className = "ProseMirror-trailingBreak"
1321
+ let hack = new BufferHackViewDesc(this.top, [], dom, null)
1322
+ if (parent != this.top) parent.children.push(hack)
1323
+ else parent.children.splice(this.index++, 0, hack)
1324
+ this.changed = true
1325
+ }
1326
+ }
1327
+
1328
+ isLocked(node: DOMNode) {
1329
+ return this.lock && (node == this.lock || isElt(node) && node.contains(this.lock.parentNode))
1330
+ }
1331
+ }
1332
+
1333
+ // Iterate from the end of the fragment and array of descs to find
1334
+ // directly matching ones, in order to avoid overeagerly reusing those
1335
+ // for other nodes.
1336
+ function preMatch(frag: Fragment, parentDesc: ViewDesc): {
1337
+ // The fragment index of the first node that is part of the sequence
1338
+ // of matched nodes at the end of the fragment.
1339
+ index: number,
1340
+ // A map from matched descs to fragment indices.
1341
+ matched: Map<ViewDesc, number>,
1342
+ // The matched descs.
1343
+ matches: readonly ViewDesc[]
1344
+ } {
1345
+ let curDesc = parentDesc, descI = curDesc.children.length, stack: number[] = []
1346
+ let fI = frag.childCount, matched = new Map, matches = []
1347
+ outer: while (fI > 0) {
1348
+ let desc
1349
+ for (;;) {
1350
+ if (descI) {
1351
+ let next = curDesc.children[descI - 1]
1352
+ if (next instanceof MarkViewDesc) {
1353
+ stack.push(descI - 1)
1354
+ curDesc = next
1355
+ descI = next.children.length
1356
+ } else {
1357
+ desc = next
1358
+ descI--
1359
+ break
1360
+ }
1361
+ } else if (curDesc == parentDesc) {
1362
+ break outer
1363
+ } else {
1364
+ descI = stack.pop()!
1365
+ curDesc = curDesc.parent!
1366
+ }
1367
+ }
1368
+ let node = desc.node
1369
+ if (!node) continue
1370
+ if (node != frag.child(fI - 1)) break
1371
+ --fI
1372
+ matched.set(desc, fI)
1373
+ matches.push(desc)
1374
+ }
1375
+ return {index: fI, matched, matches: matches.reverse()}
1376
+ }
1377
+
1378
+ function compareSide(a: Decoration, b: Decoration) {
1379
+ return (a.type as WidgetType).side - (b.type as WidgetType).side
1380
+ }
1381
+
1382
+ // This function abstracts iterating over the nodes and decorations in
1383
+ // a fragment. Calls `onNode` for each node, with its local and child
1384
+ // decorations. Splits text nodes when there is a decoration starting
1385
+ // or ending inside of them. Calls `onWidget` for each widget.
1386
+ function iterDeco(
1387
+ parent: Node,
1388
+ deco: DecorationSource,
1389
+ onWidget: (widget: Decoration, index: number, insideNode: boolean) => void,
1390
+ onNode: (node: Node, outerDeco: readonly Decoration[], innerDeco: DecorationSource, index: number) => void
1391
+ ) {
1392
+ let locals = deco.locals(parent), offset = 0
1393
+ // Simple, cheap variant for when there are no local decorations
1394
+ if (locals.length == 0) {
1395
+ for (let i = 0; i < parent.childCount; i++) {
1396
+ let child = parent.child(i)
1397
+ onNode(child, locals, deco.forChild(offset, child), i)
1398
+ offset += child.nodeSize
1399
+ }
1400
+ return
1401
+ }
1402
+
1403
+ let decoIndex = 0, active = [], restNode = null
1404
+ for (let parentIndex = 0;;) {
1405
+ let widget, widgets
1406
+ while (decoIndex < locals.length && locals[decoIndex].to == offset) {
1407
+ let next = locals[decoIndex++]
1408
+ if (next.widget) {
1409
+ if (!widget) widget = next
1410
+ else (widgets || (widgets = [widget])).push(next)
1411
+ }
1412
+ }
1413
+ if (widget) {
1414
+ if (widgets) {
1415
+ widgets.sort(compareSide)
1416
+ for (let i = 0; i < widgets.length; i++) onWidget(widgets[i], parentIndex, !!restNode)
1417
+ } else {
1418
+ onWidget(widget, parentIndex, !!restNode)
1419
+ }
1420
+ }
1421
+
1422
+ let child, index
1423
+ if (restNode) {
1424
+ index = -1
1425
+ child = restNode
1426
+ restNode = null
1427
+ } else if (parentIndex < parent.childCount) {
1428
+ index = parentIndex
1429
+ child = parent.child(parentIndex++)
1430
+ } else {
1431
+ break
1432
+ }
1433
+
1434
+ for (let i = 0; i < active.length; i++) if (active[i].to <= offset) active.splice(i--, 1)
1435
+ while (decoIndex < locals.length && locals[decoIndex].from <= offset && locals[decoIndex].to > offset)
1436
+ active.push(locals[decoIndex++])
1437
+
1438
+ let end = offset + child.nodeSize
1439
+ if (child.isText) {
1440
+ let cutAt = end
1441
+ if (decoIndex < locals.length && locals[decoIndex].from < cutAt) cutAt = locals[decoIndex].from
1442
+ for (let i = 0; i < active.length; i++) if (active[i].to < cutAt) cutAt = active[i].to
1443
+ if (cutAt < end) {
1444
+ restNode = child.cut(cutAt - offset)
1445
+ child = child.cut(0, cutAt - offset)
1446
+ end = cutAt
1447
+ index = -1
1448
+ }
1449
+ } else {
1450
+ while (decoIndex < locals.length && locals[decoIndex].to < end) decoIndex++
1451
+ }
1452
+
1453
+ let outerDeco = child.isInline && !child.isLeaf ? active.filter(d => !d.inline) : active.slice()
1454
+ onNode(child, outerDeco, deco.forChild(offset, child), index)
1455
+ offset = end
1456
+ }
1457
+ }
1458
+
1459
+ // List markers in Mobile Safari will mysteriously disappear
1460
+ // sometimes. This works around that.
1461
+ function iosHacks(dom: HTMLElement) {
1462
+ if (dom.nodeName == "UL" || dom.nodeName == "OL") {
1463
+ let oldCSS = dom.style.cssText
1464
+ dom.style.cssText = oldCSS + "; list-style: square !important"
1465
+ window.getComputedStyle(dom).listStyle
1466
+ dom.style.cssText = oldCSS
1467
+ }
1468
+ }
1469
+
1470
+ // Find a piece of text in an inline fragment, overlapping from-to
1471
+ function findTextInFragment(frag: Fragment, text: string, from: number, to: number) {
1472
+ for (let i = 0, pos = 0; i < frag.childCount && pos <= to;) {
1473
+ let child = frag.child(i++), childStart = pos
1474
+ pos += child.nodeSize
1475
+ if (!child.isText) continue
1476
+ let str = child.text!
1477
+ while (i < frag.childCount) {
1478
+ let next = frag.child(i++)
1479
+ pos += next.nodeSize
1480
+ if (!next.isText) break
1481
+ str += next.text
1482
+ }
1483
+ if (pos >= from) {
1484
+ if (pos >= to && str.slice(to - text.length - childStart, to - childStart) == text)
1485
+ return to - text.length
1486
+ let found = childStart < to ? str.lastIndexOf(text, to - childStart - 1) : -1
1487
+ if (found >= 0 && found + text.length + childStart >= from)
1488
+ return childStart + found
1489
+ if (from == to && str.length >= (to + text.length) - childStart &&
1490
+ str.slice(to - childStart, to - childStart + text.length) == text)
1491
+ return to
1492
+ }
1493
+ }
1494
+ return -1
1495
+ }
1496
+
1497
+ // Replace range from-to in an array of view descs with replacement
1498
+ // (may be null to just delete). This goes very much against the grain
1499
+ // of the rest of this code, which tends to create nodes with the
1500
+ // right shape in one go, rather than messing with them after
1501
+ // creation, but is necessary in the composition hack.
1502
+ function replaceNodes(nodes: readonly ViewDesc[], from: number, to: number, view: EditorView, replacement?: ViewDesc) {
1503
+ let result = []
1504
+ for (let i = 0, off = 0; i < nodes.length; i++) {
1505
+ let child = nodes[i], start = off, end = off += child.size
1506
+ if (start >= to || end <= from) {
1507
+ result.push(child)
1508
+ } else {
1509
+ if (start < from) result.push((child as MarkViewDesc | TextViewDesc).slice(0, from - start, view))
1510
+ if (replacement) {
1511
+ result.push(replacement)
1512
+ replacement = undefined
1513
+ }
1514
+ if (end > to) result.push((child as MarkViewDesc | TextViewDesc).slice(to - start, child.size, view))
1515
+ }
1516
+ }
1517
+ return result
1518
+ }