keepfold 0.6.4__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- keepfold/__init__.py +1 -0
- keepfold/_proc.py +102 -0
- keepfold/access.py +154 -0
- keepfold/agent_eval.py +162 -0
- keepfold/agent_text.py +56 -0
- keepfold/anki.py +285 -0
- keepfold/app/__init__.py +5 -0
- keepfold/app/actions.py +690 -0
- keepfold/app/desktop.py +677 -0
- keepfold/app/exports.py +254 -0
- keepfold/app/hello.py +79 -0
- keepfold/app/launch.py +114 -0
- keepfold/app/news.py +60 -0
- keepfold/app/server.py +3142 -0
- keepfold/app/status.py +811 -0
- keepfold/app/targets.py +1374 -0
- keepfold/app/winpath.py +54 -0
- keepfold/app/wizard.py +506 -0
- keepfold/ask.py +475 -0
- keepfold/askfile.py +322 -0
- keepfold/assets/LICENSE-d3.txt +13 -0
- keepfold/assets/agent_eval.json +235 -0
- keepfold/assets/app/app.css +611 -0
- keepfold/assets/app/app.js +2712 -0
- keepfold/assets/app/capture.html +16 -0
- keepfold/assets/app/capture.js +91 -0
- keepfold/assets/app/index.html +149 -0
- keepfold/assets/brain3d.js +3730 -0
- keepfold/assets/chat_eval.json +454 -0
- keepfold/assets/d3.v7.min.js +2 -0
- keepfold/assets/dashboard.css +774 -0
- keepfold/assets/dashboard.html.tmpl +170 -0
- keepfold/assets/dashboard.js +4262 -0
- keepfold/assets/help/GUIDE.md +544 -0
- keepfold/assets/help/help.md +83 -0
- keepfold/assets/keepfold.ico +0 -0
- keepfold/assets/whats_new.json +162 -0
- keepfold/backup.py +100 -0
- keepfold/brainmap.py +1382 -0
- keepfold/browse/__init__.py +10 -0
- keepfold/browse/build.py +1320 -0
- keepfold/browse/forget.py +510 -0
- keepfold/browse/legacy.py +95 -0
- keepfold/browse/lists.py +285 -0
- keepfold/browse/privacy.py +391 -0
- keepfold/browse/selftest.py +166 -0
- keepfold/browse/sites.py +1068 -0
- keepfold/browse/sources.py +329 -0
- keepfold/browse/store.py +991 -0
- keepfold/browse/takeout.py +312 -0
- keepfold/browse/titles.py +127 -0
- keepfold/browse/vectors.py +326 -0
- keepfold/browse_serve.py +332 -0
- keepfold/catalog.py +564 -0
- keepfold/chat.py +1464 -0
- keepfold/chat_archive.py +165 -0
- keepfold/chat_eval.py +583 -0
- keepfold/chat_facts.py +721 -0
- keepfold/chat_import.py +1045 -0
- keepfold/chat_pages.py +291 -0
- keepfold/chat_study.py +371 -0
- keepfold/chats.py +669 -0
- keepfold/claims.py +650 -0
- keepfold/cli.py +3254 -0
- keepfold/clients.py +96 -0
- keepfold/cloudllm.py +135 -0
- keepfold/contract.py +43 -0
- keepfold/corrections.py +134 -0
- keepfold/dashboard.py +959 -0
- keepfold/dates.py +202 -0
- keepfold/delta.py +146 -0
- keepfold/digest.py +72 -0
- keepfold/doctor.py +565 -0
- keepfold/duplicates.py +145 -0
- keepfold/egress.py +68 -0
- keepfold/eval_history.py +109 -0
- keepfold/events.py +554 -0
- keepfold/export_context.py +109 -0
- keepfold/fact_harvest.py +578 -0
- keepfold/forget.py +720 -0
- keepfold/harvest.py +334 -0
- keepfold/home.py +714 -0
- keepfold/importers.py +627 -0
- keepfold/index.py +733 -0
- keepfold/know.py +40 -0
- keepfold/learning_eval.py +261 -0
- keepfold/levels.py +595 -0
- keepfold/life_sources.py +747 -0
- keepfold/lint.py +241 -0
- keepfold/localllm.py +699 -0
- keepfold/loops.py +316 -0
- keepfold/mcp_server.py +4464 -0
- keepfold/migrate.py +552 -0
- keepfold/more_sources.py +709 -0
- keepfold/packs.py +148 -0
- keepfold/people.py +99 -0
- keepfold/planner.py +819 -0
- keepfold/prime.py +630 -0
- keepfold/prime_hook.py +265 -0
- keepfold/profiles.py +118 -0
- keepfold/quarantine.py +123 -0
- keepfold/recall_log.py +93 -0
- keepfold/redteam.py +393 -0
- keepfold/reflect.py +164 -0
- keepfold/relink.py +477 -0
- keepfold/render.py +406 -0
- keepfold/review.py +1181 -0
- keepfold/rollups.py +412 -0
- keepfold/safety_net.py +571 -0
- keepfold/sample.py +103 -0
- keepfold/sample_vault/areas/programming.algorithms.md +11 -0
- keepfold/sample_vault/areas/programming.basics.md +11 -0
- keepfold/sample_vault/concepts/big-o-notation.md +13 -0
- keepfold/sample_vault/concepts/functions.md +13 -0
- keepfold/sample_vault/concepts/loops.md +14 -0
- keepfold/sample_vault/concepts/recursion.md +13 -0
- keepfold/sample_vault/domains/programming.md +10 -0
- keepfold/sample_vault/journal/2026-01-12.md +9 -0
- keepfold/sample_vault/me/goals.md +17 -0
- keepfold/sample_vault/me/profile.md +19 -0
- keepfold/sample_vault/mistakes/programming.off-by-one-loop.md +16 -0
- keepfold/sample_vault/notes/recursion-needs-a-base-case.md +18 -0
- keepfold/sample_vault/problems/fizzbuzz.md +12 -0
- keepfold/sample_vault/projects/text-adventure.md +15 -0
- keepfold/sample_vault/resources/python-tutorial.md +16 -0
- keepfold/semantic.py +1254 -0
- keepfold/session.py +764 -0
- keepfold/share.py +69 -0
- keepfold/sources.py +612 -0
- keepfold/sync_copies.py +83 -0
- keepfold/tags.py +230 -0
- keepfold/taint.py +301 -0
- keepfold/tonight.py +195 -0
- keepfold/topics.py +1072 -0
- keepfold/update.py +300 -0
- keepfold/vault.py +942 -0
- keepfold/vecstore.py +218 -0
- keepfold/voice.py +260 -0
- keepfold/voice_memos.py +280 -0
- keepfold/watch.py +303 -0
- keepfold/where.py +119 -0
- keepfold/xray.py +516 -0
- keepfold/zotero.py +303 -0
- keepfold-0.6.4.dist-info/METADATA +644 -0
- keepfold-0.6.4.dist-info/RECORD +148 -0
- keepfold-0.6.4.dist-info/WHEEL +4 -0
- keepfold-0.6.4.dist-info/entry_points.txt +6 -0
- keepfold-0.6.4.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,4262 @@
|
|
|
1
|
+
/* Keepfold dashboard, Night Platform. Every note-derived string goes
|
|
2
|
+
in with textContent (or d3 .text); nothing here parses HTML. */
|
|
3
|
+
(async () => {
|
|
4
|
+
'use strict';
|
|
5
|
+
const T0 = performance.now();
|
|
6
|
+
// The snapshot (Export snapshot) carries its data; the app's live home fetches it and keeps
|
|
7
|
+
// it current from /api/home/delta.
|
|
8
|
+
const BLOB = document.getElementById('data'), LIVE = !BLOB;
|
|
9
|
+
let KEY = '';
|
|
10
|
+
let cold = null; // the 90-second check's { root, timer } while its panel is open
|
|
11
|
+
if (LIVE) { // the app's key, as app.js: from the link once, then this tab's sessionStorage
|
|
12
|
+
KEY = new URLSearchParams(location.search).get('t') || '';
|
|
13
|
+
try { if (KEY) sessionStorage.setItem('keepfold.key', KEY); else KEY = sessionStorage.getItem('keepfold.key') || ''; } catch (e) { /* storage off */ }
|
|
14
|
+
history.replaceState(null, '', '/' + location.hash);
|
|
15
|
+
}
|
|
16
|
+
// GET, or POST with a JSON body; a refused key (401, 403) throws an error marked `key`
|
|
17
|
+
async function api(path, body) {
|
|
18
|
+
const r = await fetch(path, body === undefined ? { headers: { 'X-Keepfold-Token': KEY }, cache: 'no-store' } : {
|
|
19
|
+
method: 'POST', headers: { 'X-Keepfold-Token': KEY, 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
|
20
|
+
if (!r.ok) { // the app's own words when it gives them (409: "Wait: Importing is still running.")
|
|
21
|
+
let d = {};
|
|
22
|
+
try { d = await r.json(); } catch (e) { /* no body */ }
|
|
23
|
+
const msg = typeof d.error === 'string' && d.error ? d.error : `The app answered ${r.status}.`;
|
|
24
|
+
throw Object.assign(new Error(msg), { key: r.status === 401 || r.status === 403, status: r.status });
|
|
25
|
+
}
|
|
26
|
+
return r.json();
|
|
27
|
+
}
|
|
28
|
+
function offline(err) { // the header chip: the app is not answering, or no longer takes this page's key
|
|
29
|
+
const s = document.getElementById('stale');
|
|
30
|
+
s.textContent = err && err.key ? '· This page’s key expired. Open Keepfold from the tray or Start menu.'
|
|
31
|
+
: '· Keepfold is not answering. Reopen it from the tray or Start menu.';
|
|
32
|
+
s.hidden = !err;
|
|
33
|
+
}
|
|
34
|
+
async function fetchHome() {
|
|
35
|
+
// the app builds the home once after it starts (a minute on a big vault): say so, never a blank page
|
|
36
|
+
const s = document.getElementById('stale');
|
|
37
|
+
s.textContent = '· Loading your notes (up to a minute after Keepfold starts)';
|
|
38
|
+
s.hidden = false;
|
|
39
|
+
for (;;) {
|
|
40
|
+
try { const d = await api('/api/home'); offline(null); return d; } catch (e) { offline(e); }
|
|
41
|
+
await new Promise((r) => setTimeout(r, 3000));
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
let D = BLOB ? JSON.parse(BLOB.textContent) : await fetchHome();
|
|
45
|
+
const STATES = ['solid', 'learning', 'needs_refresh', 'unverified', 'not_started'];
|
|
46
|
+
const GLYPH = { solid: '●', learning: '◐', needs_refresh: '↻', unverified: '◌', not_started: '○' };
|
|
47
|
+
const LABEL = { solid: 'Solid', learning: 'Learning', needs_refresh: 'Needs refresh',
|
|
48
|
+
unverified: 'Unverified', not_started: 'Not started' };
|
|
49
|
+
const VERDICT = { correct: '✓', partial: '½', wrong: '✗' };
|
|
50
|
+
const OUTCOME = { pass: '✓ pass', fail: '✗ fail', pending: '… pending', taken: '◷ waiting for result', unknown: '? unknown' };
|
|
51
|
+
const GROUPS = [['unchecked', 'Taught, not yet checked'], ['asked', 'Asked, not graded'],
|
|
52
|
+
['confident_miss', 'Confident miss'], ['track', 'Plan steps'], ['warmup', 'Warm-up'],
|
|
53
|
+
['refresh', 'Refresh'], ['new', 'Ready to learn']];
|
|
54
|
+
const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
|
55
|
+
const $ = (id) => document.getElementById(id);
|
|
56
|
+
let TODAY = D.day || D.as_of.slice(0, 10); // the 04:00 Keepfold day, as `keepfold today`
|
|
57
|
+
let NAME = D.owner && D.owner.name ? D.owner.name : '';
|
|
58
|
+
const SVGNS = d3.namespaces.svg;
|
|
59
|
+
const REDUCED = window.matchMedia('(prefers-reduced-motion: reduce)');
|
|
60
|
+
const motion = (ms) => (REDUCED.matches ? 0 : ms); // a d3 transition's length: instant under reduced motion
|
|
61
|
+
|
|
62
|
+
/* A segmented control or tab list: when its pressed (or selected) button changes, the highlight (the
|
|
63
|
+
button's ::before, the tabs' underline ::after; dashboard.css) slides in from the button that lost
|
|
64
|
+
it, 200 ms ease-out, transform only. One observer, so no call site changes; off under reduced motion. */
|
|
65
|
+
const GLIDE = '.seg, .viewswitch, .presets, .scrub-span, .tabs';
|
|
66
|
+
const lit = (b) => b.getAttribute('aria-pressed') === 'true' || b.getAttribute('aria-selected') === 'true';
|
|
67
|
+
new MutationObserver((recs) => {
|
|
68
|
+
if (REDUCED.matches) return;
|
|
69
|
+
const lost = recs.filter((r) => r.oldValue === 'true' && !lit(r.target)).map((r) => r.target);
|
|
70
|
+
for (const r of recs) {
|
|
71
|
+
const b = r.target, g = lit(b) && r.oldValue !== 'true' && b.closest(GLIDE);
|
|
72
|
+
const from = g && lost.find((o) => o !== b && g.contains(o));
|
|
73
|
+
if (!from) continue; // a multi-select toggle, or a first draw: no glide
|
|
74
|
+
const a = from.getBoundingClientRect(), z = b.getBoundingClientRect();
|
|
75
|
+
if (!a.width || !z.width || !b.animate) continue;
|
|
76
|
+
b.animate([{ transform: `translate(${a.left + a.width / 2 - z.left - z.width / 2}px, ${a.top + a.height / 2 - z.top - z.height / 2}px) `
|
|
77
|
+
+ `scale(${a.width / z.width}, ${a.height / z.height})` }, { transform: 'none' }],
|
|
78
|
+
{ duration: 200, easing: 'cubic-bezier(.2,.7,.2,1)', pseudoElement: g.matches('.tabs') ? '::after' : '::before' });
|
|
79
|
+
}
|
|
80
|
+
}).observe(document.body, { subtree: true, attributes: true, attributeFilter: ['aria-pressed', 'aria-selected'], attributeOldValue: true });
|
|
81
|
+
|
|
82
|
+
function el(tag, cls, text) {
|
|
83
|
+
const e = document.createElement(tag);
|
|
84
|
+
if (cls) e.className = cls;
|
|
85
|
+
if (text != null) e.textContent = String(text);
|
|
86
|
+
return e;
|
|
87
|
+
}
|
|
88
|
+
function svgEl(tag, attrs) {
|
|
89
|
+
const e = document.createElementNS(SVGNS, tag);
|
|
90
|
+
for (const k in attrs || {}) e.setAttribute(k, attrs[k]);
|
|
91
|
+
return e;
|
|
92
|
+
}
|
|
93
|
+
function button(cls, text, onClick, label) {
|
|
94
|
+
const b = el('button', cls, text);
|
|
95
|
+
b.type = 'button';
|
|
96
|
+
if (label) { b.setAttribute('aria-label', label); b.title = label; }
|
|
97
|
+
if (onClick) b.addEventListener('click', onClick);
|
|
98
|
+
return b;
|
|
99
|
+
}
|
|
100
|
+
const isDay = (s) => typeof s === 'string' && /^\d{4}-\d{2}-\d{2}/.test(s);
|
|
101
|
+
const dayNum = (s) => Date.UTC(+s.slice(0, 4), +s.slice(5, 7) - 1, +s.slice(8, 10)) / 864e5;
|
|
102
|
+
const between = (a, b) => Math.round(dayNum(b) - dayNum(a));
|
|
103
|
+
const fmtDay = (s) => (isDay(s) ? `${+s.slice(8, 10)} ${MON[+s.slice(5, 7) - 1]}` : (s || ''));
|
|
104
|
+
const fmtMonth = (s) => `${MON[+s.slice(5, 7) - 1]} ${s.slice(0, 4)}`;
|
|
105
|
+
const plural = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`;
|
|
106
|
+
const glyph = (state) => el('span', 'glyph g-' + state, GLYPH[state] || '▫');
|
|
107
|
+
const stateWord = (state) => {
|
|
108
|
+
const s = el('span', 'state');
|
|
109
|
+
s.append(glyph(state), ' ' + (LABEL[state] || ''));
|
|
110
|
+
return s;
|
|
111
|
+
};
|
|
112
|
+
function nextText(due) {
|
|
113
|
+
if (!isDay(due)) return 'no refresh scheduled';
|
|
114
|
+
const n = between(TODAY, due);
|
|
115
|
+
return n > 0 ? `refresh in ${plural(n, 'day')}` : n === 0 ? 'refresh due today'
|
|
116
|
+
: `due since ${plural(-n, 'day')}`;
|
|
117
|
+
}
|
|
118
|
+
function greeting() {
|
|
119
|
+
const h = new Date().getHours();
|
|
120
|
+
const g = h >= 5 && h < 12 ? 'Good morning' : h >= 12 && h < 17 ? 'Good afternoon'
|
|
121
|
+
: h >= 17 && h < 22 ? 'Good evening' : 'Late night';
|
|
122
|
+
return NAME ? `${g}, ${NAME}` : g;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/* ---- dot matrix: an authored 5x7 font drawn as lit dots over the unlit cell ---- */
|
|
126
|
+
const FONT = {
|
|
127
|
+
0: [14, 17, 19, 21, 25, 17, 14], 1: [4, 12, 4, 4, 4, 4, 14], 2: [14, 17, 1, 2, 4, 8, 31],
|
|
128
|
+
3: [31, 2, 4, 2, 1, 17, 14], 4: [2, 6, 10, 18, 31, 2, 2], 5: [31, 16, 30, 1, 1, 17, 14],
|
|
129
|
+
6: [6, 8, 16, 30, 17, 17, 14], 7: [31, 1, 2, 4, 8, 8, 8], 8: [14, 17, 17, 14, 17, 17, 14],
|
|
130
|
+
9: [14, 17, 17, 15, 1, 2, 12], A: [14, 17, 17, 17, 31, 17, 17], B: [30, 17, 17, 30, 17, 17, 30],
|
|
131
|
+
C: [14, 17, 16, 16, 16, 17, 14], D: [28, 18, 17, 17, 17, 18, 28], E: [31, 16, 16, 30, 16, 16, 31],
|
|
132
|
+
F: [31, 16, 16, 30, 16, 16, 16], G: [14, 17, 16, 23, 17, 17, 15], H: [17, 17, 17, 31, 17, 17, 17],
|
|
133
|
+
I: [14, 4, 4, 4, 4, 4, 14], J: [7, 2, 2, 2, 2, 18, 12], K: [17, 18, 20, 24, 20, 18, 17],
|
|
134
|
+
L: [16, 16, 16, 16, 16, 16, 31], M: [17, 27, 21, 21, 17, 17, 17], N: [17, 17, 25, 21, 19, 17, 17],
|
|
135
|
+
O: [14, 17, 17, 17, 17, 17, 14], P: [30, 17, 17, 30, 16, 16, 16], Q: [14, 17, 17, 17, 21, 18, 13],
|
|
136
|
+
R: [30, 17, 17, 30, 20, 18, 17], S: [15, 16, 16, 14, 1, 1, 30], T: [31, 4, 4, 4, 4, 4, 4],
|
|
137
|
+
U: [17, 17, 17, 17, 17, 17, 14], V: [17, 17, 17, 17, 17, 10, 4], W: [17, 17, 17, 21, 21, 21, 10],
|
|
138
|
+
X: [17, 17, 10, 4, 10, 17, 17], Y: [17, 17, 17, 10, 4, 4, 4], Z: [31, 1, 2, 4, 8, 16, 31],
|
|
139
|
+
':': [0, 12, 12, 0, 12, 12, 0], '.': [0, 0, 0, 0, 0, 12, 12], '-': [0, 0, 0, 31, 0, 0, 0],
|
|
140
|
+
'/': [0, 1, 2, 4, 8, 16, 0], '+': [0, 4, 4, 31, 4, 4, 0], '%': [24, 25, 2, 4, 8, 19, 3],
|
|
141
|
+
' ': [0, 0, 0, 0, 0, 0, 0],
|
|
142
|
+
};
|
|
143
|
+
const SCRAMBLE = 'ABCDEFGHKMNPRSTXZ0123456789';
|
|
144
|
+
function dmPaths(text, size) {
|
|
145
|
+
const pitch = size + 1, r = size / 2;
|
|
146
|
+
let on = '', off = '';
|
|
147
|
+
[...text].forEach((ch, ci) => {
|
|
148
|
+
const rows = FONT[ch] || FONT[' '];
|
|
149
|
+
for (let y = 0; y < 7; y++) {
|
|
150
|
+
for (let x = 0; x < 5; x++) {
|
|
151
|
+
const cx = (ci * 6 + x) * pitch + pitch / 2, cy = y * pitch + pitch / 2;
|
|
152
|
+
const d = `M${cx - r} ${cy}a${r} ${r} 0 1 0 ${size} 0a${r} ${r} 0 1 0 ${-size} 0`;
|
|
153
|
+
if (rows[y] & (16 >> x)) on += d; else off += d;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
return [on, off];
|
|
158
|
+
}
|
|
159
|
+
// A dot-matrix display of `text` (upper-cased) with `size` px dots.
|
|
160
|
+
function dm(text, size, label) {
|
|
161
|
+
const t = String(text).toUpperCase();
|
|
162
|
+
const pitch = size + 1, w = Math.max(1, t.length * 6 - 1) * pitch, h = 7 * pitch;
|
|
163
|
+
const s = svgEl('svg', { class: 'dm', viewBox: `0 0 ${w} ${h}`, width: w, height: h, role: 'img',
|
|
164
|
+
'aria-label': label || t });
|
|
165
|
+
const [on, off] = dmPaths(t, size);
|
|
166
|
+
s.append(svgEl('path', { class: 'off', d: off }), svgEl('path', { class: 'on', d: on }));
|
|
167
|
+
s.dataset.text = t;
|
|
168
|
+
s.dataset.size = size;
|
|
169
|
+
return s;
|
|
170
|
+
}
|
|
171
|
+
function dmSet(s, text) { // redraw in place (the split-flap flick)
|
|
172
|
+
const [on, off] = dmPaths(text, +s.dataset.size);
|
|
173
|
+
s.lastChild.setAttribute('d', on);
|
|
174
|
+
s.firstChild.setAttribute('d', off);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/* ---- icons: one 1.5 px stroke, round caps, currentColor ---- */
|
|
178
|
+
const ICONS = {
|
|
179
|
+
copy: ['M9 9h10v10H9z', 'M5 15V5h10'],
|
|
180
|
+
obsidian: ['M14 4h6v6', 'M20 4l-9 9', 'M18 14v5H5V6h5'],
|
|
181
|
+
focus: ['M4 9V4h5', 'M15 4h5v5', 'M20 15v5h-5', 'M9 20H4v-5', 'M12 11a1 1 0 1 0 0.01 0'],
|
|
182
|
+
target: ['M12 3v3', 'M12 18v3', 'M3 12h3', 'M18 12h3', 'M12 7a5 5 0 1 0 0.01 0', 'M12 11a1 1 0 1 0 0.01 0'],
|
|
183
|
+
search: ['M10.5 4a6.5 6.5 0 1 0 0.01 0', 'M15.5 15.5L20 20'],
|
|
184
|
+
sun: ['M12 8a4 4 0 1 0 0.01 0', 'M12 2v2', 'M12 20v2', 'M2 12h2', 'M20 12h2', 'M4.9 4.9l1.4 1.4',
|
|
185
|
+
'M17.7 17.7l1.4 1.4', 'M4.9 19.1l1.4-1.4', 'M17.7 6.3l1.4-1.4'],
|
|
186
|
+
moon: ['M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5z'],
|
|
187
|
+
close: ['M6 6l12 12', 'M18 6L6 18'],
|
|
188
|
+
chevron: ['M9 6l6 6-6 6'],
|
|
189
|
+
check: ['M5 12.5l4.5 4.5L19 7.5'],
|
|
190
|
+
help: ['M12 3a9 9 0 1 0 0.01 0', 'M9.5 9.5a2.5 2.5 0 1 1 3.5 2.3c-.7.3-1 .9-1 1.7', 'M12 17h.01'],
|
|
191
|
+
gear: ['M12 5.5a6.5 6.5 0 1 0 0.01 0', 'M12 9.5a2.5 2.5 0 1 0 0.01 0', 'M12 3v2.5', 'M12 18.5V21', 'M3 12h2.5',
|
|
192
|
+
'M18.5 12H21', 'M5.6 5.6l1.8 1.8', 'M16.6 16.6l1.8 1.8', 'M5.6 18.4l1.8-1.8', 'M16.6 7.4l1.8-1.8'],
|
|
193
|
+
lock: ['M6 11h12v9H6z', 'M8.5 11V8a3.5 3.5 0 0 1 7 0v3'],
|
|
194
|
+
unlock: ['M6 11h12v9H6z', 'M8.5 11V8a3.5 3.5 0 0 1 6.8-1.2'],
|
|
195
|
+
update: ['M12 4v11', 'M7.5 10.5L12 15l4.5-4.5', 'M5 19h14'],
|
|
196
|
+
};
|
|
197
|
+
function icon(name) {
|
|
198
|
+
const s = svgEl('svg', { class: 'ico', viewBox: '0 0 24 24', 'aria-hidden': 'true' });
|
|
199
|
+
for (const d of ICONS[name]) s.append(svgEl('path', { d }));
|
|
200
|
+
return s;
|
|
201
|
+
}
|
|
202
|
+
function iconBtn(name, label, onClick, cls) {
|
|
203
|
+
const b = button(cls || 'act', null, onClick, label);
|
|
204
|
+
b.append(icon(name));
|
|
205
|
+
return b;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/* ---- tooltip, toast, copy ---- */
|
|
209
|
+
const tip = $('tip');
|
|
210
|
+
function showTipAt(x, y, parts) {
|
|
211
|
+
tip.replaceChildren(...parts);
|
|
212
|
+
tip.hidden = false;
|
|
213
|
+
tip.style.left = Math.max(8, Math.min(x + 14, window.innerWidth - tip.offsetWidth - 8)) + 'px';
|
|
214
|
+
tip.style.top = Math.min(y + 14, window.innerHeight - tip.offsetHeight - 8) + 'px';
|
|
215
|
+
}
|
|
216
|
+
const showTip = (e, parts) => showTipAt(e.clientX, e.clientY, parts);
|
|
217
|
+
const moveTip = (e) => showTipAt(e.clientX, e.clientY, [...tip.childNodes]);
|
|
218
|
+
const hideTip = () => { tip.hidden = true; };
|
|
219
|
+
const toastEl = $('toast');
|
|
220
|
+
let toastTimer = 0;
|
|
221
|
+
function toast(msg, kind) { // kind: 'error' (read out as an alert, stays 6 s) or none
|
|
222
|
+
toastEl.textContent = msg;
|
|
223
|
+
toastEl.className = 'toast' + (kind ? ' ' + kind : '');
|
|
224
|
+
toastEl.setAttribute('role', kind === 'error' ? 'alert' : 'status');
|
|
225
|
+
toastEl.hidden = false;
|
|
226
|
+
clearTimeout(toastTimer);
|
|
227
|
+
toastTimer = setTimeout(() => { toastEl.hidden = true; }, kind === 'error' ? 6000 : 2200);
|
|
228
|
+
}
|
|
229
|
+
// a short confirmation a screen reader hears without a toast (Copied on a labelled button)
|
|
230
|
+
function announce(msg) {
|
|
231
|
+
const a = $('announce');
|
|
232
|
+
if (!a) return;
|
|
233
|
+
a.textContent = msg;
|
|
234
|
+
setTimeout(() => { if (a.textContent === msg) a.textContent = ''; }, 1500);
|
|
235
|
+
}
|
|
236
|
+
function fallbackCopy(text) {
|
|
237
|
+
const ta = el('textarea');
|
|
238
|
+
ta.value = text;
|
|
239
|
+
ta.setAttribute('readonly', '');
|
|
240
|
+
ta.style.position = 'fixed';
|
|
241
|
+
ta.style.opacity = '0';
|
|
242
|
+
document.body.append(ta);
|
|
243
|
+
ta.select();
|
|
244
|
+
let ok = false;
|
|
245
|
+
try { ok = document.execCommand('copy'); } catch (e) { ok = false; }
|
|
246
|
+
ta.remove();
|
|
247
|
+
return ok;
|
|
248
|
+
}
|
|
249
|
+
// Copy: the button turns to a check (and Copied, when it has words) for 1.5 s, as in the app;
|
|
250
|
+
// an icon-only button also says Copied in the toast. A failure says so in an error toast.
|
|
251
|
+
const copyFaces = new WeakMap(), copyTimers = new WeakMap();
|
|
252
|
+
async function copyText(text, b) {
|
|
253
|
+
let ok = false;
|
|
254
|
+
try {
|
|
255
|
+
if (navigator.clipboard && window.isSecureContext) { await navigator.clipboard.writeText(text); ok = true; }
|
|
256
|
+
} catch (e) { ok = false; }
|
|
257
|
+
if (!ok) ok = fallbackCopy(text);
|
|
258
|
+
if (!ok) { copyFace(b); toast('Copy failed. Select the text and copy it.', 'error'); return; }
|
|
259
|
+
if (!b) { toast('Copied. Paste it into Claude.'); return; }
|
|
260
|
+
if (!copyFaces.has(b)) copyFaces.set(b, [...b.childNodes]);
|
|
261
|
+
const words = copyFaces.get(b).some((n) => n.textContent.trim());
|
|
262
|
+
clearTimeout(copyTimers.get(b));
|
|
263
|
+
const ck = icon('check');
|
|
264
|
+
ck.classList.add('draw'); // the stroke is drawn (dashboard.css .ico.draw)
|
|
265
|
+
b.replaceChildren(ck, ...(words ? [' Copied'] : []));
|
|
266
|
+
if (words) announce('Copied'); else toast('Copied. Paste it into Claude.');
|
|
267
|
+
copyTimers.set(b, setTimeout(() => copyFace(b), 1500));
|
|
268
|
+
}
|
|
269
|
+
function copyFace(b) { // the button's own face again
|
|
270
|
+
if (!b || !copyFaces.has(b)) return;
|
|
271
|
+
clearTimeout(copyTimers.get(b));
|
|
272
|
+
b.replaceChildren(...copyFaces.get(b));
|
|
273
|
+
copyFaces.delete(b);
|
|
274
|
+
}
|
|
275
|
+
function copyBtn(prompt, cls) {
|
|
276
|
+
const b = iconBtn('copy', 'Copy: ' + prompt, () => copyText(prompt, b), cls);
|
|
277
|
+
return b;
|
|
278
|
+
}
|
|
279
|
+
// copied text becomes the user's own message, so it carries ids only, never note titles
|
|
280
|
+
const loopPrompt = (id) => `Let's work on the open loop [[${id}]] from Keepfold.`;
|
|
281
|
+
|
|
282
|
+
/* ---- pages, lobes, platform codes ---- */
|
|
283
|
+
const PAGES = new Map(D.pages.map((p) => [p.id, p]));
|
|
284
|
+
const GN = new Map(D.graph.nodes.map((n) => [n.id, n]));
|
|
285
|
+
const LOBES = new Map(D.clusters.map((c) => [c.id, c]));
|
|
286
|
+
const WIKI = new Set(['project', 'resource', 'note', 'decision']);
|
|
287
|
+
const KIND_WORD = { concept: 'Concept', domain: 'Domain', area: 'Area', project: 'Project',
|
|
288
|
+
resource: 'Resource', note: 'Note', decision: 'Decision', journal: 'Journal', me: 'About me',
|
|
289
|
+
mistake: 'Mistake', problem: 'Problem', assessment: 'Assessment', application: 'Application',
|
|
290
|
+
track: 'Track', session: 'Session', loop: 'Loop', person: 'Person' };
|
|
291
|
+
const kindWord = (k) => KIND_WORD[k] || k;
|
|
292
|
+
const linkIds = (v) => [].concat(v || []).flatMap((s) => [...String(s).matchAll(/\[\[([^\]|#^]+)/g)])
|
|
293
|
+
.map((m) => m[1].trim());
|
|
294
|
+
const SMALL = new Set(['and', 'of', 'the', 'a', 'an', 'in', 'on', 'for', 'to', 'with']);
|
|
295
|
+
const CODES = new Map();
|
|
296
|
+
function code(title) { // a station-style code: a short first word, else initials, else 4 letters
|
|
297
|
+
if (!CODES.has(title)) {
|
|
298
|
+
const words = String(title).toUpperCase().split(/[^A-Z0-9]+/).filter(Boolean);
|
|
299
|
+
let c = '';
|
|
300
|
+
if (words.length && words[0].length <= 5) c = words[0];
|
|
301
|
+
else {
|
|
302
|
+
const sig = words.filter((w) => !SMALL.has(w.toLowerCase()));
|
|
303
|
+
c = sig.length > 1 ? sig.map((w) => w[0]).join('').slice(0, 5) : (sig[0] || words[0] || '').slice(0, 4);
|
|
304
|
+
}
|
|
305
|
+
CODES.set(title, c || '—');
|
|
306
|
+
}
|
|
307
|
+
return CODES.get(title);
|
|
308
|
+
}
|
|
309
|
+
function lobeChip(clusterId) {
|
|
310
|
+
const c = LOBES.get(clusterId);
|
|
311
|
+
if (!c) return el('span', 'code', '—');
|
|
312
|
+
const s = el('span', 'code', code(c.title));
|
|
313
|
+
s.title = c.title;
|
|
314
|
+
s.setAttribute('aria-label', 'Lobe: ' + c.title);
|
|
315
|
+
return s;
|
|
316
|
+
}
|
|
317
|
+
const pageLobe = (id) => (PAGES.has(id) ? PAGES.get(id).cluster : null);
|
|
318
|
+
const CHAT = new Set(['Claude', 'Gemini', 'Perplexity']);
|
|
319
|
+
const MEDIA = new Set(['YouTube', 'NotebookLM']);
|
|
320
|
+
function kindGroup(p) {
|
|
321
|
+
if (p.kind === 'concept' || p.kind === 'domain' || p.kind === 'area') return 'concept';
|
|
322
|
+
if (p.kind === 'note' || p.kind === 'project' || p.kind === 'decision' || p.kind === 'person') return p.kind;
|
|
323
|
+
if (p.kind === 'resource') {
|
|
324
|
+
if (CHAT.has(p.source)) return 'chat';
|
|
325
|
+
if (MEDIA.has(p.source) || p.tags.includes('youtube') || p.tags.includes('notebooklm')) return 'youtube';
|
|
326
|
+
}
|
|
327
|
+
return 'other';
|
|
328
|
+
}
|
|
329
|
+
const dateOf = (p) => p.date || p.updated;
|
|
330
|
+
function promptFor(p) {
|
|
331
|
+
if (p.kind === 'project') return `/keepfold project ${p.id}`;
|
|
332
|
+
if (p.kind === 'concept') return `/keepfold learn ${p.id}`;
|
|
333
|
+
if (p.kind === 'loop') return loopPrompt(p.id);
|
|
334
|
+
return `/keepfold about ${p.id}`;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/* ---- Markdown reader: DOM nodes only ---- */
|
|
338
|
+
let selfId = null; // the page being drawn: a link to itself is plain text, not a button that does nothing
|
|
339
|
+
function wikilink(id, label) {
|
|
340
|
+
if (!PAGES.has(id)) return el('span', 'wl-missing', (label || id).trim());
|
|
341
|
+
const text = (label || PAGES.get(id).title).trim();
|
|
342
|
+
return id === selfId ? el('span', null, text) : button('wl', text, () => openReader(id));
|
|
343
|
+
}
|
|
344
|
+
// Inline Markdown as DOM nodes: text nodes only, images dropped, [label](url) keeps the label.
|
|
345
|
+
const INLINE = new RegExp(['(`+)([\\s\\S]*?)\\1', '!\\[[^\\]]*\\]\\([^)]*\\)',
|
|
346
|
+
'\\[\\[([^\\]|#]+)(?:#[^\\]|]*)?(?:\\|([^\\]]*))?\\]\\]', '\\[([^\\]]*)\\]\\([^)]*\\)',
|
|
347
|
+
'\\*\\*(.+?)\\*\\*', '(?<!\\w)__(.+?)__(?!\\w)', '\\*(.+?)\\*', '(?<!\\w)_(.+?)_(?!\\w)'].join('|'), 'g');
|
|
348
|
+
function inline(text, into) {
|
|
349
|
+
let i = 0;
|
|
350
|
+
for (const m of text.matchAll(INLINE)) {
|
|
351
|
+
if (m.index > i) into.append(text.slice(i, m.index));
|
|
352
|
+
i = m.index + m[0].length;
|
|
353
|
+
if (m[1]) into.append(el('code', null, m[2]));
|
|
354
|
+
else if (m[3]) into.append(wikilink(m[3].trim(), m[4]));
|
|
355
|
+
else if (m[5] != null) inline(m[5], into);
|
|
356
|
+
else if (m[6] || m[7]) inline(m[6] || m[7], into.appendChild(el('strong')));
|
|
357
|
+
else if (m[8] || m[9]) inline(m[8] || m[9], into.appendChild(el('em')));
|
|
358
|
+
}
|
|
359
|
+
if (i < text.length) into.append(text.slice(i));
|
|
360
|
+
return into;
|
|
361
|
+
}
|
|
362
|
+
// an escaped pipe (\|) is text inside a cell, not a border
|
|
363
|
+
const cells = (l) => l.trim().replace(/^\||(?<!\\)\|$/g, '').split(/(?<!\\)\|/)
|
|
364
|
+
.map((c) => c.trim().replace(/\\\|/g, '|'));
|
|
365
|
+
// Block Markdown: headings, paragraphs, lists, fenced code, blockquotes, tables, rules.
|
|
366
|
+
const QUOTE_DEPTH = 20; // deeper quotes render as text: untrusted nesting must not blow the stack
|
|
367
|
+
function md(src, depth = 0) {
|
|
368
|
+
const out = document.createDocumentFragment();
|
|
369
|
+
const lines = src.replace(/\r\n?/g, '\n').split('\n');
|
|
370
|
+
let para = [], list = null;
|
|
371
|
+
const flush = () => {
|
|
372
|
+
if (para.length) out.append(inline(para.join(' '), el('p')));
|
|
373
|
+
para = [];
|
|
374
|
+
list = null;
|
|
375
|
+
};
|
|
376
|
+
for (let i = 0; i < lines.length; i++) {
|
|
377
|
+
const line = lines[i];
|
|
378
|
+
let m;
|
|
379
|
+
if ((m = /^\s*(```+|~~~+)/.exec(line))) {
|
|
380
|
+
flush();
|
|
381
|
+
const code = [];
|
|
382
|
+
while (++i < lines.length && !lines[i].trim().startsWith(m[1])) code.push(lines[i]);
|
|
383
|
+
const pre = el('pre');
|
|
384
|
+
pre.append(el('code', null, code.join('\n')));
|
|
385
|
+
out.append(pre);
|
|
386
|
+
} else if (!line.trim()) flush();
|
|
387
|
+
else if ((m = /^(#{1,6})\s+(.*?)\s*#*$/.exec(line))) {
|
|
388
|
+
flush();
|
|
389
|
+
out.append(inline(m[2], el('h' + Math.min(6, m[1].length + 3), 'md-h' + m[1].length)));
|
|
390
|
+
} else if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) { flush(); out.append(el('hr')); }
|
|
391
|
+
else if (line.startsWith('>')) {
|
|
392
|
+
flush();
|
|
393
|
+
const q = [];
|
|
394
|
+
for (; i < lines.length && lines[i].startsWith('>'); i++) q.push(lines[i].replace(/^>\s?/, ''));
|
|
395
|
+
i--;
|
|
396
|
+
const bq = el('blockquote');
|
|
397
|
+
bq.append(depth < QUOTE_DEPTH ? md(q.join('\n'), depth + 1) : el('p', null, q.join('\n')));
|
|
398
|
+
out.append(bq);
|
|
399
|
+
} else if (line.trim().startsWith('|') && /^\s*\|?[\s:|-]*-[\s:|-]*$/.test(lines[i + 1] || '')) {
|
|
400
|
+
flush();
|
|
401
|
+
const tr = el('tr'), thead = el('thead'), tbody = el('tbody'), table = el('table');
|
|
402
|
+
for (const c of cells(line)) tr.append(inline(c, el('th')));
|
|
403
|
+
thead.append(tr);
|
|
404
|
+
for (i += 2; i < lines.length && lines[i].trim().startsWith('|'); i++) {
|
|
405
|
+
const r = el('tr');
|
|
406
|
+
for (const c of cells(lines[i])) r.append(inline(c, el('td')));
|
|
407
|
+
tbody.append(r);
|
|
408
|
+
}
|
|
409
|
+
i--;
|
|
410
|
+
table.append(thead, tbody);
|
|
411
|
+
const wrap = el('div', 'md-table');
|
|
412
|
+
wrap.append(table);
|
|
413
|
+
out.append(wrap);
|
|
414
|
+
} else if ((m = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(line))) {
|
|
415
|
+
if (para.length) flush();
|
|
416
|
+
const tag = /\d/.test(m[2]) ? 'OL' : 'UL';
|
|
417
|
+
if (!list || list.tagName !== tag) { list = el(tag); out.append(list); }
|
|
418
|
+
const li = el('li');
|
|
419
|
+
const depth = Math.floor(m[1].replace(/\t/g, ' ').length / 2);
|
|
420
|
+
if (depth) li.style.marginLeft = (16 * depth) + 'px';
|
|
421
|
+
let t = m[3];
|
|
422
|
+
const box = /^\[([ xX])\]\s+/.exec(t);
|
|
423
|
+
if (box) { li.append(box[1] === ' ' ? '☐ ' : '☑ '); t = t.slice(box[0].length); }
|
|
424
|
+
list.append(inline(t, li));
|
|
425
|
+
} else if (list && /^\s+\S/.test(line)) inline(' ' + line.trim(), list.lastChild);
|
|
426
|
+
else { list = null; para.push(line.trim()); }
|
|
427
|
+
}
|
|
428
|
+
flush();
|
|
429
|
+
return out;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
let BACK = null;
|
|
433
|
+
function backlinks(id) {
|
|
434
|
+
if (!BACK) {
|
|
435
|
+
BACK = new Map();
|
|
436
|
+
for (const p of D.pages) {
|
|
437
|
+
for (const t of p.links) {
|
|
438
|
+
if (!BACK.has(t)) BACK.set(t, []);
|
|
439
|
+
BACK.get(t).push(p);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
const marks = ['[[' + id + ']]', '[[' + id + '|', '[[' + id + '#'];
|
|
444
|
+
return (BACK.get(id) || []).map((p) => ({ p, line: (p.body.split('\n')
|
|
445
|
+
.find((l) => marks.some((k) => l.includes(k))) || '').replace(/^[\s>#*+-]+/, '').slice(0, 240) }));
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// shortcut: a linear scan over a precomputed lowercase index; ~5k pages scan in tens of ms.
|
|
449
|
+
let HAY = null;
|
|
450
|
+
function search(q, tag) {
|
|
451
|
+
if (!HAY) {
|
|
452
|
+
HAY = D.pages.map((p) => ({ p, t: p.title.toLowerCase(),
|
|
453
|
+
a: [].concat(p.props.aliases || []).join(' ').toLowerCase(),
|
|
454
|
+
s: (p.summary || '').toLowerCase(), b: p.body.toLowerCase() }));
|
|
455
|
+
}
|
|
456
|
+
const words = q.toLowerCase().split(/\s+/).filter(Boolean);
|
|
457
|
+
const hits = [];
|
|
458
|
+
for (const h of HAY) {
|
|
459
|
+
if (tag && !h.p.tags.includes(tag)) continue;
|
|
460
|
+
let score = 0;
|
|
461
|
+
for (const w of words) {
|
|
462
|
+
const s = h.t.includes(w) ? 4 : h.a.includes(w) ? 3 : h.s.includes(w) ? 2 : h.b.includes(w) ? 1 : 0;
|
|
463
|
+
if (!s) { score = -1; break; }
|
|
464
|
+
score += s;
|
|
465
|
+
}
|
|
466
|
+
if (score >= 0) hits.push({ h, words, score });
|
|
467
|
+
}
|
|
468
|
+
return hits.sort((x, y) => y.score - x.score || x.h.p.title.localeCompare(y.h.p.title));
|
|
469
|
+
}
|
|
470
|
+
function snippet({ h, words }) {
|
|
471
|
+
const i = Math.min(...words.map((w) => h.b.indexOf(w)).filter((j) => j >= 0));
|
|
472
|
+
if (!isFinite(i)) return h.p.summary || '';
|
|
473
|
+
const s = h.p.body.slice(Math.max(0, i - 40), i + 100)
|
|
474
|
+
.replace(/\[\[(?:[^\]|]*\|)?([^\]]*)\]\]/g, '$1').replace(/[#*_`>|]/g, '').replace(/\s+/g, ' ').trim();
|
|
475
|
+
return (i > 40 ? '…' : '') + s + '…';
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/* ---- reader panel: one for every section ---- */
|
|
479
|
+
const reader = $('reader');
|
|
480
|
+
let readerId = null, readerFrom = null;
|
|
481
|
+
function readerSection(title, list) {
|
|
482
|
+
if (!list.length) return [];
|
|
483
|
+
const ul = el('ul');
|
|
484
|
+
for (const li of list) ul.append(li);
|
|
485
|
+
return [el('h4', null, title), ul];
|
|
486
|
+
}
|
|
487
|
+
function chipTo(id) {
|
|
488
|
+
const n = GN.get(id) || PAGES.get(id);
|
|
489
|
+
return button('chip', n ? n.title : id, () => openReader(id));
|
|
490
|
+
}
|
|
491
|
+
function groupCounts(n) {
|
|
492
|
+
const key = n.kind === 'domain' ? 'domain' : 'area';
|
|
493
|
+
const c = Object.fromEntries(STATES.map((s) => [s, 0]));
|
|
494
|
+
for (const x of D.graph.nodes) if (x.kind === 'concept' && x[key] === n.id) c[x.state]++;
|
|
495
|
+
return c;
|
|
496
|
+
}
|
|
497
|
+
function conceptDetails(n) {
|
|
498
|
+
const out = [];
|
|
499
|
+
const dom = GN.get(n.domain), area = GN.get(n.area);
|
|
500
|
+
if (n.kind === 'concept') {
|
|
501
|
+
const m = el('div', 'meta');
|
|
502
|
+
m.append(stateWord(n.state));
|
|
503
|
+
out.push(m, el('div', 'meta muted', [dom && dom.title, area && area.title].filter(Boolean).join(' › ')),
|
|
504
|
+
el('div', 'meta', nextText(n.next_due)));
|
|
505
|
+
const d = D.details[n.id] || {};
|
|
506
|
+
if (d.leech) out.push(el('div', 'meta', d.leech));
|
|
507
|
+
// display only: how long answers took never changes a grade or a schedule
|
|
508
|
+
if (d.answer_secs != null) out.push(el('div', 'meta muted', `Usually answers in about ${d.answer_secs} s`));
|
|
509
|
+
const mist = new Map(D.mistakes.map((x) => [x.id, x]));
|
|
510
|
+
out.push(...readerSection('Open mistakes', (d.mistakes || []).map((id) => {
|
|
511
|
+
const mm = mist.get(id), li = el('li');
|
|
512
|
+
li.append(el('span', 'flag', '⚑ '), mm ? mm.title : id, el('span', 'muted', mm ? ` (${mm.count}×)` : ''));
|
|
513
|
+
return li;
|
|
514
|
+
})));
|
|
515
|
+
out.push(...readerSection('Evidence trail', (d.evidence || []).map((ev) => el('li', null,
|
|
516
|
+
[fmtDay(ev.day), VERDICT[ev.verdict] || ev.verdict, ev.item_type, ev.source].filter(Boolean).join(' · ')))));
|
|
517
|
+
for (const [title, ids] of [['Requires', d.requires || []], ['Required by', d.required_by || []]]) {
|
|
518
|
+
if (!ids.length) continue;
|
|
519
|
+
const box = el('div', 'chip-list');
|
|
520
|
+
for (const id of ids) box.append(chipTo(id));
|
|
521
|
+
out.push(el('h4', null, title), box);
|
|
522
|
+
}
|
|
523
|
+
out.push(...readerSection('Problems', (d.problems || []).map((p) => {
|
|
524
|
+
const li = el('li');
|
|
525
|
+
li.append(p.title, el('span', 'muted', p.status ? ' · ' + p.status : ''));
|
|
526
|
+
return li;
|
|
527
|
+
})));
|
|
528
|
+
if (!d.evidence || !d.evidence.length) out.push(el('p', 'empty', 'No evidence yet. Try /keepfold learn on it.'));
|
|
529
|
+
} else {
|
|
530
|
+
if (n.kind === 'area' && dom) out.push(el('div', 'meta muted', dom.title));
|
|
531
|
+
const c = groupCounts(n), total = STATES.reduce((a, s) => a + c[s], 0);
|
|
532
|
+
out.push(el('div', 'meta', total ? `${Math.round(100 * c.solid / total)}% solid · ${plural(total, 'topic')}`
|
|
533
|
+
: 'No topics yet'));
|
|
534
|
+
out.push(...readerSection('Topics by state', STATES.filter((s) => c[s]).map((s) => {
|
|
535
|
+
const li = el('li');
|
|
536
|
+
li.append(stateWord(s), el('span', 'muted', ' ' + c[s]));
|
|
537
|
+
return li;
|
|
538
|
+
})));
|
|
539
|
+
}
|
|
540
|
+
return out;
|
|
541
|
+
}
|
|
542
|
+
function pageView(p) {
|
|
543
|
+
const out = [];
|
|
544
|
+
selfId = p.id;
|
|
545
|
+
if (p.summary) out.push(el('p', 'summary', p.summary));
|
|
546
|
+
if (p.tags.length) {
|
|
547
|
+
const box = el('div', 'chip-list');
|
|
548
|
+
for (const t of p.tags) box.append(button('chip', '#' + t, () => setTag(t), 'Show pages tagged ' + t + ' in the Library'));
|
|
549
|
+
out.push(box);
|
|
550
|
+
}
|
|
551
|
+
const keys = Object.keys(p.props);
|
|
552
|
+
if (keys.length) {
|
|
553
|
+
const table = el('table', 'props'), tbody = el('tbody');
|
|
554
|
+
for (const k of keys) {
|
|
555
|
+
const tr = el('tr'), th = el('th', null, k), td = el('td');
|
|
556
|
+
th.scope = 'row';
|
|
557
|
+
[].concat(p.props[k]).forEach((v, i) => { if (i) td.append(', '); inline(String(v), td); });
|
|
558
|
+
tr.append(th, td);
|
|
559
|
+
tbody.append(tr);
|
|
560
|
+
}
|
|
561
|
+
table.append(tbody);
|
|
562
|
+
out.push(el('h4', null, 'Properties'), table);
|
|
563
|
+
}
|
|
564
|
+
const body = el('div', 'md');
|
|
565
|
+
body.append(md(p.body));
|
|
566
|
+
out.push(body);
|
|
567
|
+
if (p.links.length) {
|
|
568
|
+
const box = el('div', 'chip-list');
|
|
569
|
+
for (const id of p.links) box.append(chipTo(id));
|
|
570
|
+
out.push(el('h4', null, 'Links'), box);
|
|
571
|
+
}
|
|
572
|
+
out.push(el('h4', null, 'Backlinks'));
|
|
573
|
+
const back = backlinks(p.id);
|
|
574
|
+
if (!back.length) out.push(el('p', 'empty', 'No backlinks: no other page links here yet.'));
|
|
575
|
+
else {
|
|
576
|
+
const ul = el('ul', 'backlinks');
|
|
577
|
+
for (const { p: from, line } of back) {
|
|
578
|
+
const li = el('li');
|
|
579
|
+
li.append(button('chip', from.title, () => openReader(from.id)));
|
|
580
|
+
if (line) li.append(inline(line, el('div', 'muted small')));
|
|
581
|
+
ul.append(li);
|
|
582
|
+
}
|
|
583
|
+
out.push(ul);
|
|
584
|
+
}
|
|
585
|
+
selfId = null;
|
|
586
|
+
return out;
|
|
587
|
+
}
|
|
588
|
+
// The right-side panel, emptied and titled: the reader, or the brain's compact inspector.
|
|
589
|
+
function panel(id, title, inspector) {
|
|
590
|
+
closeLook(false); // the inspector and Look share the right side; the newer one wins
|
|
591
|
+
if (reader.hidden) readerFrom = document.activeElement;
|
|
592
|
+
readerId = id;
|
|
593
|
+
hideTip();
|
|
594
|
+
reader.replaceChildren();
|
|
595
|
+
reader.classList.toggle('inspector', !!inspector);
|
|
596
|
+
reader.setAttribute('aria-label', inspector ? 'Brain inspector' : 'Page reader');
|
|
597
|
+
reader.hidden = false;
|
|
598
|
+
reader.scrollTop = 0;
|
|
599
|
+
reader.append(iconBtn('close', `Close the ${inspector ? 'inspector' : 'reader'} (Esc)`, closeReader, 'icon-btn close'),
|
|
600
|
+
el('h2', null, title));
|
|
601
|
+
}
|
|
602
|
+
function openReader(id, keep) { // keep: a live refresh (no focus moved, the scroll kept)
|
|
603
|
+
const p = PAGES.get(id), n = GN.get(id), top = reader.scrollTop;
|
|
604
|
+
if (!p && !n) return;
|
|
605
|
+
panel(id, p ? p.title : n.title, false);
|
|
606
|
+
const meta = el('div', 'rmeta');
|
|
607
|
+
meta.append(el('span', null, kindWord(p ? p.kind : n.kind)));
|
|
608
|
+
if (p) {
|
|
609
|
+
const lobe = LOBES.get(p.cluster);
|
|
610
|
+
meta.append(lobeChip(p.cluster));
|
|
611
|
+
if (lobe) meta.append(el('span', null, lobe.title));
|
|
612
|
+
if (p.date) meta.append(el('span', null, fmtDay(p.date) + ' ' + p.date.slice(0, 4)));
|
|
613
|
+
if (p.source) meta.append(el('span', null, p.source));
|
|
614
|
+
}
|
|
615
|
+
reader.append(meta);
|
|
616
|
+
const acts = el('div', 'ractions');
|
|
617
|
+
if (p) {
|
|
618
|
+
const sib = button('btn', null, () => showInBrain(id));
|
|
619
|
+
sib.append(icon('target'), ' Show in brain');
|
|
620
|
+
acts.append(obsidianBtn(p), sib, promptBtn(p));
|
|
621
|
+
}
|
|
622
|
+
reader.append(acts);
|
|
623
|
+
if (n && (n.kind === 'concept' || n.kind === 'domain' || n.kind === 'area')) reader.append(...conceptDetails(n));
|
|
624
|
+
if (p) reader.append(...pageView(p));
|
|
625
|
+
G.setCurrent(id);
|
|
626
|
+
if (keep) reader.scrollTop = top;
|
|
627
|
+
else reader.querySelector('.close').focus({ preventScroll: true });
|
|
628
|
+
}
|
|
629
|
+
function obsidianBtn(p) {
|
|
630
|
+
const a = el('a', 'btn', null);
|
|
631
|
+
a.append(icon('obsidian'), ' Open in Obsidian');
|
|
632
|
+
a.href = 'obsidian://open?vault=' + encodeURIComponent(D.vault_name)
|
|
633
|
+
+ '&file=' + encodeURIComponent(p.path);
|
|
634
|
+
return a;
|
|
635
|
+
}
|
|
636
|
+
function promptBtn(p) {
|
|
637
|
+
const cp = button('btn', null, () => copyText(promptFor(p), cp));
|
|
638
|
+
cp.append(icon('copy'), ' Copy prompt');
|
|
639
|
+
cp.title = promptFor(p);
|
|
640
|
+
return cp;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/* ---- the brain inspector: a page's neighbourhood, or a lobe ---- */
|
|
644
|
+
const DEG = new Map(); // undirected link degree, for "top pages" lists
|
|
645
|
+
countDegrees();
|
|
646
|
+
function countDegrees() {
|
|
647
|
+
DEG.clear();
|
|
648
|
+
const seen = new Set();
|
|
649
|
+
for (const p of D.pages) {
|
|
650
|
+
for (const t of p.links) {
|
|
651
|
+
if (t === p.id || !PAGES.has(t)) continue;
|
|
652
|
+
const key = p.id < t ? p.id + '\n' + t : t + '\n' + p.id;
|
|
653
|
+
if (seen.has(key)) continue;
|
|
654
|
+
seen.add(key);
|
|
655
|
+
DEG.set(p.id, (DEG.get(p.id) || 0) + 1);
|
|
656
|
+
DEG.set(t, (DEG.get(t) || 0) + 1);
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
const topPagesOf = (lobeId, n) => D.pages.filter((p) => p.cluster === lobeId)
|
|
661
|
+
.sort((a, b) => (DEG.get(b.id) || 0) - (DEG.get(a.id) || 0) || a.title.localeCompare(b.title)).slice(0, n);
|
|
662
|
+
const live = (msg) => { const r = $('brain-live'); r.textContent = ''; setTimeout(() => { r.textContent = msg; }, 30); };
|
|
663
|
+
function ilist(ids, cls) {
|
|
664
|
+
const ul = el('ul', 'ilist');
|
|
665
|
+
for (const id of ids) {
|
|
666
|
+
const p = PAGES.get(id);
|
|
667
|
+
if (!p) continue;
|
|
668
|
+
const li = el('li');
|
|
669
|
+
if (cls) { // the same solid / dashed marks as the brain's lines
|
|
670
|
+
const mk = el('span', 'mk ' + cls);
|
|
671
|
+
mk.setAttribute('aria-hidden', 'true');
|
|
672
|
+
li.append(mk);
|
|
673
|
+
}
|
|
674
|
+
li.append(button('linkbtn', p.title, () => explorePage(id)));
|
|
675
|
+
ul.append(li);
|
|
676
|
+
}
|
|
677
|
+
return ul;
|
|
678
|
+
}
|
|
679
|
+
// Fly to a page, light its neighbourhood and show it in the inspector.
|
|
680
|
+
function explorePage(id) {
|
|
681
|
+
const info = brain && brain.explore(id);
|
|
682
|
+
if (info) inspectPage(id, info);
|
|
683
|
+
else openReader(id);
|
|
684
|
+
}
|
|
685
|
+
function inspectPage(id, info) {
|
|
686
|
+
const p = PAGES.get(id);
|
|
687
|
+
if (!p) return;
|
|
688
|
+
panel(id, p.title, true);
|
|
689
|
+
const meta = el('div', 'rmeta'), lobe = LOBES.get(p.cluster), st = GN.has(id) ? GN.get(id).state : null;
|
|
690
|
+
meta.append(el('span', null, kindWord(p.kind)), lobeChip(p.cluster));
|
|
691
|
+
if (lobe) meta.append(el('span', null, lobe.title));
|
|
692
|
+
if (p.kind === 'concept' && st) meta.append(stateWord(st));
|
|
693
|
+
if (dateOf(p)) meta.append(el('span', null, fmtDay(dateOf(p)) + ' ' + dateOf(p).slice(0, 4)));
|
|
694
|
+
const acts = el('div', 'ractions'), open = button('btn', 'Open page', () => openReader(id));
|
|
695
|
+
const lib = button('btn', 'Show in Library', () => libraryFind(p.title));
|
|
696
|
+
acts.append(open, obsidianBtn(p), promptBtn(p), lib);
|
|
697
|
+
reader.append(meta, acts);
|
|
698
|
+
const beacons = (info.beacons || []).filter((l) => LOBES.has(l));
|
|
699
|
+
if (beacons.length) {
|
|
700
|
+
const box = el('div', 'file-under'), row = el('div', 'ractions');
|
|
701
|
+
box.append(el('h4', null, 'File this chat under…'));
|
|
702
|
+
for (const l of beacons) {
|
|
703
|
+
const t = LOBES.get(l).title, b = button('btn', null,
|
|
704
|
+
() => copyText(`File the chat [[${p.id}]] under the topic [[${l.replace(/^domain:/, '')}]] in Keepfold.`, b));
|
|
705
|
+
b.append(icon('copy'), ' ' + t);
|
|
706
|
+
b.title = `Copy: file this chat under ${t}`;
|
|
707
|
+
row.append(b);
|
|
708
|
+
}
|
|
709
|
+
box.append(row);
|
|
710
|
+
reader.append(box);
|
|
711
|
+
}
|
|
712
|
+
reader.append(el('h4', null, `Linked (${info.linked.length + info.hiddenLinks})`));
|
|
713
|
+
if (info.linked.length) reader.append(ilist(info.linked, 'linked'));
|
|
714
|
+
else reader.append(el('p', 'empty', 'No links.'));
|
|
715
|
+
if (info.hiddenLinks > 0) reader.append(el('p', 'muted small', `+${info.hiddenLinks} more links (open the page for all of them)`));
|
|
716
|
+
reader.append(el('h4', null, 'Similar meaning'));
|
|
717
|
+
if (info.similar.length) reader.append(ilist(info.similar, 'similar'));
|
|
718
|
+
else reader.append(el('p', 'empty', 'No similar pages beyond the links.'));
|
|
719
|
+
markOutline(id);
|
|
720
|
+
live(`Selected ${p.title}, ${kindWord(p.kind)}${lobe ? ' in ' + lobe.title : ''}: `
|
|
721
|
+
+ `${plural(info.linked.length + info.hiddenLinks, 'link')}, ${info.similar.length} similar.`);
|
|
722
|
+
}
|
|
723
|
+
/* ---- a website of the brain's stem: its details from the browsing store (the app's own
|
|
724
|
+
route, never a vault page); a private one only while the Private switch is on ---- */
|
|
725
|
+
const siteWords = (n) => ['Website', String(n.category || 'other').replace(/-/g, ' '), plural(n.visits, 'visit')]
|
|
726
|
+
.concat(n.private ? ['private'] : []);
|
|
727
|
+
function exploreSite(id) {
|
|
728
|
+
const n = brain && brain.node(id);
|
|
729
|
+
if (n && brain.explore(id)) inspectSite(n);
|
|
730
|
+
}
|
|
731
|
+
async function inspectSite(n) {
|
|
732
|
+
const id = n.id, gen = privGen;
|
|
733
|
+
panel(id, n.title, true);
|
|
734
|
+
const meta = el('div', 'rmeta');
|
|
735
|
+
for (const w of siteWords(n)) meta.append(el('span', null, w));
|
|
736
|
+
reader.append(meta);
|
|
737
|
+
live(`Selected ${n.title}, ${siteWords(n).join(', ')}.`);
|
|
738
|
+
markOutline(id);
|
|
739
|
+
let s = null;
|
|
740
|
+
try {
|
|
741
|
+
s = await api('/api/home/site?site=' + encodeURIComponent(n.site) + (PRIVATE ? '&private=1' : ''));
|
|
742
|
+
} catch (e) {
|
|
743
|
+
if (readerId === id && gen === privGen) reader.append(el('p', 'empty', e.status === 404
|
|
744
|
+
? 'This website is not in the browsing store any more.' : 'Keepfold is not answering.'));
|
|
745
|
+
return;
|
|
746
|
+
}
|
|
747
|
+
if (readerId !== id || gen !== privGen || reader.hidden) return; // moved on, or the switch moved meanwhile
|
|
748
|
+
const days = s.days || [];
|
|
749
|
+
if (days.length) meta.append(el('span', null, `first ${fmtDay(days[0])} ${days[0].slice(0, 4)}`),
|
|
750
|
+
el('span', null, `last ${fmtDay(days[days.length - 1])} ${days[days.length - 1].slice(0, 4)}`));
|
|
751
|
+
if (s.description) reader.append(el('p', 'summary', s.description));
|
|
752
|
+
const recent = days.slice(-60).reverse().map(fmtDay).join(', ');
|
|
753
|
+
reader.append(el('h4', null, `Visit days (${days.length})`),
|
|
754
|
+
el('p', 'muted small', recent + (days.length > 60 ? `, and ${days.length - 60} earlier` : '')));
|
|
755
|
+
const counted = (rows) => rows.map(([t, c]) => { const li = el('li'); li.append(el('span', null, t), el('span', 'n', `${c}×`)); return li; });
|
|
756
|
+
reader.append(...readerSection('Searched here', counted(s.searches || [])),
|
|
757
|
+
...readerSection('Searches that led here', counted(s.led || [])),
|
|
758
|
+
...readerSection('Pages read', (s.titles || []).map((t) => el('li', null, t))));
|
|
759
|
+
const hubs = (s.hubs || []).filter((h) => PAGES.has(h.id));
|
|
760
|
+
if (hubs.length) {
|
|
761
|
+
const box = el('div', 'chip-list');
|
|
762
|
+
for (const h of hubs) box.append(button('chip', h.title, () => explorePage(h.id)));
|
|
763
|
+
reader.append(el('h4', null, 'Topics'), box);
|
|
764
|
+
}
|
|
765
|
+
const rel = (s.related || []).filter((x) => BRAIN_IDS.has('site:' + x));
|
|
766
|
+
if (rel.length) {
|
|
767
|
+
const box = el('div', 'chip-list');
|
|
768
|
+
for (const x of rel) box.append(button('chip', x, () => exploreSite('site:' + x)));
|
|
769
|
+
reader.append(el('h4', null, 'Related websites'), box);
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
function inspectLobe(lobeId) {
|
|
773
|
+
const c = LOBES.get(lobeId), k = D.clusters.findIndex((x) => x.id === lobeId);
|
|
774
|
+
if (!c) return;
|
|
775
|
+
panel(null, c.title, true);
|
|
776
|
+
const meta = el('div', 'rmeta');
|
|
777
|
+
meta.append(lobeChip(lobeId), el('span', null, plural(c.count, 'page')));
|
|
778
|
+
const acts = el('div', 'ractions');
|
|
779
|
+
acts.append(button('btn', 'Show in Library', () => { filterLibraryLobe(lobeId); show('library'); }));
|
|
780
|
+
reader.append(meta, acts);
|
|
781
|
+
const tracts = ((D.brain && D.brain.tracts) || []).filter((t) => t.a === k || t.b === k)
|
|
782
|
+
.map((t) => ({ l: D.clusters[t.a === k ? t.b : t.a], n: t.n })).filter((t) => t.l)
|
|
783
|
+
.sort((a, b) => b.n - a.n).slice(0, 5);
|
|
784
|
+
if (tracts.length) {
|
|
785
|
+
const ul = el('ul', 'ilist');
|
|
786
|
+
for (const t of tracts) {
|
|
787
|
+
const li = el('li');
|
|
788
|
+
li.append(el('span', null, 'connected to '), button('linkbtn', t.l.title, () => selectLobe(t.l.id)),
|
|
789
|
+
el('span', 'n', `(${plural(t.n, 'link')})`));
|
|
790
|
+
ul.append(li);
|
|
791
|
+
}
|
|
792
|
+
reader.append(el('h4', null, 'Strongest connections'), ul);
|
|
793
|
+
}
|
|
794
|
+
const top = topPagesOf(lobeId, 20);
|
|
795
|
+
reader.append(el('h4', null, `Pages (top ${top.length} by links)`), ilist(top.map((p) => p.id), null));
|
|
796
|
+
live(`${c.title}: ${plural(c.count, 'page')}.`);
|
|
797
|
+
}
|
|
798
|
+
function closeReader() {
|
|
799
|
+
if (reader.hidden) return;
|
|
800
|
+
reader.hidden = true;
|
|
801
|
+
readerId = null;
|
|
802
|
+
G.setCurrent(null);
|
|
803
|
+
if (readerFrom && readerFrom.isConnected) readerFrom.focus({ preventScroll: true });
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
/* ---- sections and routing ---- */
|
|
807
|
+
// Study only for someone who studies (dashboard.studies), decided once per page load
|
|
808
|
+
const STUDIES = D.studies !== false;
|
|
809
|
+
const SECTIONS = ['home', 'brain', 'library', 'you', 'timeline', 'ideas', 'study', 'help']
|
|
810
|
+
.filter((s) => STUDIES || s !== 'study');
|
|
811
|
+
if (!STUDIES) { $('tab-study').remove(); $('view-study').remove(); }
|
|
812
|
+
const TITLES = { home: 'Home', brain: 'Brain', library: 'Library', you: 'You', timeline: 'Timeline',
|
|
813
|
+
ideas: 'Ideas', study: 'Study', help: 'Help' };
|
|
814
|
+
const rendered = new Set(), stale = new Set(); // stale: rendered from older data (live home)
|
|
815
|
+
let current = null;
|
|
816
|
+
const sel = $('section-select');
|
|
817
|
+
for (const s of SECTIONS) { const o = el('option', null, TITLES[s]); o.value = s; sel.append(o); }
|
|
818
|
+
sel.addEventListener('change', () => show(sel.value));
|
|
819
|
+
function show(name, focusTab) {
|
|
820
|
+
if (!SECTIONS.includes(name)) name = 'home';
|
|
821
|
+
hideTip();
|
|
822
|
+
if (name !== current) {
|
|
823
|
+
closeLook(false);
|
|
824
|
+
for (const s of SECTIONS) {
|
|
825
|
+
const t = $('tab-' + s);
|
|
826
|
+
t.setAttribute('aria-selected', String(s === name));
|
|
827
|
+
t.tabIndex = s === name ? 0 : -1;
|
|
828
|
+
$('view-' + s).hidden = s !== name;
|
|
829
|
+
}
|
|
830
|
+
sel.value = name;
|
|
831
|
+
current = name;
|
|
832
|
+
try { history.replaceState(null, '', '#' + name); } catch (e) { /* a file URL may refuse */ }
|
|
833
|
+
if (!rendered.has(name)) { rendered.add(name); RENDER[name](); }
|
|
834
|
+
else if (stale.delete(name)) rerender(name);
|
|
835
|
+
if (name === 'home') placeBrain('home-brain-slot');
|
|
836
|
+
else clearLens(); // the lens is Home's
|
|
837
|
+
if (name === 'brain') setView(view);
|
|
838
|
+
window.scrollTo(0, 0);
|
|
839
|
+
}
|
|
840
|
+
if (focusTab) $('tab-' + name).focus();
|
|
841
|
+
}
|
|
842
|
+
for (const s of SECTIONS) $('tab-' + s).addEventListener('click', () => show(s));
|
|
843
|
+
$('tabs').addEventListener('keydown', (e) => {
|
|
844
|
+
const f = SECTIONS.indexOf(String(e.target.id).replace('tab-', '')), i = f >= 0 ? f : SECTIONS.indexOf(current);
|
|
845
|
+
const to = { ArrowRight: i + 1, ArrowLeft: i - 1, Home: 0, End: SECTIONS.length - 1 }[e.key];
|
|
846
|
+
if (to === undefined) return;
|
|
847
|
+
e.preventDefault();
|
|
848
|
+
show(SECTIONS[(to + SECTIONS.length) % SECTIONS.length], true);
|
|
849
|
+
});
|
|
850
|
+
window.addEventListener('hashchange', () => show(location.hash.slice(1)));
|
|
851
|
+
const typing = (t) => t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT'
|
|
852
|
+
|| t.isContentEditable);
|
|
853
|
+
document.addEventListener('keydown', (e) => {
|
|
854
|
+
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k') { e.preventDefault(); openPalette(); return; }
|
|
855
|
+
if (e.key === 'Escape') {
|
|
856
|
+
if (!$('palette').hidden) { closePalette(); return; }
|
|
857
|
+
if (!look.hidden) { closeLook(true); return; }
|
|
858
|
+
if (!reader.hidden) { closeReader(); return; }
|
|
859
|
+
if (cold) { closeCold(); return; }
|
|
860
|
+
hideTip();
|
|
861
|
+
return;
|
|
862
|
+
}
|
|
863
|
+
if (e.ctrlKey || e.metaKey || e.altKey || typing(e.target) || !$('palette').hidden) return;
|
|
864
|
+
// the brain uses + - 0, arrows and A M G S; the outline uses arrows
|
|
865
|
+
if (e.target && e.target.closest && e.target.closest('.brain-host, .outline')) return;
|
|
866
|
+
const n = +e.key;
|
|
867
|
+
if (n >= 1 && n <= SECTIONS.length) { e.preventDefault(); show(SECTIONS[n - 1]); }
|
|
868
|
+
});
|
|
869
|
+
function setHdr() {
|
|
870
|
+
document.documentElement.style.setProperty('--hdr', $('top').offsetHeight + 'px');
|
|
871
|
+
}
|
|
872
|
+
window.addEventListener('resize', setHdr);
|
|
873
|
+
|
|
874
|
+
/* ---- header: wordmark, greeting, clock, theme ---- */
|
|
875
|
+
const phone = () => window.innerWidth <= 760;
|
|
876
|
+
const roomy = () => window.innerWidth > 1360; // room for "AS OF" beside the tabs (150% laptops are ~1280)
|
|
877
|
+
const snug = () => window.innerWidth < 1300; // the header's narrow widths: a smaller clock, no greeting
|
|
878
|
+
function renderHeader() {
|
|
879
|
+
$('wordmark').replaceChildren(dm('KEEPFOLD', phone() ? 2 : 3, 'Keepfold'));
|
|
880
|
+
$('greet').textContent = greeting();
|
|
881
|
+
const hm = D.as_of.slice(11, 16);
|
|
882
|
+
$('clock').replaceChildren(dm(roomy() ? 'AS OF ' + hm : hm, snug() ? 2 : 3, `As of ${fmtDay(TODAY)}, ${hm}`));
|
|
883
|
+
$('clock').title = `Built ${fmtDay(TODAY)} ${TODAY.slice(0, 4)}, ${hm}`;
|
|
884
|
+
if (!LIVE) $('stale').hidden = !(Date.now() - Date.parse(D.as_of) > 12 * 36e5);
|
|
885
|
+
$('open-search').replaceChildren(icon('search'));
|
|
886
|
+
}
|
|
887
|
+
$('open-search').addEventListener('click', () => openPalette());
|
|
888
|
+
if (LIVE) { // the app's other pages: setup, chat, status, connect, local model, browsing, vault
|
|
889
|
+
const a = el('a', 'icon-btn');
|
|
890
|
+
a.href = '/manage';
|
|
891
|
+
a.setAttribute('aria-label', 'Settings');
|
|
892
|
+
a.title = 'Settings';
|
|
893
|
+
a.append(icon('gear'));
|
|
894
|
+
$('theme').before(a);
|
|
895
|
+
}
|
|
896
|
+
/* ---- the Private switch (live home): private items show only after Windows Hello verifies
|
|
897
|
+
the user; the app relocks it after 10 minutes, on minimise and on restart ---- */
|
|
898
|
+
let PRIVATE = false, switching = false, privGen = 0;
|
|
899
|
+
const lockBtn = LIVE ? button('icon-btn', null, () => setPrivate(!PRIVATE)) : null;
|
|
900
|
+
function syncLock() {
|
|
901
|
+
const word = PRIVATE ? 'Hide private items' : 'Show private items';
|
|
902
|
+
lockBtn.replaceChildren(icon(PRIVATE ? 'unlock' : 'lock'));
|
|
903
|
+
lockBtn.setAttribute('aria-label', word);
|
|
904
|
+
lockBtn.title = word;
|
|
905
|
+
}
|
|
906
|
+
async function setPrivate(on) {
|
|
907
|
+
if (switching) return;
|
|
908
|
+
switching = true;
|
|
909
|
+
try {
|
|
910
|
+
const r = await api(on ? '/api/home/unlock' : '/api/home/lock', {});
|
|
911
|
+
if (on && !r.unlocked) { toast(r.message || 'Private items stay hidden.', 'error'); return; }
|
|
912
|
+
const d = await api(on ? '/api/home?private=1' : '/api/home'); // the whole home again, not a delta
|
|
913
|
+
PRIVATE = on && !d.relock;
|
|
914
|
+
privGen++;
|
|
915
|
+
syncLock();
|
|
916
|
+
applyDelta({ ...d, full: true });
|
|
917
|
+
} catch (e) {
|
|
918
|
+
toast(e.key ? 'This page’s key expired. Open Keepfold from the tray or Start menu.' : 'Keepfold is not answering.', 'error');
|
|
919
|
+
} finally { switching = false; }
|
|
920
|
+
}
|
|
921
|
+
// a newer Keepfold the app has already downloaded: Restart to update, applied only on this click
|
|
922
|
+
// (below 1300 px only its icon shows, named by its label and tooltip); a dev install's is a
|
|
923
|
+
// link to Status, where Updates shows its command
|
|
924
|
+
let updBtn = null;
|
|
925
|
+
function showUpdate(u) {
|
|
926
|
+
if (!u) { if (updBtn) updBtn.hidden = true; return; }
|
|
927
|
+
if (updBtn && updBtn.dataset.mode !== u.mode) { updBtn.remove(); updBtn = null; }
|
|
928
|
+
if (!updBtn) {
|
|
929
|
+
if (u.mode === 'installer') {
|
|
930
|
+
updBtn = button('chip upd', null, async () => {
|
|
931
|
+
try {
|
|
932
|
+
await api('/api/update/apply', {});
|
|
933
|
+
toast('Keepfold is closing to install the update. It reopens by itself when it is done.');
|
|
934
|
+
} catch (e) { toast(e.message, 'error'); }
|
|
935
|
+
});
|
|
936
|
+
} else {
|
|
937
|
+
updBtn = el('a', 'chip upd');
|
|
938
|
+
updBtn.href = '/manage#status';
|
|
939
|
+
}
|
|
940
|
+
updBtn.setAttribute('aria-label', 'Restart to update');
|
|
941
|
+
updBtn.append(icon('update'), el('span', 'upd-word', 'Restart to update'));
|
|
942
|
+
updBtn.dataset.mode = u.mode;
|
|
943
|
+
$('open-search').before(updBtn);
|
|
944
|
+
}
|
|
945
|
+
updBtn.title = `Restart to update: Keepfold ${u.version} is ready` + (u.mode === 'installer' ? '' : '. Status shows the command.');
|
|
946
|
+
updBtn.hidden = false;
|
|
947
|
+
}
|
|
948
|
+
if (LIVE) {
|
|
949
|
+
syncLock();
|
|
950
|
+
$('open-search').before(lockBtn);
|
|
951
|
+
}
|
|
952
|
+
const fit = () => `${phone()} ${roomy()} ${snug()}`;
|
|
953
|
+
let wasFit = fit();
|
|
954
|
+
window.addEventListener('resize', () => {
|
|
955
|
+
if (fit() !== wasFit) { wasFit = fit(); renderHeader(); setHdr(); }
|
|
956
|
+
});
|
|
957
|
+
|
|
958
|
+
const darkMq = window.matchMedia('(prefers-color-scheme: dark)');
|
|
959
|
+
let theme = 'night', themeChosen = false;
|
|
960
|
+
try {
|
|
961
|
+
// one key with Manage (app.js); 'keepfold-app-theme' was Manage's own key before
|
|
962
|
+
const t = localStorage.getItem('keepfold-theme') || localStorage.getItem('keepfold-app-theme');
|
|
963
|
+
if (t === 'night' || t === 'day') { theme = t; themeChosen = true; }
|
|
964
|
+
} catch (e) { /* storage off: follow the system */ }
|
|
965
|
+
if (!themeChosen) theme = darkMq.matches || !window.matchMedia('(prefers-color-scheme: light)').matches ? 'night' : 'day';
|
|
966
|
+
function applyTheme(t) {
|
|
967
|
+
theme = t;
|
|
968
|
+
document.documentElement.dataset.theme = t;
|
|
969
|
+
const b = $('theme'), next = t === 'night' ? 'day' : 'night';
|
|
970
|
+
b.replaceChildren(icon(t === 'night' ? 'sun' : 'moon'));
|
|
971
|
+
b.setAttribute('aria-label', `Switch to the ${next} theme`);
|
|
972
|
+
b.title = `Switch to the ${next} theme`;
|
|
973
|
+
G.retheme();
|
|
974
|
+
}
|
|
975
|
+
$('theme').addEventListener('click', () => {
|
|
976
|
+
applyTheme(theme === 'night' ? 'day' : 'night');
|
|
977
|
+
try { localStorage.setItem('keepfold-theme', theme); } catch (e) { /* not kept */ }
|
|
978
|
+
});
|
|
979
|
+
darkMq.addEventListener('change', () => { if (!themeChosen) applyTheme(darkMq.matches ? 'night' : 'day'); });
|
|
980
|
+
|
|
981
|
+
/* ---- the brain: one instance, moved between Home and Brain ---- */
|
|
982
|
+
// An old blob has no `brain` (layout is Python's now): the Brain section falls back to the 2D map.
|
|
983
|
+
let brain = null, brainHost = null, brainFailed = !(D.brain && D.brain.nodes && window.KeepfoldBrain);
|
|
984
|
+
let view = brainFailed ? '2d' : '3d', archiveOn = true;
|
|
985
|
+
const BRAIN_IDS = new Set(brainFailed ? [] : D.brain.nodes.ids);
|
|
986
|
+
const MODES = [['activity', 'Activity', 'A'], ['mastery', 'Mastery', 'M'], ['growth', 'Growth', 'G']];
|
|
987
|
+
const modeBtns = [], spinBtns = [], aliveBtns = [];
|
|
988
|
+
const brainFilter = { kinds: new Set(['concept', 'note', 'project', 'decision', 'chat', 'youtube', 'person', 'other']),
|
|
989
|
+
states: new Set(STATES) };
|
|
990
|
+
// keep: a remount's view (camera, mode, style) from the brain it replaces
|
|
991
|
+
function ensureBrain(keep) {
|
|
992
|
+
if (brain || brainFailed) return brain;
|
|
993
|
+
const t = performance.now();
|
|
994
|
+
const pages = D.pages.map((p) => ({ id: p.id, title: p.title, kind: p.kind, cluster: p.cluster, links: p.links,
|
|
995
|
+
date: p.date, updated: p.updated, group: kindGroup(p), state: GN.has(p.id) ? GN.get(p.id).state : null,
|
|
996
|
+
private: !!p.private })); // never in a blob today; Save picture leaves one out all the same
|
|
997
|
+
const first = !brainHost;
|
|
998
|
+
if (first) {
|
|
999
|
+
brainHost = el('div', 'brain-host');
|
|
1000
|
+
$('home-brain-slot').append(brainHost);
|
|
1001
|
+
}
|
|
1002
|
+
try {
|
|
1003
|
+
brain = window.KeepfoldBrain.mount(brainHost, {
|
|
1004
|
+
brain: D.brain, pages, today: TODAY, camera: keep && keep.camera, mode: keep && keep.mode,
|
|
1005
|
+
onHover(n, pos) {
|
|
1006
|
+
if (!n || !pos) { hideTip(); return; }
|
|
1007
|
+
const r = brainHost.getBoundingClientRect(), c = LOBES.get(n.cluster);
|
|
1008
|
+
showTipAt(r.left + pos.x, r.top + pos.y, [el('b', null, n.title), el('br'),
|
|
1009
|
+
el('span', 'k', n.kind === 'site' ? siteWords(n).join(' · ')
|
|
1010
|
+
: kindWord(n.kind) + (n.state ? ' · ' + LABEL[n.state] : '') + (c ? ' · ' + c.title : ''))]);
|
|
1011
|
+
},
|
|
1012
|
+
onSelect(n, info) {
|
|
1013
|
+
growClicked.add(n.id); // a chosen page stops its faint growth glow
|
|
1014
|
+
if (info) { if (n.kind === 'site') inspectSite(n); else inspectPage(n.id, info); }
|
|
1015
|
+
},
|
|
1016
|
+
onToday: syncToday,
|
|
1017
|
+
onLens() { lensId = null; syncLens(); }, // Esc in the brain, or Today, ended the lens
|
|
1018
|
+
onCluster(c) { if (c) { markLobe(c.id); filterLibraryLobe(c.id); } },
|
|
1019
|
+
onLobe(c) { if (c) inspectLobe(c.id); },
|
|
1020
|
+
onMode: syncMode,
|
|
1021
|
+
onSpin: syncSpin,
|
|
1022
|
+
onAlive: syncAlive,
|
|
1023
|
+
style: HAS_STYLE ? (keep && keep.style) || savedStyle() : undefined,
|
|
1024
|
+
keyHelp: HAS_STYLE ? 'L opens Look.' : '',
|
|
1025
|
+
onStyle(s) { saveStyle(s); syncLook(); },
|
|
1026
|
+
onCrumbs(c) {
|
|
1027
|
+
syncStem();
|
|
1028
|
+
const words = (c || []).map((x) => (typeof x === 'string' ? x : x && (x.label || x.title))).filter(Boolean);
|
|
1029
|
+
if (words.length) live(words.join(' › '));
|
|
1030
|
+
},
|
|
1031
|
+
});
|
|
1032
|
+
} catch (err) {
|
|
1033
|
+
if (window.console) console.warn('brain: could not mount, showing the 2D map', err);
|
|
1034
|
+
brainHost.remove();
|
|
1035
|
+
brain = null;
|
|
1036
|
+
brainFailed = true;
|
|
1037
|
+
noBrain();
|
|
1038
|
+
return null;
|
|
1039
|
+
}
|
|
1040
|
+
// brain3d.js owns the other keys on the stage; L is the page's
|
|
1041
|
+
if (first) {
|
|
1042
|
+
brainHost.addEventListener('keydown', (e) => {
|
|
1043
|
+
if (HAS_STYLE && !e.ctrlKey && !e.metaKey && !e.altKey && (e.key === 'l' || e.key === 'L')) {
|
|
1044
|
+
e.preventDefault();
|
|
1045
|
+
openLook();
|
|
1046
|
+
}
|
|
1047
|
+
});
|
|
1048
|
+
}
|
|
1049
|
+
document.body.dataset.brainMs = String(Math.round(performance.now() - t));
|
|
1050
|
+
document.body.dataset.brainRenderer = brain.renderer;
|
|
1051
|
+
requestAnimationFrame(() => { document.body.dataset.brainFrameMs = String(Math.round(performance.now() - T0)); });
|
|
1052
|
+
syncMode(brain.mode);
|
|
1053
|
+
syncAlive(!!brain.alive);
|
|
1054
|
+
syncStem();
|
|
1055
|
+
syncToday(null);
|
|
1056
|
+
faintToday();
|
|
1057
|
+
return brain;
|
|
1058
|
+
}
|
|
1059
|
+
// No 3D brain: Home says so in one line, the Brain section opens on the 2D map.
|
|
1060
|
+
function noBrainNote(tail) {
|
|
1061
|
+
const p = el('p', 'empty', (LIVE ? 'The 3D brain did not start in this window. Keepfold builds it from your pages by itself, '
|
|
1062
|
+
+ 'so reloading the page usually brings it back. ' : 'This snapshot has no 3D brain: Export snapshot in the Keepfold app makes a new one. ') + tail);
|
|
1063
|
+
if (LIVE) p.append(' ', button('btn', 'Reload', () => location.reload()));
|
|
1064
|
+
return p;
|
|
1065
|
+
}
|
|
1066
|
+
function noBrain() {
|
|
1067
|
+
$('home-brain-slot').replaceChildren(noBrainNote('The 2D map is in Brain.'));
|
|
1068
|
+
$('home-brain-tools').hidden = true;
|
|
1069
|
+
$('viewswitch').querySelector('[data-view="3d"]').hidden = true;
|
|
1070
|
+
if (view === '3d') view = '2d';
|
|
1071
|
+
}
|
|
1072
|
+
function placeBrain(slotId) {
|
|
1073
|
+
const b = ensureBrain(), slot = $(slotId);
|
|
1074
|
+
if (!b) return;
|
|
1075
|
+
if (brainHost.parentNode !== slot) slot.append(brainHost);
|
|
1076
|
+
b.setArchive(slotId === 'brain-slot' && archiveOn); // the unsorted-chat ring stays off on Home
|
|
1077
|
+
b.resize();
|
|
1078
|
+
if (slotId === 'home-brain-slot') growCheck();
|
|
1079
|
+
}
|
|
1080
|
+
/* ---- the growth moment: the pages added since this viewer last saw the Home brain glow where it
|
|
1081
|
+
grew (brain3d.js draws it). `keepfold.brain.seenAt` keeps the newest `added` stamp shown; with
|
|
1082
|
+
none yet, the first look only sets it. Storage may fail: the page's memory stands in. ---- */
|
|
1083
|
+
const SEEN_KEY = 'keepfold.brain.seenAt', GROWTH = (window.KeepfoldBrain || {}).GROWTH;
|
|
1084
|
+
const growClicked = new Set();
|
|
1085
|
+
let seenMem = null, growWait = false, faintTimer = 0, countRaf = 0;
|
|
1086
|
+
const store = () => { try { return window.localStorage; } catch (e) { return null; } };
|
|
1087
|
+
function growCheck() {
|
|
1088
|
+
if (!brain || !GROWTH || !D.brain || !D.brain.nodes) return null;
|
|
1089
|
+
if (current !== 'home' || brainHost.parentNode !== $('home-brain-slot')) return null; // the Home brain only
|
|
1090
|
+
if (document.hidden) { growWait = true; return null; } // played when the window shows again
|
|
1091
|
+
growWait = false;
|
|
1092
|
+
const added = D.brain.nodes.added || {}, kept = GROWTH.read(store(), SEEN_KEY);
|
|
1093
|
+
const seen = kept && (!seenMem || kept > seenMem) ? kept : seenMem;
|
|
1094
|
+
const p = GROWTH.pending(added, seen, (id) => brain.shows(id), new Date().toISOString());
|
|
1095
|
+
if (p.newest && p.newest !== seen) { seenMem = p.newest; GROWTH.write(store(), SEEN_KEY, p.newest); }
|
|
1096
|
+
const got = p.ids.length ? brain.grow(p.ids) : null;
|
|
1097
|
+
if (got) {
|
|
1098
|
+
countUp(got.n);
|
|
1099
|
+
live(`The brain grew: ${got.labels.join(', ')}.`);
|
|
1100
|
+
}
|
|
1101
|
+
return got;
|
|
1102
|
+
}
|
|
1103
|
+
document.addEventListener('visibilitychange', () => { if (!document.hidden && growWait) growCheck(); });
|
|
1104
|
+
// today's new pages keep a faint glow until local midnight, or until chosen
|
|
1105
|
+
function faintToday() {
|
|
1106
|
+
if (!brain || !GROWTH || !D.brain || !D.brain.nodes) return;
|
|
1107
|
+
const mid = new Date();
|
|
1108
|
+
mid.setHours(0, 0, 0, 0);
|
|
1109
|
+
brain.faint(GROWTH.since(D.brain.nodes.added, mid.getTime(), growClicked));
|
|
1110
|
+
clearTimeout(faintTimer);
|
|
1111
|
+
faintTimer = setTimeout(faintToday, Math.max(1000, mid.getTime() + 864e5 - Date.now() + 1000));
|
|
1112
|
+
}
|
|
1113
|
+
// the panel header's page count climbs from before the new pages to now (none under reduced motion)
|
|
1114
|
+
function countUp(n) {
|
|
1115
|
+
const line = $('lobe-line');
|
|
1116
|
+
cancelAnimationFrame(countRaf);
|
|
1117
|
+
if (REDUCED.matches || !line) return;
|
|
1118
|
+
const to = D.pages.length, from = Math.max(0, to - n), t0 = performance.now();
|
|
1119
|
+
const step = (t) => {
|
|
1120
|
+
const p = Math.min(1, Math.max(0, (t - t0 - 400) / 1600)), e = p * p * (3 - 2 * p);
|
|
1121
|
+
const k = p < 1 ? Math.round(from + (to - from) * e) : D.pages.length;
|
|
1122
|
+
line.textContent = line.textContent.replace(/^[\d,]+/, k.toLocaleString('en'));
|
|
1123
|
+
if (p < 1) countRaf = requestAnimationFrame(step);
|
|
1124
|
+
};
|
|
1125
|
+
step(t0);
|
|
1126
|
+
}
|
|
1127
|
+
// Live home: a new brain blob. brain3d.js has no incremental add, so the brain is mounted
|
|
1128
|
+
// again where it was (camera, selection, mode, Growth month, spin, style, filters) and the new
|
|
1129
|
+
// pages pop for 3 s. Never under a pointer or a flight, at most once every 2 s.
|
|
1130
|
+
let remountIds = null, remountAt = 0, remountTimer = 0, popTimer = 0;
|
|
1131
|
+
function remountBrain(added) {
|
|
1132
|
+
remountIds = (remountIds || []).concat(added || []);
|
|
1133
|
+
clearTimeout(remountTimer);
|
|
1134
|
+
if (!brain) { remountIds = null; return; } // not mounted yet: it mounts the new blob
|
|
1135
|
+
const wait = brain.busy ? 250 : remountAt + 2000 - Date.now();
|
|
1136
|
+
if (wait > 0) { remountTimer = setTimeout(remountBrain, wait); return; }
|
|
1137
|
+
remountAt = Date.now();
|
|
1138
|
+
const ids = remountIds, old = brain;
|
|
1139
|
+
remountIds = null;
|
|
1140
|
+
const keep = { camera: old.camera, mode: old.mode, style: old.style, selected: old.selected,
|
|
1141
|
+
spin: old.spin, growth: old.growth, focused: old.focused, atStem: old.atStem, today: old.todayIds,
|
|
1142
|
+
lensCam: old.lensCam };
|
|
1143
|
+
hideTip();
|
|
1144
|
+
old.destroy();
|
|
1145
|
+
brain = null;
|
|
1146
|
+
if (!ensureBrain(keep)) return;
|
|
1147
|
+
brain.setArchive(brainHost.parentNode === $('brain-slot') && archiveOn);
|
|
1148
|
+
if (brainUi) applyBrainFilter();
|
|
1149
|
+
if (keep.growth) brain.setGrowth(keep.growth);
|
|
1150
|
+
if (keep.focused) { brain.refocus(keep.focused); markLobe(brain.focused); }
|
|
1151
|
+
if (keep.selected) brain.reselect(keep.selected);
|
|
1152
|
+
if (keep.spin) brain.setSpin(true);
|
|
1153
|
+
if (keep.atStem) brain.atStem = true;
|
|
1154
|
+
if (keep.today) brain.today(keep.today, keep.selected, true);
|
|
1155
|
+
if (lensId) { if (BRAIN_IDS.has(lensId)) applyLens(true, keep.lensCam); else { lensId = null; syncLens(); } }
|
|
1156
|
+
syncStem();
|
|
1157
|
+
syncLook();
|
|
1158
|
+
findInBrain();
|
|
1159
|
+
// new pages: the growth moment on Home; elsewhere (or nothing new to this viewer) they pop for 3 s
|
|
1160
|
+
if (!growCheck() && ids.length) {
|
|
1161
|
+
brain.highlight(ids);
|
|
1162
|
+
clearTimeout(popTimer);
|
|
1163
|
+
popTimer = setTimeout(() => { if (brain) findInBrain(); }, 3000);
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
function showInBrain(id) {
|
|
1167
|
+
show('brain');
|
|
1168
|
+
if (!ensureBrain()) { setView('2d'); G.setCurrent(id); return; }
|
|
1169
|
+
setView('3d');
|
|
1170
|
+
if (!brain.flyTo(id)) { // filtered out: show everything, then fly
|
|
1171
|
+
resetBrainFilters();
|
|
1172
|
+
brain.flyTo(id);
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
// Mode buttons: Home and Brain both show them; onMode keeps them in step.
|
|
1176
|
+
function modeGroup() {
|
|
1177
|
+
const g = el('div', 'seg');
|
|
1178
|
+
g.setAttribute('role', 'group');
|
|
1179
|
+
g.setAttribute('aria-label', 'Brain mode');
|
|
1180
|
+
for (const [m, word, key] of MODES) {
|
|
1181
|
+
const b = button(null, word, () => { if (brain) brain.setMode(m); });
|
|
1182
|
+
b.title = `${word} mode (${key} in the brain)`;
|
|
1183
|
+
b.dataset.mode = m;
|
|
1184
|
+
b.setAttribute('aria-pressed', 'false');
|
|
1185
|
+
modeBtns.push(b);
|
|
1186
|
+
g.append(b);
|
|
1187
|
+
}
|
|
1188
|
+
return g;
|
|
1189
|
+
}
|
|
1190
|
+
// Today, and while in it: the previous and next page of today with "k of n" between them
|
|
1191
|
+
const todayUis = [];
|
|
1192
|
+
function todayBtn(cls) {
|
|
1193
|
+
const b = button(cls + ' tbtn', null, playToday);
|
|
1194
|
+
b.title = 'Show everything from today in the brain: pages taught, tested, asked about, added or saved; the Left and Right arrow keys step through them; press again to leave Today';
|
|
1195
|
+
b.append(icon('target'), ' Today');
|
|
1196
|
+
b.setAttribute('aria-pressed', 'false');
|
|
1197
|
+
const at = el('span', 'today-at');
|
|
1198
|
+
const stepper = el('span', 'today-step');
|
|
1199
|
+
stepper.append(button(cls, '‹', () => { if (brain) brain.todayStep(-1); }, 'Previous page from today'), at,
|
|
1200
|
+
button(cls, '›', () => { if (brain) brain.todayStep(1); }, 'Next page from today'));
|
|
1201
|
+
stepper.hidden = true;
|
|
1202
|
+
todayUis.push({ b, at, stepper });
|
|
1203
|
+
const g = el('span', 'today-group');
|
|
1204
|
+
g.append(b, stepper);
|
|
1205
|
+
return g;
|
|
1206
|
+
}
|
|
1207
|
+
function syncToday(st) {
|
|
1208
|
+
for (const u of todayUis) {
|
|
1209
|
+
u.b.setAttribute('aria-pressed', String(!!st));
|
|
1210
|
+
u.stepper.hidden = !st || st.n < 2;
|
|
1211
|
+
u.at.textContent = st ? (st.at >= 0 ? `${st.at + 1} of ${st.n}` : `${st.n} today`) : '';
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
// Stem: fly to the browsing stem's websites; pressed again, back to the overview
|
|
1215
|
+
const stemBtns = [];
|
|
1216
|
+
function stemBtn() {
|
|
1217
|
+
const b = button('btn tbtn', 'Stem', () => { if (brain) { const on = brain.stem(); live(on ? 'Showing the websites in the brain stem.' : 'Back to the whole brain.'); } syncStem(); });
|
|
1218
|
+
b.title = 'Fly to the websites in the brain stem; press again for the whole brain';
|
|
1219
|
+
stemBtns.push(b);
|
|
1220
|
+
syncStem();
|
|
1221
|
+
return b;
|
|
1222
|
+
}
|
|
1223
|
+
function syncStem() {
|
|
1224
|
+
for (const b of stemBtns) {
|
|
1225
|
+
b.hidden = !(brain && brain.hasStem);
|
|
1226
|
+
b.setAttribute('aria-pressed', String(!!(brain && brain.atStem)));
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
/* ---- Save picture: the brain's shape and light as a 1200 x 675 PNG, safe to post anywhere. Its
|
|
1230
|
+
only text is the caption, built from two counts and the day, never from a page field. ---- */
|
|
1231
|
+
const PIC_W = 1200, PIC_H = 675;
|
|
1232
|
+
function pictureBtn() {
|
|
1233
|
+
const b = button('btn tbtn', null, savePicture);
|
|
1234
|
+
b.title = 'Save a picture of your brain’s shape: no titles, no names, nothing private';
|
|
1235
|
+
b.append(icon('update'), ' Save picture');
|
|
1236
|
+
return b;
|
|
1237
|
+
}
|
|
1238
|
+
function brainPicture() {
|
|
1239
|
+
const p = brain && brain.picture && brain.picture(PIC_W, PIC_H);
|
|
1240
|
+
if (!p) return null;
|
|
1241
|
+
const g = p.canvas.getContext('2d'), n = (k, w) => `${k.toLocaleString('en')} ${w}${k === 1 ? '' : 's'}`;
|
|
1242
|
+
g.font = '18px system-ui, "Segoe UI", sans-serif';
|
|
1243
|
+
g.textBaseline = 'alphabetic';
|
|
1244
|
+
g.textAlign = 'left';
|
|
1245
|
+
g.fillStyle = 'rgba(255, 176, 0, 0.85)'; // --lit at 85 %
|
|
1246
|
+
g.fillText(`${n(p.pages, 'page')} in ${n(p.areas, 'area')}, kept on this computer`, 24, PIC_H - 24);
|
|
1247
|
+
g.textAlign = 'right';
|
|
1248
|
+
g.fillStyle = '#958870'; // night --ink-3
|
|
1249
|
+
g.fillText(`${fmtDay(TODAY)} ${TODAY.slice(0, 4)}`, PIC_W - 24, PIC_H - 24);
|
|
1250
|
+
return p.canvas;
|
|
1251
|
+
}
|
|
1252
|
+
function downloadBlob(blob, name) {
|
|
1253
|
+
const a = el('a');
|
|
1254
|
+
a.href = URL.createObjectURL(blob);
|
|
1255
|
+
a.download = name;
|
|
1256
|
+
document.body.append(a);
|
|
1257
|
+
a.click();
|
|
1258
|
+
a.remove();
|
|
1259
|
+
setTimeout(() => URL.revokeObjectURL(a.href), 60000);
|
|
1260
|
+
}
|
|
1261
|
+
async function savePicture() {
|
|
1262
|
+
const name = `keepfold-brain-${TODAY.slice(0, 10)}.png`;
|
|
1263
|
+
try {
|
|
1264
|
+
const c = brainPicture();
|
|
1265
|
+
const blob = c && await new Promise((r) => c.toBlob(r, 'image/png'));
|
|
1266
|
+
if (!blob) throw new Error('That picture could not be made.');
|
|
1267
|
+
if (!LIVE) { downloadBlob(blob, name); live('Picture saved to your downloads.'); return; }
|
|
1268
|
+
const url = await new Promise((ok, no) => {
|
|
1269
|
+
const fr = new FileReader();
|
|
1270
|
+
fr.onload = () => ok(String(fr.result));
|
|
1271
|
+
fr.onerror = () => no(new Error('That picture could not be made.'));
|
|
1272
|
+
fr.readAsDataURL(blob);
|
|
1273
|
+
});
|
|
1274
|
+
const r = await api('/api/brain/picture', { png: url.slice(url.indexOf(',') + 1), day: TODAY.slice(0, 10) });
|
|
1275
|
+
if (r.download) { downloadBlob(blob, name); live('Picture saved to your downloads.'); }
|
|
1276
|
+
else if (r.saved) live(`Picture saved: ${r.saved}`);
|
|
1277
|
+
} catch (e) { live(e.message); }
|
|
1278
|
+
}
|
|
1279
|
+
function playToday() {
|
|
1280
|
+
if (!brain) return;
|
|
1281
|
+
if (brain.todayIds) { brain.overview(); live('Left Today.'); return; }
|
|
1282
|
+
// all of today's work: the feed's today (taught, tested, asked, added, chats; events, which leave a
|
|
1283
|
+
// concept's file alone) and every page the owner saved today (`today_ids`: never a page a Keepfold
|
|
1284
|
+
// job rewrote), newest first; the feed and the pages are already privacy-filtered
|
|
1285
|
+
const d = (p) => dateOf(p) || '';
|
|
1286
|
+
const mine = new Set(D.today_ids || []);
|
|
1287
|
+
const saved = D.pages.filter((p) => mine.has(p.id))
|
|
1288
|
+
.sort((a, b) => (d(b) > d(a) ? 1 : d(b) < d(a) ? -1 : 0)).map((p) => p.id);
|
|
1289
|
+
// a chat the automatic import brought in today counts only when the chat itself is from today (or
|
|
1290
|
+
// undated), so a first import of older chats does not flood Today
|
|
1291
|
+
const fresh = (i) => i.kind !== 'chat' || !PAGES.has(i.id) || !PAGES.get(i.id).date || PAGES.get(i.id).date === TODAY;
|
|
1292
|
+
const ids = [...new Set([...((D.feed && D.feed.today) || []).filter(fresh).map((i) => i.id), ...saved])]
|
|
1293
|
+
.filter((id) => BRAIN_IDS.has(id));
|
|
1294
|
+
brain.today(ids);
|
|
1295
|
+
live(ids.length ? `Showing ${plural(ids.length, 'page')} from today.` : 'Nothing from today yet.');
|
|
1296
|
+
}
|
|
1297
|
+
function syncMode(m) {
|
|
1298
|
+
for (const b of modeBtns) b.setAttribute('aria-pressed', String(b.dataset.mode === m));
|
|
1299
|
+
for (const s of scrubs) { s.root.hidden = m !== 'growth'; if (m !== 'growth') s.stop(); }
|
|
1300
|
+
if (brainUi && !brainFailed) renderLegend(m);
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
/* ---- the Growth scrubber: a bar per month of new pages above the range (decoration; the range is
|
|
1304
|
+
the real control), "1 year" and "All" for the span, and Play, which runs the handle through it ---- */
|
|
1305
|
+
let growthData = null;
|
|
1306
|
+
function growthMonths() {
|
|
1307
|
+
if (growthData) return growthData;
|
|
1308
|
+
const months = [], counts = {};
|
|
1309
|
+
// a typo like 0001-01-01 or 9999-12-31 must not make the slider thousands of months long
|
|
1310
|
+
const latest = String(+TODAY.slice(0, 4) + 1) + TODAY.slice(4);
|
|
1311
|
+
const dates = D.pages.map((p) => p.date).filter((d) => isDay(d) && d >= '1990' && d <= latest).sort();
|
|
1312
|
+
if (dates.length) {
|
|
1313
|
+
let y = +dates[0].slice(0, 4), m = +dates[0].slice(5, 7);
|
|
1314
|
+
const end = dates[dates.length - 1].slice(0, 7);
|
|
1315
|
+
for (;;) {
|
|
1316
|
+
const k = `${y}-${String(m).padStart(2, '0')}`;
|
|
1317
|
+
months.push(k);
|
|
1318
|
+
if (k >= end) break;
|
|
1319
|
+
if (++m > 12) { m = 1; y++; }
|
|
1320
|
+
}
|
|
1321
|
+
}
|
|
1322
|
+
for (const d of dates) counts[d.slice(0, 7)] = (counts[d.slice(0, 7)] || 0) + 1;
|
|
1323
|
+
return (growthData = { months, counts });
|
|
1324
|
+
}
|
|
1325
|
+
const scrubs = [];
|
|
1326
|
+
const PLAY_MS = 6000;
|
|
1327
|
+
function buildScrub() {
|
|
1328
|
+
let all = growthMonths().months, counts = growthMonths().counts;
|
|
1329
|
+
let span = all, yearOn = false, playing = false, raf = 0;
|
|
1330
|
+
const root = el('div', 'scrub'), bars = el('div', 'scrub-bars'), range = el('input'), out = el('output');
|
|
1331
|
+
root.hidden = !(brain && brain.mode === 'growth');
|
|
1332
|
+
bars.setAttribute('aria-hidden', 'true');
|
|
1333
|
+
range.type = 'range';
|
|
1334
|
+
range.min = '0';
|
|
1335
|
+
range.setAttribute('aria-label', 'Growth: show pages up to this month');
|
|
1336
|
+
const yr = button('btn tbtn', '1 year', () => setSpan(true)), whole = button('btn tbtn', 'All', () => setSpan(false));
|
|
1337
|
+
const play = button('btn tbtn', 'Play', () => (playing ? stop() : start()));
|
|
1338
|
+
play.hidden = REDUCED.matches;
|
|
1339
|
+
REDUCED.addEventListener('change', () => { play.hidden = REDUCED.matches; if (REDUCED.matches) stop(); });
|
|
1340
|
+
const paint = () => {
|
|
1341
|
+
const v = +range.value;
|
|
1342
|
+
[...bars.children].forEach((b, k) => b.classList.toggle('on', k <= v));
|
|
1343
|
+
const mo = span[v];
|
|
1344
|
+
out.textContent = mo ? fmtMonth(mo) : '';
|
|
1345
|
+
range.setAttribute('aria-valuetext', out.textContent);
|
|
1346
|
+
};
|
|
1347
|
+
const draw = () => {
|
|
1348
|
+
const peak = Math.max(1, ...span.map((m) => counts[m] || 0));
|
|
1349
|
+
range.max = String(Math.max(0, span.length - 1));
|
|
1350
|
+
bars.replaceChildren(...span.map((m, k) => {
|
|
1351
|
+
const b = el('span', 'sb'), i = el('i'), n = counts[m] || 0;
|
|
1352
|
+
i.style.height = n ? Math.max(2, Math.round(32 * n / peak)) + 'px' : '0';
|
|
1353
|
+
b.dataset.i = String(k);
|
|
1354
|
+
b.append(i);
|
|
1355
|
+
return b;
|
|
1356
|
+
}));
|
|
1357
|
+
yr.setAttribute('aria-pressed', String(yearOn));
|
|
1358
|
+
whole.setAttribute('aria-pressed', String(!yearOn));
|
|
1359
|
+
};
|
|
1360
|
+
const apply = () => {
|
|
1361
|
+
paint();
|
|
1362
|
+
const mo = span[+range.value] || null;
|
|
1363
|
+
if (brain) brain.setGrowth(mo);
|
|
1364
|
+
for (const s of scrubs) if (s.root !== root) s.set(mo);
|
|
1365
|
+
};
|
|
1366
|
+
function setSpan(year) {
|
|
1367
|
+
stop();
|
|
1368
|
+
yearOn = year;
|
|
1369
|
+
span = year ? all.slice(-12) : all;
|
|
1370
|
+
range.value = String(span.length - 1);
|
|
1371
|
+
draw();
|
|
1372
|
+
apply();
|
|
1373
|
+
}
|
|
1374
|
+
function stop() {
|
|
1375
|
+
if (!playing) return;
|
|
1376
|
+
playing = false;
|
|
1377
|
+
cancelAnimationFrame(raf);
|
|
1378
|
+
play.textContent = 'Play';
|
|
1379
|
+
document.removeEventListener('keydown', onKey);
|
|
1380
|
+
}
|
|
1381
|
+
function onKey(e) { if (e.key === 'Escape') stop(); }
|
|
1382
|
+
function start() {
|
|
1383
|
+
if (span.length < 2) return;
|
|
1384
|
+
playing = true;
|
|
1385
|
+
play.textContent = 'Pause';
|
|
1386
|
+
document.addEventListener('keydown', onKey);
|
|
1387
|
+
const t0 = performance.now();
|
|
1388
|
+
let last = -1;
|
|
1389
|
+
const step = () => {
|
|
1390
|
+
if (!playing) return;
|
|
1391
|
+
if (!root.offsetParent) { stop(); return; } // the tab or the mode was left
|
|
1392
|
+
const p = Math.min(1, (performance.now() - t0) / PLAY_MS), k = Math.round(p * (span.length - 1));
|
|
1393
|
+
if (k !== last) { last = k; range.value = String(k); apply(); }
|
|
1394
|
+
if (p >= 1) stop(); else raf = requestAnimationFrame(step);
|
|
1395
|
+
};
|
|
1396
|
+
step();
|
|
1397
|
+
}
|
|
1398
|
+
range.addEventListener('input', () => { stop(); apply(); });
|
|
1399
|
+
bars.addEventListener('click', (e) => { // pointer only: the range is the keyboard's way
|
|
1400
|
+
const b = e.target.closest && e.target.closest('.sb');
|
|
1401
|
+
if (!b) return;
|
|
1402
|
+
stop();
|
|
1403
|
+
range.value = b.dataset.i;
|
|
1404
|
+
apply();
|
|
1405
|
+
});
|
|
1406
|
+
range.value = String(Math.max(0, span.length - 1));
|
|
1407
|
+
draw();
|
|
1408
|
+
paint();
|
|
1409
|
+
const row = el('div', 'scrub-row'), seg = el('span', 'scrub-span');
|
|
1410
|
+
seg.append(yr, whole);
|
|
1411
|
+
row.append(el('span', null, 'Up to'), range, out, seg, play);
|
|
1412
|
+
root.append(bars, row);
|
|
1413
|
+
if (!all.length) { range.disabled = true; for (const b of [yr, whole, play]) b.disabled = true; }
|
|
1414
|
+
const me = { root, stop, refresh() { // new data: the months and counts again, the chosen month kept
|
|
1415
|
+
stop();
|
|
1416
|
+
const keep = span[+range.value];
|
|
1417
|
+
all = growthMonths().months;
|
|
1418
|
+
counts = growthMonths().counts;
|
|
1419
|
+
span = yearOn ? all.slice(-12) : all;
|
|
1420
|
+
const k = span.indexOf(keep);
|
|
1421
|
+
range.disabled = !all.length;
|
|
1422
|
+
for (const b of [yr, whole, play]) b.disabled = !all.length;
|
|
1423
|
+
draw();
|
|
1424
|
+
range.value = String(k < 0 ? Math.max(0, span.length - 1) : k);
|
|
1425
|
+
paint();
|
|
1426
|
+
}, set(month) { // follow the other scrubber, without moving the brain
|
|
1427
|
+
let k = span.indexOf(month);
|
|
1428
|
+
if (k < 0) k = month && month < span[0] ? 0 : span.length - 1;
|
|
1429
|
+
range.value = String(Math.max(0, k));
|
|
1430
|
+
paint();
|
|
1431
|
+
} };
|
|
1432
|
+
for (let i = scrubs.length; i--;) if (!scrubs[i].root.isConnected) scrubs.splice(i, 1); // a rerender's old ones
|
|
1433
|
+
scrubs.push(me);
|
|
1434
|
+
return me;
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1437
|
+
/* ---- Focus Lens: a Home row's page and the pages linked with it stay lit, the rest dims as in
|
|
1438
|
+
Today and the camera frames them; Clear, Esc, the same row again or Today ends it ---- */
|
|
1439
|
+
let lensId = null, lensAdj = null, lensEl = null;
|
|
1440
|
+
const LENS_CAP = 40, LENS_FEW = 5;
|
|
1441
|
+
function lensNear(id) { // links both ways, between pages the brain shows
|
|
1442
|
+
if (!lensAdj) {
|
|
1443
|
+
lensAdj = new Map();
|
|
1444
|
+
const add = (a, b) => { if (!lensAdj.has(a)) lensAdj.set(a, new Set()); lensAdj.get(a).add(b); };
|
|
1445
|
+
for (const p of D.pages) {
|
|
1446
|
+
if (!BRAIN_IDS.has(p.id)) continue;
|
|
1447
|
+
for (const t of p.links) if (t !== p.id && BRAIN_IDS.has(t)) { add(p.id, t); add(t, p.id); }
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
return lensAdj.get(id) || [];
|
|
1451
|
+
}
|
|
1452
|
+
function lensBar() {
|
|
1453
|
+
lensEl = el('span', 'lens-bar');
|
|
1454
|
+
lensEl.hidden = true;
|
|
1455
|
+
return lensEl;
|
|
1456
|
+
}
|
|
1457
|
+
function syncLens() {
|
|
1458
|
+
if (lensEl) {
|
|
1459
|
+
lensEl.hidden = !lensId;
|
|
1460
|
+
if (lensId) {
|
|
1461
|
+
const n = lensEl.dataset.n, p = PAGES.get(lensId);
|
|
1462
|
+
const note = el('span', 'lens-note', 'Focus: ');
|
|
1463
|
+
note.append(el('b', null, p ? p.title : lensId), `, ${plural(+n, 'linked page')}`);
|
|
1464
|
+
lensEl.replaceChildren(note, button('band-btn', 'Clear', () => clearLens()));
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
for (const b of document.querySelectorAll('[data-lens]')) b.setAttribute('aria-pressed', String(b.dataset.lens === lensId));
|
|
1468
|
+
}
|
|
1469
|
+
// quiet: a remount puts the same lens on the new brain (no camera move)
|
|
1470
|
+
function applyLens(quiet, cam) {
|
|
1471
|
+
const ids = window.KeepfoldBrain.LENS.set(lensId, lensNear, LENS_CAP, LENS_FEW), got = brain.lens(ids, quiet, cam);
|
|
1472
|
+
if (!got) { lensId = null; syncLens(); return false; }
|
|
1473
|
+
lensEl.dataset.n = String(Math.max(0, got - 1));
|
|
1474
|
+
syncLens();
|
|
1475
|
+
return true;
|
|
1476
|
+
}
|
|
1477
|
+
function setLens(id) {
|
|
1478
|
+
if (!brain || !BRAIN_IDS.has(id)) return;
|
|
1479
|
+
lensId = id;
|
|
1480
|
+
if (!applyLens(false)) return;
|
|
1481
|
+
const slot = $('home-brain-slot');
|
|
1482
|
+
if (slot.scrollIntoView) slot.scrollIntoView({ block: 'nearest', behavior: REDUCED.matches ? 'auto' : 'smooth' });
|
|
1483
|
+
live(`Focus: ${PAGES.get(id) ? PAGES.get(id).title : id}, ${plural(+lensEl.dataset.n, 'linked page')}.`);
|
|
1484
|
+
}
|
|
1485
|
+
function clearLens() {
|
|
1486
|
+
if (!lensId) return;
|
|
1487
|
+
lensId = null;
|
|
1488
|
+
if (brain) brain.endLens();
|
|
1489
|
+
syncLens();
|
|
1490
|
+
}
|
|
1491
|
+
const toggleLens = (id) => (lensId === id ? clearLens() : setLens(id));
|
|
1492
|
+
// a quiet button at a Home row's right end (rows of pages the brain does not show get none)
|
|
1493
|
+
function lensBtn(id, title) {
|
|
1494
|
+
if (brainFailed || !BRAIN_IDS.has(id) || !PAGES.has(id)) return null;
|
|
1495
|
+
const b = iconBtn('focus', `Show ${title} in the brain`, () => toggleLens(id));
|
|
1496
|
+
b.dataset.lens = id;
|
|
1497
|
+
b.setAttribute('aria-pressed', String(id === lensId));
|
|
1498
|
+
return b;
|
|
1499
|
+
}
|
|
1500
|
+
document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && lensId && !e.defaultPrevented) clearLens(); });
|
|
1501
|
+
function syncSpin(on) {
|
|
1502
|
+
for (const b of spinBtns) b.setAttribute('aria-pressed', String(on));
|
|
1503
|
+
}
|
|
1504
|
+
function syncAlive(on) {
|
|
1505
|
+
for (const b of aliveBtns) b.setAttribute('aria-pressed', String(on));
|
|
1506
|
+
}
|
|
1507
|
+
if (!brainFailed) {
|
|
1508
|
+
$('home-brain-tools').append(modeGroup(), todayBtn('band-btn'), lensBar());
|
|
1509
|
+
$('home-brain-slot').before(buildScrub().root); // under the band, where the panel's own colours are
|
|
1510
|
+
} else noBrain();
|
|
1511
|
+
$('explore').addEventListener('click', () => { show('brain'); setView('3d'); });
|
|
1512
|
+
|
|
1513
|
+
/* ---- Look: the brain's style, generated from the renderer's schema ---- */
|
|
1514
|
+
const CB = window.KeepfoldBrain || {};
|
|
1515
|
+
// an older brain3d.js has no schema: no Look button, nothing else changes
|
|
1516
|
+
const HAS_STYLE = !brainFailed && Array.isArray(CB.STYLE_SCHEMA) && Array.isArray(CB.PRESETS);
|
|
1517
|
+
const SCHEMA = HAS_STYLE ? CB.STYLE_SCHEMA : [];
|
|
1518
|
+
const STYLE_KEY = 'keepfold.brain.style';
|
|
1519
|
+
const look = $('look'), lookSync = [], lookBtns = [];
|
|
1520
|
+
let lookBuilt = false, lookFrom = null, readerWas = false;
|
|
1521
|
+
// Only schema keys survive a reload, so a stale or hand-edited entry cannot inject others.
|
|
1522
|
+
function savedStyle() {
|
|
1523
|
+
const out = Object.assign({}, CB.DEFAULT_STYLE);
|
|
1524
|
+
try {
|
|
1525
|
+
const s = JSON.parse(localStorage.getItem(STYLE_KEY));
|
|
1526
|
+
if (s && typeof s === 'object' && !Array.isArray(s)) for (const f of SCHEMA) if (f.key in s) out[f.key] = s[f.key];
|
|
1527
|
+
} catch (e) { /* storage blocked or bad JSON: the default */ }
|
|
1528
|
+
return out;
|
|
1529
|
+
}
|
|
1530
|
+
// Only keys that differ from the default are kept, so a later default change still reaches the user.
|
|
1531
|
+
function saveStyle(s) {
|
|
1532
|
+
const diff = {};
|
|
1533
|
+
for (const f of SCHEMA) if (f.key in s && !same(s[f.key], CB.DEFAULT_STYLE[f.key])) diff[f.key] = s[f.key];
|
|
1534
|
+
try {
|
|
1535
|
+
if (Object.keys(diff).length) localStorage.setItem(STYLE_KEY, JSON.stringify(diff));
|
|
1536
|
+
else localStorage.removeItem(STYLE_KEY);
|
|
1537
|
+
} catch (e) { /* not kept */ }
|
|
1538
|
+
}
|
|
1539
|
+
function setLook(partial) {
|
|
1540
|
+
if (!brain) return;
|
|
1541
|
+
brain.setStyle(partial);
|
|
1542
|
+
syncLook();
|
|
1543
|
+
}
|
|
1544
|
+
const same = (a, b) => (typeof a === 'number' && typeof b === 'number' ? Math.abs(a - b) < 1e-6 : a === b);
|
|
1545
|
+
const fullPreset = (p) => Object.assign({}, CB.DEFAULT_STYLE, p.style);
|
|
1546
|
+
function fmtVal(f, v) {
|
|
1547
|
+
const dec = String(f.step || 1).split('.')[1];
|
|
1548
|
+
return String(+(+v).toFixed(dec ? dec.length : 0));
|
|
1549
|
+
}
|
|
1550
|
+
function buildLook() {
|
|
1551
|
+
lookBuilt = true;
|
|
1552
|
+
look.append(iconBtn('close', 'Close Look (Esc)', () => closeLook(true), 'icon-btn close'), el('h2', null, 'Look'));
|
|
1553
|
+
const pre = el('div', 'look-presets'), seg = el('div', 'seg'), custom = el('span', 'look-custom', 'Custom');
|
|
1554
|
+
seg.setAttribute('role', 'group');
|
|
1555
|
+
seg.setAttribute('aria-label', 'Presets');
|
|
1556
|
+
for (const p of CB.PRESETS) {
|
|
1557
|
+
const b = button(null, p.label, () => setLook(fullPreset(p)));
|
|
1558
|
+
b.setAttribute('aria-pressed', 'false');
|
|
1559
|
+
seg.append(b);
|
|
1560
|
+
lookSync.push((s) => {
|
|
1561
|
+
const full = fullPreset(p);
|
|
1562
|
+
b.setAttribute('aria-pressed', String(SCHEMA.every((f) => same(s[f.key], full[f.key]))));
|
|
1563
|
+
});
|
|
1564
|
+
}
|
|
1565
|
+
lookSync.push(() => { custom.hidden = !!seg.querySelector('[aria-pressed="true"]'); });
|
|
1566
|
+
pre.append(el('h3', null, 'Presets'), seg, custom);
|
|
1567
|
+
look.append(pre);
|
|
1568
|
+
const groups = [];
|
|
1569
|
+
for (const f of SCHEMA) if (!groups.includes(f.group)) groups.push(f.group);
|
|
1570
|
+
for (const g of groups) {
|
|
1571
|
+
const sec = el('details', 'look-group');
|
|
1572
|
+
sec.open = true;
|
|
1573
|
+
sec.append(el('summary', null, g));
|
|
1574
|
+
for (const f of SCHEMA.filter((x) => x.group === g)) sec.append(lookRow(f));
|
|
1575
|
+
look.append(sec);
|
|
1576
|
+
}
|
|
1577
|
+
look.append(button('btn look-reset', 'Reset to default', () => setLook(Object.assign({}, CB.DEFAULT_STYLE))));
|
|
1578
|
+
}
|
|
1579
|
+
function lookRow(f) {
|
|
1580
|
+
const row = el('div', 'look-row'), id = 'look-' + f.key, helpId = id + '-help';
|
|
1581
|
+
const help = f.help ? el('p', 'look-help', f.help) : null;
|
|
1582
|
+
if (help) help.id = helpId;
|
|
1583
|
+
const describe = (n) => { if (help) n.setAttribute('aria-describedby', helpId); };
|
|
1584
|
+
if (f.type === 'toggle') {
|
|
1585
|
+
const lab = el('label', 'toggle'), box = el('input');
|
|
1586
|
+
box.type = 'checkbox';
|
|
1587
|
+
box.id = id;
|
|
1588
|
+
describe(box);
|
|
1589
|
+
box.addEventListener('change', () => setLook({ [f.key]: box.checked }));
|
|
1590
|
+
lab.append(box, ' ' + f.label);
|
|
1591
|
+
row.append(lab);
|
|
1592
|
+
lookSync.push((s) => { box.checked = !!s[f.key]; });
|
|
1593
|
+
} else if (f.type === 'range') {
|
|
1594
|
+
const lab = el('label', 'look-label', f.label), r = el('input'), out = el('output'), line = el('div', 'look-range');
|
|
1595
|
+
lab.htmlFor = id;
|
|
1596
|
+
r.type = 'range';
|
|
1597
|
+
r.id = id;
|
|
1598
|
+
r.min = String(f.min);
|
|
1599
|
+
r.max = String(f.max);
|
|
1600
|
+
r.step = String(f.step || 'any');
|
|
1601
|
+
out.htmlFor = id;
|
|
1602
|
+
describe(r);
|
|
1603
|
+
const showVal = (v) => { out.textContent = fmtVal(f, v); r.setAttribute('aria-valuetext', out.textContent); };
|
|
1604
|
+
r.addEventListener('input', () => { showVal(r.value); setLook({ [f.key]: +r.value }); });
|
|
1605
|
+
line.append(r, out);
|
|
1606
|
+
row.append(lab, line);
|
|
1607
|
+
lookSync.push((s) => { if (s[f.key] != null) { r.value = String(s[f.key]); showVal(s[f.key]); } });
|
|
1608
|
+
} else if (f.type === 'choice') {
|
|
1609
|
+
const lab = el('span', 'look-label', f.label), seg = el('div', 'seg');
|
|
1610
|
+
lab.id = id;
|
|
1611
|
+
seg.setAttribute('role', 'group');
|
|
1612
|
+
seg.setAttribute('aria-labelledby', id);
|
|
1613
|
+
describe(seg);
|
|
1614
|
+
for (const [v, word] of f.options || []) {
|
|
1615
|
+
const b = button(null, word, () => setLook({ [f.key]: v }));
|
|
1616
|
+
b.setAttribute('aria-pressed', 'false');
|
|
1617
|
+
seg.append(b);
|
|
1618
|
+
lookSync.push((s) => b.setAttribute('aria-pressed', String(same(s[f.key], v))));
|
|
1619
|
+
}
|
|
1620
|
+
row.append(lab, seg);
|
|
1621
|
+
} else return row;
|
|
1622
|
+
if (help) row.append(help);
|
|
1623
|
+
return row;
|
|
1624
|
+
}
|
|
1625
|
+
function syncLook() {
|
|
1626
|
+
if (!lookBuilt || !brain) return;
|
|
1627
|
+
const s = brain.style || {};
|
|
1628
|
+
for (const fn of lookSync) fn(s);
|
|
1629
|
+
}
|
|
1630
|
+
function openLook() {
|
|
1631
|
+
if (!brain || !HAS_STYLE) return;
|
|
1632
|
+
if (!lookBuilt) buildLook();
|
|
1633
|
+
if (look.hidden) {
|
|
1634
|
+
lookFrom = document.activeElement;
|
|
1635
|
+
readerWas = !reader.hidden;
|
|
1636
|
+
reader.hidden = true;
|
|
1637
|
+
hideTip();
|
|
1638
|
+
}
|
|
1639
|
+
look.hidden = false;
|
|
1640
|
+
syncLook();
|
|
1641
|
+
for (const b of lookBtns) b.setAttribute('aria-expanded', 'true');
|
|
1642
|
+
const first = look.querySelector('.look-presets button');
|
|
1643
|
+
if (first) first.focus({ preventScroll: true });
|
|
1644
|
+
}
|
|
1645
|
+
function closeLook(restore) {
|
|
1646
|
+
if (look.hidden) return;
|
|
1647
|
+
look.hidden = true;
|
|
1648
|
+
for (const b of lookBtns) b.setAttribute('aria-expanded', 'false');
|
|
1649
|
+
if (restore && readerWas) reader.hidden = false;
|
|
1650
|
+
readerWas = false;
|
|
1651
|
+
if (restore && lookFrom && lookFrom.isConnected) lookFrom.focus({ preventScroll: true });
|
|
1652
|
+
}
|
|
1653
|
+
function lookBtn() {
|
|
1654
|
+
const b = button('btn tbtn', 'Look', () => (look.hidden ? openLook() : closeLook(true)));
|
|
1655
|
+
b.title = 'Change how the brain looks (L in the brain)';
|
|
1656
|
+
b.setAttribute('aria-expanded', 'false');
|
|
1657
|
+
b.setAttribute('aria-controls', 'look');
|
|
1658
|
+
b.setAttribute('aria-keyshortcuts', 'L');
|
|
1659
|
+
lookBtns.push(b);
|
|
1660
|
+
return b;
|
|
1661
|
+
}
|
|
1662
|
+
|
|
1663
|
+
/* ---- boards ---- */
|
|
1664
|
+
function board(title, opts) {
|
|
1665
|
+
opts = opts || {};
|
|
1666
|
+
const root = el('div', 'board' + (opts.cls ? ' ' + opts.cls : ''));
|
|
1667
|
+
const band = el('div', 'band');
|
|
1668
|
+
band.append(el('h2', null, title));
|
|
1669
|
+
if (opts.note) band.append(el('span', 'band-note', opts.note));
|
|
1670
|
+
if (opts.action) band.append(opts.action);
|
|
1671
|
+
const body = el('div', 'board-body');
|
|
1672
|
+
root.append(band, body);
|
|
1673
|
+
return { root, band, body };
|
|
1674
|
+
}
|
|
1675
|
+
// Board -> brain: hovering or focusing a row lights its page in the brain.
|
|
1676
|
+
function syncRow(row, id) {
|
|
1677
|
+
const on = () => { if (brain) brain.hoverId(id); }, off = () => { if (brain) brain.hoverId(null); };
|
|
1678
|
+
row.addEventListener('pointerenter', on);
|
|
1679
|
+
row.addEventListener('pointerleave', off);
|
|
1680
|
+
row.addEventListener('focusin', on);
|
|
1681
|
+
row.addEventListener('focusout', off);
|
|
1682
|
+
}
|
|
1683
|
+
// One board row: title (opens the reader) over a muted line, a right-hand cell and actions.
|
|
1684
|
+
function brow({ id, title, sub, left, right, prompt, brainId }) {
|
|
1685
|
+
const r = el('div', 'brow');
|
|
1686
|
+
const t = el('div', 't'), l1 = el('div', 'line1');
|
|
1687
|
+
if (left) l1.append(left);
|
|
1688
|
+
l1.append(id && (PAGES.has(id) || GN.has(id)) ? button('ttl linkbtn', title, () => openReader(id)) : el('span', 'ttl', title));
|
|
1689
|
+
t.append(l1);
|
|
1690
|
+
if (sub) t.append(el('span', 'sub', sub));
|
|
1691
|
+
const acts = el('div', 'acts');
|
|
1692
|
+
if (right) acts.append(right);
|
|
1693
|
+
if (prompt) acts.append(copyBtn(prompt));
|
|
1694
|
+
if (brainId && PAGES.has(brainId)) {
|
|
1695
|
+
acts.append(iconBtn('target', 'Show in brain', () => showInBrain(brainId)));
|
|
1696
|
+
syncRow(r, brainId);
|
|
1697
|
+
const f = homeRows && lensBtn(brainId, title);
|
|
1698
|
+
if (f) acts.append(f);
|
|
1699
|
+
}
|
|
1700
|
+
r.append(t, acts);
|
|
1701
|
+
return r;
|
|
1702
|
+
}
|
|
1703
|
+
// Home's own rows (Exams and deadlines, Open loops, Back on your mind) carry the Focus Lens button
|
|
1704
|
+
let homeRows = false;
|
|
1705
|
+
const onHome = (fn) => (x) => { homeRows = true; try { return fn(x); } finally { homeRows = false; } };
|
|
1706
|
+
function moreFoot(n, where, section) {
|
|
1707
|
+
const f = el('div', 'foot');
|
|
1708
|
+
f.append(button('linkbtn', `+ ${n} more on ${where}`, () => show(section)));
|
|
1709
|
+
return f;
|
|
1710
|
+
}
|
|
1711
|
+
const LOOP_CODE = { commitment: 'CMT', question: 'Q', idea: 'IDEA' };
|
|
1712
|
+
const loopCode = (t) => el('span', 'code', LOOP_CODE[t] || (t ? String(t).slice(0, 4).toUpperCase() : 'LOOP'));
|
|
1713
|
+
function loopRow(l) {
|
|
1714
|
+
const bits = [];
|
|
1715
|
+
if (l.created) bits.push('since ' + fmtDay(l.created));
|
|
1716
|
+
if (l.due) bits.push('due ' + fmtDay(l.due));
|
|
1717
|
+
if (l.summary) bits.push(l.summary);
|
|
1718
|
+
return brow({ id: l.id, title: l.title, sub: bits.join(' · '), left: loopCode(l.loop_type),
|
|
1719
|
+
prompt: loopPrompt(l.id), brainId: l.id });
|
|
1720
|
+
}
|
|
1721
|
+
const fromWhen = (id) => {
|
|
1722
|
+
const p = PAGES.get(id), d = p && dateOf(p);
|
|
1723
|
+
return isDay(d) ? 'from ' + fmtMonth(d) : '';
|
|
1724
|
+
};
|
|
1725
|
+
function resurfaceRow(r) {
|
|
1726
|
+
return brow({ id: r.id, title: r.title, sub: [fromWhen(r.id), r.summary].filter(Boolean).join(' · '),
|
|
1727
|
+
left: el('span', 'kind', kindWord(r.kind)), prompt: `/keepfold about ${r.id}`, brainId: r.id });
|
|
1728
|
+
}
|
|
1729
|
+
function followRow(f) {
|
|
1730
|
+
return brow({ id: f.id, title: f.title, sub: 'revisit on ' + fmtDay(f.review_on),
|
|
1731
|
+
left: el('span', 'code', 'DEC'), prompt: loopPrompt(f.id), brainId: f.id });
|
|
1732
|
+
}
|
|
1733
|
+
function boardList(b, rows, cap, empty, more) {
|
|
1734
|
+
if (!rows.length) b.body.append(el('p', 'empty', empty));
|
|
1735
|
+
for (const r of rows.slice(0, cap)) b.body.append(r);
|
|
1736
|
+
if (more && rows.length > cap) b.root.append(moreFoot(rows.length - cap, more[0], more[1]));
|
|
1737
|
+
return b.root;
|
|
1738
|
+
}
|
|
1739
|
+
// One readiness metric on Study: the weighted Solid share, named as such, beside
|
|
1740
|
+
// the plain topic count (the two differ when topics carry different weights).
|
|
1741
|
+
function readiness(r) {
|
|
1742
|
+
const topics = `${r.solid} of ${plural(r.total, 'topic')}`;
|
|
1743
|
+
if (r.share == null) return { pct: Math.round(100 * r.solid / r.total), label: `${topics} solid` };
|
|
1744
|
+
const pct = Math.round(100 * r.share);
|
|
1745
|
+
return { pct, label: `${pct}% of the test's weight solid · ${topics}` };
|
|
1746
|
+
}
|
|
1747
|
+
|
|
1748
|
+
// Nothing planned and nothing ever checked: three first steps instead of "Done for today";
|
|
1749
|
+
// for someone who does not study, steps that fit everyone (shown until something is imported)
|
|
1750
|
+
function firstRunBoard() {
|
|
1751
|
+
const b = board('Start here', { cls: 'first-run' });
|
|
1752
|
+
const steps = STUDIES ? [
|
|
1753
|
+
['Add a test date', 'Tell any Claude chat about a test and its date, or add one in assessments/.', null],
|
|
1754
|
+
['Run /keepfold in Claude', 'Your home card, what is due and what is waiting for you.', '/keepfold'],
|
|
1755
|
+
['Import your notes or chats', 'In the Keepfold app: Setup → Add your history. Or in a terminal: keepfold import <file>.', null]] : [
|
|
1756
|
+
['Add your chats', 'In the Keepfold app: Setup → Add your history. Your AI chats, notes and calendar become pages you can ask about.', null],
|
|
1757
|
+
['Connect an AI app', 'In the Keepfold app: Connect AI apps. Claude, ChatGPT, Codex or Cursor then know your preferences.', null],
|
|
1758
|
+
['Ask Chat', "In the Keepfold app: Chat. Ask about anything you've saved.", null]];
|
|
1759
|
+
steps.forEach(([title, sub, prompt], i) => b.body.append(brow({ title, sub, prompt,
|
|
1760
|
+
left: el('span', 'code', String(i + 1)) })));
|
|
1761
|
+
return b.root;
|
|
1762
|
+
}
|
|
1763
|
+
|
|
1764
|
+
/* ---- Home ---- */
|
|
1765
|
+
// Next up: tests and deadlines in the next 2 days, then each subject's next steps (the most
|
|
1766
|
+
// recently studied subject first; the snapshot has today's plan), then due loops and decisions.
|
|
1767
|
+
function nextUp() {
|
|
1768
|
+
const items = [];
|
|
1769
|
+
for (const a of D.exams || D.assessments) {
|
|
1770
|
+
if (a.days_left == null || a.days_left < 0 || a.days_left > 2) continue;
|
|
1771
|
+
items.push({ time: a.days_left === 0 ? 'TODAY' : `IN ${a.days_left}D`, id: a.id,
|
|
1772
|
+
title: [a.company || a.id, a.kind].filter(Boolean).join(' · '),
|
|
1773
|
+
why: a.kind === 'deadline' ? 'Deadline' : 'Assessment',
|
|
1774
|
+
lobe: pageLobe(a.id), word: 'DUE', prompt: `/keepfold mock ${a.id}` });
|
|
1775
|
+
}
|
|
1776
|
+
const groupOf = Object.fromEntries(GROUPS);
|
|
1777
|
+
let first = true;
|
|
1778
|
+
for (const g of D.next_up || [{ subject: null, items: D.today }]) {
|
|
1779
|
+
for (const i of g.items) {
|
|
1780
|
+
const now = D.next_up ? first : i.kind === 'unchecked' || i.kind === 'asked';
|
|
1781
|
+
first = false;
|
|
1782
|
+
items.push({ time: now ? 'NOW' : 'NEXT', id: i.id, title: i.title, why: i.why || groupOf[i.kind] || '',
|
|
1783
|
+
lobe: g.subject ? g.subject.id : pageLobe(i.id), subject: g.subject, state: i.state,
|
|
1784
|
+
prompt: i.kind === 'refresh' || i.kind === 'review' ? '/keepfold review' : i.id ? `/keepfold learn ${i.id}` : '/keepfold learn' });
|
|
1785
|
+
}
|
|
1786
|
+
}
|
|
1787
|
+
const dated = (d) => (d === TODAY ? 'TODAY' : fmtDay(d).toUpperCase());
|
|
1788
|
+
for (const l of D.loops) {
|
|
1789
|
+
if (!isDay(l.due) || l.due > TODAY) continue;
|
|
1790
|
+
items.push({ time: dated(l.due), id: l.id, title: l.title, why: 'Open loop', lobe: pageLobe(l.id),
|
|
1791
|
+
word: 'OPEN', prompt: loopPrompt(l.id) });
|
|
1792
|
+
}
|
|
1793
|
+
for (const f of D.follow_ups) {
|
|
1794
|
+
if (!isDay(f.review_on) || f.review_on > TODAY) continue;
|
|
1795
|
+
items.push({ time: dated(f.review_on), id: f.id, title: f.title, why: 'Decision to revisit',
|
|
1796
|
+
lobe: pageLobe(f.id), word: 'DUE', prompt: loopPrompt(f.id) });
|
|
1797
|
+
}
|
|
1798
|
+
return items;
|
|
1799
|
+
}
|
|
1800
|
+
// TOPIC: the subject's lobe chip, else a chip of the subject's own title
|
|
1801
|
+
function platChip(it) {
|
|
1802
|
+
if (!it.subject || LOBES.has(it.lobe)) return lobeChip(it.lobe);
|
|
1803
|
+
const s = el('span', 'code', code(it.subject.title));
|
|
1804
|
+
s.title = it.subject.title;
|
|
1805
|
+
s.setAttribute('aria-label', 'Subject: ' + it.subject.title);
|
|
1806
|
+
return s;
|
|
1807
|
+
}
|
|
1808
|
+
function examRow(a) {
|
|
1809
|
+
const n = a.days_left, name = a.company || a.title || a.id;
|
|
1810
|
+
// the kind only when the name does not say it already: "DSA exam", but "Google · interview"
|
|
1811
|
+
const kind = a.kind && !name.toLowerCase().includes(a.kind.toLowerCase()) ? a.kind : null;
|
|
1812
|
+
return brow({ id: a.id, title: [name, kind].filter(Boolean).join(' · '), sub: fmtDay(a.date),
|
|
1813
|
+
right: el('span', 'kind', n === 0 ? 'today' : `${plural(n, 'day')} left`),
|
|
1814
|
+
prompt: a.kind === 'deadline' ? null : `/keepfold mock ${a.id}`, brainId: a.id });
|
|
1815
|
+
}
|
|
1816
|
+
|
|
1817
|
+
/* the live feed: Today or This week, grouped by subject, newest first */
|
|
1818
|
+
const FEED = [['today', 'Today'], ['week', 'This week']];
|
|
1819
|
+
const feedKey = (i) => [i.ts, i.kind, i.id, i.title].join('\n');
|
|
1820
|
+
let feedRange = 'today', feedSeen = null;
|
|
1821
|
+
const hhmm = (ts) => {
|
|
1822
|
+
const t = new Date(ts);
|
|
1823
|
+
return isNaN(t) ? '' : `${String(t.getHours()).padStart(2, '0')}:${String(t.getMinutes()).padStart(2, '0')}`;
|
|
1824
|
+
};
|
|
1825
|
+
function feedRows() {
|
|
1826
|
+
const items = (D.feed && D.feed[feedRange]) || [];
|
|
1827
|
+
if (!items.length) {
|
|
1828
|
+
return [el('p', 'empty', `${feedRange === 'today' ? 'Nothing yet today' : 'Nothing earlier this week'}. `
|
|
1829
|
+
+ 'What you save, study and ask shows up here.')];
|
|
1830
|
+
}
|
|
1831
|
+
const out = [];
|
|
1832
|
+
let subj = null;
|
|
1833
|
+
for (const i of items) {
|
|
1834
|
+
const s = i.subject ? i.subject.id : '';
|
|
1835
|
+
if (s !== subj) { subj = s; out.push(el('h3', 'feed-subj', i.subject ? i.subject.title : 'Other')); }
|
|
1836
|
+
const r = brow({ id: i.id, title: i.title, sub: i.detail,
|
|
1837
|
+
left: el('span', 'ftime', [feedRange === 'today' ? '' : fmtDay(i.day), i.timed === false ? '' : hhmm(i.ts)].filter(Boolean).join(' ')) });
|
|
1838
|
+
if (feedSeen && !feedSeen.has(feedKey(i))) r.classList.add('fresh'); // new since the last render
|
|
1839
|
+
out.push(r);
|
|
1840
|
+
}
|
|
1841
|
+
return out;
|
|
1842
|
+
}
|
|
1843
|
+
function feedBoard() {
|
|
1844
|
+
const tools = el('div', 'band-tools'), seg = el('div', 'seg');
|
|
1845
|
+
seg.setAttribute('role', 'group');
|
|
1846
|
+
seg.setAttribute('aria-label', 'Feed range');
|
|
1847
|
+
tools.append(seg);
|
|
1848
|
+
const b = board('Live feed', { cls: 'feed', action: tools });
|
|
1849
|
+
const fill = () => {
|
|
1850
|
+
for (const t of seg.children) t.setAttribute('aria-pressed', String(t.dataset.k === feedRange));
|
|
1851
|
+
b.body.replaceChildren(...feedRows());
|
|
1852
|
+
};
|
|
1853
|
+
for (const [k, word] of FEED) {
|
|
1854
|
+
const t = button(null, word, () => { feedRange = k; fill(); });
|
|
1855
|
+
t.dataset.k = k;
|
|
1856
|
+
seg.append(t);
|
|
1857
|
+
}
|
|
1858
|
+
fill();
|
|
1859
|
+
feedSeen = new Set(D.feed ? [...D.feed.today, ...D.feed.week].map(feedKey) : []);
|
|
1860
|
+
return b.root;
|
|
1861
|
+
}
|
|
1862
|
+
|
|
1863
|
+
/* quick chat: one question to the app's chat, the answer and its numbered sources */
|
|
1864
|
+
let chatBoard = null, chatId = null;
|
|
1865
|
+
function quickChat() {
|
|
1866
|
+
const full = el('a', 'band-btn', 'Open full chat');
|
|
1867
|
+
full.href = '/manage#chat';
|
|
1868
|
+
const b = board('Quick chat', { cls: 'quick-chat', action: full });
|
|
1869
|
+
const lab = el('label', 'qc-label', 'Ask about your notes'), q = el('input'), row = el('div', 'qc-row');
|
|
1870
|
+
q.type = 'text';
|
|
1871
|
+
q.id = 'qc-q';
|
|
1872
|
+
q.autocomplete = 'off';
|
|
1873
|
+
lab.htmlFor = 'qc-q';
|
|
1874
|
+
const go = button('btn', 'Ask', () => ask());
|
|
1875
|
+
row.append(q, go);
|
|
1876
|
+
const need = el('div'), out = el('div', 'qc-out');
|
|
1877
|
+
out.setAttribute('aria-live', 'polite');
|
|
1878
|
+
b.body.append(lab, row, need, out);
|
|
1879
|
+
q.addEventListener('keydown', (e) => { if (e.key === 'Enter' && !e.isComposing) { e.preventDefault(); ask(); } });
|
|
1880
|
+
const setUp = (what, why) => { // what is missing, with the page that sets it up
|
|
1881
|
+
const p = el('p', 'qc-need', why + ' '), a = el('a', null, what === 'llm' ? 'Set up a local model' : 'Finish setup');
|
|
1882
|
+
a.href = what === 'llm' ? '/manage#llm' : '/manage#setup';
|
|
1883
|
+
p.append(a);
|
|
1884
|
+
return p;
|
|
1885
|
+
};
|
|
1886
|
+
api('/api/chat').then((s) => {
|
|
1887
|
+
if ((s.missing || []).includes('llm')) {
|
|
1888
|
+
need.replaceChildren(setUp('llm', 'No local model is set up yet, so this chat can only count and list what Keepfold keeps: your notes, saved chats, browsing and study.'));
|
|
1889
|
+
}
|
|
1890
|
+
}, () => {});
|
|
1891
|
+
function sources(src) {
|
|
1892
|
+
if (!src || !src.length) return [];
|
|
1893
|
+
const box = el('div', 'chip-list');
|
|
1894
|
+
for (const s of src) {
|
|
1895
|
+
const p = D.pages.find((x) => x.path === s.path), label = `${s.n} ${s.title || s.path}`;
|
|
1896
|
+
box.append(p ? button('chip', label, () => openReader(p.id), `Open source ${s.n}: ${p.title}`) : el('span', 'chip', label));
|
|
1897
|
+
}
|
|
1898
|
+
return [el('h4', null, 'Sources'), box];
|
|
1899
|
+
}
|
|
1900
|
+
let busy = false;
|
|
1901
|
+
async function ask() {
|
|
1902
|
+
const text = q.value.trim();
|
|
1903
|
+
if (!text || busy) return;
|
|
1904
|
+
busy = true;
|
|
1905
|
+
go.disabled = true;
|
|
1906
|
+
out.setAttribute('aria-busy', 'true');
|
|
1907
|
+
out.replaceChildren(el('p', 'muted', 'Thinking…'));
|
|
1908
|
+
let answer = '', src = [], failed = null;
|
|
1909
|
+
try {
|
|
1910
|
+
const r = await fetch('/api/chat', { method: 'POST', body: JSON.stringify({ id: chatId, text }),
|
|
1911
|
+
headers: { 'X-Keepfold-Token': KEY, 'Content-Type': 'application/json' } });
|
|
1912
|
+
if (!r.ok) {
|
|
1913
|
+
let d = {};
|
|
1914
|
+
try { d = await r.json(); } catch (e) { /* no body */ }
|
|
1915
|
+
throw new Error(d.error || `The app answered ${r.status}.`);
|
|
1916
|
+
}
|
|
1917
|
+
const rd = r.body.getReader(), dec = new TextDecoder();
|
|
1918
|
+
let buf = '';
|
|
1919
|
+
for (;;) {
|
|
1920
|
+
const { value, done } = await rd.read();
|
|
1921
|
+
if (done) break;
|
|
1922
|
+
buf += dec.decode(value, { stream: true });
|
|
1923
|
+
let i;
|
|
1924
|
+
while ((i = buf.indexOf('\n')) >= 0) {
|
|
1925
|
+
const line = buf.slice(0, i).trim();
|
|
1926
|
+
buf = buf.slice(i + 1);
|
|
1927
|
+
if (!line) continue;
|
|
1928
|
+
const ev = JSON.parse(line);
|
|
1929
|
+
if (ev.id) chatId = ev.id;
|
|
1930
|
+
if (ev.t === 'tok') answer += ev.s;
|
|
1931
|
+
else if (ev.t === 'text') answer = ev.s;
|
|
1932
|
+
else if (ev.t === 'src') src = ev.sources || [];
|
|
1933
|
+
else if (ev.t === 'err') failed = ev;
|
|
1934
|
+
if ((ev.t === 'tok' || ev.t === 'text') && answer) out.replaceChildren(md(answer));
|
|
1935
|
+
}
|
|
1936
|
+
}
|
|
1937
|
+
} catch (e) {
|
|
1938
|
+
failed = { code: 'app', message: e.name === 'TypeError' ? 'The app is not answering.' : e.message };
|
|
1939
|
+
}
|
|
1940
|
+
busy = false;
|
|
1941
|
+
go.disabled = false;
|
|
1942
|
+
out.setAttribute('aria-busy', 'false');
|
|
1943
|
+
if (failed) {
|
|
1944
|
+
const what = failed.code === 'no_local_model' ? 'llm' : failed.code === 'not_set_up' ? 'setup' : null;
|
|
1945
|
+
const why = failed.message || 'No answer.';
|
|
1946
|
+
out.replaceChildren(what ? setUp(what, why) : el('p', 'qc-need', why));
|
|
1947
|
+
return;
|
|
1948
|
+
}
|
|
1949
|
+
q.value = '';
|
|
1950
|
+
out.replaceChildren(md(answer || 'No answer.'), ...sources(src));
|
|
1951
|
+
}
|
|
1952
|
+
return b.root;
|
|
1953
|
+
}
|
|
1954
|
+
|
|
1955
|
+
/* the 90-second check: up to 3 due concepts, recall, reveal, self-grade; a text countdown */
|
|
1956
|
+
const COLD_S = 90;
|
|
1957
|
+
const COLD_ANSWERS = [['forgot', 'Forgot'], ['shaky', 'Shaky'], ['knew', 'Knew it']];
|
|
1958
|
+
function closeCold() {
|
|
1959
|
+
if (!cold) return;
|
|
1960
|
+
clearInterval(cold.timer);
|
|
1961
|
+
cold.root.remove();
|
|
1962
|
+
cold = null;
|
|
1963
|
+
const opener = $('cold-open');
|
|
1964
|
+
(opener || $('view-home')).focus();
|
|
1965
|
+
}
|
|
1966
|
+
async function openCold() {
|
|
1967
|
+
if (cold) return;
|
|
1968
|
+
const close = button('band-btn', 'Close', closeCold, 'Close the 90-second check');
|
|
1969
|
+
const b = board('90-second check', { cls: 'cold', action: close });
|
|
1970
|
+
const clock = el('p', 'cold-timer');
|
|
1971
|
+
clock.setAttribute('role', 'timer');
|
|
1972
|
+
b.body.append(clock);
|
|
1973
|
+
cold = { root: b.root, timer: null };
|
|
1974
|
+
$('departures').prepend(b.root);
|
|
1975
|
+
let items = [];
|
|
1976
|
+
try { items = (await api('/api/home/check')).items || []; } catch (e) {
|
|
1977
|
+
clock.textContent = 'The check could not load. ' + e.message;
|
|
1978
|
+
close.focus();
|
|
1979
|
+
return;
|
|
1980
|
+
}
|
|
1981
|
+
if (!cold || cold.root !== b.root) return; // closed while loading
|
|
1982
|
+
if (!items.length) {
|
|
1983
|
+
clock.textContent = 'Nothing is due right now.';
|
|
1984
|
+
close.focus();
|
|
1985
|
+
return;
|
|
1986
|
+
}
|
|
1987
|
+
const open = new Set(), state = cold; // answer buttons of items not answered yet; this panel
|
|
1988
|
+
let left = COLD_S;
|
|
1989
|
+
const tick = () => { clock.textContent = `${Math.floor(left / 60)}:${String(left % 60).padStart(2, '0')} left`; };
|
|
1990
|
+
const finish = (text) => {
|
|
1991
|
+
clearInterval(state.timer); // the panel may be closed by now
|
|
1992
|
+
for (const btn of open) btn.disabled = true;
|
|
1993
|
+
open.clear();
|
|
1994
|
+
clock.textContent = text;
|
|
1995
|
+
};
|
|
1996
|
+
for (const it of items) {
|
|
1997
|
+
const box = el('div', 'cold-item'), acts = el('div', 'cold-acts'), said = el('p', 'muted');
|
|
1998
|
+
said.setAttribute('aria-live', 'polite');
|
|
1999
|
+
const sum = el('p', 'cold-sum', it.summary || 'Its page has no summary yet.');
|
|
2000
|
+
sum.hidden = true;
|
|
2001
|
+
acts.hidden = true;
|
|
2002
|
+
let shownAt = 0; // answer time is shown here only: never sent, never stored
|
|
2003
|
+
const reveal = button('btn', 'Reveal', () => {
|
|
2004
|
+
shownAt = performance.now();
|
|
2005
|
+
sum.hidden = false;
|
|
2006
|
+
acts.hidden = false;
|
|
2007
|
+
reveal.remove();
|
|
2008
|
+
acts.firstChild.focus();
|
|
2009
|
+
}, `Reveal what you wrote about ${it.title}`);
|
|
2010
|
+
const btns = COLD_ANSWERS.map(([k, word]) => button('btn', word, async () => {
|
|
2011
|
+
btns.forEach((x) => { x.disabled = true; open.delete(x); });
|
|
2012
|
+
const took = `answered in ${Math.round((performance.now() - shownAt) / 1000)} s`;
|
|
2013
|
+
try {
|
|
2014
|
+
await api('/api/home/check/answer', { id: it.id, answer: k });
|
|
2015
|
+
said.textContent = `Saved: ${word}, ${took}.`;
|
|
2016
|
+
} catch (e) {
|
|
2017
|
+
said.textContent = `Not saved, ${took}. ` + e.message;
|
|
2018
|
+
}
|
|
2019
|
+
if (!open.size && left > 0) finish('Done. Your answers are saved.');
|
|
2020
|
+
}, `${word}: ${it.title}`));
|
|
2021
|
+
btns.forEach((x) => open.add(x));
|
|
2022
|
+
acts.append(...btns);
|
|
2023
|
+
box.append(el('h3', null, it.title), el('p', null, 'Recall what you know, then reveal.'), reveal, sum, acts, said);
|
|
2024
|
+
b.body.append(box);
|
|
2025
|
+
}
|
|
2026
|
+
tick();
|
|
2027
|
+
state.timer = setInterval(() => {
|
|
2028
|
+
left -= 1;
|
|
2029
|
+
if (left > 0) tick();
|
|
2030
|
+
else finish('Time is up. Unanswered ones are not recorded.');
|
|
2031
|
+
}, 1000);
|
|
2032
|
+
b.body.querySelector('.cold-item .btn').focus();
|
|
2033
|
+
}
|
|
2034
|
+
|
|
2035
|
+
/* B2-b: a chat export found in Downloads, else the claude.ai export reminder (/api/import/pickup;
|
|
2036
|
+
the server looks at Downloads once a minute at most). One card at a time, above Next up. */
|
|
2037
|
+
let pickupEl = null, pickupKey = '';
|
|
2038
|
+
function pickupBoard(p) {
|
|
2039
|
+
const f = p && p.found;
|
|
2040
|
+
if (!f && !(p && p.remind)) return null;
|
|
2041
|
+
const b = board(f ? 'Found in Downloads' : 'claude.ai chats', { cls: 'pickup' });
|
|
2042
|
+
const what = f && f.source === 'google-activity' ? 'history' : 'chats'; // Search, YouTube, Chrome
|
|
2043
|
+
const r = brow(f ? { title: `You downloaded a ${f.name} export on ${fmtDay(f.day)}. Add its ${what} to Keepfold?`, sub: f.file }
|
|
2044
|
+
: { title: 'Export your claude.ai chats so Keepfold keeps all of them (2 minutes)' });
|
|
2045
|
+
const close = () => { b.root.remove(); pickupEl = null; $('view-home').focus(); };
|
|
2046
|
+
const post = (path, body, said) => async () => {
|
|
2047
|
+
try { await api(path, body); } catch (e) { toast(e.message, 'error'); return; }
|
|
2048
|
+
close();
|
|
2049
|
+
if (said) toast(said);
|
|
2050
|
+
};
|
|
2051
|
+
r.querySelector('.acts').append(...(f
|
|
2052
|
+
? [button('btn', `Add ${what}`, post('/api/import/pickup/add', { path: f.path }, `Adding the ${what}. Setup shows when it is done.`)),
|
|
2053
|
+
button('btn', 'Not this one', post('/api/import/pickup/dismiss', { path: f.path }))]
|
|
2054
|
+
: [button('btn', 'Show me how', () => location.assign('/manage#import-claude')),
|
|
2055
|
+
button('btn', 'Later', post('/api/import/pickup/later', {}))]));
|
|
2056
|
+
b.body.append(r);
|
|
2057
|
+
return b.root;
|
|
2058
|
+
}
|
|
2059
|
+
async function loadPickup() {
|
|
2060
|
+
if (document.hidden) return;
|
|
2061
|
+
let p;
|
|
2062
|
+
try { p = await api('/api/import/pickup'); } catch (e) { return; }
|
|
2063
|
+
const key = JSON.stringify(p);
|
|
2064
|
+
if (key === pickupKey && (pickupEl || !(p.found || p.remind))) return; // unchanged: focus stays
|
|
2065
|
+
pickupKey = key;
|
|
2066
|
+
if (pickupEl) pickupEl.remove();
|
|
2067
|
+
pickupEl = pickupBoard(p);
|
|
2068
|
+
if (pickupEl) $('departures').prepend(pickupEl);
|
|
2069
|
+
}
|
|
2070
|
+
if (LIVE) {
|
|
2071
|
+
loadPickup();
|
|
2072
|
+
setInterval(loadPickup, 60000);
|
|
2073
|
+
}
|
|
2074
|
+
|
|
2075
|
+
/* R31: Add a date on the Exams and deadlines board (POST /api/home/date, an assessment page as
|
|
2076
|
+
an AI app's keepfold_add makes it), and calendar events that look like exams, each added in a
|
|
2077
|
+
click. The open form is one element kept across renders, so a live update keeps its text. */
|
|
2078
|
+
let dateForm = null;
|
|
2079
|
+
async function addDate(body) {
|
|
2080
|
+
const r = await api('/api/home/date', body);
|
|
2081
|
+
toast(`Added: ${r.title} on ${fmtDay(r.date)}.`);
|
|
2082
|
+
poll(); // the board shows the new row from the next data load
|
|
2083
|
+
}
|
|
2084
|
+
function dateOpener() {
|
|
2085
|
+
const f = el('div', 'foot add-date');
|
|
2086
|
+
const b = button('linkbtn', 'Add a date', openDateForm);
|
|
2087
|
+
b.id = 'date-open';
|
|
2088
|
+
f.append(b);
|
|
2089
|
+
return f;
|
|
2090
|
+
}
|
|
2091
|
+
function closeDateForm() {
|
|
2092
|
+
if (!dateForm) return;
|
|
2093
|
+
const f = dateOpener();
|
|
2094
|
+
dateForm.replaceWith(f);
|
|
2095
|
+
dateForm = null;
|
|
2096
|
+
f.firstChild.focus();
|
|
2097
|
+
}
|
|
2098
|
+
function openDateForm() {
|
|
2099
|
+
const form = el('form', 'date-form');
|
|
2100
|
+
form.noValidate = true; // the server's words, in the toast, for every refusal
|
|
2101
|
+
const field = (id, label, input) => {
|
|
2102
|
+
const box = el('div', 'df-field'), lab = el('label', 'qc-label', label);
|
|
2103
|
+
input.id = id;
|
|
2104
|
+
lab.htmlFor = id;
|
|
2105
|
+
box.append(lab, input);
|
|
2106
|
+
return box;
|
|
2107
|
+
};
|
|
2108
|
+
const what = el('input'), when = el('input'), kind = el('select');
|
|
2109
|
+
what.type = 'text';
|
|
2110
|
+
what.required = true;
|
|
2111
|
+
what.maxLength = 120;
|
|
2112
|
+
what.placeholder = 'DSA exam';
|
|
2113
|
+
what.autocomplete = 'off';
|
|
2114
|
+
when.type = 'date';
|
|
2115
|
+
when.required = true;
|
|
2116
|
+
when.min = TODAY;
|
|
2117
|
+
for (const [v, t] of [['exam', 'Exam'], ['deadline', 'Deadline']]) {
|
|
2118
|
+
const o = el('option', null, t);
|
|
2119
|
+
o.value = v;
|
|
2120
|
+
kind.append(o);
|
|
2121
|
+
}
|
|
2122
|
+
const add = el('button', 'btn lit', 'Add'), acts = el('div', 'df-acts');
|
|
2123
|
+
add.type = 'submit';
|
|
2124
|
+
acts.append(add, button('btn', 'Cancel', closeDateForm));
|
|
2125
|
+
const whatBox = field('date-what', 'What', what);
|
|
2126
|
+
whatBox.classList.add('df-what');
|
|
2127
|
+
form.append(whatBox, field('date-when', 'When', when), field('date-kind', 'Exam or deadline', kind), acts);
|
|
2128
|
+
form.addEventListener('submit', async (e) => {
|
|
2129
|
+
e.preventDefault();
|
|
2130
|
+
if (add.disabled) return;
|
|
2131
|
+
add.disabled = true;
|
|
2132
|
+
try {
|
|
2133
|
+
await addDate({ what: what.value, when: when.value, kind: kind.value });
|
|
2134
|
+
} catch (err) {
|
|
2135
|
+
add.disabled = false;
|
|
2136
|
+
toast(err.message, 'error');
|
|
2137
|
+
return;
|
|
2138
|
+
}
|
|
2139
|
+
closeDateForm();
|
|
2140
|
+
});
|
|
2141
|
+
form.addEventListener('keydown', (e) => { if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); closeDateForm(); } });
|
|
2142
|
+
const opener = $('date-open');
|
|
2143
|
+
if (opener) opener.parentNode.replaceWith(form);
|
|
2144
|
+
dateForm = form;
|
|
2145
|
+
what.focus();
|
|
2146
|
+
}
|
|
2147
|
+
// the board's live extras: the suggestions under its rows, then the opener or the open form;
|
|
2148
|
+
// returns what puts the focus back once the board is on the page
|
|
2149
|
+
function dateExtras(b) {
|
|
2150
|
+
const sug = D.exam_suggestions || [];
|
|
2151
|
+
if (sug.length) b.body.append(el('h3', 'feed-subj', 'From your calendar'));
|
|
2152
|
+
for (const s of sug) {
|
|
2153
|
+
const word = s.kind === 'deadline' ? 'deadline' : 'exam';
|
|
2154
|
+
const go = button('btn', `Add as ${word}`, async () => {
|
|
2155
|
+
go.disabled = true;
|
|
2156
|
+
try { await addDate({ what: s.title, when: s.day, kind: word }); } catch (e) { go.disabled = false; toast(e.message, 'error'); }
|
|
2157
|
+
}, `Add as ${word}: ${s.title}`);
|
|
2158
|
+
b.body.append(brow({ title: s.title, sub: fmtDay(s.day), right: go }));
|
|
2159
|
+
}
|
|
2160
|
+
if (!dateForm) { b.root.append(dateOpener()); return null; }
|
|
2161
|
+
const act = dateForm.contains(document.activeElement) ? document.activeElement : null;
|
|
2162
|
+
b.root.append(dateForm);
|
|
2163
|
+
return act && (() => act.focus({ preventScroll: true }));
|
|
2164
|
+
}
|
|
2165
|
+
|
|
2166
|
+
let flicked = false;
|
|
2167
|
+
function renderHome() {
|
|
2168
|
+
const items = nextUp(), host = $('departures');
|
|
2169
|
+
const coldBtn = LIVE && D.cold_check ? button('band-btn', '90-second check', openCold,
|
|
2170
|
+
'Start a 90-second check of what is due') : null;
|
|
2171
|
+
if (coldBtn) coldBtn.id = 'cold-open';
|
|
2172
|
+
const b = board('Next up', { cls: 'departures', action: coldBtn });
|
|
2173
|
+
const times = [];
|
|
2174
|
+
// nothing due: only the one-line message below, no header and no idle rows that look like loading
|
|
2175
|
+
if (items.length) {
|
|
2176
|
+
const head = el('div', 'dep-head');
|
|
2177
|
+
for (const h of ['TIME', 'ITEM', 'TOPIC', 'STATUS', '']) head.append(el('span', null, h));
|
|
2178
|
+
b.body.append(head);
|
|
2179
|
+
}
|
|
2180
|
+
for (let k = 0; k < (items.length ? 8 : 0); k++) {
|
|
2181
|
+
const it = items[k], r = el('div', 'dep-row' + (it ? '' : ' idle'));
|
|
2182
|
+
const tc = el('div', 'tcell'), d = dm(it ? it.time : ' ', 2, it ? it.time : 'empty');
|
|
2183
|
+
tc.append(d);
|
|
2184
|
+
times.push(it ? d : null);
|
|
2185
|
+
if (!it) {
|
|
2186
|
+
r.setAttribute('aria-hidden', 'true');
|
|
2187
|
+
r.append(tc, el('div'), el('div', 'plat'), el('div', 'status'), el('div', 'acts'));
|
|
2188
|
+
b.body.append(r);
|
|
2189
|
+
continue;
|
|
2190
|
+
}
|
|
2191
|
+
const item = el('div', 't');
|
|
2192
|
+
item.append(PAGES.has(it.id) || GN.has(it.id) ? button('ttl linkbtn', it.title, () => openReader(it.id))
|
|
2193
|
+
: el('span', 'ttl', it.title), el('span', 'sub', it.why));
|
|
2194
|
+
const plat = el('div', 'plat');
|
|
2195
|
+
plat.append(platChip(it));
|
|
2196
|
+
const st = el('div', 'status' + (it.word ? ' word' : ''));
|
|
2197
|
+
if (it.word) st.textContent = it.word; else st.append(stateWord(it.state));
|
|
2198
|
+
const acts = el('div', 'acts');
|
|
2199
|
+
acts.append(copyBtn(it.prompt));
|
|
2200
|
+
if (PAGES.has(it.id)) acts.append(iconBtn('target', 'Show in brain', () => showInBrain(it.id)));
|
|
2201
|
+
const lb = lensBtn(it.id, it.title);
|
|
2202
|
+
if (lb) acts.append(lb);
|
|
2203
|
+
r.append(tc, item, plat, st, acts);
|
|
2204
|
+
if (PAGES.has(it.id)) syncRow(r, it.id);
|
|
2205
|
+
b.body.append(r);
|
|
2206
|
+
}
|
|
2207
|
+
if (!items.length) b.root.append(el('div', 'foot', STUDIES ? 'Board clear. Nothing due. Run /keepfold in Claude to start something new.'
|
|
2208
|
+
: 'Nothing next. Open loops and decisions that come due show here.'));
|
|
2209
|
+
else if (items.length > 8) b.root.append(STUDIES ? moreFoot(items.length - 8, 'Study', 'study') : moreFoot(items.length - 8, 'Ideas', 'ideas'));
|
|
2210
|
+
else b.root.append(el('div', 'foot', 'That is everything due today.'));
|
|
2211
|
+
// how long each subject stays sharp (9 in 10 recalls right), as one plain line (home._keep)
|
|
2212
|
+
const keeps = (D.next_up || []).filter((g) => g.subject && g.keep);
|
|
2213
|
+
if (keeps.length) {
|
|
2214
|
+
const k = el('div', 'foot keep');
|
|
2215
|
+
for (const g of keeps) k.append(el('div', null, `${g.subject.title}: ${g.keep.text}`));
|
|
2216
|
+
b.root.append(k);
|
|
2217
|
+
}
|
|
2218
|
+
// an open 90-second check stays where it is (a live update never takes its focus or clock)
|
|
2219
|
+
for (const c of [...host.children]) if ((!cold || c !== cold.root) && c !== pickupEl) c.remove();
|
|
2220
|
+
// `imported` is computed only for someone who does not study; Get started, when it shows, is
|
|
2221
|
+
// the one first-run board
|
|
2222
|
+
const started = getStarted();
|
|
2223
|
+
host.append(!started && (STUDIES ? D.first_run : !D.imported) && !items.length ? firstRunBoard() : b.root);
|
|
2224
|
+
if (!flicked && !REDUCED.matches) { // the one authored motion: a split-flap flick, on the first render only
|
|
2225
|
+
flicked = true;
|
|
2226
|
+
times.forEach((d, k) => {
|
|
2227
|
+
if (!d) return;
|
|
2228
|
+
setTimeout(() => {
|
|
2229
|
+
dmSet(d, [...d.dataset.text].map((c) => (c === ' ' ? c : SCRAMBLE[Math.floor(Math.random() * SCRAMBLE.length)])).join(''));
|
|
2230
|
+
requestAnimationFrame(() => requestAnimationFrame(() => dmSet(d, d.dataset.text)));
|
|
2231
|
+
}, k * 40);
|
|
2232
|
+
});
|
|
2233
|
+
}
|
|
2234
|
+
|
|
2235
|
+
const lobes = D.clusters.filter((c) => c.count > 0).length;
|
|
2236
|
+
$('lobe-line').textContent = `${D.pages.length.toLocaleString('en')} pages in ${plural(lobes, 'lobe')}`;
|
|
2237
|
+
|
|
2238
|
+
const exams = (D.exams || D.assessments.filter((a) => isDay(a.date))).slice().sort((a, c) => a.days_left - c.days_left);
|
|
2239
|
+
const eb = STUDIES ? board('Exams and deadlines') : null;
|
|
2240
|
+
const examsBoard = eb ? boardList(eb, exams.map(onHome(examRow)), 4,
|
|
2241
|
+
'Nothing scheduled. Tell any Claude chat about a test and its date.', ['Study', 'study']) : null;
|
|
2242
|
+
const refocus = eb && LIVE ? dateExtras(eb) : null; // the snapshot cannot add a date
|
|
2243
|
+
const loops = boardList(board('Open loops'), D.loops.map(onHome(loopRow)), 5,
|
|
2244
|
+
"No open loops. Say 'remind me to…' in any Claude chat.", ['Ideas', 'ideas']);
|
|
2245
|
+
const back = boardList(board('Back on your mind'), D.resurface.map(onHome(resurfaceRow)), 3,
|
|
2246
|
+
'Nothing coming back today. Old ideas and decisions return here when they are due another look.',
|
|
2247
|
+
['Ideas', 'ideas']);
|
|
2248
|
+
const boards = { study: examsBoard, build: loops, research: back };
|
|
2249
|
+
const g = homeGroups().map((k) => boards[k]).filter(Boolean);
|
|
2250
|
+
const rowA = $('home-row-a'), rowB = $('home-row-b');
|
|
2251
|
+
const cols = (n) => 'home-row ' + ['one', 'one', 'two', 'three'][n];
|
|
2252
|
+
if (!LIVE) { // the snapshot has no feed and no chat
|
|
2253
|
+
rowA.className = cols(g.length);
|
|
2254
|
+
rowA.replaceChildren(...g);
|
|
2255
|
+
rowB.replaceChildren();
|
|
2256
|
+
return;
|
|
2257
|
+
}
|
|
2258
|
+
// as Home always was: one group board (or the first of three) between the feed and the
|
|
2259
|
+
// chat, the others in the row below
|
|
2260
|
+
const mid = g.length % 2 ? g.shift() : null;
|
|
2261
|
+
rowA.className = cols(mid ? 3 : 2);
|
|
2262
|
+
// the quick chat is built once: a live update never takes its text or focus
|
|
2263
|
+
if (!chatBoard) chatBoard = quickChat();
|
|
2264
|
+
for (const c of [...rowA.children]) if (c !== chatBoard) c.remove();
|
|
2265
|
+
rowA.prepend(...[feedBoard(), mid].filter(Boolean));
|
|
2266
|
+
if (!chatBoard.isConnected) rowA.append(chatBoard);
|
|
2267
|
+
rowB.className = cols(g.length);
|
|
2268
|
+
rowB.hidden = !g.length;
|
|
2269
|
+
rowB.replaceChildren(...g);
|
|
2270
|
+
if (refocus) refocus();
|
|
2271
|
+
pinLink();
|
|
2272
|
+
}
|
|
2273
|
+
|
|
2274
|
+
/* UX-E: Home's group boards (Exams and deadlines: study; Open loops: build; Back on your mind:
|
|
2275
|
+
research) in the order of how much of the vault serves each (dashboard.signals; a stable
|
|
2276
|
+
sort, so ties keep this order), or as pinned (app.home_layout). A group at 0 hides, study
|
|
2277
|
+
exactly as the Study tab does; all at 0 is Home as it always was. */
|
|
2278
|
+
const HOME_GROUPS = ['study', 'build', 'research'];
|
|
2279
|
+
let PIN = Array.isArray(D.home_layout) ? D.home_layout.filter((k) => HOME_GROUPS.includes(k)) : null;
|
|
2280
|
+
function homeOrder() {
|
|
2281
|
+
const s = D.signals || {};
|
|
2282
|
+
return PIN ? [...PIN, ...HOME_GROUPS.filter((k) => !PIN.includes(k))]
|
|
2283
|
+
: HOME_GROUPS.slice().sort((a, b) => (s[b] || 0) - (s[a] || 0));
|
|
2284
|
+
}
|
|
2285
|
+
function homeGroups() {
|
|
2286
|
+
const s = D.signals || {}, none = HOME_GROUPS.every((k) => !s[k]);
|
|
2287
|
+
return homeOrder().filter((k) => (k === 'study' ? STUDIES : none || s[k] > 0));
|
|
2288
|
+
}
|
|
2289
|
+
// Pin layout, at Home's end (the live home only): Home stops reordering until Unpin layout
|
|
2290
|
+
let pinEl = null;
|
|
2291
|
+
function pinLink() {
|
|
2292
|
+
if (!pinEl) {
|
|
2293
|
+
pinEl = el('div', 'home-pin');
|
|
2294
|
+
$('view-home').append(pinEl);
|
|
2295
|
+
}
|
|
2296
|
+
const b = button('linkbtn', PIN ? 'Unpin layout' : 'Pin layout', async () => {
|
|
2297
|
+
b.disabled = true;
|
|
2298
|
+
try {
|
|
2299
|
+
const r = await api('/api/home/layout', { order: PIN ? null : homeOrder() });
|
|
2300
|
+
PIN = r.home_layout || null;
|
|
2301
|
+
} catch (e) { b.disabled = false; toast(e.message, 'error'); return; }
|
|
2302
|
+
toast(PIN ? 'Home keeps this layout.' : 'Home orders its boards by itself again.');
|
|
2303
|
+
renderHome();
|
|
2304
|
+
pinEl.firstChild.focus();
|
|
2305
|
+
});
|
|
2306
|
+
pinEl.replaceChildren(b);
|
|
2307
|
+
}
|
|
2308
|
+
|
|
2309
|
+
/* UX-E: Get started on a new vault (dashboard.get_started, the live home only): three steps,
|
|
2310
|
+
each ticked from the vault (`connected` from the app), until all three are ticked or Hide
|
|
2311
|
+
(app.first_run_hidden). Built once, so a live update keeps the typed line. */
|
|
2312
|
+
const GS_STEPS = ['Tell Keepfold one thing about you', 'Connect an AI app', 'Bring in what you already have'];
|
|
2313
|
+
let gs = null, gsTicks = null, FIRST_HIDDEN = !!D.first_run_hidden;
|
|
2314
|
+
function gsBoard() {
|
|
2315
|
+
const note = el('span', 'band-note');
|
|
2316
|
+
const b = board('Get started', { cls: 'get-started', action: note });
|
|
2317
|
+
const form = el('form', 'gs-form'), input = el('input'), save = el('button', 'btn lit', 'Save');
|
|
2318
|
+
input.type = 'text';
|
|
2319
|
+
input.id = 'gs-fact';
|
|
2320
|
+
input.maxLength = 300;
|
|
2321
|
+
input.autocomplete = 'off';
|
|
2322
|
+
input.placeholder = 'Where you work or study, or what you are into';
|
|
2323
|
+
input.setAttribute('aria-label', 'One thing about you');
|
|
2324
|
+
save.type = 'submit';
|
|
2325
|
+
form.append(input, save);
|
|
2326
|
+
form.addEventListener('submit', async (e) => {
|
|
2327
|
+
e.preventDefault();
|
|
2328
|
+
if (save.disabled) return;
|
|
2329
|
+
save.disabled = true;
|
|
2330
|
+
try {
|
|
2331
|
+
const r = await api('/api/home/fact', { text: input.value });
|
|
2332
|
+
input.value = '';
|
|
2333
|
+
toast(r.saved && r.saved.length ? 'Saved to your profile.' : 'Your profile has that line already.');
|
|
2334
|
+
poll(); // the tick comes with the next data load
|
|
2335
|
+
} catch (err) { toast(err.message, 'error'); }
|
|
2336
|
+
save.disabled = false;
|
|
2337
|
+
});
|
|
2338
|
+
const go = (text, href) => { const a = el('a', 'btn', text); a.href = href; return a; };
|
|
2339
|
+
const controls = [form, go('Connect', '/manage#connect'), go('Import', '/manage#setup')];
|
|
2340
|
+
const codes = GS_STEPS.map((title, i) => {
|
|
2341
|
+
const code = el('span', 'code');
|
|
2342
|
+
b.body.append(brow({ title, left: code, right: controls[i] }));
|
|
2343
|
+
return code;
|
|
2344
|
+
});
|
|
2345
|
+
const f = el('div', 'foot');
|
|
2346
|
+
f.append(button('linkbtn', 'Hide', async () => {
|
|
2347
|
+
try { await api('/api/home/layout', { first_run_hidden: true }); } catch (e) { toast(e.message, 'error'); return; }
|
|
2348
|
+
FIRST_HIDDEN = true;
|
|
2349
|
+
renderHome();
|
|
2350
|
+
toast('Get started is hidden. Settings still has Connect AI apps and Setup.');
|
|
2351
|
+
$('view-home').focus({ preventScroll: true });
|
|
2352
|
+
}, 'Hide Get started'));
|
|
2353
|
+
b.root.append(f);
|
|
2354
|
+
return { root: b.root, note, codes };
|
|
2355
|
+
}
|
|
2356
|
+
function getStarted() {
|
|
2357
|
+
const st = LIVE && !FIRST_HIDDEN ? D.get_started : null;
|
|
2358
|
+
const ticks = st ? [!!st.fact, !!D.connected, !!st.imported] : null; // D: the latest poll
|
|
2359
|
+
if (ticks && gsTicks) ticks.forEach((t, i) => { if (t && !gsTicks[i]) announce(`Step ${i + 1} of 3 done: ${GS_STEPS[i]}.`); });
|
|
2360
|
+
gsTicks = ticks;
|
|
2361
|
+
if (!ticks || ticks.every(Boolean)) {
|
|
2362
|
+
if (gs) { gs.root.remove(); gs = null; }
|
|
2363
|
+
return false;
|
|
2364
|
+
}
|
|
2365
|
+
if (!gs) gs = gsBoard();
|
|
2366
|
+
ticks.forEach((t, i) => {
|
|
2367
|
+
gs.codes[i].textContent = t ? '✓' : String(i + 1);
|
|
2368
|
+
gs.codes[i].setAttribute('aria-label', t ? 'Done' : `Step ${i + 1}`);
|
|
2369
|
+
});
|
|
2370
|
+
gs.note.textContent = `${ticks.filter(Boolean).length} of 3 done`;
|
|
2371
|
+
if (!gs.root.isConnected) $('view-home').prepend(gs.root);
|
|
2372
|
+
return true;
|
|
2373
|
+
}
|
|
2374
|
+
|
|
2375
|
+
/* ---- Brain section ---- */
|
|
2376
|
+
const KGROUPS = [['concept', 'Concepts'], ['note', 'Notes'], ['project', 'Projects'], ['decision', 'Decisions'],
|
|
2377
|
+
['chat', 'Chats'], ['youtube', 'YouTube'], ['person', 'People'], ['other', 'Other']];
|
|
2378
|
+
function applyBrainFilter() {
|
|
2379
|
+
const k = brainFilter.kinds, s = brainFilter.states;
|
|
2380
|
+
const all = k.size === KGROUPS.length && s.size === STATES.length;
|
|
2381
|
+
brain.setFilter(all ? null : (n) => n.kind === 'site' || (k.has(n.group) && (n.kind !== 'concept' || s.has(n.state))));
|
|
2382
|
+
for (const b of $('bkinds').children) b.setAttribute('aria-pressed', String(k.has(b.dataset.k)));
|
|
2383
|
+
for (const b of $('bstates').children) b.setAttribute('aria-pressed', String(s.has(b.dataset.s)));
|
|
2384
|
+
}
|
|
2385
|
+
function resetBrainFilters() {
|
|
2386
|
+
KGROUPS.forEach(([k]) => brainFilter.kinds.add(k));
|
|
2387
|
+
STATES.forEach((s) => brainFilter.states.add(s));
|
|
2388
|
+
applyBrainFilter();
|
|
2389
|
+
}
|
|
2390
|
+
function markLobe(id) {
|
|
2391
|
+
$('all-lobes').setAttribute('aria-pressed', String(!id));
|
|
2392
|
+
for (const li of $('outline').querySelectorAll('.lobe')) li.setAttribute('aria-selected', String(li.dataset.id === id));
|
|
2393
|
+
}
|
|
2394
|
+
function markOutline(pageId) {
|
|
2395
|
+
if (!brainUi || brainFailed) return;
|
|
2396
|
+
for (const li of $('outline').querySelectorAll('.page')) li.setAttribute('aria-selected', String(li.dataset.id === pageId));
|
|
2397
|
+
}
|
|
2398
|
+
function selectLobe(id) {
|
|
2399
|
+
if (!brain) return;
|
|
2400
|
+
brain.focusCluster(id);
|
|
2401
|
+
markLobe(id);
|
|
2402
|
+
inspectLobe(id);
|
|
2403
|
+
}
|
|
2404
|
+
function renderLegend(m) {
|
|
2405
|
+
const lg = $('legend');
|
|
2406
|
+
lg.replaceChildren(el('p', 'honest', D.brain.legend || ''));
|
|
2407
|
+
if (brain && brain.legendNote) lg.append(el('p', null, brain.legendNote));
|
|
2408
|
+
if (m === 'mastery') {
|
|
2409
|
+
const sw = el('div', 'sw');
|
|
2410
|
+
for (const s of STATES) sw.append(stateWord(s));
|
|
2411
|
+
lg.append(sw, el('p', null, 'Concepts take their state; study lobes are tinted from Needs refresh to Solid; other lobes are grey.'));
|
|
2412
|
+
} else if (m === 'growth') {
|
|
2413
|
+
lg.append(el('p', null, 'Pages appear month by month, dated by the source, not by when it was saved.'));
|
|
2414
|
+
} else lg.append(el('p', null, 'A halo marks a page saved or changed in the last 7 days.'));
|
|
2415
|
+
const st = D.brain.stem;
|
|
2416
|
+
if (st && st.shown) {
|
|
2417
|
+
lg.append(el('p', null, `The stem below holds ${plural(st.shown, 'website')} from your browsing: size by visits, `
|
|
2418
|
+
+ 'brightness by the last visit, colour by category' + (st.sites.some((x) => x[5]) ? ', a hollow ring when private' : '') + '.'
|
|
2419
|
+
+ (st.total > st.shown ? ` It shows the most visited and those of the last 30 days; the other ${st.total - st.shown} stay in the browsing store.` : '')));
|
|
2420
|
+
const key = el('div', 'sw');
|
|
2421
|
+
for (const c of Object.keys(st.colors || {}).sort()) {
|
|
2422
|
+
const col = String(st.colors[c]);
|
|
2423
|
+
if (!/^#[0-9a-f]{6}$/i.test(col)) continue;
|
|
2424
|
+
const dot = el('span', 'dot'), item = el('span');
|
|
2425
|
+
dot.style.background = col;
|
|
2426
|
+
item.append(dot, c.replace(/-/g, ' '));
|
|
2427
|
+
key.append(item);
|
|
2428
|
+
}
|
|
2429
|
+
if (key.childElementCount) lg.append(key);
|
|
2430
|
+
}
|
|
2431
|
+
lg.append(el('p', null, 'drag to turn · scroll to zoom · click a lobe name for its pages · click a point to inspect it · double-click empty space for the overview'));
|
|
2432
|
+
lg.append(el('p', null, 'keys: Esc back · [ ] step (Today: ← → too) · Backspace previous · F frame · 0 reset · arrows turn · + − zoom · A M G modes · S spin'
|
|
2433
|
+
+ (HAS_STYLE ? ' · L look' : '')));
|
|
2434
|
+
}
|
|
2435
|
+
|
|
2436
|
+
/* the outline: region > lobe > page as a WAI tree (an equal route to the canvas) */
|
|
2437
|
+
const REGIONS = [['topic', 'Topics'], ['domain', 'Study subjects'], ['group', 'Routines, projects and the rest'],
|
|
2438
|
+
['archive', 'Unsorted chats']];
|
|
2439
|
+
const regionOf = (l) => (l.archive ? 'archive' : l.kind === 'topic' || l.kind === 'domain' ? l.kind : 'group');
|
|
2440
|
+
function treeItem(cls, level, label, parent) {
|
|
2441
|
+
const li = el('li', cls);
|
|
2442
|
+
li.setAttribute('role', 'treeitem');
|
|
2443
|
+
li.setAttribute('aria-level', String(level));
|
|
2444
|
+
li.tabIndex = -1;
|
|
2445
|
+
const row = el('div', 'ti');
|
|
2446
|
+
row.append(...label);
|
|
2447
|
+
li.append(row);
|
|
2448
|
+
parent.append(li);
|
|
2449
|
+
return li;
|
|
2450
|
+
}
|
|
2451
|
+
function addGroup(li) {
|
|
2452
|
+
const ul = el('ul');
|
|
2453
|
+
ul.setAttribute('role', 'group');
|
|
2454
|
+
ul.hidden = li.getAttribute('aria-expanded') !== 'true';
|
|
2455
|
+
li.append(ul);
|
|
2456
|
+
return ul;
|
|
2457
|
+
}
|
|
2458
|
+
function setExpanded(li, on) {
|
|
2459
|
+
if (!li.hasAttribute('aria-expanded')) return;
|
|
2460
|
+
li.setAttribute('aria-expanded', String(on));
|
|
2461
|
+
let ul = li.querySelector(':scope > ul');
|
|
2462
|
+
if (on && li.classList.contains('lobe') && !ul.childElementCount) { // pages are built on first open
|
|
2463
|
+
for (const p of topPagesOf(li.dataset.id, 20)) {
|
|
2464
|
+
const pi = treeItem('page', 3, [el('span'), el('span', 'nm', p.title)], ul);
|
|
2465
|
+
pi.dataset.id = p.id;
|
|
2466
|
+
pi.setAttribute('aria-selected', 'false');
|
|
2467
|
+
}
|
|
2468
|
+
}
|
|
2469
|
+
ul.hidden = !on;
|
|
2470
|
+
}
|
|
2471
|
+
function activate(li) {
|
|
2472
|
+
if (li.classList.contains('region')) setExpanded(li, li.getAttribute('aria-expanded') !== 'true');
|
|
2473
|
+
else if (li.classList.contains('lobe')) { setExpanded(li, true); selectLobe(li.dataset.id); }
|
|
2474
|
+
else if (li.classList.contains('site')) exploreSite(li.dataset.id);
|
|
2475
|
+
else explorePage(li.dataset.id);
|
|
2476
|
+
}
|
|
2477
|
+
// The tree's rows from D (again on a live update: open lobes and closed regions stay so).
|
|
2478
|
+
function fillOutline() {
|
|
2479
|
+
const tree = $('outline'), gone = tree.nextElementSibling;
|
|
2480
|
+
const okey = (li) => li.dataset.id || li.querySelector('.nm').textContent;
|
|
2481
|
+
const was = new Map([...tree.querySelectorAll('[aria-expanded]')].map((li) => [okey(li), li.getAttribute('aria-expanded')]));
|
|
2482
|
+
tree.replaceChildren();
|
|
2483
|
+
if (gone && gone.classList.contains('empty')) gone.remove();
|
|
2484
|
+
const lobes = D.brain.lobes.filter((l) => l.count > 0);
|
|
2485
|
+
for (const [r, word] of REGIONS) {
|
|
2486
|
+
const ls = lobes.filter((l) => regionOf(l) === r);
|
|
2487
|
+
if (!ls.length) continue;
|
|
2488
|
+
const n = ls.reduce((a, l) => a + l.count, 0);
|
|
2489
|
+
const ri = treeItem('region', 1, [icon('chevron'), el('span', 'nm', word), el('span', 'n', n.toLocaleString('en'))], tree);
|
|
2490
|
+
ri.setAttribute('aria-expanded', 'true');
|
|
2491
|
+
const rg = addGroup(ri);
|
|
2492
|
+
for (const l of ls) {
|
|
2493
|
+
const li = treeItem('lobe', 2, [icon('chevron'), el('span', 'code', code(l.title)), el('span', 'nm', l.title),
|
|
2494
|
+
el('span', 'n', l.count.toLocaleString('en'))], rg);
|
|
2495
|
+
li.dataset.id = l.id;
|
|
2496
|
+
li.title = `${l.title} · ${l.count.toLocaleString('en')}`;
|
|
2497
|
+
li.setAttribute('aria-label', `${l.title}, ${plural(l.count, 'page')}`);
|
|
2498
|
+
li.setAttribute('aria-expanded', 'false');
|
|
2499
|
+
li.setAttribute('aria-selected', 'false');
|
|
2500
|
+
addGroup(li);
|
|
2501
|
+
}
|
|
2502
|
+
}
|
|
2503
|
+
const st = D.brain.stem;
|
|
2504
|
+
if (st && st.shown && Array.isArray(st.sites)) {
|
|
2505
|
+
const ri = treeItem('region', 1, [icon('chevron'), el('span', 'nm', 'Browsing'), el('span', 'n', st.shown.toLocaleString('en'))], tree);
|
|
2506
|
+
ri.dataset.id = 'region:browsing';
|
|
2507
|
+
ri.setAttribute('aria-expanded', 'false');
|
|
2508
|
+
const rg = addGroup(ri), visits = (x) => +x[2] || 0;
|
|
2509
|
+
for (const x of st.sites.filter(Array.isArray).sort((a, b) => visits(b) - visits(a) || String(a[0]).localeCompare(String(b[0]))).slice(0, 20)) {
|
|
2510
|
+
const li = treeItem('page site', 2, [el('span'), el('span', 'nm', String(x[0])), el('span', 'n', visits(x).toLocaleString('en'))], rg);
|
|
2511
|
+
li.dataset.id = 'site:' + x[0];
|
|
2512
|
+
li.title = `${x[0]} · ${plural(visits(x), 'visit')}`;
|
|
2513
|
+
li.setAttribute('aria-label', `${x[0]}, website, ${plural(visits(x), 'visit')}`);
|
|
2514
|
+
li.setAttribute('aria-selected', 'false');
|
|
2515
|
+
}
|
|
2516
|
+
}
|
|
2517
|
+
if (!lobes.length) tree.after(el('p', 'empty', 'No lobes yet. Pages you save gather into lobes here.'));
|
|
2518
|
+
const f = brain && brain.focused; // a refill keeps the focused lobe marked
|
|
2519
|
+
$('all-lobes').setAttribute('aria-pressed', String(!f));
|
|
2520
|
+
for (const li of tree.querySelectorAll('.lobe')) li.setAttribute('aria-selected', String(li.dataset.id === f));
|
|
2521
|
+
for (const li of tree.querySelectorAll('[aria-expanded]')) {
|
|
2522
|
+
const open = was.get(okey(li));
|
|
2523
|
+
if (open && open !== li.getAttribute('aria-expanded')) setExpanded(li, open === 'true');
|
|
2524
|
+
}
|
|
2525
|
+
const first = tree.querySelector('[role="treeitem"]');
|
|
2526
|
+
if (first) first.tabIndex = 0;
|
|
2527
|
+
}
|
|
2528
|
+
function buildOutline() {
|
|
2529
|
+
fillOutline();
|
|
2530
|
+
const tree = $('outline');
|
|
2531
|
+
const visible =() => [...tree.querySelectorAll('[role="treeitem"]')].filter((li) => !li.parentElement.closest('[role="group"][hidden]'));
|
|
2532
|
+
const move = (li) => {
|
|
2533
|
+
if (!li) return;
|
|
2534
|
+
for (const x of tree.querySelectorAll('[role="treeitem"][tabindex="0"]')) x.tabIndex = -1;
|
|
2535
|
+
li.tabIndex = 0;
|
|
2536
|
+
li.focus();
|
|
2537
|
+
};
|
|
2538
|
+
tree.addEventListener('click', (e) => {
|
|
2539
|
+
const li = e.target.closest('[role="treeitem"]');
|
|
2540
|
+
if (!li) return;
|
|
2541
|
+
move(li);
|
|
2542
|
+
activate(li);
|
|
2543
|
+
});
|
|
2544
|
+
tree.addEventListener('keydown', (e) => {
|
|
2545
|
+
const li = e.target.closest('[role="treeitem"]');
|
|
2546
|
+
if (!li || e.ctrlKey || e.metaKey || e.altKey) return;
|
|
2547
|
+
const vis = visible(), i = vis.indexOf(li), open = li.getAttribute('aria-expanded');
|
|
2548
|
+
if (e.key === 'ArrowDown') move(vis[i + 1]);
|
|
2549
|
+
else if (e.key === 'ArrowUp') move(vis[i - 1]);
|
|
2550
|
+
else if (e.key === 'Home') move(vis[0]);
|
|
2551
|
+
else if (e.key === 'End') move(vis[vis.length - 1]);
|
|
2552
|
+
else if (e.key === 'ArrowRight') {
|
|
2553
|
+
if (open === 'false') setExpanded(li, true);
|
|
2554
|
+
else if (open === 'true') move(li.querySelector(':scope > ul > [role="treeitem"]'));
|
|
2555
|
+
} else if (e.key === 'ArrowLeft') {
|
|
2556
|
+
if (open === 'true') setExpanded(li, false);
|
|
2557
|
+
else move(li.parentElement.closest('[role="treeitem"]'));
|
|
2558
|
+
} else if (e.key === 'Enter' || e.key === ' ') activate(li);
|
|
2559
|
+
else return;
|
|
2560
|
+
e.preventDefault();
|
|
2561
|
+
});
|
|
2562
|
+
}
|
|
2563
|
+
|
|
2564
|
+
const LEGEND_KEY = 'keepfold.legend';
|
|
2565
|
+
function legendToggle() {
|
|
2566
|
+
// the first visit: open where it clears the stem (at 1024x768 it covers it); after it, closed unless opened
|
|
2567
|
+
let open = innerWidth >= 1300 && innerHeight >= 900;
|
|
2568
|
+
try {
|
|
2569
|
+
const v = localStorage.getItem(LEGEND_KEY);
|
|
2570
|
+
if (v === null) localStorage.setItem(LEGEND_KEY, 'closed'); else open = v === 'open';
|
|
2571
|
+
} catch (e) { /* storage off: the first-visit default */ }
|
|
2572
|
+
const t = $('legend-toggle'), set = (on) => { t.setAttribute('aria-expanded', String(on)); $('legend').hidden = !on; };
|
|
2573
|
+
t.prepend(icon('chevron'));
|
|
2574
|
+
set(open);
|
|
2575
|
+
t.addEventListener('click', () => {
|
|
2576
|
+
const on = t.getAttribute('aria-expanded') !== 'true';
|
|
2577
|
+
set(on);
|
|
2578
|
+
try { localStorage.setItem(LEGEND_KEY, on ? 'open' : 'closed'); } catch (e) { /* not kept */ }
|
|
2579
|
+
});
|
|
2580
|
+
}
|
|
2581
|
+
function renderBrainSection() {
|
|
2582
|
+
for (const b of $('viewswitch').children) b.addEventListener('click', () => setView(b.dataset.view));
|
|
2583
|
+
legendToggle();
|
|
2584
|
+
if (brainFailed) {
|
|
2585
|
+
$('b2d').prepend(noBrainNote('Showing the 2D map.'));
|
|
2586
|
+
return;
|
|
2587
|
+
}
|
|
2588
|
+
// The toolbar: modes, spin, Today, the unsorted-chat ring, and the Growth scrubber.
|
|
2589
|
+
const tools = $('brain-tools');
|
|
2590
|
+
const spin = button('btn tbtn', null, () => { if (brain) brain.setSpin(spin.getAttribute('aria-pressed') !== 'true'); });
|
|
2591
|
+
spin.textContent = 'Spin';
|
|
2592
|
+
spin.title = 'Turn the brain slowly when idle (S in the brain)';
|
|
2593
|
+
spin.setAttribute('aria-pressed', 'false');
|
|
2594
|
+
spinBtns.push(spin);
|
|
2595
|
+
const alive = button('btn tbtn', null, () => { if (brain) brain.setAlive(alive.getAttribute('aria-pressed') !== 'true'); });
|
|
2596
|
+
alive.textContent = 'Alive';
|
|
2597
|
+
alive.title = 'Neurons fire now and then and waves drift through the topics; sleeps after 2 minutes idle';
|
|
2598
|
+
alive.setAttribute('aria-pressed', String(!!(brain && brain.alive)));
|
|
2599
|
+
aliveBtns.push(alive);
|
|
2600
|
+
const arch = button('btn tbtn', 'Unsorted chats', () => {
|
|
2601
|
+
archiveOn = !archiveOn;
|
|
2602
|
+
arch.setAttribute('aria-pressed', String(archiveOn));
|
|
2603
|
+
if (brain) brain.setArchive(archiveOn);
|
|
2604
|
+
});
|
|
2605
|
+
arch.title = 'Show the unsorted chats as a faint ring under the brain';
|
|
2606
|
+
arch.setAttribute('aria-pressed', String(archiveOn));
|
|
2607
|
+
const scrub = buildScrub().root;
|
|
2608
|
+
scrub.id = 'scrub';
|
|
2609
|
+
tools.append(modeGroup(), spin, alive, todayBtn('btn'), stemBtn(), pictureBtn(), arch);
|
|
2610
|
+
tools.addEventListener('click', syncStem); // another flight (Today) leaves the stem
|
|
2611
|
+
if (HAS_STYLE) tools.append(lookBtn());
|
|
2612
|
+
tools.append(scrub);
|
|
2613
|
+
buildOutline();
|
|
2614
|
+
$('all-lobes').addEventListener('click', () => { if (brain) brain.focusCluster(null); markLobe(null); });
|
|
2615
|
+
$('outline-toggle').addEventListener('click', () => {
|
|
2616
|
+
const on = $('outline-toggle').getAttribute('aria-expanded') !== 'true';
|
|
2617
|
+
$('outline-toggle').setAttribute('aria-expanded', String(on));
|
|
2618
|
+
$('outline-box').hidden = !on;
|
|
2619
|
+
});
|
|
2620
|
+
if (!ensureBrain()) return;
|
|
2621
|
+
for (const [k, word] of KGROUPS) {
|
|
2622
|
+
const b = button(null, word, () => {
|
|
2623
|
+
if (brainFilter.kinds.has(k)) brainFilter.kinds.delete(k); else brainFilter.kinds.add(k);
|
|
2624
|
+
applyBrainFilter();
|
|
2625
|
+
});
|
|
2626
|
+
b.dataset.k = k;
|
|
2627
|
+
$('bkinds').append(b);
|
|
2628
|
+
}
|
|
2629
|
+
for (const s of STATES) {
|
|
2630
|
+
const b = button(null, null, () => {
|
|
2631
|
+
if (brainFilter.states.has(s)) brainFilter.states.delete(s); else brainFilter.states.add(s);
|
|
2632
|
+
applyBrainFilter();
|
|
2633
|
+
});
|
|
2634
|
+
b.dataset.s = s;
|
|
2635
|
+
b.append(glyph(s), ' ' + LABEL[s]);
|
|
2636
|
+
$('bstates').append(b);
|
|
2637
|
+
}
|
|
2638
|
+
applyBrainFilter();
|
|
2639
|
+
markLobe(null);
|
|
2640
|
+
let timer = 0;
|
|
2641
|
+
$('bq').addEventListener('input', () => {
|
|
2642
|
+
clearTimeout(timer);
|
|
2643
|
+
timer = setTimeout(() => {
|
|
2644
|
+
const msg = findInBrain();
|
|
2645
|
+
$('bq-note').textContent = msg;
|
|
2646
|
+
if (msg) live(msg);
|
|
2647
|
+
}, 160);
|
|
2648
|
+
});
|
|
2649
|
+
$('rail-toggle').addEventListener('click', () => {
|
|
2650
|
+
const open = $('rail').classList.toggle('closed');
|
|
2651
|
+
$('rail-toggle').setAttribute('aria-expanded', String(!open));
|
|
2652
|
+
$('rail-body').hidden = open;
|
|
2653
|
+
});
|
|
2654
|
+
if (phone()) $('rail-toggle').click();
|
|
2655
|
+
syncMode(brain.mode);
|
|
2656
|
+
}
|
|
2657
|
+
// the Find box's matches lit in the brain (an empty box: none); its message
|
|
2658
|
+
function findInBrain() {
|
|
2659
|
+
const q = $('bq').value.trim();
|
|
2660
|
+
if (!q) { brain.highlight(null); return ''; }
|
|
2661
|
+
const hits = search(q);
|
|
2662
|
+
brain.highlight(hits.map((h) => h.h.p.id));
|
|
2663
|
+
return hits.length ? `${plural(hits.length, 'page')} lit` : 'No pages match.';
|
|
2664
|
+
}
|
|
2665
|
+
let brainUi = false;
|
|
2666
|
+
function ensureBrainUi() { if (!brainUi) { brainUi = true; renderBrainSection(); } }
|
|
2667
|
+
function setView(v) {
|
|
2668
|
+
ensureBrainUi();
|
|
2669
|
+
if (v === '3d' && brainFailed) v = '2d';
|
|
2670
|
+
view = v;
|
|
2671
|
+
for (const b of $('viewswitch').children) b.setAttribute('aria-pressed', String(b.dataset.view === v));
|
|
2672
|
+
$('b3d').hidden = v !== '3d';
|
|
2673
|
+
$('b2d').hidden = v === '3d';
|
|
2674
|
+
hideTip();
|
|
2675
|
+
if (current !== 'brain') return;
|
|
2676
|
+
if (v === '3d') placeBrain('brain-slot');
|
|
2677
|
+
if (v === '3d' && brainFailed) { setView('2d'); return; } // the mount just failed
|
|
2678
|
+
if (v !== '3d') { closeLook(false); G.init(); G.setList(v === 'list'); }
|
|
2679
|
+
}
|
|
2680
|
+
|
|
2681
|
+
/* ---- Library ---- */
|
|
2682
|
+
const PRESETS = [['all', 'All'], ['project', 'Projects'], ['note', 'Notes'], ['decision', 'Decisions'],
|
|
2683
|
+
['reading', 'Reading'], ['chat', 'Chats'], ['youtube', 'YouTube'], ['person', 'People'], ['topic', 'Topics']];
|
|
2684
|
+
const LIB = { q: '', preset: 'all', lobe: '', tag: '', sort: 'date', shown: 100, hits: null };
|
|
2685
|
+
function inPreset(p) {
|
|
2686
|
+
const k = LIB.preset;
|
|
2687
|
+
if (k === 'all') return true;
|
|
2688
|
+
if (k === 'topic') return p.tags.includes('topic');
|
|
2689
|
+
if (k === 'reading') return p.kind === 'resource' && kindGroup(p) === 'other';
|
|
2690
|
+
if (k === 'chat' || k === 'youtube') return kindGroup(p) === k;
|
|
2691
|
+
return p.kind === k;
|
|
2692
|
+
}
|
|
2693
|
+
// Brain -> Library: a lobe clicked in the brain filters the Library (a chip clears it).
|
|
2694
|
+
function filterLibraryLobe(id) {
|
|
2695
|
+
LIB.lobe = id || '';
|
|
2696
|
+
LIB.shown = 100;
|
|
2697
|
+
$('llobe').value = LIB.lobe;
|
|
2698
|
+
renderLibraryRows();
|
|
2699
|
+
}
|
|
2700
|
+
function libraryFind(text) {
|
|
2701
|
+
$('lq').value = text;
|
|
2702
|
+
LIB.q = text;
|
|
2703
|
+
LIB.hits = new Set(search(text).map((h) => h.h.p.id));
|
|
2704
|
+
LIB.shown = 100;
|
|
2705
|
+
show('library');
|
|
2706
|
+
renderLibraryRows();
|
|
2707
|
+
}
|
|
2708
|
+
function setTag(t) {
|
|
2709
|
+
LIB.tag = t;
|
|
2710
|
+
LIB.shown = 100;
|
|
2711
|
+
show('library');
|
|
2712
|
+
renderLibraryRows();
|
|
2713
|
+
}
|
|
2714
|
+
function renderLibrary() {
|
|
2715
|
+
const pr = $('lpresets');
|
|
2716
|
+
for (const [k, word] of PRESETS) {
|
|
2717
|
+
const b = button(null, word, () => { LIB.preset = k; LIB.shown = 100; renderLibraryRows(); });
|
|
2718
|
+
b.dataset.k = k;
|
|
2719
|
+
pr.append(b);
|
|
2720
|
+
}
|
|
2721
|
+
const lob = $('llobe');
|
|
2722
|
+
fillLobes();
|
|
2723
|
+
lob.addEventListener('change', () => { LIB.lobe = lob.value; LIB.shown = 100; renderLibraryRows(); });
|
|
2724
|
+
$('lsort').addEventListener('change', () => { LIB.sort = $('lsort').value; renderLibraryRows(); });
|
|
2725
|
+
let timer = 0;
|
|
2726
|
+
$('lq').addEventListener('input', () => {
|
|
2727
|
+
clearTimeout(timer);
|
|
2728
|
+
timer = setTimeout(() => {
|
|
2729
|
+
LIB.q = $('lq').value.trim();
|
|
2730
|
+
LIB.hits = LIB.q ? new Set(search(LIB.q).map((h) => h.h.p.id)) : null;
|
|
2731
|
+
LIB.shown = 100;
|
|
2732
|
+
renderLibraryRows();
|
|
2733
|
+
}, 160);
|
|
2734
|
+
});
|
|
2735
|
+
$('lmore').addEventListener('click', () => { LIB.shown += 100; renderLibraryRows(); });
|
|
2736
|
+
renderLibraryRows();
|
|
2737
|
+
}
|
|
2738
|
+
function fillLobes() {
|
|
2739
|
+
const lob = $('llobe');
|
|
2740
|
+
lob.replaceChildren(lob.options[0]); // All lobes
|
|
2741
|
+
for (const c of D.clusters) {
|
|
2742
|
+
if (!c.count) continue;
|
|
2743
|
+
const o = el('option', null, `${code(c.title)} · ${c.title} (${c.count})`);
|
|
2744
|
+
o.value = c.id;
|
|
2745
|
+
lob.append(o);
|
|
2746
|
+
}
|
|
2747
|
+
lob.disabled = lob.options.length < 2; // no lobes yet: nothing to choose
|
|
2748
|
+
}
|
|
2749
|
+
function renderLibraryRows() {
|
|
2750
|
+
if (!rendered.has('library')) return;
|
|
2751
|
+
for (const b of $('lpresets').children) b.setAttribute('aria-pressed', String(b.dataset.k === LIB.preset));
|
|
2752
|
+
const tagBox = $('ltag');
|
|
2753
|
+
tagBox.hidden = !LIB.tag;
|
|
2754
|
+
tagBox.replaceChildren();
|
|
2755
|
+
if (LIB.tag) {
|
|
2756
|
+
tagBox.append(el('span', null, 'Tagged'), el('span', 'chip', '#' + LIB.tag),
|
|
2757
|
+
button('linkbtn', 'Clear tag', () => { LIB.tag = ''; renderLibraryRows(); }));
|
|
2758
|
+
}
|
|
2759
|
+
const chip = $('llobe-chip'), lobe = LOBES.get(LIB.lobe);
|
|
2760
|
+
$('llobe').value = LIB.lobe;
|
|
2761
|
+
chip.hidden = !lobe;
|
|
2762
|
+
chip.replaceChildren();
|
|
2763
|
+
if (lobe) {
|
|
2764
|
+
const x = button('chip', null, () => filterLibraryLobe(''), 'Clear the lobe filter');
|
|
2765
|
+
x.append('Filtered by ' + lobe.title + ' ', icon('close'));
|
|
2766
|
+
chip.append(x);
|
|
2767
|
+
}
|
|
2768
|
+
const rows = D.pages.filter((p) => inPreset(p) && (!LIB.lobe || p.cluster === LIB.lobe)
|
|
2769
|
+
&& (!LIB.tag || p.tags.includes(LIB.tag)) && (!LIB.hits || LIB.hits.has(p.id)));
|
|
2770
|
+
const key = LIB.sort === 'title' ? null : LIB.sort === 'updated' ? (p) => p.updated : dateOf;
|
|
2771
|
+
rows.sort(key ? (a, b) => { const x = key(a) || '', y = key(b) || ''; return x < y ? 1 : x > y ? -1 : a.title.localeCompare(b.title); }
|
|
2772
|
+
: (a, b) => a.title.localeCompare(b.title));
|
|
2773
|
+
$('lcount').textContent = `${rows.length.toLocaleString('en')} of ${D.pages.length.toLocaleString('en')} pages`
|
|
2774
|
+
+ (rows.length > LIB.shown ? `, showing the first ${LIB.shown.toLocaleString('en')}` : '');
|
|
2775
|
+
if (!rows.length) {
|
|
2776
|
+
$('ltable').replaceChildren(el('p', 'empty', D.pages.length
|
|
2777
|
+
? 'No pages match. Clear the search, preset, lobe or tag to see more.'
|
|
2778
|
+
: 'No pages yet. Import your chats or notes, or save something from a Claude chat.'));
|
|
2779
|
+
$('lmore').hidden = true;
|
|
2780
|
+
return;
|
|
2781
|
+
}
|
|
2782
|
+
const table = el('table'), thead = el('thead'), htr = el('tr'), tbody = el('tbody');
|
|
2783
|
+
for (const h of ['DATE', 'TITLE', 'KIND', 'TOPIC', 'SOURCE', 'UPDATED']) {
|
|
2784
|
+
const th = el('th', null, h);
|
|
2785
|
+
th.scope = 'col';
|
|
2786
|
+
htr.append(th);
|
|
2787
|
+
}
|
|
2788
|
+
thead.append(htr);
|
|
2789
|
+
for (const p of rows.slice(0, LIB.shown)) {
|
|
2790
|
+
const tr = el('tr'), tc = el('td', 'ttlc');
|
|
2791
|
+
tc.append(button(null, p.title, (e) => { e.stopPropagation(); openReader(p.id); }));
|
|
2792
|
+
if (p.summary) tc.append(el('span', 'sum', p.summary));
|
|
2793
|
+
const pc = el('td');
|
|
2794
|
+
pc.append(lobeChip(p.cluster));
|
|
2795
|
+
tr.append(el('td', 'nowrap', dateOf(p) ? fmtDay(dateOf(p)) + ' ' + dateOf(p).slice(0, 4) : ''), tc,
|
|
2796
|
+
el('td', 'nowrap', kindWord(p.kind)), pc, el('td', 'nowrap', p.source || ''), el('td', 'nowrap', fmtDay(p.updated)));
|
|
2797
|
+
tr.addEventListener('click', () => openReader(p.id));
|
|
2798
|
+
syncRow(tr, p.id);
|
|
2799
|
+
tbody.append(tr);
|
|
2800
|
+
}
|
|
2801
|
+
table.append(thead, tbody);
|
|
2802
|
+
$('ltable').replaceChildren(table);
|
|
2803
|
+
$('lmore').hidden = rows.length <= LIB.shown;
|
|
2804
|
+
}
|
|
2805
|
+
|
|
2806
|
+
/* ---- You ---- */
|
|
2807
|
+
const TIER_ROWS = [['you confirmed', ['confirmed', 'typed', 'legacy'], false],
|
|
2808
|
+
['a chat relayed (ask)', ['agent'], true], ['a chat saved (ask)', ['exposed'], true]];
|
|
2809
|
+
/* Mind Mirror (R27a): each line about you or decision and what replaced it, one lane per
|
|
2810
|
+
chain on a month axis. The list view is its table, and the narrow screen's default. */
|
|
2811
|
+
const MM = { all: false, list: null, SHOWN: 8, LANE: 36, AXIS: 22, END: 56, MIN_TEXT: 48 };
|
|
2812
|
+
const fullDay = (s) => `${fmtDay(s)} ${s.slice(0, 4)}`;
|
|
2813
|
+
const mmRange = (v) => `${v.open_start ? 'an unknown day' : fullDay(v.from)} to ${v.until ? fullDay(v.until) : 'now'}`;
|
|
2814
|
+
const mmTitle = (id) => (PAGES.has(id) ? PAGES.get(id).title : id);
|
|
2815
|
+
const utcDay = (s) => new Date(dayNum(s) * 864e5);
|
|
2816
|
+
function mindMirror() {
|
|
2817
|
+
const chains = (D.you && D.you.changes) || [];
|
|
2818
|
+
if (MM.list === null) MM.list = window.matchMedia('(max-width: 559px)').matches;
|
|
2819
|
+
const toggle = chains.length ? button('band-btn', '', () => { hideTip(); MM.list = !MM.list; draw(); }) : null;
|
|
2820
|
+
const b = board('Lines and decisions you replaced',
|
|
2821
|
+
{ note: chains.length ? plural(chains.length, 'change') : '', action: toggle });
|
|
2822
|
+
if (!chains.length) {
|
|
2823
|
+
b.body.append(el('p', 'empty', 'Nothing has changed yet. When you revise a line about you or replace a decision, both versions show here.'));
|
|
2824
|
+
return b.root;
|
|
2825
|
+
}
|
|
2826
|
+
const foot = el('div', 'foot');
|
|
2827
|
+
b.root.append(foot);
|
|
2828
|
+
let width = 0;
|
|
2829
|
+
function draw(expanded) {
|
|
2830
|
+
toggle.textContent = MM.list ? 'Show as a timeline' : 'Show as a list';
|
|
2831
|
+
const shown = MM.all ? chains : chains.slice(0, MM.SHOWN);
|
|
2832
|
+
b.body.replaceChildren(MM.list ? mmList(shown) : mmLanes(shown, chains, width));
|
|
2833
|
+
foot.replaceChildren();
|
|
2834
|
+
if (shown.length < chains.length) {
|
|
2835
|
+
foot.append(button('linkbtn', `Show all ${chains.length}`, () => { MM.all = true; draw(true); }));
|
|
2836
|
+
}
|
|
2837
|
+
foot.hidden = !foot.childNodes.length;
|
|
2838
|
+
const next = expanded && b.body.querySelector('.mm-first');
|
|
2839
|
+
if (next) next.focus(); // the button that had focus is gone: the first row it showed takes it
|
|
2840
|
+
}
|
|
2841
|
+
draw();
|
|
2842
|
+
new ResizeObserver(() => {
|
|
2843
|
+
const w = b.body.clientWidth;
|
|
2844
|
+
if (w && w !== width) { width = w; if (!MM.list) draw(); }
|
|
2845
|
+
}).observe(b.body);
|
|
2846
|
+
return b.root;
|
|
2847
|
+
}
|
|
2848
|
+
function mmList(shown) {
|
|
2849
|
+
const ul = el('ul', 'mm-list');
|
|
2850
|
+
shown.forEach((c, i) => {
|
|
2851
|
+
const li = el('li'), first = i === MM.SHOWN ? ' mm-first' : '';
|
|
2852
|
+
li.append(PAGES.has(c.page) ? button('linkbtn' + first, mmTitle(c.page), () => openReader(c.page))
|
|
2853
|
+
: el('span', null, mmTitle(c.page)));
|
|
2854
|
+
li.append(el('div', 'mm-chain', c.versions.map((v) =>
|
|
2855
|
+
`${v.text} (${mmRange(v)}${v.status === 'retired' ? ', retired' : ''})`).join(' → ')));
|
|
2856
|
+
ul.append(li);
|
|
2857
|
+
});
|
|
2858
|
+
return ul;
|
|
2859
|
+
}
|
|
2860
|
+
function mmLanes(shown, all, W) {
|
|
2861
|
+
const box = el('div', 'mm');
|
|
2862
|
+
box.style.height = (MM.AXIS + shown.length * MM.LANE) + 'px';
|
|
2863
|
+
const x0 = 4, x1 = W - 24 - MM.END; // .mm's side margins
|
|
2864
|
+
if (x1 - x0 < 40) return box; // not laid out yet: the resize observer draws it
|
|
2865
|
+
const hi = utcDay(TODAY), first = Math.min(...all.flatMap((c) => c.versions.map((v) => dayNum(v.from))));
|
|
2866
|
+
const lo = d3.utcMonth.floor(new Date(Math.min(first * 864e5, +d3.utcMonth.offset(hi, -1))));
|
|
2867
|
+
const x = d3.scaleUtc().domain([lo, hi]).range([x0, x1]).clamp(true);
|
|
2868
|
+
const months = Math.max(1, d3.utcMonth.count(lo, hi));
|
|
2869
|
+
const step = [1, 2, 3, 4, 6, 12].find((k) => (x1 - x0) * k / months >= 56) || 12;
|
|
2870
|
+
x.ticks(d3.utcMonth.every(step)).forEach((t, i) => {
|
|
2871
|
+
const tick = el('div', 'mm-tick');
|
|
2872
|
+
tick.style.left = x(t) + 'px';
|
|
2873
|
+
tick.append(el('span', null, MON[t.getUTCMonth()] + (i === 0 || t.getUTCMonth() === 0 ? ' ' + t.getUTCFullYear() : '')));
|
|
2874
|
+
tick.setAttribute('aria-hidden', 'true');
|
|
2875
|
+
box.append(tick);
|
|
2876
|
+
});
|
|
2877
|
+
shown.forEach((c, li) => {
|
|
2878
|
+
const lane = el('div', 'mm-lane');
|
|
2879
|
+
lane.style.top = (MM.AXIS + li * MM.LANE) + 'px';
|
|
2880
|
+
let end = -Infinity;
|
|
2881
|
+
c.versions.forEach((v, vi) => {
|
|
2882
|
+
const a = Math.max(x(utcDay(v.from)), end + 2), z = Math.max(v.until ? x(utcDay(v.until)) : x1, a + 4);
|
|
2883
|
+
const bar = el('div', 'mm-bar ' + (v.status === 'live' ? 'live' : 'past') + (v.open_start ? ' open' : '')
|
|
2884
|
+
+ (li === MM.SHOWN && vi === 0 ? ' mm-first' : ''));
|
|
2885
|
+
Object.assign(bar.style, { left: a + 'px', width: (z - a) + 'px' });
|
|
2886
|
+
bar.tabIndex = 0;
|
|
2887
|
+
bar.setAttribute('role', 'button');
|
|
2888
|
+
const span = `from ${mmRange(v)}${v.status === 'retired' ? ', then retired' : ''}`;
|
|
2889
|
+
bar.setAttribute('aria-label', `${v.text}, ${span}, on ${mmTitle(v.page)}`);
|
|
2890
|
+
const tipParts = () => [el('div', null, v.text), el('div', 'k', span), el('div', 'k', mmTitle(v.page))];
|
|
2891
|
+
bar.addEventListener('mouseenter', (e) => showTip(e, tipParts()));
|
|
2892
|
+
bar.addEventListener('mousemove', moveTip);
|
|
2893
|
+
bar.addEventListener('mouseleave', hideTip);
|
|
2894
|
+
bar.addEventListener('focus', () => { const r = bar.getBoundingClientRect(); showTipAt(r.left, r.bottom, tipParts()); });
|
|
2895
|
+
bar.addEventListener('blur', hideTip);
|
|
2896
|
+
bar.addEventListener('click', () => { hideTip(); openReader(v.page); });
|
|
2897
|
+
bar.addEventListener('keydown', (e) => {
|
|
2898
|
+
if (e.key !== 'Enter' && e.key !== ' ') return;
|
|
2899
|
+
e.preventDefault();
|
|
2900
|
+
hideTip();
|
|
2901
|
+
openReader(v.page);
|
|
2902
|
+
});
|
|
2903
|
+
lane.append(bar);
|
|
2904
|
+
if (z - a >= MM.MIN_TEXT) {
|
|
2905
|
+
const t = el('div', 'mm-text', v.text);
|
|
2906
|
+
Object.assign(t.style, { left: a + 'px', width: (z - a) + 'px' });
|
|
2907
|
+
t.setAttribute('aria-hidden', 'true');
|
|
2908
|
+
lane.append(t);
|
|
2909
|
+
}
|
|
2910
|
+
end = z;
|
|
2911
|
+
});
|
|
2912
|
+
const last = c.versions[c.versions.length - 1].status;
|
|
2913
|
+
if (last === 'retired') {
|
|
2914
|
+
const cap = el('div', 'mm-cap');
|
|
2915
|
+
cap.style.left = (end + 1) + 'px';
|
|
2916
|
+
lane.append(cap);
|
|
2917
|
+
}
|
|
2918
|
+
if (last === 'live' || last === 'retired') {
|
|
2919
|
+
const tag = el('span', 'mm-end', last === 'live' ? 'now' : 'retired');
|
|
2920
|
+
tag.style.left = (end + 6) + 'px';
|
|
2921
|
+
tag.setAttribute('aria-hidden', 'true');
|
|
2922
|
+
lane.append(tag);
|
|
2923
|
+
}
|
|
2924
|
+
box.append(lane);
|
|
2925
|
+
});
|
|
2926
|
+
return box;
|
|
2927
|
+
}
|
|
2928
|
+
function renderYou() {
|
|
2929
|
+
const host = $('view-you'), know = D.you.know || { pages: [], total: { tiers: {} } };
|
|
2930
|
+
host.append(el('h1', null, NAME || 'You'));
|
|
2931
|
+
const tiers = (t) => TIER_ROWS.map(([, keys]) => keys.reduce((a, k) => a + ((t || {})[k] || 0), 0));
|
|
2932
|
+
const pagesWith = know.pages.filter((p) => !p.private && p.live).length;
|
|
2933
|
+
const lead = el('p', 'muted');
|
|
2934
|
+
lead.textContent = `Keepfold has ${plural(tiers(know.total.tiers)[0], 'confirmed line')} about you across ${plural(pagesWith, 'page')}.`;
|
|
2935
|
+
host.append(lead);
|
|
2936
|
+
|
|
2937
|
+
const grid = el('div', 'you-grid');
|
|
2938
|
+
const wait = board('Waiting for your yes', { action: copyBtn('/keepfold reflect', 'band-btn') });
|
|
2939
|
+
const un = D.you.unconfirmed || [];
|
|
2940
|
+
if (!un.length) wait.body.append(el('p', 'empty', 'Nothing waiting. Lines a chat proposes about you wait here for your yes.'));
|
|
2941
|
+
for (const u of un) {
|
|
2942
|
+
const r = el('div', 'brow');
|
|
2943
|
+
const t = el('div', 't');
|
|
2944
|
+
t.append(el('div', null, u.text), el('span', 'sub', u.since ? 'proposed ' + fmtDay(u.since) : 'in inbox.md'));
|
|
2945
|
+
r.append(t, el('div'));
|
|
2946
|
+
wait.body.append(r);
|
|
2947
|
+
}
|
|
2948
|
+
wait.root.append(el('div', 'foot', 'Copy /keepfold reflect and paste it into Claude to go through them.'));
|
|
2949
|
+
|
|
2950
|
+
const kb = board('How well Keepfold knows you');
|
|
2951
|
+
const rows = know.pages.filter((p) => !p.private);
|
|
2952
|
+
const max = Math.max(1, ...rows.map((p) => Math.max(...tiers(p.tiers))));
|
|
2953
|
+
const box = el('div', 'tiers');
|
|
2954
|
+
for (const p of know.pages) {
|
|
2955
|
+
const r = el('div', 'trow2');
|
|
2956
|
+
const title = PAGES.has(p.page) ? button('linkbtn', PAGES.get(p.page).title, () => openReader(p.page)) : el('span', null, p.page);
|
|
2957
|
+
r.append(title);
|
|
2958
|
+
const bars = el('div');
|
|
2959
|
+
if (p.private) bars.append(el('span', 'sub', 'A private page; not shown here.'));
|
|
2960
|
+
else {
|
|
2961
|
+
tiers(p.tiers).forEach((v, k) => {
|
|
2962
|
+
const b = el('div', 'tbar'), tr = el('div', 'track' + (TIER_ROWS[k][2] ? ' ask' : '')), f = el('span');
|
|
2963
|
+
f.style.setProperty('--f', String(v / max)); // the fill is scaleX(--f)
|
|
2964
|
+
tr.append(f);
|
|
2965
|
+
tr.setAttribute('role', 'img');
|
|
2966
|
+
tr.setAttribute('aria-label', `${v} lines ${TIER_ROWS[k][0]}`);
|
|
2967
|
+
b.append(el('span', null, TIER_ROWS[k][0]), tr, el('span', 'v', v));
|
|
2968
|
+
bars.append(b);
|
|
2969
|
+
});
|
|
2970
|
+
}
|
|
2971
|
+
r.append(bars);
|
|
2972
|
+
box.append(r);
|
|
2973
|
+
}
|
|
2974
|
+
if (!know.pages.length) box.append(el('p', 'empty', 'No pages about you yet. Tell any Claude chat about yourself.'));
|
|
2975
|
+
kb.body.append(box);
|
|
2976
|
+
grid.append(wait.root, kb.root);
|
|
2977
|
+
host.append(grid);
|
|
2978
|
+
|
|
2979
|
+
host.append(el('h2', null, 'How your mind changed'), mindMirror());
|
|
2980
|
+
|
|
2981
|
+
host.append(el('h2', null, 'Your pages'));
|
|
2982
|
+
const g2 = el('div', 'you-grid');
|
|
2983
|
+
const me = D.pages.filter((p) => p.kind === 'me').sort((a, b) => (a.id === 'profile' ? -1 : b.id === 'profile' ? 1 : a.title.localeCompare(b.title)));
|
|
2984
|
+
const lb = board('About you', { note: plural(me.length, 'page') });
|
|
2985
|
+
const view = board('Profile');
|
|
2986
|
+
const peeks = [];
|
|
2987
|
+
const showMe = (p) => {
|
|
2988
|
+
for (const [b, id] of peeks) b.setAttribute('aria-pressed', String(id === p.id)); // which page is beside
|
|
2989
|
+
view.band.firstChild.textContent = p.title;
|
|
2990
|
+
const body = el('div', 'md me-view');
|
|
2991
|
+
body.append(md(p.body));
|
|
2992
|
+
view.body.replaceChildren(body);
|
|
2993
|
+
};
|
|
2994
|
+
if (!me.length) lb.body.append(el('p', 'empty', 'No me/ pages yet. Tell any Claude chat about yourself.'));
|
|
2995
|
+
for (const p of me) {
|
|
2996
|
+
const r = brow({ id: p.id, title: p.title, sub: p.summary || '', prompt: `/keepfold about ${p.id}`, brainId: p.id });
|
|
2997
|
+
const peek = iconBtn('chevron', 'Show beside the list', () => showMe(p));
|
|
2998
|
+
peeks.push([peek, p.id]);
|
|
2999
|
+
r.lastChild.prepend(peek);
|
|
3000
|
+
lb.body.append(r);
|
|
3001
|
+
}
|
|
3002
|
+
const prof = me.find((p) => p.id === 'profile') || me[0];
|
|
3003
|
+
if (prof) showMe(prof); else view.body.append(el('p', 'empty', 'No profile yet. Tell any Claude chat about yourself.'));
|
|
3004
|
+
g2.append(lb.root, view.root);
|
|
3005
|
+
host.append(g2);
|
|
3006
|
+
|
|
3007
|
+
host.append(el('h2', null, 'Patterns'));
|
|
3008
|
+
const pats = D.pages.filter((p) => p.tags.includes('patterns'));
|
|
3009
|
+
host.append(boardList(board('Patterns Keepfold has noticed'), pats.map((p) => brow({ id: p.id, title: p.title,
|
|
3010
|
+
sub: p.summary || '', brainId: p.id })), 50,
|
|
3011
|
+
'No pattern notes yet. Ask a Claude chat to look for patterns in your imports.'));
|
|
3012
|
+
}
|
|
3013
|
+
|
|
3014
|
+
/* ---- Timeline ---- */
|
|
3015
|
+
const STEP = (n) => (n >= 8 ? 3 : n >= 3 ? 2 : n >= 1 ? 1 : 0); // fixed thresholds: 1, 3, 8+
|
|
3016
|
+
function renderTimeline() {
|
|
3017
|
+
const host = $('view-timeline');
|
|
3018
|
+
host.append(el('h1', null, 'Timeline'));
|
|
3019
|
+
const byDay = new Map();
|
|
3020
|
+
for (const p of D.pages) {
|
|
3021
|
+
if (!isDay(p.date)) continue;
|
|
3022
|
+
const d = p.date.slice(0, 10);
|
|
3023
|
+
if (!byDay.has(d)) byDay.set(d, []);
|
|
3024
|
+
byDay.get(d).push(p);
|
|
3025
|
+
}
|
|
3026
|
+
if (!byDay.size) {
|
|
3027
|
+
host.append(el('p', 'empty', 'No dated pages yet. Import your chats or keep a journal and they appear here.'));
|
|
3028
|
+
return;
|
|
3029
|
+
}
|
|
3030
|
+
const days = [...byDay.keys()].sort();
|
|
3031
|
+
const last = days[days.length - 1] > TODAY ? TODAY : days[days.length - 1];
|
|
3032
|
+
let y = +last.slice(0, 4), m = +last.slice(5, 7);
|
|
3033
|
+
const first = days[0].slice(0, 7), months = [];
|
|
3034
|
+
while (months.length < 48) {
|
|
3035
|
+
const key = `${y}-${String(m).padStart(2, '0')}`;
|
|
3036
|
+
months.push(key);
|
|
3037
|
+
if (key <= first) break;
|
|
3038
|
+
if (--m === 0) { m = 12; y--; }
|
|
3039
|
+
}
|
|
3040
|
+
host.append(el('p', 'muted', `Pages by the day they were written, newest month first${months.length === 48 ? ' (the last 48 months)' : ''}. Every month uses the same scale.`));
|
|
3041
|
+
const LW = 116, CW = 14, RH = 25, TW = 48;
|
|
3042
|
+
const W = LW + 31 * CW + TW, H = months.length * RH;
|
|
3043
|
+
const svg = svgEl('svg', { class: 'tl-grid', viewBox: `0 0 ${W} ${H}`, width: W, height: H, role: 'group',
|
|
3044
|
+
'aria-label': 'Pages per day, one row per month' });
|
|
3045
|
+
const label = (day, n) => `${+day.slice(8, 10)} ${MON[+day.slice(5, 7) - 1]} ${day.slice(0, 4)} · ${plural(n, 'page')}`;
|
|
3046
|
+
months.forEach((key, r) => {
|
|
3047
|
+
const g = svgEl('g', { transform: `translate(0 ${r * RH})` });
|
|
3048
|
+
const lab = dm(MON[+key.slice(5, 7) - 1] + ' ' + key.slice(2, 4), 2);
|
|
3049
|
+
lab.setAttribute('x', 0);
|
|
3050
|
+
lab.setAttribute('y', 2); // 21 px tall in a 25 px row
|
|
3051
|
+
g.append(lab);
|
|
3052
|
+
const dim = new Date(Date.UTC(+key.slice(0, 4), +key.slice(5, 7), 0)).getUTCDate();
|
|
3053
|
+
let total = 0;
|
|
3054
|
+
for (let d = 1; d <= dim; d++) {
|
|
3055
|
+
const day = `${key}-${String(d).padStart(2, '0')}`, n = (byDay.get(day) || []).length;
|
|
3056
|
+
total += n;
|
|
3057
|
+
const c = svgEl('circle', { cx: LW + (d - 1) * CW + CW / 2, cy: RH / 2, r: 4.5, class: 'c' + STEP(n) + (n ? ' hit' : '') });
|
|
3058
|
+
c.dataset.day = day;
|
|
3059
|
+
c.dataset.n = n;
|
|
3060
|
+
if (n) { // a day with pages is a keyboard button too, not mouse-only
|
|
3061
|
+
c.setAttribute('tabindex', '0');
|
|
3062
|
+
c.setAttribute('role', 'button');
|
|
3063
|
+
c.setAttribute('aria-label', label(day, n));
|
|
3064
|
+
} else c.setAttribute('aria-hidden', 'true');
|
|
3065
|
+
g.append(c);
|
|
3066
|
+
}
|
|
3067
|
+
const t = svgEl('text', { x: W - 4, y: RH / 2 + 4, 'text-anchor': 'end', class: 'tl-total' });
|
|
3068
|
+
t.textContent = String(total);
|
|
3069
|
+
g.append(t);
|
|
3070
|
+
svg.append(g);
|
|
3071
|
+
});
|
|
3072
|
+
svg.addEventListener('mousemove', (e) => {
|
|
3073
|
+
const c = e.target.closest('circle');
|
|
3074
|
+
if (!c) { hideTip(); return; }
|
|
3075
|
+
showTip(e, [label(c.dataset.day, +c.dataset.n)]);
|
|
3076
|
+
});
|
|
3077
|
+
svg.addEventListener('mouseleave', hideTip);
|
|
3078
|
+
const list = el('div');
|
|
3079
|
+
let selC = null;
|
|
3080
|
+
const pick = (e) => {
|
|
3081
|
+
const c = e.target.closest('circle');
|
|
3082
|
+
if (!c || !+c.dataset.n) return;
|
|
3083
|
+
if (e.type === 'keydown') {
|
|
3084
|
+
if (e.key !== 'Enter' && e.key !== ' ') return;
|
|
3085
|
+
e.preventDefault();
|
|
3086
|
+
}
|
|
3087
|
+
if (selC) selC.classList.remove('sel');
|
|
3088
|
+
selC = c;
|
|
3089
|
+
c.classList.add('sel');
|
|
3090
|
+
dayList(list, c.dataset.day, byDay.get(c.dataset.day));
|
|
3091
|
+
};
|
|
3092
|
+
svg.addEventListener('click', pick);
|
|
3093
|
+
svg.addEventListener('keydown', pick);
|
|
3094
|
+
const wrap = board('Activity', { note: `${plural(byDay.size, 'day')} with dated pages` });
|
|
3095
|
+
const sc = el('div', 'tl-wrap');
|
|
3096
|
+
sc.append(svg);
|
|
3097
|
+
const key = el('div', 'tl-key');
|
|
3098
|
+
for (const [s, txt] of [[0, 'none'], [1, '1 to 2 pages'], [2, '3 to 7'], [3, '8 or more']]) {
|
|
3099
|
+
const k = el('span'), ks = svgEl('svg', { width: 12, height: 12, class: 'tl-grid', 'aria-hidden': 'true' });
|
|
3100
|
+
ks.append(svgEl('circle', { cx: 6, cy: 6, r: 4.5, class: 'c' + s }));
|
|
3101
|
+
k.append(ks, ' ' + txt);
|
|
3102
|
+
key.append(k);
|
|
3103
|
+
}
|
|
3104
|
+
key.append(el('span', null, 'Click a day to list its pages.'));
|
|
3105
|
+
sc.append(key);
|
|
3106
|
+
wrap.body.append(sc);
|
|
3107
|
+
host.append(wrap.root, list);
|
|
3108
|
+
|
|
3109
|
+
host.append(el('h2', null, 'Months'));
|
|
3110
|
+
const SRC = [['Claude', (p) => p.source === 'Claude'], ['Gemini', (p) => p.source === 'Gemini'],
|
|
3111
|
+
['Perplexity', (p) => p.source === 'Perplexity'], ['YouTube', (p) => p.source === 'YouTube' || p.source === 'NotebookLM'],
|
|
3112
|
+
['notes', (p) => p.kind === 'note'], ['journal', (p) => p.kind === 'journal']];
|
|
3113
|
+
const mb = board('Months');
|
|
3114
|
+
const ul = el('ul', 'months');
|
|
3115
|
+
for (const key of months) {
|
|
3116
|
+
const ps = days.filter((d) => d.startsWith(key)).flatMap((d) => byDay.get(d));
|
|
3117
|
+
if (!ps.length) continue;
|
|
3118
|
+
const li = el('li');
|
|
3119
|
+
li.append(el('span', 'm', fmtMonth(key + '-01')));
|
|
3120
|
+
for (const [word, f] of SRC) {
|
|
3121
|
+
const n = ps.filter(f).length;
|
|
3122
|
+
if (n) li.append(el('span', 'muted', `${word} ${n}`));
|
|
3123
|
+
}
|
|
3124
|
+
const jr = D.pages.find((p) => p.kind === 'journal' && p.id.startsWith(key));
|
|
3125
|
+
if (jr) li.append(button('linkbtn', 'Journal', () => openReader(jr.id)));
|
|
3126
|
+
if (PAGES.has('youtube-' + key)) li.append(button('linkbtn', 'YouTube month', () => openReader('youtube-' + key)));
|
|
3127
|
+
ul.append(li);
|
|
3128
|
+
}
|
|
3129
|
+
mb.body.append(ul);
|
|
3130
|
+
host.append(mb.root);
|
|
3131
|
+
}
|
|
3132
|
+
function dayList(host, day, ps) {
|
|
3133
|
+
const groups = new Map();
|
|
3134
|
+
for (const p of ps) {
|
|
3135
|
+
const k = p.source || kindWord(p.kind);
|
|
3136
|
+
if (!groups.has(k)) groups.set(k, []);
|
|
3137
|
+
groups.get(k).push(p);
|
|
3138
|
+
}
|
|
3139
|
+
const b = board(`${+day.slice(8, 10)} ${MON[+day.slice(5, 7) - 1]} ${day.slice(0, 4)}`, { note: plural(ps.length, 'page') });
|
|
3140
|
+
for (const [k, xs] of groups) {
|
|
3141
|
+
b.body.append(el('h4', 'pad-h', k));
|
|
3142
|
+
for (const p of xs) b.body.append(brow({ id: p.id, title: p.title, sub: p.summary || kindWord(p.kind), left: lobeChip(p.cluster), brainId: p.id }));
|
|
3143
|
+
}
|
|
3144
|
+
b.root.style.marginTop = '16px';
|
|
3145
|
+
host.replaceChildren(b.root);
|
|
3146
|
+
b.root.scrollIntoView({ block: 'nearest', behavior: REDUCED.matches ? 'auto' : 'smooth' });
|
|
3147
|
+
}
|
|
3148
|
+
|
|
3149
|
+
/* ---- Ideas ---- */
|
|
3150
|
+
function renderIdeas() {
|
|
3151
|
+
const host = $('view-ideas');
|
|
3152
|
+
host.append(el('h1', null, 'Ideas and loops'));
|
|
3153
|
+
const grid = el('div', 'ideas-grid');
|
|
3154
|
+
const lb = board('Open loops', { note: plural(D.loops.length, 'open loop') });
|
|
3155
|
+
if (!D.loops.length) lb.body.append(el('p', 'empty', "No open loops. Say 'remind me to…' in any Claude chat."));
|
|
3156
|
+
const TYPES = [['commitment', 'Commitments'], ['question', 'Questions'], ['idea', 'Ideas']];
|
|
3157
|
+
const known = new Set(TYPES.map((t) => t[0]));
|
|
3158
|
+
for (const [t, word] of [...TYPES, ['', 'Other']]) {
|
|
3159
|
+
const ls = D.loops.filter((l) => (t ? l.loop_type === t : !known.has(l.loop_type)));
|
|
3160
|
+
if (!ls.length) continue;
|
|
3161
|
+
lb.body.append(el('h4', 'pad-h', word));
|
|
3162
|
+
for (const l of ls) lb.body.append(loopRow(l));
|
|
3163
|
+
}
|
|
3164
|
+
grid.append(lb.root);
|
|
3165
|
+
grid.append(boardList(board('Decisions to revisit'), D.follow_ups.map(followRow), 1e9,
|
|
3166
|
+
'No decisions waiting for a second look. A decision with a review date shows up here when it is due.'));
|
|
3167
|
+
grid.append(boardList(board('Back on your mind'), D.resurface.map(resurfaceRow), 1e9,
|
|
3168
|
+
'Nothing coming back today. Old ideas and decisions return here when they are due another look.'));
|
|
3169
|
+
host.append(grid);
|
|
3170
|
+
host.append(el('h2', null, 'Recent ideas'));
|
|
3171
|
+
const since = new Date(dayNum(TODAY) * 864e5 - 30 * 864e5).toISOString().slice(0, 10);
|
|
3172
|
+
const ideas = D.pages.filter((p) => p.kind === 'note' && (p.tags.includes('idea')
|
|
3173
|
+
|| ['fleeting', 'permanent'].includes(String(p.props.note_type || ''))) && (dateOf(p) || '') >= since)
|
|
3174
|
+
.sort((a, b) => (dateOf(b) > dateOf(a) ? 1 : -1));
|
|
3175
|
+
host.append(boardList(board('Notes from the last 30 days', { note: plural(ideas.length, 'note') }),
|
|
3176
|
+
ideas.map((p) => brow({ id: p.id, title: p.title, sub: `${fmtDay(dateOf(p))} · ${p.summary || kindWord(p.kind)}`,
|
|
3177
|
+
left: lobeChip(p.cluster), prompt: `/keepfold about ${p.id}`, brainId: p.id })), 1e9,
|
|
3178
|
+
'No new ideas in the last 30 days. Say "note this idea" in any Claude chat.'));
|
|
3179
|
+
}
|
|
3180
|
+
|
|
3181
|
+
/* ---- Study (the old Today and History) ---- */
|
|
3182
|
+
function renderStudy() {
|
|
3183
|
+
// v8: plans have no dates; each shows its next step and how many are done and left
|
|
3184
|
+
const box = $('sprint'), ps = D.plans || [];
|
|
3185
|
+
if (!ps.length) box.hidden = true;
|
|
3186
|
+
for (const p of ps) {
|
|
3187
|
+
box.append(el('p', null, `${p.title} · ${p.next.length ? 'next: ' + p.next[0] : 'all steps done'}`
|
|
3188
|
+
+ ` · ${p.done} done · ${p.left} left`));
|
|
3189
|
+
}
|
|
3190
|
+
const tiles = $('tiles');
|
|
3191
|
+
for (const st of STATES) {
|
|
3192
|
+
const b = button(null, null, () => { show('brain'); setView('2d'); G.onlyState(st); });
|
|
3193
|
+
b.append(glyph(st), ' ' + LABEL[st], dm(String(D.counts[st] || 0), 4));
|
|
3194
|
+
b.setAttribute('aria-label', `${LABEL[st]}: ${D.counts[st] || 0}, show on the 2D map`);
|
|
3195
|
+
tiles.append(b);
|
|
3196
|
+
}
|
|
3197
|
+
const plan = $('plan');
|
|
3198
|
+
const leeches = D.leeches || [], leech = new Set(leeches.map((x) => x.id));
|
|
3199
|
+
if (leeches.length) { // concepts forgotten again and again after they were learned
|
|
3200
|
+
const n = leeches.length, first = leeches[0].id, line = el('p', 'small');
|
|
3201
|
+
const text = n === 1 ? '1 concept keeps slipping: simplify its note.' : `${n} concepts keep slipping: simplify their notes.`;
|
|
3202
|
+
line.append(PAGES.has(first) || GN.has(first) ? button('linkbtn', text, () => openReader(first)) : text);
|
|
3203
|
+
plan.append(line);
|
|
3204
|
+
}
|
|
3205
|
+
if (D.first_run) plan.append(firstRunBoard());
|
|
3206
|
+
else if (D.plan_cleared) plan.append(el('div', 'board done-card', 'Done for today ✓'));
|
|
3207
|
+
else if (!D.today.length) plan.append(el('p', 'empty', 'Nothing planned yet. Run /keepfold in Claude to pick what to learn next.'));
|
|
3208
|
+
for (const [kind, head] of GROUPS) {
|
|
3209
|
+
const items = D.today.filter((i) => i.kind === kind);
|
|
3210
|
+
if (!items.length) continue;
|
|
3211
|
+
const g = el('div', 'group');
|
|
3212
|
+
const ul = el('ul', 'rows');
|
|
3213
|
+
for (const i of items) {
|
|
3214
|
+
const li = el('li', 'row');
|
|
3215
|
+
const mid = el('span', 'title');
|
|
3216
|
+
mid.append(PAGES.has(i.id) || GN.has(i.id) ? button('linkbtn', i.title, () => openReader(i.id)) : i.title);
|
|
3217
|
+
if (i.state) mid.append(el('span', 'label muted', LABEL[i.state]));
|
|
3218
|
+
if (leech.has(i.id)) {
|
|
3219
|
+
const tag = el('span', 'label muted', 'leech');
|
|
3220
|
+
tag.title = i.why;
|
|
3221
|
+
mid.append(tag);
|
|
3222
|
+
}
|
|
3223
|
+
li.append(glyph(i.state), mid, el('span', 'why', i.why === head ? '' : i.why));
|
|
3224
|
+
ul.append(li);
|
|
3225
|
+
}
|
|
3226
|
+
g.append(el('h3', null, head), ul);
|
|
3227
|
+
plan.append(g);
|
|
3228
|
+
}
|
|
3229
|
+
const coming = $('coming');
|
|
3230
|
+
if (!D.assessments.length) coming.append(el('p', 'empty', 'Nothing scheduled. Tell any Claude chat about a test and its date.'));
|
|
3231
|
+
for (const a of D.assessments) {
|
|
3232
|
+
const c = el('div', 'board assess');
|
|
3233
|
+
c.append(el('h3', null, [a.company || a.id, a.kind].filter(Boolean).join(' · ')));
|
|
3234
|
+
const n = a.days_left;
|
|
3235
|
+
c.append(el('div', 'when', n == null ? 'date not set' : n === 0 ? 'today' : n === 1 ? 'tomorrow' : `in ${n} days`));
|
|
3236
|
+
const r = a.readiness;
|
|
3237
|
+
if (r.total) {
|
|
3238
|
+
const wrap = el('div', 'ready'), bar = el('div', 'bar');
|
|
3239
|
+
bar.setAttribute('role', 'img');
|
|
3240
|
+
const { pct, label } = readiness(r);
|
|
3241
|
+
bar.setAttribute('aria-label', label);
|
|
3242
|
+
const fill = el('span');
|
|
3243
|
+
fill.style.setProperty('--f', String(pct / 100)); // the fill is scaleX(--f)
|
|
3244
|
+
bar.append(fill);
|
|
3245
|
+
wrap.append(bar);
|
|
3246
|
+
c.append(wrap, el('div', 'small muted', label));
|
|
3247
|
+
if (r.forecast != null) { // FSRS prediction, never a score; the Solid share stays
|
|
3248
|
+
const day = new Date(a.date + 'T12:00').toLocaleDateString('en-GB', { day: 'numeric', month: 'short' });
|
|
3249
|
+
c.append(el('div', 'small muted', `Forecast recall on ${day}: ${Math.round(100 * r.forecast)}%`));
|
|
3250
|
+
} else if (r.calibrating) { // too few checked forecasts to trust a number yet
|
|
3251
|
+
const { n, need } = r.calibrating; // enough reviews but no skill yet: say so, like render.py
|
|
3252
|
+
c.append(el('div', 'small muted', n < need ? `Forecast after ${need} checked reviews (${n} so far)`
|
|
3253
|
+
: 'Forecast still calibrating: not yet better than a guess'));
|
|
3254
|
+
}
|
|
3255
|
+
} else c.append(el('div', 'small muted', 'No tested topics recorded'));
|
|
3256
|
+
if (a.domains.length) {
|
|
3257
|
+
const chips = el('div', 'chip-list');
|
|
3258
|
+
for (const d of a.domains) chips.append(el('span', 'chip', d));
|
|
3259
|
+
c.append(chips);
|
|
3260
|
+
}
|
|
3261
|
+
const acts = el('div', 'chip-list');
|
|
3262
|
+
const cp = button('btn', null, () => copyText(`/keepfold mock ${a.id}`, cp));
|
|
3263
|
+
cp.append(icon('copy'), ' Copy mock prompt');
|
|
3264
|
+
acts.append(cp);
|
|
3265
|
+
c.append(acts);
|
|
3266
|
+
coming.append(c);
|
|
3267
|
+
}
|
|
3268
|
+
const om = $('open-mistakes');
|
|
3269
|
+
const open = D.mistakes.filter((m) => m.status === 'open').slice(0, 5);
|
|
3270
|
+
if (!open.length) om.append(el('p', 'empty', 'No open mistakes. A wrong answer in a graded check shows up here until it is fixed.'));
|
|
3271
|
+
for (const m of open) {
|
|
3272
|
+
const row = el('div', 'mrow');
|
|
3273
|
+
const left = el('span');
|
|
3274
|
+
left.append(el('span', 'flag', '⚑ '), PAGES.has(m.id) ? button('linkbtn', m.title, () => openReader(m.id)) : m.title,
|
|
3275
|
+
el('span', 'muted', ` (${m.count}×)`));
|
|
3276
|
+
row.append(left, el('span', 'muted small', m.last_day ? 'last ' + fmtDay(m.last_day) : ''));
|
|
3277
|
+
om.append(row);
|
|
3278
|
+
}
|
|
3279
|
+
renderHistory();
|
|
3280
|
+
}
|
|
3281
|
+
function renderHistory() {
|
|
3282
|
+
const W = D.history.weeks, host = $('weeks');
|
|
3283
|
+
const w = Math.max(320, host.clientWidth - 28 || 640), h = 200;
|
|
3284
|
+
const m = { t: 12, r: 6, b: 26, l: 30 };
|
|
3285
|
+
const x = d3.scaleBand().domain(W.map((d) => d.start)).range([m.l, w - m.r]);
|
|
3286
|
+
const max = d3.max(W, (d) => d.answers) || 1;
|
|
3287
|
+
const y = d3.scaleLinear().domain([0, max]).nice().range([h - m.b, m.t]);
|
|
3288
|
+
const svg = d3.select(host).append('svg').attr('viewBox', `0 0 ${w} ${h}`)
|
|
3289
|
+
.attr('role', 'img').attr('aria-label', 'Graded answers per week, last 8 weeks: '
|
|
3290
|
+
+ W.map((d) => `${fmtDay(d.start)} ${d.answers}`).join(', '));
|
|
3291
|
+
const ticks = y.ticks(4);
|
|
3292
|
+
svg.append('g').selectAll('line').data(ticks).join('line').attr('class', 'grid')
|
|
3293
|
+
.attr('x1', m.l).attr('x2', w - m.r).attr('y1', y).attr('y2', y);
|
|
3294
|
+
svg.append('g').selectAll('text').data(ticks).join('text').attr('class', 'axis')
|
|
3295
|
+
.attr('x', m.l - 6).attr('y', (d) => y(d) + 4).attr('text-anchor', 'end').text((d) => d);
|
|
3296
|
+
const bw = Math.max(1, x.bandwidth() - 2);
|
|
3297
|
+
svg.append('g').selectAll('rect').data(W).join('rect').attr('class', 'wbar')
|
|
3298
|
+
.attr('x', (d) => x(d.start) + 1).attr('width', bw)
|
|
3299
|
+
.attr('y', (d) => y(d.answers)).attr('height', (d) => Math.max(0, y(0) - y(d.answers)))
|
|
3300
|
+
.on('mouseenter', (e, d) => showTip(e, [`Week of ${fmtDay(d.start)}: ` + plural(d.answers, 'answer')]))
|
|
3301
|
+
.on('mousemove', moveTip).on('mouseleave', hideTip);
|
|
3302
|
+
svg.append('g').selectAll('text').data(W).join('text').attr('class', 'axis')
|
|
3303
|
+
.attr('x', (d) => x(d.start) + x.bandwidth() / 2).attr('y', h - 8)
|
|
3304
|
+
.attr('text-anchor', 'middle').text((d) => fmtDay(d.start));
|
|
3305
|
+
|
|
3306
|
+
const tl = $('timeline');
|
|
3307
|
+
const rows = D.history.assessments;
|
|
3308
|
+
if (!rows.length) tl.append(el('p', 'empty', 'No assessments yet. Tell any Claude chat about a test and its date.'));
|
|
3309
|
+
for (const a of rows) {
|
|
3310
|
+
const r = el('div', 'trow');
|
|
3311
|
+
const who = el('span');
|
|
3312
|
+
who.append(a.company || a.id, el('span', 'muted', a.kind ? ' · ' + a.kind : ''));
|
|
3313
|
+
r.append(el('span', 'muted', a.date ? fmtDay(a.date) + ' ' + a.date.slice(0, 4) : 'date not set'),
|
|
3314
|
+
el('span', 'badge', OUTCOME[a.outcome] || a.outcome), who,
|
|
3315
|
+
el('span', 'muted', a.score ? 'score ' + a.score : ''));
|
|
3316
|
+
tl.append(r);
|
|
3317
|
+
}
|
|
3318
|
+
const ms = $('mstats');
|
|
3319
|
+
for (const [k, word] of [['opened', 'opened'], ['resolved', 'resolved']]) {
|
|
3320
|
+
const b = el('div');
|
|
3321
|
+
b.append(dm(String(D.history.mistakes[k]), 4), el('span', 'muted', word));
|
|
3322
|
+
ms.append(b);
|
|
3323
|
+
}
|
|
3324
|
+
// display-only; a band under its minimum shows its count, not a share
|
|
3325
|
+
const mir = $('mirror'), C = D.confidence || [];
|
|
3326
|
+
if (!C.some((r) => r.n)) mir.append(el('p', 'empty', 'No answers with a "how sure" (1-4) yet. Say how sure you are when you answer in /keepfold review.'));
|
|
3327
|
+
else {
|
|
3328
|
+
mir.append(el('p', 'small muted', 'Each time you answer, you say how sure you are. This is how often you were right at each level, over all your answers.'));
|
|
3329
|
+
for (const r of C) {
|
|
3330
|
+
mir.append(el('div', 'mrow', r.share == null
|
|
3331
|
+
? `When you said ${r.label}: not enough answers yet (${r.n})`
|
|
3332
|
+
: `When you said ${r.label}, you were right ${r.right} of ${r.n} times`));
|
|
3333
|
+
}
|
|
3334
|
+
}
|
|
3335
|
+
}
|
|
3336
|
+
|
|
3337
|
+
/* ---- Help ---- */
|
|
3338
|
+
function commandRows() {
|
|
3339
|
+
const md0 = D.help && D.help.commands_md;
|
|
3340
|
+
if (!md0) return [];
|
|
3341
|
+
const out = [];
|
|
3342
|
+
for (const line of md0.split('\n')) {
|
|
3343
|
+
const m = /^\|\s*`([^`]+)`\s*\|\s*(.*?)\s*\|?\s*$/.exec(line);
|
|
3344
|
+
if (m && /^\/?keepfold\b/.test(m[1])) out.push({ cmd: m[1], desc: m[2].replace(/[`*]/g, '') });
|
|
3345
|
+
}
|
|
3346
|
+
return out;
|
|
3347
|
+
}
|
|
3348
|
+
function renderHelp() {
|
|
3349
|
+
const host = $('view-help');
|
|
3350
|
+
host.append(el('h1', null, 'Help'));
|
|
3351
|
+
const prose = el('div', 'prose');
|
|
3352
|
+
prose.append(el('p', null, `${greeting()}. Here is everything Keepfold can do.`),
|
|
3353
|
+
el('p', 'muted', 'This page is read-only: buttons copy a command to paste into Claude; Claude does every write.'));
|
|
3354
|
+
if (LIVE) { // the app's step-by-step first-run dialog; a snapshot file has no app behind it
|
|
3355
|
+
const wg = el('a', null, 'Show the welcome guide'), wgP = el('p', null, 'New to Keepfold? ');
|
|
3356
|
+
wg.href = '/manage#welcome';
|
|
3357
|
+
wgP.append(wg);
|
|
3358
|
+
prose.append(wgP);
|
|
3359
|
+
}
|
|
3360
|
+
host.append(prose);
|
|
3361
|
+
const h = D.help || {};
|
|
3362
|
+
if (!h.commands_md) {
|
|
3363
|
+
host.append(el('p', 'empty', 'Run /keepfold help in Claude for every command.'));
|
|
3364
|
+
} else {
|
|
3365
|
+
host.append(el('h2', null, 'Commands'));
|
|
3366
|
+
const src = h.commands_md, cut = src.indexOf('\n---'); // the lines above are for Claude
|
|
3367
|
+
const body = el('div', 'md help-cmds');
|
|
3368
|
+
body.append(md(cut >= 0 ? src.slice(cut + 4) : src));
|
|
3369
|
+
for (const c of body.querySelectorAll('td code')) {
|
|
3370
|
+
const t = c.textContent.trim();
|
|
3371
|
+
if (!/^\/?keepfold\b/.test(t)) continue;
|
|
3372
|
+
const wrap = el('span', 'copycell');
|
|
3373
|
+
c.replaceWith(wrap);
|
|
3374
|
+
wrap.append(c, copyBtn(t));
|
|
3375
|
+
}
|
|
3376
|
+
host.append(body);
|
|
3377
|
+
}
|
|
3378
|
+
host.append(el('h2', null, 'How saving works'));
|
|
3379
|
+
const ul = el('ul', 'prose');
|
|
3380
|
+
for (const t of ['The first message of a chat primes it with what Keepfold knows about the topic.',
|
|
3381
|
+
'Durable things (facts, sources, decisions, insights, results) are saved as they come up, and each save is announced.',
|
|
3382
|
+
'Lines about you wait for your yes before a chat relies on them.',
|
|
3383
|
+
'/keepfold save is the safety net for very long chats.',
|
|
3384
|
+
"Every chat's changes can be undone: keepfold undo <session>."]) ul.append(el('li', null, t));
|
|
3385
|
+
host.append(ul);
|
|
3386
|
+
host.append(el('h2', null, 'The names'));
|
|
3387
|
+
if (h.glossary_md) {
|
|
3388
|
+
const g = el('div', 'md');
|
|
3389
|
+
g.append(md(h.glossary_md));
|
|
3390
|
+
host.append(g);
|
|
3391
|
+
} else host.append(el('p', 'empty', 'Run /keepfold help in Claude for every command.'));
|
|
3392
|
+
host.append(el('h2', null, 'This dashboard'));
|
|
3393
|
+
const SAY = { home: 'what is due today, what is coming, open loops and what changed this week',
|
|
3394
|
+
brain: 'every page as a point in a 3D brain, one lobe per topic; also the 2D concept map and its list',
|
|
3395
|
+
library: 'every page as a sortable timetable, with presets, lobes and tags',
|
|
3396
|
+
you: 'what Keepfold knows about you, lines waiting for your yes, and your me/ pages',
|
|
3397
|
+
timeline: 'pages by the day they were written, month by month',
|
|
3398
|
+
ideas: 'open loops, decisions to revisit, ideas coming back and recent notes',
|
|
3399
|
+
study: 'your study plans, learning states, the plan, readiness for tests, mistakes and weekly answers',
|
|
3400
|
+
help: 'this page' };
|
|
3401
|
+
const tbl = el('table'), tb = el('tbody');
|
|
3402
|
+
SECTIONS.forEach((s, i) => {
|
|
3403
|
+
const tr = el('tr'), th = el('th', null, `${i + 1} · ${TITLES[s]}`);
|
|
3404
|
+
th.scope = 'row';
|
|
3405
|
+
tr.append(th, el('td', null, SAY[s]));
|
|
3406
|
+
tb.append(tr);
|
|
3407
|
+
});
|
|
3408
|
+
tbl.append(tb);
|
|
3409
|
+
const tb2 = board('Sections');
|
|
3410
|
+
tb2.body.append(tbl);
|
|
3411
|
+
host.append(tb2.root);
|
|
3412
|
+
host.append(el('h3', null, 'Keyboard'));
|
|
3413
|
+
const keys = el('ul', 'prose');
|
|
3414
|
+
for (const t of ['Ctrl+K: search pages, sections and commands', `1 to ${SECTIONS.length}: switch sections`,
|
|
3415
|
+
'Arrow keys in the section tabs: move between sections', 'Esc: close the reader or the search',
|
|
3416
|
+
'In the brain: drag to turn, scroll to zoom, arrows turn (in Today, Left and Right step through today\'s pages), + and − zoom, 0 resets the view',
|
|
3417
|
+
'In the brain: Esc goes back one level (page, region, overview); double-click empty space for the overview; double-click a page or region name to fly to it',
|
|
3418
|
+
'With a page selected: [ and ] step to the previous or next connection, Backspace returns to the previous page, F frames the selection',
|
|
3419
|
+
'With the brain focused: A, M and G switch Activity, Mastery and Growth; S turns spin on or off; L opens Look',
|
|
3420
|
+
'In Look: presets, then switches and sliders for each part of the brain; Esc closes it',
|
|
3421
|
+
'In the brain outline: arrows move and open, Enter selects']) keys.append(el('li', null, t));
|
|
3422
|
+
host.append(keys);
|
|
3423
|
+
}
|
|
3424
|
+
|
|
3425
|
+
/* ---- command palette (Ctrl+K) ---- */
|
|
3426
|
+
const pal = $('palette'), pq = $('pq'), pres = $('presults');
|
|
3427
|
+
let palItems = [], palSel = 0, palFrom = null, CMDS = null;
|
|
3428
|
+
function openPalette() {
|
|
3429
|
+
if (pal.hidden) palFrom = document.activeElement;
|
|
3430
|
+
pal.hidden = false;
|
|
3431
|
+
hideTip();
|
|
3432
|
+
pq.focus();
|
|
3433
|
+
pq.select();
|
|
3434
|
+
renderPalette();
|
|
3435
|
+
}
|
|
3436
|
+
function closePalette() {
|
|
3437
|
+
pal.hidden = true;
|
|
3438
|
+
if (palFrom && palFrom.isConnected) palFrom.focus({ preventScroll: true });
|
|
3439
|
+
}
|
|
3440
|
+
function palRow(title, sub, right, run) {
|
|
3441
|
+
const b = button('hit', null, () => { closePalette(); run(); });
|
|
3442
|
+
b.setAttribute('role', 'option');
|
|
3443
|
+
b.tabIndex = -1;
|
|
3444
|
+
const t = el('span', 'ttl', title);
|
|
3445
|
+
b.append(t, right || el('span'));
|
|
3446
|
+
if (sub) b.append(el('span', 'sub', sub));
|
|
3447
|
+
palItems.push(b);
|
|
3448
|
+
return b;
|
|
3449
|
+
}
|
|
3450
|
+
function renderPalette() {
|
|
3451
|
+
const q = pq.value.trim().toLowerCase();
|
|
3452
|
+
palItems = [];
|
|
3453
|
+
pres.replaceChildren();
|
|
3454
|
+
const secs = SECTIONS.filter((s) => !q || TITLES[s].toLowerCase().includes(q) || s.includes(q));
|
|
3455
|
+
if (secs.length) {
|
|
3456
|
+
pres.append(el('h4', null, 'Sections'));
|
|
3457
|
+
for (const s of secs) pres.append(palRow(TITLES[s], null, el('span', 'kind', 'key ' + (SECTIONS.indexOf(s) + 1)), () => show(s)));
|
|
3458
|
+
}
|
|
3459
|
+
if (q) {
|
|
3460
|
+
if (!CMDS) CMDS = commandRows();
|
|
3461
|
+
const cmds = CMDS.filter((c) => c.cmd.toLowerCase().includes(q) || c.desc.toLowerCase().includes(q)).slice(0, 6);
|
|
3462
|
+
if (cmds.length) {
|
|
3463
|
+
pres.append(el('h4', null, 'Commands (Enter copies)'));
|
|
3464
|
+
for (const c of cmds) pres.append(palRow(c.cmd, c.desc, el('span', 'kind', 'copy'), () => copyText(c.cmd)));
|
|
3465
|
+
}
|
|
3466
|
+
const hits = search(q).slice(0, 40);
|
|
3467
|
+
if (hits.length) {
|
|
3468
|
+
pres.append(el('h4', null, 'Pages'));
|
|
3469
|
+
for (const x of hits) {
|
|
3470
|
+
const p = x.h.p, right = el('span', 'line1');
|
|
3471
|
+
right.append(el('span', 'kind', kindWord(p.kind)), lobeChip(p.cluster));
|
|
3472
|
+
pres.append(palRow(p.title, p.summary || snippet(x), right, () => openReader(p.id)));
|
|
3473
|
+
}
|
|
3474
|
+
}
|
|
3475
|
+
if (!cmds.length && !hits.length && !secs.length) pres.append(el('p', 'empty', 'Nothing matches. Try fewer words.'));
|
|
3476
|
+
}
|
|
3477
|
+
palSel = 0;
|
|
3478
|
+
markPal();
|
|
3479
|
+
}
|
|
3480
|
+
function markPal() {
|
|
3481
|
+
palItems.forEach((b, i) => b.setAttribute('aria-selected', String(i === palSel)));
|
|
3482
|
+
if (palItems[palSel]) palItems[palSel].scrollIntoView({ block: 'nearest' });
|
|
3483
|
+
}
|
|
3484
|
+
let palTimer = 0;
|
|
3485
|
+
pq.addEventListener('input', () => { clearTimeout(palTimer); palTimer = setTimeout(renderPalette, 120); });
|
|
3486
|
+
pq.addEventListener('keydown', (e) => {
|
|
3487
|
+
if (e.key === 'ArrowDown') { e.preventDefault(); palSel = Math.min(palSel + 1, palItems.length - 1); markPal(); }
|
|
3488
|
+
else if (e.key === 'ArrowUp') { e.preventDefault(); palSel = Math.max(palSel - 1, 0); markPal(); }
|
|
3489
|
+
else if (e.key === 'Enter') {
|
|
3490
|
+
e.preventDefault();
|
|
3491
|
+
clearTimeout(palTimer);
|
|
3492
|
+
if (pq.value.trim() && !palItems.length) renderPalette();
|
|
3493
|
+
if (palItems[palSel]) palItems[palSel].click();
|
|
3494
|
+
}
|
|
3495
|
+
});
|
|
3496
|
+
pal.addEventListener('mousedown', (e) => { if (e.target === pal) closePalette(); });
|
|
3497
|
+
// a modal dialog: Tab stays on the search box (results move with the arrows)
|
|
3498
|
+
pal.addEventListener('keydown', (e) => { if (e.key === 'Tab') { e.preventDefault(); pq.focus(); } });
|
|
3499
|
+
|
|
3500
|
+
/* ---- 2D map (the old Map tab, behaviour unchanged) ---- */
|
|
3501
|
+
const G = (() => {
|
|
3502
|
+
const F = { states: new Set(STATES), domain: '', weak: false, list: false, q: '',
|
|
3503
|
+
kinds: new Set(['concept', 'project']), local: false };
|
|
3504
|
+
const RADIUS = { area: 4.5, you: 9, project: 5, resource: 3.5, note: 2.5, decision: 3.5 };
|
|
3505
|
+
const DIST = { domain: 55, area: 28, requires: 70, wiki: 45 };
|
|
3506
|
+
const PRETICKS = 80;
|
|
3507
|
+
const CHARGE = { you: -300, domain: -300, area: -70, concept: -24, project: -40, resource: -24,
|
|
3508
|
+
note: -24, decision: -24 };
|
|
3509
|
+
let nodes, links, byId, adj, R, sim, hover = null, k = 1, ready = false, touched = false, built = false;
|
|
3510
|
+
let tf = d3.zoomIdentity, ticks = 0, near = null;
|
|
3511
|
+
let sortKey = 'title', sortDir = 1, current = null;
|
|
3512
|
+
|
|
3513
|
+
const KINDS = [['concept', '●', 'Concepts'], ['project', '▢', 'Projects'],
|
|
3514
|
+
['resource', '◆', 'Resources'], ['note', '•', 'Notes'], ['decision', '▲', 'Decisions']];
|
|
3515
|
+
const kchips = $('kinds'), chips = $('chips'), sel = $('domain');
|
|
3516
|
+
// the Domain list from the current data; a chosen domain that is gone goes back to All domains
|
|
3517
|
+
function fillDomains() {
|
|
3518
|
+
const doms = D.graph.nodes.filter((x) => x.kind === 'domain');
|
|
3519
|
+
if (F.domain && !doms.some((n) => n.id === F.domain)) F.domain = '';
|
|
3520
|
+
sel.replaceChildren(sel.options[0], ...doms.map((n) => { const o = el('option', null, n.title); o.value = n.id; return o; }));
|
|
3521
|
+
sel.value = F.domain;
|
|
3522
|
+
sel.disabled = sel.options.length < 2; // no domains yet: nothing to choose
|
|
3523
|
+
}
|
|
3524
|
+
function build() { // the controls, once
|
|
3525
|
+
if (built) return;
|
|
3526
|
+
built = true;
|
|
3527
|
+
for (const [kd, g, word] of KINDS) {
|
|
3528
|
+
const b = button(null, null, () => {
|
|
3529
|
+
if (F.kinds.has(kd)) F.kinds.delete(kd); else F.kinds.add(kd);
|
|
3530
|
+
syncChips();
|
|
3531
|
+
apply();
|
|
3532
|
+
});
|
|
3533
|
+
b.dataset.kind = kd;
|
|
3534
|
+
b.append(el('span', 'glyph k-' + kd, g), ' ' + word);
|
|
3535
|
+
kchips.append(b);
|
|
3536
|
+
}
|
|
3537
|
+
for (const s of STATES) {
|
|
3538
|
+
const b = button(null, null, () => {
|
|
3539
|
+
if (F.states.has(s)) F.states.delete(s); else F.states.add(s);
|
|
3540
|
+
syncChips();
|
|
3541
|
+
apply();
|
|
3542
|
+
});
|
|
3543
|
+
b.dataset.state = s;
|
|
3544
|
+
b.append(glyph(s), ' ' + LABEL[s]);
|
|
3545
|
+
chips.append(b);
|
|
3546
|
+
}
|
|
3547
|
+
syncChips();
|
|
3548
|
+
fillDomains();
|
|
3549
|
+
sel.addEventListener('change', () => {
|
|
3550
|
+
F.domain = sel.value;
|
|
3551
|
+
apply();
|
|
3552
|
+
if (ready && F.domain && !F.list) R.fit(nodes.filter((n) => n.domain === F.domain), 600);
|
|
3553
|
+
});
|
|
3554
|
+
$('weak').addEventListener('change', (e) => { F.weak = e.target.checked; apply(); });
|
|
3555
|
+
$('local').addEventListener('change', (e) => { F.local = e.target.checked; relocal(); });
|
|
3556
|
+
$('files').addEventListener('change', (e) => {
|
|
3557
|
+
$('tree').hidden = !e.target.checked;
|
|
3558
|
+
if (e.target.checked && !$('tree').childElementCount) renderTree();
|
|
3559
|
+
});
|
|
3560
|
+
$('q').addEventListener('input', (e) => { F.q = e.target.value.trim().toLowerCase(); apply(); });
|
|
3561
|
+
}
|
|
3562
|
+
function setList(on) {
|
|
3563
|
+
F.list = on;
|
|
3564
|
+
$('graph').hidden = on;
|
|
3565
|
+
$('table').hidden = !on;
|
|
3566
|
+
apply();
|
|
3567
|
+
}
|
|
3568
|
+
// Obsidian's local graph: the open note plus 2 hops, never through the You hub.
|
|
3569
|
+
function relocal() {
|
|
3570
|
+
near = null;
|
|
3571
|
+
if (F.local && current && byId && byId.has(current)) {
|
|
3572
|
+
near = new Set([current]);
|
|
3573
|
+
let edge = [current];
|
|
3574
|
+
for (let d = 0; d < 2; d++) {
|
|
3575
|
+
const next = [];
|
|
3576
|
+
for (const x of edge) {
|
|
3577
|
+
for (const y of adj.get(x)) {
|
|
3578
|
+
if (!near.has(y) && byId.get(y).kind !== 'you') { near.add(y); next.push(y); }
|
|
3579
|
+
}
|
|
3580
|
+
}
|
|
3581
|
+
edge = next;
|
|
3582
|
+
}
|
|
3583
|
+
}
|
|
3584
|
+
apply();
|
|
3585
|
+
if (ready && !F.list) R.fit(nodes.filter((n) => !n._hide), 500);
|
|
3586
|
+
}
|
|
3587
|
+
function syncChips() {
|
|
3588
|
+
for (const b of chips.children) b.setAttribute('aria-pressed', String(F.states.has(b.dataset.state)));
|
|
3589
|
+
for (const b of kchips.children) b.setAttribute('aria-pressed', String(F.kinds.has(b.dataset.kind)));
|
|
3590
|
+
}
|
|
3591
|
+
|
|
3592
|
+
const weakNode = (n) => n.state === 'learning' || n.state === 'needs_refresh' || n.open_mistakes > 0;
|
|
3593
|
+
function visible(n) {
|
|
3594
|
+
if (near) { if (!near.has(n.id)) return false; if (n.id === current) return true; }
|
|
3595
|
+
if (n.kind === 'you') return true;
|
|
3596
|
+
if (F.domain && n.domain !== F.domain) return false;
|
|
3597
|
+
if (WIKI.has(n.kind)) return F.kinds.has(n.kind);
|
|
3598
|
+
if (n.kind !== 'concept') return true;
|
|
3599
|
+
return F.kinds.has('concept') && F.states.has(n.state) && (!F.weak || weakNode(n));
|
|
3600
|
+
}
|
|
3601
|
+
const matches = (n) => !!F.q && n.title.toLowerCase().includes(F.q);
|
|
3602
|
+
|
|
3603
|
+
function radius(n) {
|
|
3604
|
+
if (n.kind === 'concept') return Math.min(6, 3.5 + Math.max(0, n.degree - 1) * 0.5);
|
|
3605
|
+
if (n.kind === 'domain') return 7 + Math.sqrt(n.degree) * 1.6;
|
|
3606
|
+
return RADIUS[n.kind];
|
|
3607
|
+
}
|
|
3608
|
+
|
|
3609
|
+
function init() {
|
|
3610
|
+
build();
|
|
3611
|
+
if (ready) return;
|
|
3612
|
+
ready = true;
|
|
3613
|
+
nodes = D.graph.nodes.map((n) => Object.assign({}, n));
|
|
3614
|
+
const have = new Set(nodes.map((n) => n.id));
|
|
3615
|
+
const wiki = D.pages.filter((p) => WIKI.has(p.kind) && !have.has(p.id));
|
|
3616
|
+
for (const p of wiki) {
|
|
3617
|
+
nodes.push({ id: p.id, kind: p.kind, title: p.title, state: null, domain: null, area: null,
|
|
3618
|
+
degree: 0, open_mistakes: 0, next_due: null });
|
|
3619
|
+
}
|
|
3620
|
+
byId = new Map(nodes.map((n) => [n.id, n]));
|
|
3621
|
+
links = D.graph.links.filter((l) => byId.has(l.s) && byId.has(l.t))
|
|
3622
|
+
.map((l) => ({ source: byId.get(l.s), target: byId.get(l.t), type: l.type }));
|
|
3623
|
+
const pairs = new Set();
|
|
3624
|
+
for (const p of wiki) {
|
|
3625
|
+
for (const t of p.links) {
|
|
3626
|
+
const key = [p.id, t].sort().join('\n');
|
|
3627
|
+
if (!byId.has(t) || pairs.has(key)) continue;
|
|
3628
|
+
pairs.add(key);
|
|
3629
|
+
links.push({ source: byId.get(p.id), target: byId.get(t), type: 'wiki' });
|
|
3630
|
+
byId.get(p.id).degree++;
|
|
3631
|
+
if (WIKI.has(byId.get(t).kind)) byId.get(t).degree++;
|
|
3632
|
+
}
|
|
3633
|
+
}
|
|
3634
|
+
adj = new Map(nodes.map((n) => [n.id, new Set()]));
|
|
3635
|
+
for (const l of links) { adj.get(l.source.id).add(l.target.id); adj.get(l.target.id).add(l.source.id); }
|
|
3636
|
+
// Domains sit on a ring around You; areas and concepts settle outside their hub.
|
|
3637
|
+
const doms = nodes.filter((n) => n.kind === 'domain');
|
|
3638
|
+
const ring = Math.max(140, 11 * Math.sqrt(nodes.length));
|
|
3639
|
+
const RING = { you: 0, domain: ring, area: ring * 1.6, concept: ring * 2.1 };
|
|
3640
|
+
const PULL = { you: 0, domain: 0.5, area: 0.12, concept: 0.03 };
|
|
3641
|
+
for (const kd of WIKI) { RING[kd] = ring * 2.4; PULL[kd] = 0.02; }
|
|
3642
|
+
const angle = new Map(doms.map((n, i) => [n.id, 2 * Math.PI * i / doms.length]));
|
|
3643
|
+
for (const n of nodes) {
|
|
3644
|
+
n.r = radius(n);
|
|
3645
|
+
const a = WIKI.has(n.kind) ? Math.random() * 2 * Math.PI
|
|
3646
|
+
: (angle.get(n.domain) || 0) + (n.kind === 'domain' ? 0 : (Math.random() - 0.5) * 0.4);
|
|
3647
|
+
n.x = Math.cos(a) * RING[n.kind]; n.y = Math.sin(a) * RING[n.kind];
|
|
3648
|
+
if (n.kind === 'you') { n.fx = 0; n.fy = 0; }
|
|
3649
|
+
}
|
|
3650
|
+
sim = d3.forceSimulation(nodes).alphaMin(0.02)
|
|
3651
|
+
.force('link', d3.forceLink(links)
|
|
3652
|
+
.distance((l) => (l.type === 'hier' ? DIST[l.source.kind] : l.type === 'you' ? ring : DIST[l.type]))
|
|
3653
|
+
.strength((l) => (l.type === 'requires' || l.type === 'area' ? 0.02 : l.type === 'you' ? 0.1
|
|
3654
|
+
: 1 / Math.min(l.source.degree || 1, l.target.degree || 1))))
|
|
3655
|
+
.force('charge', d3.forceManyBody().strength((n) => CHARGE[n.kind]).distanceMax(500))
|
|
3656
|
+
.force('collide', d3.forceCollide((n) => n.r + 2))
|
|
3657
|
+
.force('radial', d3.forceRadial((n) => RING[n.kind], 0, 0).strength((n) => PULL[n.kind]));
|
|
3658
|
+
apply(); // drop the hidden kinds from the simulation before it settles
|
|
3659
|
+
const t0 = performance.now();
|
|
3660
|
+
sim.stop().tick(PRETICKS); // most of the settling happens before the first paint
|
|
3661
|
+
R = nodes.length > 1500 ? canvasRenderer() : svgRenderer();
|
|
3662
|
+
if (nodes.every((n) => n.kind === 'you')) {
|
|
3663
|
+
$('graph').prepend(el('p', 'empty', 'No topics or pages on the map yet. Run /keepfold learn in Claude to start one.'));
|
|
3664
|
+
}
|
|
3665
|
+
R.tick();
|
|
3666
|
+
sim.restart();
|
|
3667
|
+
let first = true;
|
|
3668
|
+
sim.on('tick', () => { R.tick(); if (++ticks % 5 === 0) relabel(); }).on('end', () => {
|
|
3669
|
+
relabel();
|
|
3670
|
+
if (!first) return;
|
|
3671
|
+
first = false;
|
|
3672
|
+
const ms = Math.round(performance.now() - t0);
|
|
3673
|
+
document.body.dataset.settleMs = String(ms);
|
|
3674
|
+
console.info(`keepfold: graph settled in ${ms} ms (${nodes.length} nodes)`);
|
|
3675
|
+
if (!touched) R.fit(nodes.filter((n) => !n._hide), 500);
|
|
3676
|
+
});
|
|
3677
|
+
apply();
|
|
3678
|
+
if (current) relocal();
|
|
3679
|
+
}
|
|
3680
|
+
|
|
3681
|
+
function apply() {
|
|
3682
|
+
if (!ready) return;
|
|
3683
|
+
const nb = hover ? adj.get(hover.id) : null;
|
|
3684
|
+
let changed = false;
|
|
3685
|
+
for (const n of nodes) {
|
|
3686
|
+
const hide = !visible(n);
|
|
3687
|
+
changed = changed || hide !== !!n._hide;
|
|
3688
|
+
n._hide = hide;
|
|
3689
|
+
n._dim = hover ? !(n === hover || nb.has(n.id)) : (F.q ? !matches(n) : false);
|
|
3690
|
+
n._force = matches(n) || (hover != null && (n === hover || nb.has(n.id)));
|
|
3691
|
+
n._label = !(n.kind === 'concept' || WIKI.has(n.kind)) || k >= 1.2 || n._force;
|
|
3692
|
+
}
|
|
3693
|
+
for (const l of links) {
|
|
3694
|
+
l._hide = l.source._hide || l.target._hide;
|
|
3695
|
+
l._dim = hover ? !(l.source === hover || l.target === hover)
|
|
3696
|
+
: (F.q ? !(matches(l.source) && matches(l.target)) : false);
|
|
3697
|
+
}
|
|
3698
|
+
if (changed) { // hidden nodes leave the force simulation (and rejoin when shown again)
|
|
3699
|
+
sim.nodes(nodes.filter((n) => !n._hide));
|
|
3700
|
+
sim.force('link').links(links.filter((l) => !l._hide));
|
|
3701
|
+
if (R) sim.alpha(Math.max(sim.alpha(), 0.3)).restart();
|
|
3702
|
+
}
|
|
3703
|
+
relabel();
|
|
3704
|
+
if (F.list) renderTable();
|
|
3705
|
+
}
|
|
3706
|
+
|
|
3707
|
+
// A label that would overlap a higher-priority one is skipped (the hovered node's never):
|
|
3708
|
+
// hovered and matched labels first, then domains, areas and concepts, each by degree.
|
|
3709
|
+
const mctx = document.createElement('canvas').getContext('2d');
|
|
3710
|
+
const PRI = { you: 0, domain: 1, area: 2, concept: 3, project: 3, resource: 3, note: 3, decision: 3 };
|
|
3711
|
+
const fontSize = (n) => (n.kind === 'domain' ? 14.3 : 11);
|
|
3712
|
+
const MAX_LABELS = 300; // on screen, by priority: bounds the overlap scan on big maps
|
|
3713
|
+
function labelWidth(n) {
|
|
3714
|
+
if (n._w == null) {
|
|
3715
|
+
mctx.font = `${n.kind === 'domain' ? 600 : 400} ${fontSize(n)}px system-ui, sans-serif`;
|
|
3716
|
+
n._w = mctx.measureText(n.title + (n.open_mistakes ? ' ⚑' : '')).width;
|
|
3717
|
+
}
|
|
3718
|
+
return n._w;
|
|
3719
|
+
}
|
|
3720
|
+
function relabel() {
|
|
3721
|
+
if (!R) return; // the renderer's first zoom event fires while it is being built
|
|
3722
|
+
const cand = nodes.filter((n) => n._label && !n._hide);
|
|
3723
|
+
cand.sort((a, b) => (b._force - a._force) || (PRI[a.kind] - PRI[b.kind]) || (b.degree - a.degree));
|
|
3724
|
+
const placed = [], gh = $('graph'), vw = gh.clientWidth || 800, vh = gh.clientHeight || 600;
|
|
3725
|
+
for (const n of cand) {
|
|
3726
|
+
const x0 = tf.applyX(n.x + n.r + 3), y = tf.applyY(n.y + 3.5), fs = fontSize(n);
|
|
3727
|
+
const box = [x0 - 2, y - fs * 0.85, x0 + labelWidth(n) + 2, y + fs * 0.3];
|
|
3728
|
+
const off = box[2] < 0 || box[0] > vw || box[3] < 0 || box[1] > vh; // off screen: no label
|
|
3729
|
+
n._shown = n === hover || (!off && placed.length < MAX_LABELS && !placed.some((b) => box[0] < b[2] && b[0] < box[2] && box[1] < b[3] && b[1] < box[3]));
|
|
3730
|
+
if (n._shown) placed.push(box);
|
|
3731
|
+
}
|
|
3732
|
+
for (const n of nodes) if (!n._label || n._hide) n._shown = false;
|
|
3733
|
+
R.update();
|
|
3734
|
+
}
|
|
3735
|
+
|
|
3736
|
+
function tipFor(e, n) {
|
|
3737
|
+
const parts = [el('b', null, n.title)];
|
|
3738
|
+
if (n.kind === 'concept') {
|
|
3739
|
+
parts.push(el('br'), (GLYPH[n.state] || '') + ' ' + LABEL[n.state]);
|
|
3740
|
+
if (n.open_mistakes) parts.push(' · ⚑ ' + n.open_mistakes);
|
|
3741
|
+
} else if (n.kind === 'domain' || n.kind === 'area') {
|
|
3742
|
+
const c = groupCounts(n), total = STATES.reduce((a, s) => a + c[s], 0);
|
|
3743
|
+
parts.push(el('br'), total ? `${Math.round(100 * c.solid / total)}% solid (${c.solid} of ${total})`
|
|
3744
|
+
: 'no topics yet');
|
|
3745
|
+
} else if (n.kind !== 'you') parts.push(el('br'), kindWord(n.kind));
|
|
3746
|
+
showTip(e, parts);
|
|
3747
|
+
}
|
|
3748
|
+
function hoverOn(e, n) { hover = n; apply(); tipFor(e, n); }
|
|
3749
|
+
function hoverOff() { hover = null; apply(); hideTip(); }
|
|
3750
|
+
|
|
3751
|
+
function click(n) {
|
|
3752
|
+
if (n.kind === 'domain' || n.kind === 'area') {
|
|
3753
|
+
const key = n.kind === 'domain' ? 'domain' : 'area';
|
|
3754
|
+
R.fit(nodes.filter((x) => x[key] === n.id && !x._hide), 600);
|
|
3755
|
+
}
|
|
3756
|
+
if (n.kind !== 'you') openReader(n.id);
|
|
3757
|
+
}
|
|
3758
|
+
// Bring a page's node into view (showing it if the filters hid it).
|
|
3759
|
+
function focus(id) {
|
|
3760
|
+
if (!ready) return;
|
|
3761
|
+
const n = byId.get(id);
|
|
3762
|
+
if (!n) return;
|
|
3763
|
+
if (n._hide) {
|
|
3764
|
+
F.states = new Set(STATES); F.weak = false; F.domain = ''; F.kinds.add(n.kind);
|
|
3765
|
+
syncControls();
|
|
3766
|
+
apply();
|
|
3767
|
+
}
|
|
3768
|
+
if (!F.list) R.center(n);
|
|
3769
|
+
}
|
|
3770
|
+
function syncControls() {
|
|
3771
|
+
syncChips();
|
|
3772
|
+
$('weak').checked = F.weak;
|
|
3773
|
+
sel.value = F.domain;
|
|
3774
|
+
}
|
|
3775
|
+
function setCurrent(id) {
|
|
3776
|
+
current = id;
|
|
3777
|
+
if (!ready) return;
|
|
3778
|
+
if (F.local) relocal();
|
|
3779
|
+
if (id && !$('b2d').hidden && !$('view-brain').hidden) focus(id);
|
|
3780
|
+
}
|
|
3781
|
+
|
|
3782
|
+
/* file tree: domains › areas › concepts from the catalog, every other folder flat */
|
|
3783
|
+
function renderTree() {
|
|
3784
|
+
const tree = $('tree');
|
|
3785
|
+
const kids = new Map();
|
|
3786
|
+
for (const l of D.graph.links) {
|
|
3787
|
+
if (l.type !== 'hier' || !byId.has(l.t)) continue;
|
|
3788
|
+
if (!kids.has(l.s)) kids.set(l.s, []);
|
|
3789
|
+
kids.get(l.s).push(byId.get(l.t));
|
|
3790
|
+
}
|
|
3791
|
+
const byTitle = (a, b) => a.title.localeCompare(b.title);
|
|
3792
|
+
const leaf = (id, title) => button('leaf', title, () => openReader(id));
|
|
3793
|
+
const folder = (label, children, n) => {
|
|
3794
|
+
const d = el('details'), s = el('summary', null, label + ' ');
|
|
3795
|
+
s.append(el('span', 'muted', String(children.length)));
|
|
3796
|
+
d.append(s);
|
|
3797
|
+
if (n && PAGES.has(n.id)) d.append(leaf(n.id, 'Open ' + n.title));
|
|
3798
|
+
d.append(...children);
|
|
3799
|
+
return d;
|
|
3800
|
+
};
|
|
3801
|
+
const branch = (n) => (n.kind === 'concept' ? leaf(n.id, n.title)
|
|
3802
|
+
: folder(n.title, (kids.get(n.id) || []).sort(byTitle).map(branch), n));
|
|
3803
|
+
tree.append(folder('Domains', nodes.filter((n) => n.kind === 'domain').sort(byTitle).map(branch)));
|
|
3804
|
+
const folders = new Map();
|
|
3805
|
+
for (const p of D.pages) {
|
|
3806
|
+
if (p.kind === 'concept' || p.kind === 'domain' || p.kind === 'area') continue;
|
|
3807
|
+
const f = p.path.split('/')[0];
|
|
3808
|
+
if (!folders.has(f)) folders.set(f, []);
|
|
3809
|
+
folders.get(f).push(p);
|
|
3810
|
+
}
|
|
3811
|
+
for (const [f, ps] of [...folders].sort((a, b) => a[0].localeCompare(b[0]))) {
|
|
3812
|
+
tree.append(folder(f, ps.sort(byTitle).map((p) => leaf(p.id, p.title))));
|
|
3813
|
+
}
|
|
3814
|
+
}
|
|
3815
|
+
|
|
3816
|
+
/* list view */
|
|
3817
|
+
const COLS = [['title', 'TITLE'], ['domain', 'DOMAIN'], ['area', 'AREA'], ['state', 'STATE'],
|
|
3818
|
+
['next', 'NEXT REFRESH']];
|
|
3819
|
+
function cell(n, key) {
|
|
3820
|
+
if (key === 'domain' || key === 'area') { const p = byId.get(n[key]); return p ? p.title : ''; }
|
|
3821
|
+
if (key === 'state') return STATES.indexOf(n.state);
|
|
3822
|
+
if (key === 'next') return n.next_due || '9999';
|
|
3823
|
+
return n.title.toLowerCase();
|
|
3824
|
+
}
|
|
3825
|
+
function renderTable() {
|
|
3826
|
+
const rows = nodes.filter((n) => n.kind === 'concept' && !n._hide && (!F.q || matches(n)));
|
|
3827
|
+
rows.sort((a, b) => { const x = cell(a, sortKey), y = cell(b, sortKey); return (x < y ? -1 : x > y ? 1 : 0) * sortDir; });
|
|
3828
|
+
const table = el('table');
|
|
3829
|
+
table.append(el('caption', null, `${plural(rows.length, 'topic')}`));
|
|
3830
|
+
const tr = el('tr');
|
|
3831
|
+
for (const [key, name] of COLS) {
|
|
3832
|
+
const th = el('th');
|
|
3833
|
+
th.scope = 'col';
|
|
3834
|
+
if (key === sortKey) th.setAttribute('aria-sort', sortDir > 0 ? 'ascending' : 'descending');
|
|
3835
|
+
th.append(button(null, name + (key === sortKey ? (sortDir > 0 ? ' ▲' : ' ▼') : ''), () => {
|
|
3836
|
+
sortDir = sortKey === key ? -sortDir : 1;
|
|
3837
|
+
sortKey = key;
|
|
3838
|
+
renderTable();
|
|
3839
|
+
}));
|
|
3840
|
+
tr.append(th);
|
|
3841
|
+
}
|
|
3842
|
+
const thead = el('thead');
|
|
3843
|
+
thead.append(tr);
|
|
3844
|
+
const tbody = el('tbody');
|
|
3845
|
+
for (const n of rows) {
|
|
3846
|
+
const r = el('tr');
|
|
3847
|
+
const t = el('td');
|
|
3848
|
+
t.append(button(null, n.title, () => openReader(n.id)));
|
|
3849
|
+
if (n.open_mistakes) t.append(el('span', 'flag', ' ⚑'));
|
|
3850
|
+
const s = el('td');
|
|
3851
|
+
s.append(stateWord(n.state));
|
|
3852
|
+
r.append(t, el('td', null, cell(n, 'domain')), el('td', null, cell(n, 'area')), s,
|
|
3853
|
+
el('td', 'muted', n.next_due ? nextText(n.next_due) : '—'));
|
|
3854
|
+
tbody.append(r);
|
|
3855
|
+
}
|
|
3856
|
+
table.append(thead, tbody);
|
|
3857
|
+
$('table').replaceChildren(table);
|
|
3858
|
+
if (!rows.length) {
|
|
3859
|
+
$('table').append(el('p', 'empty', D.graph.nodes.some((n) => n.kind === 'concept')
|
|
3860
|
+
? 'No topics match. Turn a state or kind back on, or clear the search.'
|
|
3861
|
+
: 'No topics yet. Run /keepfold learn in Claude to start one.'));
|
|
3862
|
+
}
|
|
3863
|
+
}
|
|
3864
|
+
|
|
3865
|
+
function onZoom(t) {
|
|
3866
|
+
const crossed = (k >= 1.2) !== (t.k >= 1.2);
|
|
3867
|
+
k = t.k;
|
|
3868
|
+
tf = t;
|
|
3869
|
+
if (crossed) apply(); else relabel();
|
|
3870
|
+
}
|
|
3871
|
+
|
|
3872
|
+
function fitTransform(set, w, h) {
|
|
3873
|
+
if (!set.length) return d3.zoomIdentity.translate(w / 2, h / 2);
|
|
3874
|
+
const xs = set.map((n) => n.x), ys = set.map((n) => n.y);
|
|
3875
|
+
const x0 = Math.min(...xs) - 30, x1 = Math.max(...xs) + 30;
|
|
3876
|
+
const y0 = Math.min(...ys) - 30, y1 = Math.max(...ys) + 30;
|
|
3877
|
+
const s = Math.min(4, 0.9 * Math.min(w / (x1 - x0), h / (y1 - y0)));
|
|
3878
|
+
return d3.zoomIdentity.translate(w / 2, h / 2).scale(s).translate(-(x0 + x1) / 2, -(y0 + y1) / 2);
|
|
3879
|
+
}
|
|
3880
|
+
|
|
3881
|
+
function dragger(subject) {
|
|
3882
|
+
const d = d3.drag()
|
|
3883
|
+
.on('start', (e) => {
|
|
3884
|
+
touched = true;
|
|
3885
|
+
if (!e.active) sim.alphaTarget(0.3).restart();
|
|
3886
|
+
e.subject.fx = e.subject.x; e.subject.fy = e.subject.y;
|
|
3887
|
+
})
|
|
3888
|
+
.on('drag', (e) => { e.subject.fx = e.x; e.subject.fy = e.y; })
|
|
3889
|
+
.on('end', (e) => {
|
|
3890
|
+
if (!e.active) sim.alphaTarget(0);
|
|
3891
|
+
e.subject.fx = null; e.subject.fy = null;
|
|
3892
|
+
});
|
|
3893
|
+
return subject ? d.subject(subject) : d;
|
|
3894
|
+
}
|
|
3895
|
+
|
|
3896
|
+
function svgRenderer() {
|
|
3897
|
+
const host = $('graph');
|
|
3898
|
+
const svg = d3.select(host).append('svg')
|
|
3899
|
+
.attr('aria-label', 'Knowledge map. List view shows the same topics as a table.');
|
|
3900
|
+
svg.append('defs').append('marker').attr('id', 'arrow').attr('viewBox', '0 0 8 8')
|
|
3901
|
+
.attr('refX', 7).attr('refY', 4).attr('markerWidth', 5).attr('markerHeight', 5)
|
|
3902
|
+
.attr('orient', 'auto').append('path').attr('d', 'M0,0L8,4L0,8z').attr('class', 'arrowhead');
|
|
3903
|
+
const root = svg.append('g');
|
|
3904
|
+
const L = root.append('g').selectAll('line').data(links).join('line')
|
|
3905
|
+
.attr('class', (l) => 'link l-' + l.type)
|
|
3906
|
+
.attr('marker-end', (l) => (l.type === 'requires' ? 'url(#arrow)' : null));
|
|
3907
|
+
const N = root.append('g').selectAll('g').data(nodes).join('g').attr('class', 'node')
|
|
3908
|
+
.attr('tabindex', (n) => (n.kind === 'you' ? null : 0))
|
|
3909
|
+
.attr('role', (n) => (n.kind === 'you' ? null : 'button'))
|
|
3910
|
+
.attr('aria-label', (n) => n.title + (n.state ? ', ' + LABEL[n.state] : ''));
|
|
3911
|
+
N.filter((n) => n.state === 'needs_refresh').append('circle').attr('class', 'ring')
|
|
3912
|
+
.attr('r', (n) => n.r + 2.5);
|
|
3913
|
+
N.each(function (n) {
|
|
3914
|
+
const p = paint(n), d = shapePath(n);
|
|
3915
|
+
const s = d3.select(this).append(d ? 'path' : 'circle').attr(d ? 'd' : 'r', d || n.r).node();
|
|
3916
|
+
s.style.fill = p.fill;
|
|
3917
|
+
s.style.stroke = p.stroke || 'none';
|
|
3918
|
+
if (p.dash) s.style.strokeDasharray = '2 1.6';
|
|
3919
|
+
});
|
|
3920
|
+
N.on('mouseenter', hoverOn).on('mousemove', moveTip).on('mouseleave', hoverOff)
|
|
3921
|
+
.on('click', (e, n) => { if (!e.defaultPrevented) click(n); })
|
|
3922
|
+
.on('keydown', (e, n) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); click(n); } })
|
|
3923
|
+
.call(dragger());
|
|
3924
|
+
const labels = root.append('g').attr('class', 'labels').attr('font-size', 11);
|
|
3925
|
+
const T = labels.selectAll('text').data(nodes).join('text')
|
|
3926
|
+
.attr('class', (n) => 'lab-' + n.kind).text((n) => n.title);
|
|
3927
|
+
T.filter((n) => n.open_mistakes > 0).append('tspan').attr('class', 'flag').text(' ⚑');
|
|
3928
|
+
const zoom = d3.zoom().scaleExtent([0.1, 8]).on('zoom', (e) => {
|
|
3929
|
+
if (e.sourceEvent) touched = true;
|
|
3930
|
+
root.attr('transform', e.transform);
|
|
3931
|
+
labels.attr('font-size', 11 / e.transform.k);
|
|
3932
|
+
onZoom(e.transform);
|
|
3933
|
+
});
|
|
3934
|
+
svg.call(zoom).on('dblclick.zoom', null);
|
|
3935
|
+
const size = () => [host.clientWidth || 800, host.clientHeight || 600];
|
|
3936
|
+
svg.call(zoom.transform, d3.zoomIdentity.translate(size()[0] / 2, size()[1] / 2).scale(0.6));
|
|
3937
|
+
return {
|
|
3938
|
+
tick() {
|
|
3939
|
+
L.each(function (l) {
|
|
3940
|
+
let { x: x2, y: y2 } = l.target;
|
|
3941
|
+
if (l.type === 'requires') {
|
|
3942
|
+
const dx = x2 - l.source.x, dy = y2 - l.source.y, len = Math.hypot(dx, dy) || 1;
|
|
3943
|
+
x2 -= dx / len * (l.target.r + 2); y2 -= dy / len * (l.target.r + 2);
|
|
3944
|
+
}
|
|
3945
|
+
this.setAttribute('x1', l.source.x); this.setAttribute('y1', l.source.y);
|
|
3946
|
+
this.setAttribute('x2', x2); this.setAttribute('y2', y2);
|
|
3947
|
+
});
|
|
3948
|
+
N.attr('transform', (n) => `translate(${n.x},${n.y})`);
|
|
3949
|
+
T.attr('x', (n) => n.x + n.r + 3).attr('y', (n) => n.y + 3.5);
|
|
3950
|
+
},
|
|
3951
|
+
update() {
|
|
3952
|
+
N.classed('hide', (n) => n._hide).classed('dim', (n) => n._dim);
|
|
3953
|
+
L.classed('hide', (l) => l._hide).classed('dim', (l) => l._dim);
|
|
3954
|
+
T.classed('show', (n) => n._shown).classed('dim', (n) => n._dim);
|
|
3955
|
+
},
|
|
3956
|
+
fit(set, ms) {
|
|
3957
|
+
const [w, h] = size();
|
|
3958
|
+
svg.transition().duration(motion(ms)).call(zoom.transform, fitTransform(set, w, h));
|
|
3959
|
+
},
|
|
3960
|
+
center(n) {
|
|
3961
|
+
const [w, h] = size();
|
|
3962
|
+
svg.transition().duration(motion(500)).call(zoom.transform, d3.zoomIdentity
|
|
3963
|
+
.translate(w / 2, h / 2).scale(Math.max(k, 1.6)).translate(-n.x, -n.y));
|
|
3964
|
+
},
|
|
3965
|
+
};
|
|
3966
|
+
}
|
|
3967
|
+
|
|
3968
|
+
// Wiki kinds: project rounded square, resource diamond, decision triangle;
|
|
3969
|
+
// a note stays a small dot (a circle, so no path).
|
|
3970
|
+
function shapePath(n) {
|
|
3971
|
+
const r = n.r;
|
|
3972
|
+
if (n.kind === 'project') {
|
|
3973
|
+
const c = 1.5;
|
|
3974
|
+
return `M${c - r},${-r}H${r - c}Q${r},${-r} ${r},${c - r}V${r - c}Q${r},${r} ${r - c},${r}`
|
|
3975
|
+
+ `H${c - r}Q${-r},${r} ${-r},${r - c}V${c - r}Q${-r},${-r} ${c - r},${-r}Z`;
|
|
3976
|
+
}
|
|
3977
|
+
if (n.kind === 'resource') return `M0,${-1.3 * r}L${1.3 * r},0L0,${1.3 * r}L${-1.3 * r},0Z`;
|
|
3978
|
+
if (n.kind === 'decision') return `M0,${-1.2 * r}L${1.1 * r},${0.8 * r}L${-1.1 * r},${0.8 * r}Z`;
|
|
3979
|
+
return null;
|
|
3980
|
+
}
|
|
3981
|
+
|
|
3982
|
+
function paint(n) {
|
|
3983
|
+
if (n.kind === 'you') return { fill: 'var(--ink)' };
|
|
3984
|
+
if (n.kind === 'domain' || n.kind === 'project') return { fill: 'var(--lit)' };
|
|
3985
|
+
if (n.kind === 'area' || WIKI.has(n.kind)) return { fill: 'var(--ink-3)' };
|
|
3986
|
+
if (n.state === 'solid') return { fill: 'var(--solid)' };
|
|
3987
|
+
if (n.state === 'learning') return { fill: 'var(--learning)' };
|
|
3988
|
+
if (n.state === 'needs_refresh') return { fill: 'var(--refresh)', ring: true };
|
|
3989
|
+
return { fill: 'var(--panel)', stroke: 'var(--hollow)', dash: n.state === 'unverified' };
|
|
3990
|
+
}
|
|
3991
|
+
|
|
3992
|
+
function canvasRenderer() {
|
|
3993
|
+
const host = $('graph');
|
|
3994
|
+
const canvas = d3.select(host).append('canvas')
|
|
3995
|
+
.attr('aria-label', 'Knowledge map. List view shows the same topics as a table.').node();
|
|
3996
|
+
const ctx = canvas.getContext('2d');
|
|
3997
|
+
let t = d3.zoomIdentity, w = 0, h = 0, raf = 0, css = null;
|
|
3998
|
+
const col = (v) => (v.startsWith('var(') ? css.getPropertyValue(v.slice(4, -1)).trim() : v);
|
|
3999
|
+
function resize() {
|
|
4000
|
+
const dpr = window.devicePixelRatio || 1;
|
|
4001
|
+
w = host.clientWidth || 800; h = host.clientHeight || 600;
|
|
4002
|
+
canvas.width = w * dpr; canvas.height = h * dpr;
|
|
4003
|
+
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
|
4004
|
+
}
|
|
4005
|
+
function draw() {
|
|
4006
|
+
raf = 0;
|
|
4007
|
+
css = getComputedStyle(document.documentElement); // the theme can change between frames
|
|
4008
|
+
ctx.save();
|
|
4009
|
+
ctx.clearRect(0, 0, w, h);
|
|
4010
|
+
ctx.translate(t.x, t.y);
|
|
4011
|
+
ctx.scale(t.k, t.k);
|
|
4012
|
+
for (const l of links) {
|
|
4013
|
+
if (l._hide) continue;
|
|
4014
|
+
ctx.globalAlpha = (l._dim ? 0.12 : 1) * (l.type === 'you' ? 0.55 : 1);
|
|
4015
|
+
ctx.strokeStyle = col(l.type === 'requires' ? 'var(--ink-3)' : 'var(--edge)');
|
|
4016
|
+
ctx.lineWidth = (l.type === 'you' || l.type === 'wiki' ? 0.6 : l.type === 'area' ? 0.5 : 1) / t.k;
|
|
4017
|
+
ctx.setLineDash(l.type === 'requires' ? [3 / t.k, 3 / t.k] : l.type === 'wiki' ? [1 / t.k, 2 / t.k] : []);
|
|
4018
|
+
ctx.beginPath(); ctx.moveTo(l.source.x, l.source.y); ctx.lineTo(l.target.x, l.target.y); ctx.stroke();
|
|
4019
|
+
}
|
|
4020
|
+
ctx.setLineDash([]);
|
|
4021
|
+
for (const n of nodes) {
|
|
4022
|
+
if (n._hide) continue;
|
|
4023
|
+
const p = paint(n);
|
|
4024
|
+
ctx.globalAlpha = n._dim ? 0.12 : 1;
|
|
4025
|
+
ctx.fillStyle = col(p.fill);
|
|
4026
|
+
const d = shapePath(n);
|
|
4027
|
+
if (d) {
|
|
4028
|
+
ctx.save(); ctx.translate(n.x, n.y); ctx.fill(new Path2D(d)); ctx.restore();
|
|
4029
|
+
continue;
|
|
4030
|
+
}
|
|
4031
|
+
ctx.beginPath(); ctx.arc(n.x, n.y, n.r, 0, 2 * Math.PI);
|
|
4032
|
+
ctx.fill();
|
|
4033
|
+
if (p.stroke) {
|
|
4034
|
+
ctx.setLineDash(p.dash ? [2, 1.6] : []);
|
|
4035
|
+
ctx.strokeStyle = col(p.stroke); ctx.lineWidth = 1.2; ctx.stroke();
|
|
4036
|
+
ctx.setLineDash([]);
|
|
4037
|
+
}
|
|
4038
|
+
if (p.ring) {
|
|
4039
|
+
ctx.beginPath(); ctx.arc(n.x, n.y, n.r + 2.5, 0, 2 * Math.PI);
|
|
4040
|
+
ctx.strokeStyle = col('var(--refresh)'); ctx.lineWidth = 1.5; ctx.stroke();
|
|
4041
|
+
}
|
|
4042
|
+
}
|
|
4043
|
+
ctx.lineJoin = 'round';
|
|
4044
|
+
for (const n of nodes) {
|
|
4045
|
+
if (!n._shown) continue;
|
|
4046
|
+
ctx.globalAlpha = n._dim ? 0.12 : 1;
|
|
4047
|
+
const fs = (n.kind === 'domain' ? 14.3 : 11) / t.k;
|
|
4048
|
+
ctx.font = `${n.kind === 'domain' ? 600 : 400} ${fs}px system-ui, sans-serif`;
|
|
4049
|
+
const s = n.title + (n.open_mistakes ? ' ⚑' : '');
|
|
4050
|
+
ctx.strokeStyle = col('var(--panel)'); ctx.lineWidth = 3 / t.k;
|
|
4051
|
+
ctx.strokeText(s, n.x + n.r + 3, n.y + 3.5);
|
|
4052
|
+
ctx.fillStyle = col(n.kind === 'area' ? 'var(--ink-2)' : 'var(--ink)');
|
|
4053
|
+
ctx.fillText(s, n.x + n.r + 3, n.y + 3.5);
|
|
4054
|
+
}
|
|
4055
|
+
ctx.restore();
|
|
4056
|
+
}
|
|
4057
|
+
const schedule = () => { if (!raf) raf = requestAnimationFrame(draw); };
|
|
4058
|
+
const find = (e) => {
|
|
4059
|
+
const [x, y] = t.invert(d3.pointer(e, canvas));
|
|
4060
|
+
let best = null, bd = Infinity;
|
|
4061
|
+
for (const n of nodes) {
|
|
4062
|
+
if (n._hide) continue;
|
|
4063
|
+
const d = Math.hypot(n.x - x, n.y - y) - n.r;
|
|
4064
|
+
if (d < bd) { bd = d; best = n; }
|
|
4065
|
+
}
|
|
4066
|
+
return bd <= 4 / t.k ? best : null;
|
|
4067
|
+
};
|
|
4068
|
+
const zoom = d3.zoom().scaleExtent([0.1, 8]).on('zoom', (e) => {
|
|
4069
|
+
if (e.sourceEvent) touched = true;
|
|
4070
|
+
t = e.transform; onZoom(t); schedule();
|
|
4071
|
+
});
|
|
4072
|
+
const sel2 = d3.select(canvas);
|
|
4073
|
+
sel2.call(dragger((e) => {
|
|
4074
|
+
const n = find(e.sourceEvent);
|
|
4075
|
+
if (!n) return null;
|
|
4076
|
+
const [x, y] = t.apply([n.x, n.y]);
|
|
4077
|
+
return { node: n, x, y };
|
|
4078
|
+
}).on('drag.canvas', (e) => {
|
|
4079
|
+
[e.subject.node.fx, e.subject.node.fy] = t.invert([e.x, e.y]);
|
|
4080
|
+
}).on('start.canvas', (e) => {
|
|
4081
|
+
e.subject.node.fx = e.subject.node.x; e.subject.node.fy = e.subject.node.y;
|
|
4082
|
+
}).on('end.canvas', (e) => { e.subject.node.fx = null; e.subject.node.fy = null; }))
|
|
4083
|
+
.call(zoom).on('dblclick.zoom', null);
|
|
4084
|
+
sel2.on('mousemove', (e) => {
|
|
4085
|
+
const n = find(e);
|
|
4086
|
+
if (n !== hover) { if (n) hoverOn(e, n); else hoverOff(); } else if (n) moveTip(e);
|
|
4087
|
+
}).on('mouseleave', () => { if (hover) hoverOff(); })
|
|
4088
|
+
.on('click', (e) => { const n = find(e); if (n) click(n); });
|
|
4089
|
+
resize();
|
|
4090
|
+
t = d3.zoomIdentity.translate(w / 2, h / 2).scale(0.4);
|
|
4091
|
+
sel2.call(zoom.transform, t);
|
|
4092
|
+
new ResizeObserver(() => { if (host.clientWidth) { resize(); schedule(); } }).observe(host);
|
|
4093
|
+
return {
|
|
4094
|
+
tick: schedule,
|
|
4095
|
+
update: schedule,
|
|
4096
|
+
fit(set) { sel2.transition().duration(motion(500)).call(zoom.transform, fitTransform(set, w, h)); },
|
|
4097
|
+
center(n) {
|
|
4098
|
+
sel2.transition().duration(motion(500)).call(zoom.transform, d3.zoomIdentity
|
|
4099
|
+
.translate(w / 2, h / 2).scale(Math.max(k, 1.6)).translate(-n.x, -n.y));
|
|
4100
|
+
},
|
|
4101
|
+
};
|
|
4102
|
+
}
|
|
4103
|
+
|
|
4104
|
+
function onlyState(st) {
|
|
4105
|
+
F.states = new Set([st]);
|
|
4106
|
+
F.weak = false;
|
|
4107
|
+
F.domain = '';
|
|
4108
|
+
syncControls();
|
|
4109
|
+
apply();
|
|
4110
|
+
}
|
|
4111
|
+
function retheme() { if (R) R.update(); }
|
|
4112
|
+
// live home: forget the drawn map, so the next init draws it from the current D. Its
|
|
4113
|
+
// controls stay; the Domain list is filled again.
|
|
4114
|
+
function reset() {
|
|
4115
|
+
if (built) fillDomains();
|
|
4116
|
+
if (!ready) return;
|
|
4117
|
+
sim.stop();
|
|
4118
|
+
ready = false; touched = false; R = null; hover = null;
|
|
4119
|
+
$('graph').replaceChildren();
|
|
4120
|
+
$('tree').replaceChildren();
|
|
4121
|
+
if (!$('tree').hidden) renderTree();
|
|
4122
|
+
}
|
|
4123
|
+
|
|
4124
|
+
return { init, onlyState, setList, setCurrent, retheme, reset };
|
|
4125
|
+
})();
|
|
4126
|
+
|
|
4127
|
+
const RENDER = { home: renderHome, brain: ensureBrainUi, library: renderLibrary, you: renderYou,
|
|
4128
|
+
timeline: renderTimeline, ideas: renderIdeas, study: renderStudy, help: renderHelp };
|
|
4129
|
+
|
|
4130
|
+
/* ---- live home: poll the version every 3 s while shown, apply each delta in place ---- */
|
|
4131
|
+
function reindex() { // every lookup derived from D, refilled in place
|
|
4132
|
+
TODAY = D.day || D.as_of.slice(0, 10);
|
|
4133
|
+
NAME = D.owner && D.owner.name ? D.owner.name : '';
|
|
4134
|
+
PAGES.clear();
|
|
4135
|
+
for (const p of D.pages) PAGES.set(p.id, p);
|
|
4136
|
+
GN.clear();
|
|
4137
|
+
for (const n of D.graph.nodes) GN.set(n.id, n);
|
|
4138
|
+
LOBES.clear();
|
|
4139
|
+
for (const c of D.clusters) LOBES.set(c.id, c);
|
|
4140
|
+
BRAIN_IDS.clear();
|
|
4141
|
+
if (D.brain && D.brain.nodes) for (const id of D.brain.nodes.ids) BRAIN_IDS.add(id);
|
|
4142
|
+
lensAdj = null;
|
|
4143
|
+
growthData = null;
|
|
4144
|
+
for (let i = scrubs.length; i--;) { if (scrubs[i].root.isConnected) scrubs[i].refresh(); else scrubs.splice(i, 1); }
|
|
4145
|
+
if (lensId && !BRAIN_IDS.has(lensId)) clearLens(); // its page is gone
|
|
4146
|
+
countDegrees();
|
|
4147
|
+
BACK = HAY = CMDS = null;
|
|
4148
|
+
}
|
|
4149
|
+
const CLEAR = { you: ['view-you'], timeline: ['view-timeline'], ideas: ['view-ideas'], help: ['view-help'],
|
|
4150
|
+
study: ['sprint', 'tiles', 'plan', 'coming', 'open-mistakes', 'weeks', 'timeline', 'mstats', 'mirror'] };
|
|
4151
|
+
// A section again from D, in place: Library and Brain keep their controls and filters.
|
|
4152
|
+
function rerender(name) {
|
|
4153
|
+
if (name === 'library') {
|
|
4154
|
+
if (!LOBES.has(LIB.lobe)) LIB.lobe = '';
|
|
4155
|
+
fillLobes();
|
|
4156
|
+
LIB.hits = LIB.q ? new Set(search(LIB.q).map((h) => h.h.p.id)) : null;
|
|
4157
|
+
renderLibraryRows();
|
|
4158
|
+
} else if (name === 'brain') {
|
|
4159
|
+
if (brainUi && !brainFailed) { fillOutline(); if (brain) renderLegend(brain.mode); }
|
|
4160
|
+
G.reset(); // the 2D map is drawn again from the new data: now if it shows, else when it does
|
|
4161
|
+
if (view !== '3d') G.init();
|
|
4162
|
+
} else {
|
|
4163
|
+
for (const id of CLEAR[name] || []) $(id).replaceChildren();
|
|
4164
|
+
if (name === 'study') $('sprint').hidden = false;
|
|
4165
|
+
RENDER[name]();
|
|
4166
|
+
}
|
|
4167
|
+
}
|
|
4168
|
+
const focusSig = (e) => [e.tagName, e.id, e.getAttribute('aria-label'), e.textContent.trim().slice(0, 80)].join('\n');
|
|
4169
|
+
let V = D.v;
|
|
4170
|
+
function applyDelta(d) {
|
|
4171
|
+
const had = new Set(BRAIN_IDS);
|
|
4172
|
+
if (d.full) { delete d.full; delete d.relock; D = d; }
|
|
4173
|
+
else {
|
|
4174
|
+
Object.assign(D, d.sections);
|
|
4175
|
+
if (d.pages) {
|
|
4176
|
+
const by = new Map(D.pages.map((p) => [p.id, p]));
|
|
4177
|
+
for (const p of d.pages.upsert) by.set(p.id, p);
|
|
4178
|
+
for (const id of d.pages.removed) by.delete(id);
|
|
4179
|
+
D.pages = d.pages.order.map((id) => by.get(id)).filter(Boolean);
|
|
4180
|
+
}
|
|
4181
|
+
if (d.brain) D.brain = d.brain.blob;
|
|
4182
|
+
}
|
|
4183
|
+
V = d.v;
|
|
4184
|
+
reindex();
|
|
4185
|
+
// what the user is in keeps its place: scroll, focus, the reader, the search overlay
|
|
4186
|
+
const y = window.scrollY, act = document.activeElement;
|
|
4187
|
+
const sig = act && act !== document.body ? focusSig(act) : null;
|
|
4188
|
+
renderHeader();
|
|
4189
|
+
for (const s of rendered) if (s !== current) stale.add(s);
|
|
4190
|
+
rerender(current);
|
|
4191
|
+
if (readerId && !reader.hidden) {
|
|
4192
|
+
if (!PAGES.has(readerId) && !GN.has(readerId) && !BRAIN_IDS.has(readerId)) {
|
|
4193
|
+
closeReader();
|
|
4194
|
+
reader.replaceChildren(); // a private site's details go with it after a relock
|
|
4195
|
+
}
|
|
4196
|
+
else if (!reader.classList.contains('inspector') && (d.full || (d.pages && d.pages.upsert.some((p) => p.id === readerId))
|
|
4197
|
+
|| (d.sections && (d.sections.graph || d.sections.details)))) openReader(readerId, true);
|
|
4198
|
+
}
|
|
4199
|
+
if (!pal.hidden && pq.value.trim()) {
|
|
4200
|
+
const at = palSel;
|
|
4201
|
+
renderPalette();
|
|
4202
|
+
palSel = Math.max(0, Math.min(at, palItems.length - 1));
|
|
4203
|
+
markPal();
|
|
4204
|
+
}
|
|
4205
|
+
if (d.brain || d.full) remountBrain(d.brain ? d.brain.added : [...BRAIN_IDS].filter((id) => !had.has(id)));
|
|
4206
|
+
window.scrollTo(0, y);
|
|
4207
|
+
if (sig && !act.isConnected) {
|
|
4208
|
+
const same = [...document.querySelectorAll(act.tagName)].find((x) => focusSig(x) === sig);
|
|
4209
|
+
if (same) same.focus({ preventScroll: true });
|
|
4210
|
+
}
|
|
4211
|
+
}
|
|
4212
|
+
let pollTimer = 0, polling = false;
|
|
4213
|
+
async function poll() {
|
|
4214
|
+
clearTimeout(pollTimer);
|
|
4215
|
+
if (polling || document.hidden) return; // hidden: no timer; showing the tab polls at once
|
|
4216
|
+
polling = true;
|
|
4217
|
+
let d = null;
|
|
4218
|
+
const gen = privGen;
|
|
4219
|
+
try {
|
|
4220
|
+
const ver = await api('/api/home/version');
|
|
4221
|
+
// the switch relocked (10 minutes, a minimise): the public home whole, no private item kept
|
|
4222
|
+
if (PRIVATE && !ver.private) d = { ...(await api('/api/home')), full: true, relock: true };
|
|
4223
|
+
else if (ver.v !== V) d = await api('/api/home/delta?since=' + encodeURIComponent(V) + (PRIVATE ? '&private=1' : ''));
|
|
4224
|
+
showUpdate(ver.update);
|
|
4225
|
+
offline(null);
|
|
4226
|
+
} catch (e) { offline(e); }
|
|
4227
|
+
polling = false;
|
|
4228
|
+
pollTimer = setTimeout(poll, 3000);
|
|
4229
|
+
if (!d || gen !== privGen || switching) return; // the switch moved meanwhile: its own load wins
|
|
4230
|
+
if (d.relock && PRIVATE) { PRIVATE = false; privGen++; syncLock(); }
|
|
4231
|
+
if (d.full || d.v !== V) applyDelta(d);
|
|
4232
|
+
}
|
|
4233
|
+
if (LIVE) {
|
|
4234
|
+
document.addEventListener('visibilitychange', () => { if (!document.hidden) poll(); });
|
|
4235
|
+
pollTimer = setTimeout(poll, 3000);
|
|
4236
|
+
}
|
|
4237
|
+
|
|
4238
|
+
/* ---- start ---- */
|
|
4239
|
+
applyTheme(theme);
|
|
4240
|
+
renderHeader();
|
|
4241
|
+
setHdr();
|
|
4242
|
+
const start = SECTIONS.includes(location.hash.slice(1)) ? location.hash.slice(1) : 'home';
|
|
4243
|
+
// The brain's layout is the slow part: let the first paint land before it is built.
|
|
4244
|
+
if (start === 'home') {
|
|
4245
|
+
rendered.add('home');
|
|
4246
|
+
renderHome();
|
|
4247
|
+
for (const s of SECTIONS) {
|
|
4248
|
+
$('tab-' + s).setAttribute('aria-selected', String(s === 'home'));
|
|
4249
|
+
$('tab-' + s).tabIndex = s === 'home' ? 0 : -1;
|
|
4250
|
+
}
|
|
4251
|
+
current = 'home';
|
|
4252
|
+
sel.value = 'home';
|
|
4253
|
+
document.body.dataset.readyMs = String(Math.round(performance.now() - T0));
|
|
4254
|
+
setTimeout(() => {
|
|
4255
|
+
placeBrain('home-brain-slot');
|
|
4256
|
+
document.body.dataset.brainReadyMs = String(Math.round(performance.now() - T0));
|
|
4257
|
+
}, 50);
|
|
4258
|
+
} else {
|
|
4259
|
+
show(start);
|
|
4260
|
+
document.body.dataset.readyMs = String(Math.round(performance.now() - T0));
|
|
4261
|
+
}
|
|
4262
|
+
})();
|