-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpositorium.html
More file actions
792 lines (756 loc) · 29.8 KB
/
positorium.html
File metadata and controls
792 lines (756 loc) · 29.8 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Positorium Query Console</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="positorium.css" />
</head>
<body>
<!-- Inline regex-based syntax highlighting (no external deps) -->
<header>
<img class="svg" src="Traqula.svg"/>
Positorium Query Console
</header>
<main>
<div id="splitContainer">
<div id="editorPane">
<section>
<label for="endpoint">Endpoint</label>
<input id="endpoint" type="text" value="http://127.0.0.1:8080/v1/query" />
<label for="script">Traqula Script (Ctrl+Enter to run)</label>
<div id="script-container">
<div id="script" contenteditable="true" spellcheck="false"></div>
</div>
<div class="controls">
<button id="runBtn">Run</button>
<button id="clearBtn" title="Clear results">Clear</button>
<label>Timeout <input type="number" id="timeout" min="0" step="100" placeholder="ms"></label>
<label><input type="checkbox" id="autoScroll" checked> Auto-scroll to latest</label>
<label><input type="checkbox" id="streamMode"> Stream results</label>
<label><input type="checkbox" id="wasmMode"> Local WASM</label>
</div>
<div id="statusBar"></div>
<progress id="progress" max="100" value="0"></progress>
</section>
</div>
<div id="splitter" title="Drag to resize"></div>
<div id="resultsPane">
<div id="resultsTabs">
<button class="tabBtn active" data-tab="table">Table</button>
<button class="tabBtn" data-tab="json">JSON</button>
<button class="tabBtn" data-tab="status">Status</button>
<select id="resultSetSelect" style="display:none;" title="Select result set"></select>
<div></div>
<span id="perf"></span>
</div>
<div id="tableView">
<table id="resultsTable">
<thead></thead>
<tbody></tbody>
</table>
</div>
<div id="jsonView">
<pre id="jsonOut"></pre>
</div>
<div id="statusView">
<pre id="statusOut"></pre>
</div>
</div>
</div>
</main>
<footer>
<span>Positorium local console (dev)</span>
<span>Drag splitter to resize editor/results • Tabs to switch view • Status tab shows logs</span>
</footer>
<script>
const els = {
endpoint: document.getElementById('endpoint'),
script: document.getElementById('script'),
runBtn: document.getElementById('runBtn'),
clearBtn: document.getElementById('clearBtn'),
tableHead: document.querySelector('#resultsTable thead'),
tableBody: document.querySelector('#resultsTable tbody'),
status: document.getElementById('statusBar'),
jsonOut: document.getElementById('jsonOut'),
autoScroll: document.getElementById('autoScroll'),
streamMode: document.getElementById('streamMode'),
wasmMode: document.getElementById('wasmMode'),
timeout: document.getElementById('timeout'),
perf: document.getElementById('perf'),
progress: document.getElementById('progress'),
splitter: document.getElementById('splitter'),
editorPane: document.getElementById('editorPane'),
resultsPane: document.getElementById('resultsPane'),
tabs: document.querySelectorAll('.tabBtn'),
tableView: document.getElementById('tableView'),
jsonView: document.getElementById('jsonView'),
statusView: document.getElementById('statusView'),
statusOut: document.getElementById('statusOut'),
resultSetSelect: document.getElementById('resultSetSelect')
};
// Hover highlight feature removed; stubs and related logic eliminated.
// Event listeners for hover highlighting on dropdown
document.addEventListener('DOMContentLoaded', () => {
// Load saved query from localStorage
const savedQuery = localStorage.getItem('positorium-query');
if (savedQuery) {
scriptEditor.textContent = savedQuery;
}
// Initialize highlighting
setTimeout(() => {
updateHighlight();
setStatus('Editor loaded with syntax highlighting');
// Initialize status view with welcome message
const initTime = new Date().toLocaleTimeString();
els.statusOut.textContent = `[${initTime}] Positorium Query Console initialized\n[${initTime}] Editor loaded with syntax highlighting\n`;
}, 100);
// Button event listeners
els.runBtn.addEventListener('click', runQuery);
els.clearBtn.addEventListener('click', () => {
els.tableHead.innerHTML='';
els.tableBody.innerHTML='';
els.jsonOut.textContent='';
els.statusOut.textContent='';
els.perf.textContent='';
// Hide and reset result set selector so old streaming sets cannot be resurrected
els.resultSetSelect.style.display='none';
els.resultSetSelect.innerHTML='';
els.resultSetSelect.onchange = null;
lastResponse = null;
setStatus('Cleared');
});
// Tabs switching
els.tabs.forEach(btn=>{
btn.addEventListener('click', ()=>{
els.tabs.forEach(b=>b.classList.remove('active'));
btn.classList.add('active');
const tab = btn.getAttribute('data-tab');
if (tab==='table') {
els.tableView.style.display='block';
els.jsonView.style.display='none';
els.statusView.style.display='none';
}
else if (tab==='json') {
els.tableView.style.display='none';
els.jsonView.style.display='block';
els.statusView.style.display='none';
}
else if (tab==='status') {
els.tableView.style.display='none';
els.jsonView.style.display='none';
els.statusView.style.display='block';
}
});
});
// Vertical splitter drag logic
let dragging = false; let startY = 0; let startHeight = 0;
function setEditorHeight(px){
const min = 100; const max = window.innerHeight * 0.85;
const clamped = Math.min(Math.max(px,min), max);
els.editorPane.style.flex = '0 0 '+clamped+'px';
}
els.splitter.addEventListener('mousedown', e=>{
dragging = true; startY = e.clientY; startHeight = els.editorPane.getBoundingClientRect().height;
document.body.style.cursor='row-resize';
e.preventDefault();
});
window.addEventListener('mousemove', e=>{
if (!dragging) return;
const dy = e.clientY - startY;
setEditorHeight(startHeight + dy);
});
window.addEventListener('mouseup', ()=>{ if (dragging) { dragging=false; document.body.style.cursor=''; }});
window.addEventListener('resize', ()=>{ /* keep within bounds */ setEditorHeight(els.editorPane.getBoundingClientRect().height); });
});
// Lightweight Traqula tokenizer/highlighter
const TRAQ_TOKENS = [
{ name: 'comment', re: /\/\*[\s\S]*?\*\//y },
{ name: 'string', re: /"(?:[^"\\]|\\.)*"/y },
{ name: 'time', re: /'[0-9:\-\s]+'/y },
{ name: 'variable-insert', re: /\+[A-Za-z][A-Za-z0-9_]*/y },
{ name: 'keyword', re: /\b(?:add|role|posit|search|return|where|and|limit|as|of)\b/iy },
{ name: 'constant', re: /@[A-Z]+/y },
{ name: 'number', re: /-?\d+(?:\.\d+)?%?/y },
{ name: 'wildcard', re: /\*/y },
{ name: 'punctuation', re: /[\[\]{}(),;]/y },
{ name: 'operator', re: /[+|<>=!]+/y },
{ name: 'variable', re: /\b[a-zA-Z][a-zA-Z0-9_]*\b/y }
];
function highlightTraqula(src) {
let pos = 0;
const out = [];
const n = src.length;
while (pos < n) {
let matched = false;
for (let i = 0; i < TRAQ_TOKENS.length; i++) {
const { name, re } = TRAQ_TOKENS[i];
re.lastIndex = pos;
const m = re.exec(src);
if (m && m.index === pos) {
const text = m[0];
out.push('<span class="token ' + name + '">' + escapeHtml(text) + '</span>');
pos += text.length;
matched = true;
break;
}
}
if (!matched) {
// Emit single character (includes whitespace)
const ch = src.charAt(pos);
out.push(escapeHtml(ch));
pos += 1;
}
}
return out.join('');
}
// Get DOM elements
const scriptEditor = document.getElementById('script');
// Debounce timer for highlighting
let highlightTimer = null;
function scheduleHighlight(delay = 50) {
if (highlightTimer) clearTimeout(highlightTimer);
highlightTimer = setTimeout(() => {
highlightTimer = null;
updateHighlight();
}, delay);
}
// Helper to convert any <br> or unwanted block elements to plain text with \n
function normalizePlainText(element) {
// Convert <br> to \n in text nodes
// This handles Enter key presses which use insertLineBreak
const brs = Array.from(element.querySelectorAll('br'));
brs.forEach(br => {
br.replaceWith(document.createTextNode('\n'));
});
}
// Function to update syntax highlighting
function updateHighlight() {
// Disconnect observer to avoid triggering on our own changes
observer.disconnect();
// Normalize: convert any <br> or <div> elements to plain text with \n
// This can happen when pasting or pressing Enter in contenteditable
normalizePlainText(scriptEditor);
const code = scriptEditor.innerText;
const highlightedCode = highlightTraqula(code);
// Save selection
const selection = window.getSelection();
const range = selection.rangeCount > 0 ? selection.getRangeAt(0) : null;
let startOffset = 0;
if (range) {
const preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(scriptEditor);
preCaretRange.setEnd(range.startContainer, range.startOffset);
startOffset = preCaretRange.toString().length;
}
scriptEditor.innerHTML = highlightedCode;
// Restore selection
if (range) {
const newRange = document.createRange();
let charCount = 0;
let found = false;
function traverse(node) {
if (found) return;
if (node.nodeType === Node.TEXT_NODE) {
const nextCharCount = charCount + node.length;
if (startOffset <= nextCharCount) {
const pos = Math.max(0, Math.min(node.length, startOffset - charCount));
newRange.setStart(node, pos);
found = true;
}
charCount = nextCharCount;
} else {
for (let child of node.childNodes) {
traverse(child);
}
}
}
traverse(scriptEditor);
if (found) {
selection.removeAllRanges();
selection.addRange(newRange);
}
}
// Reconnect observer after updating
observer.observe(scriptEditor, { subtree: true, characterData: true });
localStorage.setItem('positorium-query', code);
}
// Setup event listeners for the editor
// Use MutationObserver to detect and fix structural changes (like div/br) and trigger highlighting
const observer = new MutationObserver((mutationList) => {
let needsHighlight = false;
for (const mutation of mutationList) {
if (mutation.type === 'characterData') {
needsHighlight = true;
break;
}
}
if (needsHighlight) {
scheduleHighlight();
}
});
observer.observe(scriptEditor, { subtree: true, characterData: true });
scriptEditor.addEventListener('keydown', function(e) {
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
runQuery();
}
// Handle plain Enter to prevent div/br insertion
if (e.key === 'Enter' && !e.ctrlKey && !e.metaKey) {
e.preventDefault();
document.execCommand('insertLineBreak');
}
// Handle tab key for indentation
if (e.key === 'Tab') {
e.preventDefault();
document.execCommand('insertText', false, ' ');
}
});
// Handle paste to insert plain text and prevent HTML formatting issues
scriptEditor.addEventListener('paste', function(e) {
e.preventDefault();
const raw = e.clipboardData.getData('text/plain');
// Normalize all line endings to LF to avoid double spacing (Windows CRLF -> LF)
const text = raw.replace(/\r\n?|\u2028|\u2029/g, '\n');
// Get current selection
const selection = window.getSelection();
if (!selection.rangeCount) return;
// Delete current selection if any
selection.deleteFromDocument();
// Insert as a text node directly instead of using execCommand
// This prevents <br> creation
const textNode = document.createTextNode(text);
const range = selection.getRangeAt(0);
range.insertNode(textNode);
// Move cursor to end of inserted text
range.setStartAfter(textNode);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
// Rehighlight promptly after paste
scheduleHighlight(0);
});
// Also rehighlight after cuts that change structure
scriptEditor.addEventListener('cut', function() {
// Let the cut finish, then rehighlight
setTimeout(() => scheduleHighlight(0), 0);
});
// Save query on page unload
window.addEventListener('beforeunload', () => {
localStorage.setItem('positorium-query', scriptEditor.innerText);
});
// No Monaco initialization needed - using Prism.js instead
function setStatus(msg, cls='') {
// Update the status bar with brief messages only
if (cls === 'err') {
// For errors, show a brief indicator in status bar
els.status.textContent = 'Error occurred - see Status tab for details';
els.status.className = cls;
} else {
// For non-errors, show the full message
els.status.textContent = msg;
els.status.className = cls;
}
// Always log to status view with timestamp
const timestamp = new Date().toLocaleTimeString();
const logEntry = `[${timestamp}] ${msg}\n`;
els.statusOut.textContent += logEntry;
// Auto-scroll to bottom of status view
const statusView = els.statusView;
setTimeout(() => {
statusView.scrollTop = statusView.scrollHeight;
}, 0);
// Switch to status tab if there's an error
if (cls === 'err') {
els.tabs.forEach(btn => btn.classList.remove('active'));
const statusTab = document.querySelector('[data-tab="status"]');
if (statusTab) {
statusTab.classList.add('active');
els.tableView.style.display = 'none';
els.jsonView.style.display = 'none';
els.statusView.style.display = 'block';
}
}
// Switch back to table tab for successful query completion
else if (msg === 'OK') {
els.tabs.forEach(btn => btn.classList.remove('active'));
const tableTab = document.querySelector('[data-tab="table"]');
if (tableTab) {
tableTab.classList.add('active');
els.tableView.style.display = 'block';
els.jsonView.style.display = 'none';
els.statusView.style.display = 'none';
}
}
}
let wasmEngine = null;
async function runWasm(script, started) {
try {
if (!wasmEngine) {
setStatus('Initializing WASM engine...');
const pkg = await import('./pkg/positorium.js');
const { WasmEngine } = pkg;
await pkg.default();
wasmEngine = new WasmEngine();
}
const output = wasmEngine.execute(script);
els.progress.value = 80;
// Simple text-to-table parser for WasmEngine.execute output
const lines = output.trim().split('\n');
let columns = [];
let rows = [];
if (lines.length > 0) {
columns = lines[0].split('\t');
// Skip separator line if present (contains dashes)
const startRow = (lines.length > 1 && lines[1].includes('---')) ? 2 : 1;
for (let i = startRow; i < lines.length; i++) {
if (lines[i].startsWith('... (limited)')) continue;
rows.push(lines[i].split('\t'));
}
}
buildTable(columns, rows, []);
const ms = (performance.now() - started).toFixed(2);
els.perf.textContent = `WASM local | execution ${ms} ms | rows ${rows.length}`;
els.jsonOut.textContent = output;
setStatus('OK');
} catch (e) {
setStatus('WASM error: ' + e, 'err');
console.error(e);
}
}
function escapeHtml(s) { return s.replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"','\'':'''}[c])); }
function buildTable(columns, rows, rowTypes) {
els.tableHead.innerHTML = '';
els.tableBody.innerHTML = '';
if (!columns || columns.length===0) return;
// Collect unique data types for each column
const columnTypes = columns.map((_, colIndex) => {
const types = new Set();
if (rowTypes) {
rowTypes.forEach(rowType => {
if (rowType && rowType[colIndex]) {
types.add(rowType[colIndex]);
}
});
}
return Array.from(types).sort();
});
const tr = document.createElement('tr');
columns.forEach((c,i)=>{
const th = document.createElement('th');
th.innerHTML = escapeHtml(c) + '<br><span>'+ escapeHtml(columnTypes[i].join(', ') || '') +'</span>';
tr.appendChild(th);
});
els.tableHead.appendChild(tr);
rows.forEach((r,ri)=>{
const tr = document.createElement('tr');
r.forEach((cell,ci)=>{
const td = document.createElement('td');
const typ = (rowTypes && rowTypes[ri] ? rowTypes[ri][ci] : '');
let display = String(cell);
if (typ === 'Certainty') {
display = formatCertaintyDisplay(display);
}
td.innerHTML = '<span class="badge '+escapeHtml(typ)+'">'+escapeHtml(typ||'')+'</span> '+ escapeHtml(display);
tr.appendChild(td);
});
els.tableBody.appendChild(tr);
if (els.autoScroll.checked) tr.scrollIntoView({block:'end'});
});
}
function populateResultSetSelect(resultSets) {
const sel = els.resultSetSelect;
if (!resultSets || resultSets.length <= 1) {
sel.style.display = 'none';
sel.innerHTML = '';
return;
}
sel.style.display = 'inline-block';
sel.innerHTML = '';
resultSets.forEach((rs, idx) => {
const opt = document.createElement('option');
const colPreview = rs.columns.slice(0,4).join(', ');
opt.value = idx;
const rowCount = rs.row_count ?? (rs.rows ? rs.rows.length : undefined);
const limited = rs.limited ? ' (limited)' : '';
opt.textContent = rowCount !== undefined ? `Search ${idx+1} (${rowCount} rows${limited})` : `Search ${idx+1}`;
if (rs.search) {
const snippet = rs.search.replace(/\s+/g,' ').slice(0,120);
opt.title = `Search ${idx+1}: ${snippet}${rs.search.length>120?'…':''}`;
opt.dataset.snippet = rs.search; // full snippet for offset computation
} else {
opt.title = `Search ${idx+1} – Columns: ${colPreview}${rs.columns.length>4?'…':''}` + (rowCount!==undefined?` – ${rowCount} rows${limited}`:'');
}
sel.appendChild(opt);
});
}
// Stub previously referenced (removed highlighting feature); keep call safe.
function computeSearchOffsetsForOptions() { /* no-op: highlighting removed */ }
// Unified helper to (re)build multi-search dropdown on streaming path.
function rebuildStreamingDropdown(multiSets, currentIdx) {
const sel = els.resultSetSelect;
if (!multiSets || multiSets.length <= 1) {
sel.style.display='none'; sel.innerHTML=''; return; }
sel.style.display='inline-block';
const prev = (sel.value !== '' ? sel.value : String(currentIdx));
sel.innerHTML='';
multiSets.forEach((s,i)=>{
const opt=document.createElement('option');
const rc = s.row_count || s.rows.length || 0;
const limitedTxt = s.limited ? ' (limited)' : '';
opt.value=i; opt.textContent=`Search ${i+1} (${rc} rows${limitedTxt})`;
if (s.search) { const snippet = s.search.replace(/\s+/g,' ').slice(0,120); opt.title=`Search ${i+1}: ${snippet}${s.search.length>120?'…':''}`; opt.dataset.snippet = s.search; }
sel.appendChild(opt);
});
sel.value = prev;
sel.onchange = () => { const idx = parseInt(sel.value,10); const s = multiSets[idx]; buildTable(s.columns, s.rows, s.row_types); };
computeSearchOffsetsForOptions();
}
async function runQuery() {
console.log('runQuery called');
const endpoint = els.endpoint.value.trim();
const script = scriptEditor.innerText;
console.log('script:', script);
const doStream = els.streamMode.checked;
const doWasm = els.wasmMode.checked;
const payload = { script: script, stream: doStream };
const timeoutMs = parseInt(els.timeout.value || '0',10);
els.runBtn.disabled = true; setStatus('Running...'); els.progress.style.visibility='visible'; els.progress.value=15;
const controller = timeoutMs>0 ? new AbortController() : null;
if (controller) setTimeout(()=>controller.abort(), timeoutMs);
const started = performance.now();
try {
if (doWasm) {
await runWasm(script, started);
} else if (doStream) {
await runStream(endpoint, payload, started, controller);
} else {
const res = await fetch(endpoint, {
method:'POST',
headers: { 'Content-Type':'application/json' },
body: JSON.stringify(payload),
signal: controller? controller.signal : undefined
});
els.progress.value=60;
const json = await res.json();
lastResponse = json;
els.progress.value=85;
if (json.status === 'ok') {
if (json.result_sets) {
populateResultSetSelect(json.result_sets);
const first = json.result_sets[0];
buildTable(first.columns, first.rows||[], first.row_types||[]);
els.resultSetSelect.onchange = () => {
const idx = parseInt(els.resultSetSelect.value,10);
const rs = json.result_sets[idx];
buildTable(rs.columns, rs.rows||[], rs.row_types||[]);
};
} else {
populateResultSetSelect(null);
buildTable(json.columns, json.rows||[], json.row_types||[]);
}
const ms = (performance.now()-started).toFixed(2);
els.perf.textContent = `client ${(ms)} ms | server ${(json.elapsed_ms).toFixed(3)} ms | rows ${json.row_count}`;
setStatus('OK');
} else {
buildTable([],[],[]);
setStatus('Error: '+ json.error, 'err');
}
els.jsonOut.textContent = JSON.stringify(json, null, 2);
}
} catch (e) {
setStatus('Request failed: '+ e.message, 'err');
} finally {
els.runBtn.disabled=false; els.progress.value=100; setTimeout(()=>{els.progress.style.visibility='hidden';},400);
}
}
async function runStream(endpoint, payload, started, controller) {
// Reset table
buildTable([],[],[]); populateResultSetSelect(null); els.jsonOut.textContent='';
// Multi-search streaming accumulation structures
let multiSets = []; // each: { columns, rows, row_types, limited }
let currentSetIndex = 0;
let streamingMulti = false;
const res = await fetch(endpoint, {
method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(payload), signal: controller? controller.signal:undefined
});
if (!res.ok) {
const txt = await res.text();
setStatus('Stream init error: HTTP '+res.status, 'err');
els.jsonOut.textContent = txt; return;
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let columns = null; let rowTypesAll = []; let rowCount=0; let limited=false;
const rows = [];
function flushEvents(text) {
const parts = text.split(/\n\n/);
for (let part of parts) {
if (!part.trim()) continue;
const line = part.trim();
if (!line.startsWith('data:')) continue;
const jsonStr = line.slice(5).trim();
try {
const evt = JSON.parse(jsonStr);
if (evt.event==='meta') {
columns = evt.columns; limited = !!evt.limited; setStatus('Streaming meta received');
buildTable(columns, [], []);
} else if (evt.event==='result_set_start') {
// Start of new result set
streamingMulti = true;
if (!evt.columns) continue;
multiSets.push({ columns: evt.columns, rows: [], row_types: [], limited: false, search: evt.search || null });
const idx = evt.index;
// If first set, initialize overall view
if (multiSets.length === 1) {
currentSetIndex = 0;
buildTable(evt.columns, [], []);
}
// Rebuild dropdown if we now have >1 set
rebuildStreamingDropdown(multiSets, currentSetIndex);
setStatus(`Result set ${idx+1} start`);
} else if (evt.event==='row') {
if (streamingMulti && typeof evt.index === 'number' && multiSets[evt.index]) {
const set = multiSets[evt.index];
set.rows.push(evt.row); set.row_types.push(evt.types); set.row_count = set.rows.length;
if (evt.index === currentSetIndex) {
buildTable(set.columns, set.rows, set.row_types);
}
// Refresh dropdown option text to reflect new row counts
if (multiSets.length > 1) {
rebuildStreamingDropdown(multiSets, currentSetIndex);
}
els.perf.textContent = `stream sets ${multiSets.length} | rows set${evt.index+1}=${set.rows.length}`;
} else { // single-search path
rows.push(evt.row); rowTypesAll.push(evt.types); rowCount = rows.length;
buildTable(columns, rows, rowTypesAll);
els.perf.textContent = `stream rows ${rowCount}`;
}
} else if (evt.event==='result_set_end') {
if (streamingMulti && typeof evt.index === 'number' && multiSets[evt.index]) {
multiSets[evt.index].limited = evt.limited;
multiSets[evt.index].row_count = evt.row_count;
setStatus(`Result set ${evt.index+1} end (${evt.row_count} rows${evt.limited?' limited':''})`);
// Final refresh for this result set to include limited flag
if (multiSets.length > 1) {
rebuildStreamingDropdown(multiSets, currentSetIndex);
}
}
} else if (evt.event==='multi_end') {
const ms = (performance.now()-started).toFixed(2);
if (streamingMulti) {
const total = evt.total_rows ?? multiSets.reduce((a,s)=>a+(s.row_count||s.rows.length),0);
els.perf.textContent = `client ${(ms)} ms | sets ${multiSets.length} | total rows ${total}`;
setStatus('OK');
// Ensure dropdown exists even if earlier start events had an exception
rebuildStreamingDropdown(multiSets, currentSetIndex);
els.jsonOut.textContent = JSON.stringify({ status:'ok', result_sets: multiSets.map((s,i)=>({ index:i, columns:s.columns, rows:s.rows, row_types:s.row_types, row_count: s.row_count||s.rows.length, limited: !!s.limited, search: s.search })) }, null, 2);
} else {
els.perf.textContent = `client ${(ms)} ms | total rows ${evt.total_rows ?? rowCount}`;
setStatus('OK');
const summary = { status:'ok', last_set: { columns, rows, row_types: rowTypesAll, row_count: rowCount }, total_rows: evt.total_rows ?? rowCount };
els.jsonOut.textContent = JSON.stringify(summary,null,2);
}
} else if (evt.event==='error') {
setStatus('Stream error: '+evt.error, 'err');
} else if (evt.event==='end') {
// Fallback completion (single-search or legacy); if multi already handled do nothing extra
const ms = (performance.now()-started).toFixed(2);
els.perf.textContent = `client ${(ms)} ms | rows ${rowCount}${limited?' (limited)':''}`;
setStatus('OK');
// Summarize JSON output
const summary = { status:'ok', columns, rows, row_types: rowTypesAll, row_count: rowCount, limited };
els.jsonOut.textContent = JSON.stringify(summary,null,2);
}
} catch (e) { /* ignore parse errors mid-stream */ }
}
}
while (true) {
const {done, value} = await reader.read();
if (done) break;
buffer += decoder.decode(value, {stream:true});
// Attempt to flush complete events
const lastSep = buffer.lastIndexOf('\n\n');
if (lastSep !== -1) {
const toFlush = buffer.slice(0,lastSep+2); // include sep
flushEvents(toFlush);
buffer = buffer.slice(lastSep+2);
}
}
flushEvents(buffer); // flush remainder
}
els.runBtn.addEventListener('click', runQuery);
els.clearBtn.addEventListener('click', ()=>{
els.tableHead.innerHTML='';
els.tableBody.innerHTML='';
els.jsonOut.textContent='';
els.statusOut.textContent='';
els.perf.textContent='';
// Hide and reset result set selector so old streaming sets cannot be resurrected
els.resultSetSelect.style.display='none';
els.resultSetSelect.innerHTML='';
els.resultSetSelect.onchange = null;
lastResponse = null;
setStatus('Cleared');
});
// Tabs switching
els.tabs.forEach(btn=>{
btn.addEventListener('click', ()=>{
els.tabs.forEach(b=>b.classList.remove('active'));
btn.classList.add('active');
const tab = btn.getAttribute('data-tab');
if (tab==='table') {
els.tableView.style.display='block';
els.jsonView.style.display='none';
els.statusView.style.display='none';
}
else if (tab==='json') {
els.tableView.style.display='none';
els.jsonView.style.display='block';
els.statusView.style.display='none';
}
else if (tab==='status') {
els.tableView.style.display='none';
els.jsonView.style.display='none';
els.statusView.style.display='block';
}
});
});
// Vertical splitter drag logic
let dragging = false; let startY = 0; let startHeight = 0;
function setEditorHeight(px){
const min = 100; const max = window.innerHeight * 0.85;
const clamped = Math.min(Math.max(px,min), max);
els.editorPane.style.flex = '0 0 '+clamped+'px';
}
els.splitter.addEventListener('mousedown', e=>{
dragging = true; startY = e.clientY; startHeight = els.editorPane.getBoundingClientRect().height;
document.body.style.cursor='row-resize';
e.preventDefault();
});
window.addEventListener('mousemove', e=>{
if (!dragging) return;
const dy = e.clientY - startY;
setEditorHeight(startHeight + dy);
});
window.addEventListener('mouseup', ()=>{ if (dragging) { dragging=false; document.body.style.cursor=''; }});
window.addEventListener('resize', ()=>{ /* keep within bounds */ setEditorHeight(els.editorPane.getBoundingClientRect().height); });
function formatCertaintyDisplay(raw) {
if (raw === undefined || raw === null) return raw;
if (raw === '?') return raw;
// Expect forms: -1, -0.xx, 0, 0.xx, 1
if (raw === '1' || raw === '-1') return (raw.startsWith('-')?'-':'') + '100%';
if (raw === '0') return '0%';
const m = raw.match(/^(-?)0\.(\d{1,2})$/);
if (m) {
const sign = m[1];
const digits = m[2];
// strip potential leading zero in percent, keep as integer ("05" -> 5) but preserve up to 2 digits
const pct = parseInt(digits,10); // safe
return sign + pct + '%';
}
return raw; // fallback
}
</script>
</body>
</html>