Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
2188 lines (2104 loc) · 86.4 KB
/
Copy pathapp.js
File metadata and controls
2188 lines (2104 loc) · 86.4 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
// ============================================================
// XERJ.ai — Bootstrap + router + layout engine
//
// One render loop. Edit mode layers drag/resize/remove/add on
// top of the same render — no separate editor routes.
// ============================================================
import { registry, defaults, SECTIONS, DASHBOARD_GROUPS, dashboardsInSection } from './dashboards/registry.js';
import { Nav, SceneHeader, TimeCtrl, RefreshCtrl, FilterBar, ClusterCtrl, SavedViews, Footer, MobileCtrl } from './ux/chrome.js';
import { query, dataSourceStatus } from './data/query.js';
import { chartTypes, chartTypeList } from './ux/chart-types.js';
import { esc } from './ux/text.js';
import { hitsToCsv, downloadText, svgToPng } from './data/export.js';
import {
mergedDashboards, renameDashboard, reorderDashboards, setHidden,
createUserDashboard, deleteUserDashboard, isUserDash, resetAll as resetDashboards,
getDoc, patchPanels, setOnChange,
} from './data/dashboard-store.js';
import { renderDeclarativePanel } from './ux/panel-render.js';
import { panelResult, fetchPanel, onPanelData } from './data/panel-query.js';
import {
listClusters, listIndices, listFields, listClustersSync,
defaultClusterId, setDefaultCluster,
} from './data/data-sources.js';
import { sbBrainsPresent } from './data/brains-probe.js';
import { dataFeaturesPresent, emptyDataFeatures } from './data/data-probe.js';
import { indexNames } from './data/schema.js';
import { mount } from './ux/safe-dom.js';
import { renderCorpus, renderRelations, renderCapabilities } from './ux/corpus-render.js';
import { ReaderView, parseReaderRoute } from './ux/reader-view.js';
import { readerHref } from './ux/reader-render.js';
import { makeReaderApi } from './data/reader-api.js';
import { makeConsoleTransport } from './data/transport-console.js';
import { activeBackendId, backendBaseUrl } from './data/backends/index.js';
// ---------- state -----------------------------------------
const LS = {
theme: 'xerj.theme',
time: 'xerj.time',
edit: 'xerj.edit',
search: 'xerj.search',
refresh: 'xerj.refresh',
cluster: 'xerj.cluster',
views: 'xerj.views',
filters: (dashId) => 'xerj.filters.' + dashId,
layout: (dashId) => 'xerj.layout.' + dashId,
};
function loadJSON(key, fallback) {
try { const raw = localStorage.getItem(key); return raw ? JSON.parse(raw) : fallback; }
catch { return fallback; }
}
function loadSearch() { return loadJSON(LS.search, null); }
function loadAllFilters() {
const out = {};
for (const k of Object.keys(localStorage)) {
if (k.startsWith('xerj.filters.')) {
const id = k.slice('xerj.filters.'.length);
try { out[id] = JSON.parse(localStorage.getItem(k)) || {}; } catch {}
}
}
return out;
}
const _initial = parseRoute();
const _urlState = parseUrlState();
const state = {
section: _initial.section,
route: _initial.route,
time: _urlState.time || localStorage.getItem(LS.time) || '24H',
timeCustom: {
from: _urlState.tfrom || localStorage.getItem('xerj.timeFrom') || '',
to: _urlState.tto || localStorage.getItem('xerj.timeTo') || '',
},
cluster: _urlState.cluster || defaultClusterId(),
refresh: parseInt(localStorage.getItem(LS.refresh) || '0', 10), // ms; 0 = off
refreshTimer: null,
fetchedAt: null, // ISO string of last successful query
fetchMs: null, // last fetch duration in ms
fetchErr: null, // last fetch error message
loading: false,
filters: loadAllFilters(), // { [dashId]: { field: value } }
theme: document.documentElement.getAttribute('data-theme') || 'night',
edit: localStorage.getItem(LS.edit) === '1',
mobile: localStorage.getItem('xerj.mobile') === '1',
layouts: loadAllLayouts(),
search: (() => {
const loaded = loadSearch() || {};
return {
q: loaded.q || '',
type: loaded.type || 'match',
index: loaded.index || '*',
filters: loaded.filters || {},
sort: loaded.sort || { field: '_score', dir: 'desc' },
showTime: loaded.showTime !== false,
result: null,
};
})(),
_focusSelector: null, // set by handlers that need focus restored
// Live-gated features: a dashboard whose registry entry sets
// `requiresLive: '<key>'` only appears in the NAV once the matching
// key here is true (fed by a probe against the live engine). Routes
// and MANAGE are never filtered — a deep link must always resolve.
liveFeatures: { brains: false, ...emptyDataFeatures() },
// Real index names on the engine (from the mapping), fed by the live probe
// so the search UI aligns to what's actually indexed instead of a hardcoded
// demo list.
indices: [],
// The Corpus home's last payload (backends/xerj.js#liveCorpus) — kept so the
// Reader's index picker lists the catalogued datasets first.
corpus: null,
};
// The Reader (ux/reader-view.js) owns its own state and fetching; the shell
// only hands it a mount point after each render and the parsed route on each
// hash change. It renders through ux/safe-dom.js — record data never passes
// through this file's HTML strings.
const readerView = new ReaderView({
api: makeReaderApi(makeConsoleTransport()),
guest: false,
indices: () => {
const fromCatalog = (state.corpus?.datasets || []).map((d) => d.index);
const rest = state.indices.filter((n) => !fromCatalog.includes(n));
return [...fromCatalog, ...rest];
},
onStatus: ({ kind, label }) => {
if (state.section !== 'reader') return;
state.sourceKind = kind; state.sourceLabel = label;
const pill = document.querySelector('[data-nav-status]');
if (pill) pill.textContent = navStatus();
},
});
// Merge any URL-seeded filters into the current dashboard's filter set.
if (_urlState.filters) {
state.filters[_initial.route] = { ...(state.filters[_initial.route] || {}), ..._urlState.filters };
saveFilters(_initial.route);
}
// ---------- filters, URL state, refresh -------------------
function currentFilters() {
return state.filters[state.route] || {};
}
function saveFilters(dashId) {
const v = state.filters[dashId];
if (v && Object.keys(v).length) localStorage.setItem(LS.filters(dashId), JSON.stringify(v));
else localStorage.removeItem(LS.filters(dashId));
}
// Toggle a filter value. Multi-value semantics: clicking the same
// value twice removes it; clicking a new value on an existing field
// appends to the OR list.
function setFilter(field, value) {
const dashId = state.route;
const cur = { ...(state.filters[dashId] || {}) };
const existing = cur[field];
if (existing == null) {
cur[field] = value;
} else if (Array.isArray(existing)) {
const idx = existing.indexOf(value);
if (idx >= 0) {
const next = existing.filter((v) => v !== value);
if (next.length === 0) delete cur[field];
else if (next.length === 1) cur[field] = next[0];
else cur[field] = next;
} else {
cur[field] = [...existing, value];
}
} else {
if (existing === value) delete cur[field];
else cur[field] = [existing, value];
}
state.filters[dashId] = cur;
saveFilters(dashId);
writeUrlState();
}
// Remove one value from a field (used by pill ✕ click on a specific
// chip inside a multi-value filter).
function removeFilterValue(field, value) {
const dashId = state.route;
const cur = { ...(state.filters[dashId] || {}) };
const existing = cur[field];
if (existing == null) return;
if (Array.isArray(existing)) {
const next = existing.filter((v) => v !== value);
if (next.length === 0) delete cur[field];
else if (next.length === 1) cur[field] = next[0];
else cur[field] = next;
} else if (existing === value) {
delete cur[field];
}
state.filters[dashId] = cur;
saveFilters(dashId);
writeUrlState();
}
// KQL-lite parser: tokenize `field:value field:"multi word" foo`.
// Free-text tokens become a synthetic `q` filter; repeat fields
// turn into OR arrays.
function parseKql(text) {
const out = {};
const add = (k, v) => {
if (!v) return;
if (out[k] == null) out[k] = v;
else if (Array.isArray(out[k])) out[k].push(v);
else out[k] = [out[k], v];
};
// Match field:"quoted value" OR field:value OR loose token
const re = /([a-zA-Z_][\w.]*):"([^"]*)"|([a-zA-Z_][\w.]*):(\S+)|"([^"]+)"|(\S+)/g;
let m;
while ((m = re.exec(text)) !== null) {
if (m[1] != null) add(m[1], m[2]);
else if (m[3] != null) add(m[3], m[4]);
else if (m[5] != null) add('q', m[5]);
else if (m[6] != null) add('q', m[6]);
}
return out;
}
// Inverse of parseKql — render a filter object as a KQL string that
// re-parses to the same shape. Used to keep the input box in sync.
function serializeKql(filters) {
const parts = [];
for (const [k, v] of Object.entries(filters || {})) {
const values = Array.isArray(v) ? v : [v];
for (const x of values) {
const needsQuote = /\s/.test(String(x));
if (k === 'q') {
parts.push(needsQuote ? `"${x}"` : String(x));
} else {
parts.push(needsQuote ? `${k}:"${x}"` : `${k}:${x}`);
}
}
}
return parts.join(' ');
}
function applyKqlInput(text) {
const dashId = state.route;
state.filters[dashId] = parseKql(text);
saveFilters(dashId);
writeUrlState();
}
function clearFilters() {
const dashId = state.route;
state.filters[dashId] = {};
saveFilters(dashId);
writeUrlState();
}
// URL state: ?t=24H&f=service:auth,level:error&c=prod-us
// Filters are encoded as repeated `f` params so URLSearchParams can
// handle escaping cleanly: ?f=service:nginx&f=level:error. Multi-value
// (OR) filters repeat the same key: ?f=service:auth&f=service:web.
function parseUrlState() {
const qs = location.search.slice(1);
if (!qs) return {};
const out = {};
const params = new URLSearchParams(qs);
if (params.get('t')) out.time = params.get('t').toUpperCase();
if (params.get('tfrom')) out.tfrom = params.get('tfrom');
if (params.get('tto')) out.tto = params.get('tto');
if (params.get('c')) out.cluster = params.get('c');
const all = params.getAll('f');
if (all.length) {
out.filters = {};
for (const pair of all) {
const idx = pair.indexOf(':');
if (idx > 0) {
const k = pair.slice(0, idx);
const v = pair.slice(idx + 1);
const existing = out.filters[k];
if (existing == null) out.filters[k] = v;
else if (Array.isArray(existing)) existing.push(v);
else out.filters[k] = [existing, v];
}
}
}
return out;
}
function writeUrlState() {
const params = new URLSearchParams();
if (state.time && state.time !== '24H') params.set('t', state.time);
if (state.time === 'CUSTOM' && state.timeCustom) {
if (state.timeCustom.from) params.set('tfrom', state.timeCustom.from);
if (state.timeCustom.to) params.set('tto', state.timeCustom.to);
}
if (state.cluster) params.set('c', state.cluster);
for (const [k, v] of Object.entries(currentFilters())) {
if (Array.isArray(v)) for (const x of v) params.append('f', `${k}:${x}`);
else params.append('f', `${k}:${v}`);
}
const qs = params.toString();
const url = location.pathname + (qs ? '?' + qs : '') + location.hash;
history.replaceState(null, '', url);
}
function setRefreshInterval(ms) {
state.refresh = ms;
localStorage.setItem(LS.refresh, String(ms));
if (state.refreshTimer) { clearInterval(state.refreshTimer); state.refreshTimer = null; }
if (ms > 0) {
state.refreshTimer = setInterval(() => {
probeLiveFeatures();
if (state.section === 'dashboards' || state.section === 'discover') render();
}, ms);
}
}
// ---------- live-feature probes ---------------------------
// Some dashboards only earn a nav entry once the engine actually has
// data for them (registry `requiresLive` flag). This asks the probes,
// updates `state.liveFeatures`, and re-renders on a change so the nav
// entry appears/disappears without a reload. The probe module caches
// per baseUrl (~30 s), so calling this on every refresh tick is cheap,
// and a backend/base-URL change naturally re-probes the new target.
let _probingLive = false;
async function probeLiveFeatures() {
if (_probingLive) return;
_probingLive = true;
try {
const base = backendBaseUrl(activeBackendId());
// Two cheap probes: brains (.xerj-memory-*-edges) + the data-plane classes
// (chat-events, vector-ops, agent-memory, anomalies, logs-*). Each dashboard
// gates its nav entry on its own key so a fresh / brain-only engine never
// advertises a mock-filled telemetry dashboard.
const [brains, dataFeat, idxNames] = await Promise.all([
sbBrainsPresent(base),
dataFeaturesPresent(base),
indexNames(base),
]);
const next = { brains, ...dataFeat };
let changed = false;
for (const k of Object.keys(next)) {
if (next[k] !== state.liveFeatures[k]) { state.liveFeatures[k] = next[k]; changed = true; }
}
// Real index list. Re-render if it changed so the index picker targets
// actual data.
if (JSON.stringify(idxNames) !== JSON.stringify(state.indices)) { state.indices = idxNames || []; changed = true; }
// If the selected index no longer exists (stale localStorage, renamed or
// deleted index), fall back to a real one so the console lands on actual
// data instead of an empty/erroring result. `*` is kept (backend resolves
// it to the primary index).
if (state.indices.length && state.search.index !== '*' && !state.indices.includes(state.search.index)) {
state.search.index = state.indices[0];
state.search.result = null;
changed = true;
}
if (changed) {
// Same guards as the store/panel re-render hooks: never nuke an
// in-flight drag gesture or steal focus from a form field.
const ae = document.activeElement;
const typing = ae && (ae.tagName === 'INPUT' || ae.tagName === 'SELECT' || ae.isContentEditable);
if (!geomDrag && !typing) render();
}
} finally {
_probingLive = false;
}
}
// ---------- saved views -----------------------------------
// A saved view is a snapshot of (dashId, time, cluster, filters).
// Click it to land on that dashboard with the same context.
function loadViews() { return loadJSON(LS.views, []); }
function saveViews(views) { localStorage.setItem(LS.views, JSON.stringify(views)); }
function saveCurrentView() {
const dashId = state.route;
const all = loadViews();
const name = prompt('Save view as:', 'View ' + (all.length + 1));
if (!name) return;
const id = 'v-' + Date.now().toString(36);
all.push({
id,
name,
dashId,
time: state.time,
cluster: state.cluster,
filters: currentFilters(),
savedAt: new Date().toISOString(),
});
saveViews(all);
}
function deleteView(id) {
saveViews(loadViews().filter((v) => v.id !== id));
}
function applyView(id) {
const v = loadViews().find((x) => x.id === id);
if (!v) return;
state.time = v.time;
state.cluster = v.cluster || state.cluster;
state.filters[v.dashId] = { ...(v.filters || {}) };
saveFilters(v.dashId);
localStorage.setItem(LS.time, state.time);
location.hash = '#/dashboards/' + v.dashId;
}
function relTime(iso) {
if (!iso) return '';
const delta = Date.now() - new Date(iso).getTime();
if (delta < 2000) return 'just now';
if (delta < 60_000) return Math.round(delta / 1000) + 's ago';
if (delta < 3600_000) return Math.round(delta / 60_000) + 'm ago';
return Math.round(delta / 3600_000) + 'h ago';
}
function navStatus() {
if (state.loading) return 'LOADING…';
if (state.fetchErr) return 'ERROR · ' + state.fetchErr.slice(0, 40);
const bits = [];
// Prefer the label of the CURRENTLY-RENDERED view (state.sourceLabel, set
// from that view's own fetch below). The module-global dataSourceStatus() is
// a last-writer-wins value that any background/other-dashboard query can
// overwrite — reading it here is what let a live page show a stale/other
// dashboard's "MOCK FALLBACK". Fall back to it only before the first fetch.
bits.push(state.sourceLabel
|| (typeof dataSourceStatus === 'function' ? dataSourceStatus() : String(dataSourceStatus)));
if (state.fetchedAt) bits.push('UPDATED ' + relTime(state.fetchedAt).toUpperCase());
if (state.fetchMs != null) bits.push(state.fetchMs + 'MS');
return bits.join(' · ');
}
function runSearchNow() {
// No optimistic placeholder: until the engine answers, the table says
// SEARCHING and holds nothing. This function used to seed the result with
// mockSearch() — fabricated service/host/level hits — and keep them on any
// backend error, so a failed search showed invented documents under a LIVE
// pill (#923 review finding 5). Every outcome is now one of: pending, the
// engine's hits, or an explicit error with zero rows.
const seq = (state.search._seq = (state.search._seq || 0) + 1);
const prev = state.search.result;
state.search.result = { hits: [], total: 0, facets: {}, roles: prev?.roles || null, pending: true };
query({
dashId: 'search-discover',
range: state.time,
customRange: state.time === 'CUSTOM' ? state.timeCustom : null,
cluster: state.cluster,
filters: state.search.filters,
search: {
q: state.search.q,
type: state.search.type,
index: state.search.index,
sort: state.search.sort,
},
})
.then((res) => {
if (seq !== state.search._seq) return; // a newer search owns the table
const live = res?.data || {};
state.search.result = live.error
? { hits: [], total: 0, facets: {}, roles: live.roles || null, error: String(live.error),
resolvedIndex: live.resolvedIndex ?? null, narrowed: !!live.narrowed, request: live.request || null }
: {
hits: live.hits || [],
total: live.total ?? (live.hits?.length ?? 0),
tookMs: live.took ?? 0,
maxScore: live.max_score ?? null,
facets: live.facets || {},
histogram: live.histogram || null,
histogramField: live.histogramField || null,
roles: live.roles || null,
resolvedIndex: live.resolvedIndex ?? null,
narrowed: !!live.narrowed,
request: live.request || null,
_live: true,
};
state.fetchedAt = res.meta?.fetchedAt || Date.now();
state.fetchMs = res.meta?.durationMs ?? state.fetchMs;
// Only relabel if we're still on the search-driven view — a late search
// resolving after you've navigated away must not repaint the new view.
if (res.meta?.sourceLabel && state.section === 'discover') {
state.sourceLabel = res.meta.sourceLabel; state.sourceKind = res.meta.sourceKind;
}
if (state.section === 'discover') render();
})
.catch((err) => {
if (seq !== state.search._seq) return;
state.search.result = { hits: [], total: 0, facets: {}, roles: null, error: String(err && err.message || err) };
if (state.section === 'discover') render();
});
// Persist the inputs (not the result — it rebuilds on demand)
localStorage.setItem(LS.search, JSON.stringify({
q: state.search.q,
type: state.search.type,
index: state.search.index,
filters: state.search.filters,
sort: state.search.sort,
showTime: state.search.showTime,
}));
}
/**
* Parse the hash into { section, route }. Routes come in three shapes:
*
* #/ → section=dashboards, route=<first dashboard>
* #/dashboards → section=dashboards, route=<first dashboard>
* #/dashboards/:id → section=dashboards, route=:id
* #/<section> → section=<section>, route=<view id for that section>
*
* Backward compat: legacy `#/ai-overview` (bare dashboard id) gets
* auto-routed into `#/dashboards/ai-overview`, and legacy `#/manage`
* redirects to `#/settings`.
*/
function parseRoute() {
// Route = the hash *path* only. A `?query` tail inside the hash (e.g.
//
10BC8
`#/second-brain?brain=notes`, the deep link `xerj brain` prints) is
// view state owned by the dashboard, never part of the route.
const raw = (location.hash || '').replace(/^#\/?/, '').split('?')[0];
const parts = raw.split('/').filter(Boolean);
const merged = mergedDashboards(defaults, { includeHidden: true });
// Helper: find the default view id for a section.
const firstOfSection = (sectionId) => {
const list = dashboardsInSection(sectionId, merged);
return list[0]?.id;
};
// Empty hash → the Corpus home: what is indexed on this engine. It reads
// the live catalog and has an honest empty state (one command), so it is a
// safe landing on any engine — unlike a telemetry dashboard, it has nothing
// to fall back to.
if (!parts.length) {
return { section: 'corpus', route: 'corpus' };
}
// Legacy: #/manage → settings
if (parts[0] === 'manage') return { section: 'settings', route: 'settings' };
// Section-level route: #/section or #/section/:id
const sectionIds = new Set(SECTIONS.map((s) => s.id));
if (sectionIds.has(parts[0])) {
if (parts[0] === 'dashboards') {
const id = parts[1] || firstOfSection('dashboards') || 'ai-overview';
// Only accept real dashboards in this section
const known = merged.find((d) => d.id === id && (d.section || 'dashboards') === 'dashboards');
if (known) return { section: 'dashboards', route: id };
return { section: 'dashboards', route: firstOfSection('dashboards') || 'ai-overview' };
}
// Non-dashboards sections have exactly one view: firstOfSection
const first = firstOfSection(parts[0]);
if (first) return { section: parts[0], route: first };
}
// Legacy bare route: #/ai-overview → #/dashboards/ai-overview
if (merged.some((d) => d.id === parts[0])) {
const d = merged.find((x) => x.id === parts[0]);
const section = d.section || 'dashboards';
return { section, route: parts[0] };
}
// Fallback
return { section: 'dashboards', route: firstOfSection('dashboards') || 'ai-overview' };
}
// Build the data context that the section views (DATA / SETTINGS)
// need. Async because the reads hit the console's data-sources facade
// (data/data-sources.js — real-only; an unreachable engine yields
// empty lists, never seeded rows).
async function buildSectionData(sectionId) {
if (sectionId === 'data') {
const clusters = await listClusters();
const indicesByCluster = {};
const fieldsByIndex = {};
for (const c of clusters) {
indicesByCluster[c.id] = await listIndices(c.id);
}
const active = defaultClusterId();
for (const i of indicesByCluster[active] || []) {
fieldsByIndex[i.name] = await listFields(i.name);
}
return {
clusters,
indicesByCluster,
fieldsByIndex,
activeCluster: active,
focusIndex: state._focusIndex || (indicesByCluster[active] || [])[0]?.name,
};
}
if (sectionId === 'settings') {
return {
dashboards: mergedDashboards(defaults, { includeHidden: true }),
views: loadViews(),
};
}
return {};
}
function loadAllLayouts() {
// Iterate ALL `xerj.layout.*` keys — not just registry ids — so
// layouts synced down from /prefs.layouts (which may include ids this
// build doesn't ship, or default-dashboard overrides hydrated on
// another machine) are picked up instead of silently dropped.
const out = {};
const prefix = 'xerj.layout.';
for (const k of Object.keys(localStorage)) {
if (!k.startsWith(prefix)) continue;
const id = k.slice(prefix.length);
try {
const raw = localStorage.getItem(k);
if (raw) out[id] = JSON.parse(raw);
} catch { /* ignore corrupt */ }
}
return out;
}
function saveLayout(dashId) {
const v = state.layouts[dashId];
if (!v) localStorage.removeItem(LS.layout(dashId));
else localStorage.setItem(LS.layout(dashId), JSON.stringify(v));
}
function applyTheme(t) {
state.theme = t;
document.documentElement.setAttribute('data-theme', t);
localStorage.setItem(LS.theme, t);
}
// ---------- layout engine ---------------------------------
/**
* Merge a dashboard's default panels with the user's stored override.
* Returns a flat ordered array of panel objects ready to render.
*/
function mergeLayout(defaultPanels, override) {
if (!override) return defaultPanels.map((p) => ({ ...p, source: 'default' }));
const byId = Object.fromEntries(defaultPanels.map((p) => [p.id, p]));
const hidden = new Set(override.hidden || []);
const out = [];
const seen = new Set();
const order = override.order || defaultPanels.map((p) => p.id);
for (const id of order) {
if (hidden.has(id)) { seen.add(id); continue; }
const base = byId[id];
if (base) {
const cols = override.cols?.[id] ?? base.cols;
out.push({ ...base, cols, source: 'default' });
seen.add(id);
} else {
// Maybe a user-added panel.
const added = (override.added || []).find((a) => a.id === id);
if (added) {
const cols = override.cols?.[id] ?? added.cols;
out.push({ ...added, cols, source: 'added' });
seen.add(id);
}
}
}
// Append defaults missing from order (new panels added since override was saved).
for (const p of defaultPanels) {
if (!seen.has(p.id) && !hidden.has(p.id)) {
const cols = override.cols?.[p.id] ?? p.cols;
out.push({ ...p, cols, source: 'default' });
}
}
// Append user-added panels missing from order (freshly added).
for (const added of (override.added || [])) {
if (!seen.has(added.id)) {
const cols = override.cols?.[added.id] ?? added.cols;
out.push({ ...added, cols, source: 'added' });
}
}
return out;
}
function ensureOverride(dashId, defaultPanels) {
if (state.layouts[dashId]) return state.layouts[dashId];
const fresh = {
order: defaultPanels.map((p) => p.id),
cols: {},
hidden: [],
added: [],
};
state.layouts[dashId] = fresh;
return fresh;
}
function mutate(dashId, defaultPanels, fn) {
const ov = ensureOverride(dashId, defaultPanels);
fn(ov);
saveLayout(dashId);
}
// ---------- render ----------------------------------------
// Quick-size presets kept as a panel-toolbar convenience (the 6 discrete
// spans are no longer the ONLY resize path — declarative user panels get
// free w×h drag-resize; see the pointer handlers below).
const SIZES = [3, 4, 6, 8, 12];
const GRID_COLS = 12;
const ROW_H = 132; // px per grid row-unit in declarative canvases
const DEFAULT_GEOM = { x: 0, y: 0, w: 6, h: 2 };
// ---- declarative geometry helpers ------------------------
function clampInt(v, lo, hi) { v = Math.round(Number(v) || 0); return Math.max(lo, Math.min(hi, v)); }
function panelGeom(p) {
const g = p.geometry || {};
const w = clampInt(g.w ?? DEFAULT_GEOM.w, 1, GRID_COLS);
return {
x: clampInt(g.x ?? DEFAULT_GEOM.x, 0, GRID_COLS - w),
y: Math.max(0, Math.round(Number(g.y) || 0)),
w,
h: Math.max(1, Math.round(Number(g.h) || DEFAULT_GEOM.h)),
};
}
/** Next free row below everything, full-width-ish default slot. */
function nextGeometry(panels) {
let maxBottom = 0;
for (const p of panels || []) {
const g = panelGeom(p);
maxBottom = Math.max(maxBottom, g.y + g.h);
}
return { x: 0, y: maxBottom, w: 6, h: 2 };
}
/** Kibana-style vertical compaction: push overlapping panels down so no
* two panels occupy the same cell. Stable by (y, x). */
function compact(panels) {
const sorted = panels
.map((p, i) => ({ p, g: panelGeom(p), i }))
.sort((a, b) => (a.g.y - b.g.y) || (a.g.x - b.g.x) || (a.i - b.i));
const placed = [];
const overlaps = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
for (const item of sorted) {
const g = { ...item.g };
let moved = true;
while (moved) {
moved = false;
for (const q of placed) {
if (overlaps(g, q.g)) { g.y = q.g.y + q.g.h; moved = true; }
}
}
placed.push({ p: item.p, g });
}
return placed.map(({ p, g }) => ({ ...p, geometry: g }));
}
// ---- builder (per-panel configurator) state --------------
const builder = {
open: false,
editingId: null, // panel id when editing an existing panel, else null
viz: 'topn',
index: '',
kind: 'terms',
field: 'level',
metric: 'count',
size: 8,
interval: '1h',
q: '',
title: '',
time: false,
preview: null, // { status, html } cache of the live preview
previewKey: '',
};
let BUILDER_INDICES = []; // cached index list for the picker
let BUILDER_FIELDS = []; // cached field list for the current index
function renderEditChrome(p) {
const sizes = SIZES.map((s) =>
`<button type="button" data-panel="${esc(p.id)}" data-size="${s}" class="${p.cols === s ? 'active' : ''}" aria-pressed="${p.cols === s}">${s}</button>`
).join('');
// Compact single-line toolbar so it fits the reserved 24px strip even on
// dense 2-col tiles (Issue 3): a small n/12 readout + size presets + ✕.
return `
<span class="panel-grip" aria-hidden="true">⠿</span>
<div class="panel-edit" aria-label="Edit panel">
<span class="wh mono">${p.cols}<span class="x">/</span>12</span>
<span class="sizes">${sizes}</span>
<button type="button" class="remove" data-panel="${esc(p.id)}" data-remove aria-label="Remove">✕</button>
</div>`;
}
// Declarative user-panel chrome: a top-left drag GRIP + a top-right
// toolbar (never in title flow) + SE/E/S resize handles.
function renderUserPanelChrome(p) {
const g = panelGeom(p);
const presets = SIZES.map((s) =>
`<button type="button" data-user-size="${s}" data-panel="${esc(p.id)}" class="${g.w === s ? 'active' : ''}">${s}</button>`
).join('<span class="sep">·</span>');
return `
<span class="panel-grip" data-grip="${esc(p.id)}" title="Drag to move" aria-label="Move panel">⠿</span>
<div class="panel-edit user" aria-label="Edit panel">
<span class="wh mono">${g.w}<span class="x">×</span>${g.h}</span>
<span class="sizes">${presets}</span>
<button type="button" class="cfg" data-user-config="${esc(p.id)}" title="Edit query / viz">QUERY</button>
<button type="button" class="remove" data-user-remove="${esc(p.id)}" aria-label="Remove">✕</button>
</div>
<span class="panel-resize e" data-resize="e" data-panel="${esc(p.id)}" aria-hidden="true"></span>
<span class="panel-resize s" data-resize="s" data-panel="${esc(p.id)}" aria-hidden="true"></span>
<span class="panel-resize se" data-resize="se" data-panel="${esc(p.id)}" aria-hidden="true"></span>`;
}
function renderPanel(p, data, editMode, ctx) {
// Declarative user panels: explicit x/y/w/h placement + per-panel live
// query (data/panel-query.js) rendered through the shared chart
// catalog (ux/panel-render.js). Chrome is out of title flow.
if (p.source === 'user') {
const g = panelGeom(p);
let inner;
try {
inner = renderDeclarativePanel(p, panelResult(p, ctx || {}));
} catch (err) {
inner = `<div class="panel-empty mono faint">PANEL ERROR · ${esc((err.message || err) + '').slice(0, 80)}</div>`;
}
const style = `grid-column:${g.x + 1}/span ${g.w}; grid-row:${g.y + 1}/span ${g.h};`;
const chrome = editMode ? renderUserPanelChrome(p) : '';
return `
<section class="panel user-panel${editMode ? ' edit' : ''}" data-panel="${esc(p.id)}" data-user-panel="1" style="${style}">
${chrome}
${p.title ? `<div class="key">${esc(p.title)}</div>` : ''}
${inner}
</section>`;
}
let inner = '';
try {
if (p.source === 'added') {
const t = chartTypes[p.type] || chartTypes.markdown;
inner = t.render(data);
} else if (typeof p.render === 'function') {
inner = p.render({ data });
} else {
inner = '';
}
// Empty-state fallback: if the render produced nothing meaningful,
// show a typography-first placeholder so users see WHY the slot is
// blank (e.g. filtered everything out) rather than a broken panel.
// A safe-mount panel (Corpus, Reader) is an EMPTY element on purpose:
// mountSafePanels() fills it with DOM nodes after this string is parsed.
const stripped = String(inner || '').replace(/<[^>]+>/g, '').trim();
if (!stripped && !/\sdata-safe-mount="/.test(String(inner))) {
inner = `<div class="panel-empty mono faint">NO DATA · ADJUST FILTERS OR TIME RANGE</div>`;
}
} catch (err) {
inner = `<div class="panel-empty mono faint">PANEL ERROR · ${esc((err.message || err) + '').slice(0, 80)}</div>`;
}
const editAttrs = editMode ? ' draggable="true"' : '';
const editChrome = editMode ? renderEditChrome(p) : '';
// A panel that declares `drilldown: { to: <dashId> }` adds a
// data attribute the global click handler uses to route clicks
// to the target dashboard with the clicked filter preserved.
const drillAttr = p.drilldown?.to ? ` data-drilldown-to="${esc(p.drilldown.to)}"` : '';
const drillHint = p.drilldown?.to ? `<span class="drill-hint mono faint">→ ${esc(p.drilldown.to.toUpperCase())}</span>` : '';
return `
<section class="panel${editMode ? ' edit' : ''}" data-panel="${esc(p.id)}" style="grid-column: span ${p.cols};"${editAttrs}${drillAttr}>
${editChrome}
${p.eyebrow ? `<div class="key">${esc(p.eyebrow)}${drillHint}</div>` : ''}
${inner}
</section>`;
}
function renderAddPicker(dash) {
// Declarative user dashboards get the real builder: + ADD PANEL opens
// an inline configurator (viz type → index/query → live preview).
if (dash && dash.declarative) {
if (builder.open) return renderBuilder();
return `
<div class="add-picker">
<button type="button" class="add-panel-btn" data-builder-open>+ ADD PANEL</button>
<span class="mono faint">BUILD A PANEL FROM ANY INDEX · PICK A VISUALIZATION + QUERY</span>
</div>`;
}
// Default (code) dashboards keep the quick chart-type add picker.
const items = chartTypeList.map((t) =>
`<button type="button" data-add="${esc(t.id)}" title="${esc(t.describe || '')}">${esc(t.name)}</button>`
).join('<span class="sep">·</span>');
return `
<div class="add-picker">
<span class="key" style="color:var(--z-accent);">+ ADD PANEL</span>
<span class="types">${items}</span>
</div>`;
}
// Build a declarative panel object from the current builder state.
function builderPanelDraft() {
const autoTitle = (builder.field
? `${builder.field} · ${chartTypes[builder.viz]?.name || builder.viz}`
: (chartTypes[builder.viz]?.name || builder.viz)).toUpperCase();
return {
id: builder.editingId || ('p-' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5)),
title: (builder.title || autoTitle),
viz: { type: builder.viz, options: {} },
query: {
index: builder.index,
kind: builder.kind,
q: builder.q || '',
field: builder.field || '',
metric: builder.metric || 'count',
size: Number(builder.size) || 8,
interval: builder.interval || '1h',
time: !!builder.time,
},
geometry: builder._geometry || null,
};
}
const VIZ_LIST = ['metric', 'spark', 'gauge', 'line', 'bar', 'histogram', 'dist', 'topn', 'treemap', 'table', 'events'];
const KINDS = ['count', 'metric', 'timeseries', 'terms', 'search'];
const METRICS = ['count', 'sum', 'avg', 'max', 'min'];
// The inline configurator rendered in place of the ADD picker.
function renderBuilder() {
const b = builder;
const vizTiles = VIZ_LIST.map((id) =>
`<button type="button" data-builder-viz="${id}" class="${b.viz === id ? 'active' : ''}" title="${esc(chartTypes[id]?.describe || '')}">${esc(chartTypes[id]?.name || id)}</button>`
).join('');
const idxDatalist = BUILDER_INDICES.map((i) => `<option value="${esc(i.name)}"></option>`).join('');
const kindBtns = KINDS.map((k) =>
`<button type="button" data-builder-kind="${k}" class="${b.kind === k ? 'active' : ''}">${k.toUpperCase()}</button>`).join('<span class="sep">·</span>');
const metricBtns = METRICS.map((m) =>
`<button type="button" data-builder-metric="${m}" class="${b.metric === m ? 'active' : ''}">${m.toUpperCase()}</button>`).join('<span class="sep">·</span>');
const fieldList = BUILDER_FIELDS.map((f) => `<option value="${esc(f.name)}"></option>`).join('');
const needsField = b.kind === 'terms' || b.kind === 'metric' || (b.kind === 'timeseries' && b.metric !== 'count');
const needsSize = b.kind === 'terms';
const needsInterval = b.kind === 'timeseries';
const preview = b.preview && b.preview.html
? b.preview.html
: `<div class="panel-empty mono faint">${b.preview && b.preview.status === 'loading' ? 'RUNNING PREVIEW…' : 'PREVIEW APPEARS HERE'}</div>`;
return `
<div class="builder" role="dialog" aria-label="Configure panel">
<div class="builder-head">
<span class="key" style="color:var(--z-accent);">${b.editingId ? 'EDIT PANEL' : '+ NEW PANEL'}</span>
<button type="button" class="builder-x" data-builder-cancel aria-label="Close">✕</button>
</div>
<div class="builder-grid">
<div class="builder-col builder-form">
<label class="builder-field">
<span class="key">1 · VISUALIZATION</span>
<span class="viz-tiles">${vizTiles}</span>
</label>
<label class="builder-field">
<span class="key">2 · INDEX</span>
<input type="text" data-builder-index list="builder-indices" value="${esc(b.index)}" placeholder="e.g. logs-prod" class="builder-input" />
<datalist id="builder-indices">${idxDatalist}</datalist>
</label>
<label class="builder-field">
<span class="key">3 · QUERY KIND</span>
<span class="btn-row">${kindBtns}</span>
</label>
${needsField ? `
<label class="builder-field">
<span class="key">FIELD</span>
<input type="text" data-builder-field list="builder-fields" value="${esc(b.field)}" placeholder="e.g. level" class="builder-input" />
<datalist id="builder-fields">${fieldList}</datalist>
</label>` : ''}
${(b.kind === 'metric' || b.kind === 'timeseries' || b.kind === 'terms') ? `
<label class="builder-field">
<span class="key">METRIC</span>
<span class="btn-row">${metricBtns}</span>
</label>` : ''}
${needsSize ? `
<label class="builder-field">
<span class="key">TOP N</span>
<input type="number" min="1" max="50" data-builder-size value="${esc(b.size)}" class="builder-input short" />
</label>` : ''}
${needsInterval ? `
<label class="builder-field">
<span class="key">INTERVAL</span>
<input type="text" data-builder-interval value="${esc(b.interval)}" placeholder="1h" class="builder-input short" />
</label>` : ''}
<label class="builder-field">
<span class="key">FILTER (KQL)</span>
<input type="text" data-builder-q value="${esc(b.q)}" placeholder="optional · e.g. level:error" class="builder-input" />
</label>
<label class="builder-field">
<span class="key">TITLE</span>
<input type="text" data-builder-title value="${esc(b.title)}" placeholder="auto" class="builder-input" />
</label>
<div class="builder-actions">
<button type="button" class="builder-save" data-builder-save>${b.editingId ? 'SAVE CHANGES' : 'ADD PANEL'}</button>
<button type="button" class="builder-cancel" data-builder-cancel>CANCEL</button>
</div>
</div>
<div class="builder-col builder-preview">
<span class="key">LIVE PREVIEW</span>
<div class="builder-preview-box">${preview}</div>
</div>
</div>
</div>`;
}
// render() is async (it awaits the route's data) and is called from many
// places — boot, hashchange, the live-feature probe, the dashboard store,
// per-panel settles — with nothing serialising them. Without a guard the
// LAST render to finish wins, not the last one STARTED: a slow #/corpus fetch
// begun just before a route change resolves after the new route has painted
// and paints the old view (and its LIVE pill) back over it, with no further
// render to correct it (issue #1425). Each render takes a generation number;
// after every await, a render that has been superseded stops without touching
// state or the DOM — the newer render owns both.
let renderGen = 0;
async function render() {
const gen = ++renderGen;
const superseded = () => gen !== renderGen;
const app = document.getElementById('app');
// Resolve the active dashboard from either the default registry or
// the user metadata store. User-cloned dashboards inherit their
// render from their clonedFrom template.
const allDash = mergedDashboards(defaults, { includeHidden: true });
// NAV list only: hide live-gated dashboards until their probe says the engine
// holds their data (Second Brain before any `xerj brain`; the telemetry
// dashboards before anything is ingested). `allDash` stays unfiltered so a
// deep link resolves instantly; the nav catches up on the next probe tick.
const navDash = mergedDashboards(defaults)
.filter((d) => !d.requiresLive || state.liveFeatures[d.requiresLive]);
const dashboardsForSection = dashboardsInSection('dashboards', navDash);