Repository navigation
Expand file tree
/
Copy pathnbweb.js
More file actions
1142 lines (1050 loc) · 51.5 KB
/
Copy pathnbweb.js
File metadata and controls
1142 lines (1050 loc) · 51.5 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 plugin host — NbWeb.registerModule() API
const NbWeb = (() => {
const _modules = new Map(); // name → { spec, enabled, activeNotebooks, error }
// FM keys declared by core and by plugins (scope → [keys]).
// 'core' is built-in; plugin names added via registerModule spec.fmKeys.
const _FM_KEYS_CORE = ['title', 'type', 'status', 'tags', 'access', 'alias',
'date', 'due', 'started', 'completed', 'project', 'draft', 'pinned',
'color', 'icon', 'template', 'renderer', 'related', 'description'];
const _fmKeysByScope = new Map([['core', _FM_KEYS_CORE]]);
// Per-notebook config cache: notebook → parsed meta dict from .<notebook>.md.
// Populated lazily by loadNotebookConfig(); stays warm until explicitly busted.
const _notebookTypeConfigs = new Map();
// Flat renderer registry — populated by registerRenderer() and auto-populated
// by registerModule() from previewRenderers[]/previewRenderer entries.
// id → { id, label, icon, types, detect, render, pluginName }
// types: string[] of note type values this renderer handles, or null for
// detect-only renderers (quartz items, path-based detection, etc.)
// detect: note → bool predicate kept for backward compat; used by
// getPreviewRenderers() runtime filtering. Not used by getRenderers().
const _rendererRegistry = new Map();
// ── Plugin loading ─────────────────────────────────────────────────────────
async function _loadScript(url) {
return new Promise((resolve, reject) => {
const s = document.createElement('script');
s.src = url;
s.onload = resolve;
s.onerror = () => reject(new Error(`Failed to load: ${url}`));
document.head.appendChild(s);
});
}
async function _loadPlugins() {
let plugins = [];
try {
const r = await fetch('/api/nb-settings');
plugins = (await r.json()).plugins || [];
} catch (e) {
console.warn('NbWeb: could not read plugin list from settings', e);
}
for (const p of plugins) {
if (p.enabled === false) continue;
try {
await _loadScript(p.url);
} catch (e) {
console.error(`NbWeb: failed to load plugin "${p.url}":`, e);
}
}
}
// ── Registration ───────────────────────────────────────────────────────────
// Explicit renderer registration — plugins may call this directly instead of
// embedding renderers inside registerModule(). Auto-registration from
// registerModule() calls this internally, so duplicate IDs are silently skipped.
function registerRenderer(id, spec) {
if (_rendererRegistry.has(id)) {
console.warn(`NbWeb: renderer "${id}" already registered — skipping`);
return;
}
_rendererRegistry.set(id, { id, ...spec });
}
function registerModule(name, spec) {
if (_modules.has(name)) {
console.warn(`NbWeb: module "${name}" already registered — skipping`);
return;
}
_modules.set(name, { spec, enabled: true, activeNotebooks: [], error: null });
if (spec.fmKeys?.length) _fmKeysByScope.set(name, spec.fmKeys);
if (spec.hideExtrasCSS) {
const style = document.createElement('style');
style.dataset.nbModule = name;
style.textContent = spec.hideExtrasCSS;
document.head.appendChild(style);
}
// Auto-register named previewRenderers into the flat registry.
for (const r of spec.previewRenderers ?? []) {
if (r.id) registerRenderer(r.id, { pluginName: name, ...r });
}
// Auto-register single previewRenderer as '<module>-preview'.
// Module spec may declare previewTypes: ['account'] to make the type
// association queryable; otherwise the renderer is detect-only.
if (spec.previewRenderer && !spec.previewRenderers?.length) {
registerRenderer(`${name}-preview`, {
label: spec.label ?? name,
icon: spec.icon ?? null,
pluginName: name,
types: spec.previewTypes ?? null,
detect: spec.previewRendererDetect ?? null,
render: spec.previewRenderer,
});
}
}
// ── i18n ─────────────────────────────────────────────────────────────────
let _locale = {};
let _localePromise = null;
async function loadLocale() {
if (_localePromise) return _localePromise;
_localePromise = fetch('/api/locale')
.then(r => r.json())
.then(data => { _locale = data; return data; })
.catch(() => { _locale = {}; return {}; });
return _localePromise;
}
// Translate key → locale string, falling back to the key itself.
function t(key) { return _locale[key] ?? key; }
// Apply data-i18n="key" translations to DOM; call after loadLocale().
// Handles text content and placeholder/title attributes.
function applyI18n(root) {
root = root || document;
root.querySelectorAll('[data-i18n]').forEach(el => {
const key = el.dataset.i18n;
if (!key) return;
if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
if (el.placeholder) el.placeholder = t(key);
} else {
el.textContent = t(key);
}
});
root.querySelectorAll('[data-i18n-title]').forEach(el => {
el.title = t(el.dataset.i18nTitle);
});
// Set <html lang=""> from locale meta
if (_locale._lang) document.documentElement.lang = _locale._lang;
if (_locale._dir) document.documentElement.dir = _locale._dir;
}
// ── Extras-hidden API ─────────────────────────────────────────────────────
// Returns true when the 👁 extras toggle is active (class on #nb-preview-content).
function isExtrasHidden() {
return document.getElementById('nb-preview-content')
?.classList.contains('nb-extras-hidden') ?? false;
}
// ── Initialisation (called after plugins are loaded) ───────────────────────
let _notebooks = []; // full notebook objects from /api/nb/notebooks
async function _init() {
try {
const r = await fetch('/api/nb/notebooks');
_notebooks = (await r.json()).notebooks || [];
} catch (e) {
console.warn('NbWeb: could not load notebooks for plugin detection', e);
}
for (const [name, mod] of _modules) {
if (!mod.enabled) continue;
try {
mod.activeNotebooks = mod.spec.detect
? ((await mod.spec.detect(_notebooks)) ?? [])
: _notebooks;
} catch (e) {
console.error(`NbWeb: detect() failed for module "${name}":`, e);
mod.activeNotebooks = [];
mod.error = e.message;
}
}
}
function notebooks() { return _notebooks; }
// ── Extension point queries ────────────────────────────────────────────────
function _activeFor(notebookName) {
const out = [];
for (const [name, mod] of _modules) {
if (!mod.enabled) continue;
if (mod.activeNotebooks.some(nb => nb.name === notebookName))
out.push({ name, ...mod.spec });
}
return out;
}
// Compat fallback — reached only when getPreviewRenderers() returns [] (i.e. a plugin
// has previewRenderer but no previewRendererDetect). All current plugins declare
// previewRendererDetect, so this path is never taken in practice. Candidate for
// removal once we're confident no external plugin omits the predicate.
function getPreviewRenderer(notebook) {
const active = _activeFor(notebook);
const multi = active.find(m => m.previewRenderers?.length);
if (multi) return note => {
const r = multi.previewRenderers.find(pr => !pr.detect || pr.detect(note));
if (r) return r.render(note);
// No multi-renderer claimed this note — fall through to single previewRenderer modules
// (e.g. specialty handles project/dotfile/dashboard in a cine notebook)
for (const m of active) {
if (!m.previewRenderers && m.previewRenderer) {
const html = m.previewRenderer(note);
if (html != null) return html;
}
}
return null;
};
// No multi-renderer module active — chain through all single-previewRenderer modules.
// (Returning only the first module's fn breaks when that module returns null for
// the current note type, e.g. contacts returns null for project notes.)
return note => {
for (const m of active) {
if (!m.previewRenderers && m.previewRenderer) {
const html = m.previewRenderer(note);
if (html != null) return html;
}
}
return null;
};
}
// Fetch and cache the parsed meta from .<notebook>.md.
// Safe to call every render — resolves immediately on cache hit.
async function loadNotebookConfig(notebook) {
if (!notebook || _notebookTypeConfigs.has(notebook))
return _notebookTypeConfigs.get(notebook) || {};
try {
const r = await fetch(`/api/nb/notebook-config?notebook=${encodeURIComponent(notebook)}`);
const d = await r.json();
const cfg = d.meta || {};
_notebookTypeConfigs.set(notebook, cfg);
return cfg;
} catch (_) {
_notebookTypeConfigs.set(notebook, {});
return {};
}
}
// Synchronous read from the already-primed cache; returns {} if not loaded.
// Always call loadNotebookConfig first to warm the cache.
function getCachedNotebookConfig(notebook) {
return _notebookTypeConfigs.get(notebook) || {};
}
// Bust the cache for a notebook — call after saving type config so the next
// render re-fetches.
function bustNotebookConfigCache(notebook) {
_notebookTypeConfigs.delete(notebook);
}
// Returns all renderers for the given notebook + note, across all active modules.
// Collects from two sources in plugin-load order:
// 1. previewRenderers[] arrays (multi-renderer modules, e.g. cine)
// 2. previewRenderer + previewRendererDetect pairs (single-renderer modules, e.g. specialty)
// Modules with only previewRenderer and no previewRendererDetect are excluded here;
// they remain reachable via getPreviewRenderer()'s chain fallback.
// If the notebook config has a types[note.type].renderer preference, that renderer
// is promoted to first (becoming the toggle default).
function getPreviewRenderers(notebook, note) {
const active = _activeFor(notebook);
const renderers = [];
for (const m of active) {
if (m.previewRenderers?.length) {
renderers.push(...m.previewRenderers.filter(r => !r.detect || r.detect(note)));
} else if (m.previewRenderer && m.previewRendererDetect?.(note)) {
renderers.push({
id: `${m.name}-preview`,
icon: m.icon ?? null,
label: m.label ?? m.name,
render: m.previewRenderer,
});
}
}
if (!renderers.length) return renderers;
const preferredId = _notebookTypeConfigs.get(notebook)?.types?.[note?.type]?.renderer;
if (preferredId) {
const preferred = renderers.find(r => r.id === preferredId);
if (preferred)
return [preferred, ...renderers.filter(r => r.id !== preferredId)];
}
return renderers;
}
// Returns registered renderers from the flat registry, optionally filtered by
// note type. type=undefined → all renderers. type='shot' → renderers whose
// types[] includes 'shot' (detect-only renderers with types:null are excluded
// from typed queries but appear in the full list).
// Used by the Configure Notebook UI to populate type→renderer dropdowns.
function getRenderers(type) {
const all = [..._rendererRegistry.values()];
if (type === undefined) return all;
return all.filter(r => Array.isArray(r.types) && r.types.includes(type));
}
// Returns every type string declared across all registered renderers.
// Useful for building the full type list in the config UI.
function getRendererTypes() {
const types = new Set();
for (const r of _rendererRegistry.values()) {
if (Array.isArray(r.types)) r.types.forEach(t => types.add(t));
}
return [...types].sort();
}
// Returns only type strings from renderers whose plugin is active for this notebook.
// Used by the Configure Notebook types table so cine types don't appear in non-cine notebooks.
function getRendererTypesForNotebook(notebookName) {
const activePlugins = new Set(_activeFor(notebookName).map(m => m.name ?? ''));
// Always include global plugins (no detect) — they have no pluginName restriction
const types = new Set();
for (const r of _rendererRegistry.values()) {
if (!Array.isArray(r.types)) continue;
if (!r.pluginName || activePlugins.has(r.pluginName)) {
r.types.forEach(t => types.add(t));
}
}
return [...types].sort();
}
// Returns all custom sort options from plugins active for this notebook.
// Each entry: { id, label, sort(notes) → notes[] }
function getSortOptions(notebookName) {
return _activeFor(notebookName).flatMap(m => m.sortOptions ?? []);
}
function getListExcerpt(notebook) {
return _activeFor(notebook).find(m => m.listExcerpt)?.listExcerpt ?? null;
}
// listItemIcon(notebook) → fn(note) → string|null — plugin icon override per note
function getListItemIcon(notebook) {
return _activeFor(notebook).find(m => m.listItemIcon)?.listItemIcon ?? null;
}
// listTitle — notebook-specific fn(note) → string|null for custom list display titles
function getListTitle(notebookName) {
return _activeFor(notebookName).find(m => m.listTitle)?.listTitle ?? null;
}
// listButtons — notebook-specific, injected into the List panel toolbar
function getListButtons(notebook) {
return _activeFor(notebook).flatMap(m => m.listButtons ?? m.toolbarButtons ?? []);
}
// pluginContentModules — active modules that have a pluginContent fn (for panel toggle)
function getPluginContentModules(notebook) {
return _activeFor(notebook).filter(m => m.pluginContent);
}
// navButtons — global, injected into the main nav (#nb-cmds-plugins)
function getNavButtons() {
const seen = new Set();
return [..._modules.values()]
.filter(mod => mod.enabled)
.flatMap(mod => mod.spec.navButtons ?? [])
.filter(btn => seen.has(btn.id) ? false : seen.add(btn.id));
}
function getAddFormExtras(notebook) {
return _activeFor(notebook).find(m => m.addFormExtras)?.addFormExtras ?? null;
}
// ── Template API ──────────────────────────────────────────────────────────────
// Returns ALL plugin templates from every enabled module, always.
// scope is context (default placement), not a visibility gate.
// activeForNotebook:true when the module's detect() matched this notebook.
function getTemplatesForNotebook(notebookName) {
const out = [];
for (const [name, mod] of _modules) {
if (!mod.enabled || !mod.spec.templates?.length) continue;
const isActive = mod.activeNotebooks.some(nb => nb.name === notebookName);
const moduleLabel = mod.spec.label ?? name;
mod.spec.templates.forEach(t => {
out.push({ moduleName: name, moduleLabel, activeForNotebook: isActive, ...t });
});
}
return out;
}
// Returns non-singleton templates with scope:'notebook' from modules active for this notebook.
// Used to populate the DEFAULTS section in the Notebooks panel.
function getScopedTemplatesForNotebook(notebookName) {
return _activeFor(notebookName).flatMap(m => {
if (!m.templates?.length) return [];
return m.templates
.filter(t => t.scope === 'notebook' && !t.singleton)
.map(t => ({ moduleName: m.name, moduleLabel: m.label ?? m.name, ...t }));
});
}
// Compute the path relative to the notebook root where a template is written.
// Singletons land in the root; scoped templates land in .templates/ subdirectories.
function templateRelPath(template) {
const fname = template.filename
|| (template.name.toLowerCase().replace(/\s+/g, '_') + '.md');
const scope = template.scope || '';
if (scope.startsWith('folder:')) return `${scope.slice(7)}/.templates/${fname}`;
if (scope === 'notebook') return `.templates/${fname}`;
return fname;
}
// Write a template to disk. Scope determines the target directory:
// '' → notebook root (singleton note, indexed by nb)
// 'notebook' → notebook/.templates/
// 'folder:X' → notebook/X/.templates/
// 409 = already exists — safe, never overwrites.
async function createFromTemplate(template, notebookObj) {
const filename = template.filename
|| (template.name.toLowerCase().replace(/\s+/g, '_') + '.md');
if (!filename) {
console.error('NbWeb.createFromTemplate: could not derive filename');
return { ok: false, error: 'no filename' };
}
const content = typeof template.content === 'function'
? template.content(notebookObj)
: template.content;
try {
const r = await fetch('/api/nb/create-from-template', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
notebook: notebookObj.name,
filename,
content,
scope: template.scope || '',
}),
});
return await r.json(); // { ok, error? }
} catch (e) {
return { ok: false, error: e.message };
}
}
// Check whether a singleton file exists in a notebook root.
async function singletonExists(notebookName, filename) {
try {
const r = await fetch(
`/api/nb/file-exists?notebook=${encodeURIComponent(notebookName)}&filename=${encodeURIComponent(filename)}`
);
return (await r.json()).exists === true;
} catch (_) {
return false;
}
}
// Check whether any template (singleton or scoped) has been written for a notebook.
async function templateSeeded(notebookName, template) {
const relpath = templateRelPath(template);
try {
const r = await fetch(
`/api/nb/file-exists?notebook=${encodeURIComponent(notebookName)}&relpath=${encodeURIComponent(relpath)}`
);
return (await r.json()).exists === true;
} catch (_) {
return false;
}
}
// ── Requirements checking ─────────────────────────────────────────────────────
const _whichCache = new Map();
async function checkWhich(cmd) {
if (_whichCache.has(cmd)) return _whichCache.get(cmd);
try {
const r = await fetch(`/api/which?cmd=${encodeURIComponent(cmd)}`).then(x => x.json());
_whichCache.set(cmd, r);
return r;
} catch (_) {
const result = { found: false, path: null };
_whichCache.set(cmd, result);
return result;
}
}
async function renderRequirementsCard(container, mdOrPath) {
let md = mdOrPath;
if (typeof mdOrPath === 'string' && (mdOrPath.startsWith('/') || mdOrPath.endsWith('.md'))) {
try {
const r = await fetch(mdOrPath);
md = r.ok ? await r.text() : `# Requirements not met\n\nCould not load: \`${mdOrPath}\``;
} catch (_) {
md = `# Requirements not met\n\nCould not load: \`${mdOrPath}\``;
}
}
const html = typeof marked !== 'undefined' ? marked.parse(md) : `<pre>${md.replace(/&/g,'&').replace(/</g,'<')}</pre>`;
container.innerHTML = `<div class="nb-requirements-card">${html}</div>`;
}
// ── Editor keybinding API ─────────────────────────────────────────────────────
// Returns keybinding specs from all modules active for the note's notebook.
// Each spec: { key, ctrl, shift, alt, label, action(textarea, note) }
function getEditorKeybindings(note) {
const nb = note?.notebook || '';
const out = [];
for (const mod of _activeFor(nb)) {
const kb = mod.editorKeybindings;
if (typeof kb === 'function') out.push(...(kb(note) || []));
else if (Array.isArray(kb)) out.push(...kb);
}
return out;
}
// ── Codeblock renderer API ────────────────────────────────────────────────────
// Returns the renderer spec { html(text), render(container) } for a fence language, or null.
function getCodeblockRenderer(lang) {
for (const [, mod] of _modules) {
if (!mod.enabled) continue;
const r = mod.spec.codeblockRenderers?.find(r => r.lang === lang);
if (r) return r;
}
return null;
}
// Runs all registered render(container) functions for all enabled codeblock plugins.
async function renderCodeblocks(container) {
for (const [, mod] of _modules) {
if (!mod.enabled || !mod.spec.codeblockRenderers?.length) continue;
for (const r of mod.spec.codeblockRenderers) {
if (r.render) await r.render(container);
}
}
}
// notebookSection — appended to the Notebooks detail panel for each active plugin
function getNotebookSections(notebookObj) {
return _activeFor(notebookObj.name).flatMap(m => {
if (!m.notebookSection) return [];
try {
const s = m.notebookSection(notebookObj);
return s ? [{ moduleName: m.name, ...s }] : [];
} catch (e) {
console.error(`NbWeb: notebookSection() failed for module "${m.name}":`, e);
return [];
}
});
}
// ── Publish check gate (check sweep v2, step 4) ─────────────────────────────
// Before publishing, sweep the notebook's changed notes. Clean -> carry on.
// Errors/warnings -> a dialog: "Fix first" (default, also Escape) or "Publish
// anyway". A soft gate: if the sweep itself can't run, publishing goes ahead
// -- a broken check system must never block a publish. Resolves true to publish.
// Design: claude:check_sweep_v2_design_2026-10-02.
async function _sweepBeforePublish(notebook) {
try {
const r = await fetch('/api/check/sweep', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ notebook, mode: 'changed' }),
});
const d = await r.json();
if (r.status === 409) return d.result || null; // already running: last stored result
return r.ok ? d : null;
} catch (_) {
return null;
}
}
// "### ⚠ Broken thing" / "**Broken** thing" -> "Broken thing" for display.
function _plainCheckMessage(msg) {
return String(msg || '').replace(/^#+\s*/, '').replace(/^⚠\s*/, '').replace(/\*\*/g, '').trim();
}
// Shared by the publish dialog and the Notebooks page's Checks section.
// Returns { el: <ul>, errors, warnings, skipped }; el lists errors then
// warnings (notebook-wide findings with their note count; each note a link
// that calls onNoteOpen(selector) -- the caller decides what else happens).
function renderCheckFindings(notebook, result, onNoteOpen) {
const LEVEL_ORDER = { error: 0, warn: 1 };
const all = [
...(result?.notebook_findings || []).map(f => ({ ...f, path: null })),
...(result?.note_findings || []),
];
const items = all.filter(f => f.level in LEVEL_ORDER)
.sort((a, b) => LEVEL_ORDER[a.level] - LEVEL_ORDER[b.level]);
const plural = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`;
const noteLink = f => {
const a = document.createElement('a');
a.href = '#';
a.textContent = f.path;
a.addEventListener('click', e => { e.preventDefault(); onNoteOpen(`${notebook}:${f.path}`); });
return a;
};
const checkName = s => String(s || '').replace(/\.sh$/, '');
// Grouped by check (2026-10-07): notebook-wide findings first, then one row per check
// and level -- most notes first -- opening to its notes. Nothing is cut off: grouped,
// even a big notebook's list is short (it used to stop at 25 rows, one per note).
const list = document.createElement('ul');
list.className = 'nb-publish-gate-list';
for (const f of items.filter(f => !f.path)) {
const li = document.createElement('li');
li.className = `nb-publish-gate-item ${f.level}`;
// a notebook-wide check runs once for the whole notebook; a note count says nothing
li.textContent = `${_plainCheckMessage(f.message)} (${checkName(f.script)}, whole notebook)`;
list.appendChild(li);
}
const groups = new Map();
for (const f of items.filter(f => f.path)) {
const key = `${f.level}|${f.script}`;
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(f);
}
const ordered = [...groups.values()].sort((a, b) =>
(LEVEL_ORDER[a[0].level] - LEVEL_ORDER[b[0].level]) || (b.length - a.length));
for (const g of ordered) {
const first = g[0];
const li = document.createElement('li');
li.className = `nb-publish-gate-item ${first.level}`;
const label = first.script === 'config' ? 'config' : checkName(first.script);
if (g.length === 1) {
li.appendChild(noteLink(first));
li.append(` — ${_plainCheckMessage(first.message)} (${label})`);
} else {
const det = document.createElement('details');
det.className = 'nb-check-group';
const sum = document.createElement('summary');
sum.textContent = `${_plainCheckMessage(first.message)} (${label}, ${plural(g.length, 'note')})`;
det.appendChild(sum);
const ul = document.createElement('ul');
for (const f of g) {
const row = document.createElement('li');
row.appendChild(noteLink(f));
const msg = _plainCheckMessage(f.message);
if (msg !== _plainCheckMessage(first.message)) row.append(` — ${msg}`);
ul.appendChild(row);
}
det.appendChild(ul);
li.appendChild(det);
}
list.appendChild(li);
}
const errors = items.filter(f => f.level === 'error').length;
return { el: list, errors, warnings: items.length - errors,
skipped: all.filter(f => f.level === 'skipped').length };
}
function _publishGate(notebook, result) {
const plural = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`;
return new Promise(resolve => {
const found = renderCheckFindings(notebook, result, sel => {
close(false);
NbMain.openNote(sel);
});
if (!found.errors && !found.warnings) { resolve(true); return; }
const { el: list, errors: nErr, warnings: nWarn, skipped } = found;
const overlay = document.createElement('div');
overlay.className = 'nb-publish-gate-overlay';
const card = document.createElement('div');
card.className = 'nb-publish-gate-card';
card.setAttribute('role', 'dialog');
card.setAttribute('aria-modal', 'true');
const h = document.createElement('h4');
h.textContent = `Checks found problems in ${notebook}`;
const summary = document.createElement('p');
summary.className = 'nb-publish-gate-summary';
summary.textContent = [nErr && plural(nErr, 'error'), nWarn && plural(nWarn, 'warning')]
.filter(Boolean).join(', ') + '.';
card.append(h, summary, list);
if (skipped) {
const note = document.createElement('p');
note.className = 'nb-publish-gate-note';
note.textContent = `${plural(skipped, 'check')} timed out; ${skipped === 1 ? 'it' : 'they'} will run in the nightly sweep.`;
card.appendChild(note);
}
const btns = document.createElement('div');
btns.className = 'nb-publish-gate-btns';
const fix = document.createElement('button');
fix.type = 'button';
fix.className = 'nb-tool-btn nb-publish-gate-fix';
fix.textContent = 'Fix first';
const anyway = document.createElement('button');
anyway.type = 'button';
anyway.className = 'nb-tool-btn nb-publish-gate-anyway';
anyway.textContent = 'Publish anyway';
btns.append(fix, anyway);
card.appendChild(btns);
overlay.appendChild(card);
document.body.appendChild(overlay);
function close(proceed) {
overlay.remove();
resolve(proceed);
}
fix.addEventListener('click', () => close(false));
anyway.addEventListener('click', () => close(true));
overlay.addEventListener('click', e => { if (e.target === overlay) close(false); });
overlay.addEventListener('keydown', e => {
if (e.key === 'Escape') {
// Don't let Escape reach ui-chrome.js's document-level handler
// (invariant 60).
e.stopPropagation();
close(false);
}
});
// Focus inside the dialog at once, so Escape lands here (invariant 60);
// the safe choice is the default.
fix.focus();
});
}
// ── Shared publish helper (used by toolbar buttons + settings panel) ──────────
async function publishWebsite(notebook, btn) {
const origText = btn.textContent;
const origTitle = btn.title;
btn.disabled = true;
btn.textContent = '⏳';
btn.title = 'Checking…';
const chip = document.createElement('span');
chip.className = 'nbweb-publish-chip';
chip.textContent = 'checking…';
btn.insertAdjacentElement('afterend', chip);
const sweep = await _sweepBeforePublish(notebook);
if (sweep && !(await _publishGate(notebook, sweep))) {
chip.remove();
btn.textContent = origText;
btn.title = origTitle;
btn.disabled = false;
return;
}
btn.title = 'Publishing…';
chip.textContent = 'pushing…';
const finish = (text, ms = 5000) => {
chip.textContent = text;
setTimeout(() => {
chip.remove();
btn.textContent = origText;
btn.title = origTitle;
btn.disabled = false;
}, ms);
};
try {
const r = await fetch('/api/website/publish', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ notebook }),
}).then(x => x.json());
if (!r.ok) { finish(`✗ ${r.output?.split('\n')[0] ?? 'failed'}`, 8000); return; }
if (!r.run_id) { finish('✓ triggered'); return; }
chip.textContent = '⏳ building…';
btn.title = 'Building…';
const start = Date.now();
const repo = encodeURIComponent(r.github_repo);
const timer = setInterval(async () => {
const elapsed = Math.round((Date.now() - start) / 1000);
if (elapsed > 300) {
clearInterval(timer);
finish('⚠ timed out', 8000);
return;
}
try {
const s = await fetch(
`/api/website/build-status?run_id=${r.run_id}&repo=${repo}`
).then(x => x.json());
if (s.status !== 'completed') {
chip.textContent = `⏳ ${elapsed}s`;
return;
}
clearInterval(timer);
finish(s.conclusion === 'success'
? `✓ built in ${elapsed}s`
: `✗ build failed`, s.conclusion === 'success' ? 5000 : 10000);
} catch (_) { /* transient, keep polling */ }
}, 6000);
} catch (e) {
finish('✗ ' + e.message, 8000);
}
}
// ── Plugin manager API (for the Plugins page UI) ───────────────────────────
function list() {
return [..._modules.entries()].map(([name, mod]) => ({
name,
enabled: mod.enabled,
global: !mod.spec.detect,
activeNotebooks: mod.activeNotebooks.map(nb => nb.name),
error: mod.error,
spec: mod.spec,
}));
}
function setEnabled(name, enabled) {
if (_modules.has(name)) _modules.get(name).enabled = enabled;
}
function unregister(name) {
_modules.delete(name);
}
// ── Terminal API ──────────────────────────────────────────────────────────────
// Delegates to NbTerminal (defined in terminal.js). Plugins should always call
// NbWeb.runInTerminal() rather than NbTerminal directly — this indirection
// keeps NbTerminal an implementation detail and gives a stable plugin API.
function runInTerminal(cmd) {
if (typeof NbTerminal !== 'undefined') return NbTerminal.run(cmd);
console.warn('NbWeb.runInTerminal: NbTerminal not available');
}
// Returns key list for a scope name, or null meaning "no filter / show all".
function getFmKeysForScope(scope) {
if (!scope || scope === 'all') return null;
return _fmKeysByScope.has(scope) ? [..._fmKeysByScope.get(scope)] : [];
}
function openTerminal() {
if (typeof NbTerminal !== 'undefined') return NbTerminal.open();
console.warn('NbWeb.openTerminal: NbTerminal not available');
}
// In-note forms share the editor's Save/Cancel (2026-10-14, djp): a right-aligned row, Save
// coloured (nb-btn-primary) and Cancel outlined, both nb-tool-btn like #nb-editor-toolbar.
// formActions builds the row; formKeys makes Ctrl/Cmd+Enter click Save and Escape click Cancel
// inside `root`, stopping the event so ui-chrome's global Escape (which clicks the first
// visible "Cancel" anywhere on the page) can't cancel some other form. e2e form-actions.spec.js.
function formActions({ saveLabel, cancelLabel, onSave, onCancel } = {}) {
const row = document.createElement('div');
row.className = 'nb-form-actions';
const saveBtn = document.createElement('button');
saveBtn.type = 'button';
saveBtn.className = 'nb-tool-btn nb-btn-primary';
saveBtn.textContent = saveLabel || t('btn_save');
row.appendChild(saveBtn);
let cancelBtn = null;
if (onCancel !== null) {
cancelBtn = document.createElement('button');
cancelBtn.type = 'button';
cancelBtn.className = 'nb-tool-btn';
cancelBtn.textContent = cancelLabel || t('btn_cancel');
row.appendChild(cancelBtn);
}
if (onSave) saveBtn.addEventListener('click', onSave);
if (onCancel) cancelBtn.addEventListener('click', onCancel);
return { row, saveBtn, cancelBtn };
}
// Save is only bright once there's something to save (2026-10-14, djp): until then it carries
// nb-clean and looks like a block's + (styles.css). It still works either way.
function formDirty(btnOrRoot, dirty = true) {
const btn = btnOrRoot?._nbFormBtns ? btnOrRoot._nbFormBtns.saveBtn : btnOrRoot;
btn?.classList.toggle('nb-clean', !dirty);
}
// A root reused for a rebuilt form (the toolbar's FM panel) gets the new buttons; the one
// listener always clicks whichever are current. Typing or changing anything inside marks
// Save dirty; a form whose other edits fire no input event calls formDirty(root) itself.
// Unsaved-changes policy (2026-10-14, djp): a visible form whose Save is lit counts as unsaved
// work, so switching notes asks and closing the tab warns (NbMain._hasUnsaved). Forms register
// here through formKeys; a cancelled (hidden or removed) form drops out by itself.
const _formRoots = new Set();
function unsavedForms() {
return [..._formRoots].filter(root => {
if (!root.isConnected) { _formRoots.delete(root); return false; }
const s = root._nbFormBtns?.saveBtn;
return !!s && s.isConnected && !s.classList.contains('nb-clean') && s.checkVisibility();
});
}
function formKeys(root, saveBtn, cancelBtn) {
if (!root) return;
_formRoots.add(root);
root._nbFormBtns = { saveBtn, cancelBtn };
formDirty(saveBtn, false);
if (root.dataset.formKeys) return;
root.dataset.formKeys = '1';
const markDirty = () => formDirty(root);
root.addEventListener('input', markDirty);
root.addEventListener('change', markDirty);
root.addEventListener('keydown', e => {
const { saveBtn: s, cancelBtn: c } = root._nbFormBtns || {};
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey) && s && !s.disabled && s.isConnected) {
e.preventDefault(); e.stopPropagation();
s.click();
} else if (e.key === 'Escape' && c && c.isConnected) {
e.preventDefault(); e.stopPropagation();
c.click();
}
});
}
// A date as local YYYY-MM-DD. Never the first ten characters of toISOString(): that's the UTC date, already
// tomorrow from 20:00 in Toronto (2026-10-07; nb-web-tests/test_local_dates.py).
function isoDate(d = new Date()) {
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}
// ── choose(): one small modal for "which of these?" (djp 2026-11-04) ──────
// The shared overlay helper (M7 (c) wants the same): a title, a line or two of body, a
// button per choice, Cancel. Resolves to the chosen value, or null (Cancel, Escape, the
// backdrop). Takes focus when it opens, on the default choice; every key stops here (invariant
// 60: ui-chrome's global Escape clicks any "Cancel", and its Enter would take the key from the
// focused button). Theme colours only (invariant 64).
// const v = await NbWeb.choose({ title, body, choices: [{ label, value, primary, danger, hint }] });
// tw-nb-interop M7 (a): what of Taskwarrior is here, asked before acting, so a feature takes
// the path that works and says plainly what's missing (one answer, one wording).
// {task: {ok, version, error}, nb: {ok}, plugin: {ok}, twWeb: {state: up|down|unset, url}}.
// The server answers for task/nb/plugin; tw-web is probed from here, since tw_web_url is the
// browser's address (from the container, localhost is the container). Cached 30 s.
const TW_MISSING = {
task: "Taskwarrior isn't available here",
plugin: "nb's tw plugin isn't installed here",
down: "tw-web isn't running",
unset: "tw-web isn't set up here (tw_web_url)",
};
let _twHealth = null, _twHealthAt = 0;
// This device's own address for tw-web, when the server's doesn't work from here (djp
// 2026-11-05: the phone reaches yoga's nb-web over Tailscale, but tw_web_url names yoga's
// localhost). Kept in this browser only; it wins over tw_web_url for every link to tw-web.
const TW_WEB_HERE_KEY = 'nb-tw-web-here';
const _WEB_ADDR_RE = /^https?:\/\/[^\s"'<>`]+$/;
function twWebHere() {
try { const v = localStorage.getItem(TW_WEB_HERE_KEY) || ''; return _WEB_ADDR_RE.test(v) ? v : ''; }
catch { return ''; }
}
function setTwWebHere(url) {
try { url ? localStorage.setItem(TW_WEB_HERE_KEY, url) : localStorage.removeItem(TW_WEB_HERE_KEY); } catch {}
_twHealth = null;
document.dispatchEvent(new CustomEvent('nb-tw-web-here'));
}
async function _probeTwWeb(url) {
if (!url) return 'unset';
const ctl = new AbortController();
const timer = setTimeout(() => ctl.abort(), 2500); // over Tailscale 0.8 s ran out (s5, 2026-11-05)
try {
const ping = new URL('api/ping', url.endsWith('/') ? url : url + '/');
// no-cors: another origin answers opaquely, which still means it's up
await fetch(ping, { mode: ping.origin === location.origin ? 'same-origin' : 'no-cors',
cache: 'no-store', credentials: 'omit', signal: ctl.signal });
return 'up';
} catch { return 'down'; }
finally { clearTimeout(timer); }
}
function twHealth({ fresh = false } = {}) {
if (!fresh && _twHealth && Date.now() - _twHealthAt < 30_000) return _twHealth;
_twHealthAt = Date.now();
_twHealth = (async () => {
let d = {};
try {
const r = await fetch('/api/tw/health');
if (r.ok) d = await r.json();
} catch { /* offline: reported as unknown below */ }
const serverUrl = d.tw_web_url || '';
const here = twWebHere();
const url = here || serverUrl;
return {
task: d.task || { ok: false, version: '', error: TW_MISSING.task },
nb: d.nb || { ok: false },
plugin: d.plugin || { ok: false },
twWeb: { state: await _probeTwWeb(url), url, serverUrl, here: !!here },
};
})();
return _twHealth;
}
// With `input: {value, placeholder, label}` it also shows a text field (focused, Enter picks
// the primary choice) and resolves {value, text} instead of the bare value.
// Switch to tw-web (the menu link, W): same tab, so Back returns, but only once it answers.
// When it doesn't, say so and take this device's address instead of leaving a dead page.
// `serverUrl`: the server's tw_web_url, as the caller already has it.
// Before asking, in order (djp 2026-11-05): this device's address, the server's, this
// device's own tw-web (localhost:5000: the phone's in Termux), and tw-web's usual port where
// this page is (yoga without the bundle, or over Tailscale). Own before the page's: from the
// phone, the page's was yoga's tw-web. All probed at once, the first that answers wins; a
// fallback isn't saved, so the bundle is used again once it's back.
function _twWebCandidates(serverUrl) {
const own = `${location.protocol}//${location.hostname}:5000/`;
const all = [twWebHere(), serverUrl, 'http://localhost:5000/', own].filter(u => u && _WEB_ADDR_RE.test(u));
return [...new Set(all.map(u => u.replace(/\/?$/, '/')))];
}
async function goTwWeb(serverUrl) {
const slash = u => u.replace(/\/?$/, '/');
const url = twWebHere() || serverUrl || '';
const tries = _twWebCandidates(serverUrl).map(u => ({ u, up: _probeTwWeb(u) }));
for (const t of tries) if (await t.up === 'up') { location.href = t.u; return; }
let why = url ? `tw-web doesn't answer at ${url} from this device, nor at its usual port.`
: "tw-web's address isn't set, and it doesn't answer at its usual port.";
let text = url;
for (;;) {
const choices = [{ label: 'Save and go', value: 'save', primary: true }];
if (twWebHere()) choices.push({ label: "Use the server's address", value: 'server',
hint: serverUrl || 'none set' });
const v = await choose({
title: 'tw-web',
body: [why, "If it runs somewhere else from here (this phone's own, say), give that " +
'address. It is kept in this browser only.'],