-
Notifications
You must be signed in to change notification settings - Fork 248
/
viewdesc.ts
1493 lines (1341 loc) · 58.6 KB
/
viewdesc.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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {DOMSerializer, Fragment, Mark, Node, ParseRule} from "prosemirror-model"
import {TextSelection} from "prosemirror-state"
import {domIndex, isEquivalentPosition, nodeSize, DOMNode} from "./dom"
import * as browser from "./browser"
import {Decoration, DecorationSource, WidgetConstructor, WidgetType, NodeType} from "./decoration"
import {EditorView} from "./index"
declare global {
interface Node { pmViewDesc?: ViewDesc }
}
/// By default, document nodes are rendered using the result of the
/// [`toDOM`](#model.NodeSpec.toDOM) method of their spec, and managed
/// entirely by the editor. For some use cases, such as embedded
/// node-specific editing interfaces, you want more control over
/// the behavior of a node's in-editor representation, and need to
/// [define](#view.EditorProps.nodeViews) a custom node view.
///
/// Mark views only support `dom` and `contentDOM`, and don't support
/// any of the node view methods.
///
/// Objects returned as node views must conform to this interface.
export interface NodeView {
/// The outer DOM node that represents the document node.
dom: DOMNode
/// The DOM node that should hold the node's content. Only meaningful
/// if the node view also defines a `dom` property and if its node
/// type is not a leaf node type. When this is present, ProseMirror
/// will take care of rendering the node's children into it. When it
/// is not present, the node view itself is responsible for rendering
/// (or deciding not to render) its child nodes.
contentDOM?: HTMLElement | null
/// When given, this will be called when the view is updating itself.
/// It will be given a node (possibly of a different type), an array
/// of active decorations around the node (which are automatically
/// drawn, and the node view may ignore if it isn't interested in
/// them), and a [decoration source](#view.DecorationSource) that
/// represents any decorations that apply to the content of the node
/// (which again may be ignored). It should return true if it was
/// able to update to that node, and false otherwise. If the node
/// view has a `contentDOM` property (or no `dom` property), updating
/// its child nodes will be handled by ProseMirror.
update?: (node: Node, decorations: readonly Decoration[], innerDecorations: DecorationSource) => boolean
/// Can be used to override the way the node's selected status (as a
/// node selection) is displayed.
selectNode?: () => void
/// When defining a `selectNode` method, you should also provide a
/// `deselectNode` method to remove the effect again.
deselectNode?: () => void
/// This will be called to handle setting the selection inside the
/// node. The `anchor` and `head` positions are relative to the start
/// of the node. By default, a DOM selection will be created between
/// the DOM positions corresponding to those positions, but if you
/// override it you can do something else.
setSelection?: (anchor: number, head: number, root: Document | ShadowRoot) => void
/// Can be used to prevent the editor view from trying to handle some
/// or all DOM events that bubble up from the node view. Events for
/// which this returns true are not handled by the editor.
stopEvent?: (event: Event) => boolean
/// Called when a DOM
/// [mutation](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver)
/// or a selection change happens within the view. When the change is
/// a selection change, the record will have a `type` property of
/// `"selection"` (which doesn't occur for native mutation records).
/// Return false if the editor should re-read the selection or
/// re-parse the range around the mutation, true if it can safely be
/// ignored.
ignoreMutation?: (mutation: MutationRecord) => boolean
/// Called when the node view is removed from the editor or the whole
/// editor is destroyed. (Not available for marks.)
destroy?: () => void
}
// View descriptions are data structures that describe the DOM that is
// used to represent the editor's content. They are used for:
//
// - Incremental redrawing when the document changes
//
// - Figuring out what part of the document a given DOM position
// corresponds to
//
// - Wiring in custom implementations of the editing interface for a
// given node
//
// They form a doubly-linked mutable tree, starting at `view.docView`.
const NOT_DIRTY = 0, CHILD_DIRTY = 1, CONTENT_DIRTY = 2, NODE_DIRTY = 3
// Superclass for the various kinds of descriptions. Defines their
// basic structure and shared methods.
export class ViewDesc {
dirty = NOT_DIRTY
node!: Node | null
constructor(
public parent: ViewDesc | undefined,
public children: ViewDesc[],
public dom: DOMNode,
// This is the node that holds the child views. It may be null for
// descs that don't have children.
public contentDOM: HTMLElement | null
) {
// An expando property on the DOM node provides a link back to its
// description.
dom.pmViewDesc = this
}
// Used to check whether a given description corresponds to a
// widget/mark/node.
matchesWidget(widget: Decoration) { return false }
matchesMark(mark: Mark) { return false }
matchesNode(node: Node, outerDeco: readonly Decoration[], innerDeco: DecorationSource) { return false }
matchesHack(nodeName: string) { return false }
// When parsing in-editor content (in domchange.js), we allow
// descriptions to determine the parse rules that should be used to
// parse them.
parseRule(): ParseRule | null { return null }
// Used by the editor's event handler to ignore events that come
// from certain descs.
stopEvent(event: Event) { return false }
// The size of the content represented by this desc.
get size() {
let size = 0
for (let i = 0; i < this.children.length; i++) size += this.children[i].size
return size
}
// For block nodes, this represents the space taken up by their
// start/end tokens.
get border() { return 0 }
destroy() {
this.parent = undefined
if (this.dom.pmViewDesc == this) this.dom.pmViewDesc = undefined
for (let i = 0; i < this.children.length; i++)
this.children[i].destroy()
}
posBeforeChild(child: ViewDesc): number {
for (let i = 0, pos = this.posAtStart;; i++) {
let cur = this.children[i]
if (cur == child) return pos
pos += cur.size
}
}
get posBefore() {
return this.parent!.posBeforeChild(this)
}
get posAtStart() {
return this.parent ? this.parent.posBeforeChild(this) + this.border : 0
}
get posAfter() {
return this.posBefore + this.size
}
get posAtEnd() {
return this.posAtStart + this.size - 2 * this.border
}
localPosFromDOM(dom: DOMNode, offset: number, bias: number): number {
// If the DOM position is in the content, use the child desc after
// it to figure out a position.
if (this.contentDOM && this.contentDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode)) {
if (bias < 0) {
let domBefore, desc: ViewDesc | undefined
if (dom == this.contentDOM) {
domBefore = dom.childNodes[offset - 1]
} else {
while (dom.parentNode != this.contentDOM) dom = dom.parentNode!
domBefore = dom.previousSibling
}
while (domBefore && !((desc = domBefore.pmViewDesc) && desc.parent == this)) domBefore = domBefore.previousSibling
return domBefore ? this.posBeforeChild(desc!) + desc!.size : this.posAtStart
} else {
let domAfter, desc: ViewDesc | undefined
if (dom == this.contentDOM) {
domAfter = dom.childNodes[offset]
} else {
while (dom.parentNode != this.contentDOM) dom = dom.parentNode!
domAfter = dom.nextSibling
}
while (domAfter && !((desc = domAfter.pmViewDesc) && desc.parent == this)) domAfter = domAfter.nextSibling
return domAfter ? this.posBeforeChild(desc!) : this.posAtEnd
}
}
// Otherwise, use various heuristics, falling back on the bias
// parameter, to determine whether to return the position at the
// start or at the end of this view desc.
let atEnd
if (dom == this.dom && this.contentDOM) {
atEnd = offset > domIndex(this.contentDOM)
} else if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM)) {
atEnd = dom.compareDocumentPosition(this.contentDOM) & 2
} else if (this.dom.firstChild) {
if (offset == 0) for (let search = dom;; search = search.parentNode!) {
if (search == this.dom) { atEnd = false; break }
if (search.previousSibling) break
}
if (atEnd == null && offset == dom.childNodes.length) for (let search = dom;; search = search.parentNode!) {
if (search == this.dom) { atEnd = true; break }
if (search.nextSibling) break
}
}
return (atEnd == null ? bias > 0 : atEnd) ? this.posAtEnd : this.posAtStart
}
// Scan up the dom finding the first desc that is a descendant of
// this one.
nearestDesc(dom: DOMNode, onlyNodes: boolean = false) {
for (let first = true, cur: DOMNode | null = dom; cur; cur = cur.parentNode) {
let desc = this.getDesc(cur), nodeDOM
if (desc && (!onlyNodes || desc.node)) {
// If dom is outside of this desc's nodeDOM, don't count it.
if (first && (nodeDOM = (desc as NodeViewDesc).nodeDOM) &&
!(nodeDOM.nodeType == 1 ? nodeDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode) : nodeDOM == dom))
first = false
else
return desc
}
}
}
getDesc(dom: DOMNode) {
let desc = dom.pmViewDesc
for (let cur: ViewDesc | undefined = desc; cur; cur = cur.parent) if (cur == this) return desc
}
posFromDOM(dom: DOMNode, offset: number, bias: number) {
for (let scan: DOMNode | null = dom; scan; scan = scan.parentNode) {
let desc = this.getDesc(scan)
if (desc) return desc.localPosFromDOM(dom, offset, bias)
}
return -1
}
// Find the desc for the node after the given pos, if any. (When a
// parent node overrode rendering, there might not be one.)
descAt(pos: number): ViewDesc | undefined {
for (let i = 0, offset = 0; i < this.children.length; i++) {
let child = this.children[i], end = offset + child.size
if (offset == pos && end != offset) {
while (!child.border && child.children.length) child = child.children[0]
return child
}
if (pos < end) return child.descAt(pos - offset - child.border)
offset = end
}
}
domFromPos(pos: number, side: number): {node: DOMNode, offset: number, atom?: number} {
if (!this.contentDOM) return {node: this.dom, offset: 0, atom: pos + 1}
// First find the position in the child array
let i = 0, offset = 0
for (let curPos = 0; i < this.children.length; i++) {
let child = this.children[i], end = curPos + child.size
if (end > pos || child instanceof TrailingHackViewDesc) { offset = pos - curPos; break }
curPos = end
}
// If this points into the middle of a child, call through
if (offset) return this.children[i].domFromPos(offset - this.children[i].border, side)
// Go back if there were any zero-length widgets with side >= 0 before this point
for (let prev; i && !(prev = this.children[i - 1]).size && prev instanceof WidgetViewDesc && prev.side >= 0; i--) {}
// Scan towards the first useable node
if (side <= 0) {
let prev, enter = true
for (;; i--, enter = false) {
prev = i ? this.children[i - 1] : null
if (!prev || prev.dom.parentNode == this.contentDOM) break
}
if (prev && side && enter && !prev.border && !prev.domAtom) return prev.domFromPos(prev.size, side)
return {node: this.contentDOM, offset: prev ? domIndex(prev.dom) + 1 : 0}
} else {
let next, enter = true
for (;; i++, enter = false) {
next = i < this.children.length ? this.children[i] : null
if (!next || next.dom.parentNode == this.contentDOM) break
}
if (next && enter && !next.border && !next.domAtom) return next.domFromPos(0, side)
return {node: this.contentDOM, offset: next ? domIndex(next.dom) : this.contentDOM.childNodes.length}
}
}
// Used to find a DOM range in a single parent for a given changed
// range.
parseRange(
from: number, to: number, base = 0
): {node: DOMNode, from: number, to: number, fromOffset: number, toOffset: number} {
if (this.children.length == 0)
return {node: this.contentDOM!, from, to, fromOffset: 0, toOffset: this.contentDOM!.childNodes.length}
let fromOffset = -1, toOffset = -1
for (let offset = base, i = 0;; i++) {
let child = this.children[i], end = offset + child.size
if (fromOffset == -1 && from <= end) {
let childBase = offset + child.border
// FIXME maybe descend mark views to parse a narrower range?
if (from >= childBase && to <= end - child.border && child.node &&
child.contentDOM && this.contentDOM!.contains(child.contentDOM))
return child.parseRange(from, to, childBase)
from = offset
for (let j = i; j > 0; j--) {
let prev = this.children[j - 1]
if (prev.size && prev.dom.parentNode == this.contentDOM && !prev.emptyChildAt(1)) {
fromOffset = domIndex(prev.dom) + 1
break
}
from -= prev.size
}
if (fromOffset == -1) fromOffset = 0
}
if (fromOffset > -1 && (end > to || i == this.children.length - 1)) {
to = end
for (let j = i + 1; j < this.children.length; j++) {
let next = this.children[j]
if (next.size && next.dom.parentNode == this.contentDOM && !next.emptyChildAt(-1)) {
toOffset = domIndex(next.dom)
break
}
to += next.size
}
if (toOffset == -1) toOffset = this.contentDOM!.childNodes.length
break
}
offset = end
}
return {node: this.contentDOM!, from, to, fromOffset, toOffset}
}
emptyChildAt(side: number): boolean {
if (this.border || !this.contentDOM || !this.children.length) return false
let child = this.children[side < 0 ? 0 : this.children.length - 1]
return child.size == 0 || child.emptyChildAt(side)
}
domAfterPos(pos: number): DOMNode {
let {node, offset} = this.domFromPos(pos, 0)
if (node.nodeType != 1 || offset == node.childNodes.length)
throw new RangeError("No node after pos " + pos)
return node.childNodes[offset]
}
// View descs are responsible for setting any selection that falls
// entirely inside of them, so that custom implementations can do
// custom things with the selection. Note that this falls apart when
// a selection starts in such a node and ends in another, in which
// case we just use whatever domFromPos produces as a best effort.
setSelection(anchor: number, head: number, root: Document | ShadowRoot, force = false): void {
// If the selection falls entirely in a child, give it to that child
let from = Math.min(anchor, head), to = Math.max(anchor, head)
for (let i = 0, offset = 0; i < this.children.length; i++) {
let child = this.children[i], end = offset + child.size
if (from > offset && to < end)
return child.setSelection(anchor - offset - child.border, head - offset - child.border, root, force)
offset = end
}
let anchorDOM = this.domFromPos(anchor, anchor ? -1 : 1)
let headDOM = head == anchor ? anchorDOM : this.domFromPos(head, head ? -1 : 1)
let domSel = (root as Document).getSelection()!
let brKludge = false
// On Firefox, using Selection.collapse to put the cursor after a
// BR node for some reason doesn't always work (#1073). On Safari,
// the cursor sometimes inexplicable visually lags behind its
// reported position in such situations (#1092).
if ((browser.gecko || browser.safari) && anchor == head) {
let {node, offset} = anchorDOM
if (node.nodeType == 3) {
brKludge = !!(offset && node.nodeValue![offset - 1] == "\n")
// Issue #1128
if (brKludge && offset == node.nodeValue!.length) {
for (let scan: DOMNode | null = node, after; scan; scan = scan.parentNode) {
if (after = scan.nextSibling) {
if (after.nodeName == "BR")
anchorDOM = headDOM = {node: after.parentNode!, offset: domIndex(after) + 1}
break
}
let desc = scan.pmViewDesc
if (desc && desc.node && desc.node.isBlock) break
}
}
} else {
let prev = node.childNodes[offset - 1]
brKludge = prev && (prev.nodeName == "BR" || (prev as HTMLElement).contentEditable == "false")
}
}
// Firefox can act strangely when the selection is in front of an
// uneditable node. See #1163 and https://bugzilla.mozilla.org/show_bug.cgi?id=1709536
if (browser.gecko && domSel.focusNode && domSel.focusNode != headDOM.node && domSel.focusNode.nodeType == 1) {
let after = domSel.focusNode.childNodes[domSel.focusOffset]
if (after && (after as HTMLElement).contentEditable == "false") force = true
}
if (!(force || brKludge && browser.safari) &&
isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode!, domSel.anchorOffset) &&
isEquivalentPosition(headDOM.node, headDOM.offset, domSel.focusNode!, domSel.focusOffset))
return
// Selection.extend can be used to create an 'inverted' selection
// (one where the focus is before the anchor), but not all
// browsers support it yet.
let domSelExtended = false
if ((domSel.extend || anchor == head) && !brKludge) {
domSel.collapse(anchorDOM.node, anchorDOM.offset)
try {
if (anchor != head)
domSel.extend(headDOM.node, headDOM.offset)
domSelExtended = true
} catch (_) {
// In some cases with Chrome the selection is empty after calling
// collapse, even when it should be valid. This appears to be a bug, but
// it is difficult to isolate. If this happens fallback to the old path
// without using extend.
// Similarly, this could crash on Safari if the editor is hidden, and
// there was no selection.
}
}
if (!domSelExtended) {
if (anchor > head) { let tmp = anchorDOM; anchorDOM = headDOM; headDOM = tmp }
let range = document.createRange()
range.setEnd(headDOM.node, headDOM.offset)
range.setStart(anchorDOM.node, anchorDOM.offset)
domSel.removeAllRanges()
domSel.addRange(range)
}
}
ignoreMutation(mutation: MutationRecord): boolean {
return !this.contentDOM && (mutation.type as any) != "selection"
}
get contentLost() {
return this.contentDOM && this.contentDOM != this.dom && !this.dom.contains(this.contentDOM)
}
// Remove a subtree of the element tree that has been touched
// by a DOM change, so that the next update will redraw it.
markDirty(from: number, to: number) {
for (let offset = 0, i = 0; i < this.children.length; i++) {
let child = this.children[i], end = offset + child.size
if (offset == end ? from <= end && to >= offset : from < end && to > offset) {
let startInside = offset + child.border, endInside = end - child.border
if (from >= startInside && to <= endInside) {
this.dirty = from == offset || to == end ? CONTENT_DIRTY : CHILD_DIRTY
if (from == startInside && to == endInside &&
(child.contentLost || child.dom.parentNode != this.contentDOM)) child.dirty = NODE_DIRTY
else child.markDirty(from - startInside, to - startInside)
return
} else {
child.dirty = child.dom == child.contentDOM && child.dom.parentNode == this.contentDOM && !child.children.length
? CONTENT_DIRTY : NODE_DIRTY
}
}
offset = end
}
this.dirty = CONTENT_DIRTY
}
markParentsDirty() {
let level = 1
for (let node = this.parent; node; node = node.parent, level++) {
let dirty = level == 1 ? CONTENT_DIRTY : CHILD_DIRTY
if (node.dirty < dirty) node.dirty = dirty
}
}
get domAtom() { return false }
get ignoreForCoords() { return false }
}
// A widget desc represents a widget decoration, which is a DOM node
// drawn between the document nodes.
class WidgetViewDesc extends ViewDesc {
constructor(parent: ViewDesc, readonly widget: Decoration, view: EditorView, pos: number) {
let self: WidgetViewDesc, dom = (widget.type as any).toDOM as WidgetConstructor
if (typeof dom == "function") dom = dom(view, () => {
if (!self) return pos
if (self.parent) return self.parent.posBeforeChild(self)
})
if (!widget.type.spec.raw) {
if (dom.nodeType != 1) {
let wrap = document.createElement("span")
wrap.appendChild(dom)
dom = wrap
}
;(dom as HTMLElement).contentEditable = "false"
;(dom as HTMLElement).classList.add("ProseMirror-widget")
}
super(parent, [], dom, null)
this.widget = widget
self = this
}
matchesWidget(widget: Decoration) {
return this.dirty == NOT_DIRTY && widget.type.eq(this.widget.type)
}
parseRule() { return {ignore: true} }
stopEvent(event: Event) {
let stop = this.widget.spec.stopEvent
return stop ? stop(event) : false
}
ignoreMutation(mutation: MutationRecord) {
return (mutation.type as any) != "selection" || this.widget.spec.ignoreSelection
}
destroy() {
this.widget.type.destroy(this.dom)
super.destroy()
}
get domAtom() { return true }
get side() { return (this.widget.type as any).side as number }
}
class CompositionViewDesc extends ViewDesc {
constructor(parent: ViewDesc, dom: DOMNode, readonly textDOM: Text, readonly text: string) {
super(parent, [], dom, null)
}
get size() { return this.text.length }
localPosFromDOM(dom: DOMNode, offset: number) {
if (dom != this.textDOM) return this.posAtStart + (offset ? this.size : 0)
return this.posAtStart + offset
}
domFromPos(pos: number) {
return {node: this.textDOM, offset: pos}
}
ignoreMutation(mut: MutationRecord) {
return mut.type === 'characterData' && mut.target.nodeValue == mut.oldValue
}
}
// A mark desc represents a mark. May have multiple children,
// depending on how the mark is split. Note that marks are drawn using
// a fixed nesting order, for simplicity and predictability, so in
// some cases they will be split more often than would appear
// necessary.
class MarkViewDesc extends ViewDesc {
constructor(parent: ViewDesc, readonly mark: Mark, dom: DOMNode, contentDOM: HTMLElement | null) {
super(parent, [], dom, contentDOM)
}
static create(parent: ViewDesc, mark: Mark, inline: boolean, view: EditorView) {
let custom = view.nodeViews[mark.type.name]
let spec: {dom: HTMLElement, contentDOM?: HTMLElement} = custom && (custom as any)(mark, view, inline)
if (!spec || !spec.dom)
spec = DOMSerializer.renderSpec(document, mark.type.spec.toDOM!(mark, inline)) as any
return new MarkViewDesc(parent, mark, spec.dom, spec.contentDOM || spec.dom as HTMLElement)
}
parseRule(): ParseRule | null {
if ((this.dirty & NODE_DIRTY) || this.mark.type.spec.reparseInView) return null
return {mark: this.mark.type.name, attrs: this.mark.attrs, contentElement: this.contentDOM || undefined}
}
matchesMark(mark: Mark) { return this.dirty != NODE_DIRTY && this.mark.eq(mark) }
markDirty(from: number, to: number) {
super.markDirty(from, to)
// Move dirty info to nearest node view
if (this.dirty != NOT_DIRTY) {
let parent = this.parent!
while (!parent.node) parent = parent.parent!
if (parent.dirty < this.dirty) parent.dirty = this.dirty
this.dirty = NOT_DIRTY
}
}
slice(from: number, to: number, view: EditorView) {
let copy = MarkViewDesc.create(this.parent!, this.mark, true, view)
let nodes = this.children, size = this.size
if (to < size) nodes = replaceNodes(nodes, to, size, view)
if (from > 0) nodes = replaceNodes(nodes, 0, from, view)
for (let i = 0; i < nodes.length; i++) nodes[i].parent = copy
copy.children = nodes
return copy
}
}
// Node view descs are the main, most common type of view desc, and
// correspond to an actual node in the document. Unlike mark descs,
// they populate their child array themselves.
export class NodeViewDesc extends ViewDesc {
constructor(
parent: ViewDesc | undefined,
public node: Node,
public outerDeco: readonly Decoration[],
public innerDeco: DecorationSource,
dom: DOMNode,
contentDOM: HTMLElement | null,
readonly nodeDOM: DOMNode,
view: EditorView,
pos: number
) {
super(parent, [], dom, contentDOM)
if (contentDOM) this.updateChildren(view, pos)
}
// By default, a node is rendered using the `toDOM` method from the
// node type spec. But client code can use the `nodeViews` spec to
// supply a custom node view, which can influence various aspects of
// the way the node works.
//
// (Using subclassing for this was intentionally decided against,
// since it'd require exposing a whole slew of finicky
// implementation details to the user code that they probably will
// never need.)
static create(parent: ViewDesc | undefined, node: Node, outerDeco: readonly Decoration[],
innerDeco: DecorationSource, view: EditorView, pos: number) {
let custom = view.nodeViews[node.type.name], descObj: ViewDesc
let spec: NodeView | undefined = custom && (custom as any)(node, view, () => {
// (This is a function that allows the custom view to find its
// own position)
if (!descObj) return pos
if (descObj.parent) return descObj.parent.posBeforeChild(descObj)
}, outerDeco, innerDeco)
let dom = spec && spec.dom, contentDOM = spec && spec.contentDOM
if (node.isText) {
if (!dom) dom = document.createTextNode(node.text!)
else if (dom.nodeType != 3) throw new RangeError("Text must be rendered as a DOM text node")
} else if (!dom) {
;({dom, contentDOM} = DOMSerializer.renderSpec(document, node.type.spec.toDOM!(node)))
}
if (!contentDOM && !node.isText && dom.nodeName != "BR") { // Chrome gets confused by <br contenteditable=false>
if (!(dom as HTMLElement).hasAttribute("contenteditable")) (dom as HTMLElement).contentEditable = "false"
if (node.type.spec.draggable) (dom as HTMLElement).draggable = true
}
let nodeDOM = dom
dom = applyOuterDeco(dom, outerDeco, node)
if (spec)
return descObj = new CustomNodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM,
spec, view, pos + 1)
else if (node.isText)
return new TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM, view)
else
return new NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, view, pos + 1)
}
parseRule(): ParseRule | null {
// Experimental kludge to allow opt-in re-parsing of nodes
if (this.node.type.spec.reparseInView) return null
// FIXME the assumption that this can always return the current
// attrs means that if the user somehow manages to change the
// attrs in the dom, that won't be picked up. Not entirely sure
// whether this is a problem
let rule: ParseRule = {node: this.node.type.name, attrs: this.node.attrs}
if (this.node.type.whitespace == "pre") rule.preserveWhitespace = "full"
if (!this.contentDOM) {
rule.getContent = () => this.node.content
} else if (!this.contentLost) {
rule.contentElement = this.contentDOM
} else {
// Chrome likes to randomly recreate parent nodes when
// backspacing things. When that happens, this tries to find the
// new parent.
for (let i = this.children.length - 1; i >= 0; i--) {
let child = this.children[i]
if (this.dom.contains(child.dom.parentNode)) {
rule.contentElement = child.dom.parentNode as HTMLElement
break
}
}
if (!rule.contentElement) rule.getContent = () => Fragment.empty
}
return rule
}
matchesNode(node: Node, outerDeco: readonly Decoration[], innerDeco: DecorationSource) {
return this.dirty == NOT_DIRTY && node.eq(this.node) &&
sameOuterDeco(outerDeco, this.outerDeco) && innerDeco.eq(this.innerDeco)
}
get size() { return this.node.nodeSize }
get border() { return this.node.isLeaf ? 0 : 1 }
// Syncs `this.children` to match `this.node.content` and the local
// decorations, possibly introducing nesting for marks. Then, in a
// separate step, syncs the DOM inside `this.contentDOM` to
// `this.children`.
updateChildren(view: EditorView, pos: number) {
let inline = this.node.inlineContent, off = pos
let composition = view.composing ? this.localCompositionInfo(view, pos) : null
let localComposition = composition && composition.pos > -1 ? composition : null
let compositionInChild = composition && composition.pos < 0
let updater = new ViewTreeUpdater(this, localComposition && localComposition.node, view)
iterDeco(this.node, this.innerDeco, (widget, i, insideNode) => {
if (widget.spec.marks)
updater.syncToMarks(widget.spec.marks, inline, view)
else if ((widget.type as WidgetType).side >= 0 && !insideNode)
updater.syncToMarks(i == this.node.childCount ? Mark.none : this.node.child(i).marks, inline, view)
// If the next node is a desc matching this widget, reuse it,
// otherwise insert the widget as a new view desc.
updater.placeWidget(widget, view, off)
}, (child, outerDeco, innerDeco, i) => {
// Make sure the wrapping mark descs match the node's marks.
updater.syncToMarks(child.marks, inline, view)
// Try several strategies for drawing this node
let compIndex
if (updater.findNodeMatch(child, outerDeco, innerDeco, i)) {
// Found precise match with existing node view
} else if (compositionInChild && view.state.selection.from > off &&
view.state.selection.to < off + child.nodeSize &&
(compIndex = updater.findIndexWithChild(composition!.node)) > -1 &&
updater.updateNodeAt(child, outerDeco, innerDeco, compIndex, view)) {
// Updated the specific node that holds the composition
} else if (updater.updateNextNode(child, outerDeco, innerDeco, view, i)) {
// Could update an existing node to reflect this node
} else {
// Add it as a new view
updater.addNode(child, outerDeco, innerDeco, view, off)
}
off += child.nodeSize
})
// Drop all remaining descs after the current position.
updater.syncToMarks([], inline, view)
if (this.node.isTextblock) updater.addTextblockHacks()
updater.destroyRest()
// Sync the DOM if anything changed
if (updater.changed || this.dirty == CONTENT_DIRTY) {
// May have to protect focused DOM from being changed if a composition is active
if (localComposition) this.protectLocalComposition(view, localComposition)
renderDescs(this.contentDOM!, this.children, view)
if (browser.ios) iosHacks(this.dom as HTMLElement)
}
}
localCompositionInfo(view: EditorView, pos: number): {node: Text, pos: number, text: string} | null {
// Only do something if both the selection and a focused text node
// are inside of this node
let {from, to} = view.state.selection
if (!(view.state.selection instanceof TextSelection) || from < pos || to > pos + this.node.content.size) return null
let sel = view.domSelectionRange()
let textNode = nearbyTextNode(sel.focusNode!, sel.focusOffset)
if (!textNode || !this.dom.contains(textNode.parentNode)) return null
if (this.node.inlineContent) {
// Find the text in the focused node in the node, stop if it's not
// there (may have been modified through other means, in which
// case it should overwritten)
let text = textNode.nodeValue!
let textPos = findTextInFragment(this.node.content, text, from - pos, to - pos)
return textPos < 0 ? null : {node: textNode, pos: textPos, text}
} else {
return {node: textNode, pos: -1, text: ""}
}
}
protectLocalComposition(view: EditorView, {node, pos, text}: {node: Text, pos: number, text: string}) {
// The node is already part of a local view desc, leave it there
if (this.getDesc(node)) return
// Create a composition view for the orphaned nodes
let topNode: DOMNode = node
for (;; topNode = topNode.parentNode!) {
if (topNode.parentNode == this.contentDOM) break
while (topNode.previousSibling) topNode.parentNode!.removeChild(topNode.previousSibling)
while (topNode.nextSibling) topNode.parentNode!.removeChild(topNode.nextSibling)
if (topNode.pmViewDesc) topNode.pmViewDesc = undefined
}
let desc = new CompositionViewDesc(this, topNode, node, text)
view.input.compositionNodes.push(desc)
// Patch up this.children to contain the composition view
this.children = replaceNodes(this.children, pos, pos + text.length, view, desc)
}
// If this desc must be updated to match the given node decoration,
// do so and return true.
update(node: Node, outerDeco: readonly Decoration[], innerDeco: DecorationSource, view: EditorView) {
if (this.dirty == NODE_DIRTY ||
!node.sameMarkup(this.node)) return false
this.updateInner(node, outerDeco, innerDeco, view)
return true
}
updateInner(node: Node, outerDeco: readonly Decoration[], innerDeco: DecorationSource, view: EditorView) {
this.updateOuterDeco(outerDeco)
this.node = node
this.innerDeco = innerDeco
if (this.contentDOM) this.updateChildren(view, this.posAtStart)
this.dirty = NOT_DIRTY
}
updateOuterDeco(outerDeco: readonly Decoration[]) {
if (sameOuterDeco(outerDeco, this.outerDeco)) return
let needsWrap = this.nodeDOM.nodeType != 1
let oldDOM = this.dom
this.dom = patchOuterDeco(this.dom, this.nodeDOM,
computeOuterDeco(this.outerDeco, this.node, needsWrap),
computeOuterDeco(outerDeco, this.node, needsWrap))
if (this.dom != oldDOM) {
oldDOM.pmViewDesc = undefined
this.dom.pmViewDesc = this
}
this.outerDeco = outerDeco
}
// Mark this node as being the selected node.
selectNode() {
if (this.nodeDOM.nodeType == 1) (this.nodeDOM as HTMLElement).classList.add("ProseMirror-selectednode")
if (this.contentDOM || !this.node.type.spec.draggable) (this.dom as HTMLElement).draggable = true
}
// Remove selected node marking from this node.
deselectNode() {
if (this.nodeDOM.nodeType == 1) (this.nodeDOM as HTMLElement).classList.remove("ProseMirror-selectednode")
if (this.contentDOM || !this.node.type.spec.draggable) (this.dom as HTMLElement).removeAttribute("draggable")
}
get domAtom() { return this.node.isAtom }
}
// Create a view desc for the top-level document node, to be exported
// and used by the view class.
export function docViewDesc(doc: Node, outerDeco: readonly Decoration[], innerDeco: DecorationSource,
dom: HTMLElement, view: EditorView): NodeViewDesc {
applyOuterDeco(dom, outerDeco, doc)
return new NodeViewDesc(undefined, doc, outerDeco, innerDeco, dom, dom, dom, view, 0)
}
class TextViewDesc extends NodeViewDesc {
constructor(parent: ViewDesc | undefined, node: Node, outerDeco: readonly Decoration[],
innerDeco: DecorationSource, dom: DOMNode, nodeDOM: DOMNode, view: EditorView) {
super(parent, node, outerDeco, innerDeco, dom, null, nodeDOM, view, 0)
}
parseRule(): ParseRule {
let skip = this.nodeDOM.parentNode
while (skip && skip != this.dom && !(skip as any).pmIsDeco) skip = skip.parentNode
return {skip: (skip || true) as any}
}
update(node: Node, outerDeco: readonly Decoration[], innerDeco: DecorationSource, view: EditorView) {
if (this.dirty == NODE_DIRTY || (this.dirty != NOT_DIRTY && !this.inParent()) ||
!node.sameMarkup(this.node)) return false
this.updateOuterDeco(outerDeco)
if ((this.dirty != NOT_DIRTY || node.text != this.node.text) && node.text != this.nodeDOM.nodeValue) {
this.nodeDOM.nodeValue = node.text!
if (view.trackWrites == this.nodeDOM) view.trackWrites = null
}
this.node = node
this.dirty = NOT_DIRTY
return true
}
inParent() {
let parentDOM = this.parent!.contentDOM
for (let n: DOMNode | null = this.nodeDOM; n; n = n.parentNode) if (n == parentDOM) return true
return false
}
domFromPos(pos: number) {
return {node: this.nodeDOM, offset: pos}
}
localPosFromDOM(dom: DOMNode, offset: number, bias: number) {
if (dom == this.nodeDOM) return this.posAtStart + Math.min(offset, this.node.text!.length)
return super.localPosFromDOM(dom, offset, bias)
}
ignoreMutation(mutation: MutationRecord) {
return mutation.type != "characterData" && (mutation.type as any) != "selection"
}
slice(from: number, to: number, view: EditorView) {
let node = this.node.cut(from, to), dom = document.createTextNode(node.text!)
return new TextViewDesc(this.parent, node, this.outerDeco, this.innerDeco, dom, dom, view)
}
markDirty(from: number, to: number) {
super.markDirty(from, to)
if (this.dom != this.nodeDOM && (from == 0 || to == this.nodeDOM.nodeValue!.length))
this.dirty = NODE_DIRTY
}
get domAtom() { return false }
}
// A dummy desc used to tag trailing BR or IMG nodes created to work
// around contentEditable terribleness.
class TrailingHackViewDesc extends ViewDesc {
parseRule() { return {ignore: true} }
matchesHack(nodeName: string) { return this.dirty == NOT_DIRTY && this.dom.nodeName == nodeName }
get domAtom() { return true }
get ignoreForCoords() { return this.dom.nodeName == "IMG" }
}
// A separate subclass is used for customized node views, so that the
// extra checks only have to be made for nodes that are actually
// customized.
class CustomNodeViewDesc extends NodeViewDesc {
constructor(parent: ViewDesc | undefined, node: Node, outerDeco: readonly Decoration[], innerDeco: DecorationSource,
dom: DOMNode, contentDOM: HTMLElement | null, nodeDOM: DOMNode, readonly spec: NodeView,
view: EditorView, pos: number) {
super(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos)
}
// A custom `update` method gets to decide whether the update goes
// through. If it does, and there's a `contentDOM` node, our logic
// updates the children.
update(node: Node, outerDeco: readonly Decoration[], innerDeco: DecorationSource, view: EditorView) {
if (this.dirty == NODE_DIRTY) return false
if (this.spec.update) {
let result = this.spec.update(node, outerDeco, innerDeco)
if (result) this.updateInner(node, outerDeco, innerDeco, view)
return result
} else if (!this.contentDOM && !node.isLeaf) {
return false
} else {
return super.update(node, outerDeco, innerDeco, view)
}
}
selectNode() {
this.spec.selectNode ? this.spec.selectNode() : super.selectNode()
}
deselectNode() {
this.spec.deselectNode ? this.spec.deselectNode() : super.deselectNode()
}
setSelection(anchor: number, head: number, root: Document | ShadowRoot, force: boolean) {
this.spec.setSelection ? this.spec.setSelection(anchor, head, root)
: super.setSelection(anchor, head, root, force)
}
destroy() {
if (this.spec.destroy) this.spec.destroy()
super.destroy()
}
stopEvent(event: Event) {
return this.spec.stopEvent ? this.spec.stopEvent(event) : false
}
ignoreMutation(mutation: MutationRecord) {
return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation)
}
}
// Sync the content of the given DOM node with the nodes associated
// with the given array of view descs, recursing into mark descs
// because this should sync the subtree for a whole node at a time.
function renderDescs(parentDOM: HTMLElement, descs: readonly ViewDesc[], view: EditorView) {
let dom = parentDOM.firstChild, written = false
for (let i = 0; i < descs.length; i++) {
let desc = descs[i], childDOM = desc.dom
if (childDOM.parentNode == parentDOM) {
while (childDOM != dom) { dom = rm(dom!); written = true }
dom = dom.nextSibling
} else {
written = true
parentDOM.insertBefore(childDOM, dom)
}
if (desc instanceof MarkViewDesc) {
let pos = dom ? dom.previousSibling : parentDOM.lastChild
renderDescs(desc.contentDOM!, desc.children, view)
dom = pos ? pos.nextSibling : parentDOM.firstChild
}
}
while (dom) { dom = rm(dom); written = true }
if (written && view.trackWrites == parentDOM) view.trackWrites = null
}
type OuterDecoLevel = {[attr: string]: string}
const OuterDecoLevel: {new (nodeName?: string): OuterDecoLevel} = function(this: any, nodeName?: string) {
if (nodeName) this.nodeName = nodeName
} as any
OuterDecoLevel.prototype = Object.create(null)