-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
7435 lines (6669 loc) · 320 KB
/
Copy pathapp.js
File metadata and controls
7435 lines (6669 loc) · 320 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
// app.js — Webwarrior entry point
// All data stays in the browser. No network requests after page load.
import { ensureDefaultProfile, listProfiles, createProfile, deleteProfile, getActive, setActive, getJournals, addJournal, getLedgers, addLedger, getUdaKeys, addUdaKey, getTaskLists, addTaskList, removeTaskList, getTimeLogs, addTimeLog, removeTimeLog, getQuestionLists, addQuestionList, removeQuestionList } from './storage/profiles.js';
import * as _Tasks from './services/tasks/index.js';
import * as _Time from './services/time/index.js';
import * as _Journal from './services/journal/index.js';
import * as _Ledger from './services/ledger/index.js';
import * as _Lists from './services/lists/index.js';
import * as Next from './services/next/index.js';
import * as Warrior from './services/warrior/index.js';
import * as _Questions from './services/questions/index.js';
import * as _Community from './services/community/index.js';
import * as Export from './services/export/index.js';
import * as _Attributes from './services/attributes/index.js';
import * as Render from './ui/render.js';
import { Terminal } from './ui/terminal.js';
import { showToast, confirm, promptText } from './ui/modals.js';
import { importFromFolder, loadDemoData } from './storage/import.js';
import * as Stream from './services/stream/index.js';
import { renderLens, setAsciiMode, renderComparison } from './services/stream/render.js';
import { registerAll as streamRegisterAll } from './services/stream/intercept.js';
import { computeRegeneration } from './services/stream/regen.js';
import * as Viz from './services/viz/index.js';
import * as Gallery from './services/viz/gallery.js';
import { initWorksListener, notifyProfileChange, closeWorksListener } from './services/works-bridge/listener.js';
// ── Service proxies (intercepted when Stream is active) ──────────────────────
// These start as the raw modules, then get replaced with intercepted versions at boot.
let Tasks = _Tasks;
let Time = _Time;
let Journal = _Journal;
let Ledger = _Ledger;
let Lists = _Lists;
let Questions = _Questions;
let Community = _Community;
let Attributes = _Attributes;
// ── State ────────────────────────────────────────────────────────────────────
let activeSection = 'tasks';
let activeProfile = null;
let taskGroupMode = false;
let taskShowDone = false;
let taskShowAnns = true;
let bulkSelected = new Set();
let activeTaskList = 'main';
let activeTimeLog = 'main';
let activeJournal = 'main';
let journalTheme = 'default';
let journalFilterMode = 'all';
let twainRecentSections = [];
let twainRecentTags = [];
let twainHiddenSections = new Set();
let twainSectionsCollapsed = false;
let twainTagsCollapsed = false;
let journalShowMd = false;
let journalShowArchived = false;
let timeTagFilter = '';
let timeDateRange = 'all';
let activeLedger = 'main';
let activeReport = 'balance';
let filterText = '';
let ledgerSearchText = '';
let streamActiveFilter = null;
let streamCustomFrom = null;
let streamCustomTo = null;
let tagsSort = 'name';
let functionsLocked = false;
const scrollPositions = new Map();
const terminal = new Terminal({
onNavigate: (section) => showSection(section),
onCommand: (cmd) => handleCommand(cmd),
onFilter: (q) => applyFilter(q),
});
// ── Boot ─────────────────────────────────────────────────────────────────────
async function boot() {
activeProfile = await ensureDefaultProfile();
journalTheme = localStorage.getItem('ww_journal_theme') || 'default';
terminal.init();
terminal.setProfile(activeProfile);
initBroadcastChannel();
updateHeader();
wireSidebar();
wireProfileSwitcher();
wireTaskDrawer();
wireJournalDrawer();
wireLedgerDrawer();
wireTimeDrawer();
wireTaskSection();
wireTimeSection();
wireJournalSection();
wireLedgerSection();
wireListsSection();
wireTagsSection();
wireVizSection();
wireAttributesSection();
wireNextSection();
wireWarriorSection();
wireCommunitySection();
wireQuestionsSection();
wireProjectsSection();
wireExportSection();
wireImportSection();
wireProfileSection();
wireCtrlSection();
wireDensity();
wireHelpClose();
wireWelcome();
await showSection(activeSection, { noScroll: true });
updateStat();
// Initialize Stream service (non-blocking — stream is additive)
try {
await Stream.init(activeProfile);
// Load config to pass gap_threshold to intercept layer
const streamConfig = await Stream.getConfig(activeProfile);
// Replace service references with intercepted versions
const wrapped = streamRegisterAll(activeProfile, {
tasks: _Tasks, time: _Time, journal: _Journal, ledger: _Ledger,
lists: _Lists, questions: _Questions, community: _Community, attributes: _Attributes,
}, { gapThreshold: streamConfig.gap_threshold || 300 });
if (wrapped.tasks) Tasks = wrapped.tasks;
if (wrapped.time) Time = wrapped.time;
if (wrapped.journal) Journal = wrapped.journal;
if (wrapped.ledger) Ledger = wrapped.ledger;
if (wrapped.lists) Lists = wrapped.lists;
if (wrapped.questions) Questions = wrapped.questions;
if (wrapped.community) Community = wrapped.community;
if (wrapped.attributes) Attributes = wrapped.attributes;
// Set up live mini waveform subscription
initMiniWaveform();
// Task 31: Check if read-only (another tab owns the stream)
if (Stream.isReadOnly()) {
showToast('Stream active in another tab (read-only)');
}
} catch (err) {
console.warn('[Stream] Init skipped:', err.message);
}
updateStreamUI();
// Initialize Works Bridge listener
try {
initWorksListener({
getTasksFn: (profile) => Tasks.getTasks(profile),
getTimeFn: (profile) => Time.getIntervals(profile),
getJournalFn: (profile) => Journal.getEntries(profile),
getLedgerFn: (profile) => Ledger.getTransactions(profile),
streamBus: Stream.bus,
});
updateBridgeUI();
} catch (err) {
console.warn('[WorksBridge] Init skipped:', err.message);
}
}
// ── Section navigation ───────────────────────────────────────────────────────
const SECTION_TITLES = {
tasks: 'Tasks',
time: 'Times',
journal: 'Journals',
ledger: 'Ledgers',
lists: 'Lists',
tags: 'Tags',
attributes: 'Atts',
next: 'Next',
warrior: 'Warrior',
community: 'Communities',
questions: 'Questions',
projects: 'Projects',
stream: 'Stream',
bridge: 'Bridge',
viz: 'Viz',
export: 'Export',
import: 'Import',
profile: 'Profiles',
ctrl: 'Settings',
};
// Theme-specific modes. Maps theme → array of {value, label} mode options.
const THEME_MODES = {
twain: [{ value: '', label: '—' }, { value: 'river', label: '〰 river' }],
};
function updateThemeModeSelect(theme, resetValue = true) {
const sel = document.getElementById('global-mode-select');
if (!sel) return;
const modes = THEME_MODES[theme];
if (!modes) {
sel.innerHTML = '<option value="">—</option>';
sel.disabled = true;
sel.value = '';
return;
}
sel.disabled = false;
sel.innerHTML = modes.map(m => `<option value="${m.value}">${m.label}</option>`).join('');
if (resetValue) sel.value = '';
}
function syncThemeModeSelectToRiver() {
const sel = document.getElementById('global-mode-select');
if (!sel) return;
sel.value = document.body.classList.contains('river-mode') ? 'river' : '';
}
async function showSection(name, { noScroll = false } = {}) {
if (scrollPositions.has(activeSection)) {
const area = document.getElementById('content-area');
if (area) scrollPositions.set(activeSection, area.scrollTop);
}
const previousSection = activeSection;
activeSection = name;
filterText = '';
// Emit navigation event to stream if active
if (previousSection !== name) {
try {
Stream.emitNavEvent(activeProfile, previousSection, name);
} catch (e) { /* stream may not be initialized */ }
}
document.querySelectorAll('.section').forEach(s => s.classList.add('hidden'));
const target = document.getElementById(`section-${name}`);
if (target) target.classList.remove('hidden');
document.querySelectorAll('.nav-item, .cmd-ctrl-btn').forEach(btn => {
const sec = btn.dataset.section;
btn.classList.toggle('active', sec === name);
});
const titleEl = document.getElementById('section-title');
if (titleEl) titleEl.textContent = SECTION_TITLES[name] || name;
document.querySelectorAll('[data-resource-section]').forEach(el => el.classList.add('hidden'));
const resourceBar = document.querySelector(`[data-resource-section="${name}"]`);
if (resourceBar) resourceBar.classList.remove('hidden');
// Twain journal mode needs the content-area overflow change only when journal is visible
const contentArea = document.getElementById('content-area');
if (name === 'journal' && journalTheme === 'twain') {
contentArea?.classList.add('twain-journal-active');
} else {
contentArea?.classList.remove('twain-journal-active');
}
// Hide scrollbar for community section
if (name === 'community') {
contentArea?.classList.add('comm-no-scrollbar');
} else {
contentArea?.classList.remove('comm-no-scrollbar');
}
if (!noScroll) {
const area = document.getElementById('content-area');
if (area) area.scrollTop = scrollPositions.get(name) || 0;
}
// Auto-sync sub-lists when not locked
if (!functionsLocked && !noScroll) {
const syncName = activeTaskList !== 'main' ? activeTaskList : (activeTimeLog !== 'main' ? activeTimeLog : activeJournal);
if (syncName && syncName !== 'main') {
if (name === 'tasks') activeTaskList = syncName;
else if (name === 'time') activeTimeLog = syncName;
else if (name === 'journal') activeJournal = syncName;
}
}
await loadSection(name);
}
async function loadSection(name) {
switch (name) {
case 'tasks': return loadTasks();
case 'time': return loadTime();
case 'journal': return loadJournal();
case 'ledger': return loadLedger();
case 'lists': return loadLists();
case 'tags': return loadTags();
case 'attributes': return loadAttributes();
case 'next': return loadNext();
case 'warrior': return loadWarrior();
case 'community': return loadCommunity();
case 'questions': return loadQuestions();
case 'projects': return loadProjects();
case 'stream': return loadStream();
case 'viz': return loadViz();
case 'profile': return loadProfile();
case 'ctrl': return loadCtrl();
}
}
// ── Tasks ────────────────────────────────────────────────────────────────────
async function loadTasks() {
// Populate sub-list selector
const taskLists = await getTaskLists(activeProfile);
const tlSel = document.getElementById('task-list-select');
if (tlSel) {
tlSel.innerHTML = taskLists.map(l =>
`<option value="${esc(l)}" ${l === activeTaskList ? 'selected' : ''}>${esc(l)}</option>`
).join('');
}
const tasks = await Tasks.getTasks(activeProfile, { includeDone: false, taskList: activeTaskList });
Render.renderTasks(tasks, { filterText, groupByProject: taskGroupMode, showAnnotations: taskShowAnns, bulkSelected });
Render.updateWarriorStats(tasks.length);
updateTaskStats(tasks.length);
if (taskShowDone) {
const done = await Tasks.getTasks(activeProfile, { includeDone: true, taskList: activeTaskList });
Render.renderDoneTasks(done.filter(t => t.status === 'completed'));
}
}
function wireTaskSection() {
const form = document.getElementById('add-task-form');
form?.addEventListener('submit', async (e) => {
e.preventDefault();
const fd = new FormData(form);
const desc = fd.get('description')?.trim();
if (!desc) return;
await Tasks.addTask(activeProfile, {
taskList: activeTaskList,
description: desc,
project: fd.get('project')?.trim() || '',
tags: fd.get('tags')?.trim() || '',
priority: fd.get('priority') || '',
due: fd.get('due') || null,
scheduled: fd.get('scheduled') || null,
wait: fd.get('wait') || null,
});
form.reset();
showToast('Task added');
await loadTasks();
});
document.getElementById('btn-task-start-new')?.addEventListener('click', async () => {
const fd = new FormData(form);
const desc = fd.get('description')?.trim();
if (!desc) { showToast('Enter a description first', 'warning'); return; }
const task = await Tasks.addTask(activeProfile, {
taskList: activeTaskList,
description: desc,
project: fd.get('project')?.trim() || '',
tags: fd.get('tags')?.trim() || '',
priority: fd.get('priority') || '',
});
await Tasks.startTask(activeProfile, task.uuid);
form.reset();
showToast('Task started');
await loadTasks();
});
// Sub-list selector
document.getElementById('task-list-select')?.addEventListener('change', (e) => {
activeTaskList = e.target.value;
loadTasks();
});
document.getElementById('btn-new-task-list')?.addEventListener('click', async () => {
const name = await promptText('Task list name:');
if (!name?.trim()) return;
const clean = name.trim();
await addTaskList(activeProfile, clean);
activeTaskList = clean;
showToast(`List "${clean}" created`);
await loadTasks();
});
document.getElementById('btn-del-task-list')?.addEventListener('click', async () => {
if (activeTaskList === 'main') { showToast('Cannot remove the main list', 'warning'); return; }
if (!await confirm(`Remove task list "${activeTaskList}"? Tasks in it will remain but become unlisted.`)) return;
await removeTaskList(activeProfile, activeTaskList);
activeTaskList = 'main';
showToast('List removed');
await loadTasks();
});
document.getElementById('btn-group-toggle')?.addEventListener('click', () => {
taskGroupMode = !taskGroupMode;
loadTasks();
});
document.getElementById('btn-show-done-tasks')?.addEventListener('click', async () => {
taskShowDone = !taskShowDone;
document.getElementById('task-done-list')?.classList.toggle('hidden', !taskShowDone);
document.getElementById('btn-show-done-tasks')?.classList.toggle('active', taskShowDone);
await loadTasks();
});
document.getElementById('btn-ann-toggle')?.addEventListener('click', () => {
taskShowAnns = !taskShowAnns;
document.getElementById('btn-ann-toggle')?.classList.toggle('active', taskShowAnns);
loadTasks();
});
document.getElementById('btn-compact-toggle')?.addEventListener('click', () => {
const taskList = document.getElementById('task-list');
const isCompact = taskList?.classList.toggle('task-list-compact');
document.getElementById('btn-compact-toggle')?.classList.toggle('active', isCompact);
// Toggle full/compact action buttons
taskList?.querySelectorAll('.task-actions-full').forEach(el => el.classList.toggle('hidden', isCompact));
taskList?.querySelectorAll('.task-actions-compact').forEach(el => el.classList.toggle('hidden', !isCompact));
});
document.getElementById('task-filter')?.addEventListener('input', (e) => {
filterText = e.target.value;
loadTasks();
});
// Delegate task action clicks
document.getElementById('task-list')?.addEventListener('click', async (e) => {
// Annotation hover action buttons
const annBtn = e.target.closest('.ann-hover-btn');
if (annBtn) {
e.stopPropagation();
const action = annBtn.dataset.annAction;
const uuid = annBtn.dataset.uuid || annBtn.dataset.id;
const idx = parseInt(annBtn.dataset.idx);
await openAnnInlineDrop(annBtn, action, uuid, idx);
return;
}
// Inline drop panel submit buttons
const dropBtn = e.target.closest('[data-drop-action]');
if (dropBtn) { await handleTaskDropAction(dropBtn); return; }
// Inline drop list item click (for dep)
const dropItem = e.target.closest('.task-inline-drop-list-item[data-dep-uuid]');
if (dropItem) return; // handled by dep-specific buttons inside
// Inline panel submit/cancel (must check before data-action routing)
const panelBtn = e.target.closest('[data-panel-action]');
if (panelBtn) { await handleTaskInlinePanelAction(panelBtn); return; }
const el = e.target.closest('[data-action]');
if (!el) return;
const { action, uuid } = el.dataset;
if (action === 'select') { toggleBulkSelect(uuid, el.checked); return; }
if (action === 'inline-annotate') { openTaskInlineDrop(uuid, 'annotate'); return; }
if (action === 'inline-journal') { openTaskInlineDrop(uuid, 'journal'); return; }
if (action === 'inline-dep') { openTaskInlineDrop(uuid, 'dep'); return; }
if (action === 'inline-comm') { openTaskInlineDrop(uuid, 'comm'); return; }
if (action === 'open-drawer' || action === 'expand') { openTaskDrawer(uuid); return; }
if (action === 'task-community') { await openTaskCommunityPanel(el); return; }
await handleTaskAction(action, uuid);
});
document.getElementById('task-done-list')?.addEventListener('click', async (e) => {
const btn = e.target.closest('[data-action]');
if (btn) await handleTaskAction(btn.dataset.action, btn.dataset.uuid);
});
wireBulkToolbar();
}
async function handleTaskAction(action, uuid) {
switch (action) {
case 'done': await Tasks.completeTask(activeProfile, uuid); showToast('Done'); break;
case 'delete': {
if (!await confirm('Delete this task?')) return;
await Tasks.deleteTask(activeProfile, uuid); showToast('Deleted');
break;
}
case 'start': await Tasks.startTask(activeProfile, uuid); showToast('Started'); break;
case 'stop': await Tasks.stopTask(activeProfile, uuid); showToast('Stopped'); break;
case 'annotate': {
const text = await promptText('Annotation:');
if (!text) return;
await Tasks.annotateTask(activeProfile, uuid, text); showToast('Annotated');
break;
}
}
await loadTasks();
}
// ── Task inline drop panels ──────────────────────────────────────────────────
function closeAllTaskDrops() {
document.querySelectorAll('.task-inline-drop.open').forEach(d => { d.classList.remove('open'); d.innerHTML = ''; });
}
async function openTaskInlineDrop(uuid, mode) {
closeAllTaskDrops();
const drop = document.querySelector(`.task-inline-drop[data-drop="task-${uuid}"]`);
if (!drop) return;
let html = '';
if (mode === 'annotate') {
html = `<div class="task-inline-drop-row">
<input type="text" class="task-inline-drop-input" data-drop-field="ann-text" placeholder="annotation…" autofocus />
<button class="task-inline-drop-btn" data-drop-action="submit-ann" data-uuid="${uuid}">add</button>
</div>`;
} else if (mode === 'journal') {
const journals = await getJournals(activeProfile);
const opts = journals.map(j => `<option value="${j}"${j === activeJournal ? ' selected' : ''}>${j}</option>`).join('');
html = `<div class="task-inline-drop-row">
<input type="text" class="task-inline-drop-input" data-drop-field="jrnl-text" placeholder="note to journal…" autofocus />
<select class="task-inline-drop-select" data-drop-field="jrnl-name">${opts}</select>
<button class="task-inline-drop-btn" data-drop-action="submit-jrnl" data-uuid="${uuid}">add</button>
</div>`;
} else if (mode === 'dep') {
const allTasks = await Tasks.getTasks(activeProfile, { includeDone: false });
const filtered = allTasks.filter(t => t.uuid !== uuid);
html = `<div class="task-inline-drop-row">
<input type="text" class="task-inline-drop-input" data-drop-field="dep-search" placeholder="search tasks…" autofocus />
</div>
<div class="task-inline-drop-list" data-drop-field="dep-list">
${filtered.slice(0, 20).map(t => `
<div class="task-inline-drop-list-item" data-dep-uuid="${t.uuid}">
<span class="task-desc">${esc(t.description)}</span>
<button class="task-inline-drop-btn" data-drop-action="dep-blocked-by" data-uuid="${uuid}" data-dep="${t.uuid}">← blocked by</button>
<button class="task-inline-drop-btn" data-drop-action="dep-blocks" data-uuid="${uuid}" data-dep="${t.uuid}">→ blocks</button>
</div>
`).join('')}
</div>`;
} else if (mode === 'comm') {
const collections = await Community.listCollections();
const active = collections.filter(c => !c.archived_at);
if (active.length === 0) {
html = `<div class="task-inline-drop-row"><span style="color:var(--muted);font-size:11px">No community collections — create one in Community first.</span></div>`;
} else {
const opts = active.map(c => `<option value="${c.id}" data-name="${esc(c.name)}">${esc(c.name)}</option>`).join('');
html = `<div class="task-inline-drop-row">
<input type="text" class="task-inline-drop-input" data-drop-field="comm-note" placeholder="optional note…" autofocus />
<select class="task-inline-drop-select" data-drop-field="comm-coll">${opts}</select>
<button class="task-inline-drop-btn" data-drop-action="submit-comm" data-uuid="${uuid}">→ add</button>
</div>`;
}
}
drop.innerHTML = html;
drop.classList.add('open');
drop.querySelector('input')?.focus();
// Wire dep search filtering
if (mode === 'dep') {
const searchInput = drop.querySelector('[data-drop-field="dep-search"]');
const allTasks = await Tasks.getTasks(activeProfile, { includeDone: false });
const filtered = allTasks.filter(t => t.uuid !== uuid);
searchInput?.addEventListener('input', () => {
const q = searchInput.value.trim().toLowerCase();
const listEl = drop.querySelector('[data-drop-field="dep-list"]');
const matches = q ? filtered.filter(t => t.description.toLowerCase().includes(q)) : filtered.slice(0, 20);
listEl.innerHTML = matches.slice(0, 20).map(t => `
<div class="task-inline-drop-list-item" data-dep-uuid="${t.uuid}">
<span class="task-desc">${esc(t.description)}</span>
<button class="task-inline-drop-btn" data-drop-action="dep-blocked-by" data-uuid="${uuid}" data-dep="${t.uuid}">← blocked by</button>
<button class="task-inline-drop-btn" data-drop-action="dep-blocks" data-uuid="${uuid}" data-dep="${t.uuid}">→ blocks</button>
</div>
`).join('');
});
}
// Enter key submits for annotate/journal/comm
if (mode === 'annotate' || mode === 'journal' || mode === 'comm') {
drop.querySelector('input')?.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
drop.querySelector('[data-drop-action]')?.click();
}
});
}
}
async function handleTaskDropAction(btn) {
const action = btn.dataset.dropAction;
const uuid = btn.dataset.uuid;
const drop = btn.closest('.task-inline-drop');
if (action === 'submit-ann') {
const text = drop?.querySelector('[data-drop-field="ann-text"]')?.value.trim();
if (!text) return;
await Tasks.annotateTask(activeProfile, uuid, text);
showToast('Annotated');
closeAllTaskDrops();
await loadTasks();
} else if (action === 'submit-jrnl') {
const text = drop?.querySelector('[data-drop-field="jrnl-text"]')?.value.trim();
if (!text) return;
const jname = drop?.querySelector('[data-drop-field="jrnl-name"]')?.value || activeJournal;
const task = await Tasks.getTask(activeProfile, uuid);
const body = `${text}\n[task: ${task?.description || uuid}]`;
await Journal.addEntry(activeProfile, { body, journal: jname });
await Tasks.annotateTask(activeProfile, uuid, `journaled: ${new Date().toISOString().slice(0, 10)}`);
showToast(`Added to ${jname}`);
closeAllTaskDrops();
await loadTasks();
} else if (action === 'dep-blocked-by' || action === 'dep-blocks') {
const depUuid = btn.dataset.dep;
const task = await Tasks.getTask(activeProfile, uuid);
if (!task) return;
const deps = [...(task.depends || [])];
const direction = action === 'dep-blocked-by' ? 'blocked-by' : 'blocks';
deps.push({ uuid: depUuid, direction });
await Tasks.updateTask(activeProfile, uuid, { depends: deps });
showToast(`Dependency added (${direction})`);
closeAllTaskDrops();
await loadTasks();
} else if (action === 'submit-comm') {
const drop = btn.closest('.task-inline-drop');
const collSel = drop?.querySelector('[data-drop-field="comm-coll"]');
const collId = parseInt(collSel?.value);
const collName = collSel?.options[collSel.selectedIndex]?.dataset.name || '';
const note = drop?.querySelector('[data-drop-field="comm-note"]')?.value.trim();
if (!collId) return;
const task = await Tasks.getTask(activeProfile, uuid);
if (!task) return;
await Community.addEntry(collId, { type: 'task', profile: activeProfile, content: task });
const today = new Date().toISOString().slice(0, 10);
const ann = note
? `shared to community/${collName} — "${note}" (${today})`
: `shared to community/${collName} (${today})`;
await Tasks.annotateTask(activeProfile, uuid, ann);
showToast(`Added to ${collName}`);
closeAllTaskDrops();
await loadTasks();
}
}
// ── Annotation hover inline drop ──────────────────────────────────────────────
function closeAllAnnDrops() {
document.querySelectorAll('.ann-inline-drop.open').forEach(d => { d.classList.remove('open'); d.innerHTML = ''; });
}
async function openAnnInlineDrop(btn, action, sourceId, annIdx) {
closeAllAnnDrops();
// Get the annotation text from the parent annotation div
const annDiv = btn.closest('.task-ann, .journal-annotation');
if (!annDiv) return;
const textEl = annDiv.querySelector('.task-ann-text, .journal-ann-text');
const rawText = textEl ? textEl.textContent.replace(/^↳\s*/, '').trim() : '';
// Find or create the inline drop element after the annotation div
let drop = annDiv.nextElementSibling;
if (!drop || !drop.classList.contains('ann-inline-drop')) {
drop = document.createElement('div');
drop.className = 'ann-inline-drop';
annDiv.after(drop);
}
let html = '';
if (action === 'to-journal' || action === 'jrnl-to-journal') {
const journals = await getJournals(activeProfile);
const opts = journals.map(j => `<option value="${j}"${j === activeJournal ? ' selected' : ''}>${j}</option>`).join('');
html = `<input type="text" class="ann-inline-drop-input" data-field="ann-drop-text" value="${esc(rawText)}" />
<select class="ann-inline-drop-select" data-field="ann-drop-journal">${opts}</select>
<button class="ann-inline-drop-btn" data-ann-drop-submit="${action}" data-source="${sourceId}" data-idx="${annIdx}">send</button>`;
} else if (action === 'to-community' || action === 'jrnl-to-community') {
const collections = await Community.listCollections();
const active = collections.filter(c => !c.archived_at);
if (!active.length) {
html = `<span style="color:var(--muted);font-size:11px">No community collections.</span>`;
} else {
const opts = active.map(c => `<option value="${c.id}">${esc(c.name)}</option>`).join('');
html = `<input type="text" class="ann-inline-drop-input" data-field="ann-drop-text" value="${esc(rawText)}" />
<select class="ann-inline-drop-select" data-field="ann-drop-coll">${opts}</select>
<button class="ann-inline-drop-btn" data-ann-drop-submit="${action}" data-source="${sourceId}" data-idx="${annIdx}">send</button>`;
}
} else if (action === 'to-list' || action === 'jrnl-to-list') {
const lists = await Lists.getLists(activeProfile);
const opts = lists.map(l => `<option value="${l}"${l === activeList ? ' selected' : ''}>${l}</option>`).join('');
html = `<input type="text" class="ann-inline-drop-input" data-field="ann-drop-text" value="${esc(rawText)}" />
<select class="ann-inline-drop-select" data-field="ann-drop-list">${opts}</select>
<button class="ann-inline-drop-btn" data-ann-drop-submit="${action}" data-source="${sourceId}" data-idx="${annIdx}">send</button>`;
} else if (action === 'to-task' || action === 'jrnl-to-task') {
html = `<input type="text" class="ann-inline-drop-input" data-field="ann-drop-text" value="${esc(rawText)}" placeholder="task description…" />
<button class="ann-inline-drop-btn" data-ann-drop-submit="${action}" data-source="${sourceId}" data-idx="${annIdx}">create</button>`;
}
drop.innerHTML = html;
drop.classList.add('open');
const input = drop.querySelector('input');
if (input) {
input.focus();
input.setSelectionRange(input.value.length, input.value.length);
}
// Enter key submits
input?.addEventListener('keydown', (ev) => {
if (ev.key === 'Enter') {
ev.preventDefault();
drop.querySelector('[data-ann-drop-submit]')?.click();
}
if (ev.key === 'Escape') {
closeAllAnnDrops();
}
});
// Wire submit button
const submitBtn = drop.querySelector('[data-ann-drop-submit]');
submitBtn?.addEventListener('click', async () => {
await handleAnnDropSubmit(drop, submitBtn.dataset.annDropSubmit, submitBtn.dataset.source, parseInt(submitBtn.dataset.idx));
});
}
async function handleAnnDropSubmit(drop, action, sourceId, annIdx) {
const text = drop.querySelector('[data-field="ann-drop-text"]')?.value.trim();
if (!text) return;
if (action === 'to-journal' || action === 'jrnl-to-journal') {
const jname = drop.querySelector('[data-field="ann-drop-journal"]')?.value || activeJournal;
await Journal.addEntry(activeProfile, { body: text, journal: jname });
showToast(`Added to ${jname}`);
} else if (action === 'to-community' || action === 'jrnl-to-community') {
const collId = parseInt(drop.querySelector('[data-field="ann-drop-coll"]')?.value);
if (!collId) return;
await Community.addEntry(collId, { type: 'note', profile: activeProfile, content: { text, source: `annotation:${sourceId}` } });
showToast('Added to community');
} else if (action === 'to-list' || action === 'jrnl-to-list') {
const list = drop.querySelector('[data-field="ann-drop-list"]')?.value || 'default';
await Lists.addItem(activeProfile, text, list);
showToast(`Added to ${list}`);
} else if (action === 'to-task' || action === 'jrnl-to-task') {
await Tasks.addTask(activeProfile, { description: text });
showToast('Task created');
}
closeAllAnnDrops();
}
// ── Task inline community panel ───────────────────────────────────────────────
function closeAllTaskPanels() {
document.querySelectorAll('#task-list .jrnl-inline-panel.open').forEach(p => {
p.classList.remove('open'); p.innerHTML = '';
});
}
async function openTaskCommunityPanel(btn) {
const uuid = btn.dataset.uuid;
const panel = document.querySelector(`.jrnl-inline-panel[data-panel="task-${uuid}"]`);
if (!panel) return;
if (panel.classList.contains('open')) { closeAllTaskPanels(); return; }
closeAllTaskPanels();
const collections = await Community.listCollections();
const active = collections.filter(c => !c.archived_at);
if (active.length === 0) {
panel.innerHTML = `<div class="jrnl-inline-panel-inner"><div class="jrnl-panel-row">
<span class="jrnl-panel-confirm">No collections yet — create one in Community first.</span>
<button class="btn-inline-alt tdr-btn-sm" data-panel-action="cancel-task-panel" data-uuid="${uuid}">close</button>
</div></div>`;
panel.classList.add('open');
return;
}
const opts = active.map(c => `<option value="${c.id}" data-name="${esc(c.name)}">${esc(c.name)}</option>`).join('');
panel.innerHTML = `<div class="jrnl-inline-panel-inner"><div class="jrnl-panel-row">
<select class="jrnl-panel-select" data-field="coll-id">${opts}</select>
<input class="jrnl-panel-input" data-field="comm-note" placeholder="optional note…" style="flex:2">
<button class="btn-inline-submit tdr-btn-sm" data-panel-action="submit-task-community" data-uuid="${uuid}">→ add</button>
<button class="btn-inline-alt tdr-btn-sm" data-panel-action="cancel-task-panel" data-uuid="${uuid}">cancel</button>
</div></div>`;
panel.classList.add('open');
panel.querySelector('input')?.focus();
}
async function handleTaskInlinePanelAction(btn) {
const action = btn.dataset.panelAction;
const uuid = btn.dataset.uuid;
if (action === 'cancel-task-panel') {
closeAllTaskPanels();
return;
}
if (action === 'submit-task-community') {
const panel = document.querySelector(`.jrnl-inline-panel[data-panel="task-${uuid}"]`);
const collSel = panel?.querySelector('[data-field="coll-id"]');
const collId = parseInt(collSel?.value);
const collName = collSel?.options[collSel.selectedIndex]?.dataset.name || '';
const note = panel?.querySelector('[data-field="comm-note"]')?.value.trim();
if (!collId) return;
const task = await Tasks.getTask(activeProfile, uuid);
if (!task) return;
await Community.addEntry(collId, { type: 'task', profile: activeProfile, content: task });
// Annotate the task with the community action
const today = new Date().toISOString().slice(0, 10);
const ann = note
? `shared to community/${collName} — "${note}" (${today})`
: `shared to community/${collName} (${today})`;
await Tasks.annotateTask(activeProfile, uuid, ann);
showToast(`Added to ${collName}`);
closeAllTaskPanels();
await loadTasks();
}
}
// ── Task Detail Drawer ────────────────────────────────────────────────────────
const TASK_CORE_KEYS = new Set([
'uuid','status','description','project','tags','priority','due','scheduled',
'wait','start','end','depends','annotations','urgency','modified','entry',
]);
let _drawerUuid = null;
let _drawerTask = null;
let _allTasksCache = [];
async function openTaskDrawer(uuid) {
if (!uuid) return;
_drawerUuid = uuid;
_drawerTask = await Tasks.getTask(activeProfile, uuid);
if (!_drawerTask) return;
_allTasksCache = await Tasks.getTasks(activeProfile, { includeDone: false });
const drawer = document.getElementById('task-drawer');
drawer.classList.remove('hidden');
document.body.style.overflow = 'hidden';
// Mark row as open
document.querySelectorAll('.task-row.drawer-open').forEach(r => r.classList.remove('drawer-open'));
document.querySelector(`.task-row[data-uuid="${uuid}"]`)?.classList.add('drawer-open');
populateDrawer(_drawerTask);
}
function closeTaskDrawer() {
const drawer = document.getElementById('task-drawer');
drawer.classList.add('hidden');
document.body.style.overflow = '';
document.querySelectorAll('.task-row.drawer-open').forEach(r => r.classList.remove('drawer-open'));
_drawerUuid = null;
_drawerTask = null;
}
function populateDrawer(t) {
const level = (t.urgency >= 10 ? 'high' : t.urgency >= 5 ? 'med' : 'low');
// Header
document.getElementById('tdr-urgency-score').textContent = t.urgency.toFixed(1);
document.getElementById('tdr-header-project').textContent = t.project || '';
document.getElementById('tdr-header-project').style.display = t.project ? '' : 'none';
document.getElementById('tdr-header-title').textContent = '';
document.getElementById('tdr-header-tags').innerHTML = (t.tags||[]).map(g => `<span class="task-tag">${esc(g)}</span>`).join('');
// Header action buttons
const isActive = t.status === 'active';
document.getElementById('tdr-header-actions').innerHTML = `
${isActive
? `<button data-tdr-action="stop">■ stop</button>`
: `<button data-tdr-action="start">▶ start</button>`}
<button class="tdr-btn-primary" data-tdr-action="done">✓ done</button>
<button data-tdr-action="delete" style="color:var(--error);border-color:var(--error)">✗ delete</button>
`;
// Core fields
const toDateVal = iso => iso ? iso.slice(0,10) : '';
document.getElementById('tdr-desc').value = t.description || '';
document.getElementById('tdr-proj').value = t.project || '';
document.getElementById('tdr-pri').value = t.priority || '';
document.getElementById('tdr-due').value = toDateVal(t.due);
document.getElementById('tdr-sched').value = toDateVal(t.scheduled);
document.getElementById('tdr-wait').value = toDateVal(t.wait);
document.getElementById('tdr-tags').value = (t.tags||[]).join(', ');
document.getElementById('tdr-status').textContent = t.status || '';
document.getElementById('tdr-urgency-val').textContent = t.urgency.toFixed(2);
document.getElementById('tdr-created').textContent = t.entry ? new Date(t.entry).toLocaleDateString('en', { year:'numeric', month:'short', day:'numeric' }) : '';
populateUdas(t);
populateAnnotations(t);
populateDeps(t);
populateDrawerJournalSelect();
populateDrawerCommunitySelect();
populateDrawerTaskListSelect(t);
populateUdaDatalist();
populateProjectDatalist();
}
async function populateProjectDatalist() {
const projects = await Tasks.getProjects(activeProfile);
const dl = document.getElementById('tdr-project-datalist');
if (dl) dl.innerHTML = projects.map(p => `<option value="${esc(p.name)}">`).join('');
}
async function populateUdaDatalist() {
const keys = await getUdaKeys(activeProfile);
const dl = document.getElementById('tdr-uda-datalist');
if (dl) dl.innerHTML = keys.map(k => `<option value="${esc(k)}">`).join('');
}
async function populateUdas(t) {
const udas = Object.entries(t).filter(([k]) => !TASK_CORE_KEYS.has(k));
const el = document.getElementById('tdr-uda-list');
if (!el) return;
if (udas.length === 0) {
el.innerHTML = '<div style="font-size:11px;color:var(--muted);padding:3px 0">No attributes.</div>';
return;
}
let definitions = [];
try {
definitions = await Attributes.getAttributes(activeProfile);
} catch { /* fallback to empty */ }
el.innerHTML = udas.map(([k, v]) => {
const def = definitions.find(d => d.name === k);
let valueHtml;
if (def) {
valueHtml = Render.renderUdaInput(def, v, def.readOnly);
} else {
valueHtml = `<input type="text" class="tdr-uda-typed-input" data-uda-key="${esc(k)}" value="${esc(String(v))}" />`;
}
return `
<div class="tdr-uda-row" data-uda-name="${esc(k)}">
<span class="tdr-uda-key">${esc(k)}</span>
<span class="tdr-uda-val">${valueHtml}</span>
<button class="tdr-uda-del" data-tdr-uda-del="${esc(k)}">✗</button>
</div>
`;
}).join('');
}
function populateAnnotations(t) {
const el = document.getElementById('tdr-annotations');
if (!el) return;
const anns = t.annotations || [];
el.innerHTML = `
${anns.length === 0 ? '<div style="font-size:11px;color:var(--muted);padding:3px 0">None.</div>' : ''}
<div class="tdr-ann-list">${anns.map((a, i) => `
<div class="tdr-ann-item">
<span class="tdr-ann-date">${a.entry ? new Date(a.entry).toLocaleDateString('en',{month:'short',day:'numeric'}) : ''}</span>
<span class="tdr-ann-text">${esc(a.description)}</span>
<button class="tdr-ann-del" data-tdr-ann-del="${i}">✗</button>
</div>
`).join('')}</div>
`;
}
function populateDeps(t) {
const el = document.getElementById('tdr-dep-list');
if (!el) return;
const deps = t.depends || [];
if (deps.length === 0) {
el.innerHTML = '<div class="tdr-dep-empty">no dependencies</div>';
return;
}
el.innerHTML = deps.map(dep => {
const found = _allTasksCache.find(x => x.uuid === dep.uuid);
const desc = found ? found.description : dep.uuid;
const dir = dep.direction === 'blocks' ? 'blocks' : 'blocked by';
return `
<div class="tdr-dep-item">
<span class="tdr-dep-direction">${dir}</span>
<span class="tdr-dep-desc">${esc(desc)}</span>
<span class="tdr-dep-uuid" style="font-size:10px;color:var(--muted);font-family:monospace">${dep.uuid.slice(0,8)}</span>
<button class="tdr-dep-del" data-tdr-dep-del="${dep.uuid}">✗</button>
</div>
`;
}).join('');
}
async function populateDrawerJournalSelect() {
const journals = await getJournals(activeProfile);
const sel = document.getElementById('tdr-journal-select');
if (!sel) return;
sel.innerHTML = journals.map(j => `<option value="${esc(j)}" ${j === activeJournal ? 'selected' : ''}>${esc(j)}</option>`).join('');
}
async function populateDrawerTaskListSelect(t) {
const lists = await getTaskLists(activeProfile);
const sel = document.getElementById('tdr-task-list');
if (!sel) return;
const cur = t.taskList || 'main';
sel.innerHTML = lists.map(l => `<option value="${esc(l)}" ${l === cur ? 'selected' : ''}>${esc(l)}</option>`).join('');
}
async function populateDrawerCommunitySelect() {
const collections = await Community.listCollections();
const active = collections.filter(c => !c.archived_at);
const sel = document.getElementById('tdr-community-select');
if (!sel) return;
sel.innerHTML = active.length === 0
? '<option value="">no collections</option>'
: active.map(c => `<option value="${c.id}" data-name="${esc(c.name)}">${esc(c.name)}</option>`).join('');
}
async function saveDrawer() {
if (!_drawerUuid || !_drawerTask) return;
// Collect core field values
const rawTags = document.getElementById('tdr-tags').value;
const tags = rawTags.split(/[\s,]+/).map(s => s.trim()).filter(Boolean);