@playcanvas/inspector 0.4.0 → 0.6.0

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,837 @@
1
+ import { formatBytes } from './model.js';
2
+ import { setTip } from './tooltip.js';
3
+
4
+ /**
5
+ * One thing a snapshot measured, such as a buffer or an asset's file.
6
+ *
7
+ * @typedef {object} SnapshotItem
8
+ * @property {string} key - Who the item is, unique within the snapshot and kept from one snapshot
9
+ * of a tab to the next, such as the id of a buffer, so that a comparison pairs it with itself.
10
+ * @property {string[]} group - The groups the item is drawn in, outermost first.
11
+ * @property {string} name - Its name.
12
+ * @property {number} size - Its size, in bytes.
13
+ * @property {string} [info] - A line about it, shown while it is hovered.
14
+ * @property {WeakRef<object>} [target] - What it measured, to show in the tab that lists it.
15
+ * Held weakly, so a snapshot keeps nothing of the app alive.
16
+ * @ignore
17
+ */
18
+
19
+ /**
20
+ * How a treemap's boxes link to the tabs listing what they measured.
21
+ *
22
+ * @typedef {object} TreemapLinks
23
+ * @property {(target: object) => string|null} label - The name of the tab listing an object, or
24
+ * null when none does.
25
+ * @property {(target: object) => boolean} open - Shows an object in the tab listing it, and says
26
+ * whether it was found there.
27
+ * @ignore
28
+ */
29
+
30
+ /**
31
+ * A snapshot as the treemap draws it.
32
+ *
33
+ * @typedef {object} TreemapSnapshot
34
+ * @property {number} number - Its number among the snapshots of its tab.
35
+ * @property {number} time - When it was captured, in milliseconds since the epoch.
36
+ * @property {number} total - The sum of the sizes of its items.
37
+ * @property {SnapshotItem[]} items - What it measured.
38
+ * @property {string} note - What it leaves out, or an empty string.
39
+ * @ignore
40
+ */
41
+
42
+ /**
43
+ * What a treemap tab shows: one snapshot, or two compared.
44
+ *
45
+ * @typedef {object} TreemapData
46
+ * @property {string} tab - The name of the tab the snapshots were captured on, such as 'Memory'.
47
+ * @property {string} measure - What the sizes are, in a few words.
48
+ * @property {TreemapSnapshot} to - The snapshot shown, or the later of the two compared.
49
+ * @property {TreemapSnapshot|null} from - The earlier of the two compared, or null.
50
+ * @ignore
51
+ */
52
+
53
+ /**
54
+ * A box of the treemap: a group, or an item.
55
+ *
56
+ * @typedef {object} TreemapNode
57
+ * @property {boolean} leaf - Whether it is an item.
58
+ * @property {string} name - Its name, as drawn.
59
+ * @property {string} id - Who it is in the tree, for opening a group.
60
+ * @property {SnapshotItem|null} item - The item, for an item.
61
+ * @property {Map<string, TreemapNode>} folders - The groups inside a group, while it is built.
62
+ * @property {TreemapNode[]} leaves - The items directly inside a group, while it is built.
63
+ * @property {TreemapNode[]} kids - What a group holds, largest first.
64
+ * @property {number} value - Its bytes in the snapshot shown.
65
+ * @property {number} was - Its bytes in the snapshot compared against, or 0.
66
+ * @property {number} size - The bytes its box stands for.
67
+ * @property {TreemapNode|null} parent - The group it is drawn in.
68
+ * @property {string} color - Its fill, the colour of the group at the top it is in.
69
+ * @ignore
70
+ */
71
+
72
+ /**
73
+ * @typedef {object} TreemapRect
74
+ * @property {TreemapNode} item - The box.
75
+ * @property {number} x - Its left.
76
+ * @property {number} y - Its top.
77
+ * @property {number} w - Its width.
78
+ * @property {number} h - Its height.
79
+ * @ignore
80
+ */
81
+
82
+ // joins the names of the groups into an id no name can contain
83
+ const SEP = '\u001f';
84
+
85
+ // the height of a group's name, and the gap inside a group's frame
86
+ const HEAD = 16;
87
+ const PAD = 2;
88
+
89
+ /** The magnifications the treemap steps through. */
90
+ const SCALES = [1, 1.25, 1.5, 2, 2.5, 3, 4, 5, 6, 8];
91
+
92
+ /**
93
+ * A fill per group at the top, largest first: the report colours of the metrics pages, which read
94
+ * on the panel's dark background.
95
+ *
96
+ * @type {string[]}
97
+ */
98
+ const PALETTE = ['#3987e5', '#d95926', '#199e70', '#c98500', '#d55181', '#2f9e2f', '#9085e9'];
99
+
100
+ // the fill of the groups past the palette
101
+ const OTHERS = '#5d6a6e';
102
+
103
+ /**
104
+ * @param {string} tag - The tag name.
105
+ * @param {string} className - The class names.
106
+ * @param {string} [text] - The text content.
107
+ * @returns {HTMLElement} The element.
108
+ */
109
+ function el(tag, className, text) {
110
+ const element = document.createElement(tag);
111
+ element.className = className;
112
+ if (text !== undefined) element.textContent = text;
113
+ return element;
114
+ }
115
+
116
+ /**
117
+ * @param {number} bytes - A change in bytes.
118
+ * @returns {string} The change, signed.
119
+ */
120
+ function formatChange(bytes) {
121
+ return `${bytes > 0 ? '+' : bytes < 0 ? '−' : '±'}${formatBytes(Math.abs(bytes))}`;
122
+ }
123
+
124
+ /**
125
+ * @param {number} time - Milliseconds since the epoch.
126
+ * @returns {string} The time of day.
127
+ */
128
+ function clock(time) {
129
+ return new Date(time).toLocaleTimeString();
130
+ }
131
+
132
+ /**
133
+ * @param {number} n - A count.
134
+ * @returns {string} The count of items.
135
+ */
136
+ function items(n) {
137
+ return `${n} item${n === 1 ? '' : 's'}`;
138
+ }
139
+
140
+ /**
141
+ * Builds the groups and items of a snapshot, or of two compared, into a tree sized for drawing.
142
+ * Compared, a box holds the item as it is in either snapshot, so it takes the larger size, or
143
+ * sized by change, the size of the change; an item that did not change then has no box. A group
144
+ * holding a single group is drawn as one, and a group holding a single item as the item.
145
+ *
146
+ * @param {TreemapData} data - The snapshots.
147
+ * @param {boolean} byChange - Whether boxes are sized by how much they changed.
148
+ * @returns {TreemapNode} The root of the tree.
149
+ * @ignore
150
+ */
151
+ function buildTree(data, byChange) {
152
+ const { from, to } = data;
153
+ /** @type {(name: string, id: string, item?: SnapshotItem|null) => TreemapNode} */
154
+ const node = (name, id, item = null) => ({
155
+ leaf: !!item, name, id, item, folders: new Map(), leaves: [], kids: [], value: 0, was: 0, size: 0, parent: null, color: OTHERS
156
+ });
157
+ const root = node('', '');
158
+ const add = (item, value, was) => {
159
+ const size = !from ? value : byChange ? Math.abs(value - was) : Math.max(value, was);
160
+ if (!(size > 0)) return;
161
+ let group = root;
162
+ const grow = (n) => {
163
+ n.value += value;
164
+ n.was += was;
165
+ n.size += size;
166
+ };
167
+ grow(group);
168
+ for (const name of item.group) {
169
+ let next = group.folders.get(name);
170
+ if (!next) {
171
+ next = node(name, `${group.id}${SEP}${name}`);
172
+ group.folders.set(name, next);
173
+ }
174
+ group = next;
175
+ grow(group);
176
+ }
177
+ const leaf = node(item.name, `${group.id}${SEP}${SEP}${item.key}`, item);
178
+ grow(leaf);
179
+ group.leaves.push(leaf);
180
+ };
181
+ const before = from ? new Map(from.items.map(item => [item.key, item])) : null;
182
+ const after = new Set(to.items.map(item => item.key));
183
+ for (const item of to.items) add(item, item.size, before?.get(item.key)?.size ?? 0);
184
+ for (const item of from?.items ?? []) {
185
+ if (!after.has(item.key)) add(item, 0, item.size);
186
+ }
187
+
188
+ /** @type {(group: TreemapNode) => TreemapNode} */
189
+ const tidy = (group) => {
190
+ let kids = [...[...group.folders.values()].map(tidy), ...group.leaves];
191
+ if (group !== root) {
192
+ while (kids.length === 1 && !kids[0].leaf) {
193
+ group.name = `${group.name} / ${kids[0].name}`;
194
+ group.id = kids[0].id;
195
+ kids = kids[0].kids;
196
+ }
197
+ if (kids.length === 1) {
198
+ // the group's name, unless the item's own already starts with it
199
+ if (!kids[0].name.startsWith(group.name)) kids[0].name = `${group.name} › ${kids[0].name}`;
200
+ return kids[0];
201
+ }
202
+ }
203
+ for (const kid of kids) kid.parent = group;
204
+ group.kids = kids.sort((a, b) => b.size - a.size);
205
+ return group;
206
+ };
207
+ tidy(root);
208
+
209
+ /** @type {(n: TreemapNode, color: string) => void} */
210
+ const paint = (n, color) => {
211
+ n.color = color;
212
+ n.kids.forEach(kid => paint(kid, color));
213
+ };
214
+ root.kids.forEach((kid, i) => paint(kid, PALETTE[i] ?? OTHERS));
215
+ return root;
216
+ }
217
+
218
+ /**
219
+ * @param {TreemapNode} node - A group to search from.
220
+ * @param {string} id - The id of a group.
221
+ * @returns {TreemapNode|null} The group, or null when the tree has none by that id.
222
+ */
223
+ function findNode(node, id) {
224
+ if (node.id === id) return node;
225
+ for (const kid of node.kids) {
226
+ const found = kid.leaf ? null : findNode(kid, id);
227
+ if (found) return found;
228
+ }
229
+ return null;
230
+ }
231
+
232
+ /**
233
+ * Squarified layout: packs boxes, largest first, into rows that stay as square as possible.
234
+ *
235
+ * @param {TreemapNode[]} nodes - The boxes, largest first.
236
+ * @param {number} x - The left of the area.
237
+ * @param {number} y - The top of the area.
238
+ * @param {number} w - The width of the area.
239
+ * @param {number} h - The height of the area.
240
+ * @returns {TreemapRect[]} Where each box goes.
241
+ */
242
+ function squarify(nodes, x, y, w, h) {
243
+ /** @type {TreemapRect[]} */
244
+ const out = [];
245
+ let rest = nodes.filter(n => n.size > 0);
246
+ let remaining = rest.reduce((sum, n) => sum + n.size, 0);
247
+ const worst = (row, sum, short, area) => {
248
+ const thick = sum * area / short;
249
+ let bad = 0;
250
+ for (const n of row) {
251
+ const len = n.size * area / thick;
252
+ bad = Math.max(bad, thick / len, len / thick);
253
+ }
254
+ return bad;
255
+ };
256
+ while (rest.length && w > 0 && h > 0) {
257
+ const short = Math.min(w, h);
258
+ const area = w * h / remaining;
259
+ const row = [rest[0]];
260
+ let sum = rest[0].size;
261
+ let best = worst(row, sum, short, area);
262
+ while (row.length < rest.length) {
263
+ const next = rest[row.length];
264
+ const bad = worst([...row, next], sum + next.size, short, area);
265
+ if (bad > best) break;
266
+ row.push(next);
267
+ sum += next.size;
268
+ best = bad;
269
+ }
270
+ const thick = sum * area / short;
271
+ let offset = 0;
272
+ for (const n of row) {
273
+ const len = n.size * area / thick;
274
+ out.push(w >= h ? { item: n, x, y: y + offset, w: thick, h: len } : { item: n, x: x + offset, y, w: len, h: thick });
275
+ offset += len;
276
+ }
277
+ if (w >= h) {
278
+ x += thick;
279
+ w -= thick;
280
+ } else {
281
+ y += thick;
282
+ h -= thick;
283
+ }
284
+ remaining -= sum;
285
+ rest = rest.slice(row.length);
286
+ }
287
+ return out;
288
+ }
289
+
290
+ /**
291
+ * @param {TreemapNode} node - A box.
292
+ * @returns {string} Its groups and name, as the trail reads.
293
+ */
294
+ function pathOf(node) {
295
+ const names = [];
296
+ for (let n = node; n?.parent; n = n.parent) names.unshift(n.name);
297
+ return names.join(' › ');
298
+ }
299
+
300
+ /**
301
+ * The contents of a treemap tab: a snapshot of a tab, or two compared, drawn as a box per item
302
+ * sized by its bytes, nested in boxes for its groups. Clicking a group's name opens it.
303
+ *
304
+ * Compared, every box takes the larger of the item's two sizes, and the share of it that changed
305
+ * is marked, red for bytes added and striped green for bytes removed. An item in only one of the
306
+ * snapshots is marked whole. Sized by change instead, a box is as large as its change, and items
307
+ * that did not change are left out.
308
+ *
309
+ * Ctrl + wheel or a pinch magnifies at the pointer, drawing the treemap larger than the tab to
310
+ * give more boxes room for their names, and dragging moves around it.
311
+ *
312
+ * @ignore
313
+ */
314
+ class TreemapView {
315
+ /**
316
+ * The tab's panel.
317
+ *
318
+ * @type {HTMLElement}
319
+ */
320
+ el;
321
+
322
+ /**
323
+ * @type {TreemapData}
324
+ * @private
325
+ */
326
+ _data;
327
+
328
+ /**
329
+ * How boxes link to the tabs listing what they measured, or null for no links.
330
+ *
331
+ * @type {TreemapLinks|null}
332
+ * @private
333
+ */
334
+ _links;
335
+
336
+ /**
337
+ * Whether boxes are sized by how much they changed, when comparing.
338
+ *
339
+ * @type {boolean}
340
+ * @private
341
+ */
342
+ _byChange = false;
343
+
344
+ /**
345
+ * The id of the group open, or an empty string for everything.
346
+ *
347
+ * @type {string}
348
+ * @private
349
+ */
350
+ _zoom = '';
351
+
352
+ /**
353
+ * The magnification, one of {@link SCALES}.
354
+ *
355
+ * @type {number}
356
+ * @private
357
+ */
358
+ _scale = 1;
359
+
360
+ /**
361
+ * The tree last drawn.
362
+ *
363
+ * @type {TreemapNode|null}
364
+ * @private
365
+ */
366
+ _root = null;
367
+
368
+ /**
369
+ * The size of the view last drawn at, so a refresh redraws only when it changed.
370
+ *
371
+ * @type {string}
372
+ * @private
373
+ */
374
+ _drawnSize = '';
375
+
376
+ /**
377
+ * A drag moving around the magnified treemap.
378
+ *
379
+ * @type {{ x: number, y: number, left: number, top: number, moved: boolean }|null}
380
+ * @private
381
+ */
382
+ _drag = null;
383
+
384
+ /**
385
+ * The wheel's movement not yet turned into a step of magnification.
386
+ *
387
+ * @type {number}
388
+ * @private
389
+ */
390
+ _wheel = 0;
391
+
392
+ /** @type {HTMLElement} @private */
393
+ _crumbs;
394
+
395
+ /** @type {HTMLElement} @private */
396
+ _view;
397
+
398
+ /** @type {HTMLElement} @private */
399
+ _box;
400
+
401
+ /** @type {HTMLElement} @private */
402
+ _legend;
403
+
404
+ /** @type {HTMLElement} @private */
405
+ _tip;
406
+
407
+ /** @type {HTMLElement} @private */
408
+ _scaleText;
409
+
410
+ /** @type {HTMLButtonElement} @private */
411
+ _scaleDown;
412
+
413
+ /** @type {HTMLButtonElement} @private */
414
+ _scaleUp;
415
+
416
+ /**
417
+ * @param {TreemapData} data - What to draw.
418
+ * @param {TreemapLinks|null} [links] - How boxes link to the tabs listing what they measured.
419
+ */
420
+ constructor(data, links = null) {
421
+ this._data = data;
422
+ this._links = links;
423
+ const { from, to } = data;
424
+
425
+ this.el = el('div', 'pci-listpanel pci-treemap');
426
+ const bar = el('div', 'pci-subbar');
427
+ const summary = el('span', 'pci-tm-summary', this.summary);
428
+ setTip(summary, [`${data.measure}.`, ...new Set([from?.note, to.note].filter(Boolean))].join('\n'));
429
+ bar.appendChild(summary);
430
+ if (from) {
431
+ const label = el('label', 'pci-check', 'Size by change');
432
+ const toggle = /** @type {HTMLInputElement} */ (document.createElement('input'));
433
+ toggle.type = 'checkbox';
434
+ label.prepend(toggle);
435
+ setTip(label, 'Size each box by how much it changed, rather than by the larger of its two sizes, and leave out what did not change');
436
+ toggle.addEventListener('change', () => {
437
+ this._byChange = toggle.checked;
438
+ this.render();
439
+ });
440
+ bar.appendChild(label);
441
+ }
442
+ const scale = el('span', 'pci-group');
443
+ setTip(scale, 'Magnify the treemap, to give more boxes room for their names. Ctrl + wheel or a pinch magnifies at the pointer,\n' +
444
+ 'dragging moves around, and + and − magnify and 0 fits while the treemap has focus');
445
+ const button = (text, run) => {
446
+ const b = /** @type {HTMLButtonElement} */ (el('button', 'pci-btn', text));
447
+ b.addEventListener('click', run);
448
+ scale.appendChild(b);
449
+ return b;
450
+ };
451
+ this._scaleDown = button('−', () => this._magnify(-1));
452
+ this._scaleText = el('span', 'pci-tm-scale', '100%');
453
+ scale.appendChild(this._scaleText);
454
+ this._scaleUp = button('+', () => this._magnify(1));
455
+ button('Fit', () => this._magnify(-SCALES.length));
456
+ bar.appendChild(scale);
457
+
458
+ this._crumbs = el('div', 'pci-tm-crumbs');
459
+ this._view = el('div', 'pci-tm-view');
460
+ // focusable, for the keys
461
+ this._view.tabIndex = 0;
462
+ this._box = el('div', 'pci-tm-box');
463
+ this._view.appendChild(this._box);
464
+ this._legend = el('div', 'pci-tm-legend');
465
+ this._tip = el('div', 'pci-tm-tip');
466
+ this._tip.style.display = 'none';
467
+ this.el.append(bar, this._crumbs, this._view, this._legend, this._tip);
468
+
469
+ this._view.addEventListener('wheel', this._onWheel, { passive: false });
470
+ this._view.addEventListener('pointerdown', this._onPointerDown);
471
+ this._view.addEventListener('pointermove', this._onPointerMove);
472
+ this._view.addEventListener('pointerup', this._onPointerUp);
473
+ this._view.addEventListener('pointercancel', this._onPointerUp);
474
+ this._view.addEventListener('keydown', this._onKeyDown);
475
+ this._view.addEventListener('pointerleave', () => {
476
+ this._tip.style.display = 'none';
477
+ });
478
+ }
479
+
480
+ /**
481
+ * The name of the tab, such as 'Memory #2' or 'Memory #1→#2'.
482
+ *
483
+ * @type {string}
484
+ */
485
+ get title() {
486
+ const { tab, from, to } = this._data;
487
+ return from ? `${tab} #${from.number}→#${to.number}` : `${tab} #${to.number}`;
488
+ }
489
+
490
+ /**
491
+ * When the snapshots were captured and what they add up to.
492
+ *
493
+ * @type {string}
494
+ */
495
+ get summary() {
496
+ const { from, to } = this._data;
497
+ if (!from) return `Captured at ${clock(to.time)} · ${formatBytes(to.total)} in ${items(to.items.length)}`;
498
+ const before = new Map(from.items.map(item => [item.key, item.size]));
499
+ const after = new Set(to.items.map(item => item.key));
500
+ const added = to.items.filter(item => !before.has(item.key)).length;
501
+ const removed = from.items.filter(item => !after.has(item.key)).length;
502
+ const changed = to.items.filter(item => before.has(item.key) && before.get(item.key) !== item.size).length;
503
+ return `#${from.number} at ${clock(from.time)} → #${to.number} at ${clock(to.time)} · ` +
504
+ `${formatBytes(from.total)} → ${formatBytes(to.total)}, ${formatChange(to.total - from.total)} · ` +
505
+ `${items(added)} added, ${removed} removed, ${changed} changed`;
506
+ }
507
+
508
+ /**
509
+ * The tree last drawn, for tests.
510
+ *
511
+ * @type {TreemapNode|null}
512
+ */
513
+ get tree() {
514
+ return this._root;
515
+ }
516
+
517
+ /**
518
+ * Opens a group.
519
+ *
520
+ * @param {string} id - The group's id, or an empty string for everything.
521
+ */
522
+ zoomTo(id) {
523
+ this._zoom = id;
524
+ this.render();
525
+ }
526
+
527
+ /**
528
+ * Draws again when the tab changed size since it was drawn, as when the panel was resized.
529
+ * Called on the panel's refreshes, rather than on every frame.
530
+ */
531
+ fit() {
532
+ if (`${this._view.clientWidth}×${this._view.clientHeight}` !== this._drawnSize) this.render();
533
+ }
534
+
535
+ /**
536
+ * Draws the treemap from the top of the group open, with its trail and legend.
537
+ */
538
+ render() {
539
+ const { from } = this._data;
540
+ const root = buildTree(this._data, this._byChange);
541
+ this._root = root;
542
+ const top = (this._zoom && findNode(root, this._zoom)) || root;
543
+
544
+ // the trail of open groups
545
+ const crumbs = this._crumbs;
546
+ crumbs.textContent = '';
547
+ const trail = [];
548
+ for (let n = top; n; n = n.parent) trail.unshift(n);
549
+ trail.forEach((n, i) => {
550
+ if (i) crumbs.append(' / ');
551
+ const label = n === root ? 'everything' : n.name;
552
+ if (n === top) {
553
+ crumbs.appendChild(el('strong', '', label));
554
+ } else {
555
+ const b = el('button', 'pci-tm-crumb', label);
556
+ b.addEventListener('click', () => this.zoomTo(n.id));
557
+ crumbs.appendChild(b);
558
+ }
559
+ });
560
+ // sized by change, the boxes hold only what changed, so their sums are no totals
561
+ const figures = !from ? formatBytes(top.value) : this._byChange ? `${formatChange(top.value - top.was)} in what changed` :
562
+ `${formatBytes(top.was)} → ${formatBytes(top.value)}, ${formatChange(top.value - top.was)}`;
563
+ crumbs.appendChild(el('span', 'pci-tm-dim', ` · ${figures}`));
564
+
565
+ const legend = this._legend;
566
+ legend.textContent = '';
567
+ const key = (cls, color, text) => {
568
+ const entry = el('span', '');
569
+ const swatch = el('i', cls);
570
+ if (color) swatch.style.background = color;
571
+ entry.append(swatch, text);
572
+ legend.appendChild(entry);
573
+ };
574
+ if (from) {
575
+ key('pci-tm-added', '', `added since #${from.number}`);
576
+ key('pci-tm-removed', '', `removed since #${from.number}`);
577
+ if (!this._byChange) key('pci-tm-same', '', 'in both');
578
+ } else {
579
+ root.kids.slice(0, PALETTE.length).forEach(kid => key('', kid.color, kid.name));
580
+ if (root.kids.length > PALETTE.length) key('', OTHERS, 'others');
581
+ }
582
+
583
+ // laid out last, once the trail and the legend have taken their room
584
+ this._fitBox();
585
+ this._drawnSize = `${this._view.clientWidth}×${this._view.clientHeight}`;
586
+ const box = this._box;
587
+ box.textContent = '';
588
+ this._tip.style.display = 'none';
589
+ if (!top.kids.length) {
590
+ box.appendChild(el('div', 'pci-empty', from && this._byChange ? 'Nothing changed in size.' : 'Nothing was measured.'));
591
+ }
592
+ // the top level has no frame of its own
593
+ for (const rect of squarify(top.kids, 0, 0, box.clientWidth, box.clientHeight)) {
594
+ this._place(rect.item, box, rect, top);
595
+ }
596
+ }
597
+
598
+ /**
599
+ * Draws a box, and inside a group, the boxes it holds.
600
+ *
601
+ * @param {TreemapNode} node - The box.
602
+ * @param {HTMLElement} parent - The element it goes in.
603
+ * @param {{ x: number, y: number, w: number, h: number }} rect - Where it goes in it.
604
+ * @param {TreemapNode} top - The group open, for the share of it a box is.
605
+ * @private
606
+ */
607
+ _place(node, parent, rect, top) {
608
+ const { x, y, w, h } = rect;
609
+ if (w < 3 || h < 3) return;
610
+ const from = this._data.from;
611
+ const box = el('div', '');
612
+ box.style.cssText = `left:${x}px;top:${y}px;width:${w}px;height:${h}px`;
613
+ parent.appendChild(box);
614
+
615
+ if (node.leaf) {
616
+ const diff = node.value - node.was;
617
+ if (from && this._byChange) {
618
+ // the whole box is the change
619
+ box.className = `pci-tm-leaf ${diff > 0 ? 'pci-tm-added' : 'pci-tm-removed'}`;
620
+ } else if (from) {
621
+ // the changed share of the box, as a band across its longer side
622
+ box.className = 'pci-tm-leaf pci-tm-cmp';
623
+ const share = Math.abs(diff) / node.size;
624
+ if (share > 0) {
625
+ const part = el('div', `pci-tm-part ${diff > 0 ? 'pci-tm-added' : 'pci-tm-removed'}`);
626
+ part.style.cssText = w >= h ?
627
+ `top:0;bottom:0;right:0;width:${Math.max(2, share * w)}px` :
628
+ `left:0;right:0;bottom:0;height:${Math.max(2, share * h)}px`;
629
+ box.appendChild(part);
630
+ }
631
+ } else {
632
+ box.className = 'pci-tm-leaf';
633
+ box.style.background = node.color;
634
+ }
635
+ if (w > 50 && h > 15) {
636
+ box.appendChild(el('span', '', node.name));
637
+ if (h > 28) box.appendChild(el('span', 'pci-tm-size', !from ? formatBytes(node.value) : diff === 0 ? 'no change' : formatChange(diff)));
638
+ }
639
+ const where = this._linkOf(node);
640
+ if (where) {
641
+ // a click shows what the box measured in the tab listing it
642
+ box.classList.add('pci-tm-link');
643
+ box.addEventListener('click', (e) => {
644
+ const target = node.item?.target?.deref();
645
+ if (!target || !this._links?.open(target)) this._showTip(e, node, top, `${where} no longer lists it: it went after the snapshot`);
646
+ });
647
+ }
648
+ box.addEventListener('mousemove', e => this._showTip(e, node, top));
649
+ return;
650
+ }
651
+
652
+ box.className = 'pci-tm-group';
653
+ box.style.borderColor = `${node.color}99`;
654
+ // a group shows its name when there is room for it
655
+ const head = w > 60 && h > HEAD * 2 ? HEAD : 0;
656
+ if (head) {
657
+ const title = el('div', 'pci-tm-head', `${node.name} · ${!from ? formatBytes(node.value) : formatChange(node.value - node.was)}`);
658
+ setTip(title, `Open ${pathOf(node)}`);
659
+ title.addEventListener('click', () => this.zoomTo(node.id));
660
+ box.appendChild(title);
661
+ }
662
+ for (const inner of squarify(node.kids, PAD, head + PAD, w - 2 - PAD * 2, h - 2 - head - PAD * 2)) {
663
+ this._place(inner.item, box, inner, top);
664
+ }
665
+ }
666
+
667
+ /**
668
+ * @param {TreemapNode} node - An item's box.
669
+ * @returns {string|null} The name of the tab listing what it measured, as it was when the
670
+ * snapshot was taken, or null when no tab lists it.
671
+ * @private
672
+ */
673
+ _linkOf(node) {
674
+ const target = node.item?.target?.deref();
675
+ return target && this._links ? this._links.label(target) : null;
676
+ }
677
+
678
+ /**
679
+ * Shows what the box under the pointer holds, by the pointer.
680
+ *
681
+ * @param {MouseEvent} e - The pointer's move.
682
+ * @param {TreemapNode} node - The box.
683
+ * @param {TreemapNode} top - The group open.
684
+ * @param {string} [note] - A line to end on instead of where a click goes.
685
+ * @private
686
+ */
687
+ _showTip(e, node, top, note) {
688
+ if (this._drag?.moved) return;
689
+ const diff = node.value - node.was;
690
+ let line = `${formatBytes(node.value)} · ${(100 * node.value / (top.value || 1)).toFixed(1)}% of what is shown`;
691
+ if (this._data.from) {
692
+ line = node.was === 0 ? `added: ${formatBytes(node.value)}` :
693
+ node.value === 0 ? `removed, was ${formatBytes(node.was)}` :
694
+ `${formatBytes(node.was)} → ${formatBytes(node.value)} · ${diff === 0 ? 'no change' : formatChange(diff)}`;
695
+ }
696
+ const tip = this._tip;
697
+ tip.textContent = '';
698
+ tip.append(el('strong', '', pathOf(node)), el('div', '', line));
699
+ if (node.item?.info) tip.appendChild(el('div', 'pci-tm-dim', node.item.info));
700
+ const where = note ? null : this._linkOf(node);
701
+ if (note || where) tip.appendChild(el('div', 'pci-tm-dim', note ?? `Click to show it in ${where}`));
702
+ tip.style.display = 'block';
703
+ const view = this.el.ownerDocument.defaultView ?? window;
704
+ tip.style.left = `${Math.max(4, Math.min(e.clientX + 14, view.innerWidth - tip.offsetWidth - 4))}px`;
705
+ tip.style.top = `${e.clientY + 16 + tip.offsetHeight > view.innerHeight - 4 ? Math.max(4, e.clientY - tip.offsetHeight - 8) : e.clientY + 16}px`;
706
+ }
707
+
708
+ /**
709
+ * Sizes the treemap for the magnification, to the room the tab has.
710
+ *
711
+ * @private
712
+ */
713
+ _fitBox() {
714
+ // unmagnified, the treemap fits, and rounding must not bring up scroll bars
715
+ this._view.style.overflow = this._scale > 1 ? 'auto' : 'hidden';
716
+ this._box.style.width = `${Math.floor(this._view.clientWidth * this._scale)}px`;
717
+ this._box.style.height = `${Math.floor(this._view.clientHeight * this._scale)}px`;
718
+ this._view.classList.toggle('pci-tm-pan', this._scale > 1);
719
+ this._scaleText.textContent = `${Math.round(this._scale * 100)}%`;
720
+ this._scaleDown.disabled = this._scale === SCALES[0];
721
+ this._scaleUp.disabled = this._scale === SCALES[SCALES.length - 1];
722
+ }
723
+
724
+ /**
725
+ * Steps the magnification, keeping one point of the treemap where it is: the pointer when
726
+ * magnifying with the wheel, otherwise the middle.
727
+ *
728
+ * @param {number} step - Steps to take, up or down.
729
+ * @param {number} [anchorX] - The point to keep, from the left of the tab.
730
+ * @param {number} [anchorY] - The point to keep, from the top of the tab.
731
+ * @private
732
+ */
733
+ _magnify(step, anchorX, anchorY) {
734
+ const index = Math.max(0, Math.min(SCALES.length - 1, SCALES.indexOf(this._scale) + step));
735
+ if (SCALES[index] === this._scale) return;
736
+ const view = this._view;
737
+ const box = this._box;
738
+ const ax = anchorX ?? view.clientWidth / 2;
739
+ const ay = anchorY ?? view.clientHeight / 2;
740
+ const fx = box.offsetWidth ? (view.scrollLeft + ax) / box.offsetWidth : 0;
741
+ const fy = box.offsetHeight ? (view.scrollTop + ay) / box.offsetHeight : 0;
742
+ this._scale = SCALES[index];
743
+ this.render();
744
+ view.scrollLeft = fx * box.offsetWidth - ax;
745
+ view.scrollTop = fy * box.offsetHeight - ay;
746
+ }
747
+
748
+ /**
749
+ * Ctrl + wheel magnifies towards the pointer, as in maps and design tools; a trackpad pinch
750
+ * arrives the same way. A plain wheel scrolls, and Shift + wheel scrolls sideways, as usual.
751
+ *
752
+ * @param {WheelEvent} e - The event.
753
+ * @private
754
+ */
755
+ _onWheel = (e) => {
756
+ if (!e.ctrlKey && !e.metaKey) return;
757
+ e.preventDefault();
758
+ // a pinch sends many small movements; a wheel notch sends one large one
759
+ this._wheel += e.deltaY;
760
+ if (Math.abs(this._wheel) >= 40) {
761
+ const rect = this._view.getBoundingClientRect();
762
+ this._magnify(this._wheel < 0 ? 1 : -1, e.clientX - rect.left, e.clientY - rect.top);
763
+ this._wheel = 0;
764
+ }
765
+ };
766
+
767
+ /**
768
+ * @param {PointerEvent} e - The event.
769
+ * @private
770
+ */
771
+ _onPointerDown = (e) => {
772
+ if (e.button !== 0 || this._scale === 1) return;
773
+ this._drag = { x: e.clientX, y: e.clientY, left: this._view.scrollLeft, top: this._view.scrollTop, moved: false };
774
+ };
775
+
776
+ /**
777
+ * Dragging moves around a magnified treemap.
778
+ *
779
+ * @param {PointerEvent} e - The event.
780
+ * @private
781
+ */
782
+ _onPointerMove = (e) => {
783
+ const drag = this._drag;
784
+ if (!drag) return;
785
+ const dx = e.clientX - drag.x;
786
+ const dy = e.clientY - drag.y;
787
+ if (!drag.moved && Math.hypot(dx, dy) > 4) {
788
+ drag.moved = true;
789
+ this._view.setPointerCapture?.(e.pointerId);
790
+ this._view.classList.add('pci-tm-panning');
791
+ this._tip.style.display = 'none';
792
+ }
793
+ if (drag.moved) {
794
+ this._view.scrollLeft = drag.left - dx;
795
+ this._view.scrollTop = drag.top - dy;
796
+ }
797
+ };
798
+
799
+ /**
800
+ * @param {PointerEvent} e - The event.
801
+ * @private
802
+ */
803
+ _onPointerUp = (e) => {
804
+ if (this._drag?.moved) {
805
+ this._view.releasePointerCapture?.(e.pointerId);
806
+ // the click that ends a drag must not open the group under the pointer
807
+ this._view.addEventListener('click', event => event.stopPropagation(), { capture: true, once: true });
808
+ setTimeout(() => this._view.classList.remove('pci-tm-panning'));
809
+ }
810
+ this._drag = null;
811
+ };
812
+
813
+ /**
814
+ * + and - magnify, 0 fits and Backspace goes back up a group, while the treemap has focus.
815
+ *
816
+ * @param {KeyboardEvent} e - The event.
817
+ * @private
818
+ */
819
+ _onKeyDown = (e) => {
820
+ if (e.ctrlKey || e.metaKey || e.altKey) return;
821
+ if (e.key === '+' || e.key === '=') {
822
+ this._magnify(1);
823
+ } else if (e.key === '-') {
824
+ this._magnify(-1);
825
+ } else if (e.key === '0') {
826
+ this._magnify(-SCALES.length);
827
+ } else if (e.key === 'Backspace' && this._zoom && this._root) {
828
+ const open = findNode(this._root, this._zoom);
829
+ this.zoomTo(open?.parent?.parent ? open.parent.id : '');
830
+ } else {
831
+ return;
832
+ }
833
+ e.preventDefault();
834
+ };
835
+ }
836
+
837
+ export { TreemapView };