-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathutil.ts
More file actions
415 lines (351 loc) · 11.4 KB
/
Copy pathutil.ts
File metadata and controls
415 lines (351 loc) · 11.4 KB
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
import { Diff, DIFF_EQUAL, diff_match_patch } from 'diff-match-patch'
export type NodePredicate = (node: Node) => boolean
export type IndefiniteNodePredicate = (node: Node) => boolean | undefined
export type DiffTextType = (oldText: string, newText: string) => Diff[]
export function isElement(node: Node): node is HTMLElement {
return node.nodeType === node.ELEMENT_NODE
}
export function isText(node: Node): node is Text {
return node.nodeType === node.TEXT_NODE
}
export function isDocument(node: Node): node is Document {
return node.nodeType === node.DOCUMENT_NODE
}
export function isDocumentFragment(node: Node): node is DocumentFragment {
return node.nodeType === node.DOCUMENT_FRAGMENT_NODE
}
export function isComment(node: Node): node is Comment {
return node.nodeType === node.COMMENT_NODE
}
export type Comparator<T> = (item1: T, item2: T) => boolean
export function strictEqual<T>(item1: T, item2: T): boolean {
return item1 === item2
}
export function areArraysEqual<T>(
array1: T[],
array2: T[],
comparator: Comparator<T> = strictEqual,
): boolean {
if (array1.length !== array2.length) {
return false
}
for (let i = 0, l = array1.length; i < l; ++i) {
if (!comparator(array1[i], array2[i])) {
return false
}
}
return true
}
function getAttributeNames(element: Element): string[] {
if (element.getAttributeNames) {
return element.getAttributeNames()
} else {
const attributes = element.attributes
const length = attributes.length
const attributeNames = new Array(length)
for (let i = 0; i < length; i++) {
attributeNames[i] = attributes[i].name
}
return attributeNames
}
}
function stripNewlines(nodes: NodeList): Node[] {
return Array.from(nodes).filter((node: Node) => {
return (
node.nodeName !== '#text' ||
(node.textContent && node.textContent.trim() !== '')
)
})
}
/**
* Compares DOM nodes for equality.
* @param node1 The first node to compare.
* @param node2 The second node to compare.
* @param deep If true, the child nodes are compared recursively too.
* @returns `true`, if the 2 nodes are equal, otherwise `false`.
*/
export function areNodesEqual(
node1: Node,
node2: Node,
deep: boolean = false,
ignoreAttributes = false,
): boolean {
if (node1 === node2) {
return true
}
if (
node1.nodeType !== node2.nodeType ||
node1.nodeName !== node2.nodeName
) {
return false
}
if (isText(node1) || isComment(node1)) {
if (node1.data !== (node2 as typeof node1).data) {
return false
}
} else if (isElement(node1) && !ignoreAttributes) {
const attributeNames1 = getAttributeNames(node1).sort()
const attributeNames2 = getAttributeNames(node2 as typeof node1).sort()
if (!areArraysEqual(attributeNames1, attributeNames2)) {
return false
}
for (let i = 0, l = attributeNames1.length; i < l; ++i) {
const name = attributeNames1[i]
const value1 = node1.getAttribute(name)
const value2 = (node2 as typeof node1).getAttribute(name)
if (value1 !== value2) {
return false
}
}
}
if (deep) {
const childNodes1 = node1.childNodes
const childNodes2 = node2.childNodes
if (childNodes1.length !== childNodes2.length) {
return false
}
for (let i = 0, l = childNodes1.length; i < l; ++i) {
if (!areNodesEqual(childNodes1[i], childNodes2[i], deep)) {
return false
}
}
}
return true
}
/**
* Gets a list of `node`'s ancestor nodes up until and including `rootNode`.
* @param node Node whose ancestors to get.
* @param rootNode The root node.
*/
export function getAncestors(node: Node, rootNode: Node | null = null): Node[] {
if (!node || node === rootNode) {
return []
}
const ancestors = []
let currentNode: Node | null = node.parentNode
while (currentNode) {
ancestors.push(currentNode)
if (currentNode === rootNode) {
break
}
currentNode = currentNode.parentNode
}
return ancestors
}
export function never(
message: string = 'visual-dom-diff: Should never happen',
): never {
throw new Error(message)
}
// Source: https://stackoverflow.com/a/7616484/706807 (simplified)
export function hashCode(str: string): number {
let hash = 0
for (let i = 0; i < str.length; i++) {
// tslint:disable-next-line:no-bitwise
hash = ((hash << 5) - hash + str.charCodeAt(i)) | 0
}
return hash
}
/**
* Returns a single character which should replace the given node name
* when serializing a non-text node.
*/
export function charForNodeName(nodeName: string): string {
return String.fromCharCode(
0xe000 + (hashCode(nodeName) % (0xf900 - 0xe000)),
)
}
/**
* Moves trailing HTML tag markers in the DIFF_INSERT and DIFF_DELETE diff items to the front,
* if possible, in order to improve quality of the DOM diff.
*/
export function cleanUpNodeMarkers(diff: Diff[]): void {
for (let i = 0; i < diff.length - 2; ) {
const diff0 = diff[i]
const diff1 = diff[i + 1]
const diff2 = diff[i + 2]
if (
diff0[0] !== DIFF_EQUAL ||
diff1[0] === DIFF_EQUAL ||
diff2[0] !== DIFF_EQUAL
) {
i++
continue
}
const string0 = diff0[1]
const string1 = diff1[1]
const string2 = diff2[1]
const lastChar0 = string0[string0.length - 1]
const lastChar1 = string1[string1.length - 1]
if (
lastChar0 !== lastChar1 ||
lastChar0 < '\uE000' ||
lastChar0 >= '\uF900'
) {
i++
continue
}
diff0[1] = string0.substring(0, string0.length - 1)
diff1[1] = lastChar0 + string1.substring(0, string1.length - 1)
diff2[1] = lastChar0 + string2
if (diff0[1].length === 0) {
diff.splice(i, 1)
}
}
}
const dmp = new diff_match_patch()
/**
* Diffs the 2 strings and cleans up the result before returning it.
*/
export function diffText(oldText: string, newText: string): Diff[] {
const diff = dmp.diff_main(oldText, newText)
const result: Diff[] = []
const temp: Diff[] = []
cleanUpNodeMarkers(diff)
// Execute `dmp.diff_cleanupSemantic` excluding equal node markers.
for (let i = 0, l = diff.length; i < l; ++i) {
const item = diff[i]
if (item[0] === DIFF_EQUAL) {
const text = item[1]
const totalLength = text.length
const prefixLength = /^[^\uE000-\uF8FF]*/.exec(text)![0].length
if (prefixLength < totalLength) {
const suffixLength = /[^\uE000-\uF8FF]*$/.exec(text)![0].length
if (prefixLength > 0) {
temp.push([DIFF_EQUAL, text.substring(0, prefixLength)])
}
dmp.diff_cleanupSemantic(temp)
pushAll(result, temp)
temp.length = 0
result.push([
DIFF_EQUAL,
text.substring(prefixLength, totalLength - suffixLength),
])
if (suffixLength > 0) {
temp.push([
DIFF_EQUAL,
text.substring(totalLength - suffixLength),
])
}
} else {
temp.push(item)
}
} else {
temp.push(item)
}
}
dmp.diff_cleanupSemantic(temp)
pushAll(result, temp)
temp.length = 0
dmp.diff_cleanupMerge(result)
cleanUpNodeMarkers(result)
return result
}
function pushAll<T>(array: T[], items: T[]): void {
let destination = array.length
let source = 0
const length = items.length
while (source < length) {
array[destination++] = items[source++]
}
}
export function markUpNode(
node: Node,
elementName: string,
className: string,
): void {
const document = node.ownerDocument!
const parentNode = node.parentNode!
const previousSibling = node.previousSibling
if (isElement(node)) {
node.classList.add(className)
} else if (
previousSibling &&
previousSibling.nodeName === elementName &&
(previousSibling as Element).classList.contains(className)
) {
previousSibling.appendChild(node)
} else {
const wrapper = document.createElement(elementName)
wrapper.classList.add(className)
parentNode.insertBefore(wrapper, node)
wrapper.appendChild(node)
}
}
export function isTableValid(table: Node, verifyColumns: boolean): boolean {
let columnCount: number | undefined
return validateTable(table)
function validateTable({ childNodes }: Node): boolean {
const filteredChildNodes = stripNewlines(childNodes)
const l = filteredChildNodes.length
let i = 0
if (i < l && filteredChildNodes[i].nodeName === 'CAPTION') {
i++
}
if (i < l && filteredChildNodes[i].nodeName === 'THEAD') {
if (!validateRowGroup(filteredChildNodes[i])) {
return false
}
i++
}
if (i < l && filteredChildNodes[i].nodeName === 'TBODY') {
if (!validateRowGroup(filteredChildNodes[i])) {
return false
}
i++
} else {
return false
}
if (i < l && filteredChildNodes[i].nodeName === 'TFOOT') {
if (!validateRowGroup(filteredChildNodes[i])) {
return false
}
i++
}
return i === l
}
function validateRowGroup({ childNodes, nodeName }: Node): boolean {
const filteredChildNodes = stripNewlines(childNodes)
if (nodeName === 'TBODY' && filteredChildNodes.length === 0) {
return false
}
for (let i = 0, l = filteredChildNodes.length; i < l; ++i) {
if (!validateRow(filteredChildNodes[i])) {
return false
}
}
return true
}
function validateRow({ childNodes, nodeName }: Node): boolean {
const filteredChildNodes = stripNewlines(childNodes)
if (nodeName !== 'TR' || filteredChildNodes.length === 0) {
return false
}
if (verifyColumns) {
if (columnCount === undefined) {
columnCount = filteredChildNodes.length
} else if (columnCount !== filteredChildNodes.length) {
return false
}
}
for (let i = 0, l = filteredChildNodes.length; i < l; ++i) {
if (!validateCell(filteredChildNodes[i])) {
return false
}
}
return true
}
function validateCell(node: Node): boolean {
const { nodeName } = node
if (nodeName !== 'TD' && nodeName !== 'TH') {
return false
}
const cell = node as Element
const colspan = cell.getAttribute('colspan')
const rowspan = cell.getAttribute('rowspan')
return (
(colspan === null || colspan === '1') &&
(rowspan === null || rowspan === '1')
)
}
}