Files
Life-OS/public/addons.js
T

450 lines
37 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* Life OS reliability and productivity add-ons. */
(() => {
const DRAFT_KEY = 'lifeos_today_draft_v1';
const localDay = () => { const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`; };
const escapeHtml = value => String(value || '').replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[char]));
const APP_VERSION = '1.29.0';
window.LifeOSVersion = APP_VERSION;
const appIds = ['today', 'timeline', 'museum', 'insights', 'profile', 'tasks', 'calendar', 'system', 'browser', 'terminal', 'database'];
const t = (key, values) => LifeI18n.t(key, values);
function readDraft() {
try { return JSON.parse(localStorage.getItem(DRAFT_KEY)); } catch { return null; }
}
function saveDraft(text) {
localStorage.setItem(DRAFT_KEY, JSON.stringify({ date: (typeof todayTargetDate !== 'undefined' && todayTargetDate) || localDay(), text, updatedAt: new Date().toISOString() }));
}
function restoreDraft(entry) {
const draft = readDraft();
const today = (typeof todayTargetDate !== 'undefined' && todayTargetDate) || localDay();
if (!draft || draft.date !== today || !draft.text || entry.value) return;
entry.value = draft.text;
entry.dispatchEvent(new Event('input', { bubbles: true }));
if (typeof toast === 'function') toast('addon.draftRestored');
}
function wireToday() {
const entry = document.querySelector('#entry');
if (!entry || entry.dataset.lifeosDraft === 'ready') return;
entry.dataset.lifeosDraft = 'ready';
restoreDraft(entry);
entry.addEventListener('input', () => saveDraft(entry.value));
}
function wireLanguageControl() { /* The System renderer owns this control. */ }
function clearDraftAfterSave() {
setTimeout(() => {
const today = (typeof todayTargetDate !== 'undefined' && todayTargetDate) || localDay();
try {
const saved = JSON.parse(localStorage.getItem('lifeos_memories') || '[]').some(m => !m.trashedAt && m.date === today && m.kind !== 'moment');
if (saved) localStorage.removeItem(DRAFT_KEY);
} catch {}
}, 700);
}
function closeSearch() { document.querySelector('#lifeos-search')?.remove(); }
function openSearch() {
closeSearch();
const box = document.createElement('div');
box.id = 'lifeos-search';
box.innerHTML = `<div class="lifeos-search-backdrop"></div><section class="lifeos-search-panel"><div class="lifeos-search-head"><span>${t('addon.searchTitle')}</span><button aria-label="${t('common.close')}">×</button></div><input autofocus aria-label="${t('addon.searchPlaceholder')}" placeholder="${t('addon.searchPlaceholder')}"><div class="lifeos-search-results"></div><p class="lifeos-search-hint">${t('addon.searchHint')}</p></section>`;
document.body.append(box);
const input = box.querySelector('input');
const results = box.querySelector('.lifeos-search-results');
let searchSequence = 0;
const localResults = query => {
const board = window.LifeOSActions.board();
const rows = [
...mems().map(item => ({ kind:'memory', id:item.id, title:item.title || item.text?.trim().split('\n')[0].slice(0,64) || t('timeline.untitled'), meta:item.date, snippet:[item.text, ...(item.tags || []), item.location, item.mood].filter(Boolean).join(' · '), updated_at:item.updatedAt || item.date })),
...(board.tasks || []).map(item => ({ kind:'task', id:item.id, title:item.title, meta:item.dueDate || '', snippet:item.priority || '', updated_at:item.updatedAt || item.createdAt || '' })),
...(board.goals || []).map(item => ({ kind:'goal', id:item.id, title:item.title, meta:item.targetDate || '', snippet:item.description || '', updated_at:item.updatedAt || item.createdAt || '' }))
];
return rows.filter(item => !query || [item.title,item.meta,item.snippet,item.kind].join(' ').toLocaleLowerCase().includes(query)).sort((a,b) => String(b.updated_at).localeCompare(String(a.updated_at))).slice(0,12);
};
const render = async () => {
const request = ++searchSequence, query = input.value.trim().toLocaleLowerCase();
let found = localResults(query);
if (query && window.LifeOSLocalDB?.search) {
try {
const indexed = await window.LifeOSLocalDB.search(query, 12);
const current = new Map(found.map(item => [`${item.kind}:${item.id}`, item]));
const activeIds = new Set(mems().map(item => item.id));
const activeBoard=window.LifeOSActions.board(), activeTasks=new Set(activeBoard.tasks.map(item=>item.id)), activeGoals=new Set(activeBoard.goals.map(item=>item.id));
indexed.forEach(item => { if ((item.kind === 'memory' && !activeIds.has(item.id)) || (item.kind==='task' && !activeTasks.has(item.id)) || (item.kind==='goal' && !activeGoals.has(item.id))) return; const key = `${item.kind}:${item.id}`; if (!current.has(key)) current.set(key, item); });
found = [...current.values()].slice(0, 12);
} catch {}
}
if (request !== searchSequence || !box.isConnected) return;
const typeName = kind => kind === 'memory' ? appName('timeline') : kind === 'task' ? appName('tasks') : LifeI18n.t('calendar.goal');
results.innerHTML = found.length ? found.map(item => `<button data-id="${escapeHtml(item.id)}" data-kind="${item.kind}"><small>${escapeHtml(typeName(item.kind))}${item.meta ? ` · ${escapeHtml(item.meta)}` : ''}</small><strong>${escapeHtml(item.title || t('timeline.untitled'))}</strong><span>${escapeHtml(item.snippet || '')}</span></button>`).join('') : `<div class="lifeos-search-empty">${t('addon.noResults')}</div>`;
results.querySelectorAll('button').forEach(button => button.addEventListener('click', () => { closeSearch(); if (button.dataset.kind === 'memory') { openApp('timeline'); setTimeout(() => detail(button.dataset.id), 20); } else { openApp('tasks'); if (button.dataset.kind === 'task') window.openTaskEdit?.(button.dataset.id); else window.openGoalForm?.(button.dataset.id); } }));
};
input.addEventListener('input', render);
box.querySelector('.lifeos-search-head button').addEventListener('click', closeSearch);
box.querySelector('.lifeos-search-backdrop').addEventListener('click', closeSearch);
render(); input.focus();
}
const style = document.createElement('style');
style.textContent = `.lifeos-search-backdrop{position:fixed;inset:0;background:#0008;z-index:8000}.lifeos-search-panel{position:fixed;z-index:8001;top:18vh;left:50%;transform:translateX(-50%);width:min(560px,calc(100vw - 28px));background:var(--panel);border:1px solid var(--line);border-radius:15px;box-shadow:var(--shadow);padding:15px}.lifeos-search-head{display:flex;justify-content:space-between;align-items:center;font:500 11px 'DM Mono';letter-spacing:.12em;color:var(--muted);margin-bottom:13px}.lifeos-search-head button{border:0;background:transparent;color:var(--ink);font-size:20px}.lifeos-search-panel input{width:100%;background:var(--panel2);border:1px solid var(--line);border-radius:9px;padding:12px;outline:none}.lifeos-search-panel input:focus{border-color:var(--accent)}.lifeos-search-results{margin-top:9px;max-height:360px;overflow:auto}.lifeos-search-results button{display:grid;gap:3px;width:100%;text-align:left;border:0;border-radius:9px;padding:11px;background:transparent;color:var(--ink)}.lifeos-search-results button:hover{background:var(--panel2)}.lifeos-search-results small,.lifeos-search-results span,.lifeos-search-hint{color:var(--muted);font-size:12px}.lifeos-search-results strong{font-size:14px}.lifeos-search-results span{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.lifeos-search-empty{padding:24px;color:var(--muted);text-align:center;font-size:13px}.lifeos-search-hint{margin:11px 0 0;font:10px 'DM Mono';letter-spacing:.04em}.launchitem svg{width:28px;height:28px;display:block;margin:auto;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}.launchitem:hover svg{color:var(--accent)}`;
document.head.append(style);
function exportData() {
let desktopLayout = null, widgetLayout = null;
try { desktopLayout = JSON.parse(localStorage.getItem('lifeos_window_layout_v1') || 'null'); } catch {}
try { widgetLayout = JSON.parse(localStorage.getItem('lifeos_widget_layout_v1') || 'null'); } catch {}
const data = { app: 'Life OS', version: APP_VERSION, schemaVersion: 2, exportedAt: new Date().toISOString(), profile: profile(), memories: mems(), museum: museum(), settings: settings(), system: sys(), desktopLayout, widgetLayout };
const link = document.createElement('a');
link.href = URL.createObjectURL(new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' }));
link.download = `life-os-backup-${day()}.json`; link.click();
const state = settings(); state.lastBackup = new Date().toISOString(); save('lifeos_settings', state); renderAll(); toast('feedback.backup');
}
// The System panel uses inline onclick handlers, so expose this complete exporter.
window.exportData = exportData;
const CLOUD_KEYS = { profile: 'lifeos_profile', memories: 'lifeos_memories', museum: 'lifeos_museum', settings: 'lifeos_settings', system: 'lifeos_system' };
const OUTBOX_KEY = 'lifeos_sync_outbox_v1';
const CONFLICTS_KEY = 'lifeos_sync_conflicts_v1';
const META_KEY = 'lifeos_sync_meta_v1';
let cloudReady = false, applyingCloud = false, syncTimer = null, syncErrorShown = false, syncing = false, syncAgain = false;
let baseline = null, versions = null;
let retryTimer = null, retryAttempt = 0;
function clearRetry() { clearTimeout(retryTimer); retryTimer = null; }
function retryLater() {
clearRetry();
if (!cloudMode() || navigator.onLine === false) return;
const delay = Math.min(60000, 2000 * 2 ** Math.min(retryAttempt++, 5));
retryTimer = setTimeout(() => window.LifeOSCloud.retry().catch(() => {}), delay);
}
const readJson = (key, fallback) => { try { return JSON.parse(localStorage.getItem(key) || 'null') ?? fallback; } catch { return fallback; } };
const opKey = op => `${op.kind}:${op.id}`;
const outbox = () => readJson(OUTBOX_KEY, []);
const conflicts = () => readJson(CONFLICTS_KEY, []);
const meta = () => readJson(META_KEY, {});
function persistQueue(key, value) { localStorage.setItem(key, JSON.stringify(value)); emitSyncState(); }
function queueOperations(operations) {
const existing = new Map(outbox().map(op => [opKey(op), op])), queued = new Map();
operations.forEach(op => queued.set(opKey(op), { ...op, queuedAt: existing.get(opKey(op))?.queuedAt || new Date().toISOString() }));
persistQueue(OUTBOX_KEY, [...queued.values()]);
}
function dequeue(operation) { persistQueue(OUTBOX_KEY, outbox().filter(item => opKey(item) !== opKey(operation))); }
function setMeta(patch) { localStorage.setItem(META_KEY, JSON.stringify({ ...meta(), ...patch })); emitSyncState(); }
function syncState() {
const mode = window.LifeOSLocalDB?.mode?.() || 'unset', details = meta();
return { mode, online: navigator.onLine, phase: syncing ? 'syncing' : !navigator.onLine ? 'offline' : details.errorAt ? 'paused' : 'ready', pending: outbox().length, conflicts: conflicts().length, lastSyncAt: details.lastSyncAt || null, errorAt: details.errorAt || null, updateAvailable: Boolean(window.LifeOSPWA?.updateAvailable?.()) };
}
function emitSyncState() { if (typeof window.dispatchEvent === 'function' && typeof CustomEvent === 'function') window.dispatchEvent(new CustomEvent('lifeos-sync-state', { detail: syncState() })); }
const cloudMode = () => window.LifeOSLocalDB?.mode?.() === 'cloud';
const cloudFallback = { profile: {}, memories: [], museum: [], settings: {}, system: { schemaVersion: 2 } };
function cloudSnapshot() {
const snapshot = Object.fromEntries(Object.entries(CLOUD_KEYS).map(([field, key]) => {
try { return [field, JSON.parse(localStorage.getItem(key) || JSON.stringify(cloudFallback[field]))]; } catch { return [field, cloudFallback[field]]; }
}));
snapshot.system = { ...snapshot.system, schemaVersion: 2 };
return snapshot;
}
function hasLocalLife(state) { return state.memories.length || state.museum.length || Object.keys(state.profile).length || Object.keys(state.settings).length > 2 || state.system?.tasksBoard?.goals?.length || state.system?.tasksBoard?.tasks?.length; }
function applyCloudState(state) {
state = { ...state, system: { ...(state.system || {}), schemaVersion: 2 } };
applyingCloud = true;
Object.entries(CLOUD_KEYS).forEach(([field, key]) => localStorage.setItem(key, JSON.stringify(state[field] ?? cloudFallback[field])));
applyingCloud = false;
todayDraft = null; window.renderIcons?.(); window.renderAll?.(); window.applyLanguage?.(); window.applyDesktopPreferences?.();
}
const clone = value => JSON.parse(JSON.stringify(value));
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
function parts(state) {
const { tasksBoard, ...system } = state.system || {};
return { profile: state.profile || {}, settings: state.settings || {}, system,
memories: state.memories || [], museum: state.museum || [],
goals: tasksBoard?.goals || [], tasks: tasksBoard?.tasks || [] };
}
function record(state, kind, id) {
const group = parts(state)[kind];
return Array.isArray(group) ? group.find(item => item.id === id) || null : group;
}
function replaceRecord(state, kind, id, value) {
const next = clone(state), board = next.system.tasksBoard ||= { goals: [], tasks: [] };
if (['goals', 'tasks'].includes(kind)) board[kind] = [...board[kind].filter(item => item.id !== id), ...(value ? [value] : [])];
else if (['memories', 'museum'].includes(kind)) next[kind] = [...next[kind].filter(item => item.id !== id), ...(value ? [value] : [])];
else if (kind === 'system') next.system = { ...(value || {}), tasksBoard: board };
else next[kind] = value;
return next;
}
function changes(from, to) {
const before = parts(from), after = parts(to), operations = [];
for (const kind of ['profile', 'settings', 'system']) {
if (!same(before[kind], after[kind])) operations.push({ kind, id: 'value', value: after[kind], baseVersion: versions[kind].value || 0 });
}
for (const kind of ['memories', 'goals', 'tasks', 'museum']) {
const old = new Map(before[kind].map(item => [item.id, item]));
const current = new Map(after[kind].map(item => [item.id, item]));
for (const id of new Set([...old.keys(), ...current.keys()])) {
if (!id || same(old.get(id), current.get(id))) continue;
operations.push({ kind, id, value: current.get(id) || null, baseVersion: versions[kind][id] || 0 });
}
}
return operations;
}
function saveBaseline() {
localStorage.setItem('lifeos_cloud_baseline_v3', JSON.stringify({ state: baseline, versions }));
}
async function post(url, value) {
return fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(value) });
}
async function resolveConflict(op) {
const response = await fetch('/api/lifeos-state', { cache: 'no-store' });
if (!response.ok) throw new Error('conflict fetch failed');
const latest = await response.json();
const remote = record(latest.state, op.kind, op.id);
localStorage.setItem('lifeos_sync_conflict_backup_v1', JSON.stringify({ exportedAt: new Date().toISOString(), state: cloudSnapshot() }));
const item = { key: opKey(op), kind: op.kind, recordId: op.id, local: op.value, remote, remoteVersion: latest.versions[op.kind][op.id] || 0, detectedAt: new Date().toISOString() };
const pending = conflicts().filter(conflict => conflict.key !== item.key);
persistQueue(CONFLICTS_KEY, [...pending, item]);
baseline = replaceRecord(baseline, op.kind, op.id, remote);
versions[op.kind][op.id] = latest.versions[op.kind][op.id] || 0;
dequeue(op);
saveBaseline();
}
async function uploadCloudState() {
if (!cloudReady || syncing) { syncAgain = true; return; }
if (!cloudMode() || navigator.onLine === false) { emitSyncState(); return; }
syncing = true;
emitSyncState();
try {
do {
syncAgain = false;
const blocked = new Set(conflicts().map(item => item.key));
const operations = changes(baseline, cloudSnapshot()).filter(op => !blocked.has(opKey(op)));
queueOperations(operations);
for (const op of operations) {
if (!cloudMode()) return;
const response = await post('/api/lifeos-sync', op);
if (response.status === 409) { await resolveConflict(op); break; }
if (!response.ok) throw new Error('sync failed');
const result = await response.json();
baseline = replaceRecord(baseline, op.kind, op.id, op.value);
versions[op.kind][op.id] = result.version;
dequeue(op);
saveBaseline();
}
} while (syncAgain || changes(baseline, cloudSnapshot()).some(op => !conflicts().some(conflict => conflict.key === opKey(op))));
syncErrorShown = false;
retryAttempt = 0; clearRetry();
setMeta({ lastSyncAt: new Date().toISOString(), errorAt: null });
} catch (error) {
setMeta({ errorAt: new Date().toISOString() });
retryLater();
throw error;
} finally { syncing = false; emitSyncState(); }
}
function scheduleCloudSync() {
if (!cloudMode() || !cloudReady || applyingCloud) return;
queueOperations(changes(baseline, cloudSnapshot()).filter(op => !conflicts().some(item => item.key === opKey(op))));
clearTimeout(syncTimer);
if (navigator.onLine === false) return;
syncTimer = setTimeout(() => uploadCloudState().catch(() => {
if (!syncErrorShown) { syncErrorShown = true; toast('addon.syncPaused'); }
}), 450);
}
function resolveSavedConflict(key, choice) {
const item = conflicts().find(conflict => conflict.key === key);
if (!item || !baseline || !versions) return;
baseline = replaceRecord(baseline, item.kind, item.recordId, item.remote);
versions[item.kind][item.recordId] = item.remoteVersion || 0;
if (choice === 'cloud') {
const restored = replaceRecord(cloudSnapshot(), item.kind, item.recordId, item.remote);
applyingCloud = true;
const field = ['goals', 'tasks'].includes(item.kind) ? 'system' : item.kind;
localStorage.setItem(CLOUD_KEYS[field], JSON.stringify(restored[field]));
applyingCloud = false;
window.renderAll?.();
}
persistQueue(CONFLICTS_KEY, conflicts().filter(conflict => conflict.key !== key));
saveBaseline();
if (choice === 'local') scheduleCloudSync();
}
function migrationPrompt(state) {
const dialog = document.createElement('div');
dialog.id = 'lifeos-cloud-migration';
dialog.innerHTML = `<div class="lifeos-cloud-card"><div class="eyebrow">${t('addon.syncReady')}</div><h2>${t('addon.migrateQuestion')}</h2><p>${t('addon.migrateBody')}</p><div class="actions"><button class="primary" data-cloud="move">${t('addon.migrate')}</button><button class="secondary" data-cloud="empty">${t('addon.fresh')}</button></div></div>`;
document.body.append(dialog);
dialog.querySelector('[data-cloud="move"]').addEventListener('click', async () => { dialog.remove(); try { await initializeCloud(state); toast('addon.migrated'); } catch { toast('addon.cloudUnavailable'); } });
dialog.querySelector('[data-cloud="empty"]').addEventListener('click', async () => { dialog.remove(); applyCloudState(cloudFallback); try { await initializeCloud(cloudFallback); } catch { toast('addon.cloudUnavailable'); } });
}
async function initializeCloud(state) {
const response = await post('/api/lifeos-initialize', { state });
if (!response.ok) throw new Error('cloud initialization failed');
const data = await response.json();
baseline = clone(data.state); versions = data.versions; cloudReady = true; saveBaseline();
retryAttempt = 0; clearRetry(); setMeta({ lastSyncAt: new Date().toISOString(), errorAt: null });
}
async function startCloudSync() {
if (!cloudMode()) return;
try {
const response = await fetch('/api/lifeos-state', { cache: 'no-store' });
if (response.status === 401) {
location.assign('/signin-with-chatgpt?return_to=/');
return;
}
if (!response.ok) throw new Error('cloud unavailable');
const { state, versions: cloudVersions } = await response.json();
if (!cloudMode()) return;
const local = cloudSnapshot();
if (state) {
if (hasLocalLife(local)) localStorage.setItem('lifeos_precloud_backup_v1', JSON.stringify({ exportedAt: new Date().toISOString(), state: local }));
let previous = null;
try { previous = JSON.parse(localStorage.getItem('lifeos_cloud_baseline_v3') || 'null'); } catch {}
const pending = previous?.state ? changesFromSaved(previous.state, local) : [];
baseline = clone(state); versions = cloudVersions;
applyCloudState(state);
let hadConflict = false;
for (const op of pending) {
if (!same(record(previous.state, op.kind, op.id), record(state, op.kind, op.id))) {
localStorage.setItem('lifeos_sync_conflict_backup_v1', JSON.stringify({ exportedAt: new Date().toISOString(), state: local }));
hadConflict = true;
const item = { key: opKey(op), kind: op.kind, recordId: op.id, local: op.value, remote: record(state, op.kind, op.id), remoteVersion: cloudVersions[op.kind][op.id] || 0, detectedAt: new Date().toISOString() };
persistQueue(CONFLICTS_KEY, [...conflicts().filter(conflict => conflict.key !== item.key), item]);
}
const restored = replaceRecord(cloudSnapshot(), op.kind, op.id, op.value);
applyingCloud = true;
const field = ['goals', 'tasks'].includes(op.kind) ? 'system' : op.kind;
localStorage.setItem(CLOUD_KEYS[field], JSON.stringify(restored[field]));
applyingCloud = false;
}
cloudReady = true; saveBaseline();
if (pending.length) await uploadCloudState();
else { retryAttempt = 0; clearRetry(); setMeta({ lastSyncAt: new Date().toISOString(), errorAt: null }); }
toast(hadConflict ? 'addon.syncConflict' : 'addon.cloudRestored');
} else if (hasLocalLife(local)) {
migrationPrompt(local);
} else {
await initializeCloud(cloudFallback);
}
} catch {
setMeta({ errorAt: new Date().toISOString() });
retryLater();
if (!syncErrorShown) { syncErrorShown = true; toast('addon.cloudUnavailable'); }
}
}
function changesFromSaved(from, to) {
const savedVersions = versions;
versions = { profile: {}, settings: {}, system: {}, memories: {}, goals: {}, tasks: {}, museum: {} };
const result = changes(from, to);
versions = savedVersions;
return result;
}
const originalSetItem = Storage.prototype.setItem;
Storage.prototype.setItem = function(key, value) {
originalSetItem.call(this, key, value);
if (this === localStorage && Object.values(CLOUD_KEYS).includes(key)) scheduleCloudSync();
};
const cloudStyle = document.createElement('style');
cloudStyle.textContent = `#lifeos-cloud-migration{position:fixed;inset:0;z-index:9000;background:#071008b8;display:grid;place-items:center;padding:20px}.lifeos-cloud-card{width:min(470px,100%);background:var(--panel);border:1px solid var(--line);border-radius:16px;padding:25px;box-shadow:var(--shadow)}.lifeos-cloud-card h2{margin:10px 0;font-size:25px;letter-spacing:-.04em}.lifeos-cloud-card p{color:var(--muted);line-height:1.65;margin:0 0 20px}`;
document.head.append(cloudStyle);
function stopCloudSync() {
cloudReady = false;
syncAgain = false;
clearTimeout(syncTimer);
clearRetry();
emitSyncState();
}
window.LifeOSCloud = { start: startCloudSync, stop: stopCloudSync, retry: () => { if (!cloudMode()) return Promise.resolve(); clearRetry(); return cloudReady ? uploadCloudState() : startCloudSync(); }, status: syncState, conflicts, resolveConflict: resolveSavedConflict };
if (cloudMode()) startCloudSync();
window.addEventListener('online', () => { emitSyncState(); if (cloudMode()) window.LifeOSCloud.retry().catch(() => {}); });
window.addEventListener('offline', () => { clearRetry(); emitSyncState(); });
const syncText = {
en: { title:'SYNC CENTER', local:'Local only', ready:'Up to date', syncing:'Syncing', offline:'Offline', paused:'Sync paused', pending:'Pending changes', conflicts:'Conflicts', last:'Last synced', never:'Not yet', retry:'RETRY NOW', close:'CLOSE', update:'UPDATE READY', install:'RESTART & UPDATE', noConflicts:'No conflicts need your attention.', conflictHelp:'Choose which version to keep. Nothing is discarded until you decide.', localVersion:'THIS DEVICE', cloudVersion:'CLOUD', keepLocal:'KEEP THIS DEVICE', keepCloud:'KEEP CLOUD', mode:'Storage mode', status:'Sync status' },
'zh-CN': { title:'同步中心', local:'仅本地使用', ready:'已是最新', syncing:'正在同步', offline:'当前离线', paused:'同步已暂停', pending:'待同步更改', conflicts:'同步冲突', last:'上次同步', never:'尚未同步', retry:'立即重试', close:'关闭', update:'发现新版本', install:'重启并更新', noConflicts:'没有需要处理的冲突。', conflictHelp:'请选择保留哪个版本;在你决定之前,系统不会丢弃任何一方的数据。', localVersion:'本设备版本', cloudVersion:'云端版本', keepLocal:'保留本设备', keepCloud:'保留云端', mode:'存储模式', status:'同步状态' },
'zh-HK': { title:'同步中心', local:'只在本機使用', ready:'已是最新', syncing:'正在同步', offline:'目前離線', paused:'同步已暫停', pending:'待同步變更', conflicts:'同步衝突', last:'上次同步', never:'尚未同步', retry:'立即重試', close:'關閉', update:'發現新版本', install:'重新啟動並更新', noConflicts:'沒有需要處理的衝突。', conflictHelp:'請選擇保留哪個版本;決定前不會捨棄任何一方的資料。', localVersion:'本機版本', cloudVersion:'雲端版本', keepLocal:'保留本機', keepCloud:'保留雲端', mode:'儲存模式', status:'同步狀態' },
'zh-MO': { title:'同步中心', local:'只在本機使用', ready:'已是最新', syncing:'正在同步', offline:'目前離線', paused:'同步已暫停', pending:'待同步變更', conflicts:'同步衝突', last:'上次同步', never:'尚未同步', retry:'立即重試', close:'關閉', update:'發現新版本', install:'重新啟動並更新', noConflicts:'沒有需要處理的衝突。', conflictHelp:'請選擇保留哪個版本;決定前不會捨棄任何一方的資料。', localVersion:'本機版本', cloudVersion:'雲端版本', keepLocal:'保留本機', keepCloud:'保留雲端', mode:'儲存模式', status:'同步狀態' },
'zh-TW': { title:'同步中心', local:'僅在本機使用', ready:'已是最新', syncing:'正在同步', offline:'目前離線', paused:'同步已暫停', pending:'待同步變更', conflicts:'同步衝突', last:'上次同步', never:'尚未同步', retry:'立即重試', close:'關閉', update:'發現新版本', install:'重新啟動並更新', noConflicts:'沒有需要處理的衝突。', conflictHelp:'請選擇保留哪個版本;決定前不會捨棄任何一方的資料。', localVersion:'本機版本', cloudVersion:'雲端版本', keepLocal:'保留本機', keepCloud:'保留雲端', mode:'儲存模式', status:'同步狀態' }
};
const syncCopy = () => syncText[window.LifeI18n?.language?.()] || syncText.en;
const stateLabel = state => state.mode === 'local' ? syncCopy().local : syncCopy()[state.phase] || syncCopy().ready;
const when = value => value ? new Intl.DateTimeFormat(window.LifeI18n?.locale?.() || 'en-US', { dateStyle:'medium', timeStyle:'short' }).format(new Date(value)) : syncCopy().never;
const pretty = value => value === null ? '∅' : JSON.stringify(value, null, 2);
function syncIndicator() {
let button = document.querySelector('#lifeos-sync-indicator');
if (button) return button;
button = document.createElement('button'); button.id = 'lifeos-sync-indicator'; button.type = 'button'; button.addEventListener('click', openSyncCenter);
const taskbar = document.querySelector('.taskbar'), clockNode = taskbar?.querySelector('.clock');
if (taskbar) taskbar.insertBefore(button, clockNode || null);
return button;
}
function renderSyncSurfaces() {
const state = syncState(), copy = syncCopy(), button = syncIndicator();
if (button) {
const className = `sync-indicator ${state.phase} ${state.conflicts || state.updateAvailable ? 'attention' : ''}`;
const markup = `<span aria-hidden="true"></span><b>${state.conflicts || state.pending || (state.updateAvailable ? '↑' : '')}</b>`;
const title = state.updateAvailable ? copy.update : `${copy.status}: ${stateLabel(state)}`;
if (button.className !== className) button.className = className;
if (button.innerHTML !== markup) button.innerHTML = markup;
if (button.title !== title) button.title = title;
if (button.getAttribute('aria-label') !== title) button.setAttribute('aria-label', title);
}
const dataPanel = document.querySelector('#content-system [data-settings-group="data"]');
if (dataPanel && !dataPanel.querySelector('[data-sync-summary]')) {
dataPanel.insertAdjacentHTML('beforeend', `<section class="sync-summary" data-sync-summary><div class="eyebrow">${copy.title}</div><button class="secondary" type="button" data-open-sync></button></section>`);
}
const summary = dataPanel?.querySelector('[data-sync-summary] button');
const summaryText = `${stateLabel(state)} · ${copy.pending} ${state.pending} · ${copy.conflicts} ${state.conflicts}`;
if (summary && summary.textContent !== summaryText) summary.textContent = summaryText;
const center = document.querySelector('#lifeos-sync-center');
if (center) fillSyncCenter(center);
}
function fillSyncCenter(root) {
const state = syncState(), copy = syncCopy(), items = conflicts();
const fingerprint = JSON.stringify([state, copy, items]);
if (root.dataset.syncFingerprint === fingerprint) return;
root.dataset.syncFingerprint = fingerprint;
root.querySelector('.sync-center-card').innerHTML = `<button class="modal-close" data-close-sync aria-label="${copy.close}">×</button><div class="eyebrow">${copy.title}</div><h2>${stateLabel(state)}</h2><dl class="sync-facts"><div><dt>${copy.mode}</dt><dd>${state.mode === 'local' ? copy.local : 'Cloud'}</dd></div><div><dt>${copy.pending}</dt><dd>${state.pending}</dd></div><div><dt>${copy.conflicts}</dt><dd>${state.conflicts}</dd></div><div><dt>${copy.last}</dt><dd>${when(state.lastSyncAt)}</dd></div></dl><div class="actions">${state.mode === 'cloud' ? `<button class="primary" data-retry-sync>${copy.retry}</button>` : ''}${state.updateAvailable ? `<button class="primary" data-apply-update>${copy.install}</button>` : ''}<button class="secondary" data-close-sync>${copy.close}</button></div><div class="sync-conflict-list">${items.length ? `<p class="sync-help">${copy.conflictHelp}</p>${items.map(item => `<article class="sync-conflict" data-conflict-key="${escapeHtml(item.key)}"><header><strong>${escapeHtml(item.kind)}</strong><span>${when(item.detectedAt)}</span></header><div class="sync-compare"><section><div class="eyebrow">${copy.localVersion}</div><pre>${escapeHtml(pretty(item.local))}</pre><button class="secondary" data-conflict-choice="local">${copy.keepLocal}</button></section><section><div class="eyebrow">${copy.cloudVersion}</div><pre>${escapeHtml(pretty(item.remote))}</pre><button class="secondary" data-conflict-choice="cloud">${copy.keepCloud}</button></section></div></article>`).join('')}` : `<p class="sync-empty">${copy.noConflicts}</p>`}</div>`;
}
function openSyncCenter() {
let root = document.querySelector('#lifeos-sync-center');
if (!root) { root = document.createElement('div'); root.id = 'lifeos-sync-center'; root.className = 'modal'; root.innerHTML = '<div class="sync-center-card modalbox" role="dialog" aria-modal="true"></div>'; document.body.append(root); }
fillSyncCenter(root);
}
document.addEventListener('click', event => {
if (event.target.closest('[data-open-sync]')) openSyncCenter();
if (event.target.closest('[data-close-sync]') || (event.target.id === 'lifeos-sync-center')) document.querySelector('#lifeos-sync-center')?.remove();
if (event.target.closest('[data-retry-sync]')) window.LifeOSCloud.retry().catch(() => {});
if (event.target.closest('[data-apply-update]')) window.LifeOSPWA?.applyUpdate?.();
const choice = event.target.closest('[data-conflict-choice]');
if (choice) { const key = choice.closest('[data-conflict-key]')?.dataset.conflictKey; if (key) { resolveSavedConflict(key, choice.dataset.conflictChoice); const center = document.querySelector('#lifeos-sync-center'); if (center) fillSyncCenter(center); } }
});
let waitingWorker = null, reloadingForUpdate = false;
window.LifeOSPWA = {
updateAvailable: () => Boolean(waitingWorker),
applyUpdate: () => waitingWorker?.postMessage({ type:'SKIP_WAITING' }),
register: async () => {
if (!('serviceWorker' in navigator)) return;
const registration = await navigator.serviceWorker.register('/service-worker.js');
const inspect = worker => { if (worker?.state === 'installed' && navigator.serviceWorker.controller) { waitingWorker = worker; emitSyncState(); renderSyncSurfaces(); } };
if (registration.waiting) inspect(registration.waiting);
registration.addEventListener('updatefound', () => { const worker = registration.installing; worker?.addEventListener('statechange', () => inspect(worker)); });
const wasControlled = Boolean(navigator.serviceWorker.controller);
navigator.serviceWorker.addEventListener('controllerchange', () => { if (!wasControlled || reloadingForUpdate) return; reloadingForUpdate = true; location.reload(); });
}
};
window.openSyncCenter = openSyncCenter;
window.addEventListener('lifeos-sync-state', renderSyncSurfaces);
window.addEventListener('load', () => { renderSyncSurfaces(); window.LifeOSPWA.register().catch(() => {}); });
const syncStyle = document.createElement('style');
syncStyle.textContent = `.sync-indicator{position:relative;width:40px;height:40px;border:0;border-radius:11px;background:transparent;color:var(--muted)}.sync-indicator>span{display:block;width:10px;height:10px;margin:auto;border:2px solid currentColor;border-radius:50%}.sync-indicator.syncing>span{border-top-color:transparent;animation:sync-spin .8s linear infinite}.sync-indicator.offline,.sync-indicator.paused,.sync-indicator.attention{color:#f3a36f}.sync-indicator b{position:absolute;right:3px;top:2px;min-width:15px;height:15px;padding:0 3px;border-radius:8px;background:var(--accent);color:var(--bg);font:500 10px/15px 'DM Mono'}@keyframes sync-spin{to{transform:rotate(360deg)}}.sync-summary .secondary{font-size:12px;line-height:1.4}.sync-center-card{width:min(760px,calc(100vw - 28px));max-height:min(760px,calc(100vh - 28px));overflow:auto}.sync-center-card h2{font-size:24px;letter-spacing:-.04em}.sync-facts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;margin:18px 0}.sync-facts div{padding:13px;border:1px solid var(--line);border-radius:10px;background:var(--panel2)}.sync-facts dt{color:var(--muted);font-size:12px}.sync-facts dd{margin:5px 0 0;font-size:14px;overflow-wrap:anywhere}.sync-help,.sync-empty{margin:22px 0 0;color:var(--muted);font-size:14px;line-height:1.6}.sync-conflict{margin-top:13px;padding-top:13px;border-top:1px solid var(--line)}.sync-conflict header{display:flex;justify-content:space-between;gap:12px}.sync-conflict header span{color:var(--muted);font-size:12px}.sync-compare{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:10px}.sync-compare section{min-width:0;padding:12px;border:1px solid var(--line);border-radius:10px}.sync-compare pre{max-height:190px;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere;color:var(--muted);font:12px/1.5 'DM Mono'}.sync-compare button{width:100%}@media(max-width:650px){.sync-indicator{width:32px;padding:0}.sync-facts,.sync-compare{grid-template-columns:1fr}.sync-center-card{max-height:calc(100vh - 18px)}.sync-conflict header{display:grid}}`;
document.head.append(syncStyle);
new MutationObserver(() => { wireToday(); wireLanguageControl(); renderSyncSurfaces(); }).observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['title'] });
wireToday();
wireLanguageControl();
document.addEventListener('click', e => { if (e.target.closest('#content-today .primary')) clearDraftAfterSave(); });
document.addEventListener('click', e => {
if (e.target.closest('.launchitem')) document.querySelector('#launcher')?.classList.add('hidden');
});
document.addEventListener('keydown', e => {
const mod = e.ctrlKey || e.metaKey;
if (mod && e.key.toLowerCase() === 'k') { e.preventDefault(); toggleLauncher(); }
if (mod && e.key.toLowerCase() === 'f') { e.preventDefault(); openSearch(); }
if (mod && e.key.toLowerCase() === 's' && document.querySelector('#entry')) { e.preventDefault(); archiveToday(); }
if (e.altKey && /^[0-9]$/.test(e.key)) { e.preventDefault(); openApp(appIds[e.key === '0' ? 9 : Number(e.key) - 1]); }
if (e.key === 'Escape') { closeSearch(); document.querySelector('#launcher')?.classList.add('hidden'); document.querySelector('#calendar')?.classList.add('hidden'); document.querySelector('#life-context')?.remove(); }
if (e.key === 'Escape') document.querySelector('#lifeos-sync-center')?.remove();
});
})();