@john-guerra/fisheye-nav 0.1.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,4477 @@
1
+ // @john-guerra/fisheye-nav v0.1.0 Copyright (c) 2026 John Alexis Guerra Gómez
2
+ // reactive-widget-helper v0.0.2 Copyright (c) 2024 John Alexis Guerra Gómez
3
+ function ReactiveWidget(
4
+ target,
5
+ { showValue = () => {}, value } = {}
6
+ ) {
7
+ // 🧰 The interval value selected by the user interaction
8
+ let intervalValue = value;
9
+
10
+ // 🧰 And a function to update the current internal value. This one triggers the input event
11
+ function setValue(newValue) {
12
+ intervalValue = newValue;
13
+ target.dispatchEvent(new CustomEvent("input", { bubbles: true }));
14
+ }
15
+
16
+ // 🧰 The value attribute setter and getter
17
+ Object.defineProperty(target, "value", {
18
+ get() {
19
+ return intervalValue;
20
+ },
21
+ set(newValue) {
22
+ intervalValue = newValue;
23
+ showValue();
24
+ },
25
+ });
26
+
27
+ // 🧰 Listen to the input event, and reflec the current value
28
+ target.addEventListener("input", (evt) => {
29
+ evt.preventDefault();
30
+ evt.stopPropagation();
31
+ showValue(evt);
32
+ });
33
+
34
+ // Expose the setValue
35
+ target.setValue = setValue;
36
+
37
+ // 🧰 Finally return the html element
38
+ return target;
39
+ }
40
+
41
+ var xhtml = "http://www.w3.org/1999/xhtml";
42
+
43
+ var namespaces = {
44
+ svg: "http://www.w3.org/2000/svg",
45
+ xhtml: xhtml,
46
+ xlink: "http://www.w3.org/1999/xlink",
47
+ xml: "http://www.w3.org/XML/1998/namespace",
48
+ xmlns: "http://www.w3.org/2000/xmlns/"
49
+ };
50
+
51
+ function namespace(name) {
52
+ var prefix = name += "", i = prefix.indexOf(":");
53
+ if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns") name = name.slice(i + 1);
54
+ return namespaces.hasOwnProperty(prefix) ? {space: namespaces[prefix], local: name} : name; // eslint-disable-line no-prototype-builtins
55
+ }
56
+
57
+ function creatorInherit(name) {
58
+ return function() {
59
+ var document = this.ownerDocument,
60
+ uri = this.namespaceURI;
61
+ return uri === xhtml && document.documentElement.namespaceURI === xhtml
62
+ ? document.createElement(name)
63
+ : document.createElementNS(uri, name);
64
+ };
65
+ }
66
+
67
+ function creatorFixed(fullname) {
68
+ return function() {
69
+ return this.ownerDocument.createElementNS(fullname.space, fullname.local);
70
+ };
71
+ }
72
+
73
+ function creator(name) {
74
+ var fullname = namespace(name);
75
+ return (fullname.local
76
+ ? creatorFixed
77
+ : creatorInherit)(fullname);
78
+ }
79
+
80
+ function none() {}
81
+
82
+ function selector(selector) {
83
+ return selector == null ? none : function() {
84
+ return this.querySelector(selector);
85
+ };
86
+ }
87
+
88
+ function selection_select(select) {
89
+ if (typeof select !== "function") select = selector(select);
90
+
91
+ for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
92
+ for (var group = groups[j], n = group.length, subgroup = subgroups[j] = new Array(n), node, subnode, i = 0; i < n; ++i) {
93
+ if ((node = group[i]) && (subnode = select.call(node, node.__data__, i, group))) {
94
+ if ("__data__" in node) subnode.__data__ = node.__data__;
95
+ subgroup[i] = subnode;
96
+ }
97
+ }
98
+ }
99
+
100
+ return new Selection(subgroups, this._parents);
101
+ }
102
+
103
+ // Given something array like (or null), returns something that is strictly an
104
+ // array. This is used to ensure that array-like objects passed to d3.selectAll
105
+ // or selection.selectAll are converted into proper arrays when creating a
106
+ // selection; we don’t ever want to create a selection backed by a live
107
+ // HTMLCollection or NodeList. However, note that selection.selectAll will use a
108
+ // static NodeList as a group, since it safely derived from querySelectorAll.
109
+ function array(x) {
110
+ return x == null ? [] : Array.isArray(x) ? x : Array.from(x);
111
+ }
112
+
113
+ function empty() {
114
+ return [];
115
+ }
116
+
117
+ function selectorAll(selector) {
118
+ return selector == null ? empty : function() {
119
+ return this.querySelectorAll(selector);
120
+ };
121
+ }
122
+
123
+ function arrayAll(select) {
124
+ return function() {
125
+ return array(select.apply(this, arguments));
126
+ };
127
+ }
128
+
129
+ function selection_selectAll(select) {
130
+ if (typeof select === "function") select = arrayAll(select);
131
+ else select = selectorAll(select);
132
+
133
+ for (var groups = this._groups, m = groups.length, subgroups = [], parents = [], j = 0; j < m; ++j) {
134
+ for (var group = groups[j], n = group.length, node, i = 0; i < n; ++i) {
135
+ if (node = group[i]) {
136
+ subgroups.push(select.call(node, node.__data__, i, group));
137
+ parents.push(node);
138
+ }
139
+ }
140
+ }
141
+
142
+ return new Selection(subgroups, parents);
143
+ }
144
+
145
+ function matcher(selector) {
146
+ return function() {
147
+ return this.matches(selector);
148
+ };
149
+ }
150
+
151
+ function childMatcher(selector) {
152
+ return function(node) {
153
+ return node.matches(selector);
154
+ };
155
+ }
156
+
157
+ var find = Array.prototype.find;
158
+
159
+ function childFind(match) {
160
+ return function() {
161
+ return find.call(this.children, match);
162
+ };
163
+ }
164
+
165
+ function childFirst() {
166
+ return this.firstElementChild;
167
+ }
168
+
169
+ function selection_selectChild(match) {
170
+ return this.select(match == null ? childFirst
171
+ : childFind(typeof match === "function" ? match : childMatcher(match)));
172
+ }
173
+
174
+ var filter = Array.prototype.filter;
175
+
176
+ function children() {
177
+ return Array.from(this.children);
178
+ }
179
+
180
+ function childrenFilter(match) {
181
+ return function() {
182
+ return filter.call(this.children, match);
183
+ };
184
+ }
185
+
186
+ function selection_selectChildren(match) {
187
+ return this.selectAll(match == null ? children
188
+ : childrenFilter(typeof match === "function" ? match : childMatcher(match)));
189
+ }
190
+
191
+ function selection_filter(match) {
192
+ if (typeof match !== "function") match = matcher(match);
193
+
194
+ for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
195
+ for (var group = groups[j], n = group.length, subgroup = subgroups[j] = [], node, i = 0; i < n; ++i) {
196
+ if ((node = group[i]) && match.call(node, node.__data__, i, group)) {
197
+ subgroup.push(node);
198
+ }
199
+ }
200
+ }
201
+
202
+ return new Selection(subgroups, this._parents);
203
+ }
204
+
205
+ function sparse(update) {
206
+ return new Array(update.length);
207
+ }
208
+
209
+ function selection_enter() {
210
+ return new Selection(this._enter || this._groups.map(sparse), this._parents);
211
+ }
212
+
213
+ function EnterNode(parent, datum) {
214
+ this.ownerDocument = parent.ownerDocument;
215
+ this.namespaceURI = parent.namespaceURI;
216
+ this._next = null;
217
+ this._parent = parent;
218
+ this.__data__ = datum;
219
+ }
220
+
221
+ EnterNode.prototype = {
222
+ constructor: EnterNode,
223
+ appendChild: function(child) { return this._parent.insertBefore(child, this._next); },
224
+ insertBefore: function(child, next) { return this._parent.insertBefore(child, next); },
225
+ querySelector: function(selector) { return this._parent.querySelector(selector); },
226
+ querySelectorAll: function(selector) { return this._parent.querySelectorAll(selector); }
227
+ };
228
+
229
+ function constant$1(x) {
230
+ return function() {
231
+ return x;
232
+ };
233
+ }
234
+
235
+ function bindIndex(parent, group, enter, update, exit, data) {
236
+ var i = 0,
237
+ node,
238
+ groupLength = group.length,
239
+ dataLength = data.length;
240
+
241
+ // Put any non-null nodes that fit into update.
242
+ // Put any null nodes into enter.
243
+ // Put any remaining data into enter.
244
+ for (; i < dataLength; ++i) {
245
+ if (node = group[i]) {
246
+ node.__data__ = data[i];
247
+ update[i] = node;
248
+ } else {
249
+ enter[i] = new EnterNode(parent, data[i]);
250
+ }
251
+ }
252
+
253
+ // Put any non-null nodes that don’t fit into exit.
254
+ for (; i < groupLength; ++i) {
255
+ if (node = group[i]) {
256
+ exit[i] = node;
257
+ }
258
+ }
259
+ }
260
+
261
+ function bindKey(parent, group, enter, update, exit, data, key) {
262
+ var i,
263
+ node,
264
+ nodeByKeyValue = new Map,
265
+ groupLength = group.length,
266
+ dataLength = data.length,
267
+ keyValues = new Array(groupLength),
268
+ keyValue;
269
+
270
+ // Compute the key for each node.
271
+ // If multiple nodes have the same key, the duplicates are added to exit.
272
+ for (i = 0; i < groupLength; ++i) {
273
+ if (node = group[i]) {
274
+ keyValues[i] = keyValue = key.call(node, node.__data__, i, group) + "";
275
+ if (nodeByKeyValue.has(keyValue)) {
276
+ exit[i] = node;
277
+ } else {
278
+ nodeByKeyValue.set(keyValue, node);
279
+ }
280
+ }
281
+ }
282
+
283
+ // Compute the key for each datum.
284
+ // If there a node associated with this key, join and add it to update.
285
+ // If there is not (or the key is a duplicate), add it to enter.
286
+ for (i = 0; i < dataLength; ++i) {
287
+ keyValue = key.call(parent, data[i], i, data) + "";
288
+ if (node = nodeByKeyValue.get(keyValue)) {
289
+ update[i] = node;
290
+ node.__data__ = data[i];
291
+ nodeByKeyValue.delete(keyValue);
292
+ } else {
293
+ enter[i] = new EnterNode(parent, data[i]);
294
+ }
295
+ }
296
+
297
+ // Add any remaining nodes that were not bound to data to exit.
298
+ for (i = 0; i < groupLength; ++i) {
299
+ if ((node = group[i]) && (nodeByKeyValue.get(keyValues[i]) === node)) {
300
+ exit[i] = node;
301
+ }
302
+ }
303
+ }
304
+
305
+ function datum(node) {
306
+ return node.__data__;
307
+ }
308
+
309
+ function selection_data(value, key) {
310
+ if (!arguments.length) return Array.from(this, datum);
311
+
312
+ var bind = key ? bindKey : bindIndex,
313
+ parents = this._parents,
314
+ groups = this._groups;
315
+
316
+ if (typeof value !== "function") value = constant$1(value);
317
+
318
+ for (var m = groups.length, update = new Array(m), enter = new Array(m), exit = new Array(m), j = 0; j < m; ++j) {
319
+ var parent = parents[j],
320
+ group = groups[j],
321
+ groupLength = group.length,
322
+ data = arraylike(value.call(parent, parent && parent.__data__, j, parents)),
323
+ dataLength = data.length,
324
+ enterGroup = enter[j] = new Array(dataLength),
325
+ updateGroup = update[j] = new Array(dataLength),
326
+ exitGroup = exit[j] = new Array(groupLength);
327
+
328
+ bind(parent, group, enterGroup, updateGroup, exitGroup, data, key);
329
+
330
+ // Now connect the enter nodes to their following update node, such that
331
+ // appendChild can insert the materialized enter node before this node,
332
+ // rather than at the end of the parent node.
333
+ for (var i0 = 0, i1 = 0, previous, next; i0 < dataLength; ++i0) {
334
+ if (previous = enterGroup[i0]) {
335
+ if (i0 >= i1) i1 = i0 + 1;
336
+ while (!(next = updateGroup[i1]) && ++i1 < dataLength);
337
+ previous._next = next || null;
338
+ }
339
+ }
340
+ }
341
+
342
+ update = new Selection(update, parents);
343
+ update._enter = enter;
344
+ update._exit = exit;
345
+ return update;
346
+ }
347
+
348
+ // Given some data, this returns an array-like view of it: an object that
349
+ // exposes a length property and allows numeric indexing. Note that unlike
350
+ // selectAll, this isn’t worried about “live” collections because the resulting
351
+ // array will only be used briefly while data is being bound. (It is possible to
352
+ // cause the data to change while iterating by using a key function, but please
353
+ // don’t; we’d rather avoid a gratuitous copy.)
354
+ function arraylike(data) {
355
+ return typeof data === "object" && "length" in data
356
+ ? data // Array, TypedArray, NodeList, array-like
357
+ : Array.from(data); // Map, Set, iterable, string, or anything else
358
+ }
359
+
360
+ function selection_exit() {
361
+ return new Selection(this._exit || this._groups.map(sparse), this._parents);
362
+ }
363
+
364
+ function selection_join(onenter, onupdate, onexit) {
365
+ var enter = this.enter(), update = this, exit = this.exit();
366
+ if (typeof onenter === "function") {
367
+ enter = onenter(enter);
368
+ if (enter) enter = enter.selection();
369
+ } else {
370
+ enter = enter.append(onenter + "");
371
+ }
372
+ if (onupdate != null) {
373
+ update = onupdate(update);
374
+ if (update) update = update.selection();
375
+ }
376
+ if (onexit == null) exit.remove(); else onexit(exit);
377
+ return enter && update ? enter.merge(update).order() : update;
378
+ }
379
+
380
+ function selection_merge(context) {
381
+ var selection = context.selection ? context.selection() : context;
382
+
383
+ for (var groups0 = this._groups, groups1 = selection._groups, m0 = groups0.length, m1 = groups1.length, m = Math.min(m0, m1), merges = new Array(m0), j = 0; j < m; ++j) {
384
+ for (var group0 = groups0[j], group1 = groups1[j], n = group0.length, merge = merges[j] = new Array(n), node, i = 0; i < n; ++i) {
385
+ if (node = group0[i] || group1[i]) {
386
+ merge[i] = node;
387
+ }
388
+ }
389
+ }
390
+
391
+ for (; j < m0; ++j) {
392
+ merges[j] = groups0[j];
393
+ }
394
+
395
+ return new Selection(merges, this._parents);
396
+ }
397
+
398
+ function selection_order() {
399
+
400
+ for (var groups = this._groups, j = -1, m = groups.length; ++j < m;) {
401
+ for (var group = groups[j], i = group.length - 1, next = group[i], node; --i >= 0;) {
402
+ if (node = group[i]) {
403
+ if (next && node.compareDocumentPosition(next) ^ 4) next.parentNode.insertBefore(node, next);
404
+ next = node;
405
+ }
406
+ }
407
+ }
408
+
409
+ return this;
410
+ }
411
+
412
+ function selection_sort(compare) {
413
+ if (!compare) compare = ascending$1;
414
+
415
+ function compareNode(a, b) {
416
+ return a && b ? compare(a.__data__, b.__data__) : !a - !b;
417
+ }
418
+
419
+ for (var groups = this._groups, m = groups.length, sortgroups = new Array(m), j = 0; j < m; ++j) {
420
+ for (var group = groups[j], n = group.length, sortgroup = sortgroups[j] = new Array(n), node, i = 0; i < n; ++i) {
421
+ if (node = group[i]) {
422
+ sortgroup[i] = node;
423
+ }
424
+ }
425
+ sortgroup.sort(compareNode);
426
+ }
427
+
428
+ return new Selection(sortgroups, this._parents).order();
429
+ }
430
+
431
+ function ascending$1(a, b) {
432
+ return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
433
+ }
434
+
435
+ function selection_call() {
436
+ var callback = arguments[0];
437
+ arguments[0] = this;
438
+ callback.apply(null, arguments);
439
+ return this;
440
+ }
441
+
442
+ function selection_nodes() {
443
+ return Array.from(this);
444
+ }
445
+
446
+ function selection_node() {
447
+
448
+ for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {
449
+ for (var group = groups[j], i = 0, n = group.length; i < n; ++i) {
450
+ var node = group[i];
451
+ if (node) return node;
452
+ }
453
+ }
454
+
455
+ return null;
456
+ }
457
+
458
+ function selection_size() {
459
+ let size = 0;
460
+ for (const node of this) ++size; // eslint-disable-line no-unused-vars
461
+ return size;
462
+ }
463
+
464
+ function selection_empty() {
465
+ return !this.node();
466
+ }
467
+
468
+ function selection_each(callback) {
469
+
470
+ for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {
471
+ for (var group = groups[j], i = 0, n = group.length, node; i < n; ++i) {
472
+ if (node = group[i]) callback.call(node, node.__data__, i, group);
473
+ }
474
+ }
475
+
476
+ return this;
477
+ }
478
+
479
+ function attrRemove(name) {
480
+ return function() {
481
+ this.removeAttribute(name);
482
+ };
483
+ }
484
+
485
+ function attrRemoveNS(fullname) {
486
+ return function() {
487
+ this.removeAttributeNS(fullname.space, fullname.local);
488
+ };
489
+ }
490
+
491
+ function attrConstant(name, value) {
492
+ return function() {
493
+ this.setAttribute(name, value);
494
+ };
495
+ }
496
+
497
+ function attrConstantNS(fullname, value) {
498
+ return function() {
499
+ this.setAttributeNS(fullname.space, fullname.local, value);
500
+ };
501
+ }
502
+
503
+ function attrFunction(name, value) {
504
+ return function() {
505
+ var v = value.apply(this, arguments);
506
+ if (v == null) this.removeAttribute(name);
507
+ else this.setAttribute(name, v);
508
+ };
509
+ }
510
+
511
+ function attrFunctionNS(fullname, value) {
512
+ return function() {
513
+ var v = value.apply(this, arguments);
514
+ if (v == null) this.removeAttributeNS(fullname.space, fullname.local);
515
+ else this.setAttributeNS(fullname.space, fullname.local, v);
516
+ };
517
+ }
518
+
519
+ function selection_attr(name, value) {
520
+ var fullname = namespace(name);
521
+
522
+ if (arguments.length < 2) {
523
+ var node = this.node();
524
+ return fullname.local
525
+ ? node.getAttributeNS(fullname.space, fullname.local)
526
+ : node.getAttribute(fullname);
527
+ }
528
+
529
+ return this.each((value == null
530
+ ? (fullname.local ? attrRemoveNS : attrRemove) : (typeof value === "function"
531
+ ? (fullname.local ? attrFunctionNS : attrFunction)
532
+ : (fullname.local ? attrConstantNS : attrConstant)))(fullname, value));
533
+ }
534
+
535
+ function defaultView(node) {
536
+ return (node.ownerDocument && node.ownerDocument.defaultView) // node is a Node
537
+ || (node.document && node) // node is a Window
538
+ || node.defaultView; // node is a Document
539
+ }
540
+
541
+ function styleRemove(name) {
542
+ return function() {
543
+ this.style.removeProperty(name);
544
+ };
545
+ }
546
+
547
+ function styleConstant(name, value, priority) {
548
+ return function() {
549
+ this.style.setProperty(name, value, priority);
550
+ };
551
+ }
552
+
553
+ function styleFunction(name, value, priority) {
554
+ return function() {
555
+ var v = value.apply(this, arguments);
556
+ if (v == null) this.style.removeProperty(name);
557
+ else this.style.setProperty(name, v, priority);
558
+ };
559
+ }
560
+
561
+ function selection_style(name, value, priority) {
562
+ return arguments.length > 1
563
+ ? this.each((value == null
564
+ ? styleRemove : typeof value === "function"
565
+ ? styleFunction
566
+ : styleConstant)(name, value, priority == null ? "" : priority))
567
+ : styleValue(this.node(), name);
568
+ }
569
+
570
+ function styleValue(node, name) {
571
+ return node.style.getPropertyValue(name)
572
+ || defaultView(node).getComputedStyle(node, null).getPropertyValue(name);
573
+ }
574
+
575
+ function propertyRemove(name) {
576
+ return function() {
577
+ delete this[name];
578
+ };
579
+ }
580
+
581
+ function propertyConstant(name, value) {
582
+ return function() {
583
+ this[name] = value;
584
+ };
585
+ }
586
+
587
+ function propertyFunction(name, value) {
588
+ return function() {
589
+ var v = value.apply(this, arguments);
590
+ if (v == null) delete this[name];
591
+ else this[name] = v;
592
+ };
593
+ }
594
+
595
+ function selection_property(name, value) {
596
+ return arguments.length > 1
597
+ ? this.each((value == null
598
+ ? propertyRemove : typeof value === "function"
599
+ ? propertyFunction
600
+ : propertyConstant)(name, value))
601
+ : this.node()[name];
602
+ }
603
+
604
+ function classArray(string) {
605
+ return string.trim().split(/^|\s+/);
606
+ }
607
+
608
+ function classList(node) {
609
+ return node.classList || new ClassList(node);
610
+ }
611
+
612
+ function ClassList(node) {
613
+ this._node = node;
614
+ this._names = classArray(node.getAttribute("class") || "");
615
+ }
616
+
617
+ ClassList.prototype = {
618
+ add: function(name) {
619
+ var i = this._names.indexOf(name);
620
+ if (i < 0) {
621
+ this._names.push(name);
622
+ this._node.setAttribute("class", this._names.join(" "));
623
+ }
624
+ },
625
+ remove: function(name) {
626
+ var i = this._names.indexOf(name);
627
+ if (i >= 0) {
628
+ this._names.splice(i, 1);
629
+ this._node.setAttribute("class", this._names.join(" "));
630
+ }
631
+ },
632
+ contains: function(name) {
633
+ return this._names.indexOf(name) >= 0;
634
+ }
635
+ };
636
+
637
+ function classedAdd(node, names) {
638
+ var list = classList(node), i = -1, n = names.length;
639
+ while (++i < n) list.add(names[i]);
640
+ }
641
+
642
+ function classedRemove(node, names) {
643
+ var list = classList(node), i = -1, n = names.length;
644
+ while (++i < n) list.remove(names[i]);
645
+ }
646
+
647
+ function classedTrue(names) {
648
+ return function() {
649
+ classedAdd(this, names);
650
+ };
651
+ }
652
+
653
+ function classedFalse(names) {
654
+ return function() {
655
+ classedRemove(this, names);
656
+ };
657
+ }
658
+
659
+ function classedFunction(names, value) {
660
+ return function() {
661
+ (value.apply(this, arguments) ? classedAdd : classedRemove)(this, names);
662
+ };
663
+ }
664
+
665
+ function selection_classed(name, value) {
666
+ var names = classArray(name + "");
667
+
668
+ if (arguments.length < 2) {
669
+ var list = classList(this.node()), i = -1, n = names.length;
670
+ while (++i < n) if (!list.contains(names[i])) return false;
671
+ return true;
672
+ }
673
+
674
+ return this.each((typeof value === "function"
675
+ ? classedFunction : value
676
+ ? classedTrue
677
+ : classedFalse)(names, value));
678
+ }
679
+
680
+ function textRemove() {
681
+ this.textContent = "";
682
+ }
683
+
684
+ function textConstant(value) {
685
+ return function() {
686
+ this.textContent = value;
687
+ };
688
+ }
689
+
690
+ function textFunction(value) {
691
+ return function() {
692
+ var v = value.apply(this, arguments);
693
+ this.textContent = v == null ? "" : v;
694
+ };
695
+ }
696
+
697
+ function selection_text(value) {
698
+ return arguments.length
699
+ ? this.each(value == null
700
+ ? textRemove : (typeof value === "function"
701
+ ? textFunction
702
+ : textConstant)(value))
703
+ : this.node().textContent;
704
+ }
705
+
706
+ function htmlRemove() {
707
+ this.innerHTML = "";
708
+ }
709
+
710
+ function htmlConstant(value) {
711
+ return function() {
712
+ this.innerHTML = value;
713
+ };
714
+ }
715
+
716
+ function htmlFunction(value) {
717
+ return function() {
718
+ var v = value.apply(this, arguments);
719
+ this.innerHTML = v == null ? "" : v;
720
+ };
721
+ }
722
+
723
+ function selection_html(value) {
724
+ return arguments.length
725
+ ? this.each(value == null
726
+ ? htmlRemove : (typeof value === "function"
727
+ ? htmlFunction
728
+ : htmlConstant)(value))
729
+ : this.node().innerHTML;
730
+ }
731
+
732
+ function raise() {
733
+ if (this.nextSibling) this.parentNode.appendChild(this);
734
+ }
735
+
736
+ function selection_raise() {
737
+ return this.each(raise);
738
+ }
739
+
740
+ function lower() {
741
+ if (this.previousSibling) this.parentNode.insertBefore(this, this.parentNode.firstChild);
742
+ }
743
+
744
+ function selection_lower() {
745
+ return this.each(lower);
746
+ }
747
+
748
+ function selection_append(name) {
749
+ var create = typeof name === "function" ? name : creator(name);
750
+ return this.select(function() {
751
+ return this.appendChild(create.apply(this, arguments));
752
+ });
753
+ }
754
+
755
+ function constantNull() {
756
+ return null;
757
+ }
758
+
759
+ function selection_insert(name, before) {
760
+ var create = typeof name === "function" ? name : creator(name),
761
+ select = before == null ? constantNull : typeof before === "function" ? before : selector(before);
762
+ return this.select(function() {
763
+ return this.insertBefore(create.apply(this, arguments), select.apply(this, arguments) || null);
764
+ });
765
+ }
766
+
767
+ function remove() {
768
+ var parent = this.parentNode;
769
+ if (parent) parent.removeChild(this);
770
+ }
771
+
772
+ function selection_remove() {
773
+ return this.each(remove);
774
+ }
775
+
776
+ function selection_cloneShallow() {
777
+ var clone = this.cloneNode(false), parent = this.parentNode;
778
+ return parent ? parent.insertBefore(clone, this.nextSibling) : clone;
779
+ }
780
+
781
+ function selection_cloneDeep() {
782
+ var clone = this.cloneNode(true), parent = this.parentNode;
783
+ return parent ? parent.insertBefore(clone, this.nextSibling) : clone;
784
+ }
785
+
786
+ function selection_clone(deep) {
787
+ return this.select(deep ? selection_cloneDeep : selection_cloneShallow);
788
+ }
789
+
790
+ function selection_datum(value) {
791
+ return arguments.length
792
+ ? this.property("__data__", value)
793
+ : this.node().__data__;
794
+ }
795
+
796
+ function contextListener(listener) {
797
+ return function(event) {
798
+ listener.call(this, event, this.__data__);
799
+ };
800
+ }
801
+
802
+ function parseTypenames(typenames) {
803
+ return typenames.trim().split(/^|\s+/).map(function(t) {
804
+ var name = "", i = t.indexOf(".");
805
+ if (i >= 0) name = t.slice(i + 1), t = t.slice(0, i);
806
+ return {type: t, name: name};
807
+ });
808
+ }
809
+
810
+ function onRemove(typename) {
811
+ return function() {
812
+ var on = this.__on;
813
+ if (!on) return;
814
+ for (var j = 0, i = -1, m = on.length, o; j < m; ++j) {
815
+ if (o = on[j], (!typename.type || o.type === typename.type) && o.name === typename.name) {
816
+ this.removeEventListener(o.type, o.listener, o.options);
817
+ } else {
818
+ on[++i] = o;
819
+ }
820
+ }
821
+ if (++i) on.length = i;
822
+ else delete this.__on;
823
+ };
824
+ }
825
+
826
+ function onAdd(typename, value, options) {
827
+ return function() {
828
+ var on = this.__on, o, listener = contextListener(value);
829
+ if (on) for (var j = 0, m = on.length; j < m; ++j) {
830
+ if ((o = on[j]).type === typename.type && o.name === typename.name) {
831
+ this.removeEventListener(o.type, o.listener, o.options);
832
+ this.addEventListener(o.type, o.listener = listener, o.options = options);
833
+ o.value = value;
834
+ return;
835
+ }
836
+ }
837
+ this.addEventListener(typename.type, listener, options);
838
+ o = {type: typename.type, name: typename.name, value: value, listener: listener, options: options};
839
+ if (!on) this.__on = [o];
840
+ else on.push(o);
841
+ };
842
+ }
843
+
844
+ function selection_on(typename, value, options) {
845
+ var typenames = parseTypenames(typename + ""), i, n = typenames.length, t;
846
+
847
+ if (arguments.length < 2) {
848
+ var on = this.node().__on;
849
+ if (on) for (var j = 0, m = on.length, o; j < m; ++j) {
850
+ for (i = 0, o = on[j]; i < n; ++i) {
851
+ if ((t = typenames[i]).type === o.type && t.name === o.name) {
852
+ return o.value;
853
+ }
854
+ }
855
+ }
856
+ return;
857
+ }
858
+
859
+ on = value ? onAdd : onRemove;
860
+ for (i = 0; i < n; ++i) this.each(on(typenames[i], value, options));
861
+ return this;
862
+ }
863
+
864
+ function dispatchEvent(node, type, params) {
865
+ var window = defaultView(node),
866
+ event = window.CustomEvent;
867
+
868
+ if (typeof event === "function") {
869
+ event = new event(type, params);
870
+ } else {
871
+ event = window.document.createEvent("Event");
872
+ if (params) event.initEvent(type, params.bubbles, params.cancelable), event.detail = params.detail;
873
+ else event.initEvent(type, false, false);
874
+ }
875
+
876
+ node.dispatchEvent(event);
877
+ }
878
+
879
+ function dispatchConstant(type, params) {
880
+ return function() {
881
+ return dispatchEvent(this, type, params);
882
+ };
883
+ }
884
+
885
+ function dispatchFunction(type, params) {
886
+ return function() {
887
+ return dispatchEvent(this, type, params.apply(this, arguments));
888
+ };
889
+ }
890
+
891
+ function selection_dispatch(type, params) {
892
+ return this.each((typeof params === "function"
893
+ ? dispatchFunction
894
+ : dispatchConstant)(type, params));
895
+ }
896
+
897
+ function* selection_iterator() {
898
+ for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {
899
+ for (var group = groups[j], i = 0, n = group.length, node; i < n; ++i) {
900
+ if (node = group[i]) yield node;
901
+ }
902
+ }
903
+ }
904
+
905
+ var root = [null];
906
+
907
+ function Selection(groups, parents) {
908
+ this._groups = groups;
909
+ this._parents = parents;
910
+ }
911
+
912
+ function selection_selection() {
913
+ return this;
914
+ }
915
+
916
+ Selection.prototype = {
917
+ constructor: Selection,
918
+ select: selection_select,
919
+ selectAll: selection_selectAll,
920
+ selectChild: selection_selectChild,
921
+ selectChildren: selection_selectChildren,
922
+ filter: selection_filter,
923
+ data: selection_data,
924
+ enter: selection_enter,
925
+ exit: selection_exit,
926
+ join: selection_join,
927
+ merge: selection_merge,
928
+ selection: selection_selection,
929
+ order: selection_order,
930
+ sort: selection_sort,
931
+ call: selection_call,
932
+ nodes: selection_nodes,
933
+ node: selection_node,
934
+ size: selection_size,
935
+ empty: selection_empty,
936
+ each: selection_each,
937
+ attr: selection_attr,
938
+ style: selection_style,
939
+ property: selection_property,
940
+ classed: selection_classed,
941
+ text: selection_text,
942
+ html: selection_html,
943
+ raise: selection_raise,
944
+ lower: selection_lower,
945
+ append: selection_append,
946
+ insert: selection_insert,
947
+ remove: selection_remove,
948
+ clone: selection_clone,
949
+ datum: selection_datum,
950
+ on: selection_on,
951
+ dispatch: selection_dispatch,
952
+ [Symbol.iterator]: selection_iterator
953
+ };
954
+
955
+ function select(selector) {
956
+ return typeof selector === "string"
957
+ ? new Selection([[document.querySelector(selector)]], [document.documentElement])
958
+ : new Selection([[selector]], root);
959
+ }
960
+
961
+ function sourceEvent(event) {
962
+ let sourceEvent;
963
+ while (sourceEvent = event.sourceEvent) event = sourceEvent;
964
+ return event;
965
+ }
966
+
967
+ function pointer(event, node) {
968
+ event = sourceEvent(event);
969
+ if (node === undefined) node = event.currentTarget;
970
+ if (node) {
971
+ var svg = node.ownerSVGElement || node;
972
+ if (svg.createSVGPoint) {
973
+ var point = svg.createSVGPoint();
974
+ point.x = event.clientX, point.y = event.clientY;
975
+ point = point.matrixTransform(node.getScreenCTM().inverse());
976
+ return [point.x, point.y];
977
+ }
978
+ if (node.getBoundingClientRect) {
979
+ var rect = node.getBoundingClientRect();
980
+ return [event.clientX - rect.left - node.clientLeft, event.clientY - rect.top - node.clientTop];
981
+ }
982
+ }
983
+ return [event.pageX, event.pageY];
984
+ }
985
+
986
+ function count(node) {
987
+ var sum = 0,
988
+ children = node.children,
989
+ i = children && children.length;
990
+ if (!i) sum = 1;
991
+ else while (--i >= 0) sum += children[i].value;
992
+ node.value = sum;
993
+ }
994
+
995
+ function node_count() {
996
+ return this.eachAfter(count);
997
+ }
998
+
999
+ function node_each(callback, that) {
1000
+ let index = -1;
1001
+ for (const node of this) {
1002
+ callback.call(that, node, ++index, this);
1003
+ }
1004
+ return this;
1005
+ }
1006
+
1007
+ function node_eachBefore(callback, that) {
1008
+ var node = this, nodes = [node], children, i, index = -1;
1009
+ while (node = nodes.pop()) {
1010
+ callback.call(that, node, ++index, this);
1011
+ if (children = node.children) {
1012
+ for (i = children.length - 1; i >= 0; --i) {
1013
+ nodes.push(children[i]);
1014
+ }
1015
+ }
1016
+ }
1017
+ return this;
1018
+ }
1019
+
1020
+ function node_eachAfter(callback, that) {
1021
+ var node = this, nodes = [node], next = [], children, i, n, index = -1;
1022
+ while (node = nodes.pop()) {
1023
+ next.push(node);
1024
+ if (children = node.children) {
1025
+ for (i = 0, n = children.length; i < n; ++i) {
1026
+ nodes.push(children[i]);
1027
+ }
1028
+ }
1029
+ }
1030
+ while (node = next.pop()) {
1031
+ callback.call(that, node, ++index, this);
1032
+ }
1033
+ return this;
1034
+ }
1035
+
1036
+ function node_find(callback, that) {
1037
+ let index = -1;
1038
+ for (const node of this) {
1039
+ if (callback.call(that, node, ++index, this)) {
1040
+ return node;
1041
+ }
1042
+ }
1043
+ }
1044
+
1045
+ function node_sum(value) {
1046
+ return this.eachAfter(function(node) {
1047
+ var sum = +value(node.data) || 0,
1048
+ children = node.children,
1049
+ i = children && children.length;
1050
+ while (--i >= 0) sum += children[i].value;
1051
+ node.value = sum;
1052
+ });
1053
+ }
1054
+
1055
+ function node_sort(compare) {
1056
+ return this.eachBefore(function(node) {
1057
+ if (node.children) {
1058
+ node.children.sort(compare);
1059
+ }
1060
+ });
1061
+ }
1062
+
1063
+ function node_path(end) {
1064
+ var start = this,
1065
+ ancestor = leastCommonAncestor(start, end),
1066
+ nodes = [start];
1067
+ while (start !== ancestor) {
1068
+ start = start.parent;
1069
+ nodes.push(start);
1070
+ }
1071
+ var k = nodes.length;
1072
+ while (end !== ancestor) {
1073
+ nodes.splice(k, 0, end);
1074
+ end = end.parent;
1075
+ }
1076
+ return nodes;
1077
+ }
1078
+
1079
+ function leastCommonAncestor(a, b) {
1080
+ if (a === b) return a;
1081
+ var aNodes = a.ancestors(),
1082
+ bNodes = b.ancestors(),
1083
+ c = null;
1084
+ a = aNodes.pop();
1085
+ b = bNodes.pop();
1086
+ while (a === b) {
1087
+ c = a;
1088
+ a = aNodes.pop();
1089
+ b = bNodes.pop();
1090
+ }
1091
+ return c;
1092
+ }
1093
+
1094
+ function node_ancestors() {
1095
+ var node = this, nodes = [node];
1096
+ while (node = node.parent) {
1097
+ nodes.push(node);
1098
+ }
1099
+ return nodes;
1100
+ }
1101
+
1102
+ function node_descendants() {
1103
+ return Array.from(this);
1104
+ }
1105
+
1106
+ function node_leaves() {
1107
+ var leaves = [];
1108
+ this.eachBefore(function(node) {
1109
+ if (!node.children) {
1110
+ leaves.push(node);
1111
+ }
1112
+ });
1113
+ return leaves;
1114
+ }
1115
+
1116
+ function node_links() {
1117
+ var root = this, links = [];
1118
+ root.each(function(node) {
1119
+ if (node !== root) { // Don’t include the root’s parent, if any.
1120
+ links.push({source: node.parent, target: node});
1121
+ }
1122
+ });
1123
+ return links;
1124
+ }
1125
+
1126
+ function* node_iterator() {
1127
+ var node = this, current, next = [node], children, i, n;
1128
+ do {
1129
+ current = next.reverse(), next = [];
1130
+ while (node = current.pop()) {
1131
+ yield node;
1132
+ if (children = node.children) {
1133
+ for (i = 0, n = children.length; i < n; ++i) {
1134
+ next.push(children[i]);
1135
+ }
1136
+ }
1137
+ }
1138
+ } while (next.length);
1139
+ }
1140
+
1141
+ function hierarchy(data, children) {
1142
+ if (data instanceof Map) {
1143
+ data = [undefined, data];
1144
+ if (children === undefined) children = mapChildren;
1145
+ } else if (children === undefined) {
1146
+ children = objectChildren;
1147
+ }
1148
+
1149
+ var root = new Node(data),
1150
+ node,
1151
+ nodes = [root],
1152
+ child,
1153
+ childs,
1154
+ i,
1155
+ n;
1156
+
1157
+ while (node = nodes.pop()) {
1158
+ if ((childs = children(node.data)) && (n = (childs = Array.from(childs)).length)) {
1159
+ node.children = childs;
1160
+ for (i = n - 1; i >= 0; --i) {
1161
+ nodes.push(child = childs[i] = new Node(childs[i]));
1162
+ child.parent = node;
1163
+ child.depth = node.depth + 1;
1164
+ }
1165
+ }
1166
+ }
1167
+
1168
+ return root.eachBefore(computeHeight);
1169
+ }
1170
+
1171
+ function node_copy() {
1172
+ return hierarchy(this).eachBefore(copyData);
1173
+ }
1174
+
1175
+ function objectChildren(d) {
1176
+ return d.children;
1177
+ }
1178
+
1179
+ function mapChildren(d) {
1180
+ return Array.isArray(d) ? d[1] : null;
1181
+ }
1182
+
1183
+ function copyData(node) {
1184
+ if (node.data.value !== undefined) node.value = node.data.value;
1185
+ node.data = node.data.data;
1186
+ }
1187
+
1188
+ function computeHeight(node) {
1189
+ var height = 0;
1190
+ do node.height = height;
1191
+ while ((node = node.parent) && (node.height < ++height));
1192
+ }
1193
+
1194
+ function Node(data) {
1195
+ this.data = data;
1196
+ this.depth =
1197
+ this.height = 0;
1198
+ this.parent = null;
1199
+ }
1200
+
1201
+ Node.prototype = hierarchy.prototype = {
1202
+ constructor: Node,
1203
+ count: node_count,
1204
+ each: node_each,
1205
+ eachAfter: node_eachAfter,
1206
+ eachBefore: node_eachBefore,
1207
+ find: node_find,
1208
+ sum: node_sum,
1209
+ sort: node_sort,
1210
+ path: node_path,
1211
+ ancestors: node_ancestors,
1212
+ descendants: node_descendants,
1213
+ leaves: node_leaves,
1214
+ links: node_links,
1215
+ copy: node_copy,
1216
+ [Symbol.iterator]: node_iterator
1217
+ };
1218
+
1219
+ /**
1220
+ * Input normalization: both accepted input shapes collapse into ONE decorated
1221
+ * `d3.hierarchy`, so every layout strategy and every renderer downstream sees
1222
+ * exactly one data structure.
1223
+ *
1224
+ * A) flat rows + keys { data: [...], keys: ["year","month","day"] }
1225
+ * B) nested tree { root: {...}, children: d => d.children }
1226
+ *
1227
+ * (A) is the "tidy long table" form — a sorted list of value-tuples, which is
1228
+ * what a single SQL `GROUP BY` hands you. (B) is for ragged/precomputed trees.
1229
+ */
1230
+
1231
+
1232
+ /** Field on every node.data. `value` is the node's own key-value (e.g. "2024"),
1233
+ * NOT a count — counts live on `node.count`.
1234
+ * @typedef {{key: string|null, value: any, label: string, row: any}} NodeDatum */
1235
+
1236
+ // A separator that cannot occur inside a key or a value. Written as an ESCAPE,
1237
+ // never as a literal NUL byte: a raw \0 in the source makes the whole file look
1238
+ // like binary data, and grep silently reports no matches in it. That cost an hour.
1239
+ const PATH_SEP = "\u0000";
1240
+
1241
+ /**
1242
+ * The id of a path — the ONE place it is spelled.
1243
+ *
1244
+ * `fisheyeNav` used to build the selected id by joining with a space while the
1245
+ * rows joined with PATH_SEP, so a selection deeper than one level could never
1246
+ * match a row: selecting a DAY never highlighted it, and never labelled it. It
1247
+ * hid because the only test selected a depth-1 path, where the two joins produce
1248
+ * the same string.
1249
+ */
1250
+ const idOfPath = (path) =>
1251
+ path.map((p) => p.key + "=" + p.value).join(PATH_SEP);
1252
+
1253
+ /**
1254
+ * Roll a flat, pre-sorted row list up into a nested tree, preserving the row
1255
+ * order as the child order at every level. Order matters: the host (AutoGallery)
1256
+ * hands us rows already sorted the way its feed is sorted, and the navigator
1257
+ * must mirror that exactly — so we never re-sort, we just group.
1258
+ */
1259
+ function rollup(rows, keys, valueOf, countOf) {
1260
+ const root = { key: null, value: null, children: [], row: null };
1261
+ const byPath = new Map([["", root]]);
1262
+
1263
+ for (const row of rows) {
1264
+ let node = root;
1265
+ let path = "";
1266
+ for (const key of keys) {
1267
+ const value = valueOf(row, key);
1268
+ path += PATH_SEP + key + "=" + value;
1269
+ let child = byPath.get(path);
1270
+ if (!child) {
1271
+ child = { key, value, children: [], row: null };
1272
+ byPath.set(path, child);
1273
+ node.children.push(child);
1274
+ }
1275
+ node = child;
1276
+ }
1277
+ // `node` is now the leaf for this row's key-tuple. Several rows can land on
1278
+ // the same leaf; their counts add up and the last row wins as the exemplar.
1279
+ node.row = row;
1280
+ node.ownCount = (node.ownCount ?? 0) + countOf(row);
1281
+ }
1282
+ return root;
1283
+ }
1284
+
1285
+ /**
1286
+ * Give every internal node a synthetic HEADER pseudo-leaf as its first child.
1287
+ *
1288
+ * This is what makes the flat (indented outline) view possible without a second
1289
+ * layout engine. The layout distributes pixels over the LEAF axis, and a
1290
+ * parent's band is exactly the span of its children — so there is no vertical
1291
+ * space anywhere for a parent's own label to live. In an icicle that's fine (the
1292
+ * parent owns a column); in a flat list it means an internal node has no row,
1293
+ * and with nothing to indent relative to, "indent by level" says nothing.
1294
+ *
1295
+ * A header cell costs one slot on the leaf axis and carries `count: 0`, so mass
1296
+ * conservation is untouched, and it sits INSIDE its parent's interval, so
1297
+ * containment is untouched. Every downstream stage needs zero changes.
1298
+ */
1299
+ function withHeaders(raw, childrenOf, isRoot = true) {
1300
+ const kids = childrenOf(raw);
1301
+ if (!kids?.length) return raw;
1302
+ const nested = kids.map((k) => withHeaders(k, childrenOf, false));
1303
+ // The root is never drawn (depth 0), so a header for it would surface as a
1304
+ // stray depth-1 row labelled with nothing.
1305
+ if (isRoot) return { ...raw, children: nested };
1306
+ return {
1307
+ ...raw,
1308
+ children: [{ __header: true, __of: raw, children: null }, ...nested],
1309
+ };
1310
+ }
1311
+
1312
+ /** Depth-first, in child order. */
1313
+ function walk(node, visit) {
1314
+ visit(node);
1315
+ if (node.children) for (const c of node.children) walk(c, visit);
1316
+ }
1317
+
1318
+ /**
1319
+ * Decorate a d3.hierarchy in place with everything the layouts and renderers
1320
+ * need, so neither has to re-derive it:
1321
+ * node.count photo mass (leaf: from the data; internal: sum of children)
1322
+ * node.leafStart index of its first descendant leaf } the interval the
1323
+ * node.leafEnd index past its last descendant leaf } fisheye distorts
1324
+ * node.path [{key, value}, …] from the root down to this node
1325
+ * node.id stable string id (survives relayout; keys the DOM)
1326
+ * node.label display string
1327
+ *
1328
+ * `leafStart`/`leafEnd` are the load-bearing bit of the redesign: once every
1329
+ * node owns a LEAF INTERVAL, a parent's band is just the union of its children's
1330
+ * bands, and "parents contain their children" stops being something a renderer
1331
+ * has to be careful about and becomes true by construction.
1332
+ */
1333
+ function decorate(root, labelOf) {
1334
+ const leaves = [];
1335
+ walk(root, (n) => {
1336
+ if (!n.children?.length) leaves.push(n);
1337
+ });
1338
+
1339
+ leaves.forEach((leaf, i) => {
1340
+ leaf.leafStart = i;
1341
+ leaf.leafEnd = i + 1;
1342
+ });
1343
+
1344
+ // Pre-order: a node's path extends its PARENT's, so parents go first.
1345
+ root.eachBefore((n) => {
1346
+ const d = n.data;
1347
+ // Coerce here, once. A host's `label` accessor is arbitrary user code and
1348
+ // may well return undefined for a key it doesn't know about (an unknown
1349
+ // dimension, the synthetic root's null key). The renderer must never be the
1350
+ // place that discovers this — a widget that throws because a consumer's
1351
+ // accessor came back empty is a broken widget.
1352
+ n.label = String(labelOf(d.value, d.key, n) ?? d.value ?? "");
1353
+ if (d.header) {
1354
+ // A header stands in for its parent: same path (so clicking it selects the
1355
+ // parent, which is what you mean when you click "2024"), distinct id.
1356
+ n.keyPath = n.parent.keyPath;
1357
+ n.id = n.parent.id + "#header";
1358
+ return;
1359
+ }
1360
+ // `keyPath`, NOT `path` — d3's HierarchyNode already has a `.path(target)`
1361
+ // method, and an own property would silently shadow it.
1362
+ n.keyPath =
1363
+ n.depth === 0
1364
+ ? []
1365
+ : [...n.parent.keyPath, { key: d.key, value: d.value }];
1366
+ n.id = idOfPath(n.keyPath);
1367
+ });
1368
+
1369
+ // Post-order: a node's count and leaf interval aggregate its CHILDREN's, so
1370
+ // children go first.
1371
+ root.eachAfter((n) => {
1372
+ if (!n.children?.length) {
1373
+ n.count = n.data.ownCount ?? n.data.count ?? 0;
1374
+ return;
1375
+ }
1376
+ n.count = 0;
1377
+ n.leafStart = Infinity;
1378
+ n.leafEnd = -Infinity;
1379
+ for (const c of n.children) {
1380
+ n.count += c.count;
1381
+ if (c.leafStart < n.leafStart) n.leafStart = c.leafStart;
1382
+ if (c.leafEnd > n.leafEnd) n.leafEnd = c.leafEnd;
1383
+ }
1384
+ });
1385
+
1386
+ root.leaves_ = leaves;
1387
+ return root;
1388
+ }
1389
+
1390
+ const defaultLabel = (value) => (value == null ? "" : String(value));
1391
+
1392
+ /**
1393
+ * Normalize either input shape into one decorated hierarchy.
1394
+ *
1395
+ * @param {object} spec
1396
+ * @param {any[]} [spec.data] flat, pre-sorted rows (shape A)
1397
+ * @param {string[]} [spec.keys] the levels, outermost first (shape A)
1398
+ * @param {any} [spec.root] a nested tree (shape B)
1399
+ * @param {(d:any)=>any[]} [spec.children] child accessor (shape B)
1400
+ * @param {(row:any, key:string)=>any} [spec.value] how to read a key off a row
1401
+ * @param {(d:any)=>number} [spec.count] leaf mass; defaults to `d.count ?? 1`
1402
+ * @param {(value:any, key:string, node:any)=>string} [spec.label]
1403
+ * @returns {import("d3-hierarchy").HierarchyNode<NodeDatum> & {leaves_: any[]}}
1404
+ */
1405
+ function normalize$1(spec = {}) {
1406
+ const {
1407
+ data,
1408
+ keys,
1409
+ root: treeRoot,
1410
+ children = (d) => d.children,
1411
+ value = (row, key) => row[key],
1412
+ count = (d) => d.count ?? 1,
1413
+ label = defaultLabel,
1414
+ headers = false,
1415
+ } = spec;
1416
+
1417
+ const maybeHeaders = (raw, childrenOf) =>
1418
+ headers ? withHeaders(raw, childrenOf) : raw;
1419
+
1420
+ let root;
1421
+ if (treeRoot != null) {
1422
+ root = hierarchy(maybeHeaders(treeRoot, children), (d) =>
1423
+ headers ? d.children : children(d),
1424
+ );
1425
+ // Shape B nodes carry their own key/value/count; mirror them onto the
1426
+ // NodeDatum contract so `decorate` and the renderers stay shape-agnostic.
1427
+ root.each((n) => {
1428
+ const d = n.data ?? {};
1429
+ const of = d.__header ? d.__of : d;
1430
+ n.data = {
1431
+ key: of.key ?? null,
1432
+ value: of.value ?? of.name ?? of.id ?? null,
1433
+ row: of,
1434
+ header: !!d.__header,
1435
+ ownCount: d.__header ? 0 : n.children?.length ? undefined : count(of),
1436
+ };
1437
+ });
1438
+ } else if (Array.isArray(data) && Array.isArray(keys)) {
1439
+ root = hierarchy(
1440
+ maybeHeaders(rollup(data, keys, value, count), (d) => d.children),
1441
+ (d) => d.children,
1442
+ );
1443
+ if (headers) {
1444
+ root.each((n) => {
1445
+ if (!n.data.__header) return;
1446
+ const of = n.data.__of;
1447
+ n.data = {
1448
+ key: of.key,
1449
+ value: of.value,
1450
+ row: of.row,
1451
+ header: true,
1452
+ ownCount: 0,
1453
+ };
1454
+ });
1455
+ }
1456
+ } else {
1457
+ // An empty widget is a normal state (no library loaded yet), not an error.
1458
+ root = hierarchy({ key: null, value: null, children: [], ownCount: 0 });
1459
+ }
1460
+
1461
+ return decorate(root, label);
1462
+ }
1463
+
1464
+ /** The ordered leaf list — the sequence the fisheye lens distorts. */
1465
+ function leavesOf(root) {
1466
+ return root.leaves_ ?? root.leaves();
1467
+ }
1468
+
1469
+ /** Every node except the synthetic root, in depth-first (visual) order. */
1470
+ function nodesOf(root) {
1471
+ const out = [];
1472
+ walk(root, (n) => {
1473
+ if (n.depth > 0) out.push(n);
1474
+ });
1475
+ return out;
1476
+ }
1477
+
1478
+ /**
1479
+ * Stage 1: choose the SLOTS — the contiguous partition of the leaf axis that
1480
+ * the positioner lays out. A slot is one of:
1481
+ *
1482
+ * leaf one real leaf
1483
+ * collapsed one closed subtree, standing in for all its leaves ("2019 · 1,204")
1484
+ * elision a RUN of adjacent closed siblings, merged ("4 more groups")
1485
+ *
1486
+ * Two selectors, same output shape, so the positioner and renderers never learn
1487
+ * which one ran:
1488
+ *
1489
+ * selectAll every leaf is its own slot. Honest, proportional, no elision.
1490
+ * selectDOI Furnas degree-of-interest: score the leaves, keep the best ones
1491
+ * that fit the row budget, close everything else.
1492
+ *
1493
+ * Why score LEAVES and not internal nodes: a selector that can only choose which
1494
+ * subtrees to *open* cannot be bounded. To show the focused leaf you must open
1495
+ * its whole ancestor chain, and each open node drags in its siblings — on a
1496
+ * 10-year library that is already 48 rows before you have chosen anything. So
1497
+ * the budget has to bite at the leaf level, and structure falls out of it:
1498
+ * a node is open iff it still holds a kept leaf.
1499
+ */
1500
+
1501
+
1502
+ /** @typedef {{node: any|null, parent?: any, nodes?: any[], leafStart: number,
1503
+ * leafEnd: number, count?: number}} Slot */
1504
+
1505
+ /** One slot per leaf. Carries `count` like every other slot — `sizeBy: "count"`
1506
+ * weights the column by slot mass, and a slot without it silently weighs zero. */
1507
+ function selectAll(root) {
1508
+ return leavesOf(root).map((node) => ({
1509
+ node,
1510
+ leafStart: node.leafStart,
1511
+ leafEnd: node.leafEnd,
1512
+ count: node.count,
1513
+ }));
1514
+ }
1515
+
1516
+ /** Distance from a node's leaf interval to the focused leaf; 0 if it contains it. */
1517
+ function leafDistance(node, focusLeaf) {
1518
+ if (focusLeaf >= node.leafStart && focusLeaf < node.leafEnd) return 0;
1519
+ return focusLeaf < node.leafStart
1520
+ ? node.leafStart - focusLeaf
1521
+ : focusLeaf - (node.leafEnd - 1);
1522
+ }
1523
+
1524
+ /**
1525
+ * Hops from `a` up to the lowest common ancestor and back down to `b`. This is
1526
+ * Furnas's tree distance, and it is the thing a purely positional distance
1527
+ * cannot see: the day before the focused day might be three rows up but a whole
1528
+ * YEAR away in the tree, while the focused day's own siblings are structurally
1529
+ * adjacent no matter where they land on the axis.
1530
+ */
1531
+ function treeDistance(a, b) {
1532
+ let x = a;
1533
+ let y = b;
1534
+ let d = 0;
1535
+ while (x.depth > y.depth) {
1536
+ x = x.parent;
1537
+ d++;
1538
+ }
1539
+ while (y.depth > x.depth) {
1540
+ y = y.parent;
1541
+ d++;
1542
+ }
1543
+ while (x !== y && x.parent && y.parent) {
1544
+ x = x.parent;
1545
+ y = y.parent;
1546
+ d += 2;
1547
+ }
1548
+ return d;
1549
+ }
1550
+
1551
+ /**
1552
+ * Furnas's degree of interest: how badly does the user want to see this leaf,
1553
+ * given where they are looking?
1554
+ *
1555
+ * DOI(leaf) = importance(leaf) - distance(leaf, focus) + mass(leaf)
1556
+ *
1557
+ * Leaves are ranked by this and the best ones that fit the budget keep a full
1558
+ * row; the rest close into their ancestors. This function alone decides what a
1559
+ * DOI tree FEELS like, so each term is deliberate:
1560
+ *
1561
+ * - **importance** is depth measured RELATIVE to the focus, not absolutely. The
1562
+ * textbook `-depth` says a deep leaf matters less — true for the *root*'s
1563
+ * importance, false for leaves. In a ragged tree a depth-5 leaf isn't less
1564
+ * interesting than a depth-2 one, it's just more nested; what actually reads
1565
+ * badly is jumping between levels, so we penalise the level CHANGE.
1566
+ *
1567
+ * - **distance** blends the two notions of "far", because each alone fails:
1568
+ * the leaf axis alone gives a clean readable window but is blind to
1569
+ * structure; the tree alone keeps the focus's siblings but scatters the
1570
+ * survivors across the column. `treeWeight` slides between them.
1571
+ * Axis distance goes through `log1p` so the falloff is smooth — a linear
1572
+ * penalty makes rank flip sharply as the focus moves, which is exactly what
1573
+ * makes rows pop in and out while you drag the cursor.
1574
+ *
1575
+ * - **mass** is a weak tiebreaker, never a driver. Let it dominate and the lens
1576
+ * stops being about where you are and becomes a popularity chart.
1577
+ *
1578
+ * @param {any} leaf hierarchy node (.depth, .count, .leafStart, .leafEnd, .parent)
1579
+ * @param {{leaf: number, node: any}} focus focused leaf index and its node
1580
+ * @param {{apiWeight, distanceWeight, countWeight, treeWeight}} opts
1581
+ * @returns {number} higher = more interesting = more likely to keep its own row
1582
+ */
1583
+ function doiScore(leaf, focus, opts) {
1584
+ const importance = -Math.abs(leaf.depth - focus.node.depth) * opts.apiWeight;
1585
+
1586
+ const axis = Math.log1p(leafDistance(leaf, focus.leaf));
1587
+ const tree = treeDistance(leaf, focus.node);
1588
+ const t = opts.treeWeight;
1589
+ const distance = ((1 - t) * axis + t * tree) * opts.distanceWeight;
1590
+
1591
+ const mass = Math.log1p(leaf.count) * opts.countWeight;
1592
+
1593
+ return importance - distance + mass;
1594
+ }
1595
+
1596
+ /**
1597
+ * Keep the highest-DOI leaves that fit the row budget; close the rest.
1598
+ *
1599
+ * Guarantees the property tests lean on:
1600
+ * - slots partition [0, nLeaves) contiguously, so mass is always conserved;
1601
+ * - the focused leaf ALWAYS keeps its own slot — you can never lose the row you
1602
+ * are pointing at, whatever the budget;
1603
+ * - slot count <= budget (that is what the K search below is for).
1604
+ *
1605
+ * @param {any} root
1606
+ * @param {{budget: number, focusLeaf: number} & Record<string, number>} opts
1607
+ * @returns {Slot[]}
1608
+ */
1609
+ function selectDOI(root, opts) {
1610
+ const leaves = leavesOf(root);
1611
+ const n = leaves.length;
1612
+ if (!n) return [];
1613
+
1614
+ const budget = Math.max(1, Math.floor(opts.budget ?? n));
1615
+ if (n <= budget) return selectAll(root);
1616
+
1617
+ const focusLeaf = Math.max(0, Math.min(opts.focusLeaf ?? 0, n - 1));
1618
+ const focus = { leaf: focusLeaf, node: leaves[focusLeaf] };
1619
+
1620
+ // Rank once. Header cells are excluded: they are force-kept whenever their
1621
+ // node is open, so ranking them would just burn budget entries on rows we were
1622
+ // going to draw anyway. Ties break toward the focus, then by leaf order, so the
1623
+ // result is deterministic (a property test asserts it).
1624
+ const ranked = leaves
1625
+ .map((leaf, i) => ({ leaf, i, score: doiScore(leaf, focus, opts) }))
1626
+ .filter(({ leaf }) => !leaf.data?.header)
1627
+ .sort(
1628
+ (a, b) =>
1629
+ b.score - a.score ||
1630
+ Math.abs(a.i - focusLeaf) - Math.abs(b.i - focusLeaf) ||
1631
+ a.i - b.i,
1632
+ );
1633
+
1634
+ // Closing leaves ADDS rows back (a closed subtree is still one row), so K is
1635
+ // not simply the budget. Walk K down until the realized slot count fits. It
1636
+ // converges fast — closed rows only ever shrink as K shrinks.
1637
+ for (let K = Math.min(budget, n); K >= 1; K--) {
1638
+ const keep = new Set(ranked.slice(0, K).map((r) => r.leaf));
1639
+ keep.add(focus.node);
1640
+ const slots = buildSlots(root, keep);
1641
+ if (slots.length <= budget) return slots;
1642
+ }
1643
+ return buildSlots(root, new Set([focus.node]));
1644
+ }
1645
+
1646
+ /**
1647
+ * Turn a set of kept leaves into the slot partition.
1648
+ *
1649
+ * A node is OPEN iff it still contains a kept leaf. Under an open node, each
1650
+ * child is either open (recurse) or closed (one slot). Adjacent closed children
1651
+ * merge into a single elision slot — without that merge, a wide node whose
1652
+ * children are all closed would spend one row per child and blow the budget it
1653
+ * was supposed to be saving.
1654
+ */
1655
+ function buildSlots(root, keep) {
1656
+ const holdsKept = new Map();
1657
+ root.eachAfter((n) => {
1658
+ if (!n.children?.length) return holdsKept.set(n, keep.has(n));
1659
+ holdsKept.set(
1660
+ n,
1661
+ n.children.some((c) => holdsKept.get(c)),
1662
+ );
1663
+ });
1664
+
1665
+ const slots = [];
1666
+ let run = null; // the closed run currently being accumulated
1667
+
1668
+ const flush = () => {
1669
+ if (!run) return;
1670
+ slots.push(
1671
+ run.nodes.length === 1
1672
+ ? {
1673
+ node: run.nodes[0],
1674
+ leafStart: run.leafStart,
1675
+ leafEnd: run.leafEnd,
1676
+ count: run.count,
1677
+ }
1678
+ : {
1679
+ node: null,
1680
+ parent: run.parent,
1681
+ nodes: run.nodes,
1682
+ leafStart: run.leafStart,
1683
+ leafEnd: run.leafEnd,
1684
+ count: run.count,
1685
+ },
1686
+ );
1687
+ run = null;
1688
+ };
1689
+
1690
+ (function descend(node) {
1691
+ for (const child of node.children ?? []) {
1692
+ // A header always survives while its parent is open — a node that shows
1693
+ // its children but not its own label is worse than useless.
1694
+ const isHeader = child.data?.header;
1695
+ const open = holdsKept.get(child) && child.children?.length;
1696
+ const kept =
1697
+ isHeader || (holdsKept.get(child) && !child.children?.length);
1698
+
1699
+ if (open || kept) {
1700
+ flush(); // a visible child breaks the closed run
1701
+ if (open) descend(child);
1702
+ else
1703
+ slots.push({
1704
+ node: child,
1705
+ leafStart: child.leafStart,
1706
+ leafEnd: child.leafEnd,
1707
+ count: child.count,
1708
+ });
1709
+ continue;
1710
+ }
1711
+
1712
+ // Closed: accumulate into the current run of adjacent closed siblings.
1713
+ if (run && run.parent === node) {
1714
+ run.nodes.push(child);
1715
+ run.leafEnd = child.leafEnd;
1716
+ run.count += child.count;
1717
+ } else {
1718
+ flush();
1719
+ run = {
1720
+ parent: node,
1721
+ nodes: [child],
1722
+ leafStart: child.leafStart,
1723
+ leafEnd: child.leafEnd,
1724
+ count: child.count,
1725
+ };
1726
+ }
1727
+ }
1728
+ flush(); // a run never spans out of its parent — that would break containment
1729
+ })(root);
1730
+
1731
+ return slots;
1732
+ }
1733
+
1734
+ /**
1735
+ * Stage 2 of the layout: turn a slot sequence into pixel boundaries.
1736
+ *
1737
+ * Two steps, deliberately separate:
1738
+ *
1739
+ * basePositions() how much column each slot gets BEFORE any lens. Either
1740
+ * equal spans (`sizeBy: "slots"` — size encodes interest) or
1741
+ * spans proportional to mass (`sizeBy: "count"` — size encodes
1742
+ * photo count, a true value-encoded partition diagram).
1743
+ * distort() the fisheye, applied on top of whatever base it is given.
1744
+ *
1745
+ * The fisheye only needs its input to be monotonic, so it composes with either
1746
+ * base for free. `x === a` stays a fixed point, which is what keeps the row under
1747
+ * the cursor the row you click — mass-weighted or not.
1748
+ *
1749
+ * A slot sequence of length S gets S+1 boundaries spanning [min, max]. Slot j
1750
+ * owns [pos[j], pos[j+1]], so the last slot gets a real band instead of
1751
+ * collapsing onto the bottom edge.
1752
+ */
1753
+
1754
+ const SIZE_BY = ["slots", "count"];
1755
+
1756
+ /**
1757
+ * The fisheye scale, ported verbatim from AutoGallery's `fisheye.js`, which
1758
+ * ported it from PhotoRing's `d3_fisheye_scale` (d3 v3). Maps a base position
1759
+ * `x` in [min, max] to a distorted position that magnifies around focus pixel
1760
+ * `a` and compresses away from it. Monotonic in `x`; `x === a` is a fixed point;
1761
+ * the endpoints map to themselves. Larger `d` = gentler distortion.
1762
+ *
1763
+ * This math is correct and well covered — it is the one piece carried over
1764
+ * untouched.
1765
+ *
1766
+ * @returns {number}
1767
+ */
1768
+ function fisheyePosition(x, a, min, max, d) {
1769
+ const left = x < a;
1770
+ let m = left ? a - min : max - a;
1771
+ if (m === 0) m = max - min;
1772
+ const dx = Math.abs(x - a);
1773
+ if (dx < 1e-9) return a;
1774
+ return ((left ? -1 : 1) * (m * (d + 1))) / (d + m / dx) + a;
1775
+ }
1776
+
1777
+ const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
1778
+
1779
+ /**
1780
+ * Base (undistorted) boundaries for a sequence of weighted items.
1781
+ *
1782
+ * `sizeBy: "count"` is the honest icicle: a 40,000-photo year visibly dwarfs a
1783
+ * 400-photo one. But a pure mass split gives a zero-count group a zero-height
1784
+ * band — invisible, and impossible to click. So every item is guaranteed
1785
+ * `sizeFloor` of an equal share, and only the remainder is divided by mass:
1786
+ *
1787
+ * span(j) = (1 - sizeFloor) * mass(j)/total + sizeFloor * 1/S
1788
+ *
1789
+ * sizeFloor = 1 collapses back to equal spans, so the two modes are the ends of
1790
+ * one continuum rather than two code paths.
1791
+ *
1792
+ * @param {Array<{count?: number}>} items
1793
+ * @param {{min:number, max:number, sizeBy?:string, sizeFloor?:number}} o
1794
+ * @returns {number[]} S+1 boundaries
1795
+ */
1796
+ function basePositions(
1797
+ items,
1798
+ { min, max, sizeBy = "slots", sizeFloor = 0.25 },
1799
+ ) {
1800
+ const S = items.length;
1801
+ const span = max - min;
1802
+ const pos = new Array(S + 1);
1803
+ pos[0] = min;
1804
+
1805
+ if (sizeBy !== "count") {
1806
+ for (let j = 1; j <= S; j++) pos[j] = min + (span * j) / S;
1807
+ pos[S] = max;
1808
+ return pos;
1809
+ }
1810
+
1811
+ const total = items.reduce((s, it) => s + Math.max(0, it.count ?? 0), 0);
1812
+ const f = total > 0 ? clamp(sizeFloor, 0, 1) : 1; // no mass anywhere -> equal
1813
+ let acc = min;
1814
+ for (let j = 0; j < S; j++) {
1815
+ const mass = total > 0 ? Math.max(0, items[j].count ?? 0) / total : 0;
1816
+ acc += span * ((1 - f) * mass + f / S);
1817
+ pos[j + 1] = acc;
1818
+ }
1819
+ pos[S] = max; // absorb float drift into the endpoint, which is pinned anyway
1820
+ return pos;
1821
+ }
1822
+
1823
+ /** The slot whose base interval contains pixel `px`. Works for ANY spacing —
1824
+ * which is why this is a search and not a `scale.invert()`. */
1825
+ function slotAtPixel(basePos, px) {
1826
+ const S = basePos.length - 1;
1827
+ if (S <= 0) return 0;
1828
+ let lo = 0;
1829
+ let hi = S - 1;
1830
+ while (lo < hi) {
1831
+ const mid = (lo + hi + 1) >> 1;
1832
+ if (basePos[mid] <= px) lo = mid;
1833
+ else hi = mid - 1;
1834
+ }
1835
+ return lo;
1836
+ }
1837
+
1838
+ /**
1839
+ * Resolve the focus into BOTH representations:
1840
+ * `px` the focus pixel (what the lens magnifies around)
1841
+ * `slot` the slot sitting under that pixel (what gets highlighted)
1842
+ *
1843
+ * When the host pins the focus to the cursor (`focus.px`), the pixel is
1844
+ * authoritative and the slot is derived — that is what keeps the magnified row
1845
+ * exactly under the pointer, so a click never lands on a row that slid away.
1846
+ * When the host drives the focus from its own state (`focus.slot`), the slot is
1847
+ * authoritative and the pixel is derived (the middle of its band).
1848
+ */
1849
+ function resolveFocus(focus, basePos) {
1850
+ const S = basePos.length - 1;
1851
+ const min = basePos[0];
1852
+ const max = basePos[S];
1853
+ if (S <= 0) return { px: min, slot: 0 };
1854
+
1855
+ if (focus?.px != null) {
1856
+ const px = clamp(focus.px, min, max);
1857
+ return { px, slot: slotAtPixel(basePos, px) };
1858
+ }
1859
+ const slot = clamp(focus?.slot ?? 0, 0, S - 1);
1860
+ return { px: (basePos[slot] + basePos[slot + 1]) / 2, slot };
1861
+ }
1862
+
1863
+ /** Apply the fisheye to a base boundary array. */
1864
+ function distort(basePos, { focusPx, distortion }) {
1865
+ const S = basePos.length - 1;
1866
+ const min = basePos[0];
1867
+ const max = basePos[S];
1868
+ const a = clamp(focusPx, min, max);
1869
+ const pos = basePos.map((x) => fisheyePosition(x, a, min, max, distortion));
1870
+ // The scale pins the endpoints analytically; clamp anyway so floating-point
1871
+ // drift can never push a band a hair outside the padded column.
1872
+ pos[0] = min;
1873
+ pos[S] = max;
1874
+ return pos;
1875
+ }
1876
+
1877
+ /**
1878
+ * Stage 3: slots + pixel boundaries -> rows.
1879
+ *
1880
+ * This is where "parents contain their children" stops being something a
1881
+ * renderer has to be careful about. Every node already owns a leaf interval
1882
+ * (`leafStart`..`leafEnd`, from hierarchy.js), and the slots partition that same
1883
+ * leaf axis. So a node's band is just the pixel span of the slots its leaf
1884
+ * interval covers — and since a child's leaf interval is a SUBSET of its
1885
+ * parent's, its band is necessarily inside its parent's. Containment is
1886
+ * arithmetic, not diligence.
1887
+ *
1888
+ * A node is drawn iff its leaf interval is a whole number of slots AND no closed
1889
+ * ancestor is standing in for it.
1890
+ */
1891
+
1892
+ /** @typedef {{node: any|null, parent?: any, nodes?: any[], leafStart: number,
1893
+ * leafEnd: number, count?: number}} Slot */
1894
+
1895
+ /**
1896
+ * @param {any} root decorated hierarchy (see hierarchy.js)
1897
+ * @param {Slot[]} slots contiguous partition of the leaf axis
1898
+ * @param {number[]} pos slots.length + 1 pixel boundaries
1899
+ * @param {{focusSlot?: number}} [opts]
1900
+ * @returns {{rows: any[], maxCount: number}}
1901
+ */
1902
+ function buildRows(root, slots, pos, opts = {}) {
1903
+ const S = slots.length;
1904
+ if (!S) return { rows: [], maxCount: 0 };
1905
+
1906
+ const nLeaves = slots[S - 1].leafEnd;
1907
+ const slotOfLeaf = new Int32Array(nLeaves);
1908
+ for (let j = 0; j < S; j++) {
1909
+ for (let i = slots[j].leafStart; i < slots[j].leafEnd; i++)
1910
+ slotOfLeaf[i] = j;
1911
+ }
1912
+
1913
+ // Nodes that a closed slot is standing in for. Without this, a chain like
1914
+ // 2019 > 12 > 31 that is closed at "2019" would draw all three bands stacked
1915
+ // on the same pixels — they all happen to span exactly one slot.
1916
+ const hidden = new Set();
1917
+ const hide = (n) => n.each?.((d) => d !== n && hidden.add(d));
1918
+ for (const slot of slots) {
1919
+ if (slot.node?.children?.length) hide(slot.node);
1920
+ if (slot.nodes) for (const n of slot.nodes) n.each((d) => hidden.add(d));
1921
+ }
1922
+
1923
+ const focusSlot = opts.focusSlot;
1924
+ const rows = [];
1925
+ let maxCount = 0;
1926
+
1927
+ const push = (row) => {
1928
+ rows.push(row);
1929
+ if (row.terminal && row.count > maxCount) maxCount = row.count;
1930
+ };
1931
+
1932
+ const band = (sStart, sEnd) => {
1933
+ const y0 = pos[sStart];
1934
+ const y1 = pos[sEnd];
1935
+ return {
1936
+ slotStart: sStart,
1937
+ slotEnd: sEnd,
1938
+ leafStart: slots[sStart].leafStart,
1939
+ leafEnd: slots[sEnd - 1].leafEnd,
1940
+ focused: focusSlot != null && focusSlot >= sStart && focusSlot < sEnd,
1941
+ y0,
1942
+ y1,
1943
+ y: (y0 + y1) / 2,
1944
+ thickness: y1 - y0,
1945
+ };
1946
+ };
1947
+
1948
+ root.each((node) => {
1949
+ if (node.depth === 0) return; // the synthetic root is not a row
1950
+ if (hidden.has(node)) return;
1951
+ if (node.leafStart >= nLeaves) return;
1952
+
1953
+ const sStart = slotOfLeaf[node.leafStart];
1954
+ const sEnd = slotOfLeaf[node.leafEnd - 1] + 1;
1955
+ const aligned =
1956
+ slots[sStart].leafStart === node.leafStart &&
1957
+ slots[sEnd - 1].leafEnd === node.leafEnd;
1958
+ if (!aligned) return;
1959
+
1960
+ const slot = slots[sStart];
1961
+ const collapsed =
1962
+ sEnd - sStart === 1 && slot.node === node && !!node.children?.length;
1963
+ // Terminal rows carry the count histogram: real leaves and closed subtrees.
1964
+ // Everything else is structure.
1965
+ const terminal = collapsed || !node.children?.length;
1966
+
1967
+ push({
1968
+ node,
1969
+ parentNode: node.parent,
1970
+ id: node.id,
1971
+ depth: node.depth,
1972
+ label: node.label,
1973
+ path: node.keyPath,
1974
+ count: node.count,
1975
+ kind: node.data?.header
1976
+ ? "header"
1977
+ : collapsed
1978
+ ? "collapsed"
1979
+ : terminal
1980
+ ? "leaf"
1981
+ : "branch",
1982
+ terminal,
1983
+ elided: collapsed ? node.leafEnd - node.leafStart : 0,
1984
+ ...band(sStart, sEnd),
1985
+ });
1986
+ });
1987
+
1988
+ // Elision slots have no node of their own, so they are not reachable from the
1989
+ // walk above — emit them here.
1990
+ slots.forEach((slot, j) => {
1991
+ if (slot.node || !slot.nodes) return;
1992
+ const first = slot.nodes[0];
1993
+ push({
1994
+ node: null,
1995
+ parentNode: slot.parent,
1996
+ nodes: slot.nodes,
1997
+ id: `elision:${first.id}+${slot.nodes.length}`,
1998
+ depth: first.depth,
1999
+ label: `${slot.nodes.length} more`,
2000
+ path: slot.parent.keyPath,
2001
+ count: slot.count,
2002
+ kind: "elision",
2003
+ terminal: true,
2004
+ elided: slot.leafEnd - slot.leafStart,
2005
+ ...band(j, j + 1),
2006
+ });
2007
+ });
2008
+
2009
+ rows.sort((a, b) => a.y0 - b.y0 || a.depth - b.depth);
2010
+ return { rows, maxCount };
2011
+ }
2012
+
2013
+ function ascending(a, b) {
2014
+ return a == null || b == null ? NaN : a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
2015
+ }
2016
+
2017
+ function descending(a, b) {
2018
+ return a == null || b == null ? NaN
2019
+ : b < a ? -1
2020
+ : b > a ? 1
2021
+ : b >= a ? 0
2022
+ : NaN;
2023
+ }
2024
+
2025
+ function bisector(f) {
2026
+ let compare1, compare2, delta;
2027
+
2028
+ // If an accessor is specified, promote it to a comparator. In this case we
2029
+ // can test whether the search value is (self-) comparable. We can’t do this
2030
+ // for a comparator (except for specific, known comparators) because we can’t
2031
+ // tell if the comparator is symmetric, and an asymmetric comparator can’t be
2032
+ // used to test whether a single value is comparable.
2033
+ if (f.length !== 2) {
2034
+ compare1 = ascending;
2035
+ compare2 = (d, x) => ascending(f(d), x);
2036
+ delta = (d, x) => f(d) - x;
2037
+ } else {
2038
+ compare1 = f === ascending || f === descending ? f : zero$1;
2039
+ compare2 = f;
2040
+ delta = f;
2041
+ }
2042
+
2043
+ function left(a, x, lo = 0, hi = a.length) {
2044
+ if (lo < hi) {
2045
+ if (compare1(x, x) !== 0) return hi;
2046
+ do {
2047
+ const mid = (lo + hi) >>> 1;
2048
+ if (compare2(a[mid], x) < 0) lo = mid + 1;
2049
+ else hi = mid;
2050
+ } while (lo < hi);
2051
+ }
2052
+ return lo;
2053
+ }
2054
+
2055
+ function right(a, x, lo = 0, hi = a.length) {
2056
+ if (lo < hi) {
2057
+ if (compare1(x, x) !== 0) return hi;
2058
+ do {
2059
+ const mid = (lo + hi) >>> 1;
2060
+ if (compare2(a[mid], x) <= 0) lo = mid + 1;
2061
+ else hi = mid;
2062
+ } while (lo < hi);
2063
+ }
2064
+ return lo;
2065
+ }
2066
+
2067
+ function center(a, x, lo = 0, hi = a.length) {
2068
+ const i = left(a, x, lo, hi - 1);
2069
+ return i > lo && delta(a[i - 1], x) > -delta(a[i], x) ? i - 1 : i;
2070
+ }
2071
+
2072
+ return {left, center, right};
2073
+ }
2074
+
2075
+ function zero$1() {
2076
+ return 0;
2077
+ }
2078
+
2079
+ function number$1(x) {
2080
+ return x === null ? NaN : +x;
2081
+ }
2082
+
2083
+ const ascendingBisect = bisector(ascending);
2084
+ const bisectRight = ascendingBisect.right;
2085
+ bisector(number$1).center;
2086
+
2087
+ const e10 = Math.sqrt(50),
2088
+ e5 = Math.sqrt(10),
2089
+ e2 = Math.sqrt(2);
2090
+
2091
+ function tickSpec(start, stop, count) {
2092
+ const step = (stop - start) / Math.max(0, count),
2093
+ power = Math.floor(Math.log10(step)),
2094
+ error = step / Math.pow(10, power),
2095
+ factor = error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1;
2096
+ let i1, i2, inc;
2097
+ if (power < 0) {
2098
+ inc = Math.pow(10, -power) / factor;
2099
+ i1 = Math.round(start * inc);
2100
+ i2 = Math.round(stop * inc);
2101
+ if (i1 / inc < start) ++i1;
2102
+ if (i2 / inc > stop) --i2;
2103
+ inc = -inc;
2104
+ } else {
2105
+ inc = Math.pow(10, power) * factor;
2106
+ i1 = Math.round(start / inc);
2107
+ i2 = Math.round(stop / inc);
2108
+ if (i1 * inc < start) ++i1;
2109
+ if (i2 * inc > stop) --i2;
2110
+ }
2111
+ if (i2 < i1 && 0.5 <= count && count < 2) return tickSpec(start, stop, count * 2);
2112
+ return [i1, i2, inc];
2113
+ }
2114
+
2115
+ function ticks(start, stop, count) {
2116
+ stop = +stop, start = +start, count = +count;
2117
+ if (!(count > 0)) return [];
2118
+ if (start === stop) return [start];
2119
+ const reverse = stop < start, [i1, i2, inc] = reverse ? tickSpec(stop, start, count) : tickSpec(start, stop, count);
2120
+ if (!(i2 >= i1)) return [];
2121
+ const n = i2 - i1 + 1, ticks = new Array(n);
2122
+ if (reverse) {
2123
+ if (inc < 0) for (let i = 0; i < n; ++i) ticks[i] = (i2 - i) / -inc;
2124
+ else for (let i = 0; i < n; ++i) ticks[i] = (i2 - i) * inc;
2125
+ } else {
2126
+ if (inc < 0) for (let i = 0; i < n; ++i) ticks[i] = (i1 + i) / -inc;
2127
+ else for (let i = 0; i < n; ++i) ticks[i] = (i1 + i) * inc;
2128
+ }
2129
+ return ticks;
2130
+ }
2131
+
2132
+ function tickIncrement(start, stop, count) {
2133
+ stop = +stop, start = +start, count = +count;
2134
+ return tickSpec(start, stop, count)[2];
2135
+ }
2136
+
2137
+ function tickStep(start, stop, count) {
2138
+ stop = +stop, start = +start, count = +count;
2139
+ const reverse = stop < start, inc = reverse ? tickIncrement(stop, start, count) : tickIncrement(start, stop, count);
2140
+ return (reverse ? -1 : 1) * (inc < 0 ? 1 / -inc : inc);
2141
+ }
2142
+
2143
+ function initRange(domain, range) {
2144
+ switch (arguments.length) {
2145
+ case 0: break;
2146
+ case 1: this.range(domain); break;
2147
+ default: this.range(range).domain(domain); break;
2148
+ }
2149
+ return this;
2150
+ }
2151
+
2152
+ function define(constructor, factory, prototype) {
2153
+ constructor.prototype = factory.prototype = prototype;
2154
+ prototype.constructor = constructor;
2155
+ }
2156
+
2157
+ function extend(parent, definition) {
2158
+ var prototype = Object.create(parent.prototype);
2159
+ for (var key in definition) prototype[key] = definition[key];
2160
+ return prototype;
2161
+ }
2162
+
2163
+ function Color() {}
2164
+
2165
+ var darker = 0.7;
2166
+ var brighter = 1 / darker;
2167
+
2168
+ var reI = "\\s*([+-]?\\d+)\\s*",
2169
+ reN = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",
2170
+ reP = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",
2171
+ reHex = /^#([0-9a-f]{3,8})$/,
2172
+ reRgbInteger = new RegExp(`^rgb\\(${reI},${reI},${reI}\\)$`),
2173
+ reRgbPercent = new RegExp(`^rgb\\(${reP},${reP},${reP}\\)$`),
2174
+ reRgbaInteger = new RegExp(`^rgba\\(${reI},${reI},${reI},${reN}\\)$`),
2175
+ reRgbaPercent = new RegExp(`^rgba\\(${reP},${reP},${reP},${reN}\\)$`),
2176
+ reHslPercent = new RegExp(`^hsl\\(${reN},${reP},${reP}\\)$`),
2177
+ reHslaPercent = new RegExp(`^hsla\\(${reN},${reP},${reP},${reN}\\)$`);
2178
+
2179
+ var named = {
2180
+ aliceblue: 0xf0f8ff,
2181
+ antiquewhite: 0xfaebd7,
2182
+ aqua: 0x00ffff,
2183
+ aquamarine: 0x7fffd4,
2184
+ azure: 0xf0ffff,
2185
+ beige: 0xf5f5dc,
2186
+ bisque: 0xffe4c4,
2187
+ black: 0x000000,
2188
+ blanchedalmond: 0xffebcd,
2189
+ blue: 0x0000ff,
2190
+ blueviolet: 0x8a2be2,
2191
+ brown: 0xa52a2a,
2192
+ burlywood: 0xdeb887,
2193
+ cadetblue: 0x5f9ea0,
2194
+ chartreuse: 0x7fff00,
2195
+ chocolate: 0xd2691e,
2196
+ coral: 0xff7f50,
2197
+ cornflowerblue: 0x6495ed,
2198
+ cornsilk: 0xfff8dc,
2199
+ crimson: 0xdc143c,
2200
+ cyan: 0x00ffff,
2201
+ darkblue: 0x00008b,
2202
+ darkcyan: 0x008b8b,
2203
+ darkgoldenrod: 0xb8860b,
2204
+ darkgray: 0xa9a9a9,
2205
+ darkgreen: 0x006400,
2206
+ darkgrey: 0xa9a9a9,
2207
+ darkkhaki: 0xbdb76b,
2208
+ darkmagenta: 0x8b008b,
2209
+ darkolivegreen: 0x556b2f,
2210
+ darkorange: 0xff8c00,
2211
+ darkorchid: 0x9932cc,
2212
+ darkred: 0x8b0000,
2213
+ darksalmon: 0xe9967a,
2214
+ darkseagreen: 0x8fbc8f,
2215
+ darkslateblue: 0x483d8b,
2216
+ darkslategray: 0x2f4f4f,
2217
+ darkslategrey: 0x2f4f4f,
2218
+ darkturquoise: 0x00ced1,
2219
+ darkviolet: 0x9400d3,
2220
+ deeppink: 0xff1493,
2221
+ deepskyblue: 0x00bfff,
2222
+ dimgray: 0x696969,
2223
+ dimgrey: 0x696969,
2224
+ dodgerblue: 0x1e90ff,
2225
+ firebrick: 0xb22222,
2226
+ floralwhite: 0xfffaf0,
2227
+ forestgreen: 0x228b22,
2228
+ fuchsia: 0xff00ff,
2229
+ gainsboro: 0xdcdcdc,
2230
+ ghostwhite: 0xf8f8ff,
2231
+ gold: 0xffd700,
2232
+ goldenrod: 0xdaa520,
2233
+ gray: 0x808080,
2234
+ green: 0x008000,
2235
+ greenyellow: 0xadff2f,
2236
+ grey: 0x808080,
2237
+ honeydew: 0xf0fff0,
2238
+ hotpink: 0xff69b4,
2239
+ indianred: 0xcd5c5c,
2240
+ indigo: 0x4b0082,
2241
+ ivory: 0xfffff0,
2242
+ khaki: 0xf0e68c,
2243
+ lavender: 0xe6e6fa,
2244
+ lavenderblush: 0xfff0f5,
2245
+ lawngreen: 0x7cfc00,
2246
+ lemonchiffon: 0xfffacd,
2247
+ lightblue: 0xadd8e6,
2248
+ lightcoral: 0xf08080,
2249
+ lightcyan: 0xe0ffff,
2250
+ lightgoldenrodyellow: 0xfafad2,
2251
+ lightgray: 0xd3d3d3,
2252
+ lightgreen: 0x90ee90,
2253
+ lightgrey: 0xd3d3d3,
2254
+ lightpink: 0xffb6c1,
2255
+ lightsalmon: 0xffa07a,
2256
+ lightseagreen: 0x20b2aa,
2257
+ lightskyblue: 0x87cefa,
2258
+ lightslategray: 0x778899,
2259
+ lightslategrey: 0x778899,
2260
+ lightsteelblue: 0xb0c4de,
2261
+ lightyellow: 0xffffe0,
2262
+ lime: 0x00ff00,
2263
+ limegreen: 0x32cd32,
2264
+ linen: 0xfaf0e6,
2265
+ magenta: 0xff00ff,
2266
+ maroon: 0x800000,
2267
+ mediumaquamarine: 0x66cdaa,
2268
+ mediumblue: 0x0000cd,
2269
+ mediumorchid: 0xba55d3,
2270
+ mediumpurple: 0x9370db,
2271
+ mediumseagreen: 0x3cb371,
2272
+ mediumslateblue: 0x7b68ee,
2273
+ mediumspringgreen: 0x00fa9a,
2274
+ mediumturquoise: 0x48d1cc,
2275
+ mediumvioletred: 0xc71585,
2276
+ midnightblue: 0x191970,
2277
+ mintcream: 0xf5fffa,
2278
+ mistyrose: 0xffe4e1,
2279
+ moccasin: 0xffe4b5,
2280
+ navajowhite: 0xffdead,
2281
+ navy: 0x000080,
2282
+ oldlace: 0xfdf5e6,
2283
+ olive: 0x808000,
2284
+ olivedrab: 0x6b8e23,
2285
+ orange: 0xffa500,
2286
+ orangered: 0xff4500,
2287
+ orchid: 0xda70d6,
2288
+ palegoldenrod: 0xeee8aa,
2289
+ palegreen: 0x98fb98,
2290
+ paleturquoise: 0xafeeee,
2291
+ palevioletred: 0xdb7093,
2292
+ papayawhip: 0xffefd5,
2293
+ peachpuff: 0xffdab9,
2294
+ peru: 0xcd853f,
2295
+ pink: 0xffc0cb,
2296
+ plum: 0xdda0dd,
2297
+ powderblue: 0xb0e0e6,
2298
+ purple: 0x800080,
2299
+ rebeccapurple: 0x663399,
2300
+ red: 0xff0000,
2301
+ rosybrown: 0xbc8f8f,
2302
+ royalblue: 0x4169e1,
2303
+ saddlebrown: 0x8b4513,
2304
+ salmon: 0xfa8072,
2305
+ sandybrown: 0xf4a460,
2306
+ seagreen: 0x2e8b57,
2307
+ seashell: 0xfff5ee,
2308
+ sienna: 0xa0522d,
2309
+ silver: 0xc0c0c0,
2310
+ skyblue: 0x87ceeb,
2311
+ slateblue: 0x6a5acd,
2312
+ slategray: 0x708090,
2313
+ slategrey: 0x708090,
2314
+ snow: 0xfffafa,
2315
+ springgreen: 0x00ff7f,
2316
+ steelblue: 0x4682b4,
2317
+ tan: 0xd2b48c,
2318
+ teal: 0x008080,
2319
+ thistle: 0xd8bfd8,
2320
+ tomato: 0xff6347,
2321
+ turquoise: 0x40e0d0,
2322
+ violet: 0xee82ee,
2323
+ wheat: 0xf5deb3,
2324
+ white: 0xffffff,
2325
+ whitesmoke: 0xf5f5f5,
2326
+ yellow: 0xffff00,
2327
+ yellowgreen: 0x9acd32
2328
+ };
2329
+
2330
+ define(Color, color, {
2331
+ copy(channels) {
2332
+ return Object.assign(new this.constructor, this, channels);
2333
+ },
2334
+ displayable() {
2335
+ return this.rgb().displayable();
2336
+ },
2337
+ hex: color_formatHex, // Deprecated! Use color.formatHex.
2338
+ formatHex: color_formatHex,
2339
+ formatHex8: color_formatHex8,
2340
+ formatHsl: color_formatHsl,
2341
+ formatRgb: color_formatRgb,
2342
+ toString: color_formatRgb
2343
+ });
2344
+
2345
+ function color_formatHex() {
2346
+ return this.rgb().formatHex();
2347
+ }
2348
+
2349
+ function color_formatHex8() {
2350
+ return this.rgb().formatHex8();
2351
+ }
2352
+
2353
+ function color_formatHsl() {
2354
+ return hslConvert(this).formatHsl();
2355
+ }
2356
+
2357
+ function color_formatRgb() {
2358
+ return this.rgb().formatRgb();
2359
+ }
2360
+
2361
+ function color(format) {
2362
+ var m, l;
2363
+ format = (format + "").trim().toLowerCase();
2364
+ return (m = reHex.exec(format)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) // #ff0000
2365
+ : l === 3 ? new Rgb((m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1) // #f00
2366
+ : l === 8 ? rgba(m >> 24 & 0xff, m >> 16 & 0xff, m >> 8 & 0xff, (m & 0xff) / 0xff) // #ff000000
2367
+ : l === 4 ? rgba((m >> 12 & 0xf) | (m >> 8 & 0xf0), (m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), (((m & 0xf) << 4) | (m & 0xf)) / 0xff) // #f000
2368
+ : null) // invalid hex
2369
+ : (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)
2370
+ : (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%)
2371
+ : (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)
2372
+ : (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1)
2373
+ : (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)
2374
+ : (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1)
2375
+ : named.hasOwnProperty(format) ? rgbn(named[format]) // eslint-disable-line no-prototype-builtins
2376
+ : format === "transparent" ? new Rgb(NaN, NaN, NaN, 0)
2377
+ : null;
2378
+ }
2379
+
2380
+ function rgbn(n) {
2381
+ return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1);
2382
+ }
2383
+
2384
+ function rgba(r, g, b, a) {
2385
+ if (a <= 0) r = g = b = NaN;
2386
+ return new Rgb(r, g, b, a);
2387
+ }
2388
+
2389
+ function rgbConvert(o) {
2390
+ if (!(o instanceof Color)) o = color(o);
2391
+ if (!o) return new Rgb;
2392
+ o = o.rgb();
2393
+ return new Rgb(o.r, o.g, o.b, o.opacity);
2394
+ }
2395
+
2396
+ function rgb$1(r, g, b, opacity) {
2397
+ return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);
2398
+ }
2399
+
2400
+ function Rgb(r, g, b, opacity) {
2401
+ this.r = +r;
2402
+ this.g = +g;
2403
+ this.b = +b;
2404
+ this.opacity = +opacity;
2405
+ }
2406
+
2407
+ define(Rgb, rgb$1, extend(Color, {
2408
+ brighter(k) {
2409
+ k = k == null ? brighter : Math.pow(brighter, k);
2410
+ return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
2411
+ },
2412
+ darker(k) {
2413
+ k = k == null ? darker : Math.pow(darker, k);
2414
+ return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
2415
+ },
2416
+ rgb() {
2417
+ return this;
2418
+ },
2419
+ clamp() {
2420
+ return new Rgb(clampi(this.r), clampi(this.g), clampi(this.b), clampa(this.opacity));
2421
+ },
2422
+ displayable() {
2423
+ return (-0.5 <= this.r && this.r < 255.5)
2424
+ && (-0.5 <= this.g && this.g < 255.5)
2425
+ && (-0.5 <= this.b && this.b < 255.5)
2426
+ && (0 <= this.opacity && this.opacity <= 1);
2427
+ },
2428
+ hex: rgb_formatHex, // Deprecated! Use color.formatHex.
2429
+ formatHex: rgb_formatHex,
2430
+ formatHex8: rgb_formatHex8,
2431
+ formatRgb: rgb_formatRgb,
2432
+ toString: rgb_formatRgb
2433
+ }));
2434
+
2435
+ function rgb_formatHex() {
2436
+ return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}`;
2437
+ }
2438
+
2439
+ function rgb_formatHex8() {
2440
+ return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}${hex((isNaN(this.opacity) ? 1 : this.opacity) * 255)}`;
2441
+ }
2442
+
2443
+ function rgb_formatRgb() {
2444
+ const a = clampa(this.opacity);
2445
+ return `${a === 1 ? "rgb(" : "rgba("}${clampi(this.r)}, ${clampi(this.g)}, ${clampi(this.b)}${a === 1 ? ")" : `, ${a})`}`;
2446
+ }
2447
+
2448
+ function clampa(opacity) {
2449
+ return isNaN(opacity) ? 1 : Math.max(0, Math.min(1, opacity));
2450
+ }
2451
+
2452
+ function clampi(value) {
2453
+ return Math.max(0, Math.min(255, Math.round(value) || 0));
2454
+ }
2455
+
2456
+ function hex(value) {
2457
+ value = clampi(value);
2458
+ return (value < 16 ? "0" : "") + value.toString(16);
2459
+ }
2460
+
2461
+ function hsla(h, s, l, a) {
2462
+ if (a <= 0) h = s = l = NaN;
2463
+ else if (l <= 0 || l >= 1) h = s = NaN;
2464
+ else if (s <= 0) h = NaN;
2465
+ return new Hsl(h, s, l, a);
2466
+ }
2467
+
2468
+ function hslConvert(o) {
2469
+ if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);
2470
+ if (!(o instanceof Color)) o = color(o);
2471
+ if (!o) return new Hsl;
2472
+ if (o instanceof Hsl) return o;
2473
+ o = o.rgb();
2474
+ var r = o.r / 255,
2475
+ g = o.g / 255,
2476
+ b = o.b / 255,
2477
+ min = Math.min(r, g, b),
2478
+ max = Math.max(r, g, b),
2479
+ h = NaN,
2480
+ s = max - min,
2481
+ l = (max + min) / 2;
2482
+ if (s) {
2483
+ if (r === max) h = (g - b) / s + (g < b) * 6;
2484
+ else if (g === max) h = (b - r) / s + 2;
2485
+ else h = (r - g) / s + 4;
2486
+ s /= l < 0.5 ? max + min : 2 - max - min;
2487
+ h *= 60;
2488
+ } else {
2489
+ s = l > 0 && l < 1 ? 0 : h;
2490
+ }
2491
+ return new Hsl(h, s, l, o.opacity);
2492
+ }
2493
+
2494
+ function hsl(h, s, l, opacity) {
2495
+ return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);
2496
+ }
2497
+
2498
+ function Hsl(h, s, l, opacity) {
2499
+ this.h = +h;
2500
+ this.s = +s;
2501
+ this.l = +l;
2502
+ this.opacity = +opacity;
2503
+ }
2504
+
2505
+ define(Hsl, hsl, extend(Color, {
2506
+ brighter(k) {
2507
+ k = k == null ? brighter : Math.pow(brighter, k);
2508
+ return new Hsl(this.h, this.s, this.l * k, this.opacity);
2509
+ },
2510
+ darker(k) {
2511
+ k = k == null ? darker : Math.pow(darker, k);
2512
+ return new Hsl(this.h, this.s, this.l * k, this.opacity);
2513
+ },
2514
+ rgb() {
2515
+ var h = this.h % 360 + (this.h < 0) * 360,
2516
+ s = isNaN(h) || isNaN(this.s) ? 0 : this.s,
2517
+ l = this.l,
2518
+ m2 = l + (l < 0.5 ? l : 1 - l) * s,
2519
+ m1 = 2 * l - m2;
2520
+ return new Rgb(
2521
+ hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),
2522
+ hsl2rgb(h, m1, m2),
2523
+ hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),
2524
+ this.opacity
2525
+ );
2526
+ },
2527
+ clamp() {
2528
+ return new Hsl(clamph(this.h), clampt(this.s), clampt(this.l), clampa(this.opacity));
2529
+ },
2530
+ displayable() {
2531
+ return (0 <= this.s && this.s <= 1 || isNaN(this.s))
2532
+ && (0 <= this.l && this.l <= 1)
2533
+ && (0 <= this.opacity && this.opacity <= 1);
2534
+ },
2535
+ formatHsl() {
2536
+ const a = clampa(this.opacity);
2537
+ return `${a === 1 ? "hsl(" : "hsla("}${clamph(this.h)}, ${clampt(this.s) * 100}%, ${clampt(this.l) * 100}%${a === 1 ? ")" : `, ${a})`}`;
2538
+ }
2539
+ }));
2540
+
2541
+ function clamph(value) {
2542
+ value = (value || 0) % 360;
2543
+ return value < 0 ? value + 360 : value;
2544
+ }
2545
+
2546
+ function clampt(value) {
2547
+ return Math.max(0, Math.min(1, value || 0));
2548
+ }
2549
+
2550
+ /* From FvD 13.37, CSS Color Module Level 3 */
2551
+ function hsl2rgb(h, m1, m2) {
2552
+ return (h < 60 ? m1 + (m2 - m1) * h / 60
2553
+ : h < 180 ? m2
2554
+ : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60
2555
+ : m1) * 255;
2556
+ }
2557
+
2558
+ var constant = x => () => x;
2559
+
2560
+ function linear$1(a, d) {
2561
+ return function(t) {
2562
+ return a + t * d;
2563
+ };
2564
+ }
2565
+
2566
+ function exponential(a, b, y) {
2567
+ return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) {
2568
+ return Math.pow(a + t * b, y);
2569
+ };
2570
+ }
2571
+
2572
+ function gamma(y) {
2573
+ return (y = +y) === 1 ? nogamma : function(a, b) {
2574
+ return b - a ? exponential(a, b, y) : constant(isNaN(a) ? b : a);
2575
+ };
2576
+ }
2577
+
2578
+ function nogamma(a, b) {
2579
+ var d = b - a;
2580
+ return d ? linear$1(a, d) : constant(isNaN(a) ? b : a);
2581
+ }
2582
+
2583
+ var rgb = (function rgbGamma(y) {
2584
+ var color = gamma(y);
2585
+
2586
+ function rgb(start, end) {
2587
+ var r = color((start = rgb$1(start)).r, (end = rgb$1(end)).r),
2588
+ g = color(start.g, end.g),
2589
+ b = color(start.b, end.b),
2590
+ opacity = nogamma(start.opacity, end.opacity);
2591
+ return function(t) {
2592
+ start.r = r(t);
2593
+ start.g = g(t);
2594
+ start.b = b(t);
2595
+ start.opacity = opacity(t);
2596
+ return start + "";
2597
+ };
2598
+ }
2599
+
2600
+ rgb.gamma = rgbGamma;
2601
+
2602
+ return rgb;
2603
+ })(1);
2604
+
2605
+ function numberArray(a, b) {
2606
+ if (!b) b = [];
2607
+ var n = a ? Math.min(b.length, a.length) : 0,
2608
+ c = b.slice(),
2609
+ i;
2610
+ return function(t) {
2611
+ for (i = 0; i < n; ++i) c[i] = a[i] * (1 - t) + b[i] * t;
2612
+ return c;
2613
+ };
2614
+ }
2615
+
2616
+ function isNumberArray(x) {
2617
+ return ArrayBuffer.isView(x) && !(x instanceof DataView);
2618
+ }
2619
+
2620
+ function genericArray(a, b) {
2621
+ var nb = b ? b.length : 0,
2622
+ na = a ? Math.min(nb, a.length) : 0,
2623
+ x = new Array(na),
2624
+ c = new Array(nb),
2625
+ i;
2626
+
2627
+ for (i = 0; i < na; ++i) x[i] = interpolate(a[i], b[i]);
2628
+ for (; i < nb; ++i) c[i] = b[i];
2629
+
2630
+ return function(t) {
2631
+ for (i = 0; i < na; ++i) c[i] = x[i](t);
2632
+ return c;
2633
+ };
2634
+ }
2635
+
2636
+ function date(a, b) {
2637
+ var d = new Date;
2638
+ return a = +a, b = +b, function(t) {
2639
+ return d.setTime(a * (1 - t) + b * t), d;
2640
+ };
2641
+ }
2642
+
2643
+ function interpolateNumber(a, b) {
2644
+ return a = +a, b = +b, function(t) {
2645
+ return a * (1 - t) + b * t;
2646
+ };
2647
+ }
2648
+
2649
+ function object(a, b) {
2650
+ var i = {},
2651
+ c = {},
2652
+ k;
2653
+
2654
+ if (a === null || typeof a !== "object") a = {};
2655
+ if (b === null || typeof b !== "object") b = {};
2656
+
2657
+ for (k in b) {
2658
+ if (k in a) {
2659
+ i[k] = interpolate(a[k], b[k]);
2660
+ } else {
2661
+ c[k] = b[k];
2662
+ }
2663
+ }
2664
+
2665
+ return function(t) {
2666
+ for (k in i) c[k] = i[k](t);
2667
+ return c;
2668
+ };
2669
+ }
2670
+
2671
+ var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,
2672
+ reB = new RegExp(reA.source, "g");
2673
+
2674
+ function zero(b) {
2675
+ return function() {
2676
+ return b;
2677
+ };
2678
+ }
2679
+
2680
+ function one(b) {
2681
+ return function(t) {
2682
+ return b(t) + "";
2683
+ };
2684
+ }
2685
+
2686
+ function string(a, b) {
2687
+ var bi = reA.lastIndex = reB.lastIndex = 0, // scan index for next number in b
2688
+ am, // current match in a
2689
+ bm, // current match in b
2690
+ bs, // string preceding current number in b, if any
2691
+ i = -1, // index in s
2692
+ s = [], // string constants and placeholders
2693
+ q = []; // number interpolators
2694
+
2695
+ // Coerce inputs to strings.
2696
+ a = a + "", b = b + "";
2697
+
2698
+ // Interpolate pairs of numbers in a & b.
2699
+ while ((am = reA.exec(a))
2700
+ && (bm = reB.exec(b))) {
2701
+ if ((bs = bm.index) > bi) { // a string precedes the next number in b
2702
+ bs = b.slice(bi, bs);
2703
+ if (s[i]) s[i] += bs; // coalesce with previous string
2704
+ else s[++i] = bs;
2705
+ }
2706
+ if ((am = am[0]) === (bm = bm[0])) { // numbers in a & b match
2707
+ if (s[i]) s[i] += bm; // coalesce with previous string
2708
+ else s[++i] = bm;
2709
+ } else { // interpolate non-matching numbers
2710
+ s[++i] = null;
2711
+ q.push({i: i, x: interpolateNumber(am, bm)});
2712
+ }
2713
+ bi = reB.lastIndex;
2714
+ }
2715
+
2716
+ // Add remains of b.
2717
+ if (bi < b.length) {
2718
+ bs = b.slice(bi);
2719
+ if (s[i]) s[i] += bs; // coalesce with previous string
2720
+ else s[++i] = bs;
2721
+ }
2722
+
2723
+ // Special optimization for only a single match.
2724
+ // Otherwise, interpolate each of the numbers and rejoin the string.
2725
+ return s.length < 2 ? (q[0]
2726
+ ? one(q[0].x)
2727
+ : zero(b))
2728
+ : (b = q.length, function(t) {
2729
+ for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t);
2730
+ return s.join("");
2731
+ });
2732
+ }
2733
+
2734
+ function interpolate(a, b) {
2735
+ var t = typeof b, c;
2736
+ return b == null || t === "boolean" ? constant(b)
2737
+ : (t === "number" ? interpolateNumber
2738
+ : t === "string" ? ((c = color(b)) ? (b = c, rgb) : string)
2739
+ : b instanceof color ? rgb
2740
+ : b instanceof Date ? date
2741
+ : isNumberArray(b) ? numberArray
2742
+ : Array.isArray(b) ? genericArray
2743
+ : typeof b.valueOf !== "function" && typeof b.toString !== "function" || isNaN(b) ? object
2744
+ : interpolateNumber)(a, b);
2745
+ }
2746
+
2747
+ function interpolateRound(a, b) {
2748
+ return a = +a, b = +b, function(t) {
2749
+ return Math.round(a * (1 - t) + b * t);
2750
+ };
2751
+ }
2752
+
2753
+ function constants(x) {
2754
+ return function() {
2755
+ return x;
2756
+ };
2757
+ }
2758
+
2759
+ function number(x) {
2760
+ return +x;
2761
+ }
2762
+
2763
+ var unit = [0, 1];
2764
+
2765
+ function identity$1(x) {
2766
+ return x;
2767
+ }
2768
+
2769
+ function normalize(a, b) {
2770
+ return (b -= (a = +a))
2771
+ ? function(x) { return (x - a) / b; }
2772
+ : constants(isNaN(b) ? NaN : 0.5);
2773
+ }
2774
+
2775
+ function clamper(a, b) {
2776
+ var t;
2777
+ if (a > b) t = a, a = b, b = t;
2778
+ return function(x) { return Math.max(a, Math.min(b, x)); };
2779
+ }
2780
+
2781
+ // normalize(a, b)(x) takes a domain value x in [a,b] and returns the corresponding parameter t in [0,1].
2782
+ // interpolate(a, b)(t) takes a parameter t in [0,1] and returns the corresponding range value x in [a,b].
2783
+ function bimap(domain, range, interpolate) {
2784
+ var d0 = domain[0], d1 = domain[1], r0 = range[0], r1 = range[1];
2785
+ if (d1 < d0) d0 = normalize(d1, d0), r0 = interpolate(r1, r0);
2786
+ else d0 = normalize(d0, d1), r0 = interpolate(r0, r1);
2787
+ return function(x) { return r0(d0(x)); };
2788
+ }
2789
+
2790
+ function polymap(domain, range, interpolate) {
2791
+ var j = Math.min(domain.length, range.length) - 1,
2792
+ d = new Array(j),
2793
+ r = new Array(j),
2794
+ i = -1;
2795
+
2796
+ // Reverse descending domains.
2797
+ if (domain[j] < domain[0]) {
2798
+ domain = domain.slice().reverse();
2799
+ range = range.slice().reverse();
2800
+ }
2801
+
2802
+ while (++i < j) {
2803
+ d[i] = normalize(domain[i], domain[i + 1]);
2804
+ r[i] = interpolate(range[i], range[i + 1]);
2805
+ }
2806
+
2807
+ return function(x) {
2808
+ var i = bisectRight(domain, x, 1, j) - 1;
2809
+ return r[i](d[i](x));
2810
+ };
2811
+ }
2812
+
2813
+ function copy(source, target) {
2814
+ return target
2815
+ .domain(source.domain())
2816
+ .range(source.range())
2817
+ .interpolate(source.interpolate())
2818
+ .clamp(source.clamp())
2819
+ .unknown(source.unknown());
2820
+ }
2821
+
2822
+ function transformer() {
2823
+ var domain = unit,
2824
+ range = unit,
2825
+ interpolate$1 = interpolate,
2826
+ transform,
2827
+ untransform,
2828
+ unknown,
2829
+ clamp = identity$1,
2830
+ piecewise,
2831
+ output,
2832
+ input;
2833
+
2834
+ function rescale() {
2835
+ var n = Math.min(domain.length, range.length);
2836
+ if (clamp !== identity$1) clamp = clamper(domain[0], domain[n - 1]);
2837
+ piecewise = n > 2 ? polymap : bimap;
2838
+ output = input = null;
2839
+ return scale;
2840
+ }
2841
+
2842
+ function scale(x) {
2843
+ return x == null || isNaN(x = +x) ? unknown : (output || (output = piecewise(domain.map(transform), range, interpolate$1)))(transform(clamp(x)));
2844
+ }
2845
+
2846
+ scale.invert = function(y) {
2847
+ return clamp(untransform((input || (input = piecewise(range, domain.map(transform), interpolateNumber)))(y)));
2848
+ };
2849
+
2850
+ scale.domain = function(_) {
2851
+ return arguments.length ? (domain = Array.from(_, number), rescale()) : domain.slice();
2852
+ };
2853
+
2854
+ scale.range = function(_) {
2855
+ return arguments.length ? (range = Array.from(_), rescale()) : range.slice();
2856
+ };
2857
+
2858
+ scale.rangeRound = function(_) {
2859
+ return range = Array.from(_), interpolate$1 = interpolateRound, rescale();
2860
+ };
2861
+
2862
+ scale.clamp = function(_) {
2863
+ return arguments.length ? (clamp = _ ? true : identity$1, rescale()) : clamp !== identity$1;
2864
+ };
2865
+
2866
+ scale.interpolate = function(_) {
2867
+ return arguments.length ? (interpolate$1 = _, rescale()) : interpolate$1;
2868
+ };
2869
+
2870
+ scale.unknown = function(_) {
2871
+ return arguments.length ? (unknown = _, scale) : unknown;
2872
+ };
2873
+
2874
+ return function(t, u) {
2875
+ transform = t, untransform = u;
2876
+ return rescale();
2877
+ };
2878
+ }
2879
+
2880
+ function continuous() {
2881
+ return transformer()(identity$1, identity$1);
2882
+ }
2883
+
2884
+ function formatDecimal(x) {
2885
+ return Math.abs(x = Math.round(x)) >= 1e21
2886
+ ? x.toLocaleString("en").replace(/,/g, "")
2887
+ : x.toString(10);
2888
+ }
2889
+
2890
+ // Computes the decimal coefficient and exponent of the specified number x with
2891
+ // significant digits p, where x is positive and p is in [1, 21] or undefined.
2892
+ // For example, formatDecimalParts(1.23) returns ["123", 0].
2893
+ function formatDecimalParts(x, p) {
2894
+ if (!isFinite(x) || x === 0) return null; // NaN, ±Infinity, ±0
2895
+ var i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e"), coefficient = x.slice(0, i);
2896
+
2897
+ // The string returned by toExponential either has the form \d\.\d+e[-+]\d+
2898
+ // (e.g., 1.2e+3) or the form \de[-+]\d+ (e.g., 1e+3).
2899
+ return [
2900
+ coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,
2901
+ +x.slice(i + 1)
2902
+ ];
2903
+ }
2904
+
2905
+ function exponent(x) {
2906
+ return x = formatDecimalParts(Math.abs(x)), x ? x[1] : NaN;
2907
+ }
2908
+
2909
+ function formatGroup(grouping, thousands) {
2910
+ return function(value, width) {
2911
+ var i = value.length,
2912
+ t = [],
2913
+ j = 0,
2914
+ g = grouping[0],
2915
+ length = 0;
2916
+
2917
+ while (i > 0 && g > 0) {
2918
+ if (length + g + 1 > width) g = Math.max(1, width - length);
2919
+ t.push(value.substring(i -= g, i + g));
2920
+ if ((length += g + 1) > width) break;
2921
+ g = grouping[j = (j + 1) % grouping.length];
2922
+ }
2923
+
2924
+ return t.reverse().join(thousands);
2925
+ };
2926
+ }
2927
+
2928
+ function formatNumerals(numerals) {
2929
+ return function(value) {
2930
+ return value.replace(/[0-9]/g, function(i) {
2931
+ return numerals[+i];
2932
+ });
2933
+ };
2934
+ }
2935
+
2936
+ // [[fill]align][sign][symbol][0][width][,][.precision][~][type]
2937
+ var re = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;
2938
+
2939
+ function formatSpecifier(specifier) {
2940
+ if (!(match = re.exec(specifier))) throw new Error("invalid format: " + specifier);
2941
+ var match;
2942
+ return new FormatSpecifier({
2943
+ fill: match[1],
2944
+ align: match[2],
2945
+ sign: match[3],
2946
+ symbol: match[4],
2947
+ zero: match[5],
2948
+ width: match[6],
2949
+ comma: match[7],
2950
+ precision: match[8] && match[8].slice(1),
2951
+ trim: match[9],
2952
+ type: match[10]
2953
+ });
2954
+ }
2955
+
2956
+ formatSpecifier.prototype = FormatSpecifier.prototype; // instanceof
2957
+
2958
+ function FormatSpecifier(specifier) {
2959
+ this.fill = specifier.fill === undefined ? " " : specifier.fill + "";
2960
+ this.align = specifier.align === undefined ? ">" : specifier.align + "";
2961
+ this.sign = specifier.sign === undefined ? "-" : specifier.sign + "";
2962
+ this.symbol = specifier.symbol === undefined ? "" : specifier.symbol + "";
2963
+ this.zero = !!specifier.zero;
2964
+ this.width = specifier.width === undefined ? undefined : +specifier.width;
2965
+ this.comma = !!specifier.comma;
2966
+ this.precision = specifier.precision === undefined ? undefined : +specifier.precision;
2967
+ this.trim = !!specifier.trim;
2968
+ this.type = specifier.type === undefined ? "" : specifier.type + "";
2969
+ }
2970
+
2971
+ FormatSpecifier.prototype.toString = function() {
2972
+ return this.fill
2973
+ + this.align
2974
+ + this.sign
2975
+ + this.symbol
2976
+ + (this.zero ? "0" : "")
2977
+ + (this.width === undefined ? "" : Math.max(1, this.width | 0))
2978
+ + (this.comma ? "," : "")
2979
+ + (this.precision === undefined ? "" : "." + Math.max(0, this.precision | 0))
2980
+ + (this.trim ? "~" : "")
2981
+ + this.type;
2982
+ };
2983
+
2984
+ // Trims insignificant zeros, e.g., replaces 1.2000k with 1.2k.
2985
+ function formatTrim(s) {
2986
+ out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) {
2987
+ switch (s[i]) {
2988
+ case ".": i0 = i1 = i; break;
2989
+ case "0": if (i0 === 0) i0 = i; i1 = i; break;
2990
+ default: if (!+s[i]) break out; if (i0 > 0) i0 = 0; break;
2991
+ }
2992
+ }
2993
+ return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s;
2994
+ }
2995
+
2996
+ var prefixExponent;
2997
+
2998
+ function formatPrefixAuto(x, p) {
2999
+ var d = formatDecimalParts(x, p);
3000
+ if (!d) return prefixExponent = undefined, x.toPrecision(p);
3001
+ var coefficient = d[0],
3002
+ exponent = d[1],
3003
+ i = exponent - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1,
3004
+ n = coefficient.length;
3005
+ return i === n ? coefficient
3006
+ : i > n ? coefficient + new Array(i - n + 1).join("0")
3007
+ : i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i)
3008
+ : "0." + new Array(1 - i).join("0") + formatDecimalParts(x, Math.max(0, p + i - 1))[0]; // less than 1y!
3009
+ }
3010
+
3011
+ function formatRounded(x, p) {
3012
+ var d = formatDecimalParts(x, p);
3013
+ if (!d) return x + "";
3014
+ var coefficient = d[0],
3015
+ exponent = d[1];
3016
+ return exponent < 0 ? "0." + new Array(-exponent).join("0") + coefficient
3017
+ : coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + "." + coefficient.slice(exponent + 1)
3018
+ : coefficient + new Array(exponent - coefficient.length + 2).join("0");
3019
+ }
3020
+
3021
+ var formatTypes = {
3022
+ "%": (x, p) => (x * 100).toFixed(p),
3023
+ "b": (x) => Math.round(x).toString(2),
3024
+ "c": (x) => x + "",
3025
+ "d": formatDecimal,
3026
+ "e": (x, p) => x.toExponential(p),
3027
+ "f": (x, p) => x.toFixed(p),
3028
+ "g": (x, p) => x.toPrecision(p),
3029
+ "o": (x) => Math.round(x).toString(8),
3030
+ "p": (x, p) => formatRounded(x * 100, p),
3031
+ "r": formatRounded,
3032
+ "s": formatPrefixAuto,
3033
+ "X": (x) => Math.round(x).toString(16).toUpperCase(),
3034
+ "x": (x) => Math.round(x).toString(16)
3035
+ };
3036
+
3037
+ function identity(x) {
3038
+ return x;
3039
+ }
3040
+
3041
+ var map = Array.prototype.map,
3042
+ prefixes = ["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];
3043
+
3044
+ function formatLocale(locale) {
3045
+ var group = locale.grouping === undefined || locale.thousands === undefined ? identity : formatGroup(map.call(locale.grouping, Number), locale.thousands + ""),
3046
+ currencyPrefix = locale.currency === undefined ? "" : locale.currency[0] + "",
3047
+ currencySuffix = locale.currency === undefined ? "" : locale.currency[1] + "",
3048
+ decimal = locale.decimal === undefined ? "." : locale.decimal + "",
3049
+ numerals = locale.numerals === undefined ? identity : formatNumerals(map.call(locale.numerals, String)),
3050
+ percent = locale.percent === undefined ? "%" : locale.percent + "",
3051
+ minus = locale.minus === undefined ? "−" : locale.minus + "",
3052
+ nan = locale.nan === undefined ? "NaN" : locale.nan + "";
3053
+
3054
+ function newFormat(specifier, options) {
3055
+ specifier = formatSpecifier(specifier);
3056
+
3057
+ var fill = specifier.fill,
3058
+ align = specifier.align,
3059
+ sign = specifier.sign,
3060
+ symbol = specifier.symbol,
3061
+ zero = specifier.zero,
3062
+ width = specifier.width,
3063
+ comma = specifier.comma,
3064
+ precision = specifier.precision,
3065
+ trim = specifier.trim,
3066
+ type = specifier.type;
3067
+
3068
+ // The "n" type is an alias for ",g".
3069
+ if (type === "n") comma = true, type = "g";
3070
+
3071
+ // The "" type, and any invalid type, is an alias for ".12~g".
3072
+ else if (!formatTypes[type]) precision === undefined && (precision = 12), trim = true, type = "g";
3073
+
3074
+ // If zero fill is specified, padding goes after sign and before digits.
3075
+ if (zero || (fill === "0" && align === "=")) zero = true, fill = "0", align = "=";
3076
+
3077
+ // Compute the prefix and suffix.
3078
+ // For SI-prefix, the suffix is lazily computed.
3079
+ var prefix = (options && options.prefix !== undefined ? options.prefix : "") + (symbol === "$" ? currencyPrefix : symbol === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : ""),
3080
+ suffix = (symbol === "$" ? currencySuffix : /[%p]/.test(type) ? percent : "") + (options && options.suffix !== undefined ? options.suffix : "");
3081
+
3082
+ // What format function should we use?
3083
+ // Is this an integer type?
3084
+ // Can this type generate exponential notation?
3085
+ var formatType = formatTypes[type],
3086
+ maybeSuffix = /[defgprs%]/.test(type);
3087
+
3088
+ // Set the default precision if not specified,
3089
+ // or clamp the specified precision to the supported range.
3090
+ // For significant precision, it must be in [1, 21].
3091
+ // For fixed precision, it must be in [0, 20].
3092
+ precision = precision === undefined ? 6
3093
+ : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision))
3094
+ : Math.max(0, Math.min(20, precision));
3095
+
3096
+ function format(value) {
3097
+ var valuePrefix = prefix,
3098
+ valueSuffix = suffix,
3099
+ i, n, c;
3100
+
3101
+ if (type === "c") {
3102
+ valueSuffix = formatType(value) + valueSuffix;
3103
+ value = "";
3104
+ } else {
3105
+ value = +value;
3106
+
3107
+ // Determine the sign. -0 is not less than 0, but 1 / -0 is!
3108
+ var valueNegative = value < 0 || 1 / value < 0;
3109
+
3110
+ // Perform the initial formatting.
3111
+ value = isNaN(value) ? nan : formatType(Math.abs(value), precision);
3112
+
3113
+ // Trim insignificant zeros.
3114
+ if (trim) value = formatTrim(value);
3115
+
3116
+ // If a negative value rounds to zero after formatting, and no explicit positive sign is requested, hide the sign.
3117
+ if (valueNegative && +value === 0 && sign !== "+") valueNegative = false;
3118
+
3119
+ // Compute the prefix and suffix.
3120
+ valuePrefix = (valueNegative ? (sign === "(" ? sign : minus) : sign === "-" || sign === "(" ? "" : sign) + valuePrefix;
3121
+ valueSuffix = (type === "s" && !isNaN(value) && prefixExponent !== undefined ? prefixes[8 + prefixExponent / 3] : "") + valueSuffix + (valueNegative && sign === "(" ? ")" : "");
3122
+
3123
+ // Break the formatted value into the integer “value” part that can be
3124
+ // grouped, and fractional or exponential “suffix” part that is not.
3125
+ if (maybeSuffix) {
3126
+ i = -1, n = value.length;
3127
+ while (++i < n) {
3128
+ if (c = value.charCodeAt(i), 48 > c || c > 57) {
3129
+ valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix;
3130
+ value = value.slice(0, i);
3131
+ break;
3132
+ }
3133
+ }
3134
+ }
3135
+ }
3136
+
3137
+ // If the fill character is not "0", grouping is applied before padding.
3138
+ if (comma && !zero) value = group(value, Infinity);
3139
+
3140
+ // Compute the padding.
3141
+ var length = valuePrefix.length + value.length + valueSuffix.length,
3142
+ padding = length < width ? new Array(width - length + 1).join(fill) : "";
3143
+
3144
+ // If the fill character is "0", grouping is applied after padding.
3145
+ if (comma && zero) value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = "";
3146
+
3147
+ // Reconstruct the final output based on the desired alignment.
3148
+ switch (align) {
3149
+ case "<": value = valuePrefix + value + valueSuffix + padding; break;
3150
+ case "=": value = valuePrefix + padding + value + valueSuffix; break;
3151
+ case "^": value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length); break;
3152
+ default: value = padding + valuePrefix + value + valueSuffix; break;
3153
+ }
3154
+
3155
+ return numerals(value);
3156
+ }
3157
+
3158
+ format.toString = function() {
3159
+ return specifier + "";
3160
+ };
3161
+
3162
+ return format;
3163
+ }
3164
+
3165
+ function formatPrefix(specifier, value) {
3166
+ var e = Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3,
3167
+ k = Math.pow(10, -e),
3168
+ f = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier), {suffix: prefixes[8 + e / 3]});
3169
+ return function(value) {
3170
+ return f(k * value);
3171
+ };
3172
+ }
3173
+
3174
+ return {
3175
+ format: newFormat,
3176
+ formatPrefix: formatPrefix
3177
+ };
3178
+ }
3179
+
3180
+ var locale;
3181
+ var format;
3182
+ var formatPrefix;
3183
+
3184
+ defaultLocale({
3185
+ thousands: ",",
3186
+ grouping: [3],
3187
+ currency: ["$", ""]
3188
+ });
3189
+
3190
+ function defaultLocale(definition) {
3191
+ locale = formatLocale(definition);
3192
+ format = locale.format;
3193
+ formatPrefix = locale.formatPrefix;
3194
+ return locale;
3195
+ }
3196
+
3197
+ function precisionFixed(step) {
3198
+ return Math.max(0, -exponent(Math.abs(step)));
3199
+ }
3200
+
3201
+ function precisionPrefix(step, value) {
3202
+ return Math.max(0, Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3 - exponent(Math.abs(step)));
3203
+ }
3204
+
3205
+ function precisionRound(step, max) {
3206
+ step = Math.abs(step), max = Math.abs(max) - step;
3207
+ return Math.max(0, exponent(max) - exponent(step)) + 1;
3208
+ }
3209
+
3210
+ function tickFormat(start, stop, count, specifier) {
3211
+ var step = tickStep(start, stop, count),
3212
+ precision;
3213
+ specifier = formatSpecifier(specifier == null ? ",f" : specifier);
3214
+ switch (specifier.type) {
3215
+ case "s": {
3216
+ var value = Math.max(Math.abs(start), Math.abs(stop));
3217
+ if (specifier.precision == null && !isNaN(precision = precisionPrefix(step, value))) specifier.precision = precision;
3218
+ return formatPrefix(specifier, value);
3219
+ }
3220
+ case "":
3221
+ case "e":
3222
+ case "g":
3223
+ case "p":
3224
+ case "r": {
3225
+ if (specifier.precision == null && !isNaN(precision = precisionRound(step, Math.max(Math.abs(start), Math.abs(stop))))) specifier.precision = precision - (specifier.type === "e");
3226
+ break;
3227
+ }
3228
+ case "f":
3229
+ case "%": {
3230
+ if (specifier.precision == null && !isNaN(precision = precisionFixed(step))) specifier.precision = precision - (specifier.type === "%") * 2;
3231
+ break;
3232
+ }
3233
+ }
3234
+ return format(specifier);
3235
+ }
3236
+
3237
+ function linearish(scale) {
3238
+ var domain = scale.domain;
3239
+
3240
+ scale.ticks = function(count) {
3241
+ var d = domain();
3242
+ return ticks(d[0], d[d.length - 1], count == null ? 10 : count);
3243
+ };
3244
+
3245
+ scale.tickFormat = function(count, specifier) {
3246
+ var d = domain();
3247
+ return tickFormat(d[0], d[d.length - 1], count == null ? 10 : count, specifier);
3248
+ };
3249
+
3250
+ scale.nice = function(count) {
3251
+ if (count == null) count = 10;
3252
+
3253
+ var d = domain();
3254
+ var i0 = 0;
3255
+ var i1 = d.length - 1;
3256
+ var start = d[i0];
3257
+ var stop = d[i1];
3258
+ var prestep;
3259
+ var step;
3260
+ var maxIter = 10;
3261
+
3262
+ if (stop < start) {
3263
+ step = start, start = stop, stop = step;
3264
+ step = i0, i0 = i1, i1 = step;
3265
+ }
3266
+
3267
+ while (maxIter-- > 0) {
3268
+ step = tickIncrement(start, stop, count);
3269
+ if (step === prestep) {
3270
+ d[i0] = start;
3271
+ d[i1] = stop;
3272
+ return domain(d);
3273
+ } else if (step > 0) {
3274
+ start = Math.floor(start / step) * step;
3275
+ stop = Math.ceil(stop / step) * step;
3276
+ } else if (step < 0) {
3277
+ start = Math.ceil(start * step) / step;
3278
+ stop = Math.floor(stop * step) / step;
3279
+ } else {
3280
+ break;
3281
+ }
3282
+ prestep = step;
3283
+ }
3284
+
3285
+ return scale;
3286
+ };
3287
+
3288
+ return scale;
3289
+ }
3290
+
3291
+ function linear() {
3292
+ var scale = continuous();
3293
+
3294
+ scale.copy = function() {
3295
+ return copy(scale, linear());
3296
+ };
3297
+
3298
+ initRange.apply(scale, arguments);
3299
+
3300
+ return linearish(scale);
3301
+ }
3302
+
3303
+ function transformPow(exponent) {
3304
+ return function(x) {
3305
+ return x < 0 ? -Math.pow(-x, exponent) : Math.pow(x, exponent);
3306
+ };
3307
+ }
3308
+
3309
+ function transformSqrt(x) {
3310
+ return x < 0 ? -Math.sqrt(-x) : Math.sqrt(x);
3311
+ }
3312
+
3313
+ function transformSquare(x) {
3314
+ return x < 0 ? -x * x : x * x;
3315
+ }
3316
+
3317
+ function powish(transform) {
3318
+ var scale = transform(identity$1, identity$1),
3319
+ exponent = 1;
3320
+
3321
+ function rescale() {
3322
+ return exponent === 1 ? transform(identity$1, identity$1)
3323
+ : exponent === 0.5 ? transform(transformSqrt, transformSquare)
3324
+ : transform(transformPow(exponent), transformPow(1 / exponent));
3325
+ }
3326
+
3327
+ scale.exponent = function(_) {
3328
+ return arguments.length ? (exponent = +_, rescale()) : exponent;
3329
+ };
3330
+
3331
+ return linearish(scale);
3332
+ }
3333
+
3334
+ function pow() {
3335
+ var scale = powish(transformer());
3336
+
3337
+ scale.copy = function() {
3338
+ return copy(scale, pow()).exponent(scale.exponent());
3339
+ };
3340
+
3341
+ initRange.apply(scale, arguments);
3342
+
3343
+ return scale;
3344
+ }
3345
+
3346
+ function sqrt() {
3347
+ return pow.apply(null, arguments).exponent(0.5);
3348
+ }
3349
+
3350
+ const BAR_SCALES = ["log", "sqrt", "linear"];
3351
+
3352
+ /**
3353
+ * Bar-length scale for the count histogram: mass -> pixel length.
3354
+ *
3355
+ * The default is LOG, and that is not a stylistic choice. Real hierarchies of
3356
+ * this kind have pathological count distributions — a photo library where one
3357
+ * "Unknown date" bucket holds 113,656 of 114,125 photos is a true story. Under a
3358
+ * linear scale every other bar is the 4px minimum; under sqrt, a busy 300-photo
3359
+ * day still renders at 5% of the track. Both turn the histogram into a row of
3360
+ * identical stubs that encode nothing. `log1p(300)/log1p(113656) = 49%` — the
3361
+ * silhouette comes back.
3362
+ *
3363
+ * Use `linear` when the counts are known to be well-behaved and you want the
3364
+ * bars to be honestly proportional.
3365
+ *
3366
+ * @param {number} maxCount
3367
+ * @param {number} maxLenPx
3368
+ * @param {{minLenPx?: number, type?: "log"|"sqrt"|"linear"}} [opts]
3369
+ * @returns {(count: number) => number}
3370
+ */
3371
+ function makeBarScale(maxCount, maxLenPx, opts = {}) {
3372
+ const { minLenPx = 4, type = "log" } = opts;
3373
+ const hi = Math.max(1, maxCount);
3374
+
3375
+ if (type === "log") {
3376
+ // log1p, not scaleLog: the domain starts at 0 (an empty group is legal) and
3377
+ // log(0) is -Infinity.
3378
+ const denom = Math.log1p(hi);
3379
+ return (count) => {
3380
+ const c = Math.max(0, Math.min(count, hi));
3381
+ const t = denom > 0 ? Math.log1p(c) / denom : 0;
3382
+ return minLenPx + (maxLenPx - minLenPx) * t;
3383
+ };
3384
+ }
3385
+
3386
+ const scale = type === "linear" ? linear() : sqrt();
3387
+ return scale.domain([0, hi]).range([minLenPx, maxLenPx]).clamp(true);
3388
+ }
3389
+
3390
+ /**
3391
+ * The layout: one signature, three named strategies, ONE row contract.
3392
+ *
3393
+ * The strategies are not three algorithms — they are three cells of a 2x2 over
3394
+ * two independent stages, `selection` x `positioning`:
3395
+ *
3396
+ * | uniform positions | fisheye positions
3397
+ * -------------+-------------------+-------------------
3398
+ * all leaves | "uniform" | "fisheye"
3399
+ * DOI-selected | "doi" | "hybrid"
3400
+ *
3401
+ * Everything downstream (bands, renderers, tests) is shared, so adding a fourth
3402
+ * strategy means adding a selector or a positioner, never a new pipeline.
3403
+ *
3404
+ * Note what this dissolves: AutoGallery's old `positioning: "rank" | "proportional"`
3405
+ * knob existed only because decimation squashed the near-focus leaves into a
3406
+ * sub-pixel sliver. Here, "fisheye" never decimates (so rank IS proportional),
3407
+ * and "hybrid" magnifies over DOI-selected slots (so rank is simply correct).
3408
+ * The knob has no reason to exist.
3409
+ */
3410
+
3411
+
3412
+ const LAYOUTS = ["fisheye", "doi", "hybrid", "uniform"];
3413
+
3414
+ const LAYOUT_DEFAULTS = {
3415
+ /** Fisheye strength. Higher = gentler. (Ported knob; same meaning as before.) */
3416
+ distortion: 4,
3417
+ /** Top/bottom inset, px. */
3418
+ pad: 6,
3419
+ /** Target minimum row height — sets the DOI row budget. */
3420
+ minRowPx: 16,
3421
+ /** What a band's HEIGHT encodes.
3422
+ * "slots" — every visible group gets equal room, so height reads as INTEREST.
3423
+ * "count" — height is proportional to photo mass, so a 40k-photo year visibly
3424
+ * dwarfs a 400-photo one. A true value-encoded partition diagram. */
3425
+ sizeBy: "slots",
3426
+ /** Under `sizeBy: "count"`, the fraction of the column split EQUALLY before the
3427
+ * rest is divided by mass. Without it, a zero-count group gets a zero-height
3428
+ * band: invisible and impossible to click. 1 collapses back to "slots", so the
3429
+ * two modes are the ends of one continuum. */
3430
+ sizeFloor: 0.25,
3431
+ /** DOI: penalty for sitting at a different level than the focus. */
3432
+ apiWeight: 0.5,
3433
+ /** DOI: how fast interest falls off with distance from the focus. */
3434
+ distanceWeight: 1,
3435
+ /** DOI: 0 = distance measured purely along the leaf axis (a clean readable
3436
+ * window, blind to structure); 1 = purely tree distance (keeps the focus's
3437
+ * siblings and cousins, but scatters survivors down the column). */
3438
+ treeWeight: 0.6,
3439
+ /** DOI: how much photo mass earns a row. A weak tiebreaker by design — turn it
3440
+ * up and the lens becomes a popularity chart instead of a "where am I". */
3441
+ countWeight: 0.25,
3442
+ };
3443
+
3444
+ /**
3445
+ * @param {any} root a decorated hierarchy (see hierarchy.js `normalize`)
3446
+ * @param {object} options
3447
+ * @param {number} options.height
3448
+ * @param {"fisheye"|"doi"|"hybrid"|"uniform"} [options.layout="fisheye"]
3449
+ * @param {{leaf?: number, px?: number}} [options.focus] focus by leaf index, or
3450
+ * pinned to a cursor pixel. Pixel wins when both are given — that is what keeps
3451
+ * the magnified row exactly under the pointer.
3452
+ * @returns {{rows: any[], maxCount: number, focusLeaf: number, focusPx: number,
3453
+ * slots: number, leaves: number}}
3454
+ */
3455
+ function layout(root, options = {}) {
3456
+ const o = { ...LAYOUT_DEFAULTS, ...options };
3457
+ const height = o.height ?? 0;
3458
+ const leaves = leavesOf(root);
3459
+ const n = leaves.length;
3460
+
3461
+ const min = o.pad;
3462
+ const max = height - o.pad;
3463
+ if (!n || max <= min) {
3464
+ return {
3465
+ rows: [],
3466
+ maxCount: 0,
3467
+ focusLeaf: 0,
3468
+ focusPx: min,
3469
+ slots: 0,
3470
+ leaves: n,
3471
+ };
3472
+ }
3473
+
3474
+ const strategy = LAYOUTS.includes(o.layout) ? o.layout : "fisheye";
3475
+ const usesDOI = strategy === "doi" || strategy === "hybrid";
3476
+ const usesFisheye = strategy === "fisheye" || strategy === "hybrid";
3477
+
3478
+ const sizeBy = SIZE_BY.includes(o.sizeBy) ? o.sizeBy : "slots";
3479
+ const sizing = { min, max, sizeBy, sizeFloor: o.sizeFloor };
3480
+
3481
+ const budget = Math.max(4, Math.floor((max - min) / o.minRowPx));
3482
+
3483
+ // Which leaf is the focus? Under DOI this looks circular — the slot axis exists
3484
+ // only once DOI has run, DOI needs a focus leaf, and the focus leaf is whatever
3485
+ // sits under the cursor — but it isn't, as long as the caller says which ROW it
3486
+ // is pointing at. The widget reads that off the frame it just drew (only it can:
3487
+ // a pixel means whatever was last painted there, and this function is pure), and
3488
+ // one pass resolves everything:
3489
+ //
3490
+ // seed leaf -> DOI selects the slots -> the slot at the cursor is the focus.
3491
+ //
3492
+ // The old code had no seed, so it mapped the cursor pixel onto the WHOLE-LEAF
3493
+ // axis instead. On a real library that is about one leaf per pixel, while the
3494
+ // rows on screen are the ~35 DOI slots at ~16px apart — so one row of mouse
3495
+ // travel moved the focus by ~30 leaves. You could not hover from 06 Feb to
3496
+ // 07 Feb; it jumped straight to 06 Mar.
3497
+ //
3498
+ // Resist the urge to iterate this to a fixed point (focus the slot under the
3499
+ // cursor, re-select, repeat). It converges, and it is worse: pointing just past
3500
+ // the last open day lands on the collapsed month below, and the chase then
3501
+ // re-centres INSIDE it — 27 Jan jumps to 27 Feb. One pass steps into the month
3502
+ // and lets the next hover open it.
3503
+ const px = o.focus?.px != null ? clamp(o.focus.px, min, max) : null;
3504
+ const seed =
3505
+ o.focus?.leaf != null
3506
+ ? clamp(o.focus.leaf, 0, n - 1)
3507
+ : px != null
3508
+ ? // No seed (the first frame, before anything has been drawn). The leaf
3509
+ // axis is the only axis there is; it is a rough guess, and the very next
3510
+ // pointermove replaces it with the real row.
3511
+ resolveFocus({ px }, basePositions(leaves, sizing)).slot
3512
+ : 0;
3513
+
3514
+ const slots = usesDOI
3515
+ ? selectDOI(root, { ...o, budget, focusLeaf: seed })
3516
+ : selectAll(root);
3517
+ const S = slots.length;
3518
+ const basePos = basePositions(slots, sizing);
3519
+
3520
+ // The row under the cursor. Safe to read off the BASE axis: the fisheye pins
3521
+ // `px` as a fixed point, so the slot whose base band contains it is exactly the
3522
+ // slot whose DRAWN band contains it — which is what makes the row you click the
3523
+ // row you pointed at.
3524
+ const focusSlot =
3525
+ px != null ? slotAtPixel(basePos, px) : slotOfLeaf(slots, seed);
3526
+ const focusLeaf = px != null ? slots[focusSlot].leafStart : seed;
3527
+ const focus = {
3528
+ px: px ?? (basePos[focusSlot] + basePos[focusSlot + 1]) / 2,
3529
+ slot: focusSlot,
3530
+ };
3531
+
3532
+ // The lens distorts whatever base it is handed — equal spans or mass-weighted.
3533
+ // It only needs monotonicity, which both give it.
3534
+ const pos = usesFisheye
3535
+ ? distort(basePos, { focusPx: focus.px, distortion: o.distortion })
3536
+ : basePos;
3537
+
3538
+ const { rows, maxCount } = buildRows(root, slots, pos, {
3539
+ focusSlot: focus.slot,
3540
+ });
3541
+
3542
+ return {
3543
+ rows,
3544
+ maxCount,
3545
+ focusLeaf,
3546
+ focusPx: focus.px,
3547
+ focusSlot: focus.slot,
3548
+ slots: S,
3549
+ leaves: n,
3550
+ };
3551
+ }
3552
+
3553
+ /** Which slot holds a given leaf. Slots are ordered, so binary search. */
3554
+ function slotOfLeaf(slots, leaf) {
3555
+ let lo = 0;
3556
+ let hi = slots.length - 1;
3557
+ while (lo < hi) {
3558
+ const mid = (lo + hi) >> 1;
3559
+ if (slots[mid].leafEnd <= leaf) lo = mid + 1;
3560
+ else hi = mid;
3561
+ }
3562
+ return lo;
3563
+ }
3564
+
3565
+ /**
3566
+ * One stylesheet, injected once. Everything is expressed as a CSS custom
3567
+ * property on `.fisheye-nav`, so a host restyles the widget without a build step
3568
+ * and without the widget knowing anything about the host's design system.
3569
+ *
3570
+ * Colors are derived from a single hue + the host's text color, and the widget
3571
+ * inherits `color-scheme`, so it lands correctly in a light or a dark app
3572
+ * without being told which it is in.
3573
+ */
3574
+ const CSS = `
3575
+ .fisheye-nav {
3576
+ --fn-accent: #3b82f6;
3577
+ --fn-fg: currentColor;
3578
+ --fn-muted: color-mix(in oklab, currentColor 55%, transparent);
3579
+ --fn-band: color-mix(in oklab, currentColor 8%, transparent);
3580
+ --fn-band-hover: color-mix(in oklab, currentColor 16%, transparent);
3581
+ --fn-rule: color-mix(in oklab, currentColor 18%, transparent);
3582
+ --fn-bar: color-mix(in oklab, var(--fn-accent) 45%, transparent);
3583
+ --fn-font: system-ui, -apple-system, "Segoe UI", sans-serif;
3584
+ --fn-size: 11px;
3585
+
3586
+ position: relative;
3587
+ display: block;
3588
+ width: 100%;
3589
+ height: 100%;
3590
+ font-family: var(--fn-font);
3591
+ font-size: var(--fn-size);
3592
+ color: var(--fn-fg);
3593
+ user-select: none;
3594
+ }
3595
+ .fisheye-nav svg { display: block; width: 100%; height: 100%; overflow: hidden; }
3596
+ .fisheye-nav .fn-row { cursor: pointer; }
3597
+ .fisheye-nav .fn-band {
3598
+ fill: var(--fn-band);
3599
+ stroke: var(--fn-rule);
3600
+ stroke-width: 0.5;
3601
+ shape-rendering: crispEdges;
3602
+ }
3603
+ .fisheye-nav .fn-row:hover .fn-band { fill: var(--fn-band-hover); }
3604
+ .fisheye-nav .fn-row[data-kind="branch"] .fn-band { fill: color-mix(in oklab, currentColor 4%, transparent); }
3605
+ .fisheye-nav .fn-row[data-kind="elision"] .fn-band { fill: none; stroke-dasharray: 2 2; }
3606
+ .fisheye-nav .fn-row[data-focused="true"] .fn-band {
3607
+ fill: color-mix(in oklab, var(--fn-accent) 22%, transparent);
3608
+ stroke: var(--fn-accent);
3609
+ stroke-width: 1;
3610
+ }
3611
+ .fisheye-nav .fn-selected .fn-band {
3612
+ stroke: var(--fn-accent);
3613
+ stroke-width: 1.5;
3614
+ }
3615
+ .fisheye-nav .fn-bar { fill: var(--fn-bar); }
3616
+ .fisheye-nav .fn-label {
3617
+ fill: var(--fn-fg);
3618
+ dominant-baseline: middle;
3619
+ pointer-events: none;
3620
+ white-space: pre;
3621
+ }
3622
+ .fisheye-nav .fn-row[data-kind="branch"] .fn-label,
3623
+ .fisheye-nav .fn-row[data-kind="elision"] .fn-label { fill: var(--fn-muted); }
3624
+ .fisheye-nav .fn-count { fill: var(--fn-muted); text-anchor: end; dominant-baseline: middle; pointer-events: none; }
3625
+ .fisheye-nav .fn-spine { fill: var(--fn-rule); }
3626
+ .fisheye-nav .fn-empty { fill: var(--fn-muted); text-anchor: middle; }
3627
+
3628
+ /* ── Settings gear + popover (opt out with controls: false) ──────────────────
3629
+ Neutral defaults driven by the same --fn-* variables as the chart, so a host
3630
+ restyles the panel without patching the library. */
3631
+ .fisheye-nav .fn-gear {
3632
+ position: absolute; top: 2px; right: 4px; z-index: 6;
3633
+ width: 18px; height: 18px; padding: 0; border: none; border-radius: 4px;
3634
+ background: transparent; color: var(--fn-muted);
3635
+ font-size: 12px; line-height: 18px; cursor: pointer;
3636
+ }
3637
+ .fisheye-nav .fn-gear:hover,
3638
+ .fisheye-nav .fn-gear.on { color: var(--fn-fg); background: var(--fn-band-hover); }
3639
+ /* Visibility is driven by the .fn-open CLASS, not by the hidden attribute: the
3640
+ UA's "[hidden] { display: none }" is a single-attribute selector, so any rule
3641
+ here that sets display outranks it and setting .hidden silently does nothing.
3642
+ (It did exactly that — every popover in the demo rendered open.) The hidden
3643
+ attribute is still kept in sync, for assistive tech.
3644
+ NB: no backticks in this comment — the whole stylesheet is a JS template
3645
+ literal, and a backtick here would terminate it. */
3646
+ /* The popover is the ONE place the widget paints its own background, so it is
3647
+ the one place "inherit the host's color" stops working: an inherited
3648
+ foreground over a system background is a coin toss (a dark app's near-white
3649
+ text landed on Canvas-white and vanished). Background and foreground must
3650
+ come from the same place — so they are a system PAIR by default, and a host
3651
+ overriding one is expected to override the other. color-scheme makes the
3652
+ pair, and the native selects and sliders inside, follow the host's theme. */
3653
+ .fisheye-nav .fn-panel {
3654
+ position: absolute; top: 22px; right: 4px; z-index: 7;
3655
+ width: 220px; padding: 8px; display: none; flex-direction: column; gap: 6px;
3656
+ color-scheme: var(--fn-scheme, light dark);
3657
+ background: var(--fn-panel, Canvas);
3658
+ color: var(--fn-panel-fg, CanvasText);
3659
+ border: 1px solid var(--fn-rule); border-radius: 6px;
3660
+ box-shadow: 0 6px 20px rgb(0 0 0 / 0.28);
3661
+ }
3662
+ .fisheye-nav .fn-panel.fn-open { display: flex; }
3663
+ .fisheye-nav .fn-row-ctl { display: flex; align-items: center; gap: 6px; }
3664
+ .fisheye-nav .fn-ctl-label { flex: 0 0 76px; opacity: 0.75; }
3665
+ .fisheye-nav .fn-ctl-select {
3666
+ flex: 1; min-width: 0; font: inherit; padding: 2px 4px;
3667
+ color: inherit; background: transparent;
3668
+ border: 1px solid var(--fn-rule); border-radius: 4px;
3669
+ }
3670
+ .fisheye-nav .fn-ctl-slider { flex: 1; display: flex; align-items: center; gap: 6px; min-width: 0; }
3671
+ .fisheye-nav .fn-ctl-slider input { flex: 1; min-width: 0; accent-color: var(--fn-accent); }
3672
+ .fisheye-nav .fn-ctl-val {
3673
+ flex: 0 0 30px; text-align: right; opacity: 0.6;
3674
+ font-variant-numeric: tabular-nums;
3675
+ }
3676
+ .fisheye-nav .fn-ctl-more summary { cursor: pointer; opacity: 0.75; margin-bottom: 4px; }
3677
+ .fisheye-nav .fn-ctl-more[open] { border-top: 1px solid var(--fn-rule); padding-top: 6px; }
3678
+ .fisheye-nav .fn-ctl-reset {
3679
+ align-self: flex-start; font: inherit; padding: 2px 8px; cursor: pointer;
3680
+ color: inherit; background: transparent;
3681
+ border: 1px solid var(--fn-rule); border-radius: 4px;
3682
+ }
3683
+ /* A control that cannot affect the current lens says so, rather than silently
3684
+ doing nothing when dragged. */
3685
+ .fisheye-nav .fn-disabled { opacity: 0.4; }
3686
+ `;
3687
+
3688
+ let injected = false;
3689
+
3690
+ function injectStyle(doc = globalThis.document) {
3691
+ if (injected || !doc?.head) return;
3692
+ const el = doc.createElement("style");
3693
+ el.setAttribute("data-fisheye-nav", "");
3694
+ el.textContent = CSS;
3695
+ doc.head.appendChild(el);
3696
+ injected = true;
3697
+ }
3698
+
3699
+ /**
3700
+ * The renderers. Both consume the SAME rows, so neither knows (or can know)
3701
+ * which layout strategy produced them — that is what keeps `style` and `layout`
3702
+ * genuinely orthogonal instead of a 6-way switch.
3703
+ *
3704
+ * flat one column, indented by depth. Internal nodes get a real row (their
3705
+ * synthetic header cell), so "what level am I on" is answerable at a
3706
+ * glance. This is an outline.
3707
+ * icicle one column per depth; a node's band is its children's span. This is
3708
+ * a partition diagram whose vertical axis happens to be fisheyed.
3709
+ */
3710
+
3711
+
3712
+ const STYLES = ["flat", "icicle"];
3713
+
3714
+ const RENDER_DEFAULTS = {
3715
+ /** px of indent per level (flat). */
3716
+ indent: 11,
3717
+ /** Draw the count histogram INSIDE each band (the row is the bar's track, the
3718
+ * label sits on top). False hides it. */
3719
+ bars: true,
3720
+ /** px of clear space kept at the right edge. */
3721
+ gutter: 6,
3722
+ /** don't draw a label in a band thinner than this — it would just be noise. */
3723
+ minLabelPx: 9,
3724
+ /** count-histogram scale. Log by default — see scales.js for why. */
3725
+ barScale: "log",
3726
+ /** count formatter for the histogram tooltip/label. */
3727
+ format: (n) => n.toLocaleString(),
3728
+ };
3729
+
3730
+ /**
3731
+ * @param {SVGElement} svg
3732
+ * @param {{rows: any[], maxCount: number}} model a `layout()` result
3733
+ * @param {object} opts width, height, style, selectedId, + RENDER_DEFAULTS
3734
+ */
3735
+ function render(svg, model, opts) {
3736
+ const o = { ...RENDER_DEFAULTS, ...opts };
3737
+ injectStyle(svg.ownerDocument);
3738
+
3739
+ const root = select(svg);
3740
+ const { rows, maxCount } = model;
3741
+ const { width, height, style } = o;
3742
+
3743
+ root.attr("viewBox", `0 0 ${width} ${height}`);
3744
+
3745
+ if (!rows.length) {
3746
+ root.selectAll(".fn-row").remove();
3747
+ root
3748
+ .selectAll(".fn-empty")
3749
+ .data([0])
3750
+ .join("text")
3751
+ .attr("class", "fn-empty")
3752
+ .attr("x", width / 2)
3753
+ .attr("y", height / 2)
3754
+ .text(o.emptyLabel ?? "Nothing to show");
3755
+ return;
3756
+ }
3757
+ root.selectAll(".fn-empty").remove();
3758
+
3759
+ // The bar's track is the ROW, not a column of its own: length encodes photo
3760
+ // mass while the band's height encodes the lens, so the column reads as a
3761
+ // histogram silhouette (the original AutoGallery design). The label is drawn
3762
+ // over it.
3763
+ const trackW = width - o.gutter;
3764
+ const maxDepth = rows.reduce((m, r) => Math.max(m, r.depth), 1);
3765
+ const geom =
3766
+ style === "icicle"
3767
+ ? icicleGeom(maxDepth, trackW)
3768
+ : flatGeom(o.indent, trackW);
3769
+
3770
+ // Which rows get a bar. In an icicle the inner nodes own a column of their own,
3771
+ // so they show their AGGREGATE — the count of the whole subtree they stand for.
3772
+ // In flat mode they don't: a branch's band spans all of its children, so a bar
3773
+ // across it would just be a block sitting behind them.
3774
+ const barred = (d) =>
3775
+ o.bars &&
3776
+ d.count > 0 &&
3777
+ (d.terminal || (style === "icicle" && d.kind === "branch"));
3778
+
3779
+ // Flat: ONE scale, absolute lengths, because every row shares one track — a
3780
+ // per-row scale would draw equal counts at different lengths depending on how
3781
+ // deep the row sits, which is a lie. A deeper row starts further right, so its
3782
+ // bar is clipped to its own band.
3783
+ const flatScale = makeBarScale(maxCount, Math.max(1, trackW), {
3784
+ type: o.barScale,
3785
+ });
3786
+
3787
+ // Icicle: each depth is a column, so each depth is its OWN histogram. A year
3788
+ // (40,000 photos) and a day (300) do not belong on one scale — shared, every
3789
+ // year's bar pegs at full width and the column encodes nothing. So the bar is a
3790
+ // fraction of the row's own width, taken from a scale over that depth's max.
3791
+ const depthScale = new Map();
3792
+ if (style === "icicle") {
3793
+ const maxAt = new Map();
3794
+ for (const r of rows)
3795
+ if (barred(r))
3796
+ maxAt.set(r.depth, Math.max(maxAt.get(r.depth) ?? 0, r.count));
3797
+ for (const [depth, m] of maxAt)
3798
+ depthScale.set(
3799
+ depth,
3800
+ makeBarScale(m, 1, { type: o.barScale, minLenPx: 0.05 }),
3801
+ );
3802
+ }
3803
+
3804
+ const barLen = (d) => {
3805
+ if (!barred(d)) return 0;
3806
+ const w = Math.max(0, geom.w(d));
3807
+ return style === "icicle"
3808
+ ? (depthScale.get(d.depth)?.(d.count) ?? 0) * w
3809
+ : Math.min(flatScale(d.count), w);
3810
+ };
3811
+
3812
+ const g = root
3813
+ .selectAll("g.fn-row")
3814
+ .data(rows, (d) => d.id)
3815
+ .join((enter) => {
3816
+ const e = enter.append("g").attr("class", "fn-row");
3817
+ e.append("rect").attr("class", "fn-band");
3818
+ e.append("rect").attr("class", "fn-bar");
3819
+ e.append("text").attr("class", "fn-label");
3820
+ e.append("title");
3821
+ return e;
3822
+ });
3823
+
3824
+ g.attr("data-kind", (d) => d.kind)
3825
+ .attr("data-depth", (d) => d.depth)
3826
+ .attr("data-id", (d) => d.id)
3827
+ .attr("data-focused", (d) => (d.focused ? "true" : null))
3828
+ .classed("fn-selected", (d) => d.id === o.selectedId);
3829
+
3830
+ g.select("title").text(
3831
+ (d) =>
3832
+ `${d.label}\n${o.format(d.count)}` +
3833
+ (d.elided ? ` · ${d.elided} groups collapsed` : ""),
3834
+ );
3835
+
3836
+ g.select("rect.fn-band")
3837
+ .attr("x", (d) => geom.x(d))
3838
+ .attr("y", (d) => d.y0)
3839
+ .attr("width", (d) => Math.max(0, geom.w(d)))
3840
+ // Hairline bands still need to be clickable; 1px floor keeps the hit target.
3841
+ .attr("height", (d) => Math.max(1, d.thickness))
3842
+ // Drop the border on sub-pixel bands. In the compressed tail of an
3843
+ // undecimated fisheye, hundreds of hairline bands stack their 0.5px strokes
3844
+ // into a solid wall that swallows both the fill and the labels — the
3845
+ // silhouette turns into a white smear. Inline style, because a stylesheet
3846
+ // rule would beat a presentation attribute.
3847
+ .style("stroke-width", (d) => (d.thickness >= 2 ? 0.5 : 0));
3848
+
3849
+ // Same x and same height as the band it fills — so the lens magnifies the bar
3850
+ // along with its row, and the label (drawn after) sits over it.
3851
+ g.select("rect.fn-bar")
3852
+ .attr("x", (d) => geom.x(d))
3853
+ .attr("y", (d) => d.y0)
3854
+ .attr("width", barLen)
3855
+ .attr("height", (d) => Math.max(1, d.thickness));
3856
+
3857
+ g.select("text.fn-label")
3858
+ .attr("x", (d) => geom.x(d) + 4)
3859
+ .attr("y", (d) => d.y)
3860
+ .attr("font-weight", (d) =>
3861
+ d.kind === "header" || d.kind === "branch" ? 600 : 400,
3862
+ )
3863
+ .attr("opacity", (d) => (labelled(d, style, o) ? 1 : 0))
3864
+ .text((d) => (labelled(d, style, o) ? labelFor(d, geom.w(d)) : ""));
3865
+ }
3866
+
3867
+ /** flat: indent by depth, span the rest of the track. */
3868
+ const flatGeom = (indent, barX) => ({
3869
+ x: (d) => (d.depth - 1) * indent,
3870
+ w: (d) => barX - (d.depth - 1) * indent,
3871
+ });
3872
+
3873
+ /**
3874
+ * icicle: one column per level. A terminal row spans from its own column to the
3875
+ * end of the track, so a leaf that stops short in a ragged tree still reads as a
3876
+ * leaf rather than leaving a hole (same convention as d3's icicle).
3877
+ */
3878
+ const icicleGeom = (maxDepth, barX) => {
3879
+ const colW = barX / maxDepth;
3880
+ return {
3881
+ x: (d) => (d.depth - 1) * colW,
3882
+ w: (d) => (d.terminal ? barX - (d.depth - 1) * colW : colW),
3883
+ };
3884
+ };
3885
+
3886
+ /**
3887
+ * A branch's band spans its whole subtree, so a label centred in it would land
3888
+ * ON TOP of its children. In flat mode the branch's synthetic header row already
3889
+ * carries the name, so the branch itself stays silent — shading only. In icicle
3890
+ * mode the branch owns a column of its own, so it must be labelled.
3891
+ */
3892
+ function labelled(d, style, o) {
3893
+ if (style !== "icicle" && d.kind === "branch") return false;
3894
+ // The row you are ON and the row you have CHOSEN always say what they are, at
3895
+ // any thickness. The floor exists to stop hundreds of unreadable labels piling
3896
+ // up — it must never silence the two rows the user is actually asking about.
3897
+ // Without this, `fisheye` (which draws every leaf, so every band is a couple of
3898
+ // pixels) is a lens onto a column of anonymous stripes: you hover, and nothing
3899
+ // tells you where you are.
3900
+ if (d.focused || d.id === o.selectedId) return true;
3901
+ return d.thickness >= o.minLabelPx;
3902
+ }
3903
+
3904
+ function labelFor(d, w) {
3905
+ const text = d.kind === "elision" ? `⋯ ${d.label}` : (d.label ?? "");
3906
+ // ~6px per char at 11px system-ui; cheap and good enough to avoid measuring
3907
+ // text in a hot path that runs on every mousemove.
3908
+ const max = Math.max(0, Math.floor((w - 8) / 6));
3909
+ return text.length > max ? text.slice(0, Math.max(1, max - 1)) + "…" : text;
3910
+ }
3911
+
3912
+ /**
3913
+ * The settings gear + popover, owned by the widget.
3914
+ *
3915
+ * Same contract as @john-guerra/d3-zoomable-axis's scent controls, deliberately:
3916
+ * controls a ⚙ that live-tunes the lens. On by default; pass false to
3917
+ * suppress it and drive the options from your own UI.
3918
+ * persistKey a localStorage key, so a user's tuned lens survives a reload.
3919
+ * Pass none and listen for the "settings" event to use your own
3920
+ * store instead.
3921
+ *
3922
+ * A consumer should not have to hand-roll this — AutoGallery did, and every
3923
+ * other consumer would have too.
3924
+ */
3925
+
3926
+
3927
+ /** What the panel tunes AND persists. Never data, accessors, or sizes. */
3928
+ const PERSIST_KEYS = [
3929
+ "style",
3930
+ "layout",
3931
+ "sizeBy",
3932
+ "distortion",
3933
+ "minRowPx",
3934
+ "barScale",
3935
+ "apiWeight",
3936
+ "distanceWeight",
3937
+ "treeWeight",
3938
+ "countWeight",
3939
+ ];
3940
+
3941
+ function readStore(key) {
3942
+ if (!key || typeof localStorage === "undefined") return null;
3943
+ try {
3944
+ const s = JSON.parse(localStorage.getItem(key) ?? "null");
3945
+ return s && typeof s === "object" ? s : null;
3946
+ } catch {
3947
+ return null;
3948
+ }
3949
+ }
3950
+
3951
+ function writeStore(key, obj) {
3952
+ if (!key || typeof localStorage === "undefined") return;
3953
+ try {
3954
+ const picked = {};
3955
+ for (const k of PERSIST_KEYS) if (k in obj) picked[k] = obj[k];
3956
+ localStorage.setItem(key, JSON.stringify(picked));
3957
+ } catch {
3958
+ /* quota / disabled storage — persistence is best-effort */
3959
+ }
3960
+ }
3961
+
3962
+ /** Keep only known keys with sane values: a stale or hand-edited store must not
3963
+ * be able to wedge the widget into an unrenderable state. */
3964
+ function sanitize(raw, defaults) {
3965
+ const out = {};
3966
+ if (!raw) return out;
3967
+ const num = (v, lo, hi) => {
3968
+ const n = Number(v);
3969
+ return Number.isFinite(n) ? Math.min(hi, Math.max(lo, n)) : undefined;
3970
+ };
3971
+ const oneOf = (v, list) => (list.includes(v) ? v : undefined);
3972
+ const put = (k, v) => {
3973
+ if (v !== undefined) out[k] = v;
3974
+ };
3975
+
3976
+ put("style", oneOf(raw.style, STYLES));
3977
+ put("layout", oneOf(raw.layout, LAYOUTS));
3978
+ put("sizeBy", oneOf(raw.sizeBy, SIZE_BY));
3979
+ put("barScale", oneOf(raw.barScale, BAR_SCALES));
3980
+ put("distortion", num(raw.distortion, 1, 12));
3981
+ put("minRowPx", num(raw.minRowPx, 8, 48));
3982
+ put("apiWeight", num(raw.apiWeight, 0, 3));
3983
+ put("distanceWeight", num(raw.distanceWeight, 0, 3));
3984
+ put("treeWeight", num(raw.treeWeight, 0, 1));
3985
+ put("countWeight", num(raw.countWeight, 0, 2));
3986
+ return { ...defaults, ...out };
3987
+ }
3988
+
3989
+ const SELECTS = [
3990
+ {
3991
+ key: "style",
3992
+ label: "View",
3993
+ options: [
3994
+ ["flat", "List (indented)"],
3995
+ ["icicle", "Icicle (columns)"],
3996
+ ],
3997
+ },
3998
+ {
3999
+ key: "layout",
4000
+ label: "Lens",
4001
+ options: [
4002
+ ["hybrid", "Hybrid — magnify + fold"],
4003
+ ["fisheye", "Fisheye — every group"],
4004
+ ["doi", "Interest — full rows"],
4005
+ ["uniform", "Uniform — no lens"],
4006
+ ],
4007
+ },
4008
+ {
4009
+ key: "sizeBy",
4010
+ label: "Band size",
4011
+ options: [
4012
+ ["slots", "Interest (equal)"],
4013
+ ["count", "Photos (mass)"],
4014
+ ],
4015
+ },
4016
+ {
4017
+ key: "barScale",
4018
+ label: "Bars",
4019
+ options: [
4020
+ ["log", "Log"],
4021
+ ["sqrt", "Square root"],
4022
+ ["linear", "Linear"],
4023
+ ],
4024
+ },
4025
+ ];
4026
+
4027
+ const SLIDERS = [
4028
+ { key: "distortion", label: "Distortion", min: 1, max: 12, step: 0.5 },
4029
+ { key: "minRowPx", label: "Row size", min: 8, max: 48, step: 1, unit: "px" },
4030
+ ];
4031
+
4032
+ // The DOI weights live behind a disclosure: they are where the lens's FEEL comes
4033
+ // from, but four extra sliders up front would bury the two knobs most people
4034
+ // actually want.
4035
+ const WEIGHTS = [
4036
+ { key: "distanceWeight", label: "Focus falloff", min: 0, max: 3, step: 0.1 },
4037
+ {
4038
+ key: "treeWeight",
4039
+ label: "Structure vs. list",
4040
+ min: 0,
4041
+ max: 1,
4042
+ step: 0.05,
4043
+ },
4044
+ { key: "countWeight", label: "Busy groups", min: 0, max: 2, step: 0.05 },
4045
+ { key: "apiWeight", label: "Same-level bias", min: 0, max: 3, step: 0.1 },
4046
+ ];
4047
+
4048
+ /**
4049
+ * @param {HTMLElement} host the widget root
4050
+ * @param {{get:()=>object, set:(patch:object)=>void, reset:()=>void}} io
4051
+ * @returns {{sync:()=>void, destroy:()=>void}}
4052
+ */
4053
+ function buildControls(host, io) {
4054
+ const doc = host.ownerDocument;
4055
+ const el = (tag, cls, props) =>
4056
+ Object.assign(doc.createElement(tag), { className: cls, ...props });
4057
+
4058
+ const gear = el("button", "fn-gear", {
4059
+ type: "button",
4060
+ innerHTML: "&#9881;",
4061
+ title: "Lens settings",
4062
+ });
4063
+ gear.setAttribute("aria-label", "Lens settings");
4064
+ gear.setAttribute("aria-expanded", "false");
4065
+
4066
+ const panel = el("div", "fn-panel");
4067
+ panel.hidden = true;
4068
+ panel.setAttribute("role", "group");
4069
+ panel.setAttribute("aria-label", "Lens settings");
4070
+
4071
+ const inputs = new Map();
4072
+
4073
+ const row = (label, control) => {
4074
+ const r = el("label", "fn-row-ctl");
4075
+ r.appendChild(el("span", "fn-ctl-label", { textContent: label }));
4076
+ r.appendChild(control);
4077
+ return r;
4078
+ };
4079
+
4080
+ for (const s of SELECTS) {
4081
+ const sel = el("select", "fn-ctl-select");
4082
+ for (const [value, text] of s.options) {
4083
+ sel.appendChild(el("option", "", { value, textContent: text }));
4084
+ }
4085
+ sel.addEventListener("change", () => io.set({ [s.key]: sel.value }));
4086
+ inputs.set(s.key, sel);
4087
+ panel.appendChild(row(s.label, sel));
4088
+ }
4089
+
4090
+ const slider = (s) => {
4091
+ const wrap = el("span", "fn-ctl-slider");
4092
+ const input = el("input", "", {
4093
+ type: "range",
4094
+ min: String(s.min),
4095
+ max: String(s.max),
4096
+ step: String(s.step),
4097
+ });
4098
+ const out = el("span", "fn-ctl-val");
4099
+ input.addEventListener("input", () => {
4100
+ out.textContent = input.value + (s.unit ?? "");
4101
+ io.set({ [s.key]: Number(input.value) });
4102
+ });
4103
+ wrap.append(input, out);
4104
+ inputs.set(s.key, input);
4105
+ return { wrap, input, out, spec: s };
4106
+ };
4107
+
4108
+ const sliders = [];
4109
+ for (const s of SLIDERS) {
4110
+ const made = slider(s);
4111
+ sliders.push(made);
4112
+ panel.appendChild(row(s.label, made.wrap));
4113
+ }
4114
+
4115
+ const details = el("details", "fn-ctl-more");
4116
+ details.appendChild(el("summary", "", { textContent: "Interest weights" }));
4117
+ for (const s of WEIGHTS) {
4118
+ const made = slider(s);
4119
+ sliders.push(made);
4120
+ details.appendChild(row(s.label, made.wrap));
4121
+ }
4122
+ panel.appendChild(details);
4123
+
4124
+ const reset = el("button", "fn-ctl-reset", {
4125
+ type: "button",
4126
+ textContent: "Reset",
4127
+ });
4128
+ reset.addEventListener("click", () => io.reset());
4129
+ panel.appendChild(reset);
4130
+
4131
+ // `.fn-open` is what actually shows the panel — see style.js. `hidden` is kept
4132
+ // in sync for assistive tech, but it cannot be trusted to hide anything on its
4133
+ // own once the stylesheet sets `display`.
4134
+ const toggle = (open = panel.hidden) => {
4135
+ panel.hidden = !open;
4136
+ panel.classList.toggle("fn-open", open);
4137
+ gear.classList.toggle("on", open);
4138
+ gear.setAttribute("aria-expanded", String(open));
4139
+ };
4140
+ gear.addEventListener("click", () => toggle());
4141
+
4142
+ // Esc closes; a click outside closes. Both are what a popover is expected to
4143
+ // do, and neither is worth making every consumer reimplement.
4144
+ const onKey = (e) => {
4145
+ if (e.key === "Escape" && !panel.hidden) toggle(false);
4146
+ };
4147
+ const onDocClick = (e) => {
4148
+ if (panel.hidden) return;
4149
+ if (!panel.contains(e.target) && e.target !== gear) toggle(false);
4150
+ };
4151
+ host.addEventListener("keydown", onKey);
4152
+ doc.addEventListener("click", onDocClick, true);
4153
+
4154
+ host.append(gear, panel);
4155
+
4156
+ const sync = () => {
4157
+ const o = io.get();
4158
+ for (const [key, input] of inputs) {
4159
+ const v = o[key];
4160
+ if (input.tagName === "SELECT") input.value = String(v);
4161
+ else input.value = String(v);
4162
+ }
4163
+ for (const s of sliders) {
4164
+ s.out.textContent = String(o[s.spec.key]) + (s.spec.unit ?? "");
4165
+ }
4166
+ // Distortion means nothing without a lens; say so rather than letting the
4167
+ // user drag a slider that does nothing.
4168
+ const lensed = o.layout === "fisheye" || o.layout === "hybrid";
4169
+ const dist = inputs.get("distortion");
4170
+ dist.disabled = !lensed;
4171
+ dist.closest(".fn-row-ctl").classList.toggle("fn-disabled", !lensed);
4172
+ // Likewise the interest weights only matter when DOI is doing the selecting.
4173
+ const doi = o.layout === "doi" || o.layout === "hybrid";
4174
+ details.classList.toggle("fn-disabled", !doi);
4175
+ for (const w of WEIGHTS) inputs.get(w.key).disabled = !doi;
4176
+ };
4177
+
4178
+ sync();
4179
+
4180
+ return {
4181
+ sync,
4182
+ destroy() {
4183
+ host.removeEventListener("keydown", onKey);
4184
+ doc.removeEventListener("click", onDocClick, true);
4185
+ gear.remove();
4186
+ panel.remove();
4187
+ },
4188
+ };
4189
+ }
4190
+
4191
+ /**
4192
+ * The widget: a reactivewidgets-style DOM node.
4193
+ *
4194
+ * const nav = fisheyeNav({ data, keys: ["year","month","day"] });
4195
+ * nav.addEventListener("input", () => console.log(nav.value)); // the path
4196
+ * nav.value = [{key:"year", value:"2024"}]; // set silently
4197
+ *
4198
+ * `value` is the path to whatever the user clicked, truncated at that depth:
4199
+ * click a day and you get the full 3-level path; click the "2024" band and you
4200
+ * get just [{key:"year", value:"2024"}]. Hover drives the LENS and never fires
4201
+ * `input` — otherwise every mousemove would look like a selection.
4202
+ */
4203
+
4204
+
4205
+ const NAV_DEFAULTS = {
4206
+ ...LAYOUT_DEFAULTS,
4207
+ ...RENDER_DEFAULTS,
4208
+ style: "flat",
4209
+ /** A ⚙ that live-tunes the lens. Pass false to drive the options yourself. */
4210
+ controls: true,
4211
+ /** localStorage key, so a tuned lens survives a reload. Omit and listen for
4212
+ * the "settings" event to use your own store instead. */
4213
+ persistKey: null,
4214
+ // `hybrid`, not `fisheye`, is the default: pure fisheye draws every leaf, which
4215
+ // on a real library (thousands of days) means thousands of sub-pixel bands —
4216
+ // honest about density, unreadable as a navigator. Hybrid bounds the row count
4217
+ // to what actually fits and stays readable at any library size. Pick `fisheye`
4218
+ // deliberately when you want the undecimated silhouette.
4219
+ layout: "hybrid",
4220
+ width: null, // null = measure the container
4221
+ height: null,
4222
+ };
4223
+
4224
+ function fisheyeNav(options = {}) {
4225
+ const doc = options.document ?? globalThis.document;
4226
+ const el = doc.createElement("div");
4227
+ el.className = "fisheye-nav";
4228
+ injectStyle(doc);
4229
+
4230
+ const svg = doc.createElementNS("http://www.w3.org/2000/svg", "svg");
4231
+ svg.setAttribute("preserveAspectRatio", "none");
4232
+ svg.setAttribute("role", "listbox");
4233
+ el.appendChild(svg);
4234
+
4235
+ // A persisted lens wins over the defaults but NOT over what the caller passed
4236
+ // explicitly — a host pinning `style: "icicle"` in code means it, and a stale
4237
+ // localStorage entry must not silently override it.
4238
+ const stored = sanitize(readStore(options.persistKey), {});
4239
+ let opts = { ...NAV_DEFAULTS, ...stored, ...options };
4240
+ let root = null; // the normalized hierarchy
4241
+ let model = null; // the last layout result
4242
+ let hoverPx = null; // the pinned cursor pixel, or null when not hovering
4243
+ // Where DOI opens its window. Moves ONLY on a click (see the click handler) —
4244
+ // never on hover, or the rows reshuffle under the cursor. Null = follow the
4245
+ // selection.
4246
+ let anchorLeaf = null;
4247
+ let size = { width: 0, height: 0 };
4248
+ let controls = null;
4249
+
4250
+ // --- state derivation -----------------------------------------------------
4251
+
4252
+ const rebuild = () => {
4253
+ root = normalize$1({
4254
+ data: opts.data,
4255
+ keys: opts.keys,
4256
+ root: opts.root,
4257
+ children: opts.children,
4258
+ value: opts.value,
4259
+ count: opts.count,
4260
+ label: opts.label,
4261
+ // Flat mode needs a real row per internal node to have something to indent;
4262
+ // an icicle gives parents a column instead, so headers would be redundant.
4263
+ headers: opts.style === "flat",
4264
+ });
4265
+ };
4266
+
4267
+ /** The leaf the current selection sits on — where the lens rests when not hovering. */
4268
+ const selectedLeaf = () => {
4269
+ const path = el.value;
4270
+ if (!path?.length || !root) return 0;
4271
+ let node = root;
4272
+ for (const step of path) {
4273
+ const next = (node.children ?? []).find(
4274
+ (c) =>
4275
+ !c.data.header &&
4276
+ c.data.key === step.key &&
4277
+ c.data.value === step.value,
4278
+ );
4279
+ if (!next) break;
4280
+ node = next;
4281
+ }
4282
+ return node.leafStart ?? 0;
4283
+ };
4284
+
4285
+ // `idOfPath`, not a second copy of the same join. This built the id with a
4286
+ // SPACE while the rows built it with PATH_SEP, so any selection deeper than one
4287
+ // level failed to match its row: selecting a day never highlighted it (and,
4288
+ // once the label floor learned about the selection, never labelled it either).
4289
+ const selectedId = () => {
4290
+ const path = el.value;
4291
+ return path?.length ? idOfPath(path) : null;
4292
+ };
4293
+
4294
+ const measure = () => {
4295
+ const w = opts.width ?? el.clientWidth;
4296
+ const h = opts.height ?? el.clientHeight;
4297
+ size = { width: Math.max(0, w), height: Math.max(0, h) };
4298
+ };
4299
+
4300
+ const draw = () => {
4301
+ if (!root) rebuild();
4302
+ measure();
4303
+ if (!size.width || !size.height) return;
4304
+
4305
+ model = layout(root, {
4306
+ ...opts,
4307
+ height: size.height,
4308
+ // Two focuses, and keeping them apart is the whole trick: the PIXEL steers
4309
+ // the lens, continuously; the LEAF decides which rows DOI opens, and it
4310
+ // moves only on a click. See the pointermove and click handlers.
4311
+ focus: { px: hoverPx ?? undefined, leaf: anchorLeaf ?? selectedLeaf() },
4312
+ });
4313
+
4314
+ render(svg, model, { ...opts, ...size, selectedId: selectedId() });
4315
+ };
4316
+
4317
+ // --- interaction ----------------------------------------------------------
4318
+
4319
+ /**
4320
+ * HOVER MOVES THE LENS. IT DOES NOT RE-SELECT. This is load-bearing.
4321
+ *
4322
+ * A lens is only stable over a FIXED set of rows. DOI selection is not fixed —
4323
+ * it is a function of the focus — so re-running it on every mousemove reshuffles
4324
+ * the rows under the cursor and the leaf you are pointing at changes
4325
+ * discontinuously: hovering down through January you get 27 Jan, Feb, 23 Feb,
4326
+ * 27 Feb, Mar, and whole weeks are simply unreachable. (Plain `fisheye` selects
4327
+ * every leaf, so its set is fixed, and it never does this.)
4328
+ *
4329
+ * Re-anchoring DOI on whatever the cursor touches does not fix it either: the
4330
+ * row budget is fixed, so opening one region collapses another, and the tail
4331
+ * oscillates — 9 more, 8 more, ... 2 more, 9 more, forever.
4332
+ *
4333
+ * So which rows are open changes only when the user SAYS so, by clicking. Hover
4334
+ * magnifies what is there; a click drills in and re-opens the window around it
4335
+ * (via `selectedLeaf`). That is the DOI-browser tradition, and it is what the
4336
+ * original AutoGallery sidebar did — its decimated set was fixed too, which is
4337
+ * precisely why hovering it never jumped.
4338
+ */
4339
+ svg.addEventListener("pointermove", (e) => {
4340
+ hoverPx = pointer(e, svg)[1];
4341
+ draw();
4342
+ });
4343
+
4344
+ svg.addEventListener("pointerleave", () => {
4345
+ hoverPx = null; // the lens snaps back to the selection
4346
+ draw();
4347
+ });
4348
+
4349
+ /**
4350
+ * EVERY ITEM MUST BE SELECTABLE. The column shows ~40 rows of a library that
4351
+ * may hold thousands of leaves, so most of them are, at any moment, folded into
4352
+ * a closed subtree or an elision. Reaching them therefore has to be a matter of
4353
+ * DRILLING IN — and every click must make progress toward that, or some leaves
4354
+ * are unreachable forever.
4355
+ *
4356
+ * Which is why a click moves the DOI anchor INTO what was clicked, rather than
4357
+ * relying on the selection to do it:
4358
+ *
4359
+ * - a leaf, a header, a closed subtree -> select it; the window opens there.
4360
+ * - an ELISION (a run of closed siblings, "7 more") stands for no single node,
4361
+ * so there is no path to select. It used to select the elision's PARENT —
4362
+ * which, if the parent was already selected, changed nothing at all: click
4363
+ * it forever and the days inside it never open. A dead end, and a whole
4364
+ * region of the library you could see but never reach.
4365
+ *
4366
+ * So the anchor goes to the first leaf the clicked row stands for. That run
4367
+ * always scores highest next time, so it always opens. Drill enough and any
4368
+ * leaf gets its own row.
4369
+ */
4370
+ svg.addEventListener("click", (e) => {
4371
+ const g = e.target.closest?.("g.fn-row");
4372
+ if (!g) return;
4373
+ const row = model?.rows.find((r) => r.id === g.getAttribute("data-id"));
4374
+ if (!row) return;
4375
+
4376
+ anchorLeaf = row.leafStart; // always progress: open where you clicked
4377
+
4378
+ // `row.path` — NOT `row.parentNode.path`. An elision row already carries its
4379
+ // parent's path (bands.js), and `parentNode` is a d3 hierarchy node, whose
4380
+ // `.path` is d3's own path(target) METHOD. Reading it got a function, whose
4381
+ // `.length` is 1 (its arity), so the emptiness guard passed and `.map` threw —
4382
+ // killing the handler before it could redraw. The anchor moved, the screen did
4383
+ // not, and clicking a "2 more" row did nothing at all, forever: the two years
4384
+ // it stood for could be seen and never reached.
4385
+ const path = row.path;
4386
+ if (!path?.length) {
4387
+ draw(); // an elision at the root: nothing to select, but still drill in
4388
+ return;
4389
+ }
4390
+ el.setValue(path.map((p) => ({ ...p })));
4391
+ });
4392
+
4393
+ // --- reactive-widget contract --------------------------------------------
4394
+
4395
+ const widget = ReactiveWidget(el, {
4396
+ value: options.selected ?? null,
4397
+ // Called on `input` AND on a silent `.value = x` set — so a host pushing the
4398
+ // selection in gets the highlight without an event echoing back out.
4399
+ showValue: () => draw(),
4400
+ });
4401
+
4402
+ /** Merge new options and redraw. Re-normalizes only when it has to. */
4403
+ el.update = (next = {}) => {
4404
+ const restructure =
4405
+ ("data" in next && next.data !== opts.data) ||
4406
+ ("root" in next && next.root !== opts.root) ||
4407
+ ("keys" in next && String(next.keys) !== String(opts.keys)) ||
4408
+ ("style" in next && next.style !== opts.style); // headers on/off
4409
+ opts = { ...opts, ...next };
4410
+ if (!STYLES.includes(opts.style)) opts.style = "flat";
4411
+ if (restructure) rebuild();
4412
+ controls?.sync();
4413
+ draw();
4414
+ };
4415
+
4416
+ // --- settings -------------------------------------------------------------
4417
+
4418
+ /** Apply a settings change: persist it, tell the host, redraw. */
4419
+ const applySettings = (patch) => {
4420
+ el.update(patch);
4421
+ writeStore(opts.persistKey, opts);
4422
+ // A host that wants its own store (or wants to mirror the lens elsewhere)
4423
+ // listens for this instead of passing a persistKey.
4424
+ el.dispatchEvent(
4425
+ new CustomEvent("settings", { detail: el.getSettings(), bubbles: true }),
4426
+ );
4427
+ };
4428
+
4429
+ /** The tunable lens settings — the subset that is persisted. */
4430
+ el.getSettings = () => {
4431
+ const out = {};
4432
+ for (const k of PERSIST_KEYS) out[k] = opts[k];
4433
+ return out;
4434
+ };
4435
+
4436
+ el.setSettings = (patch) =>
4437
+ applySettings(sanitize({ ...el.getSettings(), ...patch }, {}));
4438
+
4439
+ el.resetSettings = () => {
4440
+ const defaults = {};
4441
+ for (const k of PERSIST_KEYS) defaults[k] = NAV_DEFAULTS[k];
4442
+ applySettings(defaults);
4443
+ };
4444
+
4445
+ if (opts.controls !== false) {
4446
+ controls = buildControls(el, {
4447
+ get: () => opts,
4448
+ set: applySettings,
4449
+ reset: () => el.resetSettings(),
4450
+ });
4451
+ }
4452
+
4453
+ el.getRows = () => model?.rows ?? [];
4454
+ el.getRoot = () => root;
4455
+ // Real leaves only. The synthetic header cells are an internal device for the
4456
+ // flat view's outline; leaking them here would make the count depend on the
4457
+ // current style, which is nobody's idea of a leaf count.
4458
+ el.getLeafCount = () =>
4459
+ root ? leavesOf(root).filter((n) => !n.data.header).length : 0;
4460
+
4461
+ if (typeof ResizeObserver !== "undefined") {
4462
+ const ro = new ResizeObserver(() => draw());
4463
+ ro.observe(el);
4464
+ el.destroy = () => {
4465
+ ro.disconnect();
4466
+ controls?.destroy();
4467
+ };
4468
+ } else {
4469
+ el.destroy = () => controls?.destroy();
4470
+ }
4471
+
4472
+ rebuild();
4473
+ draw();
4474
+ return widget;
4475
+ }
4476
+
4477
+ export { LAYOUTS, LAYOUT_DEFAULTS, STYLES, basePositions, buildRows, fisheyeNav as default, distort, doiScore, fisheyeNav, fisheyePosition, layout, leafDistance, leavesOf, makeBarScale, nodesOf, normalize$1 as normalize, selectAll, selectDOI, slotAtPixel };