@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,282 @@
1
+ import {Slice, Fragment, DOMParser, DOMSerializer, ResolvedPos, NodeType, Node} from "prosemirror-model"
2
+ import * as browser from "./browser"
3
+ import {EditorView} from "./index"
4
+ import {isElt} from "./dom"
5
+
6
+ export function serializeForClipboard(view: EditorView, slice: Slice) {
7
+ view.someProp("transformCopied", f => { slice = f(slice!, view) })
8
+
9
+ let context = [], {content, openStart, openEnd} = slice
10
+ while (openStart > 1 && openEnd > 1 && content.childCount == 1 && content.firstChild!.childCount == 1) {
11
+ openStart--
12
+ openEnd--
13
+ let node = content.firstChild!
14
+ context.push(node.type.name, node.attrs != node.type.defaultAttrs ? node.attrs : null)
15
+ content = node.content
16
+ }
17
+
18
+ let serializer = view.someProp("clipboardSerializer") || DOMSerializer.fromSchema(view.state.schema)
19
+ let doc = detachedDoc(), wrap = doc.createElement("div")
20
+ wrap.appendChild(serializer.serializeFragment(content, {document: doc}))
21
+
22
+ let firstChild = wrap.firstChild, needsWrap, wrappers = 0
23
+ while (firstChild && isElt(firstChild) && (needsWrap = wrapMap[firstChild.nodeName.toLowerCase()])) {
24
+ for (let i = needsWrap.length - 1; i >= 0; i--) {
25
+ let wrapper = doc.createElement(needsWrap[i])
26
+ while (wrap.firstChild) wrapper.appendChild(wrap.firstChild)
27
+ wrap.appendChild(wrapper)
28
+ wrappers++
29
+ }
30
+ firstChild = wrap.firstChild
31
+ }
32
+
33
+ if (firstChild && isElt(firstChild))
34
+ firstChild.setAttribute(
35
+ "data-pm-slice", `${openStart} ${openEnd}${wrappers ? ` -${wrappers}` : ""} ${JSON.stringify(context)}`)
36
+
37
+ let text = view.someProp("clipboardTextSerializer", f => f(slice, view)) ||
38
+ slice.content.textBetween(0, slice.content.size, "\n\n")
39
+
40
+ return {dom: wrap, text, slice}
41
+ }
42
+
43
+ // Read a slice of content from the clipboard (or drop data).
44
+ export function parseFromClipboard(view: EditorView, text: string, html: string | null, plainText: boolean, $context: ResolvedPos) {
45
+ let inCode = $context.parent.type.spec.code
46
+ let dom: HTMLElement | undefined, slice: Slice | undefined
47
+ if (!html && !text) return null
48
+ let asText = !!text && (plainText || inCode || !html)
49
+ if (asText) {
50
+ view.someProp("transformPastedText", f => { text = f(text, inCode || plainText, view) })
51
+ if (inCode) {
52
+ slice = new Slice(Fragment.from(view.state.schema.text(text.replace(/\r\n?/g, "\n"))), 0, 0)
53
+ view.someProp("transformPasted", f => { slice = f(slice!, view, true) })
54
+ return slice
55
+ }
56
+ let parsed = view.someProp("clipboardTextParser", f => f(text, $context, plainText, view))
57
+ if (parsed) {
58
+ slice = parsed
59
+ } else {
60
+ let marks = $context.marks()
61
+ let {schema} = view.state, serializer = DOMSerializer.fromSchema(schema)
62
+ dom = document.createElement("div")
63
+ text.split(/(?:\r\n?|\n)+/).forEach(block => {
64
+ let p = dom!.appendChild(document.createElement("p"))
65
+ if (block) p.appendChild(serializer.serializeNode(schema.text(block, marks)))
66
+ })
67
+ }
68
+ } else {
69
+ view.someProp("transformPastedHTML", f => { html = f(html!, view) })
70
+ dom = readHTML(html!)
71
+ if (browser.webkit) restoreReplacedSpaces(dom)
72
+ }
73
+
74
+ let contextNode = dom && dom.querySelector("[data-pm-slice]")
75
+ let sliceData = contextNode && /^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(contextNode.getAttribute("data-pm-slice") || "")
76
+ if (sliceData && sliceData[3]) for (let i = +sliceData[3]; i > 0; i--) {
77
+ let child = dom!.firstChild
78
+ while (child && !isElt(child)) child = child.nextSibling
79
+ if (!child) break
80
+ dom = child as HTMLElement
81
+ }
82
+
83
+ if (!slice) {
84
+ let parser = view.someProp("clipboardParser") || view.someProp("domParser") || DOMParser.fromSchema(view.state.schema)
85
+ slice = parser.parseSlice(dom!, {
86
+ preserveWhitespace: !!(asText || sliceData),
87
+ context: $context,
88
+ ruleFromNode(dom) {
89
+ if (dom.nodeName == "BR" && !dom.nextSibling &&
90
+ dom.parentNode && !inlineParents.test(dom.parentNode.nodeName)) return {ignore: true}
91
+ return null
92
+ }
93
+ })
94
+ }
95
+ if (sliceData) {
96
+ slice = addContext(closeSlice(slice, +sliceData[1], +sliceData[2]), sliceData[4])
97
+ } else { // HTML wasn't created by ProseMirror. Make sure top-level siblings are coherent
98
+ slice = Slice.maxOpen(normalizeSiblings(slice.content, $context), true)
99
+ if (slice.openStart || slice.openEnd) {
100
+ let openStart = 0, openEnd = 0
101
+ for (let node = slice.content.firstChild; openStart < slice.openStart && !node!.type.spec.isolating;
102
+ openStart++, node = node!.firstChild) {}
103
+ for (let node = slice.content.lastChild; openEnd < slice.openEnd && !node!.type.spec.isolating;
104
+ openEnd++, node = node!.lastChild) {}
105
+ slice = closeSlice(slice, openStart, openEnd)
106
+ }
107
+ }
108
+
109
+ view.someProp("transformPasted", f => { slice = f(slice!, view, plainText) })
110
+ return slice
111
+ }
112
+
113
+ const inlineParents = /^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i
114
+
115
+ // Takes a slice parsed with parseSlice, which means there hasn't been
116
+ // any content-expression checking done on the top nodes, tries to
117
+ // find a parent node in the current context that might fit the nodes,
118
+ // and if successful, rebuilds the slice so that it fits into that parent.
119
+ //
120
+ // This addresses the problem that Transform.replace expects a
121
+ // coherent slice, and will fail to place a set of siblings that don't
122
+ // fit anywhere in the schema.
123
+ function normalizeSiblings(fragment: Fragment, $context: ResolvedPos) {
124
+ if (fragment.childCount < 2) return fragment
125
+ for (let d = $context.depth; d >= 0; d--) {
126
+ let parent = $context.node(d)
127
+ let match = parent.contentMatchAt($context.index(d))
128
+ let lastWrap: readonly NodeType[] | undefined, result: Node[] | null = []
129
+ fragment.forEach(node => {
130
+ if (!result) return
131
+ let wrap = match.findWrapping(node.type), inLast
132
+ if (!wrap) return result = null
133
+ if (inLast = result.length && lastWrap!.length && addToSibling(wrap, lastWrap!, node, result[result.length - 1], 0)) {
134
+ result[result.length - 1] = inLast
135
+ } else {
136
+ if (result.length) result[result.length - 1] = closeRight(result[result.length - 1], lastWrap!.length)
137
+ let wrapped = withWrappers(node, wrap)
138
+ result.push(wrapped)
139
+ match = match.matchType(wrapped.type)!
140
+ lastWrap = wrap
141
+ }
142
+ })
143
+ if (result) return Fragment.from(result)
144
+ }
145
+ return fragment
146
+ }
147
+
148
+ function withWrappers(node: Node, wrap: readonly NodeType[], from = 0) {
149
+ for (let i = wrap.length - 1; i >= from; i--)
150
+ node = wrap[i].create(null, Fragment.from(node))
151
+ return node
152
+ }
153
+
154
+ // Used to group adjacent nodes wrapped in similar parents by
155
+ // normalizeSiblings into the same parent node
156
+ function addToSibling(wrap: readonly NodeType[], lastWrap: readonly NodeType[],
157
+ node: Node, sibling: Node, depth: number): Node | undefined {
158
+ if (depth < wrap.length && depth < lastWrap.length && wrap[depth] == lastWrap[depth]) {
159
+ let inner = addToSibling(wrap, lastWrap, node, sibling.lastChild!, depth + 1)
160
+ if (inner) return sibling.copy(sibling.content.replaceChild(sibling.childCount - 1, inner))
161
+ let match = sibling.contentMatchAt(sibling.childCount)
162
+ if (match.matchType(depth == wrap.length - 1 ? node.type : wrap[depth + 1]))
163
+ return sibling.copy(sibling.content.append(Fragment.from(withWrappers(node, wrap, depth + 1))))
164
+ }
165
+ }
166
+
167
+ function closeRight(node: Node, depth: number) {
168
+ if (depth == 0) return node
169
+ let fragment = node.content.replaceChild(node.childCount - 1, closeRight(node.lastChild!, depth - 1))
170
+ let fill = node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true)!
171
+ return node.copy(fragment.append(fill))
172
+ }
173
+
174
+ function closeRange(fragment: Fragment, side: number, from: number, to: number, depth: number, openEnd: number) {
175
+ let node = side < 0 ? fragment.firstChild! : fragment.lastChild!, inner = node.content
176
+ if (fragment.childCount > 1) openEnd = 0
177
+ if (depth < to - 1) inner = closeRange(inner, side, from, to, depth + 1, openEnd)
178
+ if (depth >= from)
179
+ inner = side < 0 ? node.contentMatchAt(0)!.fillBefore(inner, openEnd <= depth)!.append(inner)
180
+ : inner.append(node.contentMatchAt(node.childCount)!.fillBefore(Fragment.empty, true)!)
181
+ return fragment.replaceChild(side < 0 ? 0 : fragment.childCount - 1, node.copy(inner))
182
+ }
183
+
184
+ function closeSlice(slice: Slice, openStart: number, openEnd: number) {
185
+ if (openStart < slice.openStart)
186
+ slice = new Slice(closeRange(slice.content, -1, openStart, slice.openStart, 0, slice.openEnd), openStart, slice.openEnd)
187
+ if (openEnd < slice.openEnd)
188
+ slice = new Slice(closeRange(slice.content, 1, openEnd, slice.openEnd, 0, 0), slice.openStart, openEnd)
189
+ return slice
190
+ }
191
+
192
+ // Trick from jQuery -- some elements must be wrapped in other
193
+ // elements for innerHTML to work. I.e. if you do `div.innerHTML =
194
+ // "<td>..</td>"` the table cells are ignored.
195
+ const wrapMap: {[node: string]: string[]} = {
196
+ thead: ["table"],
197
+ tbody: ["table"],
198
+ tfoot: ["table"],
199
+ caption: ["table"],
200
+ colgroup: ["table"],
201
+ col: ["table", "colgroup"],
202
+ tr: ["table", "tbody"],
203
+ td: ["table", "tbody", "tr"],
204
+ th: ["table", "tbody", "tr"]
205
+ }
206
+
207
+ function detachedDoc() {
208
+ return document.implementation.createHTMLDocument("title")
209
+ }
210
+
211
+ let _policy: any = null
212
+
213
+ function maybeWrapTrusted(html: string): string {
214
+ let trustedTypes = (window as any).trustedTypes
215
+ if (!trustedTypes) return html
216
+ // With the require-trusted-types-for CSP, Chrome will block
217
+ // innerHTML, even on a detached document. This wraps the string in
218
+ // a way that makes the browser allow us to use its parser again.
219
+ if (!_policy) {
220
+ if (_policy = trustedTypes.defaultPolicy)
221
+ try { return _policy.createHTML(html) } catch {}
222
+ _policy = trustedTypes.createPolicy("ProseMirrorClipboard", {createHTML: (s: string) => s})
223
+ }
224
+ return _policy.createHTML(html)
225
+ }
226
+
227
+ function readHTML(html: string) {
228
+ let metas = /^(\s*<meta [^>]*>)*/.exec(html)
229
+ if (metas) html = html.slice(metas[0].length)
230
+ let doc = detachedDoc(), elt = doc.body
231
+ let firstTag = /<([a-z][^>\s]+)/i.exec(html), wrap
232
+ if (wrap = firstTag && wrapMap[firstTag[1].toLowerCase()])
233
+ html = wrap.map(n => "<" + n + ">").join("") + html + wrap.map(n => "</" + n + ">").reverse().join("")
234
+ elt.innerHTML = maybeWrapTrusted(html)
235
+ if (wrap) for (let i = 0; i < wrap.length; i++) elt = elt.querySelector(wrap[i]) || elt
236
+ // Inline styles defined in the pasted content, so that parse rules pick them up
237
+ for (let i = 0; i < doc.styleSheets.length; i++) {
238
+ let style = doc.styleSheets[i]
239
+ for (let j = 0; j < style.rules.length; j++) {
240
+ let rule = style.rules[j]
241
+ if (rule instanceof CSSStyleRule) {
242
+ let matches = elt.querySelectorAll(rule.selectorText)
243
+ for (let k = 0; k < matches.length; k++)
244
+ (matches[k] as HTMLElement).style.cssText += rule.style.cssText
245
+ }
246
+ }
247
+ }
248
+ return elt
249
+ }
250
+
251
+ // Webkit browsers do some hard-to-predict replacement of regular
252
+ // spaces with non-breaking spaces when putting content on the
253
+ // clipboard. This tries to convert such non-breaking spaces (which
254
+ // will be wrapped in a plain span on Chrome, a span with class
255
+ // Apple-converted-space on Safari) back to regular spaces.
256
+ function restoreReplacedSpaces(dom: HTMLElement) {
257
+ let nodes = dom.querySelectorAll(browser.chrome ? "span:not([class]):not([style])" : "span.Apple-converted-space")
258
+ for (let i = 0; i < nodes.length; i++) {
259
+ let node = nodes[i]
260
+ if (node.childNodes.length == 1 && node.textContent == "\u00a0" && node.parentNode)
261
+ node.parentNode.replaceChild(dom.ownerDocument.createTextNode(" "), node)
262
+ }
263
+ }
264
+
265
+ function addContext(slice: Slice, context: string) {
266
+ if (!slice.size) return slice
267
+ let schema = slice.content.firstChild!.type.schema, array
268
+ try { array = JSON.parse(context) }
269
+ catch(e) { return slice }
270
+ let {content, openStart, openEnd} = slice
271
+ for (let i = array.length - 2; i >= 0; i -= 2) {
272
+ let type = schema.nodes[array[i]]
273
+ if (!type || type.hasRequiredAttrs() || !type.createAndFill(null, content)) break
274
+ try {
275
+ content = Fragment.from(type.create(array[i + 1], content))
276
+ } catch(e) {
277
+ break
278
+ }
279
+ openStart++; openEnd++
280
+ }
281
+ return new Slice(content, openStart, openEnd)
282
+ }