Repository navigation
Expand file tree
/
Copy patheditor.js
More file actions
1084 lines (1012 loc) · 44.8 KB
/
Copy patheditor.js
File metadata and controls
1084 lines (1012 loc) · 44.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
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
// Editor + UI wiring. Mounts CodeMirror 6 on #editor; recompiles automatically
// (debounced) on every doc change. Open/Load route by extension (.trdl into the
// editor, .toda decompiled and re-built).
import { EditorView, lineNumbers, keymap, Decoration } from "@codemirror/view"
import { StateField, StateEffect } from "@codemirror/state"
import { history, historyKeymap, defaultKeymap } from "@codemirror/commands"
import { bracketMatching, syntaxHighlighting, defaultHighlightStyle } from "@codemirror/language"
import { json } from "@codemirror/lang-json"
import { compile, decompile } from "./bridge.js"
import { list_rigs } from "./rig-manifest.js"
const STARTER = `{"rig":"Example rig from spec"}
{"line":"corkline","twists":6,"shielded":false,"reqsat":"null"}
{"line":"a","twists":5,"shielded":false,"reqsat":"null"}
{"line":"b","twists":2,"shielded":false,"reqsat":"null"}
{"line":"c","twists":3,"shielded":false,"reqsat":"null"}
{"line":"d","twists":5,"shielded":false,"reqsat":"null"}
{"line":"e","twists":3,"shielded":false,"reqsat":"null"}
{"line":"f","twists":7,"shielded":false,"reqsat":"null"}
{"line":"leadline","twists":6,"shielded":false,"reqsat":"null"}
{"hitch":"Pb1","lead":"leadline[0]","meet":"leadline[1]","fastener":"f[1]","hoist":"f[4]"}
{"hitch":"Pb2","lead":"leadline[1]","meet":"leadline[2]","fastener":"f[2]","hoist":"f[5]"}
{"hitch":"Pb3","lead":"leadline[2]","meet":"leadline[3]","fastener":"e[1]","hoist":"e[2]"}
{"hitch":"Pb4","lead":"leadline[3]","meet":"leadline[4]","fastener":"d[0]","hoist":"d[2]"}
{"hitch":"Pb5","lead":"leadline[4]","meet":"leadline[5]","fastener":"d[1]","hoist":"d[3]"}
{"hitch":"F1","lead":"f[0]","meet":"f[3]","fastener":"c[0]","hoist":"c[1]","post":"none"}
{"hitch":"F2","lead":"f[3]","meet":"f[6]","fastener":"b[0]","hoist":"b[1]"}
{"hitch":"C1","lead":"c[0]","meet":"c[2]","fastener":"corkline[1]","hoist":"corkline[3]"}
{"hitch":"D1","lead":"d[0]","meet":"d[4]","fastener":"a[1]","hoist":"a[3]"}
{"hitch":"B1","lead":"b[0]","meet":"b[1]","fastener":"corkline[0]","hoist":"corkline[4]"}
{"hitch":"E1","lead":"e[0]","meet":"e[2]","fastener":"a[0]","hoist":"a[2]"}
{"hitch":"A1","lead":"a[0]","meet":"a[4]","fastener":"corkline[2]","hoist":"corkline[5]"}`
let last_built_bytes = null
let line_hashes = [] // entityIdx → [hash, ...]; from /compile
// The TRDL text as last loaded (STARTER, a decompiled .toda, a canonical
// .trdl, an opened file, …). The doc is "edited" iff it differs from this.
// set_doc updates it on every load path; the editor never writes it itself.
let loaded_baseline = STARTER
// --- highlight machinery -----------------------------------------------------
// Two independent decoration fields so a transient hover doesn't replace the
// persistent click-select. CodeMirror layers both into the same DOM line.
function decoration_field(set_effect, css_class) {
return StateField.define({
create() { return Decoration.none },
update(deco, tr) {
deco = deco.map(tr.changes)
for (let e of tr.effects) if (e.is(set_effect)) {
let lns = [...e.value].sort((a, b) => a - b)
let ranges = []
for (let n of lns) {
if (n >= 1 && n <= tr.state.doc.lines) {
let line = tr.state.doc.line(n)
ranges.push(Decoration.line({ class: css_class }).range(line.from))
}
}
deco = Decoration.set(ranges)
}
return deco
},
provide: f => EditorView.decorations.from(f),
})
}
const set_hover = StateEffect.define() // payload: Set<lineNumber>
const set_select = StateEffect.define() // payload: Set<lineNumber>
const set_issue = StateEffect.define() // payload: Set<lineNumber>
const hover_field = decoration_field(set_hover, 'cm-hl-hover')
const select_field = decoration_field(set_select, 'cm-hl-select')
const issue_field = decoration_field(set_issue, 'cm-hl-issue')
const cursor_broadcast = EditorView.updateListener.of(update => {
if (update.docChanged) { schedule_build(); refresh_edited_indicator() }
// Broadcast select ONLY on explicit cursor moves (click, arrow keys) — not
// on typing-induced moves. Typing both moves the cursor and changes the
// doc, and re-broadcasting on every keystroke would clobber whatever the
// user click-selected in viz/hex with the typed-in cursor's line hashes.
if (!update.selectionSet || update.docChanged) return
let hashes = current_line_hashes()
document.dispatchEvent(new CustomEvent('workshop:select', {
detail: { hashes, source: 'editor' },
}))
})
let build_timer = null
let build_seq = 0
function schedule_build() {
if (build_timer) clearTimeout(build_timer)
build_timer = setTimeout(() => { build_timer = null; build() }, 300)
}
const view = new EditorView({
doc: STARTER,
parent: document.getElementById('editor'),
extensions: [
lineNumbers(),
history(),
bracketMatching(),
syntaxHighlighting(defaultHighlightStyle),
keymap.of([...defaultKeymap, ...historyKeymap]),
json(),
hover_field,
select_field,
issue_field,
cursor_broadcast,
],
})
function current_line_hashes() {
let cur = view.state.doc.lineAt(view.state.selection.main.head)
if (cur.text.trim() === '') return []
let i = 0
for (let n = 1; n < cur.number; n++) {
if (view.state.doc.line(n).text.trim() !== '') i++
}
return line_hashes[i] || []
}
function lines_for(target) {
let lines = new Set()
if (!target.size) return lines
let n = 0
let doc = view.state.doc
for (let i = 1; i <= doc.lines; i++) {
if (doc.line(i).text.trim() === '') continue
let hs = line_hashes[n] || []
if (hs.some(h => target.has(h))) lines.add(i)
n++
}
return lines
}
document.addEventListener('workshop:hover', e => {
let target = new Set(e.detail.hashes || [])
view.dispatch({ effects: set_hover.of(lines_for(target)) })
})
document.addEventListener('workshop:select', e => {
if (e.detail.source === 'editor') return
let target = new Set(e.detail.hashes || [])
view.dispatch({ effects: set_select.of(lines_for(target)) })
})
// Highlight TRDL lines whose entity emits any twist the rust checker
// flagged. Same lines_for() lookup the hover/select machinery already
// uses — issue is just a separate decoration layer so it can coexist
// with click-selection and hover. Cache the last payload so build()
// can re-apply after line_hashes lands; rust fires its issue event
// during the initial render (synchronous), which happens ~300ms
// before the debounced auto-build populates line_hashes.
let _last_issue_hashes = new Set()
document.addEventListener('workshop:issue', e => {
let issues = e.detail?.issues || []
// Editor only highlights non-green failures — green leaves are
// structural confirmations rust gives along the way; surfacing
// them in the TRDL pane would be noise.
_last_issue_hashes = new Set(
issues.filter(i => i.colour !== 'green').map(i => i.hash)
)
view.dispatch({ effects: set_issue.of(lines_for(_last_issue_hashes)) })
})
// Hover dispatch: mousemove over the editor → broadcast that line's hashes.
// Mirrors the hex pane's hover semantics so cross-pane sync works the same
// way no matter which pane the cursor is in.
function hashes_at_coords(x, y) {
let pos = view.posAtCoords({x, y}, false)
if (pos == null) return []
let line = view.state.doc.lineAt(pos)
if (line.text.trim() === '') return []
let n = 0
for (let i = 1; i < line.number; i++) {
if (view.state.doc.line(i).text.trim() !== '') n++
}
return line_hashes[n] || []
}
view.dom.addEventListener('mousemove', e => {
let hashes = hashes_at_coords(e.clientX, e.clientY)
document.dispatchEvent(new CustomEvent('workshop:hover', {
detail: { hashes, source: 'editor' },
}))
})
view.dom.addEventListener('mouseleave', () => {
document.dispatchEvent(new CustomEvent('workshop:hover', {
detail: { hashes: [], source: 'editor' },
}))
})
function get_doc() { return view.state.doc.toString() }
function set_doc(text) {
// Record the baseline before dispatching so the docChanged listener that
// fires synchronously during dispatch sees doc === baseline (not edited).
loaded_baseline = text
view.dispatch({
changes: { from: 0, to: view.state.doc.length, insert: text },
})
refresh_edited_indicator()
}
// "edited" = the doc no longer matches what we loaded. Drives the marker in
// the editor panel header and gates the rig-switch discard prompt.
function refresh_edited_indicator() {
let edited = get_doc() !== loaded_baseline
if (window.workshop) window.workshop.edited = edited
let marker = document.getElementById('editor-edited')
if (marker) marker.hidden = !edited
}
function escape_html(s) {
return s.replace(/[&<>"]/g, c =>
({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]))
}
// Workshop-level status (compile / load failures, idle). When the panel
// is already showing per-checker rows (rig-check-list mode), the status
// is rendered as a banner above them rather than replacing them — so an
// edit-time compile error doesn't wipe out the prior pass's results,
// which is the user-visible "flash". When the panel hasn't rendered any
// per-checker rows yet (initial load, fresh editor) we fall back to the
// original single full-width row.
// Update the rig-check panel's section header. Called from each load path
// so the user can see which example is currently being checked. Truncated
// to keep the header from wrapping; full label available on hover.
function set_loaded_label(label) {
let titleEl = document.querySelector('#rig-check-section .section-title')
if (!titleEl) return
if (!label) { titleEl.textContent = 'Rig check'; titleEl.removeAttribute('title'); return }
const MAX = 30
let shown = label.length > MAX ? label.slice(0, MAX - 1) + '…' : label
titleEl.textContent = `Rig check for ${shown}`
titleEl.title = label
}
function set_rigcheck(klass, label, msg) {
let rc = document.getElementById('rigcheck')
if (rc.classList.contains('rig-check-list')) {
let existing = rc.querySelector('[data-section="workshop-status"]')
if (existing) existing.remove()
// Insert at the end so the workshop status always sits visually
// *after* the per-checker rows, regardless of whether the initial
// pass has finished rendering. The user reads the rig-check results
// first; the compile/render error is secondary context below them.
rc.insertAdjacentHTML('beforeend',
`<div class="rig-check ${klass}" data-section="workshop-status">` +
`<span class="badge">${label}</span>` +
`<div>${escape_html(msg)}</div></div>`)
return
}
rc.className = 'rig-check ' + klass
rc.innerHTML = `<span class="badge">${label}</span><div>${escape_html(msg)}</div>`
}
// Drop the previous rig's checker rows when switching fixtures. They describe
// different bytes, and set_rigcheck appends the workshop status *below* them —
// so a fixture that fails to compile would otherwise show the last rig's
// verdicts ("OK rust · verified") sitting above its own compile error.
function reset_rigcheck() {
let rc = document.getElementById('rigcheck')
if (!rc) return
rc.className = 'rig-check warn'
rc.innerHTML = '<span class="badge">CHECK</span><div>building…</div>'
}
async function build() {
let my = ++build_seq
let bytes, lineHashes, corkline
try {
({ bytes, lineHashes, corkline } = await compile(get_doc()))
} catch (e) {
if (my !== build_seq) return
set_rigcheck('bad', 'TRDL COMPILE ERROR', e.message)
console.error(e)
return
}
if (my !== build_seq) return // stale: a newer build is queued
last_built_bytes = bytes
line_hashes = lineHashes
// line_hashes is what lines_for() consults to translate twist hashes
// back to editor line numbers. If a workshop:issue event came in
// before the build finished (rust fires its event during the synch
// viz render, ~300ms ahead of this debounced compile), the lines_for
// lookup found nothing and the editor stayed unpainted. Now that
// line_hashes is current, re-apply.
if (_last_issue_hashes.size) {
view.dispatch({ effects: set_issue.of(lines_for(_last_issue_hashes)) })
}
// .toda load lifecycle. A .toda load renders the loaded (lossless) bytes
// into viz/hex and pins them as initial_toda_load; the editor shows the TRDL
// we put there (a decompilation, or — Case B — the canonical sibling .trdl),
// which equals loaded_baseline until the user edits.
//
// * Unedited (get_doc() === loaded_baseline): keep the loaded bytes on
// screen — re-rendering the recompiled bytes would replace them with a
// lossy reconstruction (v1 decompile regenerates random shields, etc.).
// Instead surface the decompile→recompile round-trip in the rig-check
// panel only, without touching viz/hex.
// * First edit (doc now differs): the editor is the source of truth. Drop
// the baseline so the panel stops comparing against the loaded .toda;
// viz/hex/rig-check flip to the recompiled bytes from here on.
let init = window.workshop?.initial_toda_load
if (init && get_doc() === loaded_baseline) {
window.workshop.compare_roundtrip?.(bytes, corkline)
return
}
if (init) window.workshop.initial_toda_load = null
// Don't overwrite a sidecar-supplied corkline with compile's idea —
// sidecar is the authoritative source. Auto-default (top-left twist,
// applied by app.js's notify_rendered) is also preserved across
// rebuilds, since the same TRDL keeps producing the same top-left.
if (corkline && window.workshop.corkline_source !== 'sidecar') {
window.workshop.corkline = corkline
window.workshop.corkline_source = 'compile'
}
try {
window.workshop.render(bytes)
} catch (e) {
set_rigcheck('bad', 'RENDER ERROR', e.message)
console.error(e)
}
}
// Load .toda bytes. `editor_trdl`, when given, is a canonical sibling .trdl
// (Case B): we put it in the editor instead of decompiling, so the round-trip
// compares the loaded .toda against compile(canonical .trdl). Without it
// (Case A — URL/file import, or a canned .toda with no .trdl) we decompile.
async function load_bytes(buf, editor_trdl = null) {
// Fail-fast: detect abjects and oversized files BEFORE running decompile,
// the visualizer, or the hex dump. The workshop is for single test rigs;
// abjects and big files belong in abject-workshop (see abject-workshop.md).
// Even a multi-MB abject should bail in milliseconds — Atoms.fromBytes plus
// one Line walk is the only work done here.
let bytes = new Uint8Array(buf)
let check = window.workshop.check_supported(bytes)
if (check.bailReason) {
window.workshop.initial_toda_load = null
window.workshop.render_unsupported(check.bailReason)
return
}
// set_doc fires the auto-build via the updateListener; render the loaded
// bytes immediately for instant (lossless) feedback while the rebuild runs.
// Pin this as the "initial toda load" so build() can keep the loaded bytes
// on screen and surface the decompile→recompile round-trip (compare_roundtrip)
// rather than overwriting the first-pass rig-check results.
try {
// window.workshop.corkline was just set by load_rig_meta (when the
// sidecar carries a corkline hash). Pass it as a hint to decompile
// so the corkline-line identification doesn't fall back to the
// heuristic on rigs with non-canonical corkline topologies.
let text = editor_trdl != null
? editor_trdl
: await decompile(buf, window.workshop?.corkline || null)
window.workshop.initial_toda_load = {
bytes,
rig_id: active_rig,
results: new Map(), // checker_id → {state, badge, detail}
workshop_check: check, // reuse fail-fast result; show_abject_info caches off this
}
set_doc(text) // sets loaded_baseline — build()'s "edited?" check
last_built_bytes = buf
window.workshop.render(buf)
} catch (e) {
window.workshop.initial_toda_load = null
set_rigcheck('bad', 'DECOMPILE ERROR', e.message)
console.error(e)
}
}
function deselect_rig() {
active_rig = null
render_rigs_list()
clear_rig_meta()
window.workshop.initial_toda_load = null
// Drop any sidecar-derived corkline from the previously-loaded rig.
// For upload/URL loads (no sidecar), app.js's notify_rendered will
// default it to the top-leftmost twist after the viz lays out.
window.workshop.corkline = null
window.workshop.corkline_source = null
}
async function load_file(file) {
deselect_rig()
set_loaded_label(file.name)
if (file.name.toLowerCase().endsWith('.trdl')) {
set_doc(await file.text()) // auto-build kicks in
} else {
await load_bytes(await file.arrayBuffer())
}
}
// base64url ⇄ utf-8 text. Pads/unpads on decode; replaces +//= on encode so
// the result is hash-safe (no URL-escaping needed in #trdl=...).
function b64url_encode(text) {
let bytes = new TextEncoder().encode(text)
let bin = ''
for (let b of bytes) bin += String.fromCharCode(b)
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
}
function b64url_decode(s) {
let b64 = s.replace(/-/g, '+').replace(/_/g, '/')
while (b64.length % 4) b64 += '='
let bin = atob(b64)
let bytes = new Uint8Array(bin.length)
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
return new TextDecoder().decode(bytes)
}
// Inline TRDL handoff (#trdl=<base64url>): drop the active file selection
// and push the decoded text straight into the editor. set_doc triggers the
// debounced auto-build, which fires the rig-check pipeline as usual.
function load_inline_trdl(text, label) {
deselect_rig()
set_loaded_label(label || 'shared rig')
set_doc(text)
}
// sessionStorage handoff (#blob=<key>): single-use — we consume and delete
// the entry so a page reload doesn't replay stale content.
function load_from_blob(key) {
let text = sessionStorage.getItem(key)
if (text == null) throw new Error(`blob "${key}" not found in sessionStorage`)
sessionStorage.removeItem(key)
load_inline_trdl(text, 'shared rig')
}
// Parse location.hash into one of three handoff forms. Returns null when
// the hash is empty so callers can fall back to a default rig.
function route_hash() {
let raw = location.hash.slice(1)
if (!raw) return null
let eq = raw.indexOf('=')
if (eq > 0) {
let key = raw.slice(0, eq), val = raw.slice(eq + 1)
if (key === 'trdl') return { kind: 'trdl', value: val }
if (key === 'blob') return { kind: 'blob', value: decodeURIComponent(val) }
}
return { kind: 'path', value: decodeURIComponent(raw) }
}
async function load_from_hash(route) {
if (route.kind === 'path') return load_rig(route.value)
if (route.kind === 'trdl') return load_inline_trdl(b64url_decode(route.value), 'shared rig')
if (route.kind === 'blob') return load_from_blob(route.value)
}
async function load_url(url) {
deselect_rig()
set_loaded_label(url.split('/').pop() || url)
try {
let res = await fetch(url)
if (!res.ok) throw new Error(`HTTP ${res.status}`)
if (url.toLowerCase().endsWith('.trdl')) {
set_doc(await res.text())
} else {
await load_bytes(await res.arrayBuffer())
}
} catch (e) {
set_rigcheck('bad', 'LOAD ERROR', e.message)
}
}
function download(data, name, mime) {
let blob = new Blob([data], { type: mime })
let a = document.createElement('a')
a.href = URL.createObjectURL(blob)
a.download = name
a.click()
URL.revokeObjectURL(a.href)
}
function save_trdl() {
download(get_doc(), 'rig.trdl', 'application/json')
}
function save_toda() {
if (!last_built_bytes) {
set_rigcheck('warn', 'NOPE', 'build first')
return
}
download(last_built_bytes, 'rig.toda', 'application/octet-stream')
}
document.getElementById('btn-save-trdl').addEventListener('click', save_trdl)
document.getElementById('btn-save-toda').addEventListener('click', save_toda)
document.getElementById('btn-open').addEventListener('click',
() => document.getElementById('file-input').click())
document.getElementById('file-input').addEventListener('change', e => {
let f = e.target.files[0]
if (f) load_file(f)
})
// URL field: load on Enter or on blur-after-edit. No separate Load button.
function try_load_url() {
let url = document.getElementById('url-input').value.trim()
if (url) load_url(url)
}
document.getElementById('url-input').addEventListener('change', try_load_url)
document.getElementById('url-input').addEventListener('keydown', e => {
if (e.key === 'Enter') { e.preventDefault(); try_load_url() }
})
// Share URL: encode the current editor doc as #trdl=<base64url> and copy
// to the clipboard. Always inline — the URL captures exactly what's on
// screen now, edits and all.
document.getElementById('btn-share').addEventListener('click', async () => {
let btn = document.getElementById('btn-share')
let lbl = btn.querySelector('.btn-label')
let orig = lbl.textContent
try {
let text = get_doc()
let url = `${location.origin}${location.pathname}#trdl=${b64url_encode(text)}`
await navigator.clipboard.writeText(url)
lbl.textContent = 'Copied!'
} catch (e) {
console.warn('share failed', e)
lbl.textContent = 'Copy failed'
}
setTimeout(() => { lbl.textContent = orig }, 1500)
})
// --- examples panel ---------------------------------------------------------
// Each entry is a path relative to the workshop root. The loader fetches
// the sibling .json sidecar (same path, .toda → .json or .trdl → .json)
// for moniker / corkline / canonical colour. Dot colours render after the
// list is built, via update_dot_colours() fanning out to all sidecars.
//
// The list itself is discovered at startup by list_rigs() walking the
// static server's directory indexes under todatests/ — see rig-manifest.js.
// Adding a fixture to todatests/rigging/ or todatests/reqsat/ shows up
// on next page load without editing this file.
let RIGS = []
function rig_label(path) {
let basename = path.replace(/^.*\//, '').replace(/\.(trdl|toda)$/, '')
return basename.replace(/^(\d+a?)-/, '$1 · ')
}
let active_rig = null
// Cache of expectation colour by rig path, populated by update_dot_colours().
// render_rigs_list reads this on each call; cells whose expectation hasn't
// resolved yet render with an empty dot, which fills in once the fetch
// lands and update_dot_colours triggers a re-render via patch_dot.
const sidecar_colour = new Map()
// Paths whose expectation lookup already failed, so the pool doesn't retry
// them on every re-render.
const colour_missing = new Set()
// --- rig tree ---------------------------------------------------------------
// v1-tests turned the sidebar from ~175 flat rows into ~6.8k, so the list is
// a collapsible tree over the fixtures' own directory hierarchy. Only the
// expanded nodes are rendered — collapsed subtrees emit no DOM at all, which
// is what keeps a 6.6k-fixture corpus cheap to draw and keeps the arrow-key
// walk (which reads .rig-item off the DOM) restricted to visible rows.
let rig_tree = { dirs: new Map(), files: [], count: 0 }
// rigging/ and reqsat/ open by default so the pre-v1-tests workflow is
// unchanged; v1-tests stays shut until asked for.
let expanded = new Set(['todatests/rigging', 'todatests/reqsat'])
let rig_filter = ''
// Cap on rows drawn in one pass. Only reachable via the filter box (the
// largest single directory is 256 fixtures), and reported when it bites so
// a truncated list never reads as a complete one.
const MAX_ROWS = 400
function build_tree(paths) {
let root = { dirs: new Map(), files: [], count: 0, path: '' }
for (let p of paths) {
let segs = p.split('/')
segs.pop() // filename; dirs are the path
let node = root
node.count++
for (let s of segs) {
if (!node.dirs.has(s)) {
node.dirs.set(s, { dirs: new Map(), files: [], count: 0,
path: node.path ? `${node.path}/${s}` : s, name: s })
}
node = node.dirs.get(s)
node.count++
}
node.files.push({ path: p, label: rig_label(p) })
}
// Descend through single-child roots ('todatests') so the top level is the
// fixture families themselves — rigging, reqsat, v1-tests.
while (root.dirs.size === 1 && root.files.length === 0) {
root = [...root.dirs.values()][0]
}
return root
}
// Open every ancestor directory of a rig so it's visible in the tree.
function reveal(path) {
let segs = path.split('/')
segs.pop()
let acc = ''
for (let s of segs) {
acc = acc ? `${acc}/${s}` : s
expanded.add(acc)
}
}
function matches(path) {
return path.toLowerCase().includes(rig_filter)
}
function render_rigs_list() {
let host = document.getElementById('rigs-list')
if (!host) return
let rows = [], shown = 0, total = 0
// A filter forces every matching subtree open and hides the rest; without
// one, `expanded` drives what descends.
function walk_node(node, depth) {
for (let dir of node.dirs.values()) {
let hits = rig_filter ? count_matches(dir) : dir.count
if (rig_filter && hits === 0) continue
let open = rig_filter ? true : expanded.has(dir.path)
if (shown < MAX_ROWS) {
rows.push(
`<div class="rig-dir${open ? ' open' : ''}" data-dir="${escape_html(dir.path)}" ` +
`style="padding-left:${8 + depth * 12}px">` +
`<span class="rig-chevron">${open ? '▾' : '▸'}</span>` +
`<span class="rig-dir-name">${escape_html(dir.name)}</span>` +
`<span class="rig-count">${hits}</span></div>`)
shown++
}
if (open) walk_node(dir, depth + 1)
}
for (let f of node.files) {
if (rig_filter && !matches(f.path)) continue
total++
if (shown >= MAX_ROWS) continue
let active = f.path === active_rig ? ' active' : ''
let colour = sidecar_colour.get(f.path) || ''
rows.push(
`<div class="rig-item${active}" data-file="${escape_html(f.path)}" ` +
`style="padding-left:${8 + depth * 12}px">` +
`<span class="rig-dot ${colour}"></span>${escape_html(f.label)}</div>`)
shown++
}
}
function count_matches(node) {
let n = 0
for (let d of node.dirs.values()) n += count_matches(d)
for (let f of node.files) if (matches(f.path)) n++
return n
}
walk_node(rig_tree, 0)
if (shown >= MAX_ROWS) {
rows.push(`<div class="rig-truncated">showing first ${MAX_ROWS} rows` +
(rig_filter ? ` of ${total} matches` : '') + ` — narrow the filter</div>`)
} else if (rig_filter && total === 0) {
rows.push(`<div class="rig-truncated">no fixtures match “${escape_html(rig_filter)}”</div>`)
}
host.innerHTML = rows.join('')
update_dot_colours()
}
// Patch the dot for a single rig in-place — cheaper than re-rendering
// the whole list as each of the 129 sidecar fetches resolves.
function patch_dot(path, colour) {
let host = document.getElementById('rigs-list')
if (!host) return
let item = host.querySelector(`.rig-item[data-file="${CSS.escape(path)}"] .rig-dot`)
if (!item) return
item.classList.remove('green', 'yellow', 'red')
if (colour) item.classList.add(colour)
}
// v1-tests fixtures carry a comment header AND (since todatests 88e2b2f) a
// generated .json sidecar. The sidecar's colour is authoritative: it applies
// the invariance-principle reclassification that moved ~2.9k fixtures from
// red to green, which the headers predate and no longer reflect. The header
// still supplies the only statement of Structure / Property / Condition, so
// both are read and merged.
const HEADER_META_PREFIX = 'todatests/v1-tests/'
function uses_header_meta(path) { return path.startsWith(HEADER_META_PREFIX) }
// Parse the header block every v1-tests fixture carries:
// // Structure: Basic Body
// // Property: carg must be trie or null
// // Condition: carg.shape = 0x00
// // Expected evaluation: YELLOW (nospec)
// Colours are normalised onto the sidecar's green/yellow/red vocabulary:
// VALID is used interchangeably with GREEN, and a handful of files join the
// words with underscores (e.g. RED_(ed25519-reqsat_INVALID)).
export function parse_trdl_header(src) {
let field = k => {
let m = src.match(new RegExp(`^//\\s*${k}:\\s*(.+)$`, 'm'))
return m ? m[1].trim() : null
}
let expected = field('Expected evaluation')
let colour = null
if (expected) {
let w = expected.replace(/_/g, ' ').match(/\b(GREEN|VALID|YELLOW|RED)\b/)
if (w) colour = w[1] === 'VALID' ? 'green' : w[1].toLowerCase()
}
return { structure: field('Structure'), property: field('Property'),
condition: field('Condition'), note: field('Note'),
expected, colour }
}
// Load one rig's expectation metadata, from whichever source that family
// uses. Shape matches the .json sidecar so callers stay uniform.
async function fetch_rig_meta(path) {
let json_url = path.replace(/\.(trdl|toda)$/, '.json')
let sidecar = null
try {
let res = await fetch(json_url)
if (res.ok) sidecar = await res.json()
} catch {}
if (uses_header_meta(path)) {
let res = await fetch(path)
if (!res.ok) throw new Error(`HTTP ${res.status}`)
let h = parse_trdl_header(await res.text())
if (!sidecar) return { ...h, moniker: h.condition, corkline: null, source: path }
// Sidecar colour wins; header contributes the spec coordinates. When the
// two disagree the header's original verdict is surfaced as `superseded`
// rather than dropped — that reclassification is the interesting part.
let superseded = h.colour && sidecar.colour && h.colour !== sidecar.colour
? h.expected : null
return { ...h, ...sidecar,
moniker: sidecar.moniker || h.condition,
superseded, source: json_url }
}
if (!sidecar) throw new Error(`no sidecar for ${path}`)
return { ...sidecar, source: json_url }
}
// Fill in dots for the rows currently on screen. Collapsed subtrees are
// never fetched, so opening the tree pays only for what it reveals — the
// whole-corpus fan-out this replaced would have been 6.8k requests at boot.
// Failures are recorded so a re-render doesn't retry them; a blank dot
// surfaces the gap without breaking the rest of the list.
async function update_dot_colours() {
let host = document.getElementById('rigs-list')
if (!host) return
let want = [...host.querySelectorAll('.rig-item')]
.map(el => el.dataset.file)
.filter(p => !sidecar_colour.has(p) && !colour_missing.has(p))
if (!want.length) return
// Bounded pool: each worker pulls the next path until drained. next++ is
// atomic between await points, so no two workers grab the same rig.
const CONCURRENCY = 12
let next = 0
async function worker() {
while (next < want.length) {
let path = want[next++]
try {
let m = await fetch_rig_meta(path)
if (m.colour) {
sidecar_colour.set(path, m.colour)
patch_dot(path, m.colour)
} else {
colour_missing.add(path)
}
} catch { colour_missing.add(path) }
}
}
await Promise.all(
Array.from({ length: Math.min(CONCURRENCY, want.length) }, worker))
}
function truncate_hash(h, head=10, tail=8) {
if (!h || h.length <= head + tail + 1) return h
return h.slice(0, head) + '…' + h.slice(-tail)
}
function clear_rig_meta() {
let section = document.getElementById('rig-meta-section')
if (section) section.hidden = true
}
async function load_rig_meta(rig_url, explicit_json_url) {
let section = document.getElementById('rig-meta-section')
let header = document.getElementById('rig-meta-filename')
let host = document.getElementById('rig-meta')
if (!section || !host) return
if (!explicit_json_url && !rig_url) { section.hidden = true; return }
try {
// Explicit sidecar (file / URL loads) wins; otherwise ask the family's
// own metadata source — sidecar for rigging & reqsat, comment header
// for v1-tests.
let m, json_url
if (explicit_json_url) {
let res = await fetch(explicit_json_url)
if (!res.ok) throw new Error(`HTTP ${res.status}`)
m = await res.json()
json_url = explicit_json_url
} else {
m = await fetch_rig_meta(rig_url)
json_url = m.source
}
let parts = []
if (m.moniker) parts.push(`<span class="rm-moniker">${escape_html(m.moniker)}</span>`)
if (m.colour) parts.push(`<span class="rm-colour ${escape_html(m.colour)}">${escape_html(m.colour)}</span>`)
// v1-tests header fields — the spec condition this fixture probes.
// `superseded` means the sidecar reclassified the header's verdict; show
// what it used to be, since that is the substantive change.
if (m.superseded) {
parts.push(`<span class="rm-superseded" title="reclassified by the .json sidecar">` +
`was ${escape_html(m.superseded)}</span>`)
} else if (m.expected && m.expected.replace(/_/g, ' ').trim() !== (m.colour || '').toUpperCase()) {
parts.push(`<span class="rm-expected">${escape_html(m.expected)}</span>`)
}
if (m.structure) parts.push(`<span class="rm-structure">${escape_html(m.structure)}</span>`)
if (m.property) parts.push(`<span class="rm-property">${escape_html(m.property)}</span>`)
if (m.note) parts.push(`<span class="rm-notes">${escape_html(m.note)}</span>`)
if (m.corkline) parts.push(`<span class="rm-cork" title="${escape_html(m.corkline)}">cork: ${escape_html(truncate_hash(m.corkline))}</span>`)
// `issue` historically was a flat string ('INVALID', 'MISSING'); newer
// sidecars use a structured tree. Render either — JSON-stringify the
// tree form so it's at least visible in the header rather than dropped.
if (m.issue != null) {
let s = typeof m.issue === 'string' ? m.issue : JSON.stringify(m.issue)
parts.push(`<span class="rm-issue">issue: ${escape_html(s)}</span>`)
}
if (m.invariant) {
// v1-tests invariant blocks are objects with name / spec / quote, where
// `quote` runs to a paragraph. Show the name and keep the spec citation
// on hover; stringifying the whole object floods the panel.
let s = typeof m.invariant === 'string' ? m.invariant
: m.invariant.name || JSON.stringify(m.invariant)
let cite = typeof m.invariant === 'object' && m.invariant.spec
? ` title="${escape_html(m.invariant.spec)}"` : ''
parts.push(`<span class="rm-invariant"${cite}>invariant: ${escape_html(s)}</span>`)
}
if (m.notes != null) {
let s = Array.isArray(m.notes) ? m.notes.join(' • ')
: typeof m.notes === 'string' ? m.notes
: JSON.stringify(m.notes)
parts.push(`<span class="rm-notes">notes: ${escape_html(s)}</span>`)
}
// Update only the title span, not the whole H4 — the H4 also contains
// the chevron used by the collapsible toggle.
let title = header?.querySelector('.section-title')
if (title) title.textContent = json_url.replace(/^.*\//, '')
// Mirror the rig's declared colour into the h4 status pill so it stays
// visible when the section is collapsed.
let status = header?.querySelector('.section-status')
if (status) {
status.classList.remove('green', 'yellow', 'red')
if (m.colour) {
status.classList.add(m.colour)
status.textContent = m.colour
} else {
status.textContent = ''
}
}
host.innerHTML = parts.join('')
section.hidden = parts.length === 0
// Use the JSON's canonical corkline when available — for .toda loads
// (todatests/rigging) the immediate render runs before the decompile
// → recompile cycle finishes, and without this the rig-check panel
// shows "No corkline available". For .trdl loads the auto-build also
// sets workshop.corkline, but they should agree round-trip.
if (m.corkline) {
window.workshop.corkline = m.corkline
window.workshop.corkline_source = 'sidecar'
}
} catch {
section.hidden = true
}
}
async function load_rig(path) {
active_rig = path
reveal(path)
render_rigs_list()
set_loaded_label(rig_label(path))
// Reflect the current rig in the URL hash so the page is shareable /
// bookmarkable. replaceState (not pushState) keeps the back button from
// accumulating an entry per arrow-key step through the list, and does
// NOT fire hashchange — only manual URL edits / browser nav do, which
// are handled below.
// window.history is qualified because the local `history` symbol is
// shadowed by CodeMirror's history extension imported at the top of
// this file. Without the prefix, `history.replaceState` resolves to a
// non-existent property of the extension function.
try {
let want = '#' + path
if (location.hash !== want) window.history.replaceState(null, '', want)
} catch {}
// Reset the corkline before loading the new rig. load_rig_meta only *sets*
// it when the sidecar carries one, so without this a rig whose sidecar has
// `corkline: null` would inherit the previously-loaded rig's corkline —
// making its rig-check result depend on navigation history. After the reset,
// such a rig falls through to notify_rendered's auto-default (its own
// top-left twist), which is deterministic. (deselect_rig does this for
// file/URL loads; load_rig needs it too.)
window.workshop.corkline = null
window.workshop.corkline_source = null
reset_rigcheck()
// Await the meta fetch so that workshop.corkline is set from the canonical
// JSON before load_bytes triggers an immediate render — otherwise the
// .toda rig-check fires with no corkline yet.
await load_rig_meta(path)
// Stale .toda baseline must be cleared when switching rigs. load_bytes
// resets it for the new .toda load; .trdl loads have no baseline.
window.workshop.initial_toda_load = null
try {
let res = await fetch(path)
if (!res.ok) throw new Error(`HTTP ${res.status}`)
if (path.toLowerCase().endsWith('.trdl')) {
set_doc(await res.text()) // auto-build picks it up
} else {
// .toda. If a canonical sibling .trdl exists (Case B), show it in the
// editor and round-trip against compile(it); otherwise decompile (A).
let buf = await res.arrayBuffer()
await load_bytes(buf, await fetch_sibling_trdl(path))
}
} catch (err) {
set_rigcheck('bad', 'LOAD ERROR', `${path}: ${err.message}`)
}
}
// Fetch the canonical sibling .trdl for a canned .toda path, or null if there
// isn't one. Same basename, .toda → .trdl (mirrors the .json sidecar lookup).
// Consult the manifest rather than blind-probing — a missing sibling would
// otherwise log a 404 to the console on every Case A load. RIGS lists both
// .toda and .trdl under the sidebar roots. (On the very first load the walk
// may not have finished; a Case B rig opened via initial URL hash then
// degrades to Case A — decompiled rather than canonical TRDL — still a correct
// rig, just not the hand-authored text.)
async function fetch_sibling_trdl(toda_path) {
let trdl_url = toda_path.replace(/\.toda$/i, '.trdl')
if (trdl_url === toda_path || !RIGS.includes(trdl_url)) return null
try {
let res = await fetch(trdl_url)
return res.ok ? await res.text() : null
} catch { return null }
}
let rigs_list_el = document.getElementById('rigs-list')
if (rigs_list_el) rigs_list_el.tabIndex = 0 // focusable so it can take key events
// Loading a pre-built rig replaces the editor contents. If the user has
// unsaved edits, confirm before discarding them. Guards the rigs list only —
// Open / Load-URL are deliberate explicit actions.
function confirm_discard_edits() {
if (!window.workshop?.edited) return true
return window.confirm(
'You have unsaved edits to this rig. Loading another will discard them. Continue?')
}
rigs_list_el?.addEventListener('click', async e => {
let dir = e.target.closest('.rig-dir')
if (dir) {
// Toggling under an active filter would fight the filter's forced-open
// state, so collapse is a no-op there.
if (rig_filter) return
let key = dir.dataset.dir
if (expanded.has(key)) expanded.delete(key)
else expanded.add(key)
render_rigs_list()
return
}
let item = e.target.closest('.rig-item')
if (!item) return
if (!confirm_discard_edits()) return
load_rig(item.dataset.file)
})
let rigs_filter_el = document.getElementById('rigs-filter')
rigs_filter_el?.addEventListener('input', () => {
rig_filter = rigs_filter_el.value.trim().toLowerCase()
render_rigs_list()
})
rigs_list_el?.addEventListener('keydown', e => {
if (!['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(e.key)) return
e.preventDefault()
let items = [...rigs_list_el.querySelectorAll('.rig-item')]
if (!items.length) return
let cur = items.findIndex(i => i.dataset.file === active_rig)
let next
if (e.key === 'ArrowDown') next = cur < 0 ? 0 : Math.min(items.length - 1, cur + 1)
else if (e.key === 'ArrowUp') next = cur < 0 ? items.length - 1 : Math.max(0, cur - 1)
else if (e.key === 'Home') next = 0
else if (e.key === 'End') next = items.length - 1
let path = items[next].dataset.file
if (!confirm_discard_edits()) return
load_rig(path)
// load_rig synchronously re-renders the list (active class moves), so
// the previous DOM nodes are detached. Scroll the *new* active item
// into view, but only within the rigs-list — using scrollIntoView would
// also scroll the surrounding panel and was jolting the page.
let live = rigs_list_el.querySelector(`.rig-item[data-file="${CSS.escape(path)}"]`)
if (live) {
let list_rect = rigs_list_el.getBoundingClientRect()
let item_rect = live.getBoundingClientRect()
if (item_rect.top < list_rect.top) {
rigs_list_el.scrollTop += item_rect.top - list_rect.top