-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathediting-history.html
569 lines (482 loc) · 18 KB
/
editing-history.html
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
<html>
<head>
<style>
body {
margin: 8px;
font-family: -apple-system;
}
#overlay {
width: 300px;
height: calc(100% - 32px);
position: fixed;
right: 16px;
top: 16px;
background-color: rgba(255, 255, 255, 0.75);
transition: 0.25s ease-in-out;
}
#updateInfoPanel {
height: calc(90% - 100px);
overflow: scroll;
white-space: nowrap;
padding: 10px;
}
#controls {
height: 10%;
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
}
#controls-wrapper {
margin: 0 auto;
}
.control-wrapper {
margin-top: 10px;
}
#controls {
margin-top: 20px;
}
summary:focus {
outline: none;
}
details {
padding: 8px 0;
}
#updateMarker {
width: 100%;
margin: 20px 0;
color: #34AADC;
padding-left: 25px;
}
.eh-node {
margin: 0 2px;
padding: 0 4px;
background-color: rgba(59, 131, 238, 0.25);
border-radius: 4px;
cursor: default;
}
.eh-node:hover {
background-color: rgba(59, 131, 238, 0.5);
}
.node-highlight {
position: absolute;
background-color: rgba(59, 131, 238, 0.05);
border: 1px solid rgb(59, 131, 238);
border-radius: 2px;
z-index: -1;
}
li {
line-height: 1.5;
}
summary {
margin-top: 0;
}
#dropzone {
margin: 100px;
padding: 50px;
width: calc(100% - 300px);
height: calc(100% - 300px);
border: 15px #E8E8E8 dashed;
display: flex;
align-items: center;
text-align: center;
cursor: pointer;
}
a {
text-decoration: none;
color: #007AFF;
cursor: pointer;
}
#upload {
opacity: 0;
}
#dropMessage {
font-size: 50px;
color: #E8E8E8;
margin: 0 auto;
pointer-events: none;
}
</style>
<script src="EditingHistoryUtil.js"></script>
<script>
class XPathGenerator {
constructor() {
this._cache = new Map();
}
pathForDOMNode(node) {
if (node.nodeType == Node.DOCUMENT_NODE)
return "/";
return this._path(node);
}
_path(node) {
if (node.nodeType == Node.DOCUMENT_NODE)
return "";
if (!node.parentNode)
return null;
let cachedResult = this._cache.get(node);
if (cachedResult)
return cachedResult;
if (node.nodeType == Node.TEXT_NODE) {
let indexOfNode = 0;
for (let child of node.parentNode.childNodes) {
if (child.nodeType != Node.TEXT_NODE)
continue;
indexOfNode++;
if (child == node)
break;
}
let parentPath = this._path(node.parentNode);
if (parentPath != null)
return this._cacheResult(node, `${parentPath}/text()[${indexOfNode}]`);
}
if (node.nodeType == Node.ELEMENT_NODE) {
let indexOfNode = 0;
for (let child of node.parentNode.childNodes) {
if (child.tagName !== node.tagName)
continue;
indexOfNode++;
if (child == node)
break;
}
let parentPath = this._path(node.parentNode);
if (parentPath != null)
return this._cacheResult(node, `${parentPath}/${node.tagName.toLowerCase()}[${indexOfNode}]`);
}
return null;
}
_cacheResult(node, result) {
this._cache.set(node, result);
return result;
}
}
class DOMUpdateHistoryContext {
constructor(nodeMap, updates) {
this._nodeMap = nodeMap;
this._updates = updates;
this._currentUpdateIndex = updates.length;
}
currentIndex() {
return this._currentUpdateIndex;
}
updates() {
return this._updates;
}
updateAt(index) {
if (index < 0 || index >= this._updates.length)
return null;
return this._updates[index];
}
selectionStateAt(index) {
let beforeUpdate = this.updateAt(index - 1);
let afterUpdate = this.updateAt(index);
if (beforeUpdate instanceof EditingHistory.SelectionUpdate)
return beforeUpdate.state;
if (afterUpdate instanceof EditingHistory.SelectionUpdate)
return afterUpdate.state;
return null;
}
applyCurrentSelectionState(selection) {
let selectionState = this.selectionStateAt(this._currentUpdateIndex);
if (selectionState && selection)
selectionState.applyToSelection(selection);
else
selection.removeAllRanges();
}
next() {
if (this._currentUpdateIndex >= this._updates.length)
return;
this._updates[this._currentUpdateIndex].apply();
this._currentUpdateIndex++;
}
previous() {
if (this._currentUpdateIndex <= 0)
return;
this._updates[this._currentUpdateIndex - 1].unapply();
this._currentUpdateIndex--;
}
jumpTo(index) {
index = Math.max(Math.min(index, this._updates.length), 0);
while(this._currentUpdateIndex != index) {
if (this._currentUpdateIndex < index)
this.next();
else
this.previous();
}
}
}
/**
* This generates a template for a new layout test using the current state of the DOM. Note that the DOM resulting from
* this generated HTML is not guaranteed to be identical to the state of the DOM when generating the template, since
* there is no one-to-one mapping between innerHTML/outerHTML and the structure of the DOM. This means the test template
* may need to be tweaked after generation, but this is also expected if the content contains sensitive content, or is
* too complex and should be reduced anyways.
*/
function createLayoutTestTemplateHTMLFromCurrentDOMState() {
let overlayElement = document.body.removeChild(overlay);
let clonedBody = document.body.cloneNode();
clonedBody.innerHTML = document.body.innerHTML;
clonedBody.setAttribute("onload", "runTest()");
let shouldSetSelection = !!getSelection().rangeCount;
let setSelectionCode = "";
if (shouldSetSelection) {
let selectionRange = getSelection().getRangeAt(0);
let xPathGenerator = new XPathGenerator();
setSelectionCode = `function getNodeAtDOMPath(path)
{
return document.evaluate(path, document, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).singleNodeValue;
}
let startContainer = getNodeAtDOMPath("${xPathGenerator.pathForDOMNode(selectionRange.startContainer)}");
let endContainer = getNodeAtDOMPath("${xPathGenerator.pathForDOMNode(selectionRange.endContainer)}");
if (startContainer && endContainer) {
let range = document.createRange();
range.setStart(startContainer, ${selectionRange.startOffset});
range.setEnd(endContainer, ${selectionRange.endOffset});
let selection = getSelection();
selection.removeAllRanges();
selection.addRange(range);
}\n`;
}
document.body.appendChild(overlayElement);
// FIXME: The parser seems to have trouble with the closing script tag here when enclosed in a string template.
const scriptTagName = "script";
return `<!DOCTYPE html>
<meta charset="utf-8"/>
<html>
<${scriptTagName}>
function runTest()
{
${setSelectionCode}
if (!window.testRunner) {
/* FIXME: Describe how to manually run this layout test */
return;
}
testRunner.dumpAsText();
/* FIXME: Perform test-specific actions here */
}
</${scriptTagName}>`.replace(/\n /g, "\n") + `\n\n${clonedBody.outerHTML}\n</html>\n`;
}
window.onload = () => {
function setupEditingHistory(jsonData, withControls=true) {
let parsedResult = JSON.parse(jsonData);
let globalNodeMap = EditingHistory.GlobalNodeMap.fromObject(parsedResult.globalNodeMap);
let updates = parsedResult.updates.map(updateInfo => EditingHistory.DOMUpdate.ofType(updateInfo.type).fromObject(updateInfo, globalNodeMap));
EditingHistory.context = new DOMUpdateHistoryContext(globalNodeMap, updates);
function detailsElementAtIndex(index) {
return document.querySelector(`#updateInfo-${index}`);
}
function allDetailsAreOpen() {
for (let details of document.querySelectorAll(".updateInfo")) {
if (!details.open)
return false;
}
return true;
}
function updateOverlay(andScrollMarker=true) {
let currentIndex = EditingHistory.context.currentIndex();
let numberOfUpdates = EditingHistory.context.updates().length;
progressLabel.textContent = `${currentIndex}/${numberOfUpdates}`;
previousStep.style.opacity = currentIndex <= 0 ? 0.1 : 1;
nextStep.style.opacity = currentIndex >= numberOfUpdates ? 0.1 : 1;
if (andScrollMarker) {
updateMarker.remove();
if (0 <= currentIndex && currentIndex <= numberOfUpdates) {
let currentUpdateDetails = detailsElementAtIndex(currentIndex);
updateInfoPanel.insertBefore(updateMarker, currentUpdateDetails);
if (updateMarker.offsetTop < updateInfoPanel.scrollTop)
updateInfoPanel.scrollTop = updateMarker.offsetTop;
if (updateInfoPanel.scrollTop + updateInfoPanel.clientHeight < updateMarker.offsetTop)
updateInfoPanel.scrollTop = updateMarker.offsetTop - updateInfoPanel.clientHeight + updateMarker.clientHeight;
}
}
if (allDetailsAreOpen())
toggleExpand.textContent = "Collapse updates";
else
toggleExpand.textContent = "Expand updates";
}
function openAllDetailsUnderElement(element) {
for (let child of Array.from(element.children)) {
if (child.tagName === "DETAILS")
child.open = true;
openAllDetailsUnderElement(child);
}
}
upload.remove();
dropzone.remove();
for (let node of globalNodeMap.nodes()) {
if (node.tagName === "BODY") {
document.body = node;
break;
}
}
if (!withControls)
return;
let overlay = document.createElement("div");
overlay.id = "overlay";
overlay.innerHTML =
`<div id="information" contenteditable="false">
<div id="updateInfoPanel"></div>
</div>
<div id="controls" contenteditable="false">
<div id="progressLabel">-/-</div>
<div>
<span><a id="previousStep"><</a></span> <span><a id="nextStep">></a></span>
</div>
<div class="control-wrapper">
<a id="toggleExpand">Expand all</a>
</div>
<div class="control-wrapper">
<a download="test-template.html" href="" id="newLayoutTest">Convert to layout test</a>
</div>
</div>`;
document.body.appendChild(overlay);
updates.forEach((update, index) => {
let detailsElement = update.detailsElement();
let summary = detailsElement.children[0];
let indexElement = document.createElement("span");
indexElement.classList.add("eh-index");
indexElement.innerHTML = `[<a href=#>${index}</a>] `;
indexElement.children[0].addEventListener("click", () => {
EditingHistory.context.jumpTo(index + 1);
EditingHistory.context.applyCurrentSelectionState(getSelection());
detailsElement.open = true;
updateOverlay();
});
summary.insertBefore(indexElement, summary.childNodes[0]);
detailsElement.id = `updateInfo-${index}`;
detailsElement.classList.add("updateInfo");
detailsElement.addEventListener("click", (event) => {
EditingHistory.context.applyCurrentSelectionState(getSelection());
if (event.target !== summary)
return;
if (event.altKey && !detailsElement.open)
openAllDetailsUnderElement(detailsElement);
detailsElement.open = !detailsElement.open;
updateOverlay(false);
event.preventDefault();
});
updateInfoPanel.append(detailsElement);
});
let updateMarker = document.createElement("div");
updateMarker.textContent = ">>> Current state <<<";
updateMarker.id = "updateMarker";
updateInfoPanel.append(updateMarker);
nextStep.addEventListener("click", () => {
EditingHistory.context.next();
EditingHistory.context.applyCurrentSelectionState(getSelection());
updateOverlay();
});
previousStep.addEventListener("click", () => {
EditingHistory.context.previous();
EditingHistory.context.applyCurrentSelectionState(getSelection());
updateOverlay();
});
newLayoutTest.addEventListener("click", () => {
EditingHistory.context.applyCurrentSelectionState(getSelection());
newLayoutTest.href = `data:text/html,${encodeURI(createLayoutTestTemplateHTMLFromCurrentDOMState())}`;
});
document.addEventListener("keydown", event => {
if (event.key === "ArrowRight" || event.key === "ArrowDown") {
removeAllHighlights();
EditingHistory.context.next();
EditingHistory.context.applyCurrentSelectionState(getSelection());
event.preventDefault();
updateOverlay();
} else if (event.key === "ArrowLeft" || event.key === "ArrowUp") {
removeAllHighlights();
EditingHistory.context.previous();
EditingHistory.context.applyCurrentSelectionState(getSelection());
event.preventDefault();
updateOverlay();
}
});
toggleExpand.addEventListener("click", () => {
if (allDetailsAreOpen())
document.querySelectorAll(".updateInfo").forEach(details => details.open = false);
else
document.querySelectorAll(".updateInfo").forEach(details => details.open = true);
updateOverlay();
});
["selectstart", "dragenter", "dragover", "drop", "beforeinput"].forEach((type) => {
document.addEventListener(type, event => event.preventDefault());
});
document.querySelectorAll(".eh-node").forEach((node) => {
let guid = parseInt(node.getAttribute("eh-guid"));
if (isNaN(guid))
return;
let targetNode = globalNodeMap.nodeForGUID(guid);
node.addEventListener("click", () => console.log(targetNode));
node.addEventListener("mouseenter", () => showHighlightOverNode(targetNode));
node.addEventListener("mouseleave", removeAllHighlights);
});
updateOverlay();
EditingHistory.context.applyCurrentSelectionState(getSelection());
// Allow the editing caret to show up.
document.body.contentEditable = true;
}
function showHighlightOverNode(node) {
if (!document.body.contains(node))
return;
if (node.nodeType === Node.ELEMENT_NODE) {
showHighlightOverBoundingRect(node.getBoundingClientRect());
return;
}
if (node.nodeType === Node.TEXT_NODE) {
let range = document.createRange();
range.selectNodeContents(node);
showHighlightOverBoundingRect(range.getBoundingClientRect());
}
}
function showHighlightOverBoundingRect(bounds) {
let highlight = document.createElement("div");
highlight.classList.add("node-highlight");
highlight.style.left = bounds.left - 2;
highlight.style.top = bounds.top - 2;
highlight.style.width = bounds.width + 3;
highlight.style.height = bounds.height + 3;
document.body.appendChild(highlight);
}
function removeAllHighlights() {
document.querySelectorAll(".node-highlight").forEach(highlight => highlight.remove());
}
dropzone.addEventListener("mouseenter", emphasizeDrop);
dropzone.addEventListener("mouseleave", unemphasizeDrop);
dropzone.addEventListener("dragenter", emphasizeDrop);
dropzone.addEventListener("dragleave", unemphasizeDrop);
dropzone.addEventListener("dragover", event => event.preventDefault());
dropzone.addEventListener("click", () => upload.click());
dropzone.addEventListener("drop", dropEvent => {
dropEvent.preventDefault();
fileSelected(dropEvent.dataTransfer.files);
});
upload.files = null;
EditingHistory.setupEditingHistory = setupEditingHistory;
};
function emphasizeDrop(event) {
dropzone.style.border = "15px #D8D8D8 dashed";
dropMessage.style.color = "#D8D8D8";
event.preventDefault();
}
function unemphasizeDrop(event) {
dropzone.style.border = "15px #E8E8E8 dashed";
dropMessage.style.color = "#E8E8E8";
event.preventDefault();
}
function fileSelected(files) {
dropzone.removeEventListener("mouseenter", emphasizeDrop);
dropzone.removeEventListener("mouseleave", unemphasizeDrop);
dropzone.removeEventListener("dragenter", emphasizeDrop);
dropzone.removeEventListener("dragleave", unemphasizeDrop);
console.log(`Selected ${files.length} file(s).`);
let reader = new FileReader();
reader.onload = event => EditingHistory.setupEditingHistory(event.target.result);
reader.readAsText(files[0]);
}
</script>
</head>
<body>
<div id="dropzone">
<div id="dropMessage">Drop an editing record here</div>
</div>
<input id="upload" onchange=fileSelected(files) type="file"></input>
</body>
</html>