forked from playproject-ui/ui-components
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbundle.js
More file actions
11191 lines (9935 loc) · 349 KB
/
bundle.js
File metadata and controls
11191 lines (9935 loc) · 349 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
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
},{}],2:[function(require,module,exports){
(function (__filename){(function (){
const STATE = require('STATE')
const statedb = STATE(__filename)
const { get } = statedb(fallback_module)
module.exports = graph_explorer
async function graph_explorer (opts, protocol) {
/******************************************************************************
COMPONENT INITIALIZATION
- This sets up the initial state, variables, and the basic DOM structure.
- It also initializes the IntersectionObserver for virtual scrolling and
sets up the watcher for state changes.
******************************************************************************/
const { sdb } = await get(opts.sid)
const { drive } = sdb
let vertical_scroll_value = 0
let horizontal_scroll_value = 0
let selected_instance_paths = []
let confirmed_instance_paths = []
let db = null // Database for entries
let instance_states = {} // Holds expansion state {expanded_subs, expanded_hubs} for each node instance.
let search_state_instances = {}
let search_entry_states = {} // Holds expansion state for search mode interactions separately
let view = [] // A flat array representing the visible nodes in the graph.
let mode // Current mode of the graph explorer, can be set to 'default', 'menubar' or 'search'. Its value should be set by the `mode` file in the drive.
let previous_mode
let search_query = ''
let hubs_flag = 'default' // Flag for hubs behavior: 'default' (prevent duplication), 'true' (no duplication prevention), 'false' (disable hubs)
let selection_flag = 'default' // Flag for selection behavior: 'default' (enable selection), 'false' (disable selection)
let recursive_collapse_flag = false // Flag for recursive collapse: true (recursive), false (parent level only)
let drive_updated_by_scroll = false // Flag to prevent `onbatch` from re-rendering on scroll updates.
let drive_updated_by_toggle = false // Flag to prevent `onbatch` from re-rendering on toggle updates.
let drive_updated_by_search = false // Flag to prevent `onbatch` from re-rendering on search updates.
let drive_updated_by_last_clicked = false // Flag to prevent `onbatch` from re-rendering on last clicked node updates.
let ignore_drive_updated_by_scroll = false // Prevent scroll flag.
let drive_updated_by_match = false // Flag to prevent `onbatch` from re-rendering on matching entry updates.
let drive_updated_by_tracking = false // Flag to prevent `onbatch` from re-rendering on view order tracking updates.
let drive_updated_by_undo = false // Flag to prevent onbatch from re-rendering on undo updates
let is_loading_from_drive = false // Flag to prevent saving to drive during initial load
let multi_select_enabled = false // Flag to enable multi-select mode without ctrl key
let select_between_enabled = false // Flag to enable select between mode
let select_between_first_node = null // First node selected in select between mode
let duplicate_entries_map = {}
let view_order_tracking = {} // Tracks instance paths by base path in real time as they are added into the view through toggle expand/collapse actions.
let is_rendering = false // Flag to prevent concurrent rendering operations in virtual scrolling.
let spacer_element = null // DOM element used to manage scroll position when hubs are toggled.
let spacer_initial_height = 0
let hub_num = 0 // Counter for expanded hubs.
let last_clicked_node = null // Track the last clicked node instance path for highlighting.
let root_wand_state = null // Store original root wand state when replaced with jump button
const manipulated_inside_search = {}
let keybinds = {} // Store keyboard navigation bindings
let undo_stack = [] // Stack to track drive state changes for undo functionality
// Protocol system for message-based communication
let send = null
let graph_explorer_mid = 0 // Message ID counter for graph_explorer.js -> page.js messages
if (protocol) {
send = protocol(msg => onmessage(msg))
}
// Create db object that communicates via protocol messages
db = create_db()
const el = document.createElement('div')
el.className = 'graph-explorer-wrapper'
const shadow = el.attachShadow({ mode: 'closed' })
shadow.innerHTML = `
<div class="graph-container"></div>
<div class="searchbar"></div>
<div class="menubar"></div>
`
const searchbar = shadow.querySelector('.searchbar')
const menubar = shadow.querySelector('.menubar')
const container = shadow.querySelector('.graph-container')
document.body.style.margin = 0
let scroll_update_pending = false
container.onscroll = onscroll
let start_index = 0
let end_index = 0
const chunk_size = 50
const max_rendered_nodes = chunk_size * 3
let node_height
const top_sentinel = document.createElement('div')
const bottom_sentinel = document.createElement('div')
const observer = new IntersectionObserver(handle_sentinel_intersection, {
root: container,
rootMargin: '500px 0px',
threshold: 0
})
// Define handlers for different data types from the drive, called by `onbatch`.
const on = {
style: inject_style,
runtime: on_runtime,
mode: on_mode,
flags: on_flags,
keybinds: on_keybinds,
undo: on_undo
}
// Start watching for state changes. This is the main trigger for all updates.
await sdb.watch(onbatch)
document.onkeydown = handle_keyboard_navigation
return el
/******************************************************************************
ESSAGE HANDLING
- Handles incoming messages and sends outgoing messages.
- Messages follow standardized format: { head: [by, to, mid], refs, type, data }
******************************************************************************/
function onmessage (msg) {
const { type, data } = msg
const on_message_types = {
set_mode: handle_set_mode,
set_search_query: handle_set_search_query,
select_nodes: handle_select_nodes,
expand_node: handle_expand_node,
collapse_node: handle_collapse_node,
toggle_node: handle_toggle_node,
get_selected: handle_get_selected,
get_confirmed: handle_get_confirmed,
clear_selection: handle_clear_selection,
set_flag: handle_set_flag,
scroll_to_node: handle_scroll_to_node,
db_response: handle_db_response,
db_initialized: handle_db_initialized
}
const handler = on_message_types[type]
if (handler) handler(data)
else console.warn(`[graph_explorer-protocol] Unknown message type: ${type}`, msg)
function handle_db_response () {
db.handle_response(msg)
}
function handle_set_mode (data) {
const { mode: new_mode } = data
if (new_mode && ['default', 'menubar', 'search'].includes(new_mode)) {
update_drive_state({ type: 'mode/current_mode', message: new_mode })
send_message({ type: 'mode_changed', data: { mode: new_mode } })
}
}
function handle_set_search_query (data) {
const { query } = data
if (typeof query === 'string') {
search_query = query
drive_updated_by_search = true
update_drive_state({ type: 'mode/search_query', message: query })
if (mode === 'search') perform_search(query)
send_message({ type: 'search_query_changed', data: { query } })
}
}
function handle_select_nodes (data) {
const { instance_paths } = data
if (Array.isArray(instance_paths)) {
update_drive_state({ type: 'runtime/selected_instance_paths', message: instance_paths })
send_message({ type: 'selection_changed', data: { selected: instance_paths } })
}
}
function handle_expand_node (data) {
const { instance_path, expand_subs = true, expand_hubs = false } = data
if (instance_path && instance_states[instance_path]) {
instance_states[instance_path].expanded_subs = expand_subs
instance_states[instance_path].expanded_hubs = expand_hubs
drive_updated_by_toggle = true
update_drive_state({ type: 'runtime/instance_states', message: instance_states })
send_message({ type: 'node_expanded', data: { instance_path, expand_subs, expand_hubs } })
}
}
function handle_collapse_node (data) {
const { instance_path } = data
if (instance_path && instance_states[instance_path]) {
instance_states[instance_path].expanded_subs = false
instance_states[instance_path].expanded_hubs = false
drive_updated_by_toggle = true
update_drive_state({ type: 'runtime/instance_states', message: instance_states })
send_message({ type: 'node_collapsed', data: { instance_path } })
}
}
async function handle_toggle_node (data) {
const { instance_path, toggle_type = 'subs' } = data
if (instance_path && instance_states[instance_path]) {
if (toggle_type === 'subs') {
await toggle_subs(instance_path)
} else if (toggle_type === 'hubs') {
await toggle_hubs(instance_path)
}
send_message({ type: 'node_toggled', data: { instance_path, toggle_type } })
}
}
function handle_get_selected (data) {
send_message({ type: 'selected_nodes', data: { selected: selected_instance_paths } })
}
function handle_get_confirmed (data) {
send_message({ type: 'confirmed_nodes', data: { confirmed: confirmed_instance_paths } })
}
function handle_clear_selection (data) {
update_drive_state({ type: 'runtime/selected_instance_paths', message: [] })
update_drive_state({ type: 'runtime/confirmed_selected', message: [] })
send_message({ type: 'selection_cleared', data: {} })
}
function handle_set_flag (data) {
const { flag_type, value } = data
if (flag_type === 'hubs' && ['default', 'true', 'false'].includes(value)) {
update_drive_state({ type: 'flags/hubs', message: value })
} else if (flag_type === 'selection') {
update_drive_state({ type: 'flags/selection', message: value })
} else if (flag_type === 'recursive_collapse') {
update_drive_state({ type: 'flags/recursive_collapse', message: value })
}
send_message({ type: 'flag_changed', data: { flag_type, value } })
}
function handle_scroll_to_node (data) {
const { instance_path } = data
const node_index = view.findIndex(n => n.instance_path === instance_path)
if (node_index !== -1) {
const scroll_position = node_index * node_height
container.scrollTop = scroll_position
send_message({ type: 'scrolled_to_node', data: { instance_path, scroll_position } })
}
}
}
async function handle_db_initialized (data) {
// Page.js, trigger initial render
// After receiving entries, ensure the root node state is initialized and trigger the first render.
const root_path = '/'
if (await db.has(root_path)) {
const root_instance_path = '|/'
if (!instance_states[root_instance_path]) {
instance_states[root_instance_path] = {
expanded_subs: true,
expanded_hubs: false
}
}
// don't rebuild view if we're in search mode with active query
if (mode === 'search' && search_query) {
console.log('[SEARCH DEBUG] on_entries: skipping build_and_render_view in Search Mode with query:', search_query)
perform_search(search_query)
} else {
// tracking will be initialized later if drive data is empty
build_and_render_view()
}
} else {
console.warn('Root path "/" not found in entries. Clearing view.')
view = []
if (container) container.replaceChildren()
}
}
function send_message (msg) {
if (send) {
send(msg)
}
}
function create_db () {
// Pending requests map: key is message head [by, to, mid], value is {resolve, reject}
const pending_requests = new Map()
return {
// All operations are async via protocol messages
get: (path) => send_db_request('db_get', { path }),
has: (path) => send_db_request('db_has', { path }),
is_empty: () => send_db_request('db_is_empty', {}),
root: () => send_db_request('db_root', {}),
keys: () => send_db_request('db_keys', {}),
raw: () => send_db_request('db_raw', {}),
// Handle responses from page.js
handle_response: (msg) => {
if (!msg.refs || !msg.refs.cause) {
console.warn('[graph_explorer] Response missing refs.cause:', msg)
return
}
const request_head_key = JSON.stringify(msg.refs.cause)
const pending = pending_requests.get(request_head_key)
if (pending) {
pending.resolve(msg.data.result)
pending_requests.delete(request_head_key)
} else {
console.warn('[graph_explorer] No pending request for response:', msg.refs.cause)
}
}
}
function send_db_request (operation, params) {
return new Promise((resolve, reject) => {
const head = ['graph_explorer', 'page_js', graph_explorer_mid++]
const head_key = JSON.stringify(head)
pending_requests.set(head_key, { resolve, reject })
send_message({
head,
refs: null, // New request has no references
type: operation,
data: params
})
})
}
}
/******************************************************************************
STATE AND DATA HANDLING
- These functions process incoming data from the STATE module's `sdb.watch`.
- `onbatch` is the primary entry point.
******************************************************************************/
async function onbatch (batch) {
console.log('[SEARCH DEBUG] onbatch caled:', {
mode,
search_query,
last_clicked_node,
feedback_flags: {
scroll: drive_updated_by_scroll,
toggle: drive_updated_by_toggle,
search: drive_updated_by_search,
match: drive_updated_by_match,
tracking: drive_updated_by_tracking
}
})
// Prevent feedback loops from scroll or toggle actions.
if (check_and_reset_feedback_flags()) {
console.log('[SEARCH DEBUG] onbatch prevented by feedback flags')
return
}
for (const { type, paths } of batch) {
if (!paths || !paths.length) continue
const data = await Promise.all(
paths.map(path => batch_get(path))
)
// Call the appropriate handler based on `type`.
const func = on[type]
func ? await func({ data, paths }) : fail(data, type)
}
function batch_get (path) {
return drive
.get(path)
.then(file => (file ? file.raw : null))
.catch(e => {
console.error(`Error getting file from drive: ${path}`, e)
return null
})
}
}
function fail (data, type) {
throw new Error(`Invalid message type: ${type}`, { cause: { data, type } })
}
async function on_runtime ({ data, paths }) {
const on_runtime_paths = {
'node_height.json': handle_node_height,
'vertical_scroll_value.json': handle_vertical_scroll,
'horizontal_scroll_value.json': handle_horizontal_scroll,
'selected_instance_paths.json': handle_selected_paths,
'confirmed_selected.json': handle_confirmed_paths,
'instance_states.json': handle_instance_states,
'search_entry_states.json': handle_search_entry_states,
'last_clicked_node.json': handle_last_clicked_node,
'view_order_tracking.json': handle_view_order_tracking
}
let needs_render = false
const render_nodes_needed = new Set()
paths.forEach((path, i) => runtime_handler(path, data[i]))
if (needs_render) {
if (mode === 'search' && search_query) {
console.log('[SEARCH DEBUG] on_runtime: Skipping build_and_render_view in search mode with query:', search_query)
await perform_search(search_query)
} else {
await build_and_render_view()
}
} else if (render_nodes_needed.size > 0) {
render_nodes_needed.forEach(re_render_node)
}
function runtime_handler (path, data) {
if (data === null) return
const value = parse_json_data(data, path)
if (value === null) return
// Extract filename from path and use handler if available
const filename = path.split('/').pop()
const handler = on_runtime_paths[filename]
if (handler) {
const result = handler({ value, render_nodes_needed })
if (result?.needs_render) needs_render = true
}
}
function handle_node_height ({ value }) {
node_height = value
}
function handle_vertical_scroll ({ value }) {
if (typeof value === 'number') vertical_scroll_value = value
}
function handle_horizontal_scroll ({ value }) {
if (typeof value === 'number') horizontal_scroll_value = value
}
function handle_selected_paths ({ value, render_nodes_needed }) {
selected_instance_paths = process_path_array_update({
current_paths: selected_instance_paths,
value,
render_set: render_nodes_needed,
name: 'selected_instance_paths'
})
}
function handle_confirmed_paths ({ value, render_nodes_needed }) {
confirmed_instance_paths = process_path_array_update({
current_paths: confirmed_instance_paths,
value,
render_set: render_nodes_needed,
name: 'confirmed_selected'
})
}
function handle_instance_states ({ value }) {
if (typeof value === 'object' && value && !Array.isArray(value)) {
instance_states = value
return { needs_render: true }
} else {
console.warn('instance_states is not a valid object, ignoring.', value)
}
}
function handle_search_entry_states ({ value }) {
if (typeof value === 'object' && value && !Array.isArray(value)) {
search_entry_states = value
if (mode === 'search') return { needs_render: true }
} else {
console.warn('search_entry_states is not a valid object, ignoring.', value)
}
}
function handle_last_clicked_node ({ value, render_nodes_needed }) {
const old_last_clicked = last_clicked_node
last_clicked_node = typeof value === 'string' ? value : null
if (old_last_clicked) render_nodes_needed.add(old_last_clicked)
if (last_clicked_node) render_nodes_needed.add(last_clicked_node)
}
function handle_view_order_tracking ({ value }) {
if (typeof value === 'object' && value && !Array.isArray(value)) {
is_loading_from_drive = true
view_order_tracking = value
is_loading_from_drive = false
if (Object.keys(view_order_tracking).length === 0) {
initialize_tracking_from_current_state()
}
return { needs_render: true }
} else {
console.warn('view_order_tracking is not a valid object, ignoring.', value)
}
}
}
async function on_mode ({ data, paths }) {
const on_mode_paths = {
'current_mode.json': handle_current_mode,
'previous_mode.json': handle_previous_mode,
'search_query.json': handle_search_query,
'multi_select_enabled.json': handle_multi_select_enabled,
'select_between_enabled.json': handle_select_between_enabled
}
let new_current_mode, new_previous_mode, new_search_query, new_multi_select_enabled, new_select_between_enabled
paths.forEach((path, i) => mode_handler(path, data[i]))
if (typeof new_search_query === 'string') search_query = new_search_query
if (new_previous_mode) previous_mode = new_previous_mode
if (typeof new_multi_select_enabled === 'boolean') {
multi_select_enabled = new_multi_select_enabled
render_menubar() // Re-render menubar to update button text
}
if (typeof new_select_between_enabled === 'boolean') {
select_between_enabled = new_select_between_enabled
if (!select_between_enabled) select_between_first_node = null
render_menubar()
}
if (
new_current_mode &&
!['default', 'menubar', 'search'].includes(new_current_mode)
) {
console.warn(`Invalid mode "${new_current_mode}" provided. Ignoring update.`)
return
}
if (new_current_mode === 'search' && !search_query) {
search_state_instances = instance_states
}
if (!new_current_mode || mode === new_current_mode) return
if (mode && new_current_mode === 'search') update_drive_state({ type: 'mode/previous_mode', message: mode })
mode = new_current_mode
render_menubar()
render_searchbar()
await handle_mode_change()
if (mode === 'search' && search_query) await perform_search(search_query)
function mode_handler (path, data) {
const value = parse_json_data(data, path)
if (value === null) return
const filename = path.split('/').pop()
const handler = on_mode_paths[filename]
if (handler) {
const result = handler({ value })
if (result?.current_mode !== undefined) new_current_mode = result.current_mode
if (result?.previous_mode !== undefined) new_previous_mode = result.previous_mode
if (result?.search_query !== undefined) new_search_query = result.search_query
if (result?.multi_select_enabled !== undefined) new_multi_select_enabled = result.multi_select_enabled
if (result?.select_between_enabled !== undefined) new_select_between_enabled = result.select_between_enabled
}
}
function handle_current_mode ({ value }) {
return { current_mode: value }
}
function handle_previous_mode ({ value }) {
return { previous_mode: value }
}
function handle_search_query ({ value }) {
return { search_query: value }
}
function handle_multi_select_enabled ({ value }) {
return { multi_select_enabled: value }
}
function handle_select_between_enabled ({ value }) {
return { select_between_enabled: value }
}
}
function on_flags ({ data, paths }) {
const on_flags_paths = {
'hubs.json': handle_hubs_flag,
'selection.json': handle_selection_flag,
'recursive_collapse.json': handle_recursive_collapse_flag
}
paths.forEach((path, i) => flags_handler(path, data[i]))
function flags_handler (path, data) {
const value = parse_json_data(data, path)
if (value === null) return
const filename = path.split('/').pop()
const handler = on_flags_paths[filename]
if (handler) {
const result = handler(value)
if (result && result.needs_render) {
if (mode === 'search' && search_query) {
console.log('[SEARCH DEBUG] on_flags: Skipping build_and_render_view in search mode with query:', search_query)
perform_search(search_query)
} else {
build_and_render_view()
}
}
}
}
function handle_hubs_flag (value) {
if (typeof value === 'string' && ['default', 'true', 'false'].includes(value)) {
hubs_flag = value
return { needs_render: true }
} else {
console.warn('hubs flag must be one of: "default", "true", "false", ignoring.', value)
}
}
function handle_selection_flag (value) {
selection_flag = value
return { needs_render: true }
}
function handle_recursive_collapse_flag (value) {
recursive_collapse_flag = value
return { needs_render: false }
}
}
function inject_style ({ data }) {
const sheet = new CSSStyleSheet()
sheet.replaceSync(data[0])
shadow.adoptedStyleSheets = [sheet]
}
function on_keybinds ({ data }) {
if (!data || data[0] == null) {
console.error('Keybinds data is missing or empty.')
return
}
const parsed_data = parse_json_data(data[0])
if (typeof parsed_data !== 'object' || !parsed_data) {
console.error('Parsed keybinds data is not a valid object.')
return
}
keybinds = parsed_data
}
function on_undo ({ data }) {
if (!data || data[0] == null) {
console.error('Undo stack data is missing or empty.')
return
}
const parsed_data = parse_json_data(data[0])
if (typeof parsed_data !== 'object' || !parsed_data) {
console.error('Parsed undo stack data is not a valid Object.')
return
}
undo_stack = parsed_data
}
// Helper to persist component state to the drive.
async function update_drive_state ({ type, message }) {
// Save current state to undo stack before updating (except for some)
const should_track = (
!drive_updated_by_undo &&
!type.includes('scroll') &&
!type.includes('last_clicked') &&
!type.includes('view_order_tracking') &&
!type.includes('select_between') &&
type !== 'undo/stack'
)
if (should_track) {
await save_to_undo_stack(type)
}
try {
await drive.put(`${type}.json`, JSON.stringify(message))
} catch (e) {
const [dataset, name] = type.split('/')
console.error(`Failed to update ${dataset} state for ${name}:`, e)
}
if (should_track) {
render_menubar()
}
}
async function save_to_undo_stack (type) {
try {
const current_file = await drive.get(`${type}.json`)
if (current_file && current_file.raw) {
const snapshot = {
type,
value: current_file.raw,
timestamp: Date.now()
}
// Add to stack (limit to 50 items to prevent memory issues)
undo_stack.push(snapshot)
if (undo_stack.length > 50) {
undo_stack.shift()
}
drive_updated_by_undo = true
await drive.put('undo/stack.json', JSON.stringify(undo_stack))
}
} catch (e) {
console.error('Failed to save to undo stack:', e)
}
}
function get_or_create_state (states, instance_path) {
if (!states[instance_path]) {
states[instance_path] = { expanded_subs: false, expanded_hubs: false }
}
if (states[instance_path].expanded_subs === null) {
states[instance_path].expanded_subs = true
}
return states[instance_path]
}
async function calculate_children_pipe_trail ({
depth,
is_hub,
is_last_sub,
is_first_hub = false,
parent_pipe_trail,
parent_base_path,
base_path,
db
}) {
const children_pipe_trail = [...parent_pipe_trail]
const parent_entry = await db.get(parent_base_path)
const is_hub_on_top = base_path === parent_entry?.hubs?.[0] || base_path === '/'
if (depth > 0) {
if (is_hub) {
if (is_last_sub) {
children_pipe_trail.pop()
children_pipe_trail.push(true)
}
if (is_hub_on_top && !is_last_sub) {
children_pipe_trail.pop()
children_pipe_trail.push(true)
}
if (is_first_hub) {
children_pipe_trail.pop()
children_pipe_trail.push(false)
}
}
children_pipe_trail.push(is_hub || !is_last_sub)
}
return { children_pipe_trail, is_hub_on_top }
}
// Extracted pipe logic for reuse in both default and search modes
async function calculate_pipe_trail ({
depth,
is_hub,
is_last_sub,
is_first_hub = false,
is_hub_on_top,
parent_pipe_trail,
parent_base_path,
base_path,
db
}) {
let last_pipe = null
const parent_entry = await db.get(parent_base_path)
const calculated_is_hub_on_top = base_path === parent_entry?.hubs?.[0] || base_path === '/'
const final_is_hub_on_top = is_hub_on_top !== undefined ? is_hub_on_top : calculated_is_hub_on_top
if (depth > 0) {
if (is_hub) {
last_pipe = [...parent_pipe_trail]
if (is_last_sub) {
last_pipe.pop()
last_pipe.push(true)
if (is_first_hub) {
last_pipe.pop()
last_pipe.push(false)
}
}
if (final_is_hub_on_top && !is_last_sub) {
last_pipe.pop()
last_pipe.push(true)
}
}
}
const pipe_trail = (is_hub && is_last_sub) || (is_hub && final_is_hub_on_top) ? last_pipe : parent_pipe_trail
const product = { pipe_trail, is_hub_on_top: final_is_hub_on_top }
return product
}
/******************************************************************************
VIEW AND RENDERING LOGIC AND SCALING
- These functions build the `view` array and render the DOM.
- `build_and_render_view` is the main orchestrator.
- `build_view_recursive` creates the flat `view` array from the hierarchical data.
- `calculate_mobile_scale` calculates the scale factor for mobile devices.
******************************************************************************/
async function build_and_render_view (focal_instance_path, hub_toggle = false) {
console.log('[SEARCH DEBUG] build_and_render_view called:', {
focal_instance_path,
hub_toggle,
current_mode: mode,
search_query,
last_clicked_node,
stack_trace: new Error().stack.split('\n').slice(1, 4).map(line => line.trim())
})
// This fuction should'nt be called in search mode for search
if (mode === 'search' && search_query && !hub_toggle) {
console.error('[SEARCH DEBUG] build_and_render_view called inappropriately in search mode!', {
mode,
search_query,
focal_instance_path,
stack_trace: new Error().stack.split('\n').slice(1, 6).map(line => line.trim())
})
}
const is_empty = await db.is_empty()
if (!db || is_empty) {
console.warn('No entries available to render.')
return
}
const old_view = [...view]
const old_scroll_top = vertical_scroll_value
const old_scroll_left = horizontal_scroll_value
let existing_spacer_height = 0
if (spacer_element && spacer_element.parentNode) existing_spacer_height = parseFloat(spacer_element.style.height) || 0
// Recursively build the new `view` array from the graph data.
view = await build_view_recursive({
base_path: '/',
parent_instance_path: '',
depth: 0,
is_last_sub: true,
is_hub: false,
parent_pipe_trail: [],
instance_states,
db
})
// Recalculate duplicates after view is built
collect_all_duplicate_entries()
const new_scroll_top = calculate_new_scroll_top({
old_scroll_top,
old_view,
focal_path: focal_instance_path
})
const render_anchor_index = Math.max(0, Math.floor(new_scroll_top / node_height))
start_index = Math.max(0, render_anchor_index - chunk_size)
end_index = Math.min(view.length, render_anchor_index + chunk_size)
const fragment = document.createDocumentFragment()
for (let i = start_index; i < end_index; i++) {
if (view[i]) fragment.appendChild(create_node(view[i]))
}
container.replaceChildren(top_sentinel, fragment, bottom_sentinel)
top_sentinel.style.height = `${start_index * node_height}px`
bottom_sentinel.style.height = `${(view.length - end_index) * node_height}px`
observer.observe(top_sentinel)
observer.observe(bottom_sentinel)
// Handle the spacer element used for keep entries static wrt cursor by scrolling when hubs are toggled.
handle_spacer_element({
hub_toggle,
existing_height: existing_spacer_height,
new_scroll_top,
sync_fn: set_scroll_and_sync
})
function set_scroll_and_sync () {
drive_updated_by_scroll = true
container.scrollTop = new_scroll_top
container.scrollLeft = old_scroll_left
vertical_scroll_value = container.scrollTop
}
}
// Traverses the hierarchical entries data and builds a flat `view` array for rendering.
async function build_view_recursive ({
base_path,
parent_instance_path,
parent_base_path = null,
depth,
is_last_sub,
is_hub,
is_first_hub = false,
parent_pipe_trail,
instance_states,
db
}) {
const instance_path = `${parent_instance_path}|${base_path}`
const entry = await db.get(base_path)
if (!entry) return []
const state = get_or_create_state(instance_states, instance_path)
const { children_pipe_trail, is_hub_on_top } = await calculate_children_pipe_trail({
depth,
is_hub,
is_last_sub,
is_first_hub,
parent_pipe_trail,
parent_base_path,
base_path,
db
})
const current_view = []
// If hubs are expanded, recursively add them to the view first (they appear above the node).
if (state.expanded_hubs && Array.isArray(entry.hubs)) {
for (let i = 0; i < entry.hubs.length; i++) {
const hub_path = entry.hubs[i]
const hub_view = await build_view_recursive({
base_path: hub_path,
parent_instance_path: instance_path,
parent_base_path: base_path,
depth: depth + 1,
is_last_sub: i === entry.hubs.length - 1,
is_hub: true,
is_first_hub: is_hub ? is_hub_on_top : false,
parent_pipe_trail: children_pipe_trail,
instance_states,
db
})
current_view.push(...hub_view)
}
}
// Calculate pipe_trail for this node
const { pipe_trail, is_hub_on_top: calculated_is_hub_on_top } = await calculate_pipe_trail({
depth,
is_hub,
is_last_sub,
is_first_hub,
is_hub_on_top,
parent_pipe_trail,
parent_base_path,
base_path,
db
})
current_view.push({
base_path,
instance_path,
depth,
is_last_sub,
is_hub,
is_first_hub,
parent_pipe_trail,
parent_base_path,
entry, // Include entry data in view to avoid async lookups during rendering
pipe_trail, // Pre-calculated pipe trail
is_hub_on_top: calculated_is_hub_on_top // Pre-calculated hub position
})
// If subs are expanded, recursively add them to the view (they appear below the node).
if (state.expanded_subs && Array.isArray(entry.subs)) {
for (let i = 0; i < entry.subs.length; i++) {
const sub_path = entry.subs[i]
const sub_view = await build_view_recursive({
base_path: sub_path,
parent_instance_path: instance_path,
parent_base_path: base_path,
depth: depth + 1,
is_last_sub: i === entry.subs.length - 1,
is_hub: false,
parent_pipe_trail: children_pipe_trail,
instance_states,
db
})
current_view.push(...sub_view)
}
}
return current_view
}
/******************************************************************************
4. NODE CREATION AND EVENT HANDLING
- `create_node` generates the DOM element for a single node.
- It sets up event handlers for user interactions like selecting or toggling.
******************************************************************************/
function create_node ({
base_path,
instance_path,
depth,
is_last_sub,
is_hub,
is_search_match,
is_direct_match,
is_in_original_view,
query,
entry, // Entry data is now passed from view
pipe_trail, // Pre-calculated pipe trail
is_hub_on_top // Pre-calculated hub position
}) {
if (!entry) {
const err_el = document.createElement('div')
err_el.className = 'node error'
err_el.textContent = `Error: Missing entry for ${base_path}`
return err_el
}
let states
if (mode === 'search') {
if (manipulated_inside_search[instance_path]) {
search_entry_states[instance_path] = manipulated_inside_search[instance_path]
states = search_entry_states