Files
Life-OS/public/i18n-renderers.js
T

215 lines
46 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.
/* Render-time localisation layer. User-created records are deliberately never translated. */
(() => {
const t = (key, values) => LifeI18n.t(key, values);
const locale = () => LifeI18n.locale();
const weekday = value => new Intl.DateTimeFormat(locale(), { weekday: 'long' }).format(new Date(value + 'T12:00:00'));
const uiDate = value => new Intl.DateTimeFormat(locale(), { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' }).format(new Date(value + 'T12:00:00'));
const short = value => new Intl.DateTimeFormat(locale(), { month: 'short', day: 'numeric' }).format(new Date(value + 'T12:00:00')).toUpperCase();
const weather = mood => t(`weather.${mood}`);
const rootModal = () => document.getElementById('modal');
const linkedTasks = () => (sys().tasksBoard?.tasks || []).filter(item=>!item.trashedAt);
const escAttr = value => esc(value).replace(/\"/g, '"');
const titleOf = memory => memory.title?.trim() || memory.text?.trim().split('\n')[0].slice(0, 64) || t('timeline.untitled');
const localizedFilmField = (memory, field) => { const index = LifeI18n.supported.reduce((found, code) => found >= 0 ? found : LifeI18n.dictionaries[code]?.prompt.films.findIndex(film => film.title === memory.filmTitle), -1); return index < 0 ? (memory[field] || '') : (LifeI18n.dictionaries[lang()]?.prompt.films[index]?.[field === 'filmTitle' ? 'title' : 'subtitle'] || memory[field] || ''); };
const tagList = value => [...new Set(String(value || '').split(/[,,]/).map(tag => tag.trim()).filter(Boolean))].slice(0, 12);
const memoryMetaFields = memory => `<div class="memory-meta-form"><label>${t('memory.tags')}<input id="memory-tags" maxlength="180" value="${esc((memory?.tags || []).join(', '))}" placeholder="${t('memory.tagsPlaceholder')}"></label><label>${t('memory.place')}<input id="memory-place" maxlength="100" value="${esc(memory?.location || '')}" placeholder="${t('memory.placePlaceholder')}"></label><label>${t('memory.linkTask')}<select id="memory-task"><option value="">${t('memory.noTask')}</option>${linkedTasks().map(task => `<option value="${esc(task.id)}" ${task.id === memory?.taskId ? 'selected' : ''}>${esc(task.title)}</option>`).join('')}</select></label></div>`;
window.appName = id => t(`app.${id}`);
window.moodName = weather;
window.fmtDate = uiDate;
window.shortDate = short;
window.longest = records => {
const dates = [...new Set(records.map(item => item.date))].sort(); let best = 0, run = 0, previous = '';
for (const date of dates) { run = previous && (new Date(date) - new Date(previous)) / 864e5 === 1 ? run + 1 : 1; best = Math.max(best, run); previous = date; }
return best;
};
window.streak = records => {
const dates = new Set(records.map(item => item.date)); let count = 0, date = new Date();
while (dates.has(`${date.getFullYear()}-${String(date.getMonth()+1).padStart(2,'0')}-${String(date.getDate()).padStart(2,'0')}`)) { count++; date.setDate(date.getDate()-1); }
return count;
};
window.addMemoryForDate = date => { todayTargetDate = date; todayDraft = null; todayTitleDraft = null; openApp('today'); const container = document.querySelector('#content-today'); if (container) window.today(container); };
window.closeModal = () => { rootModal().innerHTML = ''; };
window.applyLanguage = () => { document.documentElement.lang = LifeI18n.locale(); document.documentElement.dir = lang() === 'ar' ? 'rtl' : 'ltr'; document.title = t('shell.pageTitle'); const brand = document.querySelector('#desktop-brand'), launcher = document.querySelector('#life-launcher'), boot = document.querySelector('#boot span'); if (brand) brand.textContent = t('shell.brand'); if (launcher) launcher.textContent = t('shell.life'); if (boot) boot.textContent = t('shell.initializing'); if (settings().wallpaper) applyWallpaper(settings().wallpaper); };
window.applyWallpaper = wallpaper => { if (!wallpaper?.url) return; const desktop = document.querySelector('#desktop'); desktop.style.backgroundImage = `linear-gradient(120deg,color-mix(in srgb,var(--bg) 68%,transparent),color-mix(in srgb,var(--bg) 36%,transparent)),url('${wallpaper.url}')`; desktop.style.backgroundSize = 'cover'; desktop.style.backgroundPosition = 'center'; desktop.title = t('shell.wallpaperTitle', { title: wallpaper.title || t('wallpaper.dailyImage') }); };
window.today = container => {
const entryDate = todayTargetDate || day(), memory = mems().find(item => item.date === entryDate && item.kind !== 'moment');
if (todayDraft === null) { selectedMood = memory?.mood || 'cloudy'; selectedEnergy = memory?.energy || 3; }
const film = filmFor(selectedMood, selectedEnergy), text = todayDraft === null ? (memory?.text || '') : todayDraft;
container.innerHTML = `<div class="eyebrow">${weekday(entryDate).toUpperCase()}</div><h1>${uiDate(entryDate)}</h1><p class="sub">${t('today.prompt')} ${entryDate !== day() ? `<button class="text-link" onclick="todayTargetDate=null;todayDraft=null;todayTitleDraft=null;renderAll()">${t('today.backToToday')}</button>` : ''}</p><div class="today-grid"><div><textarea id="entry" class="entry" placeholder="${t('today.placeholder')}" oninput="todayDraft=this.value">${esc(text)}</textarea><label class="memory-title-field">${t('memory.title')}<input id="memory-title" maxlength="120" value="${escAttr(todayTitleDraft === null ? (memory?.title || '') : todayTitleDraft)}" oninput="todayTitleDraft=this.value" placeholder="${t('memory.titlePlaceholder')}"></label>${memoryMetaFields(memory)}<div class="actions"><button class="primary" onclick="archiveToday()">${t(entryDate === day() ? (memory ? 'today.update' : 'today.archive') : (memory ? 'today.updateDate' : 'today.archiveDate'))}</button><span id="saveStatus" class="status"></span></div></div><aside><div class="eyebrow">${t('today.weather')}</div><div class="choices">${['clear','light','cloudy','rain','storm'].map(item => `<button class="chip ${item === selectedMood ? 'selected' : ''}" onclick="setMood('${item}')">${weather(item)}</button>`).join('')}</div><div class="eyebrow" style="margin-top:22px">${t('today.energy')}</div><div class="energy">${[1,2,3,4,5].map(item => `<button class="${item === selectedEnergy ? 'selected' : ''}" onclick="setEnergy(${item})">${item}</button>`).join('')}</div><div class="film"><div class="eyebrow">${t('today.film')}</div><div class="film-title">${film.filmTitle}</div><div class="sub">${film.filmSubtitle}</div><p class="film-copy">“${film.filmLine}”</p></div></aside></div>`;
};
window.archiveToday = () => {
const entryDate = todayTargetDate || day(), status = document.querySelector('#saveStatus');
const draft = { date: entryDate, text: document.querySelector('#entry')?.value.trim() || '', title: document.querySelector('#memory-title')?.value.trim() || '', mood: selectedMood, energy: selectedEnergy, tags: tagList(document.querySelector('#memory-tags')?.value), location: document.querySelector('#memory-place')?.value.trim() || '', taskId: document.querySelector('#memory-task')?.value || '', replace: true };
status.textContent = t('today.archiving');
setTimeout(() => { todayDraft = null; todayTitleDraft = null; window.LifeOSActions.createMemory(draft); }, 360);
};
// Moments share record-level sync, search, favorites and backup with daily summaries.
const MOMENT_DRAFT = 'lifeos_moment_draft_v1';
const readMomentDraft = () => { try { return JSON.parse(localStorage.getItem(MOMENT_DRAFT) || '{}'); } catch { return {}; } };
window.openQuickMemory = (date = day()) => {
const draft = readMomentDraft();
rootModal().innerHTML = `<div class="modal" onclick="if(event.target===this) closeModal()"><form class="modalbox moment-form" role="dialog" aria-modal="true" aria-labelledby="moment-heading" onsubmit="saveQuickMemory(event)" oninput="saveQuickDraft(this)"><button type="button" class="modal-close" onclick="closeModal()" aria-label="${t('common.close')}">×</button><div class="eyebrow">${t('moments.label')}</div><h2 id="moment-heading">${t('moments.title')}</h2><p class="sub">${t('moments.hint')}</p><label>${t('memory.note')}<textarea name="text" rows="5" maxlength="20000" placeholder="${t('moments.placeholder')}">${esc(draft.text || '')}</textarea></label><label>${t('memory.title')}<input name="title" maxlength="120" value="${escAttr(draft.title || '')}" placeholder="${t('memory.titlePlaceholder')}"></label><div class="moment-fields"><label>${t('calendar.day')}<input name="date" type="date" required value="${escAttr(draft.date || date)}"></label><label>${t('memory.tags')}<input name="tags" maxlength="180" value="${escAttr(draft.tags || '')}" placeholder="${t('memory.tagsPlaceholder')}"></label></div><p class="moment-draft-note">${t('moments.draft')}</p><div class="actions"><button class="primary" type="submit">${t('moments.save')}</button><button class="secondary" type="button" onclick="closeModal()">${t('common.cancel')}</button></div><p class="moment-error" role="alert"></p></form></div>`;
rootModal().querySelector('textarea')?.focus();
};
window.saveQuickDraft = form => {
const field = name => form.elements.namedItem(name).value;
localStorage.setItem(MOMENT_DRAFT, JSON.stringify({ text:field('text'), title:field('title'), date:field('date'), tags:field('tags') }));
};
window.saveQuickMemory = event => {
event.preventDefault(); const form = event.currentTarget, field = name => form.elements.namedItem(name).value;
try {
window.LifeOSActions.createMemory({ kind:'moment', date:field('date'), title:field('title'), text:field('text'), tags:tagList(field('tags')) });
localStorage.removeItem(MOMENT_DRAFT); closeModal(); toast(t('moments.saved'));
} catch { form.querySelector('.moment-error').textContent = t('moments.invalid'); }
};
const originalToday = window.today;
window.today = container => {
originalToday(container);
const date = todayTargetDate || day(), moments = mems().filter(item => item.date === date && item.kind === 'moment');
container.insertAdjacentHTML('beforeend', `<section class="moment-day"><header><div><div class="eyebrow">${t('moments.label')}</div><h2>${t('moments.count', { count:moments.length })}</h2></div><button class="secondary" onclick="openQuickMemory('${date}')">+ ${t('moments.title')}</button></header>${moments.length ? `<div class="moment-list">${moments.map(item => `<button class="moment-item" data-id="${escAttr(item.id)}" onclick="detail(this.dataset.id)"><span>${LifeI18n.date(item.createdAt || item.date,{hour:'2-digit',minute:'2-digit'})}</span><strong>${esc(titleOf(item))}</strong><p>${esc(item.text)}</p></button>`).join('')}</div>` : `<p class="sub">${t('moments.empty')}</p>`}</section>`);
};
const quickButton = document.createElement('button');
quickButton.type = 'button'; quickButton.className = 'moment-desktop-button'; quickButton.addEventListener('click', () => window.openQuickMemory());
document.querySelector('#desktop')?.append(quickButton);
const previousLanguage = window.applyLanguage;
window.applyLanguage = () => { previousLanguage(); quickButton.textContent = `+ ${t('moments.title')}`; };
const momentStyle = document.createElement('style');
momentStyle.textContent = `.moment-desktop-button{position:absolute;top:20px;left:150px;z-index:2;border:1px solid var(--line);border-radius:9px;padding:8px 12px;background:var(--panel);color:var(--ink);font-size:14px}.moment-form{width:min(520px,calc(100vw - 28px));max-height:calc(100dvh - 28px);overflow:auto;display:grid;gap:12px}.moment-form h2{font-size:24px;letter-spacing:-.03em}.moment-form label{display:grid;gap:6px;font-size:14px}.moment-form input,.moment-form textarea{width:100%;min-width:0;background:var(--panel2);border:1px solid var(--line);border-radius:9px;padding:10px;font-size:16px}.moment-form textarea{resize:vertical}.moment-fields{display:grid;grid-template-columns:1fr 1fr;gap:12px}.moment-draft-note{font-size:12px;color:var(--muted);margin:0}.moment-error{color:#eea27d;margin:0;font-size:14px}.moment-day{margin-top:24px;border-top:1px solid var(--line);padding-top:20px}.moment-day header{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:12px}.moment-day h2{font-size:18px;letter-spacing:0;margin:0}.moment-list{display:grid;gap:8px}.moment-item{text-align:start;display:grid;gap:5px;padding:14px;background:var(--panel2);border:1px solid var(--line);border-radius:10px}.moment-item>span{font-size:12px;color:var(--muted)}.moment-item>strong{font-size:16px;overflow-wrap:anywhere}.moment-item>p{font-size:14px;color:var(--muted);margin:0;white-space:pre-wrap;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden;overflow-wrap:anywhere}@media(max-width:650px){.moment-desktop-button{top:14px;left:140px}.moment-fields{grid-template-columns:1fr}}`;
document.head.append(momentStyle);
window.timeline = container => {
const all = mems(), tags = [...new Set(all.flatMap(item => item.tags || []))].sort((a,b) => a.localeCompare(b));
const query = window.timelineQuery || '', selectedTag = window.timelineTag || '';
const filtered = all.filter(memory => {
const task = linkedTasks().find(item => item.id === memory.taskId);
const haystack = [memory.title, memory.filmTitle, memory.text, memory.location, ...(memory.tags || []), task?.title].join(' ').toLocaleLowerCase();
return (!query || haystack.includes(query.toLocaleLowerCase())) && (!selectedTag || (memory.tags || []).includes(selectedTag));
});
const isSaved = memory => museum().some(item => item.memoryId === memory.id);
container.innerHTML = `<div class="eyebrow">${t('timeline.eyebrow')}</div><h1>${t('timeline.heading',{count:filtered.length,total:all.length})}</h1><div class="timeline-tools"><label class="timeline-search"><span class="sr-only">${t('timeline.search')}</span><input type="search" value="${esc(query)}" placeholder="${t('timeline.searchPlaceholder')}" oninput="setTimelineQuery(this.value)"></label><label class="timeline-tag-filter"><span class="sr-only">${t('timeline.filterTag')}</span><select onchange="setTimelineTag(this.value)"><option value="">${t('timeline.allTags')}</option>${tags.map(tag => `<option value="${esc(tag)}" ${tag === selectedTag ? 'selected' : ''}>${esc(tag)}</option>`).join('')}</select></label></div>${filtered.length ? `<div class="timeline">${filtered.map(memory => { const task = linkedTasks().find(item => item.id === memory.taskId); return `<article class="memory"><button class="memory-open" onclick="detail('${esc(memory.id)}')"><div class="date">${short(memory.date)} · ${memory.kind === 'moment' ? t('moments.label') : `${weather(memory.mood).toUpperCase()} · ${t('common.energy')} ${memory.energy}`}${isSaved(memory) ? ` · ★ ${t('timeline.favorite')}` : ''}</div><div class="mtitle">${esc(titleOf(memory))}</div><div class="snippet">${esc(memory.text || t('timeline.noNote'))}</div><div class="memory-badges">${memory.location ? `<span>⌖ ${esc(memory.location)}</span>` : ''}${task ? `<span>↗ ${esc(task.title)}</span>` : ''}${(memory.tags || []).map(tag => `<span># ${esc(tag)}</span>`).join('')}</div></button></article>`; }).join('')}</div>` : `<div class="empty">${all.length ? t('timeline.noMatches') : `${t('timeline.emptyTitle')}<br>${t('timeline.emptyBody')}`}</div>`}`;
};
window.museumApp = container => {
const saved = museum(), memories = mems();
container.innerHTML = `<div class="eyebrow">${t('museum.eyebrow')}</div><h1>${t('museum.title')}</h1><p class="sub">${t('museum.subtitle')}</p>${saved.length ? `<div class="museum">${saved.map((artifact,index) => { const memory = memories.find(item => item.id === artifact.memoryId); if (!memory) return ''; return `<button class="artifact" onclick="detail('${esc(memory.id)}')"><span>${t('museum.collection')} #${String(index + 1).padStart(2,'0')}</span><b>${esc(titleOf(memory))}</b><small>${LifeI18n.date(memory.date,{dateStyle:'medium'})} · ${t('museum.preserved')}</small></button>`; }).join('')}</div>` : `<div class="empty">${t('museum.empty')}</div>`}`;
};
window.setTimelineQuery = value => { window.timelineQuery = value; const field = document.querySelector('#content-timeline input[type=search]'); const start = field?.selectionStart; timeline(document.querySelector('#content-timeline')); const next = document.querySelector('#content-timeline input[type=search]'); next?.focus(); if (start !== undefined) next?.setSelectionRange(start,start); };
window.setTimelineTag = value => { window.timelineTag = value; timeline(document.querySelector('#content-timeline')); };
window.detail = id => {
const memory = mems().find(item => item.id === id); if (!memory) return;
const task = linkedTasks().find(item => item.id === memory.taskId), favorite = museum().some(item => item.memoryId === memory.id);
rootModal().innerHTML = `<div class="modal" onclick="if(event.target === this) closeModal()"><div class="modalbox" role="dialog" aria-modal="true" aria-labelledby="memory-detail-title"><button class="modal-close" type="button" onclick="closeModal()" aria-label="${t('common.close')}">×</button><div class="eyebrow">${t('timeline.detail')}</div><h1 id="memory-detail-title">${esc(titleOf(memory))}</h1><p class="sub">${uiDate(memory.date)} · ${memory.kind === 'moment' ? t('moments.label') : `${weather(memory.mood)} · ${t('common.energy')} ${memory.energy}`}</p><p style="line-height:1.65">${esc(memory.text || t('timeline.noNote')).replace(/\n/g,'<br>')}</p>${memory.location ? `<p class="memory-detail-meta">⌖ ${esc(memory.location)}</p>` : ''}${task ? `<p class="memory-detail-meta">↗ ${esc(t('memory.relatedTask'))}: <button class="text-link" onclick="closeModal();openApp('tasks')">${esc(task.title)}</button></p>` : ''}${(memory.tags || []).length ? `<div class="memory-badges detail-badges">${memory.tags.map(tag => `<span># ${esc(tag)}</span>`).join('')}</div>` : ''}${memory.kind !== 'moment' ? `<p class="film-copy"><b>${t('today.film')}: ${esc(localizedFilmField(memory,'filmTitle'))}</b><br>${esc(localizedFilmField(memory,'filmSubtitle'))}</p>` : ''}<div class="actions"><button class="primary" onclick="editMemory('${esc(memory.id)}')">${t('common.edit')}</button><button class="secondary" onclick="preserve('${esc(memory.id)}')">${favorite ? t('timeline.preserved') : t('memory.favorite')}</button><button class="danger" onclick="confirmDelete('${esc(memory.id)}')">${t('common.delete')}</button></div></div></div>`;
};
window.editMemory = id => { const memory = mems().find(item => item.id === id); if (!memory) return; rootModal().innerHTML = `<div class="modal" onclick="if(event.target===this) closeModal()"><form class="modalbox memory-edit-form" onsubmit="saveMemoryEdit(event,'${esc(memory.id)}')" role="dialog" aria-modal="true" aria-labelledby="memory-edit-title"><button type="button" class="modal-close" onclick="closeModal()" aria-label="${t('common.close')}">×</button><div class="eyebrow">${t('timeline.detail')}</div><h2 id="memory-edit-title">${t('memory.edit')}</h2><p class="sub">${uiDate(memory.date)}</p><label>${t('memory.title')}<input id="memory-edit-title" maxlength="120" value="${escAttr(memory.title || '')}" placeholder="${t('memory.titlePlaceholder')}"></label><label>${t('memory.note')}<textarea id="memory-edit-note" rows="5">${esc(memory.text || '')}</textarea></label>${memoryMetaFields(memory)}<div class="actions"><button class="primary" type="submit">${t('common.save')}</button><button class="secondary" type="button" onclick="closeModal()">${t('common.cancel')}</button></div></form></div>`; };
window.saveMemoryEdit = (event,id) => { event.preventDefault(); const all=window.LifeOSActions.allMemories(), memory=all.find(item=>item.id===id); if(!memory)return; memory.title=document.querySelector('#memory-edit-title').value.trim(); memory.text=document.querySelector('#memory-edit-note').value.trim(); memory.tags=tagList(document.querySelector('#memory-tags').value); memory.location=document.querySelector('#memory-place').value.trim(); memory.taskId=document.querySelector('#memory-task').value||''; memory.updatedAt=new Date().toISOString(); save('lifeos_memories',all); closeModal(); renderAll(); detail(id); };
window.preserve = id => { const all = window.LifeOSActions.allFavorites(), alreadyPreserved = all.some(item => item.memoryId === id); if (alreadyPreserved) { save('lifeos_museum', all.filter(item => item.memoryId !== id)); toast(t('timeline.unpreserved')); } else { save('lifeos_museum', [...all, { id: `artifact_${crypto.randomUUID()}`, memoryId: id, preservedAt: new Date().toISOString() }]); toast(t('timeline.added')); } closeModal(); renderAll(); };
window.confirmDelete = id => { rootModal().innerHTML = `<div class="modal"><div class="modalbox"><div class="eyebrow">${t('timeline.confirmDelete')}</div><h2>${t('timeline.remove')}</h2><p class="sub">${t('trash.moveHint')}</p><div class="actions"><button class="danger" onclick="deleteMemory('${id}')">${t('timeline.deleteMemory')}</button><button class="secondary" onclick="modal.innerHTML=''">${t('common.cancel')}</button></div></div></div>`; };
window.deleteMemory = id => { window.LifeOSActions.deleteMemory(id); rootModal().innerHTML = ''; toast(t('trash.moved')); };
let insightView = 'week', insightOffset = 0;
const reportDateKey = value => `${value.getFullYear()}-${String(value.getMonth() + 1).padStart(2, '0')}-${String(value.getDate()).padStart(2, '0')}`;
const reportDayNumber = value => Date.UTC(value.getFullYear(), value.getMonth(), value.getDate()) / 864e5;
const reportEventDate = value => { if (!value) return ''; const parsed = new Date(value); return Number.isNaN(parsed.getTime()) ? '' : reportDateKey(parsed); };
const reportPeriod = () => {
const today = new Date(), first = insightView === 'week' ? new Date(today.getFullYear(), today.getMonth(), today.getDate(), 12) : new Date(today.getFullYear(), today.getMonth() + insightOffset, 1, 12);
if (insightView === 'week') first.setDate(first.getDate() - (first.getDay() + 6) % 7 + insightOffset * 7);
const next = new Date(first);
if (insightView === 'week') next.setDate(next.getDate() + 7); else next.setMonth(next.getMonth() + 1);
const last = new Date(next); last.setDate(last.getDate() - 1);
const elapsed = Math.min(reportDayNumber(next), reportDayNumber(today) + 1) - reportDayNumber(first);
return { start: reportDateKey(first), end: reportDateKey(next), last: reportDateKey(last), today: reportDateKey(today), elapsed };
};
window.setInsightsView = view => { if (!['week', 'month'].includes(view)) return; insightView = view; insightOffset = 0; window.insights(document.querySelector('#content-insights')); };
window.shiftInsights = delta => { const next = insightOffset + delta; if (next > 0 || !Number.isInteger(next)) return; insightOffset = next; window.insights(document.querySelector('#content-insights')); };
window.insights = container => {
if (!container) return;
const period = reportPeriod(), inPeriod = key => key && key >= period.start && key < period.end && key <= period.today;
const records = mems().filter(item => inPeriod(item.date)).sort((a, b) => a.date.localeCompare(b.date));
const daysRecorded = new Set(records.map(item => item.date)).size;
const board = sys().tasksBoard || {}, tasks = Array.isArray(board.tasks) ? board.tasks.filter(item=>!item.trashedAt) : [], goals = Array.isArray(board.goals) ? board.goals.filter(item=>!item.trashedAt) : [];
const tasksCreated = tasks.filter(item => inPeriod(reportEventDate(item.createdAt))).length;
const tasksCompleted = tasks.filter(item => item.done && inPeriod(reportEventDate(item.completedAt))).length;
const goalsCompleted = goals.filter(item => item.done && inPeriod(reportEventDate(item.completedAt))).length;
const weatherCounts = { clear: 0, light: 0, cloudy: 0, rain: 0, storm: 0 };
records.forEach(item => { if (item.contextRecorded !== false && Object.hasOwn(weatherCounts, item.mood)) weatherCounts[item.mood]++; });
const commonWeather = Object.entries(weatherCounts).filter(([, count]) => count).sort((a, b) => b[1] - a[1]).slice(0, 3);
const energies = records.filter(item => item.contextRecorded !== false).map(item => ({ date: item.date, value: Number(item.energy) })).filter(item => Number.isFinite(item.value) && item.value >= 1 && item.value <= 5);
const energyAverage = energies.length ? (energies.reduce((sum, item) => sum + item.value, 0) / energies.length).toFixed(1) : '—';
const favorites = new Set(museum().map(item => item.memoryId));
const hasHighlightTag = item => (Array.isArray(item.tags) ? item.tags : []).some(tag => ['高光', 'highlight'].includes(String(tag).replace(/^#/, '').trim().toLowerCase()));
const highlights = records.filter(item => favorites.has(item.id) || hasHighlightTag(item)).reverse().slice(0, 3);
const count = value => LifeI18n.number(value), range = `${LifeI18n.date(period.start, { month: 'short', day: 'numeric', year: 'numeric' })} — ${LifeI18n.date(period.last, { month: 'short', day: 'numeric', year: 'numeric' })}`;
container.innerHTML = `<div class="eyebrow">${t('insights.eyebrow')}</div><h1>${t('insights.title')}</h1><p class="sub report-description">${t('insights.description')}</p>
<div class="report-controls"><div class="choices" role="group" aria-label="${t('insights.period')}">${['week', 'month'].map(view => `<button class="chip ${view === insightView ? 'selected' : ''}" aria-pressed="${view === insightView}" onclick="setInsightsView('${view}')">${t(`insights.${view}`)}</button>`).join('')}</div><div class="report-range"><button class="report-step" aria-label="${t('insights.previous')}" onclick="shiftInsights(-1)">‹</button><strong>${range}</strong><button class="report-step" aria-label="${t('insights.next')}" onclick="shiftInsights(1)" ${insightOffset === 0 ? 'disabled' : ''}>›</button></div></div>
<div class="report-grid"><section class="report-card"><div class="eyebrow">${t('insights.records')}</div><div class="report-big">${count(daysRecorded)} <span>/ ${count(period.elapsed)}</span></div><p>${t('insights.recordedDays', { count: count(records.length), percent: count(period.elapsed ? Math.round(daysRecorded / period.elapsed * 100) : 0) })}</p></section>
<section class="report-card"><div class="eyebrow">${t('insights.tasks')}</div><div class="report-big">${count(tasksCompleted)}</div><p>${t('insights.completedTasks')}</p><div class="report-secondary">${t('insights.taskDetails', { created: count(tasksCreated), goals: count(goalsCompleted) })}</div></section>
<section class="report-card"><div class="eyebrow">${t('insights.weather')}</div>${commonWeather.length ? `<div class="report-weather">${commonWeather.map(([key, value]) => `<div><span>${weather(key)}</span><strong>${count(value)}</strong></div>`).join('')}</div>` : `<p>${t('insights.noWeather')}</p>`}</section>
<section class="report-card"><div class="eyebrow">${t('insights.energy')}</div><div class="report-big">${energyAverage} <span>/ 5</span></div><p>${energies.length > 1 ? t('insights.energyFromTo', { first: energies[0].value, last: energies.at(-1).value }) : energies.length ? t('insights.singleEnergy') : t('insights.noEnergy')}</p>${energies.length ? `<div class="report-energy-bars" aria-label="${t('insights.energy')}">${energies.map(item => `<i style="height:${item.value * 20}%" title="${esc(item.date)} · ${item.value}/5"></i>`).join('')}</div>` : ''}</section></div>
<section class="report-highlights"><div class="eyebrow">${t('insights.highlights')}</div><p class="sub">${t('insights.highlightSource')}</p>${highlights.length ? `<div class="report-highlight-list">${highlights.map(item => `<button class="report-highlight" data-id="${escAttr(String(item.id))}" onclick="detail(this.dataset.id)"><small>${short(item.date)} · ${favorites.has(item.id) ? t('insights.highlightFavorite') : t('insights.highlightTag')}</small><strong>${esc(titleOf(item))}</strong>${item.text ? `<span>${esc(item.text.trim().slice(0, 140))}</span>` : ''}</button>`).join('')}</div>` : `<div class="report-empty">${t('insights.highlightEmpty')}</div>`}</section>
<p class="report-note">${t('insights.note')}</p>`;
};
window.profileApp = container => {
const profileData = profile(), all = mems(), tracked = all.filter(item => item.contextRecorded !== false), common = Object.entries(tracked.reduce((out, item) => (out[item.mood] = (out[item.mood] || 0) + 1, out), {})).sort((a,b) => b[1] - a[1])[0]?.[0] || '—', average = tracked.length ? (tracked.reduce((sum,item) => sum + item.energy,0) / tracked.length).toFixed(1) : '—', started = Math.max(1, Math.floor((Date.now() - new Date(profileData.startDate)) / 864e5));
container.innerHTML = `<div class="eyebrow">${t('profile.eyebrow')}</div><h1>${profileData.name ? esc(profileData.name) + ' · ' : ''}${t('profile.online')}</h1><div class="profile-grid"><div class="stat"><b>${started}</b><span>${t('profile.daysOnline')}</span></div><div class="stat"><b>${all.length}</b><span>${t('profile.memories')}</span></div><div class="stat"><b>${museum().length}</b><span>${t('profile.museumItems')}</span></div><div class="stat"><b>${streak(all)}</b><span>${t('profile.streak')}</span></div><div class="stat"><b>${longest(all)}</b><span>${t('profile.longest')}</span></div><div class="stat"><b>${common === '—' ? common : weather(common)}</b><span>${t('profile.commonWeather')}</span></div></div><div class="eyebrow">${t('profile.personal')}</div><div class="formrow"><label>${t('profile.name')}</label><input id="pname" value="${esc(profileData.name)}"></div><div class="formrow"><label>${t('profile.birthday')}</label><input id="pbday" type="date" value="${esc(profileData.birthday)}"></div><div class="formrow"><label>${t('profile.start')}</label><input id="pstart" type="date" value="${esc(profileData.startDate)}"></div><div class="formrow"><label>${t('profile.motto')}</label><input id="pmotto" value="${esc(profileData.motto)}"></div><div class="actions"><button class="primary" onclick="saveProfile()">${t('profile.save')}</button><span class="status">${t('profile.average',{value:average})}</span></div>`;
};
window.saveProfile = () => { save('lifeos_profile', { name: pname.value, birthday: pbday.value, startDate: pstart.value || day(), motto: pmotto.value }); renderAll(); toast(t('profile.saved')); };
window.systemApp = container => {
const state = settings(), preference = LifeI18n.preference(), bytes = new Blob([JSON.stringify({ mems: mems(), museum: museum(), profile: profile(), system: sys() })]).size, oldBackup = state.lastBackup && Date.now() - new Date(state.lastBackup) > 12096e5, detected = t('system.browserDetected', { name: LifeI18n.names[LifeI18n.browserLanguage()] });
container.innerHTML = `<div class="eyebrow">${t('system.eyebrow')}</div><h1>${t('system.title')}</h1><div class="settings"><section data-settings-group="appearance"><div class="eyebrow">${t('system.appearance')}</div><div class="choices">${['dark','light','auto'].map(item => `<button class="chip ${state.theme === item ? 'selected' : ''}" onclick="theme('${item}')">${t(`system.theme.${item}`)}</button>`).join('')}</div></section><section data-settings-group="language"><div class="eyebrow">${t('system.language')}</div><p class="sub">${detected}</p><div class="choices language-choices"><button class="chip ${preference === 'auto' ? 'selected' : ''}" onclick="window.setLanguage('auto')">${t('system.auto')}</button>${LifeI18n.supported.map(code => `<button class="chip ${preference === code ? 'selected' : ''}" lang="${code}" dir="${code === 'ar' ? 'rtl' : 'ltr'}" onclick="window.setLanguage('${code}')">${LifeI18n.names[code]}</button>`).join('')}</div></section><section class="notification-settings" data-settings-group="notifications">${window.LifeOSNotifications?.markup() || ''}</section><section data-settings-group="data"><div class="eyebrow">${t('system.data')}</div><div class="actions"><button class="primary" onclick="exportData()">${t('system.export')}</button><button class="secondary" onclick="document.querySelector('#importer').click()">${t('system.import')}</button><button class="danger" onclick="resetConfirm()">${t('system.reset')}</button><input id="importer" class="hidden" type="file" accept=".json" onchange="readImport(this)"></div></section><section data-settings-group="data"><div class="eyebrow">${t('system.storage')}</div><p>${t('system.local')}<br>${t('system.storageSummary',{memories:LifeI18n.number(mems().length),museum:LifeI18n.number(museum().length),tasks:LifeI18n.number(sys().tasksBoard?.tasks?.length||0),size:LifeI18n.number(Math.ceil(bytes/1024))})}</p></section><section data-settings-group="data"><div class="eyebrow">${t('system.dataStorage')}</div><p>${t('system.stored')}<br>${t('system.backups')}</p><p>${t('system.lastBackup',{value:state.lastBackup ? short(state.lastBackup.slice(0,10)) : t('common.never')})}${oldBackup ? `<br><b style="color:var(--accent)">${t('system.recommended')}</b>` : ''}</p></section><section data-settings-group="about"><div class="eyebrow">${t('system.version')}</div><p>${t('system.release',{version:window.LifeOSVersion||'1.18.1'})}</p></section></div>`;
};
window.importPreview = () => { const data = importData, board = data.system?.tasksBoard || {}; rootModal().innerHTML = `<div class="modal"><div class="modalbox"><div class="eyebrow">${t('dialog.backup')}</div><h2>${t('dialog.ready')}</h2><p class="sub">${t('dialog.exported',{date:short(data.exportedAt.slice(0,10))})}<br>${t('dialog.memories',{count:data.memories.length})}<br>${t('dialog.museumItems',{count:data.museum.length})}<br>${t('dialog.goals',{count:board.goals?.length || 0})}<br>${t('dialog.tasks',{count:board.tasks?.length || 0})}</p><div class="actions"><button class="primary" onclick="applyImport('merge')">${t('dialog.merge')}</button><button class="danger" onclick="replaceConfirm()">${t('dialog.replaceAll')}</button><button class="secondary" onclick="modal.innerHTML=''">${t('common.cancel')}</button></div></div></div>`; };
const trashItems = () => { const board=window.LifeOSActions.allBoard(); return [...window.LifeOSActions.allMemories().map(item=>({...item,_trashType:'Memory'})),...board.tasks.map(item=>({...item,_trashType:'Task'})),...board.goals.map(item=>({...item,_trashType:'Goal'}))].filter(item=>item.trashedAt).sort((a,b)=>b.trashedAt.localeCompare(a.trashedAt)); };
const baseSystem = window.systemApp;
window.systemApp = container => {
baseSystem(container);
container.querySelector('.settings')?.insertAdjacentHTML('beforeend', `<section data-settings-group="data"><div class="eyebrow">${t('trash.title')}</div><p>${t('trash.hint')}</p><button class="secondary" onclick="openRecycleBin()">${t('trash.open', {count:trashItems().length})}</button></section>`);
};
window.openRecycleBin = () => {
const items = trashItems();
rootModal().innerHTML = `<div class="modal" onclick="if(event.target===this) closeModal()"><div class="modalbox trash-panel" role="dialog" aria-modal="true" aria-labelledby="trash-heading"><button class="modal-close" onclick="closeModal()" aria-label="${t('common.close')}">×</button><h2 id="trash-heading">${t('trash.title')}</h2><p class="sub">${t('trash.hint')}</p><p id="trash-error" role="alert"></p>${items.length ? `<div class="trash-list">${items.map(item => `<article class="trash-item"><strong>${esc(titleOf(item))}</strong><small>${item.date || item.dueDate || item.targetDate ? short(item.date || item.dueDate || item.targetDate) + ' · ' : ''}${item._trashType === 'Task' ? t('calendar.task') : item._trashType === 'Goal' ? t('calendar.goal') : item.kind === 'moment' ? t('moments.label') : t('app.today')}</small><details><summary>${t('memory.note')}</summary><p>${esc(item.text || item.description || '')}</p></details><div class="actions"><button class="secondary" data-id="${escAttr(item.id)}" data-type="${item._trashType}" onclick="restoreTrashedMemory(this.dataset.id,this.dataset.type)">${t('trash.restore')}</button><button class="danger" data-id="${escAttr(item.id)}" data-type="${item._trashType}" onclick="confirmPurgeMemory(this.dataset.id,this.dataset.type)">${t('trash.purge')}</button></div></article>`).join('')}</div>` : `<p class="sub">${t('trash.empty')}</p>`}</div></div>`;
};
window.restoreTrashedMemory = (id,type='Memory') => {
try { window.LifeOSActions[`restore${type}`](id); window.openRecycleBin(); toast(t('trash.restored')); }
catch(error) { const node=document.querySelector('#trash-error'); if(node) node.textContent=t(error.message === 'memoryExists' ? 'trash.dateConflict' : 'trash.unavailable'); }
};
window.confirmPurgeMemory = (id,type='Memory') => {
const item=trashItems().find(memory=>memory.id===id && memory._trashType===type); if(!item) return;
rootModal().innerHTML = `<div class="modal"><div class="modalbox" role="dialog" aria-modal="true"><h2>${t('trash.purgeQuestion')}</h2><p>${esc(titleOf(item))}</p><p class="sub">${t('trash.purgeHint')}</p><div class="actions"><button class="danger" data-id="${escAttr(id)}" data-type="${type}" onclick="purgeTrashedMemory(this.dataset.id,this.dataset.type)">${t('trash.purge')}</button><button class="secondary" onclick="openRecycleBin()">${t('common.cancel')}</button></div></div></div>`;
};
window.purgeTrashedMemory = (id,type='Memory') => { try { window.LifeOSActions[`purge${type}`](id); window.openRecycleBin(); toast(t('trash.purged')); } catch { window.openRecycleBin(); } };
const trashStyle = document.createElement('style');
trashStyle.textContent = `.trash-panel{width:min(650px,calc(100vw - 28px));max-height:calc(100dvh - 28px);overflow:auto}.trash-panel h2{font-size:24px;letter-spacing:0}.trash-list{display:grid;gap:12px}.trash-item{border:1px solid var(--line);background:var(--panel2);border-radius:10px;padding:14px;min-width:0}.trash-item>strong{display:block;font-size:16px;overflow-wrap:anywhere}.trash-item>small{display:block;font-size:12px;color:var(--muted);margin:7px 0}.trash-item details{font-size:14px}.trash-item details p{white-space:pre-wrap;overflow-wrap:anywhere;max-height:180px;overflow:auto;line-height:1.6}.trash-item .actions{flex-wrap:wrap}#trash-error{color:#eea27d;font-size:14px}`;
document.head.append(trashStyle);
window.replaceConfirm = () => { rootModal().innerHTML = `<div class="modal"><div class="modalbox"><div class="eyebrow">${t('dialog.final')}</div><h2>${t('dialog.replaceQuestion')}</h2><p class="sub">${t('dialog.replaceWarning')}</p><div class="actions"><button class="danger" onclick="applyImport('replace')">${t('dialog.replace')}</button><button class="secondary" onclick="importPreview()">${t('common.cancel')}</button></div></div></div>`; };
window.applyImport = mode => {
const data = importData;
if (mode === 'replace') {
save('lifeos_memories', data.memories); save('lifeos_museum', data.museum); save('lifeos_profile', data.profile || {}); save('lifeos_settings', data.settings || {}); save('lifeos_system', data.system || { schemaVersion: 2 });
if (Array.isArray(data.desktopLayout?.entries)) localStorage.setItem('lifeos_window_layout_v1', JSON.stringify({ entries: data.desktopLayout.entries }));
if (data.widgetLayout && typeof data.widgetLayout === 'object' && !Array.isArray(data.widgetLayout)) localStorage.setItem('lifeos_widget_layout_v1', JSON.stringify(data.widgetLayout));
} else {
const memories = window.LifeOSActions.allMemories(), ids = new Set(memories.map(item => item.id)), dates = new Set(memories.filter(item => !item.trashedAt && item.kind !== 'moment').map(item => item.date));
const additions = data.memories.filter(item => { if (ids.has(item.id) || (!item.trashedAt && item.kind !== 'moment' && dates.has(item.date))) return false; ids.add(item.id); if (!item.trashedAt && item.kind !== 'moment') dates.add(item.date); return true; });
save('lifeos_memories', [...memories, ...additions].sort((a,b) => b.date.localeCompare(a.date) || String(b.createdAt || '').localeCompare(String(a.createdAt || ''))));
const artifacts = window.LifeOSActions.allFavorites(), artifactIds = new Set(artifacts.map(item => item.id));
save('lifeos_museum', [...artifacts, ...data.museum.filter(item => !artifactIds.has(item.id))]);
const current = sys(), importedBoard = data.system?.tasksBoard;
if (importedBoard && Array.isArray(importedBoard.goals) && Array.isArray(importedBoard.tasks)) {
current.tasksBoard ||= { goals: [], tasks: [] };
for (const kind of ['goals', 'tasks']) { const known = new Set((current.tasksBoard[kind] || []).map(item => item.id)); current.tasksBoard[kind] = [...(current.tasksBoard[kind] || []), ...importedBoard[kind].filter(item => !known.has(item.id))]; }
save('lifeos_system', current);
}
}
rootModal().innerHTML = ''; toast('feedback.restoring'); setTimeout(() => { renderAll(); toast('feedback.restored'); }, 500);
};
window.resetConfirm = () => { rootModal().innerHTML = `<div class="modal"><div class="modalbox"><div class="eyebrow">${t('system.reset')}</div><h2>${t('dialog.resetQuestion')}</h2><p class="sub">${t('dialog.resetWarning')}</p><div class="actions"><button class="danger" onclick="['lifeos_memories','lifeos_museum','lifeos_profile','lifeos_settings','lifeos_system','lifeos_window_layout_v1','lifeos_widget_layout_v1','lifeos_notifications_v1','lifeos_notifications_sent_v1'].forEach(k=>localStorage.removeItem(k));location.reload()">${t('dialog.resetData')}</button><button class="secondary" onclick="modal.innerHTML=''">${t('common.cancel')}</button></div></div></div>`; };
window.toast = key => { const message = key.includes('.') ? t(key) : key; const node = document.createElement('div'); node.className = 'toast'; node.textContent = message; document.body.append(node); setTimeout(() => node.remove(), 2000); };
window.minWin = id => { const windowNode = windows[id]; if (!windowNode) return; windowNode.classList.add('min'); if (activeWindow === id) { activeWindow = Object.keys(windows).find(key => key !== id && !windows[key].classList.contains('min')) || null; if (activeWindow) focus(windows[activeWindow]); } renderTaskbar(); toast('feedback.minimized'); };
const memoryStyle = document.createElement('style');
memoryStyle.textContent = `.memory-meta-form{display:grid;gap:9px;margin-top:12px}.memory-title-field{display:grid;gap:6px;margin-top:10px;color:var(--muted);font-size:12px}.memory-title-field input,.memory-edit-form input{width:100%;min-width:0;border:1px solid var(--line);background:var(--panel2);border-radius:8px;padding:10px 11px;color:var(--ink);outline:none;font:inherit}.memory-title-field input:focus,.memory-edit-form input:focus{border-color:var(--accent)}.memory-meta-form label,.memory-edit-form>label{display:grid;gap:6px;color:var(--muted);font-size:12px}.memory-meta-form input,.memory-meta-form select,.memory-edit-form input,.memory-edit-form textarea{width:100%;min-width:0;border:1px solid var(--line);background:var(--panel2);border-radius:8px;padding:10px 11px;color:var(--ink);outline:none;font:inherit}.memory-meta-form input:focus,.memory-meta-form select:focus,.memory-edit-form input:focus,.memory-edit-form textarea:focus,.timeline-tools input:focus,.timeline-tools select:focus{border-color:var(--accent)}.memory-edit-form{display:grid;gap:12px;max-height:min(80vh,720px);overflow:auto}.memory-edit-form h2{font-size:21px;margin:0}.memory-edit-form textarea{resize:vertical;line-height:1.55}.memory-edit-form .memory-meta-form{margin:0}.memory-edit-form .actions{margin:0}.timeline-tools{display:grid;grid-template-columns:minmax(0,1fr) 190px;gap:8px;margin:17px 0 11px}.timeline-tools input,.timeline-tools select{width:100%;min-width:0;height:40px;border:1px solid var(--line);border-radius:8px;background:var(--panel2);color:var(--ink);padding:0 11px;outline:none;font:13px Manrope,system-ui}.timeline-tools input::placeholder{color:var(--muted)}.memory-open{display:block!important;text-align:left}.memory-badges{display:flex;gap:6px;flex-wrap:wrap;margin-top:9px}.memory-badges span,.memory-detail-meta{color:var(--muted);font-size:12px}.memory-badges span{border:1px solid var(--line);background:var(--panel2);border-radius:99px;padding:4px 8px}.detail-badges{margin:0 0 14px}.text-link{border:0;background:none;padding:0;color:var(--accent);text-decoration:underline}.memory-detail-meta{margin:8px 0}.memory-edit-form .sub{margin:0}@media(max-width:600px){.timeline-tools{grid-template-columns:1fr 130px}.memory-badges span{font-size:11px}.memory-meta-form label,.memory-edit-form>label,.memory-title-field{font-size:13px}}`;
document.head.append(memoryStyle);
const reportStyle = document.createElement('style');
reportStyle.textContent = `.report-description{max-width:620px;line-height:1.55}.report-controls{display:flex;align-items:center;justify-content:space-between;gap:14px;flex-wrap:wrap;margin:20px 0}.report-range{display:flex;align-items:center;gap:10px;min-width:0}.report-range strong{font-size:14px;line-height:1.4;text-align:center}.report-step{width:34px;height:34px;flex:none;border:1px solid var(--line);border-radius:8px;background:var(--panel2);color:var(--ink);cursor:pointer;font-size:22px}.report-step:disabled{opacity:.4;cursor:default}.report-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.report-card{min-width:0;padding:18px;border:1px solid var(--line);border-radius:12px;background:var(--panel2)}.report-card .eyebrow{margin-bottom:12px}.report-card p{font-size:13px;line-height:1.5;color:var(--muted);margin:8px 0 0}.report-big{font-size:32px;font-weight:700;line-height:1.2}.report-big span{font-size:15px;color:var(--muted)}.report-secondary{color:var(--muted);font-size:12px;line-height:1.5;margin-top:8px}.report-weather{display:grid;gap:8px}.report-weather>div{display:flex;justify-content:space-between;gap:10px;font-size:14px}.report-energy-bars{height:50px;display:flex;align-items:end;gap:4px;margin-top:14px}.report-energy-bars i{flex:1;min-width:3px;max-width:24px;background:var(--accent);border-radius:3px 3px 0 0}.report-highlights{margin-top:24px}.report-highlights .sub{line-height:1.5}.report-highlight-list{display:grid;gap:8px}.report-highlight{display:grid;gap:5px;width:100%;padding:14px;text-align:left;border:1px solid var(--line);border-radius:10px;background:var(--panel2);color:var(--ink);cursor:pointer}.report-highlight:hover,.report-highlight:focus-visible{border-color:var(--accent)}.report-highlight small,.report-highlight span{color:var(--muted);line-height:1.4}.report-highlight span{font-size:13px}.report-empty{padding:18px;border:1px dashed var(--line);border-radius:10px;color:var(--muted);font-size:13px}.report-note{margin-top:18px;color:var(--muted);font-size:12px;line-height:1.5}@media(max-width:650px){.report-grid{grid-template-columns:1fr}.report-controls{align-items:flex-start}.report-range{width:100%;justify-content:space-between}}`;
document.head.append(reportStyle);
// Render every surface again after the overrides are installed; no DOM walking is involved.
window.renderIcons(); window.renderAll(); window.applyLanguage();
})();