diff --git a/CHANGELOG.md b/CHANGELOG.md index 378b5dc..eb43d73 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ 本项目按 `v主版本.次版本.修订版本` 标记应用版本;按需创建 Git tag。下列内容以对应提交和已发布功能为准。 +## v1.24.0 — 2026-10-13 + +- 每日总结和瞬间删除后先移入回收站,可在系统设置的数据与备份页面查看、恢复或二次确认永久删除。 +- 回收站保留正文、标签、原记录 ID 和收藏关系,不自动清理;恢复时不覆盖同日现有总结。 +- 软删除状态沿用记录级云同步、SQLite 本地状态和 JSON 备份;回收站记录从时间线、搜索、日历、收藏展示和统计隐藏。 +- 编辑、创建、任务关联清理和合并导入均保留既有回收站记录。 +- 增加恢复冲突、收藏恢复、写入隔离和云端回收站状态测试。 + ## v1.23.0 — 2026-10-13 - 新增桌面快速记录入口和今日瞬间列表;同一天可保存多条文字瞬间,支持标题、日期、标签、草稿恢复和后续编辑。 diff --git a/README.md b/README.md index e89be54..24ab987 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ 以桌面操作系统为交互方式的个人记录网站。用 App 记录日常、管理目标与待办,并沿时间线回看已经留下的内容。 -在线站点:[Life OS](https://life-os-personal-desktop.biss0.chatgpt.site) · 当前应用版本:**v1.23.0** · [更新日志](CHANGELOG.md) +在线站点:[Life OS](https://life-os-personal-desktop.biss0.chatgpt.site) · 当前应用版本:**v1.24.0** · [更新日志](CHANGELOG.md) ## 功能 @@ -32,6 +32,8 @@ ## 数据与备份 +记忆和瞬间的删除操作会先移入回收站。系统设置 → 数据与备份 → 回收站可预览、恢复或确认永久删除;不会自动清理。恢复保留原记录 ID、标签与收藏关系。如果该日期已有新的每日总结,会阻止恢复并提示处理,避免覆盖。回收站状态参与云同步和 JSON 备份;永久删除后不能通过回收站恢复,已有独立备份仍保留当时的内容。任务和目标暂不进入回收站。 + 首次使用可选择“仅本地使用”或“登录并云同步”。仅本地模式无需登录,也不会请求云同步接口;数据写入当前设备、当前浏览器、本站专属的 OPFS 私有存储区,逻辑数据库位置为 `OPFS:/lifeos.sqlite`。SQLite 是本地持久层,`localStorage` 作为同步界面缓存和兼容旧版本的数据迁移来源。SQLite Schema v2 会将记忆、目标、待办和收藏投影为独立关系表,用于索引和全局检索;升级时自动从已有状态重建,不需要手动迁移。系统设置会显示当前模式、数据库状态、近似大小和持久存储状态。 云端模式继续使用 ChatGPT 登录标识隔离不同用户的数据,资料通过同源 API 保存到 Sites 的 D1 数据库,本地 SQLite 作为离线副本。首次云端恢复前,本地资料会保留一份迁移前副本。浏览器缓存与 JSON 备份仍使用 `lifeos_system.tasksBoard`;云端将其中的目标和待办拆分为独立记录。用户可随时切回仅本地模式;切换不会自动删除已有云端数据。任务栏同步入口与系统设置中的同步中心会显示联网状态、待同步更改、冲突和上次成功同步时间;写入失败时操作保留在设备队列,恢复联网后自动重试。 diff --git a/package.json b/package.json index 4f0bf90..48abd45 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "life-os", - "version": "1.23.0", + "version": "1.24.0", "private": true, "type": "module", "scripts": { diff --git a/public/addons.js b/public/addons.js index 5dd7837..ae7a81a 100644 --- a/public/addons.js +++ b/public/addons.js @@ -3,7 +3,7 @@ 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 => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[char])); - const APP_VERSION = '1.23.0'; + const APP_VERSION = '1.24.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); @@ -34,7 +34,7 @@ setTimeout(() => { const today = (typeof todayTargetDate !== 'undefined' && todayTargetDate) || localDay(); try { - const saved = JSON.parse(localStorage.getItem('lifeos_memories') || '[]').some(m => m.date === today && m.kind !== 'moment'); + 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); @@ -66,7 +66,8 @@ try { const indexed = await window.LifeOSLocalDB.search(query, 12); const current = new Map(found.map(item => [`${item.kind}:${item.id}`, item])); - indexed.forEach(item => { const key = `${item.kind}:${item.id}`; if (!current.has(key)) current.set(key, item); }); + const activeIds = new Set(mems().map(item => item.id)); + indexed.forEach(item => { if (item.kind === 'memory' && !activeIds.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 {} } diff --git a/public/backup.js b/public/backup.js index 3a8b589..03ffee8 100644 --- a/public/backup.js +++ b/public/backup.js @@ -22,7 +22,7 @@ const stored = records(); return { app: 'Life OS', - version: window.LifeOSVersion || '1.23.0', + version: window.LifeOSVersion || '1.24.0', schemaVersion: BACKUP_SCHEMA, exportedAt: new Date().toISOString(), profile: json('lifeos_profile', {}), diff --git a/public/data-actions.js b/public/data-actions.js index 46b4166..37f5662 100644 --- a/public/data-actions.js +++ b/public/data-actions.js @@ -1,5 +1,10 @@ /* Shared record writes for forms and the Life OS terminal. */ (() => { + const readMemories = mems, readFavorites = museum; + const allMemories = () => readMemories(); + const allFavorites = () => readFavorites(); + window.mems = () => allMemories().filter(item => !item.trashedAt); + window.museum = () => { const visible = new Set(window.mems().map(item => item.id)); return allFavorites().filter(item => visible.has(item.memoryId)); }; const board = () => { const current = sys().tasksBoard; return current && Array.isArray(current.goals) && Array.isArray(current.tasks) ? current : { goals: [], tasks: [] }; @@ -13,6 +18,7 @@ const persistBoard = data => { const state = sys(); state.tasksBoard = data; save('lifeos_system', state); renderAll(); }; window.LifeOSActions = { board, + allMemories, allFavorites, createGoal({ title, description = '', targetDate = '', showOnDesktop = false }) { title = required(title, 100); if (!validDate(targetDate)) throw new Error('invalidDate'); @@ -61,7 +67,7 @@ const data = board(), task = data.tasks.find(item => item.id === id); if (!task) throw new Error('notFound'); data.tasks = data.tasks.filter(item => item.id !== id); - const all = mems(); + const all = allMemories(); if (all.some(item => item.taskId === id)) save('lifeos_memories', all.map(item => item.taskId === id ? { ...item, taskId: '', updatedAt: new Date().toISOString() } : item)); persistBoard(data); return task; }, @@ -80,7 +86,7 @@ if (taskId && !board().tasks.some(task => task.id === taskId)) throw new Error('notFound'); if (!['daily', 'moment'].includes(kind)) throw new Error('invalidValue'); if (kind === 'moment' && !String(text).trim() && !title) throw new Error('invalidTitle'); - const all = mems(), old = kind === 'daily' ? all.find(item => item.date === date && item.kind !== 'moment') : null; + const all = allMemories(), old = kind === 'daily' ? all.find(item => !item.trashedAt && item.date === date && item.kind !== 'moment') : null; if (old && !replace) throw new Error('memoryExists'); const film = filmFor(mood, Number(energy)), now = new Date().toISOString(); const memory = { ...old, id: old?.id || `memory_${crypto.randomUUID()}`, kind, date, title, text: String(text).trim(), mood, energy: Number(energy), tags: [...new Set(tags.map(tag => String(tag).trim()).filter(Boolean))].slice(0, 12), location: String(location).trim().slice(0, 100), taskId, filmTitle: film.filmTitle, filmSubtitle: film.filmSubtitle, filmLine: film.filmLine, createdAt: old?.createdAt || now, updatedAt: now }; @@ -88,10 +94,24 @@ save('lifeos_memories', [...all.filter(item => item.id !== memory.id), memory].sort((a, b) => b.date.localeCompare(a.date) || String(b.createdAt || '').localeCompare(String(a.createdAt || '')))); renderAll(); return memory; }, deleteMemory(id) { - const all = mems(), memory = all.find(item => item.id === id); + const all = allMemories(), memory = all.find(item => item.id === id && !item.trashedAt); + if (!memory) throw new Error('notFound'); + memory.trashedAt = new Date().toISOString(); memory.updatedAt = memory.trashedAt; + save('lifeos_memories', all); + renderAll(); return memory; + }, + restoreMemory(id) { + const all = allMemories(), memory = all.find(item => item.id === id && item.trashedAt); + if (!memory) throw new Error('notFound'); + if (memory.kind !== 'moment' && all.some(item => !item.trashedAt && item.id !== id && item.kind !== 'moment' && item.date === memory.date)) throw new Error('memoryExists'); + delete memory.trashedAt; memory.updatedAt = new Date().toISOString(); + save('lifeos_memories', all); renderAll(); return memory; + }, + purgeMemory(id) { + const all = allMemories(), memory = all.find(item => item.id === id && item.trashedAt); if (!memory) throw new Error('notFound'); save('lifeos_memories', all.filter(item => item.id !== id)); - save('lifeos_museum', museum().filter(item => item.memoryId !== id)); + save('lifeos_museum', allFavorites().filter(item => item.memoryId !== id)); renderAll(); return memory; } }; diff --git a/public/i18n-renderers.js b/public/i18n-renderers.js index 76c5cd3..8c67190 100644 --- a/public/i18n-renderers.js +++ b/public/i18n-renderers.js @@ -100,10 +100,10 @@ rootModal().innerHTML = ``; }; window.editMemory = id => { const memory = mems().find(item => item.id === id); if (!memory) return; rootModal().innerHTML = ``; }; - window.saveMemoryEdit = (event,id) => { event.preventDefault(); const all=mems(), 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 = museum(), 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 = ``; }; - window.deleteMemory = id => { window.LifeOSActions.deleteMemory(id); rootModal().innerHTML = ''; toast(t('timeline.removed')); }; + 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 = ``; }; + 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; @@ -156,6 +156,28 @@ container.innerHTML = `
${t('system.eyebrow')}

${t('system.title')}

${t('system.appearance')}
${['dark','light','auto'].map(item => ``).join('')}
${t('system.language')}

${detected}

${LifeI18n.supported.map(code => ``).join('')}
${window.LifeOSNotifications?.markup() || ''}
${t('system.data')}
${t('system.storage')}

${t('system.local')}
${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))})}

${t('system.dataStorage')}

${t('system.stored')}
${t('system.backups')}

${t('system.lastBackup',{value:state.lastBackup ? short(state.lastBackup.slice(0,10)) : t('common.never')})}${oldBackup ? `
${t('system.recommended')}` : ''}

${t('system.version')}

${t('system.release',{version:window.LifeOSVersion||'1.18.1'})}

`; }; window.importPreview = () => { const data = importData, board = data.system?.tasksBoard || {}; rootModal().innerHTML = ``; }; + const trashItems = () => window.LifeOSActions.allMemories().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', `
${t('trash.title')}

${t('trash.hint')}

`); + }; + window.openRecycleBin = () => { + const items = trashItems(); + rootModal().innerHTML = ``; + }; + window.restoreTrashedMemory = id => { + try { window.LifeOSActions.restoreMemory(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 => { + const item=trashItems().find(memory=>memory.id===id); if(!item) return; + rootModal().innerHTML = ``; + }; + window.purgeTrashedMemory = id => { try { window.LifeOSActions.purgeMemory(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 = ``; }; window.applyImport = mode => { const data = importData; @@ -164,10 +186,10 @@ 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 = mems(), ids = new Set(memories.map(item => item.id)), dates = new Set(memories.filter(item => item.kind !== 'moment').map(item => item.date)); - const additions = data.memories.filter(item => { if (ids.has(item.id) || (item.kind !== 'moment' && dates.has(item.date))) return false; ids.add(item.id); if (item.kind !== 'moment') dates.add(item.date); return true; }); + 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 = museum(), artifactIds = new Set(artifacts.map(item => item.id)); + 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)) { diff --git a/public/index.html b/public/index.html index 40e1349..b1e2723 100644 --- a/public/index.html +++ b/public/index.html @@ -25,4 +25,4 @@ function profileApp(c){let p=profile(),a=mems(),common=Object.entries(a.reduce(( function today(c){let m=mems().find(x=>x.date===day());if(todayDraft===null){selectedMood=m?.mood||'cloudy';selectedEnergy=m?.energy||3}let f=m||filmFor(selectedMood,selectedEnergy),text=todayDraft===null?(m?.text||''):todayDraft,cWeek=new Date().toLocaleDateString(LifeI18n.locale(),{weekday:'long'}).toUpperCase();c.innerHTML=`
${cWeek}

${fmtDate(day()).replace(/^[^,]+, /,'')}

${i18n('How was your day?')}

`}function rerenderToday(){let old=document.querySelector('#entry');todayDraft=old?old.value:todayDraft||'';window.today(document.querySelector('#content-today'));let entry=document.querySelector('#entry');entry?.focus();entry?.setSelectionRange(entry.value.length,entry.value.length)} function systemApp(c){let s=settings(),bytes=new Blob([JSON.stringify({mems:mems(),museum:museum(),profile:profile()})]).size;let rec=s.lastBackup&&(Date.now()-new Date(s.lastBackup)>12096e5);c.innerHTML=`
SYSTEM SETTINGS

System, local and yours.

APPEARANCE
${['dark','light','auto'].map(x=>``).join('')}
LANGUAGE
DATA
STORAGE

Local Storage
${mems().length} memories · ${museum().length} museum items · Approx. ${Math.ceil(bytes/1024)} KB

DATA STORAGE

Your data is stored locally in this browser.
Create regular backups to prevent data loss.

${s.lastBackup?'LAST BACKUP · '+fmtDate(s.lastBackup.slice(0,10)):'LAST BACKUP · NEVER'} ${rec?'
BACKUP RECOMMENDED':''}

VERSION

Life OS
Version ${window.LifeOSVersion||'1.18.1'} · Schema v2

`}function theme(x){let s=settings();s.theme=x;save('lifeos_settings',s);init();renderAll()}function exportData(){let data={app:'Life OS',version:window.LifeOSVersion||'1.18.1',schemaVersion:1,exportedAt:new Date().toISOString(),profile:profile(),memories:mems(),museum:museum(),settings:settings()};let a=document.createElement('a');a.href=URL.createObjectURL(new Blob([JSON.stringify(data,null,2)],{type:'application/json'}));a.download='life-os-backup-'+day()+'.json';a.click();let s=settings();s.lastBackup=new Date().toISOString();save('lifeos_settings',s);renderAll();toast('BACKUP CREATED')}function readImport(el){let f=el.files[0];if(!f)return;let r=new FileReader;r.onload=()=>{try{let d=JSON.parse(r.result);if(d.app!=='Life OS'||![1,2,3].includes(d.schemaVersion)||!Array.isArray(d.memories)||!Array.isArray(d.museum))throw 0;importData=d;importPreview()}catch{toast('INVALID BACKUP FILE')}};r.readAsText(f)}function importPreview(){let d=importData;modal.innerHTML=``}function replaceConfirm(){modal.innerHTML=``}function applyImport(mode){let d=importData;if(mode==='replace'){save('lifeos_memories',d.memories);save('lifeos_museum',d.museum);save('lifeos_profile',d.profile||{});save('lifeos_settings',d.settings||{})}else{let a=mems(), ids=new Set(a.map(x=>x.id)),dates=new Set(a.map(x=>x.date));save('lifeos_memories',[...a,...d.memories.filter(x=>!ids.has(x.id)&&!dates.has(x.date))]);let mu=museum(),mi=new Set(mu.map(x=>x.id));save('lifeos_museum',[...mu,...d.museum.filter(x=>!mi.has(x.id))])}modal.innerHTML='';toast('RESTORING SYSTEM...');setTimeout(()=>{renderAll();toast('SYSTEM RESTORED')},500)}function resetConfirm(){modal.innerHTML=``}function toast(t){let x=document.createElement('div');x.className='toast';x.textContent=t;document.body.append(x);setTimeout(()=>x.remove(),2000)} window.renderIcons=renderIcons;window.renderAll=renderAll;window.toast=toast; - + diff --git a/public/local-db-worker.js b/public/local-db-worker.js index c820728..6ca5f03 100644 --- a/public/local-db-worker.js +++ b/public/local-db-worker.js @@ -90,7 +90,7 @@ function replaceRows(table, rows, sql, values) { } function projectKey(key, value) { if (key === 'lifeos_memories') { - const rows = list(json(value, [])).filter(row => row?.id); + const rows = list(json(value, [])).filter(row => row?.id && !row.trashedAt); replaceRows('memories', rows, 'INSERT INTO memories(id,date,title,text,mood,energy,tags,location,task_id,updated_at,payload) VALUES(?,?,?,?,?,?,?,?,?,?,?)', row => [String(row.id || ''), String(row.date || ''), String(row.title || ''), String(row.text || ''), String(row.mood || ''), Number.isFinite(Number(row.energy)) ? Number(row.energy) : null, list(row.tags).join(' '), String(row.location || ''), String(row.taskId || ''), String(row.updatedAt || ''), JSON.stringify(row)]); } if (key === 'lifeos_system') { diff --git a/public/locales/ar.json b/public/locales/ar.json index 4c942de..cb9b280 100644 --- a/public/locales/ar.json +++ b/public/locales/ar.json @@ -1,4 +1,20 @@ { + "trash": { + "title": "سلة المحذوفات", + "hint": "تبقى الملخصات واللحظات هنا حتى استعادتها أو حذفها نهائياً.", + "open": "فتح السلة ({count})", + "moveHint": "ستُنقل هذه الذكرى إلى السلة ويمكنك استعادتها لاحقاً.", + "moved": "تم النقل إلى السلة", + "restore": "استعادة", + "restored": "تمت استعادة الذكرى", + "empty": "السلة فارغة.", + "purge": "حذف نهائي", + "purgeQuestion": "حذف هذه الذكرى نهائياً؟", + "purgeHint": "سيُحذف النص والمفضلة المرتبطة به ولن يمكن استعادتهما من السلة.", + "purged": "تم الحذف نهائياً", + "dateConflict": "يوجد ملخص لهذا التاريخ. انقله إلى السلة قبل استعادة هذه الذكرى.", + "unavailable": "هذه الذكرى لم تعد متاحة." + }, "moments": { "label": "لحظات", "title": "ملاحظة سريعة", diff --git a/public/locales/en.json b/public/locales/en.json index a51f1d7..956b2a1 100644 --- a/public/locales/en.json +++ b/public/locales/en.json @@ -1,4 +1,20 @@ { + "trash": { + "title": "RECYCLE BIN", + "hint": "Daily summaries and moments stay here until you restore or permanently delete them.", + "open": "OPEN RECYCLE BIN ({count})", + "moveHint": "This memory will move to the recycle bin. You can restore it later.", + "moved": "Moved to recycle bin", + "restore": "RESTORE", + "restored": "Memory restored", + "empty": "The recycle bin is empty.", + "purge": "DELETE PERMANENTLY", + "purgeQuestion": "Permanently delete this memory?", + "purgeHint": "This removes the memory and its favorite entry. You cannot restore it from the recycle bin afterward.", + "purged": "Permanently deleted", + "dateConflict": "A daily summary already exists on this date. Move that summary to the recycle bin before restoring this one.", + "unavailable": "This memory is no longer available." + }, "moments": { "label": "MOMENTS", "title": "Quick memory", diff --git a/public/locales/es.json b/public/locales/es.json index 03d3de3..81123ea 100644 --- a/public/locales/es.json +++ b/public/locales/es.json @@ -1,4 +1,20 @@ { + "trash": { + "title": "PAPELERA", + "hint": "Los resúmenes y momentos permanecen aquí hasta restaurarlos o eliminarlos definitivamente.", + "open": "ABRIR PAPELERA ({count})", + "moveHint": "Este recuerdo se moverá a la papelera. Podrás restaurarlo.", + "moved": "Movido a la papelera", + "restore": "RESTAURAR", + "restored": "Recuerdo restaurado", + "empty": "La papelera está vacía.", + "purge": "ELIMINAR DEFINITIVAMENTE", + "purgeQuestion": "¿Eliminar definitivamente este recuerdo?", + "purgeHint": "Se eliminarán el texto y su favorito. No podrás restaurarlo desde la papelera.", + "purged": "Eliminado definitivamente", + "dateConflict": "Ya hay un resumen en esta fecha. Muévelo a la papelera antes de restaurar este.", + "unavailable": "Este recuerdo ya no está disponible." + }, "moments": { "label": "MOMENTOS", "title": "Nota rápida", diff --git a/public/locales/fr.json b/public/locales/fr.json index 08fad7b..aa5142e 100644 --- a/public/locales/fr.json +++ b/public/locales/fr.json @@ -1,4 +1,20 @@ { + "trash": { + "title": "CORBEILLE", + "hint": "Les résumés et instants restent ici jusqu’à leur restauration ou suppression définitive.", + "open": "OUVRIR LA CORBEILLE ({count})", + "moveHint": "Ce souvenir sera déplacé dans la corbeille. Vous pourrez le restaurer.", + "moved": "Déplacé dans la corbeille", + "restore": "RESTAURER", + "restored": "Souvenir restauré", + "empty": "La corbeille est vide.", + "purge": "SUPPRIMER DÉFINITIVEMENT", + "purgeQuestion": "Supprimer définitivement ce souvenir ?", + "purgeHint": "Le texte et son favori seront supprimés. La restauration sera impossible depuis la corbeille.", + "purged": "Supprimé définitivement", + "dateConflict": "Un résumé existe à cette date. Déplacez-le dans la corbeille avant cette restauration.", + "unavailable": "Ce souvenir n’est plus disponible." + }, "moments": { "label": "INSTANTS", "title": "Note rapide", diff --git a/public/locales/ja.json b/public/locales/ja.json index c517207..8103fe8 100644 --- a/public/locales/ja.json +++ b/public/locales/ja.json @@ -1,4 +1,20 @@ { + "trash": { + "title": "ごみ箱", + "hint": "日々のまとめと瞬間は、復元または完全削除するまで残ります。", + "open": "ごみ箱を開く({count})", + "moveHint": "この記憶をごみ箱に移します。後で復元できます。", + "moved": "ごみ箱へ移動しました", + "restore": "復元", + "restored": "復元しました", + "empty": "ごみ箱は空です。", + "purge": "完全に削除", + "purgeQuestion": "この記憶を完全に削除しますか?", + "purgeHint": "本文とお気に入りを削除します。ごみ箱から復元できなくなります。", + "purged": "完全に削除しました", + "dateConflict": "この日にはまとめがあります。先にそのまとめをごみ箱へ移してください。", + "unavailable": "この記憶は利用できません。" + }, "moments": { "label": "瞬間の記録", "title": "クイックメモ", diff --git a/public/locales/ru.json b/public/locales/ru.json index d4f5c4b..ffff69a 100644 --- a/public/locales/ru.json +++ b/public/locales/ru.json @@ -1,4 +1,20 @@ { + "trash": { + "title": "КОРЗИНА", + "hint": "Итоги дня и моменты остаются здесь до восстановления или окончательного удаления.", + "open": "ОТКРЫТЬ КОРЗИНУ ({count})", + "moveHint": "Запись попадёт в корзину. Её можно восстановить позже.", + "moved": "Перемещено в корзину", + "restore": "ВОССТАНОВИТЬ", + "restored": "Запись восстановлена", + "empty": "Корзина пуста.", + "purge": "УДАЛИТЬ НАВСЕГДА", + "purgeQuestion": "Удалить эту запись навсегда?", + "purgeHint": "Текст и избранное будут удалены. Восстановить из корзины будет невозможно.", + "purged": "Удалено навсегда", + "dateConflict": "На эту дату уже есть итог дня. Сначала переместите его в корзину.", + "unavailable": "Эта запись больше недоступна." + }, "moments": { "label": "МОМЕНТЫ", "title": "Быстрая запись", diff --git a/public/locales/zh-CN.json b/public/locales/zh-CN.json index e540cb8..5f6649e 100644 --- a/public/locales/zh-CN.json +++ b/public/locales/zh-CN.json @@ -1,4 +1,20 @@ { + "trash": { + "title": "回收站", + "hint": "每日总结和瞬间保留在这里,直到你恢复或永久删除。", + "open": "打开回收站({count})", + "moveHint": "这条记忆将移入回收站,之后可以恢复。", + "moved": "已移入回收站", + "restore": "恢复", + "restored": "记忆已恢复", + "empty": "回收站为空。", + "purge": "永久删除", + "purgeQuestion": "永久删除这条记忆?", + "purgeHint": "正文和收藏关系将被删除,之后无法从回收站恢复。", + "purged": "已永久删除", + "dateConflict": "该日期已有每日总结,请先将现有总结移入回收站,再恢复这条记忆。", + "unavailable": "这条记忆已不可用。" + }, "moments": { "label": "瞬间记录", "title": "快速记录", diff --git a/public/locales/zh-HK.json b/public/locales/zh-HK.json index f4f519d..4a2f96b 100644 --- a/public/locales/zh-HK.json +++ b/public/locales/zh-HK.json @@ -1,4 +1,20 @@ { + "trash": { + "title": "回收站", + "hint": "每日總結和瞬間保留在這裡,直到你恢復或永久刪除。", + "open": "開啟回收站({count})", + "moveHint": "這條記憶將移入回收站,之後可以恢復。", + "moved": "已移入回收站", + "restore": "恢復", + "restored": "記憶已恢復", + "empty": "回收站為空。", + "purge": "永久刪除", + "purgeQuestion": "永久刪除這條記憶?", + "purgeHint": "正文和收藏關係將被刪除,之後無法從回收站恢復。", + "purged": "已永久刪除", + "dateConflict": "該日期已有每日總結,請先將現有總結移入回收站,再恢復這條記憶。", + "unavailable": "這條記憶已不可用。" + }, "moments": { "label": "瞬間記錄", "title": "快速記錄", diff --git a/public/locales/zh-MO.json b/public/locales/zh-MO.json index dc032a1..5c5b522 100644 --- a/public/locales/zh-MO.json +++ b/public/locales/zh-MO.json @@ -1,4 +1,20 @@ { + "trash": { + "title": "回收站", + "hint": "每日總結和瞬間保留在這裡,直到你恢復或永久刪除。", + "open": "開啟回收站({count})", + "moveHint": "這條記憶將移入回收站,之後可以恢復。", + "moved": "已移入回收站", + "restore": "恢復", + "restored": "記憶已恢復", + "empty": "回收站為空。", + "purge": "永久刪除", + "purgeQuestion": "永久刪除這條記憶?", + "purgeHint": "正文和收藏關係將被刪除,之後無法從回收站恢復。", + "purged": "已永久刪除", + "dateConflict": "該日期已有每日總結,請先將現有總結移入回收站,再恢復這條記憶。", + "unavailable": "這條記憶已不可用。" + }, "moments": { "label": "瞬間記錄", "title": "快速記錄", diff --git a/public/locales/zh-TW.json b/public/locales/zh-TW.json index ee2a881..77baf92 100644 --- a/public/locales/zh-TW.json +++ b/public/locales/zh-TW.json @@ -1,4 +1,20 @@ { + "trash": { + "title": "回收站", + "hint": "每日總結和瞬間保留在這裡,直到你還原或永久刪除。", + "open": "開啟回收站({count})", + "moveHint": "這條記憶將移入回收站,之後可以還原。", + "moved": "已移入回收站", + "restore": "還原", + "restored": "記憶已還原", + "empty": "回收站為空。", + "purge": "永久刪除", + "purgeQuestion": "永久刪除這條記憶?", + "purgeHint": "正文和收藏關係將被刪除,之後無法從回收站還原。", + "purged": "已永久刪除", + "dateConflict": "該日期已有每日總結,請先將現有總結移入回收站,再還原這條記憶。", + "unavailable": "這條記憶已無法使用。" + }, "moments": { "label": "瞬間記錄", "title": "快速記錄", diff --git a/public/service-worker.js b/public/service-worker.js index f5c39c8..250149e 100644 --- a/public/service-worker.js +++ b/public/service-worker.js @@ -1,4 +1,4 @@ -const CACHE = 'life-os-shell-v1.23.0'; +const CACHE = 'life-os-shell-v1.24.0'; const SHELL = [ '/', '/index.html', '/manifest.webmanifest', '/life-os-icon.svg', '/local-db-worker.js', '/sqlite3.mjs', '/sqlite3.wasm' diff --git a/public/system-navigation.js b/public/system-navigation.js index 40e41b3..297f463 100644 --- a/public/system-navigation.js +++ b/public/system-navigation.js @@ -27,7 +27,7 @@ shell.innerHTML = `
${t('settings')}

${t(active)}

${active === 'home' ? `

${t('homeHint')}

` : ''}
`; const view = shell.querySelector('.system-settings-view'); if (active === 'home') { - view.innerHTML = `
${t('device')}

${t('deviceHint')}

${t('version', { version: window.LifeOSVersion || '1.23.0' })}
${t('quickSettings')}
${['appearance', 'notifications', 'language', 'data'].map(id => `
${navigationButton(id, true)}

${t(`${id}Hint`)}

`).join('')}
`; + view.innerHTML = `
${t('device')}

${t('deviceHint')}

${t('version', { version: window.LifeOSVersion || '1.24.0' })}
${t('quickSettings')}
${['appearance', 'notifications', 'language', 'data'].map(id => `
${navigationButton(id, true)}

${t(`${id}Hint`)}

`).join('')}
`; } else { const group = document.createElement('div'); group.className = 'settings system-settings-group'; diff --git a/public/terminal-app.js b/public/terminal-app.js index 04f3581..dc182c9 100644 --- a/public/terminal-app.js +++ b/public/terminal-app.js @@ -150,7 +150,7 @@ return { message: new Intl.DateTimeFormat(LifeI18n.locale(), options).format(new Date()) }; } if (kind === 'uptime') { if (verb) throw new Error('usage'); const seconds = Math.floor((Date.now() - startedAt) / 1000); return { message: t('uptime', { minutes: Math.floor(seconds / 60), seconds: seconds % 60 }) }; } - if (kind === 'version') { if (verb) throw new Error('usage'); return { message: `Life OS v${window.LifeOSVersion || '1.23.0'}` }; } + if (kind === 'version') { if (verb) throw new Error('usage'); return { message: `Life OS v${window.LifeOSVersion || '1.24.0'}` }; } if (kind === 'status') { if (verb) throw new Error('usage'); const data = board(); return { message: t('status', { memories: mems().length, goals: data.goals.length, tasks: data.tasks.length }) }; } if (kind === 'apps') { if (verb) throw new Error('usage'); return { message: Object.keys(APPS).map(id => `${id} — ${LifeI18n.t(`app.${id}`)}`).join('\n') }; } if (kind === 'history') { if (verb) throw new Error('usage'); return { message: history.slice(-20).map((entry,index) => `${index + 1}. ${entry}`).join('\n') || t('empty') }; } @@ -235,7 +235,7 @@ }; window.terminalApp = node => { if (node.querySelector('.terminal-shell') && node.dataset.terminalLocale === lang()) { output(node); return; } - if (!welcomed) { lines.unshift({ value: t('welcome', { version: window.LifeOSVersion || '1.23.0' }), kind: 'system' }); welcomed = true; } + if (!welcomed) { lines.unshift({ value: t('welcome', { version: window.LifeOSVersion || '1.24.0' }), kind: 'system' }); welcomed = true; } node.dataset.terminalLocale = lang(); node.innerHTML = `
Life OS / ${t('title')}${t('hint')}
`; output(node); composer(node, Boolean(compose)); diff --git a/scripts/build.mjs b/scripts/build.mjs index 51d0b65..1fe63e8 100644 --- a/scripts/build.mjs +++ b/scripts/build.mjs @@ -13,7 +13,7 @@ const [rawIndexHtml, addonsJs, backupJs, bootGuardJs, localDbJs, localDbWorkerJs readFile(new URL("../node_modules/@sqlite.org/sqlite-wasm/dist/sqlite3.wasm", import.meta.url)), text("i18n.js"), text("tasks.js"), text("calendar.js"), text("notifications.js"), text("i18n-renderers.js"), text("desktop-personalization.js"), text("desktop-widgets.js"), text("system-navigation.js"), text("browser-app.js"), text("data-actions.js"), text("terminal-app.js"), text("db-admin.js"), text("manifest.webmanifest"), text("service-worker.js"), text("life-os-icon.svg"), readFile(new URL("../public/locales/en.json", import.meta.url), "utf8"), readFile(new URL("../public/locales/zh-CN.json", import.meta.url), "utf8") ]); -const release = "1.23.0"; +const release = "1.24.0"; const localeEnJs = `window.LifeOSLocales=window.LifeOSLocales||{};window.LifeOSLocales.en=${localeEn};`; const localeZhJs = `window.LifeOSLocales=window.LifeOSLocales||{};window.LifeOSLocales['zh-CN']=${localeZh};`; const extraLocaleCodes = ['zh-HK', 'zh-MO', 'zh-TW', 'ar', 'fr', 'ru', 'es', 'ja']; diff --git a/scripts/test-cloud.mjs b/scripts/test-cloud.mjs index 8dc84bb..0803f5c 100644 --- a/scripts/test-cloud.mjs +++ b/scripts/test-cloud.mjs @@ -152,4 +152,9 @@ for (const [id, kind] of [['daily-same-date','daily'],['moment-one','moment'],[' const sameDate=(await call('/api/lifeos-state')).body.state.memories.filter(item=>item.date==='2026-10-13'); assert.equal(sameDate.length,3); assert.equal(sameDate.filter(item=>item.kind==='moment').length,2); +const trashed = {...sameDate.find(item=>item.id==='moment-one'),trashedAt:'2026-10-13T03:00:00Z'}; +assert.equal((await call('/api/lifeos-sync','POST',{kind:'memories',id:trashed.id,baseVersion:1,value:trashed})).status,200); +assert.ok((await call('/api/lifeos-state')).body.state.memories.find(item=>item.id===trashed.id).trashedAt,'trash flag survives cross-device load'); +delete trashed.trashedAt; +assert.equal((await call('/api/lifeos-sync','POST',{kind:'memories',id:trashed.id,baseVersion:2,value:trashed})).status,200,'restoring uses the same cloud record ID'); console.log("Life OS record migration, sync conflict, tags, same-day moments and user isolation valid"); diff --git a/scripts/test-moments.mjs b/scripts/test-moments.mjs index bd3644e..581b66c 100644 --- a/scripts/test-moments.mjs +++ b/scripts/test-moments.mjs @@ -2,9 +2,10 @@ import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import vm from 'node:vm'; let records = [{ id:'legacy',date:'2026-10-13',text:'Original daily summary',mood:'clear',energy:5 }]; +let favorites = [{id:'favorite-legacy',memoryId:'legacy'}]; const context = vm.createContext({ - sys:()=>({tasksBoard:{tasks:[],goals:[]}}), mems:()=>structuredClone(records), museum:()=>[], - save:(key,value)=>{if(key==='lifeos_memories') records=structuredClone(value);}, renderAll(){}, + sys:()=>({tasksBoard:{tasks:[],goals:[]}}), mems:()=>structuredClone(records), museum:()=>structuredClone(favorites), + save:(key,value)=>{if(key==='lifeos_memories') records=structuredClone(value);if(key==='lifeos_museum') favorites=structuredClone(value);}, renderAll(){}, filmFor:()=>({filmTitle:'Prompt',filmSubtitle:'',filmLine:''}), day:()=> '2026-10-13', crypto:globalThis.crypto }); context.window=context; @@ -24,6 +25,13 @@ assert.throws(()=>action.createMemory({date:'2026-10-13',text:'Duplicate summary assert.throws(()=>action.createMemory({kind:'moment',text:' '}),/invalidTitle/); assert.throws(()=>action.createMemory({kind:'moment',text:'Note',date:'2026-02-30'}),/invalidDate/); action.deleteMemory(first.id); +assert.equal(records.length,3); +assert.equal(context.mems().length,2); +assert.ok(records.find(item=>item.id===first.id).trashedAt); +action.restoreMemory(first.id); +assert.equal(context.mems().length,3); +action.deleteMemory(first.id); +action.purgeMemory(first.id); assert.equal(records.length,2); assert.ok(records.some(item=>item.id===second.id)); assert.ok(records.some(item=>item.id==='legacy')); @@ -36,4 +44,17 @@ assert.ok(records.some(item=>item.id==='imported-moment'),'merge preserves anoth assert.ok(!records.some(item=>item.id==='duplicate-daily'),'merge does not introduce a second daily summary'); context.applyImport('merge'); assert.equal(records.filter(item=>item.id==='imported-moment').length,1,'repeated import is idempotent'); +action.deleteMemory('legacy'); +assert.equal(context.museum().length,0,'trashed favorites are hidden'); +assert.equal(favorites.length,1,'favorite relationship survives trashing'); +const replacement = action.createMemory({date:'2026-10-13',text:'Replacement summary'}); +assert.ok(records.some(item=>item.id==='legacy' && item.trashedAt),'creating a summary retains trash'); +assert.throws(()=>action.restoreMemory('legacy'),/memoryExists/,'restore never overwrites a new summary'); +action.deleteMemory(replacement.id); +action.restoreMemory('legacy'); +assert.equal(context.museum().length,1,'restoring retains favorite ID'); +assert.equal(context.museum()[0].id,'favorite-legacy'); +action.deleteMemory('legacy'); +action.purgeMemory('legacy'); +assert.equal(favorites.length,0,'permanent deletion removes only the corresponding favorite'); console.log('Life OS same-day moments, legacy summary compatibility and deletion valid'); diff --git a/scripts/validate.mjs b/scripts/validate.mjs index e6e90e9..e57df4a 100644 --- a/scripts/validate.mjs +++ b/scripts/validate.mjs @@ -96,7 +96,7 @@ const editModal = { innerHTML: '' }, editToasts = [], editContent = { innerHTML: const editContext = vm.createContext({ document: { createElement: () => ({}), head: { append() {} }, querySelector: selector => selector === '#modal' ? editModal : null }, LifeI18n: { t: key => key, locale: () => 'en-US' }, - sys: () => editState, save: (key, value) => { if (key === 'lifeos_system') Object.assign(editState, structuredClone(value)); }, + sys: () => editState, mems: () => [], museum: () => [], save: (key, value) => { if (key === 'lifeos_system') Object.assign(editState, structuredClone(value)); }, renderAll: () => {}, closeModal: () => { editModal.innerHTML = ''; }, toast: value => editToasts.push(value), day: () => '2026-10-02', setInterval: () => 0, setTimeout: () => 0, crypto: globalThis.crypto, Date }); @@ -271,7 +271,8 @@ assert.match(command('yes').message, /terminal\.flow\.deleted/); assert.equal(terminalStorage.get('lifeos_system').tasksBoard.tasks.length, 1); assert.match(command('memory delete 2026-09-30').message, /terminal\.flow\.confirmDelete/); assert.equal(command('yes').message.includes('terminal.flow.deleted'), true); -assert.equal(terminalStorage.get('lifeos_memories').some(item => item.date === '2026-09-30'), false); +assert.equal(terminalContext.mems().some(item => item.date === '2026-09-30'), false); +assert.ok(terminalStorage.get('lifeos_memories').find(item => item.date === '2026-09-30').trashedAt, 'terminal deletion retains a restorable record'); terminalContext.LifeOSActions.createTask({ title: 'Linked task', goalId: terminalStorage.get('lifeos_system').tasksBoard.goals[0].id }); assert.match(command('goal delete 1').message, /terminal\.flow\.confirmDelete/); assert.match(command('yes').message, /terminal\.flow\.deleted/); @@ -284,7 +285,7 @@ assert.ok(command('date').message.length > 8); assert.ok(command('time').message.includes(':')); assert.ok(command('datetime').message.length > 12); assert.equal(command('uptime').message, 'terminal.uptime'); -assert.equal(command('version').message, 'Life OS v1.23.0'); +assert.equal(command('version').message, 'Life OS v1.24.0'); assert.equal(command('status').message, 'terminal.status'); assert.match(command('apps').message, /calendar/); assert.equal(command('echo "hello Life OS"').message, 'hello Life OS'); @@ -614,3 +615,12 @@ uiContext.today(dailySurface); assert.match(dailySurface.innerHTML, /]*>DAILY TEXT<\/textarea>/, 'daily editor never loads a same-day moment'); assert.match(dailySurface.innerHTML, /MOMENT TEXT/, 'today lists saved same-day moments separately'); assert.equal(uiContext.longest([{date:'2026-10-11'},{date:'2026-10-12'},{date:'2026-10-12'},{date:'2026-10-13'}]),3,'duplicate dates do not break streaks'); +const uiTrashed = JSON.parse(uiStorage.getItem('lifeos_memories')); +uiTrashed[0].trashedAt='2026-10-13T03:00:00Z'; +uiStorage.setItem('lifeos_memories',JSON.stringify(uiTrashed)); +assert.equal(uiContext.mems().length,1,'trash does not appear in active memory readers'); +uiContext.openRecycleBin(); +assert.match(uiNodes.get('#modal').innerHTML,/MOMENT TEXT/,'recycle bin previews the saved text'); +assert.match(uiNodes.get('#modal').innerHTML,/restoreTrashedMemory/); +uiContext.restoreTrashedMemory('quick-first'); +assert.equal(uiContext.mems().length,2,'restored memory returns to active readers');