-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1529 lines (1409 loc) · 57.2 KB
/
Copy pathapp.js
File metadata and controls
1529 lines (1409 loc) · 57.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Minimal, deployable browser app. No bundler required.
// Uses Zarrita via CDN only for store path utilities if needed; tree built from consolidated .zmetadata.
// Optional: try to import zarrita for URL helpers. If CDN fails, app still works.
let zarrita; // eslint-disable-line no-unused-vars
(async () => {
try {
zarrita = await import("https://esm.sh/zarrita@0.4?bundle");
} catch (e) {
// ignore; we don't strictly need zarrita to render metadata tree
}
})();
const $ = (sel) => document.querySelector(sel);
const statusEl = () => $("#status");
const slideEl = () => $("#slide");
const sidebarEl = () => $("#sidebar");
const state = {
baseUrl: "",
tree: null, // { pathMap: Map<string, Node>, root: Node }
activePath: "/",
highlightVarPath: null,
};
/** Node shape
* {
* path: string ("/" for root),
* type: "group" | "array",
* attrs?: object,
* zarray?: object, // for arrays
* children: string[] // child basenames sorted
* }
*/
function normalizeBase(url) {
// Ensure no trailing slash for consistent joins
return url.replace(/\/$/, "");
}
function normalizePath(p) {
if (!p) return "/";
// Ensure leading slash, collapse repeats, remove trailing slash (except root)
let s = p.replace(/\/+/g, "/");
if (!s.startsWith("/")) s = "/" + s;
if (s.length > 1) s = s.replace(/\/$/, "");
return s;
}
async function fetchJson(url) {
const res = await fetch(url, { mode: "cors" });
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
return res.json();
}
async function loadZmetadata(baseUrl) {
const u = normalizeBase(baseUrl);
const metaUrl = `${u}/.zmetadata`;
setStatus(`Fetching .zmetadata from ${metaUrl} ...`);
const jm = await fetchJson(metaUrl);
if (!jm || typeof jm !== "object" || !jm.metadata) {
throw new Error(".zmetadata missing 'metadata' key. Ensure store is consolidated.");
}
return { base: u, consolidated: jm };
}
// Zarr v3 consolidated: expect zarr.json with a metadata map.
// We'll adapt v3 keys ending with "/group.json", "/array.json", "/attrs.json" to v2-like
// ".zgroup", ".zarray", ".zattrs" so we can reuse buildTree().
async function loadZarrV3(baseUrl) {
const u = normalizeBase(baseUrl);
const url = `${u}/zarr.json`;
setStatus(`Fetching zarr.json from ${url} ...`);
const zj = await fetchJson(url);
if (!zj || typeof zj !== 'object') throw new Error('Invalid zarr.json');
console.debug('[zarr] zarr.json content keys:', Object.keys(zj || {}));
return { base: u, zarr: zj };
}
function buildTreeFromV3(v3) {
const zj = v3?.zarr;
// Expect a consolidated-like map either in zarr.json.metadata OR zarr.json.consolidated_metadata.metadata
const md = (zj && (zj.metadata || (zj.consolidated_metadata && zj.consolidated_metadata.metadata))) || null;
if (!md || typeof md !== 'object') throw new Error('zarr.json missing metadata map (expected metadata or consolidated_metadata.metadata)');
const mapped = {};
let mode = null;
for (const [key, value] of Object.entries(md)) {
// Mode A: file-like keys ending in group.json/array.json/attrs.json
if (typeof key === 'string' && /\.(json)$/.test(key)) {
mode = mode || 'filelist';
if (key.endsWith('group.json')) {
const p = key.replace(/group\.json$/i, '.zgroup');
mapped[p] = value;
} else if (key.endsWith('array.json')) {
const p = key.replace(/array\.json$/i, '.zarray');
mapped[p] = value;
} else if (key.endsWith('attrs.json')) {
const p = key.replace(/attrs\.json$/i, '.zattrs');
mapped[p] = value;
} else if (/\.z(group|array|attrs)$/i.test(key)) {
mapped[key] = value;
}
continue;
}
// Mode B: node-descriptor map: key is a path, value has node_type and attributes
if (value && typeof value === 'object' && (value.node_type || value.attributes || value.consolidated_metadata)) {
mode = mode || 'nodedesc';
const path = String(key);
const attrs = value.attributes || {};
if (value.node_type === 'group') {
mapped[`${path}/.zgroup`] = { zarr_format: 2 };
if (attrs && Object.keys(attrs).length) mapped[`${path}/.zattrs`] = attrs;
} else if (value.node_type === 'array') {
// Try to find array metadata in descriptor if present; otherwise, create minimal placeholder
const arrMeta = value.array || value.metadata || {};
mapped[`${path}/.zarray`] = arrMeta;
if (attrs && Object.keys(attrs).length) mapped[`${path}/.zattrs`] = attrs;
}
continue;
}
}
console.debug('[zarr] v3 consolidated mode used:', mode, 'entries:', Object.keys(mapped).length);
if (!Object.keys(mapped).length) throw new Error('zarr.json metadata did not contain recognizable entries');
const consolidated = { metadata: mapped };
return buildTree(consolidated);
}
function buildTree(consolidated) {
const pathMap = new Map();
// Ensure root exists
ensureNode(pathMap, "/").type = "group";
const meta = consolidated.metadata;
for (const [key, value] of Object.entries(meta)) {
// keys are like "foo/.zgroup", "foo/bar/.zarray", "foo/.zattrs"
if (!key.endsWith(".zgroup") && !key.endsWith(".zarray") && !key.endsWith(".zattrs")) continue;
const path = normalizePath("/" + key.replace(/\.z(group|array|attrs)$/i, ""));
const node = ensureNode(pathMap, path);
if (key.endsWith(".zgroup")) node.type = "group";
if (key.endsWith(".zarray")) node.type = "array";
if (key.endsWith(".zattrs")) node.attrs = value || {};
if (key.endsWith(".zarray")) node.zarray = value || {};
}
// Infer missing parent groups and children lists
for (const p of pathMap.keys()) {
if (p === "/") continue;
const parent = dirname(p);
const base = basename(p);
const parentNode = ensureNode(pathMap, parent);
if (!parentNode.children.includes(base)) parentNode.children.push(base);
}
// Sort children for stable sibling navigation
for (const node of pathMap.values()) node.children.sort((a, b) => a.localeCompare(b));
return { pathMap, root: pathMap.get("/") };
}
function ensureNode(map, path) {
const np = normalizePath(path);
let node = map.get(np);
if (!node) {
node = { path: np, type: "group", attrs: {}, children: [] };
map.set(np, node);
}
return node;
}
function dirname(p) {
const np = normalizePath(p);
if (np === "/") return "/";
const parts = np.split("/").filter(Boolean);
parts.pop();
return "/" + parts.join("/");
}
function basename(p) {
const np = normalizePath(p);
if (np === "/") return "/";
const parts = np.split("/").filter(Boolean);
return parts[parts.length - 1] || "/";
}
function siblingsOf(tree, path) {
// Operate among sibling GROUPS only
const parent = dirname(path);
const sibNames = tree.pathMap.get(parent)?.children || [];
const sibGroups = sibNames
.map((name) => tree.pathMap.get(join(parent, name)))
.filter((n) => n && n.type === "group")
.map((n) => basename(n.path));
const idx = sibGroups.indexOf(basename(path));
return { parent, list: sibGroups, index: idx };
}
function firstChildOf(tree, path) {
const node = tree.pathMap.get(path);
if (!node || !node.children.length) return null;
// Choose first GROUP child only
for (const name of node.children) {
const child = tree.pathMap.get(join(path, name));
if (child && child.type === "group") return child.path;
}
return null;
}
function join(parent, childBase) {
const pp = normalizePath(parent);
const out = pp === "/" ? `/${childBase}` : `${pp}/${childBase}`;
return normalizePath(out);
}
function setStatus(msg) { statusEl().textContent = msg; }
function renderActive() {
const { tree, activePath } = state;
const el = slideEl();
try {
if (!tree) {
el.innerHTML = `<div class="placeholder">Enter a Zarr store URL and click Load.</div>`;
renderSidebar();
return;
}
const node = tree.pathMap.get(activePath);
if (!node) {
el.innerHTML = `<div class="error">Path not found: ${escapeHtml(activePath)}</div>`;
renderSidebar();
return;
}
const crumbs = breadcrumb(activePath)
.map((p, i, arr) => `<span>${escapeHtml(basename(p) || "/")}${i < arr.length - 1 ? " / " : ""}</span>`)
.join("");
const parts = [];
parts.push(`<div class="breadcrumb">${crumbs}</div>`);
// (header contains copy buttons; no in-content copy buttons)
if (node.type === "array") {
parts.push(`<div class="node-title">Array <span class="badge">${escapeHtml(activePath)}</span></div>`);
const metaRows = [];
metaRows.push(["type", "array"]);
const za = node.zarray || {};
if (za.shape) metaRows.push(["shape", JSON.stringify(za.shape)]);
if (za.dtype) metaRows.push(["dtype", String(za.dtype)]);
if (za.chunks) metaRows.push(["chunks", JSON.stringify(za.chunks)]);
if (za.chunk_grid) metaRows.push(["chunk_grid", JSON.stringify(za.chunk_grid)]);
if (za.codecs) metaRows.push(["codecs", JSON.stringify(za.codecs)]);
if (za.compressor) metaRows.push(["compressor", JSON.stringify(za.compressor)]);
parts.push(`<div class="meta">${metaRows.map(([k, v]) => `<div class="label">${escapeHtml(k)}</div><div class="value">${escapeHtml(v)}</div>`).join("")}</div>`);
// Chunks and Attributes side-by-side
const chunkMatrix = renderChunkMatrix(node);
const hasAttrs = node.attrs && Object.keys(node.attrs).length;
const chunksSection = chunkMatrix ? `
<div class="section-row">
<details open>
<summary>Chunks</summary>
${chunkMatrix}
</details>
</div>
` : "";
const attrsSection = `
<div class="section-row">
<details ${hasAttrs?"":"open"}>
<summary>Attributes</summary>
${hasAttrs ? `<pre class="codeblock">${escapeHtml(JSON.stringify(node.attrs, null, 2))}</pre>` : `<div class="codeblock"><div class="small">(none)</div></div>`}
</details>
</div>
`;
parts.push(`
<div class="section section-row">
${chunksSection}${attrsSection}
</div>
`);
el.innerHTML = parts.join("");
// Hide aggregated panel and two-col layout for arrays
const agg = document.getElementById('aggPanel');
const stage = document.querySelector('main.stage');
if (agg) { agg.hidden = true; agg.innerHTML = ""; }
if (stage) stage.classList.remove('two-col');
updateHeaderControls();
const inputEl = document.querySelector('#zarrUrl');
if (inputEl && state.baseUrl) inputEl.value = humanReadableUri();
return;
}
parts.push(`<div class="node-title">Group <span class="badge">${escapeHtml(activePath)}</span></div>`);
// Apply naming spec to this group's direct subgroups (if any) before rendering cards
applyNamingSpecIfAny(node.path);
const groupView = renderGroupLikeXarray(state.tree, node);
parts.push(groupView);
el.innerHTML = parts.join("");
// Render aggregated attributes in separate panel
const agg = document.getElementById('aggPanel');
const aggContainer = document.querySelector('.agg-panel-container');
const stage = document.querySelector('main.stage');
if (agg && aggContainer) {
// Show the container first
aggContainer.hidden = false;
if (hasMultipleSubgroups(state.tree, node)) {
const aggView = renderAggregatedGroupAttrs(state.tree, node);
agg.hidden = false;
agg.innerHTML = `<div class="node-title">Aggregated attributes <span class="badge">${escapeHtml(activePath)}</span></div>${aggView}`;
if (stage) stage.classList.add('two-col');
} else {
aggContainer.hidden = true;
agg.innerHTML = "";
if (stage) stage.classList.remove('two-col');
}
}
updateHeaderControls();
const inputEl = document.querySelector('#zarrUrl');
if (inputEl && state.baseUrl) inputEl.value = humanReadableUri();
renderSidebar();
} catch (e) {
el.innerHTML = `<div class="error">Render error: ${escapeHtml(e.message || String(e))}</div>`;
}
}
function renderAggregatedGroupAttrs(tree, grpNode) {
if (!tree || !grpNode) return "";
// Use only direct subgroup groups of the active group
const children = (grpNode.children || [])
.map((name) => tree.pathMap.get(join(grpNode.path, name)))
.filter((n) => n && n.type === "group");
if (!children.length) return "";
const allKeys = new Set();
for (const n of children) {
const a = n.attrs || {};
for (const k of Object.keys(a)) allKeys.add(k);
}
const keys = Array.from(allKeys).sort();
// Unique values summary (previous view)
const summaryRows = [];
for (const k of keys) {
const present = [];
for (const n of children) {
const a = n.attrs || {};
if (Object.prototype.hasOwnProperty.call(a, k)) present.push(a[k]);
}
if (!present.length) continue;
let allEqual = true;
for (let i = 1; i < present.length; i++) {
if (!deepEqualSimple(present[0], present[i])) { allEqual = false; break; }
}
let display;
if (allEqual) {
const v = present[0];
if (v == null) display = "null";
else if (typeof v === "object") display = JSON.stringify(v);
else display = String(v);
} else {
const asKey = (v) => v == null ? "__NULL__" : (typeof v === "object" ? JSON.stringify(v) : String(v));
const toDisp = (v) => v == null ? "null" : (typeof v === "object" ? JSON.stringify(v) : String(v));
const seen = new Set();
const uniques = [];
for (const v of present) {
const key = asKey(v);
if (!seen.has(key)) { seen.add(key); uniques.push(toDisp(v)); }
}
display = uniques.join(", ");
}
summaryRows.push(`<div class="label">${escapeHtml(k)}</div><div class="value">${escapeHtml(display)}</div>`);
}
const summaryBody = summaryRows.length ? summaryRows.join("") : `<div class="small">(none)</div>`;
const summaryHtml = `<div class="section"><h3>Unique values</h3><div class="codeblock"><div class="meta small">${summaryBody}</div></div></div>`;
const selectOpt = (v, label) => `<option value="${escapeHtml(String(v))}">${escapeHtml(String(label))}</option>`;
const controls = `
<div class="section">
<h3>Interactive table</h3>
<div class="pivot-controls">
<label>Rows
<select id="rowAttrSel">
${selectOpt("", "(none)")}
${keys.map(k => selectOpt(k, k)).join("")}
</select>
</label>
<label>Columns
<select id="colAttrSel">
${selectOpt("", "(none)")}
${keys.map(k => selectOpt(k, k)).join("")}
</select>
</label>
</div>
<div id="pivotHost"></div>
</div>
`;
queueMicrotask(() => bindAggPivot(children));
return summaryHtml + controls;
}
function deepEqualSimple(a, b) {
if (a === b) return true;
if (typeof a !== typeof b) return false;
if (a && b && typeof a === "object") {
try { return JSON.stringify(a) === JSON.stringify(b); } catch { return false; }
}
return false;
}
// Convert zarr dtype tokens like "<f4" to human names like "float32"
function prettyDtype(dtype) {
if (!dtype) return "";
const s = String(dtype);
if (s === 'bool' || s === '|b1') return 'bool';
const core = s.replace(/[<>=|]/g, ''); // strip endianness
const m = core.match(/^([fiu])?(\d+)$/);
if (!m) return core;
const kind = m[1] || '';
const n = parseInt(m[2], 10);
if (kind === 'f') return `float${n*8}`;
if (kind === 'i') return `int${n*8}`;
if (kind === 'u') return `uint${n*8}`;
// Some encodings directly give bytes; assume integer
if (!isNaN(n)) return `${n<=2?`int${n*8}`: n<=8?`int${n*8}`:`${core}`}`;
return core;
}
function valueKey(v) {
return v == null ? '__NULL__' : (typeof v === 'object' ? JSON.stringify(v) : String(v));
}
function valueLabel(v) {
if (v == null) return 'null';
if (typeof v === 'object') return JSON.stringify(v);
return String(v);
}
function bindAggPivot(children) {
const rowSel = document.getElementById('rowAttrSel');
const colSel = document.getElementById('colAttrSel');
const host = document.getElementById('pivotHost');
if (!rowSel || !colSel || !host) return;
const render = () => {
const rowAttr = rowSel.value || '';
const colAttr = colSel.value || '';
host.innerHTML = renderPivotTable(children, rowAttr, colAttr);
queueMicrotask(() => bindNavLinks());
};
rowSel.addEventListener('change', render);
colSel.addEventListener('change', render);
render();
}
function renderPivotTable(children, rowAttr, colAttr) {
// Collect unique row/col values
const rowValsSet = new Set();
const colValsSet = new Set();
const grid = new Map(); // rowKey -> Map(colKey -> nodes[])
for (const n of children) {
const a = n.attrs || {};
const rv = rowAttr ? a[rowAttr] : '(all)';
const cv = colAttr ? a[colAttr] : '(all)';
const rk = valueKey(rv);
const ck = valueKey(cv);
rowValsSet.add(rk);
colValsSet.add(ck);
if (!grid.has(rk)) grid.set(rk, new Map());
const rowMap = grid.get(rk);
if (!rowMap.has(ck)) rowMap.set(ck, []);
rowMap.get(ck).push(n);
}
const rowKeys = Array.from(rowValsSet);
const colKeys = Array.from(colValsSet);
rowKeys.sort();
colKeys.sort();
const headCols = colKeys.map(ck => `<th>${escapeHtml(ck === '__NULL__' ? 'null' : ck)}</th>`).join('');
let bodyRows = '';
for (const rk of rowKeys) {
const cells = colKeys.map(ck => {
const nodes = grid.get(rk)?.get(ck) || [];
if (!nodes.length) return '<td></td>';
const list = nodes.map(n => {
const label = escapeHtml(basename(n.path));
return `<div><span class="badge">group</span> <a href="#" data-path="${escapeHtml(n.path)}" class="navlink">${label}</a></div>`;
}).join('');
return `<td><details><summary>${nodes.length} group(s)</summary><div class="codeblock small">${list}</div></details></td>`;
}).join('');
bodyRows += `<tr><th class="rowhead">${escapeHtml(rk === '__NULL__' ? 'null' : rk)}</th>${cells}</tr>`;
}
return `
<div class="pivot-wrap">
<table class="pivot-table">
<thead>
<tr><th></th>${headCols}</tr>
</thead>
<tbody>
${bodyRows}
</tbody>
</table>
</div>
`;
}
function hasMultipleSubgroups(tree, grpNode) {
const groupChildren = grpNode.children
.map((name) => tree.pathMap.get(join(grpNode.path, name)))
.filter((n) => n && n.type === "group");
return groupChildren.length > 1;
}
function breadcrumb(path) {
const parts = path.split("/").filter(Boolean);
const acc = ["/"];
let cur = "";
for (const p of parts) {
cur = cur ? `${cur}/${p}` : `/${p}`;
acc.push(cur);
}
return acc;
}
function escapeHtml(v) {
return String(v)
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """);
}
// Load first and last values of a time array
async function loadTimeArrayValues(baseUrl, path) {
try {
// Ensure baseUrl ends with a slash
const normalizedBase = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`;
const arrayUrl = `${normalizedBase}${path}`;
// Import Zarrita dynamically
const zarrita = await import("https://esm.sh/zarrita@0.4.0");
// Open the store and get the array
const store = zarrita.open({ url: arrayUrl });
const arr = await zarrita.Array.open(store);
// Get the length of the first dimension
const length = arr.shape[0];
if (length === 0) {
return { first: null, last: null };
}
// Load first and last values
const firstValue = await arr.get([0]);
const lastValue = await arr.get([length - 1]);
// Format date if it's a datetime64 value
const formatIfDate = (value) => {
if (value instanceof Date) {
return value.toISOString();
} else if (typeof value === 'number' && arr.dtype.startsWith('datetime64')) {
// Handle numeric timestamps (common in netCDF/Zarr)
return new Date(value).toISOString();
}
return value;
};
return {
first: formatIfDate(firstValue),
last: formatIfDate(lastValue)
};
} catch (error) {
console.error('Error loading time array:', error);
return { error: error.message };
}
}
// Handle time array button click
window.handleTimeArrayClick = async function(button, baseUrl, path) {
const originalText = button.innerHTML;
button.disabled = true;
button.innerHTML = 'Loading...';
try {
const result = await loadTimeArrayValues(baseUrl, path);
if (result.error) {
button.innerHTML = `Error: ${result.error}`;
return;
}
// Create a div to display the values
const valuesDiv = document.createElement('div');
valuesDiv.className = 'time-array-values';
valuesDiv.innerHTML = `
<div>First: ${escapeHtml(String(result.first))}</div>
<div>Last: ${escapeHtml(String(result.last))}</div>
`;
// Insert after the button
button.parentNode.insertBefore(valuesDiv, button.nextSibling);
// Remove the button after showing values
button.remove();
} catch (error) {
button.innerHTML = `Error: ${error.message}`;
setTimeout(() => {
button.innerHTML = originalText;
button.disabled = false;
}, 2000);
}
};
function icon(kind = '') {
const cls = `icon ${kind}`.trim();
if (kind === 'group') {
return `<svg class="${cls}" viewBox="0 0 24 24" aria-hidden="true"><path d="M10 4h8a2 2 0 0 1 2 2v3h-9l-2-2H4V6a2 2 0 0 1 2-2h4zm12 7v7a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9h7l2 2h11z"/></svg>`;
}
if (kind === 'attr') {
return `<svg class="${cls}" viewBox="0 0 24 24" aria-hidden="true"><path d="M3 7a2 2 0 0 1 2-2h6l10 10-6 6L5 11V7zm4 0a1 1 0 1 0 0 2 1 1 0 0 0 0-2z"/></svg>`;
}
if (kind === 'coord') {
return `<svg class="${cls}" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="9"/></svg>`;
}
if (kind === 'data') {
return `<svg class="${cls}" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 6c0-2.21 3.58-4 8-4s8 1.79 8 4-3.58 4-8 4-8-1.79-8-4zm0 6c0 2.21 3.58 4 8 4s8-1.79 8-4m-16 6c0 2.21 3.58 4 8 4s8-1.79 8-4" fill="none" stroke="currentColor" stroke-width="2"/></svg>`;
}
if (kind === 'dim') {
return `<svg class="${cls}" viewBox="0 0 24 24" aria-hidden="true"><path d="M3 3h8v8H3V3zm10 0h8v8h-8V3zM3 13h8v8H3v-8zm10 0h8v8h-8v-8z"/></svg>`;
}
return `<svg class="${cls}" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="10"/></svg>`;
}
// Toggle details sections
window.toggleDetails = function(id) {
const details = document.getElementById(id);
if (!details) return;
// Get the var-container parent
const container = details.closest('.var-container');
if (!container) return;
// Toggle the display of the details section
const isVisible = details.style.display === 'block' ||
(details.style.display === '' && window.getComputedStyle(details).display === 'block');
details.style.display = isVisible ? 'none' : 'block';
// Update the button's aria-expanded attribute for accessibility
const button = document.querySelector(`[data-target="${id}"]`);
if (button) {
const isExpanded = button.getAttribute('aria-expanded') === 'true';
button.setAttribute('aria-expanded', !isExpanded);
button.classList.toggle('active', !isExpanded);
}
// If another details section is open in the same container, close it
if (!isVisible) {
const otherDetails = container.querySelectorAll('.var-details');
otherDetails.forEach(detail => {
if (detail.id !== id && detail.style.display === 'block') {
detail.style.display = 'none';
// Update the other button's state
const otherButton = document.querySelector(`[data-target="${detail.id}"]`);
if (otherButton) {
otherButton.setAttribute('aria-expanded', 'false');
otherButton.classList.remove('active');
}
}
});
}
};
function setActive(path) {
// Prevent setting arrays as active; keep only groups active
const node = state.tree?.pathMap.get(path);
const targetPath = node && node.type === "group" ? path : dirname(path);
state.activePath = targetPath;
state.highlightVarPath = node && node.type === "array" ? node.path : null;
renderActive();
// Update hash to include active subgroup
if (state.baseUrl) {
const hash = `${encodeURI(state.baseUrl)}|${encodeURI(state.activePath)}`;
if (location.hash.slice(1) !== hash) location.hash = hash;
}
}
function handleKeydown(ev) {
if (!state.tree) return;
const { key } = ev;
if (["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].includes(key)) ev.preventDefault();
if (key === "ArrowUp") {
const parent = dirname(state.activePath);
if (parent && parent !== state.activePath) setActive(parent);
} else if (key === "ArrowDown") {
const child = firstChildOf(state.tree, state.activePath);
if (child) setActive(child);
} else if (key === "ArrowLeft" || key === "ArrowRight") {
const { parent, list, index } = siblingsOf(state.tree, state.activePath);
if (!list.length) return;
if (index < 0) return; // current not a group sibling (e.g., root) -> no-op
const delta = key === "ArrowLeft" ? -1 : 1;
const nextIdx = (index + delta + list.length) % list.length;
const nextPath = join(parent, list[nextIdx]);
setActive(nextPath);
}
}
async function onLoadClick() {
const input = $("#zarrUrl");
const entered = (input.value || "").trim();
const baseUrl = deriveBaseFromUrl(entered);
if (!baseUrl) {
setStatus("Please enter a Zarr store base URL.");
input.focus();
return;
}
await loadStore(baseUrl);
}
async function loadStore(baseUrl) {
try {
slideEl().focus();
setStatus("Loading...");
state.baseUrl = normalizeBase(baseUrl);
// Try Zarr v3 first (zarr.json). On failure, fall back to v2 consolidated (.zmetadata)
let tree = null;
try {
const v3 = await loadZarrV3(state.baseUrl);
console.info('[zarr] v3 detected at', state.baseUrl, v3?.zarr);
tree = buildTreeFromV3(v3);
console.info('[zarr] v3 tree built successfully');
setStatus('Loaded Zarr v3 (zarr.json).');
} catch (e) {
console.warn('[zarr] v3 load failed, falling back to v2 (.zmetadata). Reason:', e?.message || e);
const { consolidated } = await loadZmetadata(state.baseUrl);
console.info('[zarr] v2 consolidated loaded');
tree = buildTree(consolidated);
console.info('[zarr] v2 tree built successfully');
setStatus('Loaded Zarr v2 (.zmetadata).');
}
state.tree = tree;
state.activePath = "/";
// Apply naming spec (if any) to root subgroups before rendering, so aggregated attrs include them
applyNamingSpecIfAny('/');
renderActive();
// Update hash for deep-linking (store | path)
const hash = `${encodeURI(state.baseUrl)}|${encodeURI(state.activePath)}`;
if (location.hash.slice(1) !== hash) location.hash = hash;
} catch (err) {
console.error('[zarr] loadStore error:', err);
slideEl().innerHTML = `<div class="error">${escapeHtml(err.message || String(err))}</div>`;
setStatus("Error.");
}
}
function init() {
// Sidebar toggle functionality
const sidebar = document.getElementById('sidebar');
const sidebarToggle = document.getElementById('sidebarToggle');
const aggPanel = document.getElementById('aggPanel');
const aggPanelToggle = document.getElementById('aggPanelToggle');
const aggPanelContainer = document.querySelector('.agg-panel-container');
// Check for mobile view
const isMobileView = window.matchMedia('(max-width: 900px)').matches;
// Get saved states or use defaults based on view
let isSidebarCollapsed = localStorage.getItem('sidebarCollapsed');
let isAggPanelCollapsed = localStorage.getItem('aggPanelCollapsed');
// If no saved state, use defaults based on view
if (isSidebarCollapsed === null) {
isSidebarCollapsed = isMobileView ? 'true' : 'false';
localStorage.setItem('sidebarCollapsed', isSidebarCollapsed);
}
// Initialize aggPanel state if not set
if (isAggPanelCollapsed === null) {
isAggPanelCollapsed = 'false'; // Default to expanded
localStorage.setItem('aggPanelCollapsed', isAggPanelCollapsed);
}
// Apply the collapsed states
if (isSidebarCollapsed === 'true') {
sidebar.classList.add('collapsed');
} else {
sidebar.classList.remove('collapsed');
}
if (aggPanelContainer) {
if (isAggPanelCollapsed === 'true') {
aggPanelContainer.classList.add('collapsed');
} else {
aggPanelContainer.classList.remove('collapsed');
}
}
// Toggle sidebar on button click
if (sidebarToggle) {
sidebarToggle.addEventListener('click', () => {
sidebar.classList.toggle('collapsed');
// Save state to localStorage
localStorage.setItem('sidebarCollapsed', sidebar.classList.contains('collapsed'));
});
}
// Toggle aggPanel on button click
if (aggPanelToggle && aggPanelContainer) {
aggPanelToggle.addEventListener('click', () => {
aggPanelContainer.classList.toggle('collapsed');
// Save state to localStorage
localStorage.setItem('aggPanelCollapsed', aggPanelContainer.classList.contains('collapsed'));
});
}
$("#loadBtn").addEventListener("click", onLoadClick);
$("#zarrUrl").addEventListener("keydown", (e) => { if (e.key === "Enter") onLoadClick(); });
// Header controls
const copyUriBtn = document.getElementById('copyUriBtn');
if (copyUriBtn) {
copyUriBtn.addEventListener('click', async () => {
const uri = humanReadableUri();
try { await navigator.clipboard.writeText(uri); setStatus('URI copied to clipboard.'); }
catch { setStatus('Failed to copy URI.'); }
});
}
const copyPyBtn = document.getElementById('copyPyBtn');
if (copyPyBtn) {
copyPyBtn.addEventListener('click', async () => {
const code = buildPythonSnippet();
try { await navigator.clipboard.writeText(code); setStatus('Python snippet copied to clipboard.'); }
catch { setStatus('Failed to copy Python snippet.'); }
});
}
const visualizeBtn = document.getElementById('visualizeBtn');
if (visualizeBtn) {
visualizeBtn.addEventListener('click', () => {
const uri = humanReadableUri();
const url = `https://gridlook.pages.dev/#${encodeURI(uri)}`;
window.open(url, '_blank', 'noopener');
});
}
const applyNamingBtn = document.getElementById('applyNamingBtn');
if (applyNamingBtn) {
applyNamingBtn.addEventListener('click', onApplyNamingSpec);
}
document.addEventListener("keydown", handleKeydown);
// Auto-load from hash if present: format is <store>|<path>
const initial = location.hash ? location.hash.slice(1) : "";
if (initial) {
const [storeEnc, pathEnc] = initial.split("|");
const store = storeEnc ? decodeURI(storeEnc) : "";
const path = pathEnc ? decodeURI(pathEnc) : "/";
if (store) {
const input = $("#zarrUrl");
if (input) input.value = store;
loadStore(store).then(() => {
if (path) { state.activePath = normalizePath(path); renderActive(); }
});
}
}
// React to hash changes (e.g., user pastes a different store or subgroup)
window.addEventListener("hashchange", () => {
const raw = location.hash ? location.hash.slice(1) : "";
if (!raw) return;
const [storeEnc, pathEnc] = raw.split("|");
const store = storeEnc ? decodeURI(storeEnc) : "";
const path = pathEnc ? decodeURI(pathEnc) : "/";
if (store && store !== state.baseUrl) {
const input = $("#zarrUrl");
if (input) input.value = store;
loadStore(store).then(() => {
if (path) { state.activePath = normalizePath(path); renderActive(); }
});
} else if (path && state.tree) {
state.activePath = normalizePath(path);
renderActive();
}
});
renderActive();
}
init();
function renderSidebar() {
const el = sidebarEl();
if (!el) return;
if (!state.tree) {
el.innerHTML = `<div class="sidebar__placeholder small">Load a store to view the hierarchy</div>`;
return;
}
const html = `<ul class="tree">${renderTreeNode(state.tree, "/")}</ul>`;
el.innerHTML = html;
// Bind clicks
el.querySelectorAll("a[data-path]").forEach((a) => {
a.addEventListener("click", (e) => {
e.preventDefault();
const p = a.getAttribute("data-path");
if (!p) return;
setActive(p);
});
});
// Mark active
const active = el.querySelector(`a[data-path="${CSS.escape(state.activePath)}"]`);
if (active) active.classList.add("active");
}
function renderTreeNode(tree, path) {
const node = tree.pathMap.get(normalizePath(path));
if (!node) return "";
const isGroup = node.type === "group";
if (!isGroup) return ""; // exclude arrays from sidebar
const label = path === "/" ? "/" : basename(path);
const hasGroupKids = (node.children || []).some((name) => {
const child = tree.pathMap.get(join(node.path, name));
return child && child.type === 'group';
});
let li = `<li>`;
if (hasGroupKids) {
const open = isSubtreeOpen(node.path, state.activePath);
li += `<details ${open ? 'open' : ''}>`;
li += `<summary><a href="#" data-path="${escapeHtml(node.path)}">${escapeHtml(label)}</a></summary>`;
const kids = node.children.map((name) => {
const childPath = join(node.path, name);
const child = tree.pathMap.get(childPath);
return child && child.type === "group" ? renderTreeNode(tree, childPath) : "";
}).join("");
if (kids) li += `<ul>${kids}</ul>`;
li += `</details>`;
} else {
li += `<a href="#" data-path="${escapeHtml(node.path)}">${escapeHtml(label)}</a>`;
}
li += `</li>`;
return li;
}
function isSubtreeOpen(rootPath, activePath) {
const a = normalizePath(rootPath);
const b = normalizePath(activePath || '/');
if (a === '/') return true;
return b === a || b.startsWith(a + '/');
}
function renderGroupLikeXarray(tree, grpNode) {
const arrays = collectArrays(tree, grpNode, 0, 0); // only variables directly in this group
const dimsByVar = new Map();
const sizesByVar = new Map();
const attrsByVar = new Map();
const allDims = new Set();
const coordCandidates = new Map(); // name -> size for 1D arrays named after themselves
for (const arr of arrays) {
const dims = inferArrayDims(arr);
dimsByVar.set(arr, dims);
sizesByVar.set(arr, Array.isArray(arr.zarray?.shape) ? arr.zarray.shape : []);
attrsByVar.set(arr, arr.attrs || {});
dims.forEach((d) => allDims.add(d));
// collect 1D arrays as potential coordinates
const name = basename(arr.path);
const shp = Array.isArray(arr.zarray?.shape) ? arr.zarray.shape : [];
if (shp.length === 1 && Number.isFinite(shp[0])) {
coordCandidates.set(name, shp[0]);
}
}
// Build dim -> size mapping (prefer coords of same name, else first occurrence)
const dimSizes = new Map();
// First pass: from variables
for (const arr of arrays) {
const dims = dimsByVar.get(arr) || [];
const shape = sizesByVar.get(arr) || [];
dims.forEach((d, i) => {
if (!dimSizes.has(d) && Number.isFinite(shape[i])) dimSizes.set(d, shape[i]);
});
}
// Second pass: prefer coord arrays named after the dim
for (const arr of arrays) {
const name = basename(arr.path);
const dims = dimsByVar.get(arr) || [];
const shape = sizesByVar.get(arr) || [];
if (dims.length === 1 && dims[0] === name && Number.isFinite(shape[0])) dimSizes.set(name, shape[0]);
}
// If no explicit dim names, derive from 1D coord candidates
if (dimSizes.size === 0 && coordCandidates.size > 0) {
for (const [n, sz] of coordCandidates.entries()) dimSizes.set(n, sz);
}
// If variable has no _ARRAY_DIMENSIONS, infer names by matching axis sizes to known coord sizes
for (const arr of arrays) {
const dims = dimsByVar.get(arr) || [];
if (!dims.length || dims.every((d) => d.startsWith("dim_"))) {
const shape = sizesByVar.get(arr) || [];
const inferred = [];
const used = new Set();
for (const ax of shape) {
let match = null;
for (const [dn, sz] of dimSizes.entries()) {
if (sz === ax && !used.has(dn)) { match = dn; break; }
}
inferred.push(match || `dim_${inferred.length}`);
if (match) used.add(match);
}
dimsByVar.set(arr, inferred);
inferred.forEach((d) => allDims.add(d));
}
}
const coords = [];
const dataVars = [];