Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
469 lines (424 loc) · 19.8 KB
/
Copy pathapp.js
File metadata and controls
469 lines (424 loc) · 19.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
// app.js
import * as store from './store.js';
import { t, setLanguage, detectLanguage, saveLanguage } from './i18n.js';
import { renderNotesPanel, BRAND_MARK } from './notes-ui.js';
import { renderEditor } from './editor.js';
import { renderHistoryPanel } from './history-ui.js';
import { initSync } from './sync.js';
let currentNoteId = null;
let currentNoteRev = 0; // set by Task 18's editor via onRevChange; flush() target for lifecycle events
let savedRefreshTimer = null; // debounce for the note-list refresh on 'saved' events
// Set once renderNotesPanel has run, so the note-changed subscriber below
// (registered before the panel exists) can reach its `refresh()`.
let notesPanelHandle = null;
let syncNoteDeletedHandler = null;
const STORAGE_REASON_KEYS = {
blocked: 'error.storageBlocked',
corrupt: 'error.storageCorrupt',
unavailable: 'error.storageUnavailable',
'migration-failed': 'error.storageUnavailable',
'version-change': 'error.storageVersionChange',
};
// A dedicated container the editor never owns (unlike the old showAlert,
// which wrote into #editor-panel and was wiped by the next renderEditor()
// call — see final-review Fix 8). Uses textContent, not innerHTML: every
// caller passes an already-translated i18n literal today, but this keeps it
// safe even if that ever changes.
//
// `tone` matters here for the same reason the brand brief keeps "durable
// save" and "browser retention" visually separate: coral is reserved for a
// save failure or a destructive action, and using it for a calm, standing
// informational notice (e.g. the Safari retention notice) would itself be
// the kind of conflation this product is built to avoid.
function addNotice(message, tone = 'error') {
const container = document.getElementById('app-notices');
if (!container) return;
// Guards against the same notice stacking forever — e.g. a commitVersion
// failure recurring on every idle-timer tick while the underlying problem
// persists.
const last = container.lastElementChild;
if (last && last.textContent === message) return;
const div = document.createElement('div');
div.className = tone === 'info' ? 'app-notice tone-info' : 'app-notice';
div.textContent = message;
container.appendChild(div);
}
// Not Chrome/Chromium/Edge (which also contain "Safari" in their UA string).
// See design doc "Safari and retention": ordinary Safari is supported but
// declared non-durable, with a standing notice — this is what detects that
// case. Deliberately does NOT attempt to detect Private Browsing specifically:
// a successful storage write probe there is not proof of durability, and the
// design is explicit that such a probe must never be read as one.
function isSafari() {
const ua = navigator.userAgent || '';
if (!/Safari/.test(ua) || /Chrome|Chromium|Edg/.test(ua)) return false;
// An installed Home Screen / Dock web app is the one documented exemption:
// its storage is separate from ordinary Safari's, so the notice there would
// be a false alarm rather than a missed warning. navigator.standalone is a
// declarative property — reading it is not the write probe the design
// forbids as proof of durability.
if (navigator.standalone === true) return false;
return true;
}
// The last phrase handed to the screen-reader announcer. Kept so an unchanged
// state is not re-announced: 'saving' and 'saved' fire on every debounced
// flush, and repeating "Saved locally" into a live region on each one would
// talk over someone who is simply typing.
let lastAnnounced = '';
function announceStatus(phrase) {
if (phrase === lastAnnounced) return;
lastAnnounced = phrase;
const el = document.getElementById('status-a11y');
if (el) el.textContent = phrase;
}
function renderStatus(event) {
const revisionEl = document.getElementById('status-revision');
const retentionEl = document.getElementById('status-retention');
const noticeEl = document.getElementById('status-notice');
if (event.type === 'saved') {
revisionEl.className = 'state-saved';
revisionEl.textContent = `${t('status.saved')} · ${new Date(event.completedAt).toLocaleTimeString()}`;
// Outcome states only — 'saving' is deliberately not announced. Announcing
// it would make every flush a two-phrase alternation ("Saving…", "Saved
// locally"), which defeats the de-duplication and interrupts typing.
announceStatus(t('status.saved'));
// Titles are user-set now and never change on save — but rows still show
// "last modified" and sort by updatedAt, which every durable save bumps.
// Refresh the list then, debounced so a burst of flushes is one repaint.
if (notesPanelHandle) {
if (savedRefreshTimer) clearTimeout(savedRefreshTimer);
savedRefreshTimer = setTimeout(() => {
savedRefreshTimer = null;
notesPanelHandle.refresh();
}, 400);
}
} else if (event.type === 'saving') {
revisionEl.className = '';
revisionEl.textContent = t('status.saving');
} else if (event.type === 'memory-only') {
revisionEl.className = 'state-failed';
revisionEl.textContent = t('status.notSaved');
announceStatus(t('status.notSaved'));
} else if (event.type === 'save-failed') {
// An ordinary transient failure: the visible text is unchanged and no
// rescue buffer was populated (that is what 'memory-only' is for), so
// this must not borrow that event's wording — see final-review Fix 4.
revisionEl.className = 'state-failed';
revisionEl.textContent = t('status.saveFailed');
announceStatus(t('status.saveFailed'));
} else if (event.type === 'retention-changed') {
const key = { persistent: 'retention.persistent', 'best-effort': 'retention.bestEffort', 'session-only': 'retention.sessionOnly', unknown: 'retention.unknown' }[event.retention] || 'retention.unknown';
retentionEl.className = event.retention === 'best-effort' || event.retention === 'session-only' ? 'state-warning' : 'state-info';
retentionEl.textContent = `${t('retention.label')}: ${t(key)}`;
} else if (event.type === 'quota-warning') {
noticeEl.hidden = false;
noticeEl.className = 'state-warning';
noticeEl.textContent = t('status.quotaWarning');
} else if (event.type === 'storage-unavailable') {
// Post-boot occurrence (e.g. another tab's upgrade force-closed this
// connection) — the initial boot-time case is handled directly in boot()
// before this subscriber even exists.
addNotice(t(STORAGE_REASON_KEYS[event.reason] || 'error.storageUnavailable'));
} else if (event.type === 'note-deleted') {
if (syncNoteDeletedHandler) syncNoteDeletedHandler(event.noteId);
if (notesPanelHandle) notesPanelHandle.refresh();
} else if (event.type === 'note-changed') {
// Emitted by setPinned/trashNote/restoreNote/purgeNote/restoreVersion/
// renameNote. None of those carry enough information here to update the
// list in place, and none of them fire anywhere near per-keystroke
// frequency, so a full list refresh on each is cheap and correct.
if (notesPanelHandle) notesPanelHandle.refresh();
}
}
async function boot() {
const lang = detectLanguage();
setLanguage(lang);
document.documentElement.lang = lang;
let status;
try {
status = await store.open({});
} catch (error) {
// store.open() throws (rather than resolving with available:false) only
// for a version-mismatch: this page is older than the database on disk.
// That must never be silent — an unhandled rejection here would leave the
// status bar blank forever with no explanation.
addNotice(t('error.versionMismatch'));
return;
}
store.subscribe(renderStatus);
// Only render retention at boot when it is a definitive answer. Painting
// "Browser retention: Unknown" on every load — for a product whose whole
// pitch is that notes stay put — reads as an alarm, then flickers to
// "Persistent" a moment later. The '—' placeholder is quieter than a
// scary word, and the real state arrives via retention-changed shortly.
if (status.retention && status.retention !== 'unknown') {
renderStatus({ type: 'retention-changed', retention: status.retention });
}
if (!status.available) {
addNotice(t(STORAGE_REASON_KEYS[status.reason] || 'error.storageUnavailable'));
} else if (isSafari()) {
// Standing notice, not a transient one: shown once at boot and left
// visible for the session, regardless of what retention-changed later
// reports (persist() granting 'persistent' on Safari is not understood
// to be an exemption from its storage caps — see design doc). 'info'
// tone: this is retention information, not a failure.
addNotice(t('notice.safariNonDurable'), 'info');
}
let activeEditor = null;
// History is closed by default (brand brief §6: "Version panel: closed by
// default"); the preference persists for the session, so switching notes
// keeps whichever state the user last chose.
let historyOpen = false;
// --- Mobile single-pane view state (redesign-plan §4) -------------------
// Below 768px only one pane shows at a time: the list is the root view and
// opening a note pushes the editor over it. CSS reads #app[data-view];
// from 768px up both panes are always visible and this state is inert.
const appEl = document.getElementById('app');
const mobileLayout = window.matchMedia('(max-width: 767px)');
appEl.dataset.view = 'list';
// --- Browser tab title (docs/filename-plan.md §1.5) ---------------------
// "{name} | Heldnote" while a note is on screen; the index.html baseline
// otherwise. On a phone the list view counts as "no note on screen" even
// though a note is loaded behind it.
const DEFAULT_DOC_TITLE = document.title;
let currentNoteTitle = null;
function applyDocTitle() {
const onList = mobileLayout.matches && appEl.dataset.view !== 'editor';
document.title = currentNoteTitle && !onList
? `${currentNoteTitle} | Heldnote`
: DEFAULT_DOC_TITLE;
}
function setView(view) {
appEl.dataset.view = view;
applyDocTitle();
}
// Opening a note on a phone gets a real history entry, so the device back
// gesture returns to the list instead of leaving the app. Only one entry
// is ever pushed: while in the editor the list is off screen, so a second
// push can't happen before popstate or the back control pops this one.
function enterEditorView() {
if (
mobileLayout.matches
&& appEl.dataset.view !== 'editor'
&& !(history.state && history.state.heldnoteView === 'editor')
) {
try { history.pushState({ heldnoteView: 'editor' }, ''); } catch (e) { /* history may be sandboxed */ }
}
setView('editor');
}
function leaveEditorView() {
if (history.state && history.state.heldnoteView === 'editor') {
history.back(); // the popstate handler below performs the switch
} else {
setView('list');
}
}
// Escape closes the history sheet. Every other dismissible surface honours
// Escape (the find bar, the rename field); this one silently did not, which
// reads as the app ignoring you. The find-bar guard matters: editor.js has
// its own document-level Escape handler, and without this check one keypress
// would close both. The find bar is the innermost surface, so it wins.
document.addEventListener('keydown', (event) => {
if (event.key !== 'Escape' || !historyOpen) return;
const findBar = document.getElementById('find-bar');
if (findBar && !findBar.hidden) return;
historyOpen = false;
renderHistoryForCurrent();
if (activeEditor) activeEditor.setHistoryOpen(false);
const toggle = document.getElementById('toggle-history');
if (toggle) toggle.focus(); // return focus to the control that opened it
});
window.addEventListener('popstate', (event) => {
const toEditor = event.state && event.state.heldnoteView === 'editor';
setView(toEditor ? 'editor' : 'list');
// The history sheet floats above both views; leaving the editor while
// it is open would strand it over the list.
if (!toEditor && historyOpen) {
historyOpen = false;
renderHistoryForCurrent();
if (activeEditor) activeEditor.setHistoryOpen(false);
}
});
// Strings are baked into innerHTML when each panel renders, so a language
// change has to re-render everything — the sidebar, the editor toolbar, the
// history sheet and the status bar. A reload is the honest way to do that
// without hunting every string, and it is safe: the pagehide handler below
// flushes the open draft before the page goes away.
function changeLanguage(lang) {
const resolved = saveLanguage(lang);
document.documentElement.lang = resolved;
location.reload();
}
function toggleTheme() {
const root = document.documentElement;
const systemPrefersLight = window.matchMedia('(prefers-color-scheme: light)').matches;
const current = root.dataset.theme || (systemPrefersLight ? 'light' : 'dark');
const next = current === 'dark' ? 'light' : 'dark';
root.dataset.theme = next;
try { localStorage.setItem('heldnote-theme', next); } catch (e) { /* non-fatal */ }
}
function renderHistoryForCurrent() {
const panel = document.getElementById('history-panel');
if (!historyOpen || !currentNoteId) {
panel.hidden = true;
return;
}
const id = currentNoteId;
// A restore changes the note's draft text underneath the editor, so the
// editor must reload from store rather than keep showing the pre-restore
// text; re-opening it (same as a fresh selection) is the simplest way to
// pick up what restoreVersion just wrote.
//
// But history-ui.js's restore-in-progress retry loop can take up to
// ~1.2s to settle, and the user may have selected a different note by
// then. onRestore fires against whatever note it was created for (`id`,
// captured here), so it must check that note is still the one on screen
// before touching the editor — otherwise a slow retry for note A that
// resolves after the user has already switched to note B would yank B's
// editor out from under them and silently swap in A's.
renderHistoryPanel(panel, id, {
onRestore: () => { if (id === currentNoteId) openEditor(id); },
// On small screens the sheet covers the toggle that opened it, so the
// panel carries its own close control.
onClose: () => {
historyOpen = false;
renderHistoryForCurrent();
if (activeEditor) activeEditor.setHistoryOpen(false);
},
});
}
function openEditor(id) {
currentNoteId = id;
currentNoteRev = 0;
if (activeEditor) activeEditor.destroy();
activeEditor = renderEditor(document.getElementById('editor-panel'), id, {
onRevChange: (rev) => { currentNoteRev = rev; },
// Fires on load (with the stored name) and once per confirmed rename.
// Tab title only: the sidebar already refreshes via the note-changed
// event renameNote emits — a second refresh here would be redundant.
onTitleChange: (title) => {
currentNoteTitle = title;
applyDocTitle();
},
onError: addNotice,
historyOpen,
onToggleHistory: () => {
historyOpen = !historyOpen;
renderHistoryForCurrent();
return historyOpen;
},
onBack: leaveEditorView,
});
renderHistoryForCurrent();
}
function renderEmptyState() {
const panel = document.getElementById('editor-panel');
panel.innerHTML = `
<div class="editor-empty">
${BRAND_MARK.replace('width="22" height="22"', 'width="44" height="44"')}
<h2>${t('empty.title')}</h2>
<p>${t('empty.body')}</p>
<button id="empty-new-note">${t('empty.cta')}</button>
</div>
`;
panel.querySelector('#empty-new-note').addEventListener('click', async () => {
const note = await store.createNote();
if (notesPanelHandle) notesPanelHandle.refresh();
selectNote(note.id);
});
}
function closeEditor() {
currentNoteId = null;
currentNoteRev = 0;
currentNoteTitle = null;
if (activeEditor) { activeEditor.destroy(); activeEditor = null; }
renderEmptyState();
document.getElementById('history-panel').hidden = true;
if (notesPanelHandle) notesPanelHandle.setActive(null);
// The note this view was showing is gone; on a phone that means back to
// the list, not an empty sheet. setView also restores the tab title.
setView('list');
}
// switchView: false keeps the current pane on phones — used when a note is
// (re)opened as a side effect (boot, import reload) rather than by a tap.
function selectNote(id, { switchView = true } = {}) {
openEditor(id);
if (notesPanelHandle) notesPanelHandle.setActive(id);
if (switchView) enterEditorView();
}
// Called after any import completes. 'replace' wipes the database
// wholesale, so the note open in the editor (if any) very likely no longer
// exists; 'copy' never removes the original, but reloading is still cheap
// and correct either way, in case the id happened to collide.
async function handleImportComplete() {
if (!currentNoteId) return;
const id = currentNoteId;
try {
await store.getNote(id);
// Reload in place: imports run from the sidebar, so on a phone the
// user is on the list — do not yank them into the editor.
selectNote(id, { switchView: false });
} catch (error) {
closeEditor();
}
}
// Called after a trash purge. Unlike the other note-changed sources,
// a purge can remove the very note the editor has open, and that is not
// something a plain list refresh fixes.
function handleNoteDeleted(id) {
if (id === currentNoteId) closeEditor();
}
syncNoteDeletedHandler = handleNoteDeleted;
notesPanelHandle = renderNotesPanel(document.getElementById('notes-panel'), {
onSelect: selectNote,
onImportComplete: handleImportComplete,
onNoteDeleted: handleNoteDeleted,
onToggleTheme: toggleTheme,
onChangeLanguage: changeLanguage,
});
// A merge can replace the durable draft underneath an open editor. Reload
// only when that editor's note was actually applied; fence-skipped notes
// keep the user's newer in-memory view and will be merged next round.
store.subscribe((event) => {
if (event.type !== 'sync-applied' || !currentNoteId) return;
if ((event.deletedNoteIds || []).includes(currentNoteId)) {
handleNoteDeleted(currentNoteId);
return;
}
const change = (event.changes || []).find((entry) => entry.noteId === currentNoteId);
if (change && change.textChanged) {
selectNote(currentNoteId, { switchView: false });
}
});
initSync();
// First paint: an invitation to act, never a blank pane. If notes already
// exist, open the most recent one so returning users land back in their
// writing; on a truly first visit, show the empty state.
try {
const existing = await store.listNotes({});
if (existing.length > 0) {
// "Return anytime" means returning to where you left off: open the
// most recently edited note, not whichever pinned note sorts first.
// switchView false: on a phone the list is the root view — the note
// is loaded and one tap away, not pushed over the list unasked.
const mostRecent = existing.reduce((best, note) => (note.updatedAt > best.updatedAt ? note : best));
selectNote(mostRecent.id, { switchView: false });
} else {
renderEmptyState();
}
} catch (error) {
renderEmptyState();
}
window.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden' && currentNoteId) {
store.flush(currentNoteId, currentNoteRev).catch(() => {});
}
});
window.addEventListener('pagehide', () => {
if (currentNoteId) store.flush(currentNoteId, currentNoteRev).catch(() => {});
});
}
boot().catch((error) => {
console.error('heldnote: boot failed', error);
});
export { currentNoteId, currentNoteRev };