From f7923ec3e8c78880e86d85f1c92ec8786812dd70 Mon Sep 17 00:00:00 2001 From: LJM12914 Date: Wed, 25 Nov 2026 03:17:30 +0800 Subject: [PATCH] feat: rebuild settings, attributes, about and startup, drop legacy styles - Settings: one column of grouped settings on base controls. Time zone uses a new filterable base Combobox; an undo history cap input (empty means unlimited); body text size 14/15/16/18 px, default 15. - Attribute manager: resizable list with arrow-key selection, form on base controls; the saved attribute stays selected. - About: version, Electron, Chromium, Node.js, V8 and OS from a new app:get-info query, with a Copy button. - Startup: VS Code-style welcome page sharing the new TitleBar. - Confirmations use ConfirmDialog with a scrolling list of affected pages; toasts move onto tokens. - Retyping an attribute keeps option edits made in the same save, and the confirmation lists exactly the pages that are written. - Library and virtual list scroll handlers ignore events after the list is gone. - Removed every --c-* variable, colors.css, workspace.css, the old size variables and Bloom.svelte. Co-Authored-By: Claude Opus 5.5 --- locales/en.json | 99 +++++-- locales/zh-CN.json | 99 +++++-- main/app/ipc.ts | 17 +- main/knowledge/attributes.ts | 73 ++--- main/knowledge/commit.ts | 2 +- main/knowledge/edits.ts | 22 +- main/knowledge/retention.ts | 2 +- preload/index.ts | 7 +- renderer/components/Feed/FeedReader.svelte | 4 +- .../Knowledge/AttributeManagement.svelte | 21 +- .../Knowledge/AttributeManager.svelte | 239 +++++++++++---- renderer/components/Knowledge/Dialogs.svelte | 109 ++++--- .../components/Knowledge/LibraryGrid.svelte | 8 +- .../Knowledge/confirmation.svelte.ts | 34 ++- .../Knowledge/page-session.svelte.ts | 12 +- renderer/components/Knowledge/purge.ts | 6 +- renderer/components/Tab/restore.ts | 4 +- renderer/components/base/Combobox.svelte | 126 ++++++++ renderer/components/base/ConfirmDialog.svelte | 22 +- renderer/components/base/IconButton.svelte | 4 +- renderer/components/base/TopLayer.svelte | 4 +- renderer/components/base/VirtualList.svelte | 10 +- renderer/components/base/VirtualRows.svelte | 45 +++ renderer/components/base/controls.css | 2 +- renderer/components/layout/App.svelte | 3 +- renderer/components/layout/NavBar.svelte | 16 +- renderer/components/layout/TitleBar.svelte | 21 ++ .../components/layout/preferences.svelte.ts | 91 ++++-- renderer/components/startup/Onboarding.svelte | 276 +++++------------- renderer/components/tabs/About.svelte | 134 ++++----- renderer/components/tabs/Settings.svelte | 259 +++++++++------- renderer/components/utils/Bloom.svelte | 32 -- renderer/preview/components/Catalog.svelte | 2 + .../components/ComboboxExamples.svelte | 19 ++ renderer/styles/base.css | 12 +- renderer/styles/colors.css | 81 ----- renderer/styles/elements.css | 2 +- renderer/styles/global.css | 4 +- renderer/styles/layouts.css | 15 - renderer/styles/workspace.css | 155 ---------- shared/app.ts | 4 +- shared/app/ipc.ts | 15 + shared/content/commands.ts | 3 + shared/content/confirmation.ts | 9 +- shared/types/appearance.ts | 8 +- shared/workspace/views.ts | 2 +- tests/appearance.test.ts | 7 +- tests/attributes.test.ts | 68 +++++ tests/builtin-attrs.test.ts | 12 +- tests/content.test.ts | 5 +- tests/failure.test.ts | 2 +- tests/lifecycle.test.ts | 2 +- tests/perf/library-check.ts | 4 +- tests/perf/library-workflow.ts | 12 +- tests/perf/reader-workflow.ts | 8 +- tests/services.test.ts | 4 +- tests/tabs.test.ts | 17 +- 57 files changed, 1282 insertions(+), 993 deletions(-) create mode 100644 renderer/components/base/Combobox.svelte create mode 100644 renderer/components/base/VirtualRows.svelte create mode 100644 renderer/components/layout/TitleBar.svelte delete mode 100644 renderer/components/utils/Bloom.svelte create mode 100644 renderer/preview/components/ComboboxExamples.svelte delete mode 100644 renderer/styles/colors.css delete mode 100644 renderer/styles/workspace.css diff --git a/locales/en.json b/locales/en.json index af1245f..86da7a3 100644 --- a/locales/en.json +++ b/locales/en.json @@ -50,7 +50,6 @@ "attribute-readonly": "This attribute is managed by its corresponding operation.", "import-regular-file": "Choose a regular file.", "import-pdf-only": "Only PDF files can create paper pages.", - "import-failed": "Some files could not be imported.", "attachment-missing": "The attachment was not found.", "attachment-owned": "An attachment can belong to only one file attribute on one page.", @@ -200,27 +199,66 @@ "settings-invalid-update": "The settings update is invalid.", "workspace-in-use": "This workspace is already open in another Labloom window." }, + "app": { + "name": "知织 Labloom" + }, + "about": { + "version": "Version", + "electron": "Electron", + "chromium": "Chromium", + "node": "Node.js", + "v8": "V8", + "os": "OS", + "license": "License", + "copied": "Copied" + }, "startup": { - "brand": "Labloom", - "welcome": "Let knowledge grow from here.", - "opening": "Opening workspace", - "intro": "Welcome to Labloom. Choose a space for your ideas.", - "failed": "Unable to open workspace", - "retry": "Retry", - "create": "Create workspace", - "createHint": "Choose an empty folder to begin.", + "start": "Start", + "opening": "Opening workspace…", + "failed": "Failed to open workspace", + "newWorkspace": "New Workspace…", + "openWorkspace": "Open Workspace…", + "configBackup": "The configuration was damaged. A backup was saved to", "open": "Open existing workspace", - "openHint": "Choose a workspace folder you used before.", - "pending": "Working, please wait…", - "localHint": "Workspaces are stored locally. Choose a lasting location.", "createTitle": "Choose an empty folder for the workspace", "openTitle": "Choose an existing workspace", - "createHere": "Create here", - "configBackup": "The configuration could not be read. A backup was saved to {{path}}. Select your workspace again." + "createHere": "Create here" }, "language": { - "label": "Interface language", - "hint": "Used for startup, errors and confirmations." + "label": "Language", + "hint": "Controls the language of the interface." + }, + "settings": { + "appearance": "Appearance", + "theme": "Theme", + "themeHint": "Controls the interface colors.", + "light": "Light", + "dark": "Dark", + "system": "Follow system", + "readingSize": "Body font size", + "readingSizeHint": "Applies to the page editor and feed articles.", + "motion": "Motion", + "motionHint": "Controls interface animations and transitions.", + "time": "Time", + "timeZone": "Time zone", + "timeZoneHint": "Used for displaying, entering, and searching dates and times, and for grouping calendar entries.", + "undo": "Undo", + "historyLimit": "Undo history limit", + "historyLimitHint": "Total undo entries kept across the workspace. The oldest entries are discarded first when the limit is exceeded.", + "unlimited": "Unlimited", + "invalidHistoryLimit": "Enter a positive integer or leave the field empty for unlimited history.", + "workspace": "Workspace", + "workspaceLoading": "Reading workspace information…" + }, + "combobox": { + "title": "Combobox", + "filter": "Filter", + "empty": "No matches", + "sampleFew": "A few options", + "sampleMany": "500 options", + "sampleEmpty": "No matches", + "sampleDisabled": "Disabled", + "sampleOption": "Option {{number}}" }, "feed": { "sources": "Sources", @@ -321,14 +359,14 @@ "attributeImpact": "Attribute values on the following pages will be cleared, removed or adjusted.", "attributeRecycle": "{{count}} pages will also lose their retaining references and move to the recycle bin.", "purge": "Permanently delete pages", - "purgeImpact": "Permanently delete {{count}} pages: {{titles}}. This cannot be undone.", + "purgeImpact": "Permanently delete {{count}} pages. This cannot be undone.", "deletedLinks": "{{count}} link references will display “Deleted”.", "deleteExcerpt": "Delete {{excerpt}}.", "positions": "will disappear from {{count}} positions", "pagePositions": "will disappear from {{count}} positions across {{pages}} pages", "deleteImpact": "After deleting {{excerpt}}, {{impact}}.", "excerptImpact": "{{excerpt}} {{impact}}.", - "recycle": "Move to the recycle bin: {{titles}}.", + "recycle": "Move {{count}} pages to the recycle bin.", "join": ", ", "listJoin": ", ", "closeTimeout": "The window did not confirm that saving finished.", @@ -348,13 +386,16 @@ "markRead": "Mark {{count}} unread items from “{{source}}” as read?", "allSources": "All sources", "confirmMarkRead": "Mark all as read", - "retry": "Retry" + "retry": "Retry", + "recycleOne": "Move one page to the recycle bin.", + "purgeOne": "Permanently delete one page. This cannot be undone.", + "affectedPages": "Affected pages" }, "command": { "newPage": "New Page", "importPDF": "Import PDF", "closeTab": "Close Editor", - "settings": "Preferences", + "settings": "Settings", "undo": "Undo", "redo": "Redo", "cut": "Cut", @@ -554,7 +595,6 @@ "empty": "No pages", "count": "{{count}} pages", "selected": "{{count}} items selected", - "type": "Type", "paper": "Paper", "editable": "Note", @@ -570,7 +610,6 @@ "property": "Add a property condition", "add": "Add condition", "openFile": "Open in System Application", - "yes": "Yes", "no": "No" }, @@ -754,6 +793,22 @@ "manualDelete": "Manually deleted", "unreachable": "No remaining references" }, + "attributes": { + "create": "New Attribute", + "newName": "New Attribute", + "builtins": "Built-in Attributes", + "custom": "Custom Attributes", + "listWidth": "Attribute list width", + "name": "Name", + "type": "Type", + "options": "Options", + "optionName": "Option name", + "complete": "Complete", + "removeOption": "Remove option", + "addOption": "Add option", + "save": "Save", + "delete": "Delete Attribute" + }, "attributeType": { "string": "Text", "number": "Number", diff --git a/locales/zh-CN.json b/locales/zh-CN.json index 4bbade5..0bd1d5a 100644 --- a/locales/zh-CN.json +++ b/locales/zh-CN.json @@ -50,7 +50,6 @@ "attribute-readonly": "此属性由相应业务操作维护。", "import-regular-file": "请选择普通文件。", "import-pdf-only": "只能用 PDF 文件新建文献。", - "import-failed": "部分文件导入失败。", "attachment-missing": "附件不存在。", "attachment-owned": "附件只能属于一个页面的一个文件属性。", @@ -200,27 +199,66 @@ "settings-invalid-update": "设置内容无效。", "workspace-in-use": "这个工作区已在另一个 Labloom 窗口中打开。" }, + "app": { + "name": "知织 Labloom" + }, + "about": { + "version": "版本", + "electron": "Electron", + "chromium": "Chromium", + "node": "Node.js", + "v8": "V8", + "os": "操作系统", + "license": "许可证", + "copied": "已复制" + }, "startup": { - "brand": "知织", - "welcome": "让知识,从这里生长。", - "opening": "正在打开工作区", - "intro": "欢迎来到知织。选一块属于你的空间,种下第一颗灵感。", - "failed": "暂时无法进入工作区", - "retry": "重试", - "create": "创建工作区", - "createHint": "选择一个空文件夹,开始新的研究。", + "start": "开始", + "opening": "正在打开工作区…", + "failed": "打开工作区失败", + "newWorkspace": "新建工作区…", + "openWorkspace": "打开工作区…", + "configBackup": "配置文件损坏,备份已保存到", "open": "打开已有工作区", - "openHint": "选择之前使用的工作文件夹。", - "pending": "正在处理,请稍候…", - "localHint": "工作区保存在本机,请选择一个便于长期保存的位置。", "createTitle": "选择一个空文件夹来创建工作区", "openTitle": "选择已有的工作区", - "createHere": "在此创建", - "configBackup": "无法读取配置,备份已保存到{{path}}。请重新选择工作区。" + "createHere": "在此创建" }, "language": { - "label": "界面语言", - "hint": "用于启动页、错误提示和确认框。" + "label": "语言", + "hint": "控制界面使用的语言。" + }, + "settings": { + "appearance": "外观", + "theme": "主题", + "themeHint": "控制界面的配色。", + "light": "浅色", + "dark": "深色", + "system": "跟随系统", + "readingSize": "正文字号", + "readingSizeHint": "用于页面编辑器和订阅正文。", + "motion": "动效", + "motionHint": "控制界面动画和过渡效果。", + "time": "时间", + "timeZone": "时区", + "timeZoneHint": "用于日期和时间的显示、输入、搜索和日历分组。", + "undo": "撤销", + "historyLimit": "撤销记录上限", + "historyLimitHint": "整个工作区可保留的撤销记录总数。超出上限时,先丢掉最早的记录。", + "unlimited": "不限", + "invalidHistoryLimit": "请输入正整数,或留空表示不限。", + "workspace": "工作区", + "workspaceLoading": "正在读取工作区信息…" + }, + "combobox": { + "title": "可筛选下拉框", + "filter": "筛选", + "empty": "没有匹配项", + "sampleFew": "少量选项", + "sampleMany": "500个选项", + "sampleEmpty": "无匹配项", + "sampleDisabled": "禁用", + "sampleOption": "选项 {{number}}" }, "feed": { "sources": "订阅来源", @@ -321,14 +359,14 @@ "attributeImpact": "以下页面的属性值会被清空、移除或调整。", "attributeRecycle": "同时有{{count}}个页面失去保留关系,将进入回收站。", "purge": "永久删除页面", - "purgeImpact": "将永久删除{{count}}个页面:{{titles}}。此操作无法撤销。", + "purgeImpact": "将永久删除{{count}}个页面,无法撤销。", "deletedLinks": "{{count}}个链接引用将显示“已删除”。", "deleteExcerpt": "将删除{{excerpt}}。", "positions": "将从{{count}}个位置消失", "pagePositions": "将从{{pages}}个页面的{{count}}个位置消失", "deleteImpact": "删除{{excerpt}}后,{{impact}}。", "excerptImpact": "{{excerpt}}{{impact}}。", - "recycle": "将移入回收站:{{titles}}。", + "recycle": "将把{{count}}个页面移入回收站。", "join": ",", "listJoin": "、", "closeTimeout": "界面未能确认保存完成。", @@ -348,13 +386,16 @@ "markRead": "将“{{source}}”的{{count}}条未读内容标为已读?", "allSources": "全部来源", "confirmMarkRead": "全部标为已读", - "retry": "重试" + "retry": "重试", + "recycleOne": "将把1个页面移入回收站。", + "purgeOne": "将永久删除1个页面,无法撤销。", + "affectedPages": "受影响的页面" }, "command": { "newPage": "新建页面", "importPDF": "导入 PDF", "closeTab": "关闭标签", - "settings": "偏好设置", + "settings": "设置", "undo": "撤销", "redo": "重做", "cut": "剪切", @@ -554,7 +595,6 @@ "empty": "没有页面", "count": "{{count}} 个页面", "selected": "已选择 {{count}} 项", - "type": "类型", "paper": "文献", "editable": "笔记", @@ -570,7 +610,6 @@ "property": "按属性添加条件", "add": "添加条件", "openFile": "用系统程序打开", - "yes": "是", "no": "否" }, @@ -754,6 +793,22 @@ "manualDelete": "手动删除", "unreachable": "失去保留关系" }, + "attributes": { + "create": "新建属性", + "newName": "新属性", + "builtins": "内置属性", + "custom": "自定义属性", + "listWidth": "属性列表宽度", + "name": "名称", + "type": "类型", + "options": "选项", + "optionName": "选项名称", + "complete": "已完成", + "removeOption": "移除选项", + "addOption": "添加选项", + "save": "保存", + "delete": "删除属性" + }, "attributeType": { "string": "文本", "number": "数字", diff --git a/main/app/ipc.ts b/main/app/ipc.ts index e1ee060..cbd35cf 100644 --- a/main/app/ipc.ts +++ b/main/app/ipc.ts @@ -1,12 +1,23 @@ -import type { BrowserWindow } from "electron"; +import { app, type BrowserWindow } from "electron"; +import { machine, type as osType } from "node:os"; import typia from "typia"; -import { appChannels, type AppMessages } from "../../shared/app/ipc"; -import { invalid, on, register, route, type Messages } from "../ipc"; +import { appChannels, appQueryChannels, type AppMessages, type AppQueries } from "../../shared/app/ipc"; +import { invalid, on, register, route, type Messages, type Routes } from "../ipc"; import * as lifecycle from "../lifecycle"; type Args = Parameters; export function registerAppIPCs(window: BrowserWindow): void { const contents = window.webContents; + register(contents, appQueryChannels, { + getInfo: route(typia.createAssert>(invalid), () => ({ + version: app.getVersion(), + electron: process.versions.electron, + chromium: process.versions.chrome, + node: process.versions.node, + v8: process.versions.v8, + os: { type: osType(), arch: machine(), version: process.getSystemVersion() } + })) + } satisfies Routes); register(contents, appChannels, { openDevTools: route(typia.createAssert>(invalid), () => contents.openDevTools({ mode: "detach" })), setFrameColors: route(typia.createAssert>(invalid), (color, symbolColor) => { diff --git a/main/knowledge/attributes.ts b/main/knowledge/attributes.ts index 3d34bd8..f3cad62 100644 --- a/main/knowledge/attributes.ts +++ b/main/knowledge/attributes.ts @@ -3,7 +3,7 @@ import { createHash } from "node:crypto"; import { builtinAttrs, builtinAttrsByPageKind, editableBuiltinMetadata, isBuiltin } from "../../shared/attrs/builtins"; import { convertValue } from "../../shared/attrs/convert"; import { resolveAttributeDefinition } from "../../shared/attrs/definitions"; -import { attributeTargetKind, attributeTargets, convertMetadata, decodeValue, defaultValue, encodeValue, validUUID, validateDefinition } from "../../shared/attrs/values"; +import { attributeTargetKind, attributeTargets, decodeValue, defaultValue, encodeValue, record, validUUID, validateDefinition } from "../../shared/attrs/values"; import { resolveTimeZone } from "../../shared/content/time"; import { recurrenceMinutes } from "../../shared/content/timers"; import { LabloomError } from "../../shared/failure"; @@ -117,15 +117,15 @@ export function initializePage(pageId: string): void { function prepareDefinition(id: string, input: AttributeDefinition | null, before: AttributeDefinition | undefined): AttributeDefinition | null { if (input) { - if (before && before.type !== input.type) { - let metadata = convertMetadata(before.type, input.type, before.metadata); - if (input.type === "status" && input.metadata.options) { - metadata = { options: input.metadata.options.map(option => ({ ...option, group: option.group ?? "incomplete" })) }; - } - else if (before.type === "status" && input.type === "select" && input.metadata.options) { - metadata = { options: input.metadata.options.map(({ id, name }) => ({ id, name })) }; - } - input = { ...input, metadata }; + const options = input.metadata?.options, grouped = input.type === "status"; + if (before && before.type !== input.type && (grouped || before.type === "status") && record(input.metadata) && Array.isArray(options)) { + const normalized = options.map(option => { + if (!record(option)) return option; + if (grouped) return option.group === undefined ? { ...option, group: "incomplete" as const } : option; + const { group: _group, ...rest } = option; + return rest; + }); + input = { ...input, metadata: { ...input.metadata, options: normalized } }; } validateDefinition(input); if (id !== input.id) throw new LabloomError({ kind: "attribute-id-immutable" }); @@ -144,18 +144,40 @@ function prepareDefinition(id: string, input: AttributeDefinition | null, before return input; } -export function previewDefinition(id: string, input: AttributeDefinition | null): AttributeImpact { +// Prepare and persist within the same transaction so the confirmation describes the rows being written. +export function prepareDefinitionChange(id: string, input: AttributeDefinition | null): { + impact: AttributeImpact; + before: AttributeDefinition | undefined; + owners: string[]; + persist: () => void; +} { workspace.requireWorkspace(); const row = byId(id), before = row ? resolveAttributeDefinition(row) : undefined; - input = prepareDefinition(id, input, before); + const next = prepareDefinition(id, input, before); const rows = workspace.database().select().from(pageAttrs).where(eq(pageAttrs.attrId, id)).all(); const zone = resolveTimeZone(workspace.timeZone()); - const affected = rows.filter(row => !input || before?.type !== input.type || encodeValue(input, convertStored(before!, input, row.value, zone)) !== row.value); + const affected = rows.filter(row => !next || before?.type !== next.type || encodeValue(next, convertStored(before!, next, row.value, zone)) !== row.value); const titles = new Map((affected.length ? workspace.database().select({ id: pages.id, title: blocks.content }).from(pages).innerJoin(blocks, eq(pages.titleBlockId, blocks.id)).where(inArray(pages.id, affected.map(row => row.pageId))).all() : []).map(row => { const title = row.title ? JSON.parse(row.title).inline?.map((node: { text?: string }) => node.text ?? "").join("") : ""; - return [row.id, title || "未命名"]; + return [row.id, title]; })); - return { token: fingerprint({ id, input, before: row ?? null, rows, zone }), pages: affected.map(row => ({ id: row.pageId, title: titles.get(row.pageId) ?? "未命名" })) }; + const impact: AttributeImpact = { token: fingerprint({ id, input: next, before: row ?? null, rows, zone }), + pages: affected.map(row => ({ id: row.pageId, title: titles.get(row.pageId) ?? "" })) }; + function persist(): void { + if (!next) { + workspace.database().delete(pageAttrs).where(eq(pageAttrs.attrId, id)).run(); + workspace.database().delete(attrsMeta).where(eq(attrsMeta.id, id)).run(); + } + else { + if (before && attributeTargetKind(before.type) && !attributeTargetKind(next.type)) workspace.database().$client.prepare("DELETE FROM link_refs WHERE source_kind='page' AND source_field=?").run(id); + const name = isBuiltin(id) ? null : next.name; + const metadata = isBuiltin(id) && !editableBuiltinMetadata(id) ? {} : next.metadata; + workspace.database().insert(attrsMeta).values({ id, type: next.type, name, metadata }).onConflictDoUpdate({ target: attrsMeta.id, set: { type: next.type, name, metadata } }).run(); + for (const row of rows) persistValues(row.pageId, prepareValues(row.pageId, { [id]: convertStored(before!, next, row.value, zone) }, [], true)); + } + for (const page of impact.pages) persistValues(page.id, prepareValues(page.id, { modified_at: workspace.seconds() }, [], true)); + } + return { impact, before, owners: rows.map(row => row.pageId), persist }; } function convertStored(before: AttributeDefinition, target: AttributeDefinition, stored: unknown, zone: string): AttributeValue { @@ -170,24 +192,9 @@ function convertStored(before: AttributeDefinition, target: AttributeDefinition, export function persistDefinition(id: string, input: AttributeDefinition | null, token?: string): AttributeImpact | null { workspace.requireWorkspace(); return workspace.database().$client.transaction(() => { - const impact = previewDefinition(id, input); - if (impact.pages.length && token !== impact.token) return impact; - const row = byId(id), before = row ? resolveAttributeDefinition(row) : undefined; - const next = prepareDefinition(id, input, before); - const rows = workspace.database().select().from(pageAttrs).where(eq(pageAttrs.attrId, id)).all(); - if (!next) { - workspace.database().delete(pageAttrs).where(eq(pageAttrs.attrId, id)).run(); - workspace.database().delete(attrsMeta).where(eq(attrsMeta.id, id)).run(); - } - else { - if (before && attributeTargetKind(before.type) && !attributeTargetKind(next.type)) workspace.database().$client.prepare("DELETE FROM link_refs WHERE source_kind='page' AND source_field=?").run(id); - const name = isBuiltin(id) ? null : next.name; - const metadata = isBuiltin(id) && !editableBuiltinMetadata(id) ? {} : next.metadata; - workspace.database().insert(attrsMeta).values({ id, type: next.type, name, metadata }).onConflictDoUpdate({ target: attrsMeta.id, set: { type: next.type, name, metadata } }).run(); - const zone = resolveTimeZone(workspace.timeZone()); - for (const row of rows) persistValues(row.pageId, prepareValues(row.pageId, { [id]: convertStored(before!, next, row.value, zone) }, [], true)); - } - for (const page of impact.pages) persistValues(page.id, prepareValues(page.id, { modified_at: workspace.seconds() }, [], true)); + const change = prepareDefinitionChange(id, input); + if (change.impact.pages.length && token !== change.impact.token) return change.impact; + change.persist(); return null; })(); } \ No newline at end of file diff --git a/main/knowledge/commit.ts b/main/knowledge/commit.ts index d26bb36..88eba06 100644 --- a/main/knowledge/commit.ts +++ b/main/knowledge/commit.ts @@ -173,7 +173,7 @@ export function forecast(plan: EditChanges, inspect: string[] = []): ReturnType< function changePreview(plan: EditChanges, { action, deletedBlocks = [], positions }: Review, projection?: Projection): ChangePreview | null { const ids = projection?.changes.filter(row => !row.deleted && row.reason !== null).map(row => row.id) ?? []; if (!ids.length && !deletedBlocks.length) return null; - const name = (id: string): { id: string; title: string } => ({ id, title: data.title(id) }); + const name = (id: string): { id: string; title: string } => ({ id, title: data.title(id, "") }); return { token: fingerprint({ action, ids, ...(positions ? { positions, deletedBlocks } : {}) }), recycled: ids.map(name), direct: ids.filter(id => plan.direct.has(id)).map(name), causes: [...plan.causes], deletedBlocks diff --git a/main/knowledge/edits.ts b/main/knowledge/edits.ts index c161070..61b6e76 100644 --- a/main/knowledge/edits.ts +++ b/main/knowledge/edits.ts @@ -330,18 +330,16 @@ export function setDefinition(id: string, definition: AttributeDefinition | null workspace.requireWorkspace(); try { commit.run({ history: false, confirmation: token }, context => { - const impact = attributes.previewDefinition(id, definition); + const change = attributes.prepareDefinitionChange(id, definition); + const { impact, before: previous, owners } = change; for (const page of impact.pages) data.writable(page.id); - const owners = data.statement("SELECT page_id AS pageId FROM page_attrs WHERE attr_id=?").all(id) as { pageId: string }[]; const plan = new EditChanges(); - const old = data.statement("SELECT type FROM attrs_meta WHERE id=?").get(id) as { type: string } | undefined; - const previous = old ? attributes.definition(id) : undefined; - const previousValues = new Map(owners.map(({ pageId }) => [pageId, data.valuesFor([pageId]).get(pageId)?.[id]])); - const previousLinks = new Map(owners.map(({ pageId }) => [pageId, data.outgoing({ kind: "page", id: pageId })])); - attributes.persistDefinition(id, definition, impact.token); + const previousValues = new Map(owners.map(pageId => [pageId, data.valuesFor([pageId]).get(pageId)?.[id]])); + const previousLinks = new Map(owners.map(pageId => [pageId, data.outgoing({ kind: "page", id: pageId })])); + change.persist(); const next = definition ? attributes.definition(id) : undefined; - if ([old?.type, definition?.type].some(type => ["page-link", "page-links", "file", "files"].includes(type ?? ""))) { - for (const { pageId } of owners) { + if ([previous?.type, next?.type].some(type => ["page-link", "page-links", "file", "files"].includes(type ?? ""))) { + for (const pageId of owners) { const value = plan.readValue(pageId, id)?.value; const targets = next && value !== undefined ? attributeTargets(next.type, decodeValue(next, value)) : []; plan.setLinks({ kind: "page", id: pageId }, id, targets, previousLinks.get(pageId), false); @@ -350,10 +348,10 @@ export function setDefinition(id: string, definition: AttributeDefinition | null let ids: string[] = []; context.persist(plan, undefined, undefined, projected => { ids = projected?.changes.filter(row => !row.deleted && row.reason !== null).map(row => row.id) ?? []; - const combined: AttributeImpact = { ...impact, token: fingerprint({ impact: impact.token, ids }), recycled: ids.map(id => ({ id, title: data.title(id) })) }; + const combined: AttributeImpact = { ...impact, token: fingerprint({ impact: impact.token, ids }), recycled: ids.map(id => ({ id, title: data.title(id, "") })) }; if ((impact.pages.length || ids.length) && token !== combined.token) throw new DefinitionRollback(combined); }); - for (const { pageId } of owners) { + for (const pageId of owners) { const before = previousValues.get(pageId), after = data.valuesFor([pageId]).get(pageId)?.[id]; if (completedOption(previous, before) !== completedOption(next, after)) timerState.recalculate(pageId); else if (previous?.type !== next?.type || JSON.stringify(before) !== JSON.stringify(after)) timerState.recalculate(pageId, [id, "modified_at"]); @@ -361,7 +359,7 @@ export function setDefinition(id: string, definition: AttributeDefinition | null const removedOptions = previous?.metadata.options?.some(option => !next?.metadata.options?.some(value => value.id === option.id)); commit.invalidate([...new Set([...impact.pages.map(p => p.id), ...ids])].map(id => "page:" + id) .concat(!next || previous?.type !== next.type || removedOptions ? ["attribute:" + id] : [])); - context.change({ definition: id, pages: [...new Set([...owners.map(p => p.pageId), ...ids])] }); + context.change({ definition: id, pages: [...new Set([...owners, ...ids])] }); }); } catch (error) { diff --git a/main/knowledge/retention.ts b/main/knowledge/retention.ts index e1bbe71..277b8dc 100644 --- a/main/knowledge/retention.ts +++ b/main/knowledge/retention.ts @@ -143,7 +143,7 @@ export function purgePlan(ids: string[] | null): { pages: { id: string; title: s SELECT 'page',id FROM removed UNION ALL SELECT 'block',id FROM removed_blocks ) SELECT ( - SELECT json_group_array(json_object('id',p.id,'title',COALESCE(NULLIF(knowledge_text(b.type,b.content),''),'未命名')) ORDER BY p.id) + SELECT json_group_array(json_object('id',p.id,'title',COALESCE(knowledge_text(b.type,b.content),'')) ORDER BY p.id) FROM removed r CROSS JOIN pages p ON p.id=r.id JOIN blocks b ON b.id=p.title_block_id ) AS pages, (SELECT json_group_array(id ORDER BY id) FROM removed_blocks) AS blocks, diff --git a/preload/index.ts b/preload/index.ts index f1ec256..a16b6e1 100644 --- a/preload/index.ts +++ b/preload/index.ts @@ -1,7 +1,7 @@ import { contextBridge, ipcRenderer, webUtils } from "electron"; -import type { AppAPI, BridgeAPI } from "../shared/ipc"; +import type { AppAPI, AppCommands, AppQueries, BridgeAPI } from "../shared/ipc"; import type { Channels, InvokeKeys } from "../shared/ipc/contract"; -import { appChannels, beforeQuit, feedChanged, historyChanged, pagesChanged, settingsChanged, openReminderPage, pagesChannels, attributesChannels, historyChannels, papersChannels, timersChannels, workspaceChannels, settingsChannels, startupChannels, feedChannels } from "../shared/ipc"; +import { appChannels, appQueryChannels, beforeQuit, feedChanged, historyChanged, pagesChanged, settingsChanged, openReminderPage, pagesChannels, attributesChannels, historyChannels, papersChannels, timersChannels, workspaceChannels, settingsChannels, startupChannels, feedChannels } from "../shared/ipc"; function methods(channels: Record, call: (channel: string, ...args: unknown[]) => unknown): API { return Object.fromEntries(Object.entries(channels).map(([key, channel]) => [key, (...args: unknown[]) => call(channel, ...args)])) as API; @@ -18,7 +18,8 @@ function subscribe(channel: string, listener: (...args: const { beforeQuitResult, ...commands } = appChannels; const api: BridgeAPI = { app: { - ...methods>(commands, (channel, ...args) => ipcRenderer.send(channel, ...args)), + ...invokes(appQueryChannels), + ...methods>(commands, (channel, ...args) => ipcRenderer.send(channel, ...args)), beforeQuit(check) { const listener = (_event: unknown, id: string): void => { Promise.resolve().then(check).then(block => ipcRenderer.send(beforeQuitResult, id, block !== false)) diff --git a/renderer/components/Feed/FeedReader.svelte b/renderer/components/Feed/FeedReader.svelte index 258c9b6..cb534c0 100644 --- a/renderer/components/Feed/FeedReader.svelte +++ b/renderer/components/Feed/FeedReader.svelte @@ -94,7 +94,7 @@

{article.title || t("shell.untitled")}

{#if content}
{:else if article.summary}
{article.summary}
{/if} @@ -112,7 +112,7 @@ .article { max-width: calc(var(--ui-editor-content-width) + 2 * var(--ui-editor-gutter)); box-sizing: border-box; margin-inline: auto; padding: var(--ui-space-6) var(--ui-editor-gutter); user-select: text; } h2 { margin: 0 0 var(--ui-space-4); font: 700 var(--ui-editor-font-title)/var(--ui-editor-heading-line-height) var(--ui-font-family); overflow-wrap: anywhere; } .metadata { display: flex; flex-wrap: wrap; align-items: center; gap: var(--ui-space-2) var(--ui-space-3); margin-block-end: var(--ui-space-5); font-size: var(--ui-font-small); line-height: 1.4; color: var(--ui-text-secondary); } - .badge { background: var(--ui-surface-panel); border-radius: var(--ui-radius-control); padding: var(--ui-space-1) var(--ui-space-2); } + .summary-only { background: var(--ui-surface-panel); border-radius: var(--ui-radius-control); padding: var(--ui-space-1) var(--ui-space-2); } .feed-content { font: var(--ui-editor-font-body)/var(--ui-editor-line-height) var(--ui-font-family); overflow-wrap: anywhere; } .plain { white-space: pre-wrap; } .feed-content :global(:where([data-paragraph], div, ol, ul, dl, blockquote, pre, figure, h3, h4, h5, h6, hr, table)) { margin: 0; font: inherit; } diff --git a/renderer/components/Knowledge/AttributeManagement.svelte b/renderer/components/Knowledge/AttributeManagement.svelte index 3ac1903..0b5d835 100644 --- a/renderer/components/Knowledge/AttributeManagement.svelte +++ b/renderer/components/Knowledge/AttributeManagement.svelte @@ -1,12 +1,27 @@ - + onparams({ listWidth })} /> + \ No newline at end of file diff --git a/renderer/components/Knowledge/AttributeManager.svelte b/renderer/components/Knowledge/AttributeManager.svelte index f87033d..c1e3ce3 100644 --- a/renderer/components/Knowledge/AttributeManager.svelte +++ b/renderer/components/Knowledge/AttributeManager.svelte @@ -1,85 +1,107 @@ -
- -
- {#if draft} - - - {#if draft.type === "status" || draft.type === "select" || draft.type === "multiselect"} -
选项改名会保留原有选择;移除选项前会预览影响。
-
- {#each draft.metadata.options ?? [] as option (option.id)} -
- {#if draft.type === "status"}{/if} -
- {/each} -
- - {/if} -
{#if !isBuiltin(draft.id)}{/if}
- {#if error}
{message(error)}
{/if} - {/if} -
-
- \ No newline at end of file + + +
+
+
+ +
+
+ {#each [{ title: t("attributes.builtins"), rows: builtins }, { title: t("attributes.custom"), rows: custom }] as group (group.title)} +
+

{group.title}

+ {#each group.rows as item (item.id)} + {@const name = propertyName(item)} + {@const active = draft?.id === item.id} + select(item)} + buttonProps={{ role: "option", "aria-selected": active, disabled: busy, + tabindex: active || selected < 0 && item.id === items[0]?.id ? 0 : -1, + onkeydown: event => move(event, item.id) }}> + {name} + {t(`attributeType.${item.type}`)} + + {/each} +
+ {/each} +
+
+ onresize(Math.round(value))} /> +
+ {#if draft} +
+
+
{t("attributes.name")}
+ { + if (draft) draft.name = name; + }} /> +
+
+
{t("attributes.type")}
+ option.name = name} /> + {#if draft.type === "status"} + option.group = checked ? "complete" : "incomplete"} /> + {/if} + removeOption(option.id)} /> +
+ {/each} +
+ +
+ {/if} +
+ + {#if !builtin}{/if} +
+ {#if error}{/if} +
+ {/if} + + + + \ No newline at end of file diff --git a/renderer/components/Knowledge/Dialogs.svelte b/renderer/components/Knowledge/Dialogs.svelte index ee1ce25..d89feeb 100644 --- a/renderer/components/Knowledge/Dialogs.svelte +++ b/renderer/components/Knowledge/Dialogs.svelte @@ -1,45 +1,82 @@ -{#if knowledgeState.error} -
showLayer(element, clearError)}>
{message(knowledgeState.error)}{#if knowledgeState.error.diagnostic}
{t("dialog.details")}
{knowledgeState.error.diagnostic}
{/if}
-{:else if knowledgeState.notice} -
showLayer(element, clearNotice)}>{knowledgeState.notice}
-{/if} -{#if confirmation.resolve} -
showLayer(element, () => answer(false))} role="dialog" aria-modal="true" aria-label={confirmation.heading()}> -
-

{confirmation.heading()}

-
{confirmation.text()}
- {#if confirmation.names.length} -
    - {#each confirmation.names as name, index (index)} -
  • {name || t("dialog.untitled")}
  • - {/each} -
- {/if} -
- - -
-
-
-{/if} - \ No newline at end of file + + +{#if knowledgeState.error || knowledgeState.notice} + {@const error = knowledgeState.error} + {@const close = error ? clearError : clearNotice} + +
+
+ {error ? message(error) : knowledgeState.notice} + {#if error && error.diagnostic} +
+ {t("dialog.details")} +
{error.diagnostic}
+
+ {/if} +
+ +
+
+{/if} + +{#if request} + {#key request} + answer(true)} oncancel={() => answer(false)}> + {#if names.length} +
+ + {#snippet row(name, index)} +
+ {name || t("dialog.untitled")} +
+ {/snippet} +
+
+ {/if} +
+ {/key} +{/if} + + \ No newline at end of file diff --git a/renderer/components/Knowledge/LibraryGrid.svelte b/renderer/components/Knowledge/LibraryGrid.svelte index 608e9b3..fa9a610 100644 --- a/renderer/components/Knowledge/LibraryGrid.svelte +++ b/renderer/components/Knowledge/LibraryGrid.svelte @@ -39,9 +39,11 @@ untrack(() => onrange(from, to)); }); let queued: number | undefined; - function scrollWindow(): void { + function scrollWindow(event: Event & { currentTarget: HTMLElement }): void { + const viewport = event.currentTarget; + if (viewport !== grid) return; hideTip(); - const at = grid.scrollTop, row = Math.floor(at / rowHeight); + const at = viewport.scrollTop, row = Math.floor(at / rowHeight); if (row < start || Math.min(index.ids.length, row + count) > end) { scroll = at; } @@ -49,7 +51,7 @@ // Chromium can finish the current wheel frame before we replenish the buffer. queued = requestIdleCallback(() => { queued = undefined; - scroll = grid.scrollTop; + if (viewport === grid) scroll = viewport.scrollTop; }, { timeout: 24 }); } } diff --git a/renderer/components/Knowledge/confirmation.svelte.ts b/renderer/components/Knowledge/confirmation.svelte.ts index 13692ad..eed0a90 100644 --- a/renderer/components/Knowledge/confirmation.svelte.ts +++ b/renderer/components/Knowledge/confirmation.svelte.ts @@ -1,23 +1,30 @@ -import { confirmationText } from "../../../shared/content/confirmation"; +import { confirmationText, recycledPageNames } from "../../../shared/content/confirmation"; import { type AttributeDefinition } from "../../../shared/types/attributes"; -import { type CommitResult } from "../../../shared/types/content"; +import { type ChangePreview, type CommitResult } from "../../../shared/types/content"; import { t } from "../../i18n.svelte"; -export const confirmation = $state<{ heading: () => string; text: () => string; names: string[]; resolve: ((value: boolean) => void) | null }>({ heading: () => "", text: () => "", names: [], resolve: null }); -export function ask(heading: () => string, text: () => string, names: string[] = []): Promise { - if (confirmation.resolve) return Promise.resolve(false); - return new Promise(resolve => Object.assign(confirmation, { heading, text, names, resolve })); +type Request = { heading: () => string; text: () => string; names: string[]; danger: boolean; resolve: (value: boolean) => void }; +export const confirmation = $state<{ current: Request | null }>({ current: null }); +export function ask(heading: () => string, text: () => string, names: string[] = [], danger = false): Promise { + if (confirmation.current) return Promise.resolve(false); + return new Promise(resolve => { + confirmation.current = { heading, text, names, danger, resolve }; + }); } export function answer(value: boolean): void { - const resolve = confirmation.resolve; - confirmation.resolve = null; - resolve?.(value); + const request = confirmation.current; + confirmation.current = null; + request?.resolve(value); +} +export function confirmChange(preview: ChangePreview, heading = (): string => t("dialog.change")): Promise { + const names = recycledPageNames(preview); + return ask(heading, () => confirmationText(preview, t, names.length), names); } export async function confirmed(commit: (token?: string) => Promise): Promise { let result = await commit(); while (result.status === "confirmation") { const { preview } = result; - if (!await ask(() => t(preview.deletedBlocks.length ? "dialog.deleteBlock" : "dialog.change"), () => confirmationText(preview, t))) return false; + if (!await confirmChange(preview, () => t(preview.deletedBlocks.length ? "dialog.deleteBlock" : "dialog.change"))) return false; result = await commit(preview.token); } return true; @@ -25,8 +32,11 @@ export async function confirmed(commit: (token?: string) => Promise { let impact = await window.api.attributes.define(id, value); while (impact) { - if (!await ask(() => t("dialog.sharedAttribute"), () => t("dialog.attributeImpact") + (impact?.recycled?.length ? t("dialog.attributeRecycle", { count: impact.recycled.length }) : ""), [...impact.pages, ...(impact.recycled ?? [])].map(page => page.title))) return false; - impact = await window.api.attributes.define(id, value, impact.token); + const { pages, recycled, token } = impact; + if (!await ask(() => t("dialog.sharedAttribute"), + () => t("dialog.attributeImpact") + (recycled?.length ? "\n" + t("dialog.attributeRecycle", { count: recycled.length }) : ""), + [...pages, ...(recycled ?? [])].map(page => page.title), value === null)) return false; + impact = await window.api.attributes.define(id, value, token); } return true; } \ No newline at end of file diff --git a/renderer/components/Knowledge/page-session.svelte.ts b/renderer/components/Knowledge/page-session.svelte.ts index 1541c6a..192db17 100644 --- a/renderer/components/Knowledge/page-session.svelte.ts +++ b/renderer/components/Knowledge/page-session.svelte.ts @@ -1,20 +1,19 @@ import { watchHistory } from "./history"; import { type HistorySource } from "../../../shared/history/ipc"; import { PageWrites, fallbackFields, fields, reviewEdit, type Fields } from "./page-writes"; -import { confirmationText } from "../../../shared/content/confirmation"; import { publishTitle } from "../Tab/page-titles"; import { blockText } from "../../../shared/content/blocks"; import { type AttributeDefinition, type AttributeValue } from "../../../shared/types/attributes"; -import { type Backlink, type ChangePreview, type Changed, type CommitResult, type KnowledgeChange, type PageRecord } from "../../../shared/types/content"; +import { type Backlink, type Changed, type CommitResult, type KnowledgeChange, type PageRecord } from "../../../shared/types/content"; import { type HistoryState } from "../../../shared/types/knowledge"; import { PendingInput } from "../Editor/pending-input"; import { readingTabs, visits } from "../Tab/activity.svelte"; import { registerPageView } from "./page-visits"; import { WriteReceipts } from "./write-tracker"; -import { ask, confirmed } from "./confirmation.svelte"; +import { confirmChange, confirmed } from "./confirmation.svelte"; import { copyData } from "../copy-data"; import { knowledgeState, perform } from "./feedback.svelte"; -import { t, failure, type ErrorValue } from "../../i18n.svelte"; +import { failure, type ErrorValue } from "../../i18n.svelte"; import { LabloomError } from "../../../shared/failure"; class PageState { @@ -100,7 +99,6 @@ export function makeSession(tabId: string, pageId: string, source: HistorySource const newBlocks = new Set(); let timer: ReturnType | undefined, composing = false; let reviewing: Promise | undefined, load = 0; - const prompt = (p: ChangePreview): Promise => ask(() => t("dialog.change"), () => confirmationText(p, t)); function updateCounts(ids: string[], uses: Record): void { if (!ids.length || !state.page) return; const counts = state.page.sharedUses ??= {}; @@ -125,7 +123,7 @@ export function makeSession(tabId: string, pageId: string, source: HistorySource const { safe, restore, proposed } = fallbackFields(input, causes, stored, key => writes.current(key)); apply(fields(restore)); notify(ids); - if (!await prompt(result.preview)) { + if (!await confirmChange(result.preview)) { writes.retain(fields(safe)); return; } @@ -287,7 +285,7 @@ export function makeSession(tabId: string, pageId: string, source: HistorySource const input = writes.input(edit); try { let savedResult: Extract | undefined; - await reviewEdit(input, prompt, async (value, token) => { + await reviewEdit(input, confirmChange, async (value, token) => { const result = await receipts.submit(id => api.pages.commitEdit(value, source, token, id)); if (result.status === "saved") savedResult = result; return result; diff --git a/renderer/components/Knowledge/purge.ts b/renderer/components/Knowledge/purge.ts index 3dd3dc9..e30d965 100644 --- a/renderer/components/Knowledge/purge.ts +++ b/renderer/components/Knowledge/purge.ts @@ -7,8 +7,10 @@ export async function purgePages(ids: string[] | null): Promise { let result = await submit(); while (result.status === "confirmation") { const preview = result; - const text = (): string => t("dialog.purgeImpact", { count: preview.pages.length, titles: preview.pages.map(page => page.title).join(t("dialog.listJoin")) }) + (preview.links ? "\n" + t("dialog.deletedLinks", { count: preview.links }) : ""); - if (!await ask(() => t("dialog.purge"), text)) return false; + const count = preview.pages.length; + const text = (): string => t(count === 1 ? "dialog.purgeOne" : "dialog.purgeImpact", { count }) + + (preview.links ? "\n" + t("dialog.deletedLinks", { count: preview.links }) : ""); + if (!await ask(() => t("dialog.purge"), text, preview.pages.map(page => page.title), true)) return false; result = await submit(result.token); } return true; diff --git a/renderer/components/Tab/restore.ts b/renderer/components/Tab/restore.ts index 0dea999..4ec373e 100644 --- a/renderer/components/Tab/restore.ts +++ b/renderer/components/Tab/restore.ts @@ -47,7 +47,9 @@ export function restoreTabState(state: unknown): TabState | undefined { type: "overview", params: { status: defaultOverviewStatus, date: defaultOverviewDate } } }); else if (record(view) && view.type === "calendar") tabs.push({ id: tab.id, view: { type: "calendar", params: defaultCalendar } }); - else if (record(view) && view.type === "feed") tabs.push({ id: tab.id, view: { type: "feed", params: {} } }); + else if (record(view) && (view.type === "feed" || view.type === "attributes" || view.type === "settings" || view.type === "about")) { + tabs.push({ id: tab.id, view: { type: view.type, params: {} } }); + } else if (record(view) && view.type === "library") { const papers = record(view.params) && view.params.paperOnly === true; tabs.push({ id: tab.id, view: { type: "library", params: defaultLibrary(papers) } }); diff --git a/renderer/components/base/Combobox.svelte b/renderer/components/base/Combobox.svelte new file mode 100644 index 0000000..2bbbe69 --- /dev/null +++ b/renderer/components/base/Combobox.svelte @@ -0,0 +1,126 @@ + + + + + open, setOpen} + contentProps={{ class: "combobox-popup", onOpenAutoFocus: show, onCloseAutoFocus: restore, onInteractOutside: () => restoreTrigger = false }}> + {#snippet trigger({ props })} + + {/snippet} +
+ +
+ option.value} bind:this={rows}> + {#snippet row(option, index)} + + {/snippet} + + {#if !matches.length}
{t("combobox.empty")}
{/if} +
+ + \ No newline at end of file diff --git a/renderer/components/base/ConfirmDialog.svelte b/renderer/components/base/ConfirmDialog.svelte index 991fc83..42e416a 100644 --- a/renderer/components/base/ConfirmDialog.svelte +++ b/renderer/components/base/ConfirmDialog.svelte @@ -1,9 +1,11 @@ -
showLayer(element)}>{@render children()}
+
showLayer(element, onEscape)}>{@render children()}
\ No newline at end of file diff --git a/renderer/components/base/controls.css b/renderer/components/base/controls.css index 99e5b25..6433a72 100644 --- a/renderer/components/base/controls.css +++ b/renderer/components/base/controls.css @@ -1,6 +1,6 @@ @import "../../styles/ui-tokens.css"; -/* Reset the native elements before styling so the legacy button/input/kbd rules cannot leak in. */ +/* Reset native element styles before applying control styles. */ .ui-control, .ui-field, .ui-field-input, .ui-check, .ui-row, .ui-row-main, .ui-popup, .ui-menu-item, .ui-shortcut { all: unset; box-sizing: border-box; diff --git a/renderer/components/layout/App.svelte b/renderer/components/layout/App.svelte index eac582b..e582f55 100644 --- a/renderer/components/layout/App.svelte +++ b/renderer/components/layout/App.svelte @@ -33,7 +33,7 @@ import Sidebar from "./Sidebar.svelte"; import Main from "./Main.svelte"; import Onboarding from "../startup/Onboarding.svelte"; - import { initializeAppearance } from "./preferences.svelte"; + import { finishPreferences, initializeAppearance } from "./preferences.svelte"; import Dialogs from "../Knowledge/Dialogs.svelte"; import { syncInspected, closeSession, saveAll } from "../Knowledge/page-sessions"; import { knowledgeState } from "../Knowledge/feedback.svelte"; @@ -141,6 +141,7 @@ window.addEventListener("focus", focus); const stopClose = window.api.app.beforeQuit(async () => { if (document.activeElement instanceof HTMLElement) document.activeElement.blur(); + await finishPreferences(); if (!await saveAll()) { knowledgeState.error = { kind: "workspace-close-unsaved" }; return true; } diff --git a/renderer/components/layout/NavBar.svelte b/renderer/components/layout/NavBar.svelte index 09c67ce..0f21300 100644 --- a/renderer/components/layout/NavBar.svelte +++ b/renderer/components/layout/NavBar.svelte @@ -4,6 +4,7 @@ import { commandLabel } from "../../i18n.svelte"; import IconButton from "../base/IconButton.svelte"; import Menu from "./Menu.svelte"; + import TitleBar from "./TitleBar.svelte"; let { collapsed, oncommand, disabled, onremember, children }: { collapsed: boolean; oncommand: (id: Command) => void; disabled: (id: Command) => boolean; @@ -11,28 +12,19 @@ } = $props(); -
+
oncommand("sidebar")} />
{@render children()}
-
+ \ No newline at end of file diff --git a/renderer/components/layout/preferences.svelte.ts b/renderer/components/layout/preferences.svelte.ts index 1aa420d..a4e1755 100644 --- a/renderer/components/layout/preferences.svelte.ts +++ b/renderer/components/layout/preferences.svelte.ts @@ -1,19 +1,20 @@ import { defaultAppearance, type Appearance } from "../../../shared/types/appearance"; import { resolveTimeZone } from "../../../shared/content/time"; -import { type SettingsSnapshot } from "../../../shared/settings/Settings"; +import { defaultSettings } from "../../../shared/settings/defaults"; +import { type SettingsPatch, type SettingsSnapshot } from "../../../shared/settings/Settings"; import { failure, setLocale, type ErrorValue } from "../../i18n.svelte"; import { applyPanel } from "./shell.svelte"; -export const appearance = $state({ ...defaultAppearance, loaded: false, saving: false, error: "" }); +export const appearance = $state({ ...defaultAppearance }); +export const preferences = $state({ loaded: false, saving: false, error: "" as ErrorValue, historyLimit: defaultSettings.history.limit }); +type PreferencePatch = Pick & { history?: Readonly<{ limit: number | null }> }; +let latest: SettingsSnapshot | undefined; +let pending = 0, writes = Promise.resolve(), rejected: PreferencePatch = {}, writeError: ErrorValue = ""; let savedZone = $state(defaultAppearance.timeZone); -let latest: SettingsSnapshot | undefined, pending = 0, sequence = 0; const zone = $derived(resolveTimeZone(savedZone)); export function currentTimeZone(): string { return zone; } -function values(): Appearance { - return { theme: appearance.theme, readingSize: appearance.readingSize, motion: appearance.motion, timeZone: appearance.timeZone, language: appearance.language }; -} let frameColors = "", appliedAppearance = ""; function apply(): void { @@ -24,8 +25,7 @@ function apply(): void { appliedAppearance = signature; document.documentElement.dataset.theme = dark ? "dark" : "light"; document.documentElement.dataset.motion = appearance.motion ? "on" : "off"; - document.documentElement.style.setProperty("--reading-font-size", `${appearance.readingSize}px`); - document.documentElement.style.setProperty("--ui-editor-font-body", appearance.readingSize === defaultAppearance.readingSize ? "" : `${appearance.readingSize}px`); + document.documentElement.style.setProperty("--ui-editor-font-body", appearance.readingSize + "px"); setLocale(appearance.language); const style = getComputedStyle(document.documentElement); const color = style.getPropertyValue("--ui-titlebar-background").trim(), symbol = style.getPropertyValue("--ui-titlebar-foreground").trim(); @@ -35,45 +35,71 @@ function apply(): void { } } +function reconcile(): void { + if (latest && !pending) { + Object.assign(appearance, latest.settings.appearance, rejected.appearance); + preferences.historyLimit = (rejected.history ?? latest.settings.history).limit; + } + preferences.saving = pending > 0 || !!latest?.saving; + preferences.error = writeError || latest?.error || ""; + apply(); +} function receive(snapshot: SettingsSnapshot): void { if (latest && snapshot.revision < latest.revision) return; latest = snapshot; - if (!pending) Object.assign(appearance, snapshot.settings.appearance); savedZone = snapshot.settings.appearance.timeZone; - appearance.loaded = true; appearance.saving = snapshot.saving; - appearance.error = snapshot.error ? failure(snapshot.error) : ""; + preferences.loaded = true; applyPanel(snapshot.settings.layout, snapshot.revision); - apply(); + reconcile(); } + export async function loadAppearance(): Promise { try { receive(await window.api.settings.get()); } catch (error) { - appearance.error = failure(error); apply(); + preferences.error = failure(error); + apply(); } } -export async function saveAppearance(): Promise { - if (!appearance.loaded) return; - const id = pending = ++sequence; - appearance.error = ""; apply(); - try { - const result = await window.api.settings.update({ appearance: values() }); - receive(result.snapshot); - if (!result.success) appearance.error = failure(result.error); - } - catch (error) { - appearance.error = failure(error); - } - finally { - if (pending === id) { - pending = 0; - if (latest) Object.assign(appearance, latest.settings.appearance); - apply(); + +export function savePreferences(patch?: PreferencePatch): Promise { + if (!preferences.loaded) return Promise.resolve(); + pending++; + Object.assign(appearance, patch?.appearance); + if (patch?.history) preferences.historyLimit = patch.history.limit; + reconcile(); + + writes = writes.then(async () => { + try { + rejected = { ...rejected, ...patch, ...(patch?.appearance && { appearance: { ...rejected.appearance, ...patch.appearance } }) }; + if (Object.keys(rejected).length) { + const result = await window.api.settings.update(rejected); + receive(result.snapshot); + if (!result.success) throw result.error; + rejected = {}; + } + if (!patch && latest?.dirty) { + const result = await window.api.settings.flush(latest.settingsRevision); + receive(result.snapshot); + if (!result.success) throw result.error; + } + writeError = ""; } - } + catch (error) { + writeError = failure(error); + } + finally { + pending--; + reconcile(); + } + }); + return writes; } + +export const finishPreferences = (): Promise => writes; + export function initializeAppearance(): () => void { const systemTheme = window.matchMedia("(prefers-color-scheme: dark)"); systemTheme.addEventListener("change", apply); @@ -81,6 +107,7 @@ export function initializeAppearance(): () => void { const off = window.api.settings.onChanged(receive); void loadAppearance(); return () => { - systemTheme.removeEventListener("change", apply); off(); + systemTheme.removeEventListener("change", apply); + off(); }; } \ No newline at end of file diff --git a/renderer/components/startup/Onboarding.svelte b/renderer/components/startup/Onboarding.svelte index cbb02ed..2376d25 100644 --- a/renderer/components/startup/Onboarding.svelte +++ b/renderer/components/startup/Onboarding.svelte @@ -1,214 +1,86 @@ -
- - {t("startup.brand")} -
+ + + + + {t("app.name")} + + +
+
+ {#if startup?.status === "needs-workspace"} +
{t("app.name")}
+
+

{t("startup.start")}

+
+ choose("create")} /> + choose("open")} /> +
+
+ {#if startup.notice} +
{t("startup.configBackup")} {startup.notice.path}
{/if} - {#if state.error} -
- - - - \ No newline at end of file + :global(.startup-titlebar) { display: flex; gap: var(--ui-space-3); padding-inline-end: var(--system-controls); font-size: var(--ui-font-small); } + img { width: var(--ui-icon-normal); height: var(--ui-icon-normal); } + .onboarding { flex: 1; min-height: 0; overflow: auto; background: var(--ui-surface-window); color: var(--ui-text); font-size: var(--ui-font-body); } + .content { max-width: var(--ui-editor-content-width); padding: clamp(var(--ui-space-6), 12vh, calc(4 * var(--ui-space-6))) clamp(var(--ui-space-6), 7vw, calc(4 * var(--ui-space-6))); } + .name { margin-bottom: var(--ui-space-6); font-size: var(--ui-font-title); font-weight: 600; } + h2 { margin: 0 0 var(--ui-space-2); font-size: var(--ui-font-body); font-weight: 600; } + .actions { display: grid; justify-items: start; gap: var(--ui-space-1); } + .actions :global(.workspace-link:enabled) { color: var(--ui-text-match); } + .actions :global(.workspace-link) { padding-inline: 0 var(--ui-space-3); } + .message { margin-top: var(--ui-space-5); } + .message > div + div, .message > div + :global(.ui-control) { margin-top: var(--ui-space-2); } + .error-heading { color: var(--ui-text-danger); font-weight: 600; } + .path, .diagnostic { user-select: text; overflow-wrap: anywhere; } + .path { color: var(--ui-text-secondary); } + .diagnostic { white-space: pre-wrap; font-family: var(--ui-font-mono); } + \ No newline at end of file diff --git a/renderer/components/tabs/About.svelte b/renderer/components/tabs/About.svelte index ded3327..95dd705 100644 --- a/renderer/components/tabs/About.svelte +++ b/renderer/components/tabs/About.svelte @@ -1,76 +1,70 @@ -
-
- Labloom 标志 + +
+
{t("app.name")}
+ {#if info} +
+ {#each rows as { label, value } (label)} +
{label}
{value}
+ {/each} +
+ {/if} +
+ + {copied ? t("about.copied") : ""} +
+ {#if error}{/if} +
- \ No newline at end of file + \ No newline at end of file diff --git a/renderer/components/tabs/Settings.svelte b/renderer/components/tabs/Settings.svelte index 65cb8b0..72c319f 100644 --- a/renderer/components/tabs/Settings.svelte +++ b/renderer/components/tabs/Settings.svelte @@ -1,126 +1,163 @@ -
-

偏好设置

让这个小小的知识花园,更合你的心意。
保存在本机,所有工作区通用
-
-

外观与阅读

-
{t("language.hint")}
-
暖纸主题
奶油色纸张、柔和配色与手绘小植物。
-
应用于订阅摘要与页面编辑器。
-
按钮悬停的轻微位移。也会遵循系统的减少动态效果设置。
-
-
用于日期时间的显示、输入、搜索和日历分组。
-
- - -
-
-
一个好问题,是知识开始生长的地方。
- {#if appearance.saving}
正在保存偏好设置…
{/if} - {#if appearance.error}{/if} -
-
-

当前工作区

- {#if workspace}
{workspace.name}
{workspace.path}
本地文件夹
{:else}
{workspaceError ? message(workspaceError) : "正在读取工作区信息…"}
{/if} -
-
- - - - - \ No newline at end of file + + function change(key: K, value: Appearance[K]): void { + void savePreferences({ appearance: { [key]: value } }); + } + + function applyLimit(): void { + if (limitText === null) return; + const text = limitText.trim(), limit = text ? Number(text) : null; + invalidLimit = limit !== null && (!/^\d+$/.test(text) || !Number.isSafeInteger(limit) || limit <= 0); + if (invalidLimit) return; + limitText = null; + if (limit !== preferences.historyLimit) void savePreferences({ history: { limit } }); + } + + function limitKeys(event: KeyboardEvent): void { + if (isComposingKey(event) || event.key !== settingsShortcuts.apply) return; + event.preventDefault(); + event.stopPropagation(); + applyLimit(); + } + + +
+
+ {#if preferences.error} + + {/if} + +
+

{t("settings.appearance")}

+ {#snippet language()} + ({ value, label: t(`settings.${value}`) }))} onchange={value => change("theme", value as Appearance["theme"])} /> + {/snippet} + {@render field(t("settings.theme"), t("settings.themeHint"), theme)} + {#snippet readingSize()} + { + limitText = value; invalidLimit = false; + }} + inputProps={{ inputmode: "numeric", onblur: applyLimit, onkeydown: limitKeys, + "aria-describedby": invalidLimit ? limitErrorId : undefined }} /> +
+ {#if invalidLimit}{/if} + {/snippet} + {@render field(t("settings.historyLimit"), t("settings.historyLimitHint"), historyLimit)} +
+ +
+

{t("settings.workspace")}

+ {#if workspace} +
{workspace.name}
+
{workspace.path}
+ {:else} +
{workspaceError ? message(workspaceError) : t("settings.workspaceLoading")}
+ {/if} +
+ + + +{#snippet field(name: string, hint: string, control: Snippet)} +
+
{name}
+
{hint}
+
{@render control()}
+
+{/snippet} + + \ No newline at end of file diff --git a/renderer/components/utils/Bloom.svelte b/renderer/components/utils/Bloom.svelte deleted file mode 100644 index 1b323b9..0000000 --- a/renderer/components/utils/Bloom.svelte +++ /dev/null @@ -1,32 +0,0 @@ - - - - \ No newline at end of file diff --git a/renderer/preview/components/Catalog.svelte b/renderer/preview/components/Catalog.svelte index fae6980..fe0ba1e 100644 --- a/renderer/preview/components/Catalog.svelte +++ b/renderer/preview/components/Catalog.svelte @@ -6,6 +6,7 @@ import Input from "../../components/base/Input.svelte"; import ListRow from "../../components/base/ListRow.svelte"; import ShellExample from "./ShellExample.svelte"; + import ComboboxExamples from "./ComboboxExamples.svelte"; import DatePickerExamples from "./DatePickerExamples.svelte"; import EditorExample from "./EditorExample.svelte"; import StateTable from "./StateTable.svelte"; @@ -80,6 +81,7 @@ +

外壳

diff --git a/renderer/preview/components/ComboboxExamples.svelte b/renderer/preview/components/ComboboxExamples.svelte new file mode 100644 index 0000000..0e1f461 --- /dev/null +++ b/renderer/preview/components/ComboboxExamples.svelte @@ -0,0 +1,19 @@ + + +
+

{t("combobox.title")}

+
+ + + + +
+
\ No newline at end of file diff --git a/renderer/styles/base.css b/renderer/styles/base.css index 7ec0c25..e65972c 100644 --- a/renderer/styles/base.css +++ b/renderer/styles/base.css @@ -26,13 +26,15 @@ background-color: var(--ui-text-selection); } +:root[data-theme="dark"] { color-scheme: dark; } + body { margin: 0; height: 100vh; width: 100vw; - color: var(--c-ink); - background: var(--c-cream); - font-size: var(--font-body); + color: var(--ui-text); + background: var(--ui-surface-window); + font-size: var(--ui-font-body); font-family: var(--ui-font-family); text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; @@ -76,8 +78,8 @@ button, a, input, select, textarea, summary { } :focus-visible { - outline: 3px solid var(--c-border-focus); - outline-offset: 3px; + outline: var(--ui-focus-width) solid var(--ui-focus); + outline-offset: var(--ui-focus-offset); } input, textarea, [contenteditable="true"] { diff --git a/renderer/styles/colors.css b/renderer/styles/colors.css deleted file mode 100644 index c126cf6..0000000 --- a/renderer/styles/colors.css +++ /dev/null @@ -1,81 +0,0 @@ -:root { - /* Warm paper, ink outlines and muted botanical accents. */ - --c-ink: #302c25; - --c-paper: #fffdf7; - --c-cream: #f7f3e8; - --c-gold: #f2cc78; - --c-gold-light: #fff0ca; - --c-sage: #e3ebd8; - --c-lilac: #eae3f1; - --c-peach: #f6e2d4; - --c-muted: #776e5d; - --c-line: #e3dccb; - --c-shadow: 3px 4px 0 var(--c-ink); - --c-navbar-background: var(--c-paper); - --c-tab-header-border: #d6ccb7; - - /* Inline code outside the page editor. */ - --dc-c-code-background: #f3ecd9; - - /* PDF reader */ - --c-reader-background: #ede8dc; - --c-reader-toolbar-background: #fffaf0; - --c-reader-toolbar-border: #ddd3bd; - --c-reader-input-border: #c8bda4; - --c-reader-muted-text: #776e5d; - --c-reader-error-text: #a14232; - - /* Shared interaction states */ - --c-accent: #946924; - --c-surface: #fffdf7; - --c-surface-hover: #f7f0df; - --c-surface-focus: #fff0ca; - --c-border-focus: #b38c48; - - /* Search launcher */ - --c-search-trigger-text: #776e5d; - - /* Search popover */ - --c-popover-border: #d4c8af; - --c-popover-text: #302c25; - --c-search-placeholder: #928671; - --c-search-secondary-text: #776e5d; - --c-kbd-border: #d9cfba; -} - -:root[data-theme="dark"] { - --c-dots: #4b493b; - color-scheme: dark; - --c-ink: #eee4d1; - --c-paper: #292923; - --c-cream: #22231e; - --c-gold: #6f572e; - --c-gold-light: #4e432c; - --c-sage: #374632; - --c-lilac: #443b50; - --c-peach: #573b30; - --c-muted: #c0b59f; - --c-line: #4a463a; - --c-shadow: 3px 4px 0 #14150f; - --c-tab-header-border: #68604c; - --c-accent: #e0b96d; - --c-surface: var(--c-paper); - --c-surface-hover: #37372b; - --c-surface-focus: var(--c-gold-light); - --c-reader-background: #20221e; - --c-reader-toolbar-background: var(--c-paper); - --c-reader-toolbar-border: var(--c-line); - --c-reader-input-border: #68604c; - --c-reader-muted-text: var(--c-muted); - --c-reader-error-text: #f3aa91; - --c-search-trigger-text: var(--c-muted); - --c-popover-text: var(--c-ink); - --c-kbd-border: #68604c; - --dc-c-code-background: #403b2e; - - --c-popover-border: #68604c; - --c-search-placeholder: #a69a85; - --c-search-secondary-text: #b9ae99; - --c-note-stripe: #303326; - --c-note-line: #34382b; -} \ No newline at end of file diff --git a/renderer/styles/elements.css b/renderer/styles/elements.css index dfcbd61..159607c 100644 --- a/renderer/styles/elements.css +++ b/renderer/styles/elements.css @@ -51,7 +51,7 @@ s { kbd { padding: .1em .4em; - border: .0625em solid var(--c-kbd-border); + border: var(--ui-stroke) solid var(--ui-border-input); border-radius: .25em; font-size: .9em; font-family: inherit; diff --git a/renderer/styles/global.css b/renderer/styles/global.css index d54e35b..c49099c 100644 --- a/renderer/styles/global.css +++ b/renderer/styles/global.css @@ -1,5 +1,3 @@ -@import "./colors.css"; @import "./layouts.css"; @import "./base.css" layer(base); -@import "./elements.css"; -@import "./workspace.css"; \ No newline at end of file +@import "./elements.css"; \ No newline at end of file diff --git a/renderer/styles/layouts.css b/renderer/styles/layouts.css index 8e7d4c4..afa479e 100644 --- a/renderer/styles/layouts.css +++ b/renderer/styles/layouts.css @@ -1,18 +1,3 @@ :root { --annotation-min-height: 150px; - --library-toolbar-height: 32px; - --library-row-height: 28px; - --panel-row-height: 22px; - --menu-row-height: 26px; - --property-row-height: 26px; - --button-height: 24px; - --control-radius: 4px; - --font-body: 13px; - --font-secondary: 12px; - --font-min: 11px; - --border-width: 1px; - --focus-width: 2px; - --focus-offset: 2px; - - --dc-font-mono: "JetBrains Mono", ui-monospace, "Cascadia Code", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace; } \ No newline at end of file diff --git a/renderer/styles/workspace.css b/renderer/styles/workspace.css deleted file mode 100644 index 54c55ad..0000000 --- a/renderer/styles/workspace.css +++ /dev/null @@ -1,155 +0,0 @@ -.workspace-page { - width: 100%; - max-width: 1480px; - min-height: 100%; - margin: 0 auto; - padding: clamp(20px, 3vw, 38px); - container-type: inline-size; -} - -.page-heading { - display: flex; - align-items: center; - justify-content: space-between; - flex-wrap: wrap; - gap: 16px; - margin-bottom: 26px; -} - -.eyebrow { - display: block; - color: var(--c-muted); - font-size: var(--font-min); - font-weight: 800; - letter-spacing: 2px; - text-transform: uppercase; -} - -.page-heading h1 { - margin: 7px 0 8px; - font-size: clamp(24px, 3vw, 32px); - font-weight: 900; - letter-spacing: -1px; -} - -.page-heading :where([data-paragraph]) { - margin: 0; - color: var(--c-muted); - font-size: 13px; - line-height: 1.7; -} - -.paper-card { - min-width: 0; - border: var(--border-width) solid var(--c-line); - border-radius: 0; - background: var(--c-paper); - box-shadow: none; -} - -.button { - display: inline-flex; - align-items: center; - justify-content: center; - gap: 8px; - height: var(--button-height); - min-height: var(--button-height); - padding: 0 8px; - border: var(--border-width) solid var(--c-line); - border-radius: var(--control-radius); - background: var(--c-paper); - color: var(--c-ink); - font-size: 12px; - font-weight: 800; - -} - -.button.primary { - background: var(--c-gold); - box-shadow: none; -} - -.button:hover:not(:disabled) { - - - background: var(--c-gold-light); -} - -.button:active:not(:disabled) { - - box-shadow: none; -} - -.badge { - display: inline-flex; - align-items: center; - gap: 6px; - padding: 5px 9px; - border: 1px solid var(--c-line); - border-radius: 7px; - background: var(--c-cream); - color: var(--c-muted); - font-size: var(--font-min); - font-weight: 800; - white-space: nowrap; -} - -.notice { - padding: 12px 16px; - border: 1px solid var(--c-tab-header-border); - border-radius: var(--control-radius); - background: var(--c-gold-light); - color: var(--c-muted); - font-size: 12px; - line-height: 1.8; -} - -.notice.error { - border-color: var(--c-reader-error-text); - color: var(--c-reader-error-text); - background: var(--c-peach); -} - -.empty-state { - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - gap: 12px; - padding: 34px 20px; - color: var(--c-muted); - text-align: center; -} - -.empty-state :where([data-paragraph]) { - max-width: 400px; - margin: 0; - font-size: 12px; - line-height: 1.8; -} - -.empty-state strong { - color: var(--c-ink); - font-size: 15px; -} - -.text-button { - display: inline-flex; - align-items: center; - gap: 6px; - padding: 5px 0; - color: var(--c-accent); - font-size: 12px; - font-weight: 700; -} - -.text-button:hover:not(:disabled) { - text-decoration: underline; - text-underline-offset: 3px; -} - -.compact-menu { min-width: 190px; max-height: var(--bits-context-menu-content-available-height, 70vh); overflow: auto; padding: 4px; border: var(--border-width) solid var(--c-line); border-radius: var(--control-radius); background: var(--c-paper); color: var(--c-ink); box-shadow: 0 3px 12px #0002; font-size: var(--font-body); } -.compact-item { display: flex; align-items: center; justify-content: space-between; gap: 16px; height: var(--menu-row-height); padding-inline: 8px; border-radius: var(--control-radius); cursor: default; white-space: nowrap; outline: none; } -.compact-item[data-highlighted], .compact-item:hover { background: var(--c-sage); } -.compact-item[data-disabled] { opacity: .4; pointer-events: none; } -.compact-item kbd { margin-left: auto; color: var(--c-muted); font: inherit; font-size: var(--font-secondary); } \ No newline at end of file diff --git a/shared/app.ts b/shared/app.ts index e683251..2a14d11 100644 --- a/shared/app.ts +++ b/shared/app.ts @@ -1,4 +1,4 @@ -import type { AppCommands } from "./app/ipc"; +import type { AppCommands, AppQueries } from "./app/ipc"; import type { PagesAPI } from "./pages/ipc"; import type { AttributesAPI } from "./attributes/ipc"; import type { HistoryAPI } from "./history/ipc"; @@ -10,7 +10,7 @@ import type { StartupAPI } from "./startup/ipc"; import type { FeedAPI } from "./feed/ipc"; export type AppAPI = { - app: AppCommands; + app: AppCommands & AppQueries; pages: PagesAPI; attributes: AttributesAPI; history: HistoryAPI; diff --git a/shared/app/ipc.ts b/shared/app/ipc.ts index 0fe3f9c..a0552c3 100644 --- a/shared/app/ipc.ts +++ b/shared/app/ipc.ts @@ -1,3 +1,18 @@ +import type { Channels } from "../ipc/contract"; + +export type AppInfo = { + version: string; + electron: string; + chromium: string; + node: string; + v8: string; + os: { type: string; arch: string; version: string }; +}; +export type AppQueries = { + getInfo(): Promise; +}; +export const appQueryChannels = { getInfo: "app:get-info" } as const satisfies Channels; + export type AppCommands = { openDevTools(): void; setFrameColors(color: string, symbolColor: string): void; diff --git a/shared/content/commands.ts b/shared/content/commands.ts index 4ea8054..9154743 100644 --- a/shared/content/commands.ts +++ b/shared/content/commands.ts @@ -42,6 +42,9 @@ export const libraryShortcuts = { export const feedShortcuts = { previous: "ArrowUp", next: "ArrowDown", first: "Home", last: "End", screenUp: "PageUp", screenDown: "PageDown", menu: "F10" } as const; +export const comboboxShortcuts = { previous: "ArrowUp", next: "ArrowDown", select: "Enter" } as const; +export const attributeShortcuts = { previous: "ArrowUp", next: "ArrowDown" } as const; +export const settingsShortcuts = { apply: "Enter" } as const; export const calendarShortcuts = { left: "ArrowLeft", right: "ArrowRight", up: "ArrowUp", down: "ArrowDown", previousPage: "PageUp", nextPage: "PageDown", today: "Home", cancel: "Escape" diff --git a/shared/content/confirmation.ts b/shared/content/confirmation.ts index 7fcfc81..9a05fbd 100644 --- a/shared/content/confirmation.ts +++ b/shared/content/confirmation.ts @@ -4,7 +4,11 @@ import { createI18n, type Translate } from "../i18n"; const chinese = createI18n("zh-CN"); const defaultTranslation: Translate = (key, options) => chinese.t(key, options); -export function confirmationText(preview: ChangePreview, t: Translate = defaultTranslation): string { +export function recycledPageNames(preview: ChangePreview): string[] { + return [...new Map([...preview.direct, ...preview.recycled].map(page => [page.id, page.title])).values()]; +} + +export function confirmationText(preview: ChangePreview, t: Translate = defaultTranslation, count = recycledPageNames(preview).length): string { const lines = preview.deletedBlocks.map(({ excerpt, pages, positions, links }) => { const impact: string[] = []; if (positions) impact.push(t(pages ? "dialog.pagePositions" : "dialog.positions", { pages, count: positions })); @@ -12,7 +16,6 @@ export function confirmationText(preview: ChangePreview, t: Translate = defaultT if (!impact.length) return t("dialog.deleteExcerpt", { excerpt }); return t(positions ? "dialog.excerptImpact" : "dialog.deleteImpact", { excerpt, impact: impact.join(t("dialog.join")) }); }); - const pages = new Map([...preview.direct, ...preview.recycled].map(page => [page.id, page.title || t("shell.untitled")])); - if (pages.size) lines.push(t("dialog.recycle", { titles: [...pages.values()].join(t("dialog.listJoin")) })); + if (count) lines.push(t(count === 1 ? "dialog.recycleOne" : "dialog.recycle", { count })); return lines.join("\n"); } \ No newline at end of file diff --git a/shared/types/appearance.ts b/shared/types/appearance.ts index e5509dd..237fdff 100644 --- a/shared/types/appearance.ts +++ b/shared/types/appearance.ts @@ -1,9 +1,11 @@ import { validTimeZone } from "../content/time"; import { isLanguage, type Language } from "../locale"; +export const readingSizes = [14, 15, 16, 18] as const; + export type Appearance = { theme: "light" | "dark" | "system"; - readingSize: 14 | 16 | 18; + readingSize: typeof readingSizes[number]; motion: boolean; timeZone: string; language: Language; @@ -11,7 +13,7 @@ export type Appearance = { export const defaultAppearance: Readonly = { theme: "light", - readingSize: 16, + readingSize: 15, motion: true, timeZone: "system", language: "zh-CN" @@ -21,7 +23,7 @@ export function isAppearance(value: unknown): value is Appearance { if (!value || typeof value !== "object" || Array.isArray(value)) return false; const candidate = value as Record; return ["light", "dark", "system"].includes(candidate.theme as string) - && [14, 16, 18].includes(candidate.readingSize as number) + && readingSizes.some(size => size === candidate.readingSize) && typeof candidate.motion === "boolean" && validTimeZone(candidate.timeZone) && isLanguage(candidate.language); diff --git a/shared/workspace/views.ts b/shared/workspace/views.ts index f0bdcb5..53655b4 100644 --- a/shared/workspace/views.ts +++ b/shared/workspace/views.ts @@ -30,7 +30,7 @@ export type ViewParams = { }; calendar: { date: AttributeRef<"day">; start?: AttributeRef<"minute">; status?: AttributeRef<"status">; agendaWidth?: number & tags.Minimum<1> }; overview: { status?: AttributeRef<"status">; date?: AttributeRef<"day"> }; - attributes: NoParams; + attributes: { listWidth?: number & tags.Minimum<1> }; feed: FeedParams; settings: NoParams; about: NoParams; diff --git a/tests/appearance.test.ts b/tests/appearance.test.ts index 4b52af9..69adb19 100644 --- a/tests/appearance.test.ts +++ b/tests/appearance.test.ts @@ -16,6 +16,7 @@ import * as history from "../main/knowledge/history"; import * as commit from "../main/knowledge/commit"; import * as events from "../main/knowledge/events"; import { defaultSettings, minWindowHeight, minWindowWidth } from "../shared/settings/defaults"; +import { readingSizes } from "../shared/types/appearance"; import { dayToSeconds } from "../shared/content/time"; import { randomUUID } from "node:crypto"; import { hasFailure } from "./failures"; @@ -39,6 +40,7 @@ test("settings snapshots are frozen, merge groups, flush durably and leave confi const root = fixture(t), legacy = "{\"version\":1,\"lastWorkspace\":{\"id\":\"ignored\"}}"; writeFileSync(join(root, "config.json"), legacy); const first = settings.get(); + assert.equal(first.settings.appearance.readingSize, 15); assert.equal(Object.isFrozen(first), true); assert.equal(Object.isFrozen(first.settings.appearance), true); assert.equal(Reflect.set(first.settings.layout, "width", 400), false); @@ -63,7 +65,7 @@ test("settings snapshots are frozen, merge groups, flush durably and leave confi test("existing settings without a history limit retain their layout and default to unlimited", () => { const root = folder(), { history: _history, ...legacy } = defaultSettings; - const value = { ...legacy, layout: { width: 311, collapsed: true } }; + const value = { ...legacy, appearance: { ...legacy.appearance, readingSize: 16 }, layout: { width: 311, collapsed: true } }; writeFileSync(join(root, "settings.json"), JSON.stringify(value)); assert.equal(settings.initialize(root).notice, undefined); assert.deepEqual(settings.get().settings, { ...value, history: { limit: null } }); @@ -78,12 +80,13 @@ test("five rapid changes write once within 600ms of the final theme update", asy } })); for (let i = 0; i < 5; i++) { - assert.equal(settings.update({ appearance: { readingSize: [14, 16, 18, 14, 16][i], theme: i % 2 ? "light" : "dark" } }).success, true); + assert.equal(settings.update({ appearance: { readingSize: readingSizes[i % readingSizes.length], theme: i % 2 ? "light" : "dark" } }).success, true); if (i < 4) await delay(25); } const start = performance.now(); await delay(600); assert.equal(stored(root).appearance.theme, "dark"); + assert.equal(stored(root).appearance.readingSize, readingSizes[4 % readingSizes.length]); assert.ok(completed - start <= 600); assert.equal(saved.length, 1); }); diff --git a/tests/attributes.test.ts b/tests/attributes.test.ts index d91b660..6c93332 100644 --- a/tests/attributes.test.ts +++ b/tests/attributes.test.ts @@ -171,6 +171,74 @@ test("removing options clears a selected option and preserves remaining multisel } }); +test("retyping retains option additions, renames and removals from the same save", t => { + const { service } = fixture(t), { setDefinition } = knowledgeServices(); + const a = { id: "a", name: "A" }, b = { id: "b", name: "B" }, c = { id: "c", name: "C" }; + for (const { from, to, options } of [ + { from: "select", to: "multiselect", options: [a, b, c] }, + { from: "select", to: "multiselect", options: [{ ...a, name: "A2" }, b] }, + { from: "multiselect", to: "select", options: [a] } + ] as const) { + const id = `custom:${randomUUID()}`; + const original = { id, name: "Choices", type: from, metadata: { options: [a, b] } }; + const next = { ...original, type: to, metadata: { options: [...options] } }; + assert.equal(setDefinition(id, original), null); + assert.equal(setDefinition(id, next), null); + assert.deepEqual(service.definition(id), next); + } +}); + +test("retyping status options keeps edits and selected option IDs while normalizing groups", t => { + const { id: page, service } = fixture(t), { setDefinition } = knowledgeServices(); + const id = `custom:${randomUUID()}`; + const a = { id: "a", name: "A" }, b = { id: "b", name: "B" }, c = { id: "c", name: "C" }; + const original: AttributeDefinition = { id, name: "Choices", type: "select", metadata: { options: [a, b] } }; + assert.equal(setDefinition(id, original), null); + service.write(page, { [id]: a.id }); + + const complete = { ...b, group: "complete" as const }; + const status: AttributeDefinition = { ...original, type: "status", metadata: { options: [a, complete, c] } }; + const statusImpact = setDefinition(id, status)!; + assert.deepEqual(statusImpact.pages.map(({ id }) => id), [page]); + assert.equal(setDefinition(id, status, statusImpact.token), null); + const grouped = service.definition(id); + assert.deepEqual(grouped.metadata.options, [{ ...a, group: "incomplete" }, complete, { ...c, group: "incomplete" }]); + assert.equal(service.values(page)[id], a.id); + + const select: AttributeDefinition = { ...grouped, type: "select", metadata: { options: grouped.metadata.options!.map(option => + option.id === a.id ? { ...option, name: "A2" } : option) } }; + const selectImpact = setDefinition(id, select)!; + assert.deepEqual(selectImpact.pages.map(({ id }) => id), [page]); + assert.equal(setDefinition(id, select, selectImpact.token), null); + assert.deepEqual(service.definition(id).metadata.options, [{ ...a, name: "A2" }, b, c]); + assert.equal(service.values(page)[id], a.id); +}); + +test("retyping with an option removed confirms and writes the same affected pages", t => { + const { id: pageA, service } = fixture(t), knowledge = knowledgeServices(); + const pageB = knowledge.create("editable", "B").id, pageC = knowledge.create("editable", "C").id; + const id = `custom:${randomUUID()}`, a = { id: "a", name: "A" }, b = { id: "b", name: "B" }; + const original: AttributeDefinition = { id, name: "Choices", type: "select", metadata: { options: [a, b] } }; + assert.equal(knowledge.setDefinition(id, original), null); + service.write(pageA, { [id]: a.id, modified_at: 0 }, true); + service.write(pageB, { [id]: b.id, modified_at: 0 }, true); + service.write(pageC, { modified_at: 0 }, true); + + const next: AttributeDefinition = { ...original, type: "status", metadata: { options: [a] } }; + const preview = knowledge.setDefinition(id, next)!; + assert.deepEqual(preview.pages.map(page => page.id).sort(), [pageA, pageB].sort()); + assert.ok(preview.pages.some(page => page.id === pageB && page.title === "B")); + assert.equal(service.values(pageB)[id], b.id); + assert.equal(service.values(pageB).modified_at, 0); + assert.deepEqual(service.definition(id), original); + + assert.equal(knowledge.setDefinition(id, next, preview.token), null); + assert.equal(service.values(pageA)[id], a.id); + assert.equal(service.values(pageB)[id], null); + assert.equal(service.values(pageC)[id], undefined); + assert.deepEqual([pageA, pageB, pageC].filter(page => service.values(page).modified_at !== 0).sort(), preview.pages.map(page => page.id).sort()); +}); + test("recurrence has a canonical nullable JSON value, readable search text and empty cross-type conversions", () => { const recurrence: AttributeDefinition = { id: "feed_refresh", type: "recurrence", name: "重复", metadata: {} }, value = { every: 2, unit: "week" }; validateValue(recurrence, value); diff --git a/tests/builtin-attrs.test.ts b/tests/builtin-attrs.test.ts index 1af3044..94552b8 100644 --- a/tests/builtin-attrs.test.ts +++ b/tests/builtin-attrs.test.ts @@ -87,7 +87,7 @@ test("builtin identity, names, permissions and fixed metadata cannot be edited", assert.deepEqual(service.attributes.definition(base.id), base); }); -test("metadata has a type-specific shape and retyping normalizes metadata before converting values", t => { +test("submitted metadata must match the destination type when creating or retyping an attribute", t => { const { service, database } = fixture(t), select = definition("select"); for (const value of [ { ...select, metadata: { options: [{ id: "a", name: "A" }, { id: "a", name: "B" }] } }, @@ -97,9 +97,15 @@ test("metadata has a type-specific shape and retyping normalizes metadata before ]) assert.throws(() => service.setDefinition(value.id, value), hasFailure("attribute-invalid-metadata")); select.metadata.options = [{ id: "a", name: "A" }, { id: "b", name: "B" }]; service.setDefinition(select.id, select); - service.setDefinition(select.id, { ...select, type: "multiselect", metadata: {} }); + for (const value of [ + { ...select, type: "multiselect", metadata: {} }, + { ...select, type: "string" }, + { ...select, type: "status", metadata: { ...select.metadata, name: "Wrong location" } } + ] as const) assert.throws(() => service.setDefinition(select.id, value), hasFailure("attribute-invalid-metadata")); + assert.deepEqual(service.attributes.definition(select.id), select); + service.setDefinition(select.id, { ...select, type: "multiselect" }); assert.deepEqual(service.attributes.definition(select.id).metadata, select.metadata); - service.setDefinition(select.id, { ...select, type: "string" }); + service.setDefinition(select.id, { ...select, type: "string", metadata: {} }); assert.deepEqual(service.attributes.definition(select.id).metadata, {}); assert.deepEqual(database.prepare("SELECT name,metadata FROM attrs_meta WHERE id=?").get(select.id), { name: "A", metadata: "{}" }); }); diff --git a/tests/content.test.ts b/tests/content.test.ts index da8326e..5278b46 100644 --- a/tests/content.test.ts +++ b/tests/content.test.ts @@ -17,7 +17,7 @@ import { display } from "../shared/attrs/format"; import { dayToSeconds } from "../shared/content/time"; import { validateValue } from "../shared/attrs/values"; import { pageKinds } from "../shared/types/content"; -import { confirmationText } from "../shared/content/confirmation"; +import { confirmationText, recycledPageNames } from "../shared/content/confirmation"; import { payload, blockText } from "../shared/content/blocks"; import { type ContentBlock, type EditCommit, type CommitResult, type PageRecord } from "../shared/types/content"; @@ -367,7 +367,8 @@ test("reference deletion names its target, omits zero counts and lists all recyc const remove = (token?: string): CommitResult => service.deleteBlock({ pageId: d.id, blockId }, pageHistory(d.id), token); const result = remove(); assert.equal(result.status, "confirmation"); - assert.equal(confirmationText(result.preview), "指向「E」的链接引用将从1个页面的1个位置消失。\n将移入回收站:E、F。"); + assert.equal(confirmationText(result.preview), "指向「E」的链接引用将从1个页面的1个位置消失。\n将把2个页面移入回收站。"); + assert.deepEqual(recycledPageNames(result.preview), ["E", "F"]); assert.equal(remove(result.preview.token).status, "saved"); for (const page of [e, f]) assert.equal(service.get(page.id).attributes.deleted, true); }); diff --git a/tests/failure.test.ts b/tests/failure.test.ts index 779728f..33abb1f 100644 --- a/tests/failure.test.ts +++ b/tests/failure.test.ts @@ -159,7 +159,7 @@ test("confirmation descriptions use the selected language and include the actual }; const chinese = confirmationText(preview, translator("zh-CN")), english = confirmationText(preview, translator("en")); assert.ok(chinese.includes("3个位置") && chinese.includes("4个链接")); - assert.ok(english.includes("3 positions across 2 pages") && english.includes("4 link references") && english.includes("recycle bin: A")); + assert.ok(english.includes("3 positions across 2 pages") && english.includes("4 link references") && english.includes("Move one page to the recycle bin.")); assert.ok(!/[\u4e00-\u9fff]/.test(english)); }); diff --git a/tests/lifecycle.test.ts b/tests/lifecycle.test.ts index 529636b..4177bf0 100644 --- a/tests/lifecycle.test.ts +++ b/tests/lifecycle.test.ts @@ -45,7 +45,7 @@ function fixture(t: TestContext, platform: NodeJS.Platform = "win32", options: s } }; Object.assign(contents, { - mainFrame: frame, ipc, isDestroyed: () => state.contentsDestroyed, isLoadingMainFrame: () => state.loading, + mainFrame: frame, ipc: Object.assign(ipc, { handle: () => { } }), isDestroyed: () => state.contentsDestroyed, isLoadingMainFrame: () => state.loading, send: (channel: string, id: string) => sent.push({ channel, id }), focus: () => state.focused++ }); Object.assign(window, { diff --git a/tests/perf/library-check.ts b/tests/perf/library-check.ts index baecfed..1175498 100644 --- a/tests/perf/library-check.ts +++ b/tests/perf/library-check.ts @@ -104,10 +104,10 @@ export async function checkLibraryDeletion(papers: boolean): Promise { find(active + "[data-library-keyboard]")!.dispatchEvent(new KeyboardEvent("keydown", { key: value, bubbles: true, cancelable: true, ...opts })); }; const started = performance.now(); key("a", { ctrlKey: true }); key("Delete"); - const dialog = await until(() => find("[role=dialog].confirmation") ?? find(".shade[role=dialog] .confirmation")); + const dialog = await until(() => find(":popover-open [role=alertdialog]")); await paint(); const deletion = performance.now() - started; if (!find(active + "aside")?.textContent?.includes(String(total))) throw Error("Partial select all"); - if (papers && !(dialog.textContent?.includes("批注 00001") && dialog.textContent.includes("Annotation 09991"))) throw Error("Missing dependent annotations from recycle preview"); + if (papers && !dialog.querySelector("[role=listitem][aria-setsize=\"6000\"]")) throw Error("Missing dependent annotations from recycle preview"); dialog.querySelector("button")!.click(); find(".tab.active .close-tab")!.click(); await paint(); diff --git a/tests/perf/library-workflow.ts b/tests/perf/library-workflow.ts index b4a6d1b..5f412f5 100644 --- a/tests/perf/library-workflow.ts +++ b/tests/perf/library-workflow.ts @@ -79,8 +79,8 @@ export async function libraryWorkflow(paths: string[], bulkPapers: string[] | nu const importButton = await until(() => button(toolbar, "导入 PDF"), "import PDF button"); importButton.click(); await until(() => el(library + "aside > [data-paragraph]")?.textContent?.includes("2"), "multiple PDF selection"); - await until(() => el(".notice.error details")?.textContent?.includes("broken.pdf"), "per-file failure"); - el(".notice.error button")?.click(); + await until(() => el(":popover-open .toast.error details")?.textContent?.includes("broken.pdf"), "per-file failure"); + el(":popover-open .toast.error button")?.click(); const target = await until(() => [...document.querySelectorAll(library + "[data-kind=paper]")].find(r => r.getAttribute("aria-selected") === "true"), "imported row"); const importedIds = [...document.querySelectorAll(library + "[aria-selected=true][data-page-id]")].map(r => r.dataset.pageId!); target.click(); @@ -182,9 +182,9 @@ export async function libraryWorkflow(paths: string[], bulkPapers: string[] | nu const purge = await until(() => button(el(library + ".library-toolbar")!, "永久删除全部结果"), "purge filtered results"); await until(() => !purge.disabled && el(library + "[role=grid]")?.getAttribute("aria-rowcount") === "2", "only the recycled paper"); purge.click(); - const confirmation = await until(() => el(".confirmation"), "filtered purge confirmation"); + const confirmation = await until(() => el(":popover-open [role=alertdialog]"), "filtered purge confirmation"); if (!confirmation.textContent?.includes("1个页面") || confirmation.textContent.includes(note.title)) throw Error("Incorrect purge scope"); - confirmation.querySelectorAll("footer button")[1].dispatchEvent(new MouseEvent("click", { bubbles: true })); + confirmation.querySelectorAll(".ui-dialog-actions button")[1].dispatchEvent(new MouseEvent("click", { bubbles: true })); await until(() => purge.disabled && el(library + "[role=grid]")?.getAttribute("aria-rowcount") === "1", "empty filtered trash disabled"); if (!(await window.api.pages.get(note.id)).attributes.deleted) throw Error("Unrelated recycled page lost"); @@ -200,10 +200,10 @@ export async function libraryWorkflow(paths: string[], bulkPapers: string[] | nu await until(() => !purge.disabled && el(library + "[role=grid]")?.getAttribute("aria-rowcount") === "5001", "bulk recycle results"); const start = performance.now(); purge.click(); - const preview = await until(() => el(".confirmation"), "bulk permanent deletion confirmation"); + const preview = await until(() => el(":popover-open [role=alertdialog]"), "bulk permanent deletion confirmation"); await new Promise(resolve => requestAnimationFrame(() => setTimeout(resolve, 0))); const elapsed = performance.now() - start, message = preview.textContent ?? ""; - if (!message.includes("6000个页面") || !message.includes("批注 00001") || !message.includes("Annotation 09991") || message.includes(note.title)) { + if (!message.includes("6000个页面") || !preview.querySelector("[role=listitem][aria-setsize=\"6000\"]") || message.includes(note.title)) { throw Error("Incorrect bulk purge confirmation scope"); } preview.querySelector("button")!.click(); diff --git a/tests/perf/reader-workflow.ts b/tests/perf/reader-workflow.ts index b06bb20..219ee62 100644 --- a/tests/perf/reader-workflow.ts +++ b/tests/perf/reader-workflow.ts @@ -34,7 +34,7 @@ export async function readerWorkflow(paperId: string, fileId: string, dropNames: const openMenu = (text: string): HTMLElement | undefined => [...document.querySelectorAll("[role^=menuitem]")] .find(item => item.textContent?.trim().startsWith(text)); const confirm = async (): Promise => { - (await until(() => find(".confirmation footer button:last-child"), "confirmation")).click(); + (await until(() => find(":popover-open [role=alertdialog] .ui-dialog-actions button:last-child"), "confirmation")).click(); }; const sidebar = (): HTMLElement | null => find(root + ".paper-sidebar"); @@ -158,8 +158,8 @@ export async function readerWorkflow(paperId: string, fileId: string, dropNames: } drop.dispatchEvent(new DragEvent("drop", { dataTransfer: transfer, bubbles: true, cancelable: true })); await until(async () => ((await paper()).attributes.paper_files as string[]).length === 3, "two attachments in one drop"); - await until(() => find(".notice.error")?.textContent?.includes("Broken.pdf"), "failed file reported"); - find(".notice.error button")?.click(); + await until(() => find(":popover-open .toast.error")?.textContent?.includes("Broken.pdf"), "failed file reported"); + find(":popover-open .toast.error button")?.click(); const select = await until(() => find(root + ".toolbar [aria-label='PDF file']"), "PDF selector in toolbar"); select.focus(); key(select, "ArrowDown"); @@ -200,7 +200,7 @@ export async function readerWorkflow(paperId: string, fileId: string, dropNames: const lockedRow = await until(() => list()?.querySelector("[data-annotation-id=\"" + firstFixture + "\"]"), "kept annotation row"); lockedRow.click(); key(list(), "Delete"); - if (find(".confirmation")) throw Error("Deletion prompt opened in trash"); + if (find(":popover-open [role=alertdialog]")) throw Error("Deletion prompt opened in trash"); key(list(), "Enter"); const readonly = await until(() => find(".annotation-popover .tiptap[contenteditable=false] [data-body]"), "read-only popup"); const range = document.createRange(); diff --git a/tests/services.test.ts b/tests/services.test.ts index 27e3018..d2a0238 100644 --- a/tests/services.test.ts +++ b/tests/services.test.ts @@ -19,7 +19,7 @@ import * as commit from "../main/knowledge/commit"; import * as events from "../main/knowledge/events"; import * as feed from "../main/feed/service"; import { registerIPCs } from "../main/register"; -import { pagesChannels, attributesChannels, historyChannels, papersChannels, timersChannels, workspaceChannels, settingsChannels, startupChannels, feedChannels } from "../shared/ipc"; +import { appQueryChannels, pagesChannels, attributesChannels, historyChannels, papersChannels, timersChannels, workspaceChannels, settingsChannels, startupChannels, feedChannels } from "../shared/ipc"; import { type CommitResult, type PageRecord } from "../shared/types/content"; import { type AnnotationInput } from "../shared/types/papers"; import { type FeedEntry } from "../shared/types/feed"; @@ -341,7 +341,7 @@ test("IPC can register again for a recreated window without replacing the worksp }; const a = create(); registerIPCs(a.window, () => { }); - assert.deepEqual(new Set(a.handlers.keys()), new Set([pagesChannels, attributesChannels, historyChannels, papersChannels, timersChannels, workspaceChannels, settingsChannels, startupChannels, feedChannels].flatMap(group => Object.values(group)))); + assert.deepEqual(new Set(a.handlers.keys()), new Set([appQueryChannels, pagesChannels, attributesChannels, historyChannels, papersChannels, timersChannels, workspaceChannels, settingsChannels, startupChannels, feedChannels].flatMap(group => Object.values(group)))); a.window.webContents.emit("destroyed"); a.window.emit("closed"); const b = create(); diff --git a/tests/tabs.test.ts b/tests/tabs.test.ts index da8e5bd..887bf00 100644 --- a/tests/tabs.test.ts +++ b/tests/tabs.test.ts @@ -174,6 +174,7 @@ const savedViews = [ { type: "overview", params: { status, date } }, { type: "feed", params: { scope: pageRef.id, read: "unread", order: "oldest", sourcesWidth: 200, listWidth: 340 } }, { type: "feed", params: { scope: "followed" } }, + { type: "attributes", params: { listWidth: 275 } }, ...["feed", "attributes", "settings", "about"].map(type => ({ type, params: {} })) ]; function layout(views: unknown[]): { groups: { id: string; tabs: { id: string; view: unknown }[]; activeTabId: string | null }[]; focusedGroupId: string; layout: { type: "group"; groupId: string } } { @@ -185,12 +186,11 @@ test("all view parameters round-trip independently of whether referenced objects assert.deepEqual(restoreTabState(saved), saved); assert.deepEqual(restoreTabState(layout([])), layout([])); }); -test("unknown views and invalid parameters discard only their tab and repair the active selection", () => { +test("unknown views and invalid page locations discard only their tab and repair the active selection", () => { for (const bad of [ { type: "future", params: {} }, { type: "page", params: { page: { kind: "page", id: "invalid" } } }, - { type: "page", params: { page: pageRef, unexpected: "true" } }, - { type: "about", params: { keyword: "A" } } + { type: "page", params: { page: pageRef, unexpected: "true" } } ]) { const saved = layout([bad, ...savedViews]); const restored = restoreTabState(saved); @@ -215,6 +215,17 @@ test("invalid overview and feed parameters keep the active tab and use defaults" const invalidScope = layout([{ type: "feed", params: { scope: "not-a-source" } }]); assert.deepEqual(restoreTabState(invalidScope)?.groups[0].tabs[0].view, { type: "feed", params: {} }); }); +test("invalid attribute, settings and about parameters keep the tab and use defaults", () => { + const cases = [ + { type: "attributes", params: { listWidth: 0 } }, + { type: "attributes", params: { listWidth: "wide" } }, + { type: "settings", params: null }, + { type: "about", params: { keyword: "A" } } + ]; + for (const { type, params } of cases) { + assert.deepEqual(restoreTabState(layout([{ type, params }])), layout([{ type, params: {} }])); + } +}); test("invalid reader sidebar settings keep the page and its selected PDF", () => { const location = { page: pageRef, fileId: pageRef.id }; for (const invalid of [{ infoWidth: 0 }, { showProperties: "true" }, { paperSidebar: "unknown" }]) {