@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.
package/src/index.ts ADDED
@@ -0,0 +1,800 @@
1
+ import {NodeSelection, EditorState, Plugin, PluginView, Transaction, Selection} from "prosemirror-state"
2
+ import {Slice, ResolvedPos, DOMParser, DOMSerializer, Node, Mark} from "prosemirror-model"
3
+
4
+ import {scrollRectIntoView, posAtCoords, coordsAtPos, endOfTextblock, storeScrollPos,
5
+ resetScrollPos, focusPreventScroll} from "./domcoords"
6
+ import {docViewDesc, ViewDesc, NodeView, NodeViewDesc, MarkView} from "./viewdesc"
7
+ import {initInput, destroyInput, dispatchEvent, ensureListeners, clearComposition,
8
+ InputState, doPaste, Dragging, findCompositionNode} from "./input"
9
+ import {DOMSelState} from "./selection"
10
+ import {Decoration, viewDecorations, DecorationSource} from "./decoration"
11
+ import {DOMObserver} from "./domobserver"
12
+ import {DOMSelection, DOMNode, clearReusedRange, isElt} from "./dom"
13
+ import * as browser from "./browser"
14
+
15
+ export {Decoration, DecorationSet, DecorationAttrs, DecorationSource} from "./decoration"
16
+ export {NodeView, MarkView, ViewMutationRecord} from "./viewdesc"
17
+
18
+ // Exported for testing
19
+ import {serializeForClipboard, parseFromClipboard} from "./clipboard"
20
+ import {endComposition} from "./input"
21
+ /// @internal
22
+ export const __parseFromClipboard = parseFromClipboard
23
+ /// @internal
24
+ export const __endComposition = endComposition
25
+
26
+ /// An editor view manages the DOM structure that represents an
27
+ /// editable document. Its state and behavior are determined by its
28
+ /// [props](#view.DirectEditorProps).
29
+ export class EditorView {
30
+ /// @internal
31
+ _props: DirectEditorProps
32
+ private directPlugins: readonly Plugin[]
33
+ private _root: Document | ShadowRoot | null = null
34
+ /// @internal
35
+ focused = false
36
+ /// Kludge used to work around a Chrome bug @internal
37
+ trackWrites: DOMNode | null = null
38
+ private mounted = false
39
+ /// @internal
40
+ markCursor: readonly Mark[] | null = null
41
+ /// @internal
42
+ cursorWrapper: {dom: DOMNode, deco: Decoration} | null = null
43
+ /// @internal
44
+ nodeViews: NodeViewSet
45
+ /// @internal
46
+ lastSelectedViewDesc: ViewDesc | undefined = undefined
47
+ /// @internal
48
+ docView: NodeViewDesc
49
+ /// @internal
50
+ input = new InputState
51
+ private prevDirectPlugins: readonly Plugin[] = []
52
+ private pluginViews: PluginView[] = []
53
+ /// @internal
54
+ domObserver: DOMObserver
55
+ /// State related to the relation between the DOM selection and the
56
+ /// state selection. Not to be confused with `domSelection`, which
57
+ /// gives access to the raw DOM `Selection` object. @internal
58
+ domSel: DOMSelState
59
+ /// Holds `true` when a hack node is needed in Firefox to prevent the
60
+ /// [space is eaten issue](https://code.haverbeke.berlin/prosemirror/prosemirror/issues/651)
61
+ /// @internal
62
+ requiresGeckoHackNode: boolean = false
63
+
64
+ /// The view's current [state](#state.EditorState).
65
+ public state: EditorState
66
+
67
+ /// Create a view. `place` may be a DOM node that the editor should
68
+ /// be appended to, a function that will place it into the document,
69
+ /// or an object whose `mount` property holds the node to use as the
70
+ /// document container. If it is `null`, the editor will not be
71
+ /// added to the document.
72
+ constructor(place: null | DOMNode | ((editor: HTMLElement) => void) | {mount: HTMLElement}, props: DirectEditorProps) {
73
+ this._props = props
74
+ this.state = props.state
75
+ this.directPlugins = props.plugins || []
76
+ this.directPlugins.forEach(checkStateComponent)
77
+
78
+ this.dispatch = this.dispatch.bind(this)
79
+
80
+ this.dom = (place && (place as {mount: HTMLElement}).mount) || document.createElement("div")
81
+ if (place) {
82
+ if ((place as DOMNode).appendChild) (place as DOMNode).appendChild(this.dom)
83
+ else if (typeof place == "function") place(this.dom)
84
+ else if ((place as {mount: HTMLElement}).mount) this.mounted = true
85
+ }
86
+
87
+ this.editable = getEditable(this)
88
+ updateCursorWrapper(this)
89
+ this.nodeViews = buildNodeViews(this)
90
+ this.docView = docViewDesc(this.state.doc, computeDocDeco(this), viewDecorations(this), this.dom, this)
91
+
92
+ this.domObserver = new DOMObserver(this)
93
+ this.domSel = new DOMSelState(this)
94
+ this.domObserver.start()
95
+ this.domSel.read()
96
+ initInput(this)
97
+ this.updatePluginViews()
98
+ }
99
+
100
+ /// An editable DOM node containing the document. (You probably
101
+ /// should not directly interfere with its content.)
102
+ readonly dom: HTMLElement
103
+
104
+ /// Indicates whether the editor is currently [editable](#view.EditorProps.editable).
105
+ editable: boolean
106
+
107
+ /// When editor content is being dragged, this object contains
108
+ /// information about the dragged slice and whether it is being
109
+ /// copied or moved. At any other time, it is null.
110
+ dragging: null | {slice: Slice, move: boolean} = null
111
+
112
+ /// Holds `true` when a
113
+ /// [composition](https://w3c.github.io/uievents/#events-compositionevents)
114
+ /// is active.
115
+ get composing() { return this.input.composing }
116
+
117
+ /// The view's current [props](#view.EditorProps).
118
+ get props() {
119
+ if (this._props.state != this.state) {
120
+ let prev = this._props
121
+ this._props = {} as any
122
+ for (let name in prev) (this._props as any)[name] = (prev as any)[name]
123
+ this._props.state = this.state
124
+ }
125
+ return this._props
126
+ }
127
+
128
+ /// Update the view's props. Will immediately cause an update to
129
+ /// the DOM.
130
+ update(props: DirectEditorProps) {
131
+ if (props.handleDOMEvents != this._props.handleDOMEvents) ensureListeners(this)
132
+ let prevProps = this._props
133
+ this._props = props
134
+ if (props.plugins) {
135
+ props.plugins.forEach(checkStateComponent)
136
+ this.directPlugins = props.plugins
137
+ }
138
+ this.updateStateInner(props.state, prevProps)
139
+ }
140
+
141
+ /// Update the view by updating existing props object with the object
142
+ /// given as argument. Equivalent to `view.update(Object.assign({},
143
+ /// view.props, props))`.
144
+ setProps(props: Partial<DirectEditorProps>) {
145
+ let updated = {} as DirectEditorProps
146
+ for (let name in this._props) (updated as any)[name] = (this._props as any)[name]
147
+ updated.state = this.state
148
+ for (let name in props) (updated as any)[name] = (props as any)[name]
149
+ this.update(updated)
150
+ }
151
+
152
+ /// Update the editor's `state` prop, without touching any of the
153
+ /// other props.
154
+ updateState(state: EditorState) {
155
+ this.updateStateInner(state, this._props)
156
+ }
157
+
158
+ private updateStateInner(state: EditorState, prevProps: DirectEditorProps) {
159
+ let prev = this.state, redraw = false, updateSel = false
160
+ // When stored marks are added, stop composition, so that they can
161
+ // be displayed.
162
+ if (state.storedMarks && this.composing) {
163
+ clearComposition(this)
164
+ updateSel = true
165
+ }
166
+ this.state = state
167
+ let pluginsChanged = prev.plugins != state.plugins || this._props.plugins != prevProps.plugins
168
+ if (pluginsChanged || this._props.plugins != prevProps.plugins || this._props.nodeViews != prevProps.nodeViews) {
169
+ let nodeViews = buildNodeViews(this)
170
+ if (changedNodeViews(nodeViews, this.nodeViews)) {
171
+ this.nodeViews = nodeViews
172
+ redraw = true
173
+ }
174
+ }
175
+ if (pluginsChanged || prevProps.handleDOMEvents != this._props.handleDOMEvents) {
176
+ ensureListeners(this)
177
+ }
178
+
179
+ this.editable = getEditable(this)
180
+ updateCursorWrapper(this)
181
+ let innerDeco = viewDecorations(this), outerDeco = computeDocDeco(this)
182
+
183
+ let scroll = prev.plugins != state.plugins && !prev.doc.eq(state.doc) ? "reset"
184
+ : (state as any).scrollToSelection > (prev as any).scrollToSelection ? "to selection" : "preserve"
185
+ let updateDoc = redraw || !this.docView.matchesNode(state.doc, outerDeco, innerDeco)
186
+ if (updateDoc || !state.selection.eq(prev.selection) || !this.domSel.synced && this.domSel.active) updateSel = true
187
+ let oldScrollPos = scroll == "preserve" && updateSel && this.dom.style.overflowAnchor == null && storeScrollPos(this)
188
+
189
+ if (updateSel) this.domObserver.stopped(() => {
190
+ // Work around an issue in Chrome where changing the DOM around
191
+ // an active selection puts it into a broken state where the
192
+ // thing the user sees differs from the selection reported by
193
+ // the Selection object (#710, #973, #1011, #1013, #1035).
194
+ let forceSelUpdate = updateDoc && browser.chrome && !this.composing &&
195
+ !prev.selection.empty && !state.selection.empty && selectionContextChanged(prev.selection, state.selection)
196
+ if (updateDoc) {
197
+ // If the node that the selection points into is written to,
198
+ // Chrome sometimes starts misreporting the selection, so this
199
+ // tracks that and forces a selection reset when our update
200
+ // did write to the node.
201
+ let chromeKludge = browser.chrome ? (this.trackWrites = this.domSel.range.focusNode) : null
202
+ if (this.composing) this.input.compositionNode = findCompositionNode(this)
203
+ if (redraw || !this.docView.update(state.doc, outerDeco, innerDeco, this, -1)) {
204
+ let prevOuter = this.docView.outerDeco
205
+ this.docView.destroy()
206
+ this.docView = docViewDesc(state.doc, outerDeco, innerDeco, this.dom, this, prevOuter)
207
+ }
208
+ if (chromeKludge && (!this.trackWrites || !this.dom.contains(this.trackWrites))) forceSelUpdate = true
209
+ }
210
+ this.domSel.sync(forceSelUpdate)
211
+ })
212
+
213
+ this.updatePluginViews(prev)
214
+ if ((this.dragging as Dragging)?.node && !prev.doc.eq(state.doc))
215
+ this.updateDraggedNode(this.dragging as Dragging, prev)
216
+
217
+ if (scroll == "reset") {
218
+ this.dom.scrollTop = 0
219
+ } else if (scroll == "to selection") {
220
+ this.scrollToSelection()
221
+ } else if (oldScrollPos) {
222
+ resetScrollPos(oldScrollPos)
223
+ }
224
+ }
225
+
226
+ /// @internal
227
+ scrollToSelection() {
228
+ let startDOM = this.domSel.range.focusNode
229
+ if (!startDOM || !this.domSel.active) {
230
+ // Ignore selections outside the editor
231
+ } else if (this.someProp("handleScrollToSelection", f => f(this))) {
232
+ // Handled
233
+ } else if (this.state.selection instanceof NodeSelection) {
234
+ let target = this.docView.domAfterPos(this.state.selection.from)
235
+ if (isElt(target)) scrollRectIntoView(this, target.getBoundingClientRect(), startDOM)
236
+ } else {
237
+ scrollRectIntoView(this, this.coordsAtPos(this.state.selection.head, 1), startDOM)
238
+ }
239
+ }
240
+
241
+ private destroyPluginViews() {
242
+ let view
243
+ while (view = this.pluginViews.pop()) if (view.destroy) view.destroy()
244
+ }
245
+
246
+ private updatePluginViews(prevState?: EditorState) {
247
+ if (!prevState || prevState.plugins != this.state.plugins || this.directPlugins != this.prevDirectPlugins) {
248
+ this.prevDirectPlugins = this.directPlugins
249
+ this.destroyPluginViews()
250
+ for (let i = 0; i < this.directPlugins.length; i++) {
251
+ let plugin = this.directPlugins[i]
252
+ if (plugin.spec.view) this.pluginViews.push(plugin.spec.view(this))
253
+ }
254
+ for (let i = 0; i < this.state.plugins.length; i++) {
255
+ let plugin = this.state.plugins[i]
256
+ if (plugin.spec.view) this.pluginViews.push(plugin.spec.view(this))
257
+ }
258
+ } else {
259
+ for (let i = 0; i < this.pluginViews.length; i++) {
260
+ let pluginView = this.pluginViews[i]
261
+ if (pluginView.update) pluginView.update(this, prevState)
262
+ }
263
+ }
264
+ }
265
+
266
+ private updateDraggedNode(dragging: Dragging, prev: EditorState) {
267
+ let sel = dragging.node!, found = -1
268
+ if (sel.from < this.state.doc.content.size && this.state.doc.nodeAt(sel.from) == sel.node) {
269
+ found = sel.from
270
+ } else {
271
+ let movedPos = sel.from + (this.state.doc.content.size - prev.doc.content.size)
272
+ let moved = movedPos > 0 && movedPos < this.state.doc.content.size && this.state.doc.nodeAt(movedPos)
273
+ if (moved == sel.node) found = movedPos
274
+ }
275
+ this.dragging = new Dragging(dragging.slice, dragging.move,
276
+ found < 0 ? undefined : NodeSelection.create(this.state.doc, found))
277
+ }
278
+
279
+ /// Goes over the values of a prop, first those provided directly,
280
+ /// then those from plugins given to the view, then from plugins in
281
+ /// the state (in order), and calls `f` every time a non-undefined
282
+ /// value is found. When `f` returns a truthy value, that is
283
+ /// immediately returned. When `f` isn't provided, it is treated as
284
+ /// the identity function (the prop value is returned directly).
285
+ someProp<PropName extends keyof EditorProps, Result>(
286
+ propName: PropName,
287
+ f: (value: NonNullable<EditorProps[PropName]>) => Result
288
+ ): Result | undefined
289
+ someProp<PropName extends keyof EditorProps>(propName: PropName): NonNullable<EditorProps[PropName]> | undefined
290
+ someProp<PropName extends keyof EditorProps, Result>(
291
+ propName: PropName,
292
+ f?: (value: NonNullable<EditorProps[PropName]>) => Result
293
+ ): Result | undefined {
294
+ let prop = this._props && this._props[propName], value
295
+ if (prop != null && (value = f ? f(prop as any) : prop)) return value as any
296
+ for (let i = 0; i < this.directPlugins.length; i++) {
297
+ let prop = this.directPlugins[i].props[propName]
298
+ if (prop != null && (value = f ? f(prop as any) : prop)) return value as any
299
+ }
300
+ let plugins = this.state.plugins
301
+ if (plugins) for (let i = 0; i < plugins.length; i++) {
302
+ let prop = plugins[i].props[propName]
303
+ if (prop != null && (value = f ? f(prop as any) : prop)) return value as any
304
+ }
305
+ }
306
+
307
+ /// Query whether the view has focus.
308
+ hasFocus() {
309
+ return this.root.activeElement == this.dom
310
+ }
311
+
312
+ /// Focus the editor.
313
+ focus() {
314
+ if (this.editable) focusPreventScroll(this.dom)
315
+ this.domSel.sync()
316
+ }
317
+
318
+ /// Get the document root in which the editor exists. This will
319
+ /// usually be the top-level `document`, but might be a [shadow
320
+ /// DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM)
321
+ /// root if the editor is inside one.
322
+ get root(): Document | ShadowRoot {
323
+ let connected = this.dom.isConnected !== false
324
+ if (!connected) this._root = null
325
+
326
+ let cached = this._root
327
+ if (cached == null && connected) for (let search = this.dom.parentNode; search; search = search.parentNode) {
328
+ if (search.nodeType == 9 || (search.nodeType == 11 && (search as any).host)) {
329
+ if (!(search as any).getSelection)
330
+ Object.getPrototypeOf(search).getSelection = () => (search as DOMNode).ownerDocument!.getSelection()
331
+ return this._root = search as Document | ShadowRoot
332
+ }
333
+ }
334
+ return cached || document
335
+ }
336
+
337
+ /// When an existing editor view is moved to a new document or
338
+ /// shadow tree, call this to make it recompute its root.
339
+ updateRoot() {
340
+ this._root = null
341
+ }
342
+
343
+ /// Given a pair of viewport coordinates, return the document
344
+ /// position that corresponds to them. May return null if the given
345
+ /// coordinates aren't inside of the editor. When an object is
346
+ /// returned, its `pos` property is the position nearest to the
347
+ /// coordinates, and its `inside` property holds the position of the
348
+ /// inner node that the position falls inside of, or -1 if it is at
349
+ /// the top level, not in any node.
350
+ posAtCoords(coords: {left: number, top: number}): {pos: number, inside: number, affinity: -1 | 0 | 1} | null {
351
+ return posAtCoords(this, coords)
352
+ }
353
+
354
+ /// Returns the viewport rectangle at a given document position.
355
+ /// `left` and `right` will be the same number, as this returns a
356
+ /// flat cursor-ish rectangle. If the position is between two things
357
+ /// that aren't directly adjacent, `side` determines which element
358
+ /// is used. When < 0, the element before the position is used,
359
+ /// otherwise the element after.
360
+ coordsAtPos(pos: number, side = 1): {left: number, right: number, top: number, bottom: number} {
361
+ return coordsAtPos(this, pos, side)
362
+ }
363
+
364
+ /// Find the DOM position that corresponds to the given document
365
+ /// position. When `side` is negative, find the position as close as
366
+ /// possible to the content before the position. When positive,
367
+ /// prefer positions close to the content after the position. When
368
+ /// zero, prefer as shallow a position as possible.
369
+ ///
370
+ /// Note that you should **not** mutate the editor's internal DOM,
371
+ /// only inspect it (and even that is usually not necessary).
372
+ domAtPos(pos: number, side = 0): {node: DOMNode, offset: number} {
373
+ return this.docView.domFromPos(pos, side)
374
+ }
375
+
376
+ /// Find the DOM node that represents the document node after the
377
+ /// given position. May return `null` when the position doesn't point
378
+ /// in front of a node or if the node is inside an opaque node view.
379
+ ///
380
+ /// This is intended to be able to call things like
381
+ /// `getBoundingClientRect` on that DOM node. Do **not** mutate the
382
+ /// editor DOM directly, or add styling this way, since that will be
383
+ /// immediately overriden by the editor as it redraws the node.
384
+ nodeDOM(pos: number): DOMNode | null {
385
+ let desc = this.docView.descAt(pos)
386
+ return desc ? desc.nodeDOM : null
387
+ }
388
+
389
+ /// Find the document position that corresponds to a given DOM
390
+ /// position. (Whenever possible, it is preferable to inspect the
391
+ /// document structure directly, rather than poking around in the
392
+ /// DOM, but sometimes—for example when interpreting an event
393
+ /// target—you don't have a choice.)
394
+ ///
395
+ /// The `bias` parameter can be used to influence which side of a DOM
396
+ /// node to use when the position is inside a leaf node.
397
+ posAtDOM(node: DOMNode, offset: number, bias = -1): number {
398
+ let pos = this.docView.posFromDOM(node, offset, bias)
399
+ if (pos == null) throw new RangeError("DOM position not inside the editor")
400
+ return pos
401
+ }
402
+
403
+ /// Find out whether the selection is at the end of a textblock when
404
+ /// moving in a given direction. When, for example, given `"left"`,
405
+ /// it will return true if moving left from the current cursor
406
+ /// position would leave that position's parent textblock. Will apply
407
+ /// to the view's current state by default, but it is possible to
408
+ /// pass a different state.
409
+ endOfTextblock(dir: "up" | "down" | "left" | "right" | "forward" | "backward", state?: EditorState): boolean {
410
+ return endOfTextblock(this, state || this.state, dir)
411
+ }
412
+
413
+ /// Run the editor's paste logic with the given HTML string. The
414
+ /// `event`, if given, will be passed to the
415
+ /// [`handlePaste`](#view.EditorProps.handlePaste) hook.
416
+ pasteHTML(html: string, event?: ClipboardEvent) {
417
+ return doPaste(this, "", html, false, event || new ClipboardEvent("paste"))
418
+ }
419
+
420
+ /// Run the editor's paste logic with the given plain-text input.
421
+ pasteText(text: string, event?: ClipboardEvent) {
422
+ return doPaste(this, text, null, true, event || new ClipboardEvent("paste"))
423
+ }
424
+
425
+ /// Serialize the given slice as it would be if it was copied from
426
+ /// this editor. Returns a DOM element that contains a
427
+ /// representation of the slice as its children, a textual
428
+ /// representation, and the transformed slice (which can be
429
+ /// different from the given input due to hooks like
430
+ /// [`transformCopied`](#view.EditorProps.transformCopied)).
431
+ serializeForClipboard(slice: Slice): {dom: HTMLElement, text: string, slice: Slice} {
432
+ return serializeForClipboard(this, slice)
433
+ }
434
+
435
+ /// Removes the editor from the DOM and destroys all [node
436
+ /// views](#view.NodeView).
437
+ destroy() {
438
+ if (!this.docView) return
439
+ destroyInput(this) // disconnects this.domObserver
440
+ this.domSel.destroy()
441
+ this.destroyPluginViews()
442
+ if (this.mounted) {
443
+ this.docView.update(this.state.doc, [], viewDecorations(this), this, -1)
444
+ this.dom.textContent = ""
445
+ } else if (this.dom.parentNode) {
446
+ this.dom.parentNode.removeChild(this.dom)
447
+ }
448
+ this.docView.destroy()
449
+ ;(this as any).docView = null
450
+ clearReusedRange()
451
+ }
452
+
453
+ /// This is true when the view has been
454
+ /// [destroyed](#view.EditorView.destroy) (and thus should not be
455
+ /// used anymore).
456
+ get isDestroyed() {
457
+ return this.docView == null
458
+ }
459
+
460
+ /// Used for testing.
461
+ dispatchEvent(event: Event) {
462
+ return dispatchEvent(this, event)
463
+ }
464
+
465
+ /// Dispatch a transaction. Will call
466
+ /// [`dispatchTransaction`](#view.DirectEditorProps.dispatchTransaction)
467
+ /// when given, and otherwise defaults to applying the transaction to
468
+ /// the current state and calling
469
+ /// [`updateState`](#view.EditorView.updateState) with the result.
470
+ /// This method is bound to the view instance, so that it can be
471
+ /// easily passed around.
472
+ declare dispatch: (tr: Transaction) => void
473
+
474
+ /// @internal
475
+ domSelection(): DOMSelection | null {
476
+ return (this.root as Document).getSelection()
477
+ }
478
+ }
479
+
480
+ EditorView.prototype.dispatch = function(tr: Transaction) {
481
+ let dispatchTransaction = this._props.dispatchTransaction
482
+ if (dispatchTransaction) dispatchTransaction.call(this, tr)
483
+ else this.updateState(this.state.apply(tr))
484
+ }
485
+
486
+ function computeDocDeco(view: EditorView) {
487
+ let attrs = Object.create(null)
488
+ attrs.class = "ProseMirror"
489
+ attrs.contenteditable = String(view.editable)
490
+
491
+ view.someProp("attributes", value => {
492
+ if (typeof value == "function") value = value(view.state)
493
+ if (value) for (let attr in value) {
494
+ if (attr == "class")
495
+ attrs.class += " " + value[attr]
496
+ else if (attr == "style")
497
+ attrs.style = (attrs.style ? attrs.style + ";" : "") + value[attr]
498
+ else if (!attrs[attr] && attr != "contenteditable" && attr != "nodeName")
499
+ attrs[attr] = String(value[attr])
500
+ }
501
+ })
502
+ if (!attrs.translate) attrs.translate = "no"
503
+
504
+ return [Decoration.node(0, view.state.doc.content.size, attrs)]
505
+ }
506
+
507
+ function updateCursorWrapper(view: EditorView) {
508
+ if (view.markCursor) {
509
+ let dom = document.createElement("img")
510
+ dom.className = "ProseMirror-separator"
511
+ dom.setAttribute("mark-placeholder", "true")
512
+ dom.setAttribute("alt", "")
513
+ view.cursorWrapper = {dom, deco: Decoration.widget(view.state.selection.from,
514
+ dom, {raw: true, marks: view.markCursor} as any)}
515
+ } else {
516
+ view.cursorWrapper = null
517
+ }
518
+ }
519
+
520
+ function getEditable(view: EditorView) {
521
+ return !view.someProp("editable", value => value(view.state) === false)
522
+ }
523
+
524
+ function selectionContextChanged(sel1: Selection, sel2: Selection) {
525
+ let depth = Math.min(sel1.$anchor.sharedDepth(sel1.head), sel2.$anchor.sharedDepth(sel2.head))
526
+ return sel1.$anchor.start(depth) != sel2.$anchor.start(depth)
527
+ }
528
+
529
+ function buildNodeViews(view: EditorView) {
530
+ let result: NodeViewSet = Object.create(null)
531
+ function add(obj: NodeViewSet) {
532
+ for (let prop in obj) if (!Object.prototype.hasOwnProperty.call(result, prop))
533
+ result[prop] = obj[prop]
534
+ }
535
+ view.someProp("nodeViews", add)
536
+ view.someProp("markViews", add)
537
+ return result
538
+ }
539
+
540
+ function changedNodeViews(a: NodeViewSet, b: NodeViewSet) {
541
+ let nA = 0, nB = 0
542
+ for (let prop in a) {
543
+ if (a[prop] != b[prop]) return true
544
+ nA++
545
+ }
546
+ for (let _ in b) nB++
547
+ return nA != nB
548
+ }
549
+
550
+ function checkStateComponent(plugin: Plugin) {
551
+ if (plugin.spec.state || plugin.spec.filterTransaction || plugin.spec.appendTransaction)
552
+ throw new RangeError("Plugins passed directly to the view must not have a state component")
553
+ }
554
+
555
+ /// The type of function [provided](#view.EditorProps.nodeViews) to
556
+ /// create [node views](#view.NodeView).
557
+ export type NodeViewConstructor = (node: Node, view: EditorView, getPos: () => number | undefined,
558
+ decorations: readonly Decoration[], innerDecorations: DecorationSource) => NodeView
559
+
560
+ /// The function types [used](#view.EditorProps.markViews) to create
561
+ /// mark views.
562
+ export type MarkViewConstructor = (mark: Mark, view: EditorView, inline: boolean) => MarkView
563
+
564
+ type NodeViewSet = {[name: string]: NodeViewConstructor | MarkViewConstructor}
565
+
566
+ /// Helper type that maps event names to event object types, but
567
+ /// includes events that TypeScript's HTMLElementEventMap doesn't know
568
+ /// about.
569
+ export interface DOMEventMap extends HTMLElementEventMap {
570
+ [event: string]: any
571
+ }
572
+
573
+ /// Props are configuration values that can be passed to an editor view
574
+ /// or included in a plugin. This interface lists the supported props.
575
+ ///
576
+ /// The various event-handling functions may all return `true` to
577
+ /// indicate that they handled the given event. The view will then take
578
+ /// care to call `preventDefault` on the event, except with
579
+ /// `handleDOMEvents`, where the handler itself is responsible for that.
580
+ ///
581
+ /// How a prop is resolved depends on the prop. Handler functions are
582
+ /// called one at a time, starting with the base props and then
583
+ /// searching through the plugins (in order of appearance) until one of
584
+ /// them returns true. For some props, the first plugin that yields a
585
+ /// value gets precedence.
586
+ ///
587
+ /// The optional type parameter refers to the type of `this` in prop
588
+ /// functions, and is used to pass in the plugin type when defining a
589
+ /// [plugin](#state.Plugin).
590
+ export interface EditorProps<P = any> {
591
+ /// Can be an object mapping DOM event type names to functions that
592
+ /// handle them. Such functions will be called before any handling
593
+ /// ProseMirror does of events fired on the editable DOM element.
594
+ /// Contrary to the other event handling props, when returning true
595
+ /// from such a function, you are responsible for calling
596
+ /// `preventDefault` yourself (or not, if you want to allow the
597
+ /// default behavior).
598
+ handleDOMEvents?: {
599
+ [event in keyof DOMEventMap]?: (this: P, view: EditorView, event: DOMEventMap[event]) => boolean | void
600
+ }
601
+
602
+ /// Called when the editor receives a `keydown` event.
603
+ handleKeyDown?: (this: P, view: EditorView, event: KeyboardEvent) => boolean | void
604
+
605
+ /// Handler for `keypress` events.
606
+ handleKeyPress?: (this: P, view: EditorView, event: KeyboardEvent) => boolean | void
607
+
608
+ /// Whenever the user directly input text, this handler is called
609
+ /// before the input is applied. If it returns `true`, the default
610
+ /// behavior of actually inserting the text is suppressed.
611
+ handleTextInput?: (this: P, view: EditorView, from: number, to: number, text: string, deflt: () => Transaction) => boolean | void
612
+
613
+ /// Called for each node around a click, from the inside out. The
614
+ /// `direct` flag will be true for the inner node.
615
+ handleClickOn?: (this: P, view: EditorView, pos: number, node: Node, nodePos: number, event: MouseEvent, direct: boolean) => boolean | void
616
+
617
+ /// Called when the editor is clicked, after `handleClickOn` handlers
618
+ /// have been called.
619
+ handleClick?: (this: P, view: EditorView, pos: number, event: MouseEvent) => boolean | void
620
+
621
+ /// Called for each node around a double click.
622
+ handleDoubleClickOn?: (this: P, view: EditorView, pos: number, node: Node, nodePos: number, event: MouseEvent, direct: boolean) => boolean | void
623
+
624
+ /// Called when the editor is double-clicked, after `handleDoubleClickOn`.
625
+ handleDoubleClick?: (this: P, view: EditorView, pos: number, event: MouseEvent) => boolean | void
626
+
627
+ /// Called for each node around a triple click.
628
+ handleTripleClickOn?: (this: P, view: EditorView, pos: number, node: Node, nodePos: number, event: MouseEvent, direct: boolean) => boolean | void
629
+
630
+ /// Called when the editor is triple-clicked, after `handleTripleClickOn`.
631
+ handleTripleClick?: (this: P, view: EditorView, pos: number, event: MouseEvent) => boolean | void
632
+
633
+ /// Can be used to override the behavior of pasting. `slice` is the
634
+ /// pasted content parsed by the editor, but you can directly access
635
+ /// the event to get at the raw content.
636
+ handlePaste?: (this: P, view: EditorView, event: ClipboardEvent, slice: Slice) => boolean | void
637
+
638
+ /// Called when something is dropped on the editor. `moved` will be
639
+ /// true if this drop moves from the current selection (which should
640
+ /// thus be deleted).
641
+ handleDrop?: (this: P, view: EditorView, event: DragEvent, slice: Slice, moved: boolean) => boolean | void
642
+
643
+ /// Called when the view, after updating its state, tries to scroll
644
+ /// the selection into view. A handler function may return false to
645
+ /// indicate that it did not handle the scrolling and further
646
+ /// handlers or the default behavior should be tried.
647
+ handleScrollToSelection?: (this: P, view: EditorView) => boolean
648
+
649
+ /// Determines whether an in-editor drag event should copy or move
650
+ /// the selection. When not given, the event's `altKey` property is
651
+ /// used on macOS, `ctrlKey` on other platforms.
652
+ dragCopies?: (event: DragEvent) => boolean
653
+
654
+ /// Can be used to override the way a selection is created when
655
+ /// reading a DOM selection between the given anchor and head.
656
+ createSelectionBetween?: (this: P, view: EditorView, anchor: ResolvedPos, head: ResolvedPos) => Selection | null
657
+
658
+ /// Check and optionally adjust a selection created from positions
659
+ /// read from the DOM. Can just return the selection it was given
660
+ /// when not making adjustments.
661
+ adjustSelectionFromDOM?: (this: P, view: EditorView, selection: Selection) => Selection
662
+
663
+ /// The [parser](#model.DOMParser) to use when reading editor changes
664
+ /// from the DOM. Defaults to calling
665
+ /// [`DOMParser.fromSchema`](#model.DOMParser^fromSchema) on the
666
+ /// editor's schema.
667
+ domParser?: DOMParser
668
+
669
+ /// Can be used to transform pasted HTML text, _before_ it is parsed,
670
+ /// for example to clean it up.
671
+ transformPastedHTML?: (this: P, html: string, view: EditorView) => string
672
+
673
+ /// The [parser](#model.DOMParser) to use when reading content from
674
+ /// the clipboard. When not given, the value of the
675
+ /// [`domParser`](#view.EditorProps.domParser) prop is used.
676
+ clipboardParser?: DOMParser
677
+
678
+ /// Transform pasted plain text. The `plain` flag will be true when
679
+ /// the text is pasted as plain text.
680
+ transformPastedText?: (this: P, text: string, plain: boolean, view: EditorView) => string
681
+
682
+ /// A function to parse text from the clipboard into a document
683
+ /// slice. Called after
684
+ /// [`transformPastedText`](#view.EditorProps.transformPastedText).
685
+ /// The default behavior is to split the text into lines, wrap them
686
+ /// in `<p>` tags, and call
687
+ /// [`clipboardParser`](#view.EditorProps.clipboardParser) on it.
688
+ /// The `plain` flag will be true when the text is pasted as plain text.
689
+ clipboardTextParser?: (this: P, text: string, $context: ResolvedPos, plain: boolean, view: EditorView) => Slice
690
+
691
+ /// Can be used to transform pasted or dragged-and-dropped content
692
+ /// before it is applied to the document. The `plain` flag will be
693
+ /// true when the text is pasted as plain text.
694
+ transformPasted?: (this: P, slice: Slice, view: EditorView, plain: boolean) => Slice
695
+
696
+ /// Can be used to transform copied or cut content before it is
697
+ /// serialized to the clipboard.
698
+ transformCopied?: (this: P, slice: Slice, view: EditorView) => Slice
699
+
700
+ /// Allows you to pass custom rendering and behavior logic for
701
+ /// nodes. Should map node names to constructor functions that
702
+ /// produce a [`NodeView`](#view.NodeView) object implementing the
703
+ /// node's display behavior. The third argument `getPos` is a
704
+ /// function that can be called to get the node's current position,
705
+ /// which can be useful when creating transactions to update it.
706
+ /// Note that if the node is not in the document, the position
707
+ /// returned by this function will be `undefined`.
708
+ ///
709
+ /// `decorations` is an array of node or inline decorations that are
710
+ /// active around the node. They are automatically drawn in the
711
+ /// normal way, and you will usually just want to ignore this, but
712
+ /// they can also be used as a way to provide context information to
713
+ /// the node view without adding it to the document itself.
714
+ ///
715
+ /// `innerDecorations` holds the decorations for the node's content.
716
+ /// You can safely ignore this if your view has no content or a
717
+ /// `contentDOM` property, since the editor will draw the decorations
718
+ /// on the content. But if you, for example, want to create a nested
719
+ /// editor with the content, it may make sense to provide it with the
720
+ /// inner decorations.
721
+ ///
722
+ /// (For backwards compatibility reasons, [mark
723
+ /// views](#view.EditorProps.markViews) can also be included in this
724
+ /// object.)
725
+ nodeViews?: {[node: string]: NodeViewConstructor}
726
+
727
+ /// Pass custom mark rendering functions. Note that these cannot
728
+ /// provide the kind of dynamic behavior that [node
729
+ /// views](#view.NodeView) can—they just provide custom rendering
730
+ /// logic. The third argument indicates whether the mark's content
731
+ /// is inline.
732
+ markViews?: {[mark: string]: MarkViewConstructor}
733
+
734
+ /// The DOM serializer to use when putting content onto the
735
+ /// clipboard. If not given, the result of
736
+ /// [`DOMSerializer.fromSchema`](#model.DOMSerializer^fromSchema)
737
+ /// will be used. This object will only have its
738
+ /// [`serializeFragment`](#model.DOMSerializer.serializeFragment)
739
+ /// method called, and you may provide an alternative object type
740
+ /// implementing a compatible method.
741
+ clipboardSerializer?: DOMSerializer
742
+
743
+ /// A function that will be called to get the text for the current
744
+ /// selection when copying text to the clipboard. By default, the
745
+ /// editor will use [`textBetween`](#model.Node.textBetween) on the
746
+ /// selected range.
747
+ clipboardTextSerializer?: (this: P, content: Slice, view: EditorView) => string
748
+
749
+ /// A set of [document decorations](#view.Decoration) to show in the
750
+ /// view.
751
+ decorations?: (this: P, state: EditorState) => DecorationSource | null | undefined
752
+
753
+ /// When this returns false, the content of the view is not directly
754
+ /// editable.
755
+ editable?: (this: P, state: EditorState) => boolean
756
+
757
+ /// Control the DOM attributes of the editable element. May be either
758
+ /// an object or a function going from an editor state to an object.
759
+ /// By default, the element will get a class `"ProseMirror"`, and
760
+ /// will have its `contentEditable` attribute determined by the
761
+ /// [`editable` prop](#view.EditorProps.editable). Additional classes
762
+ /// provided here will be added to the class. For other attributes,
763
+ /// the value provided first (as in
764
+ /// [`someProp`](#view.EditorView.someProp)) will be used.
765
+ attributes?: {[name: string]: string} | ((state: EditorState) => {[name: string]: string})
766
+
767
+ /// Determines the distance (in pixels) between the cursor and the
768
+ /// end of the visible viewport at which point, when scrolling the
769
+ /// cursor into view, scrolling takes place. Defaults to 0.
770
+ scrollThreshold?: number | {top: number, right: number, bottom: number, left: number}
771
+
772
+ /// Determines the extra space (in pixels) that is left above or
773
+ /// below the cursor when it is scrolled into view. Defaults to 5.
774
+ scrollMargin?: number | {top: number, right: number, bottom: number, left: number}
775
+ }
776
+
777
+ /// The props object given directly to the editor view supports some
778
+ /// fields that can't be used in plugins:
779
+ export interface DirectEditorProps extends EditorProps {
780
+ /// The current state of the editor.
781
+ state: EditorState
782
+
783
+ /// A set of plugins to use in the view, applying their [plugin
784
+ /// view](#state.PluginSpec.view) and
785
+ /// [props](#state.PluginSpec.props). Passing plugins with a state
786
+ /// component (a [state field](#state.PluginSpec.state) field or a
787
+ /// [transaction](#state.PluginSpec.filterTransaction) filter or
788
+ /// appender) will result in an error, since such plugins must be
789
+ /// present in the state to work.
790
+ plugins?: readonly Plugin[]
791
+
792
+ /// The callback over which to send transactions (state updates)
793
+ /// produced by the view. If you specify this, you probably want to
794
+ /// make sure this ends up calling the view's
795
+ /// [`updateState`](#view.EditorView.updateState) method with a new
796
+ /// state that has the transaction
797
+ /// [applied](#state.EditorState.apply). The callback will be bound to have
798
+ /// the view instance as its `this` binding.
799
+ dispatchTransaction?: (tr: Transaction) => void
800
+ }