-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
360 lines (296 loc) · 9.49 KB
/
index.js
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
import "@spectrum-web-components/theme/sp-theme.js";
import "@spectrum-web-components/theme/theme-light.js";
import "@spectrum-web-components/theme/scale-medium.js";
import "@spectrum-web-components/textfield/sp-textfield.js";
import "@spectrum-web-components/number-field/sp-number-field.js";
import "@spectrum-web-components/search/sp-search.js";
import "@spectrum-web-components/checkbox/sp-checkbox.js";
import "@spectrum-web-components/radio/sp-radio.js";
import "@spectrum-web-components/slider/sp-slider.js";
import "@spectrum-web-components/switch/sp-switch.js";
let nextDebugId = 0;
export class SubtreeWatcher {
constructor(root, outputEle) {
this._timerId = 0;
this._outputEle = outputEle;
this._buildSnapshot(root);
this._outputEle.innerHTML = this.getSubtreeString(this._entries[0]).join(
""
);
}
stop() {
if (this._timerId) {
clearInterval(this._timerId);
this._timerId = 0;
}
}
start() {
this.stop();
this._timerId = setInterval(this._handleUpdate, 1000);
}
_handleUpdate = () => {
this.update();
};
ensureDebugId(node) {
if (node._debugId === undefined) {
Object.defineProperty(node, "_debugId", { value: nextDebugId++ });
}
return node;
}
getNodeLabel(node, includeHandlers, includeDescendantCount) {
let label = node.nodeName.toLowerCase();
switch (label) {
case "#document-fragment":
if (!node.parentNode && node.host) {
label = "#shadow-root";
}
break;
default:
break;
}
if (node.id) {
label += "#" + node.id;
}
if (typeof node.className === "string") {
let classes = node.className.replace(/^ +| +$/g, "").replace(/ +/g, " ");
if (classes) {
label += "." + classes.split(/ +/).join(".");
}
}
if (node.getAttribute) {
let slotAttr = node.getAttribute("slot");
if (slotAttr) {
label += "[slot=" + slotAttr + "]";
}
}
if (includeHandlers && window.getEventListeners) {
let eventNames = Object.keys(window.getEventListeners(node));
if (eventNames && eventNames.length) {
label += " activeListeners(" + eventNames.join(", ") + ")";
}
}
return label;
}
getPathToNodeAsString(node, includeHandlers, includeDescendantCount) {
let path = [];
while (node) {
path.push(
this.getNodeLabel(node, includeHandlers, includeDescendantCount)
);
node = node.parentNode || node.host;
}
let indentStr = "";
path = path.reverse().map((label) => {
label = indentStr + label;
indentStr += "| ";
return label;
});
return path.join("\n");
}
getSubtreeNodeCount = function (root) {
let count = 0;
this.traverseSubtree(root, function (node, scopeData) {
++count;
});
return count;
};
traverseSubtree(node, preCallback, postCallback) {
let scopeData = {};
if (preCallback) {
preCallback(node, scopeData);
}
if (node.shadowRoot) {
this.traverseSubtree(node.shadowRoot, preCallback, postCallback);
}
let child = node.firstChild;
while (child) {
// Save next child just in case the current child is removed from subtree.
let nextChild = child.nextSibling;
this.traverseSubtree(child, preCallback, postCallback);
child = nextChild;
}
if (postCallback) {
postCallback(node, scopeData);
}
}
_getSnapshotPreCallback(stack) {
return (node, scopeData) => {
this.ensureDebugId(node);
let label = this.getNodeLabel(node, true, true);
let entry = {
id: node._debugId,
label,
ref: new WeakRef(node),
path: this.getPathToNodeAsString(node),
parent: !node.parentNode
? undefined
: this._entryDict[node.parentNode._debugId],
children: [],
};
this._entries.push(entry);
this._entryDict[entry.id] = entry;
if (stack.length) {
stack[stack.length - 1].push(entry);
}
stack.push(entry.children);
};
}
_getSnapshotPostCallback(stack) {
return function () {
stack.pop();
};
}
_buildSnapshot(root) {
this._entries = [];
this._entryDict = {};
let stack = [];
this.traverseSubtree(
root,
this._getSnapshotPreCallback(stack),
this._getSnapshotPostCallback(stack)
);
}
getSubtreeString(entry, output = [], indent = "") {
let isActive = !!entry.ref.deref();
let className = isActive ? "active" : "garbage-collected";
let status = isActive ? "" : "[GC] ";
output.push(
`<div id="node-${entry.id}" class="entry ${className}">${indent}${status}${entry.label}</div>`
);
let children = entry.children;
for (let i = 0; i < children.length; i++) {
this.getSubtreeString(children[i], output, (indent || "") + "|--- ");
}
return output;
}
isShadowRoot(node) {
return !!node && node.nodeName.toLowerCase() === "#document-fragment";
}
unparent() {
let entries = this._entries;
for (let i = 0; i < entries.length; i++) {
let node = entries[i].ref.deref();
if (node && !this.isShadowRoot(node)) {
if (node.parentNode) {
node.parentNode.removeChild(node);
} else if (node.host && node.host.shadowRoot) {
node.host.shadowRoot.removeChild(node);
}
}
}
}
update() {
let entries = this._entries;
let activeCount = entries.length;
for (let i = 0; i < entries.length; i++) {
let entry = entries[i];
let isActive = !!entry.ref.deref();
if (!isActive) {
--activeCount;
let entryEle = document.getElementById(`node-${entry.id}`);
if (entryEle && entryEle.classList.contains("active")) {
entryEle.classList.remove("active");
entryEle.classList.add("garbage-collected");
}
}
}
if (activeCount <= 0) {
this.stop();
this._outputEle.classList.add("garbage-collected");
}
}
}
let nextSampleId = 0;
let sampleTemplate = document.createElement("template");
sampleTemplate.innerHTML = `
<div class="controls">
<button type="button" class="remove-btn">Remove</button>
<button type="button" class="unparent-btn">Unparent Children</button>
<button type="button" class="show-results-btn">Show results</button>
<span class="results"></span>
</div>
<div class="subtree-view"></div>
`;
function getRemoveHandler(id, watcher) {
return function (e) {
let sampleEle = document.getElementById(id);
// Remove the sample subtree.
if (sampleEle) {
sampleEle.remove();
// Disable the button so the user
// can't press it again!
this.disabled = true;
// Start the watcher so we can watch
// garbage-collection realtime.
watcher.start();
}
};
}
function getUnparentHandler(watcher) {
return function () {
// Disable the button so the user
// can't press it again!
this.disabled = true;
// Unparent the nodes in the sample subtree.
watcher.unparent();
// Start the watcher so we can watch
// garbage-collection realtime.
watcher.start();
};
}
function getResultsHandler(subtreeView, controls) {
return function () {
this.disabled = true;
const active = subtreeView.querySelectorAll(".entry.active")?.length ?? 0;
const collected =
subtreeView.querySelectorAll(".entry.garbage-collected")?.length ?? 0;
const resultsEl = controls.querySelector(".results");
resultsEl.textContent = `Active: ${active} | Collected: ${collected} | Total: ${
active + collected
}`;
};
}
function updatePatchHeading() {
const route = window.location.pathname.slice(1);
const inputTagName = `sp-${route}`;
const inputEl = document.querySelector(inputTagName);
const patchedInput = inputEl?.shadowRoot?.querySelector(
"input[data-test-id='patched']"
);
const isPatchedVersion = Boolean(patchedInput);
const heading = document.querySelector("h1");
heading.textContent = `${heading.textContent} ${
isPatchedVersion ? "(Patched)" : "(without patch)"
}`;
}
// For each sample on the page, inject a subtree-view controller.
// We need to wait for some time after document load to give any samples
// that use LitHTML/LitElement a chance to render.
self.addEventListener("load", function () {
setTimeout(function () {
updatePatchHeading();
document.querySelectorAll(".sample").forEach(function (sample) {
let controllerContainer = document.createElement("div");
controllerContainer.className = "subtree-view-controller";
controllerContainer.appendChild(sampleTemplate.content.cloneNode(true));
sample.insertAdjacentElement("afterend", controllerContainer);
let subtreeView = controllerContainer.querySelector(".subtree-view");
let controls = controllerContainer.querySelector(".controls");
let watcher = new SubtreeWatcher(sample, subtreeView);
// Make sure the sample has an id on it!
if (!sample.id) {
sample.setAttribute("id", `sample-id-${nextSampleId++}`);
}
controllerContainer
.querySelector(".remove-btn")
.addEventListener("click", getRemoveHandler(sample.id, watcher));
controllerContainer
.querySelector(".unparent-btn")
.addEventListener("click", getUnparentHandler(watcher));
controllerContainer
.querySelector(".show-results-btn")
.addEventListener("click", getResultsHandler(subtreeView, controls));
sample._watcher = watcher;
});
}, 10);
});