Repository navigation
Expand file tree
/
Copy pathnav.js
More file actions
1828 lines (1665 loc) · 81.4 KB
/
Copy pathnav.js
File metadata and controls
1828 lines (1665 loc) · 81.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// nb-web nav.js — command bar, opts bar, output bar, side menu
const NbNav = (() => {
const _t = (key) => NbWeb.t(key);
let _notebooks = [];
let _scope = 'home'; // global notebook scope, set via Notebooks cmd
let _activeCmd = 'list';
// Per-notebook defaults: hardcoded base, overridden by server-stored prefs
const _NB_HARDCODED = {
contacts: { type: 'contact', sort: 'az' },
nb: { type: 'todo', sort: 'default' },
};
const _DEFAULT_LIST = { type: 'all', sort: 'default' };
let _nbStoredPrefs = {}; // populated from /api/notebooks on load
function _applyNotebookDefaults(nb) {
const base = _NB_HARDCODED[nb] || _DEFAULT_LIST;
const stored = _nbStoredPrefs[nb] || {};
const sort = stored.default_sort || base.sort;
const type = stored.default_list_type || base.type;
_state.list.type = type;
NbMain.resetSort?.(sort);
}
// Per-command state (scope-independent options only)
const _state = {
list: { type: 'all', todoStatus: 'open' },
add: { type: 'note', title: '', url: '', template: null, templateName: '', dirty: false, encrypt: false, password: '' },
templates: {},
todo: { status: 'open' },
cal: { displayYear: new Date().getFullYear(), displayMonth: new Date().getMonth() + 1,
selected: null, start: null, end: null, noteDays: new Set() },
daily: { date: '' },
g: { all: false, context: 0, before: 0, after: 0, pattern: '' },
info: {},
weather: {},
};
let _calKeyHandler = null; // removed when leaving cal mode
// folder drill state (per-command so drill persists)
const _folder = {};
// ── Notebooks ─────────────────────────────────────────────────
// The notebook and folder of the note named by the URL hash (#notebook:path/note.md),
// or null.
function _hashLocation() {
const sel = location.hash ? decodeURIComponent(location.hash.slice(1)) : '';
const i = sel.indexOf(':');
if (i <= 0) return null;
const path = sel.slice(i + 1);
return { nb: sel.slice(0, i), folder: path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '' };
}
async function _loadNotebooks() {
try {
const r = await fetch('/api/notebooks');
const d = await r.json();
_notebooks = d.notebooks || [];
_nbStoredPrefs = d.notebook_prefs || {};
// Seed scope from nb's actual current notebook on first load -- unless the URL
// names a note (a refresh, bookmark or shared link): then list that note's
// notebook, so the list and the preview agree.
const loc = _hashLocation();
if (loc && _notebooks.includes(loc.nb)) {
_scope = loc.nb;
_folder.list = loc.folder;
} else if (d.current_notebook && _notebooks.includes(d.current_notebook)) {
_scope = d.current_notebook;
}
renderOptsBar();
if (_folder.list) updateBreadcrumb(_folder.list.split('/'));
// Apply per-notebook defaults now that scope is known, then
// poll sync status against the correct notebook
_applyNotebookDefaults(_scope);
_pollNbSyncStatus();
} catch (e) {
console.error('loadNotebooks:', e);
}
}
// ── Command bar ───────────────────────────────────────────────
function _initCmdBar() {
document.querySelectorAll('.nb-cmd').forEach(btn => {
btn.addEventListener('click', () => activateCmd(btn.dataset.cmd));
});
// Search-bar icon buttons (toggle: click active icon → back to list)
document.getElementById('nb-cal-icon')?.addEventListener('click', () =>
activateCmd(_activeCmd === 'cal' ? 'list' : 'cal'));
}
function activateCmd(cmd, opts = {}) {
if (!opts.internal && NbMain.isEditing?.()) {
if (!confirm('Discard unsaved changes?')) return;
NbMain.closeEditor?.();
}
if (!opts.internal) { NbDialog.close?.(); NbMain.clearSelection?.(); }
if (cmd === 'add' && !opts.internal) {
const pa = document.getElementById('nb-preview-actions');
if (pa) pa.hidden = true;
}
const isContactsShortcut = (cmd === 'contacts');
if (isContactsShortcut) { _scope = 'contacts'; cmd = 'list'; }
// Explicit user navigation to List: clear transient filters so the
// list always opens clean, regardless of what command was active.
if (cmd === 'list' && !opts.internal && !isContactsShortcut) {
// Coming from contacts scope: reset back to home
if (_scope === 'contacts') _scope = 'home';
// Coming from a different command: clear search + tags
if (_activeCmd !== 'list') {
_searchQuery = '';
_tagsQuery = '';
['nb-search', 'nb-tags'].forEach(id => {
const el = document.getElementById(id);
if (el) el.value = '';
});
['nb-search-clear', 'nb-tags-clear'].forEach(id => {
const el = document.getElementById(id);
if (el) el.hidden = true;
});
}
}
_activeCmd = cmd;
document.querySelectorAll('.nb-cmd').forEach(b =>
b.classList.toggle('active', b.dataset.cmd === cmd));
// Full-preview layout (no list pane) for output-only commands
const fullPreview = ['daily', 'info', 'weather'].includes(cmd);
document.getElementById('nb-layout').classList.toggle('nb-full-preview', fullPreview);
// Clean up cal Enter handler when leaving cal
if (_calKeyHandler) {
document.removeEventListener('keydown', _calKeyHandler);
_calKeyHandler = null;
}
if (cmd === 'list') _applyNotebookDefaults(_scope);
else NbMain.resetSort?.(); // non-list commands just reset
_updateSearchIcons();
renderOptsBar();
_executeCmd();
}
// ── Opts bar ──────────────────────────────────────────────────
function renderOptsBar() {
const bar = document.getElementById('nb-cmd-opts-bar');
bar.innerHTML = '';
(_optsRenderers[_activeCmd] || (() => {}))(bar);
_updateOutputBar();
}
const _optsRenderers = {
list: _renderListOpts,
add: _renderAddOpts,
todo: _renderTodoOpts,
cal: _renderCalOpts,
daily: _renderDailyOpts,
g: _renderGrepOpts,
templates: _renderTemplatesOpts,
info: () => {},
weather: () => {},
};
// Scope selector — a compact <select> showing all notebooks + All
function _makeScopeSelect(onChange) {
const wrap = document.createElement('span');
wrap.className = 'nb-scope-wrap';
wrap.title = 'Scope (notebook)';
const icon = document.createElement('span');
icon.className = 'nb-scope-icon';
icon.textContent = '📒';
icon.setAttribute('aria-hidden', 'true');
const sel = document.createElement('select');
sel.className = 'nb-scope-select';
const allOpt = document.createElement('option');
allOpt.value = '_all'; allOpt.textContent = 'all';
sel.appendChild(allOpt);
_notebooks.forEach(name => {
const opt = document.createElement('option');
opt.value = name; opt.textContent = name;
if (name === _scope) opt.selected = true;
sel.appendChild(opt);
});
if (_scope === '_all') sel.value = '_all';
sel.addEventListener('change', () => {
_scope = sel.value;
_updateOutputBar();
onChange(_scope);
_pollNbSyncStatus();
sel.blur(); // release focus so arrow keys go to the list, not notebook options
});
wrap.append(icon, sel);
return wrap;
}
function _renderListOpts(bar) {
const st = _state.list;
function _run() {
_executeCmd(); // honours _searchQuery / _tagsQuery alongside type + status
}
bar.appendChild(_makeScopeSelect(nb => {
_folder[_activeCmd] = '';
updateBreadcrumb([]);
_applyNotebookDefaults(nb); renderOptsBar(); _run();
}));
bar.appendChild(_makeSep());
bar.appendChild(_makeChipRow([
{ val: 'all', label: 'all' },
{ val: 'note', label: '📝' },
{ val: 'bookmark', label: '🔖' },
{ val: 'todo', label: '✔' },
{ val: 'contact', label: '🪪' },
{ val: 'folder', label: '📂' },
{ val: 'image', label: '🌄' },
], st.type, val => {
st.type = val;
statusWrap.hidden = val !== 'todo';
_updateOutputBar();
_run();
}));
// Status chips — appear only when ✔ todo type is active
const statusWrap = document.createElement('span');
statusWrap.className = 'nb-opts-chips';
statusWrap.hidden = st.type !== 'todo';
['open', 'closed'].forEach(s => {
const chip = _makeChip(s, st.todoStatus === s, () => {
st.todoStatus = s;
statusWrap.querySelectorAll('.nb-opt-chip').forEach(c => c.classList.remove('active'));
chip.classList.add('active');
_updateOutputBar();
_run();
});
statusWrap.appendChild(chip);
});
bar.appendChild(statusWrap);
}
function _renderAddOpts(bar) {
const st = _state.add;
let urlInput, titleInput, actionWrap, scopeWrap, tmplBtn, encBtn, encPwInput;
let _tmplMode = false;
function _syncTmplBtn() {
if (!tmplBtn) return;
const hasTemplate = !!st.template;
tmplBtn.classList.toggle('active', _tmplMode || hasTemplate);
tmplBtn.title = hasTemplate
? `Template: ${st.templateName} (click to change)`
: 'Use template';
}
async function _applyDefaultTemplate(nb, folder = '') {
try {
let url = `/api/template/default?notebook=${encodeURIComponent(nb)}`;
if (folder) url += `&folder=${encodeURIComponent(folder)}`;
const r = await fetch(url);
const d = await r.json();
if (d.template) {
st.template = d.template.path;
st.templateName = d.template.name;
st.templateFolder = d.folder || '';
} else {
st.template = null; st.templateName = ''; st.templateFolder = '';
}
_syncTmplBtn();
_updateOutputBar();
} catch(e) { /* network error — leave template state unchanged */ }
}
// Scope select — first/leftmost; hidden when creating a notebook (they're top-level)
scopeWrap = _makeScopeSelect(async nb => {
_updateOutputBar();
await _applyDefaultTemplate(nb === '_all' ? 'home' : nb, _folder['list'] || '');
_tmplMode ? NbMain.loadTemplatesForAdd() : NbMain.loadNotes();
});
scopeWrap.hidden = st.type === 'notebook';
bar.appendChild(scopeWrap);
bar.appendChild(_makeSep());
// Type chips
bar.appendChild(_makeChipRow([
{ val: 'note', label: '📝 Note' },
{ val: 'bookmark', label: '🔖 Bookmark' },
{ val: 'todo', label: '✔ Todo' },
{ val: 'task', label: '☑ Task' }, // a Taskwarrior task + its note (NbTwAdd)
{ val: 'folder', label: '📂 Folder' },
{ val: 'notebook', label: '📒 Notebook' },
], st.type, val => {
st.type = val;
if (urlInput) urlInput.hidden = val !== 'bookmark';
if (scopeWrap) scopeWrap.hidden = val === 'notebook';
if (titleInput) titleInput.placeholder =
val === 'folder' ? 'Folder name…' :
val === 'notebook' ? 'Notebook name…' :
val === 'task' ? 'Task description…' : 'Title…';
if (tmplBtn) {
tmplBtn.hidden = val !== 'note';
if (val !== 'note' && _tmplMode) {
_tmplMode = false;
st.template = null; st.templateName = '';
_syncTmplBtn();
NbMain.loadNotes();
}
}
if (encBtn) {
encBtn.hidden = val !== 'note';
if (val !== 'note' && st.encrypt) {
st.encrypt = false; st.password = '';
encBtn.classList.remove('active');
if (encPwInput) encPwInput.hidden = true;
}
}
_updateOutputBar();
}));
// Templates toggle — note type only; active when template mode is on OR a template is applied
tmplBtn = document.createElement('button');
tmplBtn.className = 'nb-icon-btn';
tmplBtn.textContent = '📋';
tmplBtn.hidden = st.type !== 'note';
tmplBtn.addEventListener('click', () => {
_tmplMode = !_tmplMode;
_syncTmplBtn();
_tmplMode ? NbMain.loadTemplatesForAdd() : NbMain.loadNotes();
});
_syncTmplBtn(); // reflect any already-applied template
bar.appendChild(tmplBtn);
// Encrypt toggle — note type only
encBtn = document.createElement('button');
encBtn.className = 'nb-icon-btn';
encBtn.textContent = '🔑';
encBtn.title = 'Encrypt note';
encBtn.hidden = st.type !== 'note';
encBtn.classList.toggle('active', st.encrypt);
encBtn.addEventListener('click', () => {
st.encrypt = !st.encrypt;
encBtn.classList.toggle('active', st.encrypt);
encPwInput.hidden = !st.encrypt;
if (st.encrypt) {
const known = NbMain.encPassword?.();
if (known) { st.password = known; encPwInput.value = known; }
encPwInput.focus();
} else {
st.password = '';
}
});
bar.appendChild(encBtn);
bar.appendChild(_makeSep());
// Password input — encrypt mode only, left of title
encPwInput = document.createElement('input');
encPwInput.type = 'password';
encPwInput.className = 'nb-opt-input';
encPwInput.placeholder = 'Password…';
encPwInput.style.maxWidth = '130px';
encPwInput.hidden = !st.encrypt;
if (st.encrypt && st.password) encPwInput.value = st.password;
encPwInput.addEventListener('input', () => { st.password = encPwInput.value; });
encPwInput.addEventListener('keydown', e => {
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey) && st.dirty) _doEdit();
else if (e.key === 'Enter' && st.dirty) _doSave();
if (e.key === 'Escape') _doCancel();
});
bar.appendChild(encPwInput);
// Title input — grows to fill available space
titleInput = document.createElement('input');
titleInput.type = 'text';
titleInput.className = 'nb-opt-input nb-add-title';
titleInput.placeholder = st.type === 'folder' ? 'Folder name…' :
st.type === 'notebook' ? 'Notebook name…' :
st.type === 'task' ? 'Task description…' : 'Title…';
titleInput.value = st.title;
titleInput.addEventListener('input', () => { st.title = titleInput.value; _markDirty(); });
titleInput.addEventListener('keydown', e => {
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey) && st.dirty) _doEdit();
else if (e.key === 'Enter' && st.dirty) _doSave();
if (e.key === 'Escape') _doCancel();
});
bar.appendChild(titleInput);
// URL input — bookmark only
urlInput = document.createElement('input');
urlInput.type = 'url';
urlInput.className = 'nb-opt-input nb-add-url';
urlInput.placeholder = 'URL…';
urlInput.value = st.url;
urlInput.hidden = st.type !== 'bookmark';
urlInput.addEventListener('input', () => { st.url = urlInput.value; _markDirty(); });
urlInput.addEventListener('keydown', e => {
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey) && st.dirty) _doEdit();
else if (e.key === 'Enter' && st.dirty) _doSave();
if (e.key === 'Escape') _doCancel();
});
bar.appendChild(urlInput);
// Cancel / Save row — full-width so it always sits on its own line
actionWrap = document.createElement('div');
actionWrap.className = 'nb-add-actions';
actionWrap.hidden = !st.dirty;
const cancelBtn = document.createElement('button');
cancelBtn.className = 'nb-tool-btn';
cancelBtn.textContent = _t('btn_cancel');
cancelBtn.addEventListener('click', _doCancel);
const wantsEditor = st.type === 'note' || st.type === 'todo';
const editBtn = document.createElement('button');
editBtn.className = 'nb-tool-btn';
editBtn.textContent = _t('btn_edit');
editBtn.hidden = !wantsEditor;
editBtn.addEventListener('click', _doEdit);
const saveBtn = document.createElement('button');
saveBtn.className = 'nb-tool-btn nb-btn-primary';
saveBtn.textContent = _t('btn_save');
saveBtn.addEventListener('click', _doSave);
actionWrap.append(cancelBtn, editBtn, saveBtn);
bar.appendChild(actionWrap);
// ── Local helpers (close over DOM refs) ───────────────────
function _markDirty() {
st.dirty = true;
actionWrap.hidden = false;
_updateOutputBar();
}
function _busy(label) {
saveBtn.disabled = editBtn.disabled = true;
saveBtn.textContent = label;
}
function _idle() {
saveBtn.disabled = editBtn.disabled = false;
saveBtn.textContent = _t('btn_save');
}
// Show a note just made from the Add bar: back to the List command, which keeps the
// folder you were in (the Add command's own list is the notebook's top level), with
// auto-select off so the list can't open its first note over the new one (2026-10-07,
// note-actions.spec.js; same pattern as NbNoteActions' create form).
async function _openCreated(sel) {
NbMain.setNoAutoSelect(true);
activateCmd('list', { internal: true });
try {
await NbMain.openNote(sel);
// A note filed elsewhere (a task note into its project folder, djp 2026-11-01):
// show its folder, or it's open but not in the list you're looking at
NbNav.followHashNotebook();
} finally { NbMain.setNoAutoSelect(false); }
}
function _doCancel(reload = true) {
st.title = ''; st.url = ''; st.template = null; st.templateName = ''; st.dirty = false;
st.encrypt = false; st.password = '';
titleInput.value = ''; urlInput.value = '';
if (encPwInput) { encPwInput.value = ''; encPwInput.hidden = true; }
if (encBtn) encBtn.classList.remove('active');
actionWrap.hidden = true;
_tmplMode = false;
_syncTmplBtn();
_updateOutputBar();
if (reload) NbMain.loadNotes();
}
function _noteArgs() {
return {
notebook: _scope === '_all' ? 'home' : _scope,
folder: st.templateFolder || _folder['list'] || '',
type: st.type,
title: st.title,
url: st.url,
template_path: st.template || '',
template_content: st.templateContent || '',
};
}
// ☑ Task: tw-web's own Add dialog (pre-filled with the title) adds the task, then
// nb-web makes its note. From home or All the note goes to tasknotes:, the plugin's
// default; from any other notebook, there.
async function _doAddTask() {
const notebook = (_scope === '_all' || _scope === 'home') ? '' : _scope;
const result = await NbTwAdd.open({ description: st.title, notebook });
if (result && result.selector) {
_doCancel(false);
await _openCreated(result.selector);
}
}
async function _doSave() {
if (st.type === 'task') return _doAddTask();
if (!st.title && !st.url) return;
if (saveBtn.disabled) return;
if (st.encrypt && !st.password) { encPwInput?.focus(); return; }
_busy('Saving…');
try {
const result = st.encrypt
? await NbMain.addEncryptedNote({..._noteArgs(), password: st.password})
: await NbMain.addNote(_noteArgs());
if (result) {
_doCancel(false);
if (result.folder) NbNav.showFolder(result.notebook, result.folder);
else if (result.selector) _openCreated(result.selector);
else NbMain.loadNotes();
}
} finally {
_idle();
}
}
async function _doEdit() {
if (st.type === 'task') return _doAddTask();
if (!st.title && !st.url) return;
if (editBtn.disabled) return;
if (st.encrypt && !st.password) { encPwInput?.focus(); return; }
_busy('Opening…');
try {
const result = st.encrypt
? await NbMain.addEncryptedNote({..._noteArgs(), password: st.password})
: await NbMain.addNote(_noteArgs());
if (result && result.folder) {
_doCancel(false);
NbNav.showFolder(result.notebook, result.folder);
} else if (result && result.selector) {
st.title = ''; st.url = ''; st.template = null; st.dirty = false;
await _openCreated(result.selector);
NbMain.openEditor(result.selector);
} else if (result) {
console.warn('[doEdit] no selector returned — falling back to save', result);
_doCancel();
}
} finally {
_idle();
}
}
// Focus title immediately when Add is clicked
requestAnimationFrame(() => titleInput.focus());
// Auto-apply notebook default template on open (async — won't delay render)
// Pass list-folder context so items/.templates/ wins when user is browsing items/
if (st.type === 'note' && !st.dirty) {
_applyDefaultTemplate(_scope === '_all' ? 'home' : _scope, _folder['list'] || '');
}
}
function _renderTodoOpts(bar) {
bar.appendChild(_makeScopeSelect(() => _executeCmd()));
bar.appendChild(_makeSep());
bar.appendChild(_makeChipRow([
{ val: 'open', label: 'open' },
{ val: 'closed', label: 'closed' },
], _state.todo.status, val => {
_state.todo.status = val;
_updateOutputBar();
_executeCmd();
}));
}
function _renderCalOpts(bar) {
const st = _state.cal;
const today = NbWeb.isoDate();
// Default selected to today on first open; clean up any stale Enter handler
if (!st.selected) st.selected = today;
if (_calKeyHandler) {
document.removeEventListener('keydown', _calKeyHandler);
_calKeyHandler = null;
}
// ── Widget shell ──────────────────────────────────────────
const widget = document.createElement('div');
widget.className = 'nb-cal-widget';
// ── Left: mini calendar ───────────────────────────────────
const left = document.createElement('div');
left.className = 'nb-cal-left';
// Month header
const header = document.createElement('div');
header.className = 'nb-cal-header';
const prevBtn = document.createElement('button');
prevBtn.className = 'nb-cal-nav-btn';
prevBtn.textContent = '‹';
const monthLabel = document.createElement('div');
monthLabel.className = 'nb-cal-month-label';
const nextBtn = document.createElement('button');
nextBtn.className = 'nb-cal-nav-btn';
nextBtn.textContent = '›';
const MONTHS = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
function _updateMonthLabel() {
monthLabel.innerHTML = '';
const y = st.displayYear, m = st.displayMonth;
const pfx = `${y}-${String(m).padStart(2,'0')}`;
const last = new Date(y, m, 0).getDate();
const mBtn = document.createElement('button');
mBtn.className = 'nb-cal-label-btn';
mBtn.textContent = MONTHS[m - 1];
mBtn.addEventListener('click', () => {
st.start = `${pfx}-01`; st.end = `${pfx}-${last}`; st.selected = null;
_updateLabels(); _renderGrid(); _updateOutputBar();
NbMain.runCal({ start: st.start, end: st.end, notebook: _scope });
});
const yBtn = document.createElement('button');
yBtn.className = 'nb-cal-label-btn';
yBtn.textContent = y;
yBtn.addEventListener('click', () => {
st.start = `${y}-01-01`; st.end = `${y}-12-31`; st.selected = null;
_updateLabels(); _renderGrid(); _updateOutputBar();
NbMain.runCal({ start: st.start, end: st.end, notebook: _scope });
});
monthLabel.append(mBtn, ' ', yBtn);
}
_updateMonthLabel();
header.append(prevBtn, monthLabel, nextBtn);
left.appendChild(header);
// Calendar grid
const grid = document.createElement('div');
grid.className = 'nb-cal-grid';
// Weekday header row
['Mo','Tu','We','Th','Fr','Sa','Su'].forEach(d => {
const cell = document.createElement('span');
cell.className = 'nb-cal-day nb-cal-day-hdr';
cell.textContent = d;
grid.appendChild(cell);
});
function _renderGrid() {
while (grid.children.length > 7) grid.removeChild(grid.lastChild);
const y = st.displayYear, m = st.displayMonth;
const firstDay = new Date(y, m - 1, 1).getDay();
const offset = (firstDay + 6) % 7; // Mon-first
const daysInMonth = new Date(y, m, 0).getDate();
const pfx = `${y}-${String(m).padStart(2,'0')}`;
for (let i = 0; i < offset; i++) {
const cell = document.createElement('span');
cell.className = 'nb-cal-day nb-cal-empty';
grid.appendChild(cell);
}
for (let d = 1; d <= daysInMonth; d++) {
const ds = `${pfx}-${String(d).padStart(2,'0')}`;
const cell = document.createElement('button');
cell.className = 'nb-cal-day';
cell.textContent = d;
cell.dataset.date = ds;
if (ds === today) cell.classList.add('today');
if (st.noteDays?.has(ds)) cell.classList.add('has-notes');
if (ds === st.selected) cell.classList.add('selected');
if (ds === st.start) cell.classList.add('range-start');
if (ds === st.end) cell.classList.add('range-end');
if (st.start && st.end && ds > st.start && ds < st.end)
cell.classList.add('in-range');
cell.addEventListener('click', () => _selectDay(ds));
grid.appendChild(cell);
}
}
_renderGrid();
left.appendChild(grid);
widget.appendChild(left);
// ── Right: action column ──────────────────────────────────
const right = document.createElement('div');
right.className = 'nb-cal-right';
const startLabel = document.createElement('div');
startLabel.className = 'nb-cal-range-item';
const endLabel = document.createElement('div');
endLabel.className = 'nb-cal-range-item';
function _updateLabels() {
startLabel.textContent = `▶ ${st.start || '–'}`;
endLabel.textContent = `◀ ${st.end || '–'}`;
startLabel.classList.toggle('nb-cal-range-set', !!st.start);
endLabel.classList.toggle('nb-cal-range-set', !!st.end);
}
_updateLabels();
function _makeCalBtn(label, onClick) {
const b = document.createElement('button');
b.className = 'nb-opt-chip';
b.textContent = label;
b.addEventListener('click', onClick);
return b;
}
right.append(
_makeCalBtn('Today', () => {
const now = new Date();
st.displayYear = now.getFullYear();
st.displayMonth = now.getMonth() + 1;
st.start = null; st.end = null; st.selected = today;
_updateMonthLabel(); _updateLabels(); _renderGrid(); _updateOutputBar();
_loadNoteDays();
_selectDay(today);
}),
startLabel,
endLabel,
_makeCalBtn('Start', () => {
if (!st.selected) return;
st.start = st.selected; st.end = null;
_updateLabels(); _renderGrid(); _updateOutputBar();
NbMain.runCal({ start: st.start, notebook: _scope });
}),
_makeCalBtn('End', () => {
if (!st.selected) return;
st.end = st.selected;
if (st.start && st.end < st.start) [st.start, st.end] = [st.end, st.start];
_updateLabels(); _renderGrid(); _updateOutputBar();
NbMain.runCal({ start: st.start || st.end, end: st.end, notebook: _scope });
}),
_makeCalBtn('Clear', () => {
st.start = null; st.end = null; st.selected = null;
_updateLabels(); _renderGrid(); _updateOutputBar();
_runMonth();
}),
_makeScopeSelect(() => { _updateOutputBar(); _runMonth(); }),
);
widget.appendChild(right);
bar.appendChild(widget);
// ── Month navigation ──────────────────────────────────────
function _stepMonth(delta) {
st.displayMonth += delta;
if (st.displayMonth < 1) { st.displayMonth = 12; st.displayYear--; }
if (st.displayMonth > 12) { st.displayMonth = 1; st.displayYear++; }
_updateMonthLabel();
_renderGrid(); _updateOutputBar();
_loadNoteDays();
}
prevBtn.addEventListener('click', () => _stepMonth(-1));
nextBtn.addEventListener('click', () => _stepMonth(1));
// ── Select a day ──────────────────────────────────────────
function _selectDay(ds) {
st.selected = ds;
_renderGrid(); _updateOutputBar();
const s = st.start || ds;
const e = st.end || ds;
NbMain.runCal({ start: s, end: e, notebook: _scope });
}
// ── Run current display month ─────────────────────────────
function _runMonth() {
const y = st.displayYear, m = st.displayMonth;
const pfx = `${y}-${String(m).padStart(2,'0')}`;
const last = new Date(y, m, 0).getDate();
NbMain.runCal({ start: `${pfx}-01`, end: `${pfx}-${last}`, notebook: _scope });
}
// ── Load note-days for current month (async highlight) ────
async function _loadNoteDays() {
const y = st.displayYear, m = st.displayMonth;
const pfx = `${y}-${String(m).padStart(2,'0')}`;
const last = new Date(y, m, 0).getDate();
try {
const params = new URLSearchParams({
start: `${pfx}-01`, end: `${pfx}-${last}`,
notebook: (_scope && _scope !== '_all') ? _scope : 'home',
});
const r = await fetch('/api/cal?' + params);
const d = await r.json();
st.noteDays = new Set((d.entries || []).map(e => e.date));
_renderGrid();
} catch(_e) {}
}
_loadNoteDays();
// Show today's notes on open (or re-run the current selection)
_selectDay(st.selected || today);
// Enter key selects the currently highlighted day
_calKeyHandler = (e) => {
if (e.key !== 'Enter') return;
if (['INPUT','TEXTAREA','SELECT'].includes(document.activeElement?.tagName)) return;
e.preventDefault();
_selectDay(st.selected || today);
};
document.addEventListener('keydown', _calKeyHandler);
}
function _renderDailyOpts(bar) {
const st = _state.daily;
const label = document.createElement('span');
label.className = 'nb-opt-nav-label';
label.textContent = st.date || _t('label_today');
function step(d) {
const base = st.date ? new Date(st.date + 'T12:00:00') : new Date();
base.setDate(base.getDate() + d);
st.date = NbWeb.isoDate(base);
label.textContent = st.date;
_updateOutputBar(); _executeCmd();
}
const wrap = document.createElement('div');
wrap.className = 'nb-opts-nav';
wrap.append(
_makeNavBtn('◀', () => step(-1)),
label,
_makeNavBtn('▶', () => step(1)),
_makeChip(_t('label_today'), !st.date, () => {
st.date = ''; label.textContent = _t('label_today');
_updateOutputBar(); _executeCmd();
})
);
bar.appendChild(wrap);
}
function _renderGrepOpts(bar) {
const st = _state.g;
const patInput = document.createElement('input');
patInput.type = 'text';
patInput.className = 'nb-opt-input';
patInput.placeholder = 'pattern…';
patInput.value = st.pattern;
patInput.addEventListener('input', () => { st.pattern = patInput.value; _updateOutputBar(); });
patInput.addEventListener('keydown', e => { if (e.key === 'Enter') _executeCmd(); });
bar.appendChild(patInput);
bar.appendChild(_makeSep());
const allChip = _makeChip('--all', st.all, () => {
st.all = !st.all;
allChip.classList.toggle('active', st.all);
_updateOutputBar();
if (st.pattern) _executeCmd();
});
bar.appendChild(allChip);
bar.appendChild(_makeSep());
// Context lines stepper
const stepWrap = document.createElement('div');
stepWrap.className = 'nb-opts-stepper';
const ctxLbl = document.createElement('span');
ctxLbl.className = 'nb-step-label';
ctxLbl.textContent = `-C ${st.context}`;
ctxLbl.title = 'Context lines (before + after)';
const btnM = document.createElement('button'); btnM.className = 'nb-step-btn'; btnM.textContent = '−';
const btnP = document.createElement('button'); btnP.className = 'nb-step-btn'; btnP.textContent = '+';
btnM.addEventListener('click', () => { if (st.context > 0) { st.context--; st.before = st.after = st.context; } ctxLbl.textContent = `-C ${st.context}`; _updateOutputBar(); });
btnP.addEventListener('click', () => { if (st.context < 9) { st.context++; st.before = st.after = st.context; } ctxLbl.textContent = `-C ${st.context}`; _updateOutputBar(); });
stepWrap.append(btnM, ctxLbl, btnP);
bar.appendChild(stepWrap);
bar.appendChild(_makeSep());
const runBtn = document.createElement('button');
runBtn.className = 'nb-opt-chip nb-opt-run';
runBtn.textContent = _t('btn_run');
runBtn.addEventListener('click', _executeCmd);
bar.appendChild(runBtn);
requestAnimationFrame(() => patInput.focus());
}
function _renderTemplatesOpts(_bar) {
// All templates (notebook + global) are always shown; no scope filter needed.
}
// ── Helpers ───────────────────────────────────────────────────
function _typeArg(type) { return type !== 'all' ? `--type ${type}` : null; }
function _makeChipRow(items, activeVal, onChange) {
const row = document.createElement('div');
row.className = 'nb-opts-chips';
items.forEach(({ val, label, minLevel }) => {
if (minLevel && !window.NbAuth?.is(minLevel)) return;
const chip = _makeChip(label, val === activeVal, () => {
row.querySelectorAll('.nb-opt-chip').forEach(c => c.classList.remove('active'));
chip.classList.add('active');
onChange(val);
});
chip.title = val;
row.appendChild(chip);
});
return row;
}
function _makeChip(label, isActive, onClick) {
const btn = document.createElement('button');
btn.className = 'nb-opt-chip' + (isActive ? ' active' : '');
const m = label.match(/^(\S+)\s+(.+)$/);
if (m) {
btn.innerHTML = `${m[1]}<span class="nb-chip-label"> ${m[2]}</span>`;
} else {
btn.textContent = label;
}
btn.addEventListener('click', onClick);
return btn;
}
function _makeNavBtn(label, onClick) {
const btn = document.createElement('button');
btn.className = 'nb-opt-nav-btn';
btn.textContent = label;
btn.addEventListener('click', onClick);
return btn;
}
function _makeSep() {
const s = document.createElement('span');
s.className = 'nb-opts-sep';
s.setAttribute('aria-hidden', 'true');
return s;
}
// ── Output bar (omnipresent token bar) ───────────────────────
let _searchQuery = '';
let _tagsQuery = '';
// Build an ordered list of token descriptors for the current state.
// Tokens with a clearFn become filter chips with ×.
function _buildTokens() {
const cmd = _activeCmd;
const st = _state[cmd] || {};
const folder = _folder[cmd] || '';
const tokens = [];
// Helper: scope token (notebook + folder combined)
function _scopeTok() {
if (_scope === '_all') {
return { text: '--all', clearFn: () => {
_scope = 'home'; _executeCmd(); _updateOutputBar();
}};
}
if (_scope !== 'home' || folder) {
const t = folder ? `${_scope}:${folder}/` : `${_scope}:`;
return { text: t, clearFn: () => {
_scope = 'home'; _folder[cmd] = ''; updateBreadcrumb([]);
_executeCmd(); _updateOutputBar();
}};
}
return null;
}
// Helper: search token
function _searchTok() {
if (!_searchQuery) return null;
return { text: `"${_searchQuery}"`, clearFn: () => {
_searchQuery = '';
const el = document.getElementById('nb-search');
const cl = document.getElementById('nb-search-clear');
if (el) el.value = '';
if (cl) cl.hidden = true;
_executeCmd(); _updateOutputBar();
}};
}
// Helper: tags token
function _tagsTok() {
if (!_tagsQuery) return null;
return { text: `--tags ${_tagsQuery}`, clearFn: () => {
_tagsQuery = '';
const el = document.getElementById('nb-tags');
const cl = document.getElementById('nb-tags-clear');
if (el) el.value = '';
if (cl) cl.hidden = true;
_executeCmd(); _updateOutputBar();
}};
}
switch (cmd) {
case 'list': {
tokens.push({ text: 'list' });
const sc = _scopeTok(); if (sc) tokens.push(sc);
if (st.type && st.type !== 'all') {
const typeText = st.type === 'todo'
? `todo ${st.todoStatus || 'open'}`
: `--type ${st.type}`;