diff --git a/.gitignore b/.gitignore index e91df56..2e8dfee 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,7 @@ dist .local .VSCodeCounter ~$* +.claude/ /交付材料/ /course_docs/**/示例/ \ No newline at end of file diff --git a/configs/components.preview.ts b/configs/components.preview.ts new file mode 100644 index 0000000..aa3d92e --- /dev/null +++ b/configs/components.preview.ts @@ -0,0 +1,9 @@ +import { resolve } from "node:path"; +import { svelte } from "@sveltejs/vite-plugin-svelte"; +import { defineConfig } from "vite"; + +export default defineConfig({ + root: resolve("renderer/preview/components"), + plugins: [svelte({ configFile: resolve("configs/svelte.config.js") })], + server: { host: "127.0.0.1", port: 15175, strictPort: true } +}); \ No newline at end of file diff --git a/configs/electron.vite.config.ts b/configs/electron.vite.config.ts index b4cde73..8829ee5 100644 --- a/configs/electron.vite.config.ts +++ b/configs/electron.vite.config.ts @@ -45,12 +45,16 @@ export default defineConfig({ plugins: [ typia({ include: [/[/\\]Tab[/\\]restore\.ts$/], tsconfig: resolve("configs/tsconfig.web.json") }), svelte({ configFile: resolve("configs/svelte.config.js") }), - // pdf.js fetches these at runtime, see renderer/components/Reader/pdfjs.ts. + // Serve PDF.js runtime assets and the licenses for bundled fonts and icons. viteStaticCopy({ targets: [{ src: "../node_modules/pdfjs-dist/{cmaps,iccs,standard_fonts,wasm}/*", dest: "pdfjs", rename: { stripBase: 2 } + }, { + src: "assets/fonts/*.txt", + dest: "licenses", + rename: { stripBase: true } }] }) ] diff --git "a/course_docs/2 \347\263\273\347\273\237\346\246\202\350\246\201\350\256\276\350\256\241/1.6.docx" "b/course_docs/2 \347\263\273\347\273\237\346\246\202\350\246\201\350\256\276\350\256\241/1.6.docx" new file mode 100644 index 0000000..3243fa4 Binary files /dev/null and "b/course_docs/2 \347\263\273\347\273\237\346\246\202\350\246\201\350\256\276\350\256\241/1.6.docx" differ diff --git a/locales/en.json b/locales/en.json index 2b34a19..d5e668d 100644 --- a/locales/en.json +++ b/locales/en.json @@ -258,6 +258,129 @@ "confirmMarkRead": "Mark all as read", "retry": "Retry" }, + "command": { + "newPage": "New Page", + "importPDF": "Import PDF", + "closeTab": "Close Editor", + "settings": "Preferences", + "undo": "Undo", + "redo": "Redo", + "cut": "Cut", + "copy": "Copy", + "paste": "Paste", + "selectAll": "Select All", + "sidebar": "Toggle Primary Side Bar", + "splitRight": "Split Right", + "splitDown": "Split Down", + "mergeGroup": "Join Editor Group", + "commandPalette": "Command Palette", + "overview": "Overview", + "feed": "Feeds", + "library": "Knowledge Base", + "papers": "Paper Library", + "calendar": "Calendar", + "attributes": "Manage Attributes", + "search": "Search", + "nextTab": "Next Editor", + "previousTab": "Previous Editor", + "group1": "Focus First Editor Group", + "group2": "Focus Second Editor Group", + "group3": "Focus Third Editor Group", + "about": "About Labloom", + "devtools": "Developer Tools" + }, + "menu": { + "file": "File", + "edit": "Edit", + "view": "View", + "go": "Go", + "help": "Help" + }, + "shell": { + "mainNavigation": "Primary Navigation", + "menuBar": "Menu Bar", + "filter": "Filter by Title", + "filterHint": "Filter by title…", + "clearFilter": "Clear Filter", + "pinned": "Pinned", + "independent": "All Independent Pages", + "untitled": "Untitled", + "more": "More…", + "page": "Page", + "missing": "Page Not Found", + "editorGroup": "Editor Group", + "unsaved": "Unsaved", + "syncing": "Syncing", + "closeNamed": "Close {{title}}", + "groupActions": "More Editor Group Actions", + "close": "Close", + "closeOthers": "Close Others", + "closeRight": "Close to the Right", + "closeAll": "Close All Editors", + "resizePanel": "Resize Side Bar", + "resizeGroup": "Resize Editor Group", + "trashView": "Recycle Bin", + "pinnedView": "Pinned Pages", + "calendarView": "Research Calendar", + "overviewView": "My Garden", + "feedView": "Feed Activity", + "targetDeleted": "Target has been deleted" + }, + "pageAction": { + "open": "Open", + "openSide": "Open to the Side", + "pin": "Pin to Side Bar", + "unpin": "Unpin", + "trash": "Move to Recycle Bin", + "restore": "Restore", + "purge": "Delete Permanently" + }, + "quickOpen": { + "input": "Search pages or commands…", + "results": "Search Results", + "noPages": "No matching pages", + "noCommands": "No matching commands", + "title": "Title", + "body": "Body" + }, + "attributeName": { + "deleted": "Deleted", + "independent": "Independent", + "created_at": "Created", + "modified_at": "Modified", + "recycle_reason": "Reason for Removal", + "recycled_at": "Recycled", + "pinned": "Pinned", + "tags": "Tags", + "links": "Linked Pages", + "paper_files": "Attachments", + "paper_authors": "Authors", + "paper_doi": "DOI", + "paper_year": "Publication Date", + "paper_venue": "Journal / Conference", + "paper_url": "Source URL", + "paper_abstract": "Abstract", + "paper_keywords": "Keywords", + "source_snapshot": "Original Source", + "reading_position": "Reading Position", + "paper_annotations": "Annotations", + "annotation_file": "File", + "annotation_position": "Position", + "annotation_color": "Color", + "annotation_quote": "Quote", + "annotation_context": "Context", + "annotation_extractor": "Extractor Version", + "feed_url": "Feed URL", + "feed_status": "Feed Status", + "feed_refresh": "Refresh Interval", + "feed_last_refreshed": "Last Successful Refresh", + "feed_last_checked": "Last Refresh Attempt", + "feed_last_added": "Last Added Count", + "feed_error": "Error", + "feed_failures": "Consecutive Failures", + "feed_etag": "ETag", + "feed_last_modified": "Last-Modified" + }, "notice": { "reminderTitle": "Labloom reminder" } diff --git a/locales/zh-CN.json b/locales/zh-CN.json index db0be29..4157d9e 100644 --- a/locales/zh-CN.json +++ b/locales/zh-CN.json @@ -258,6 +258,129 @@ "confirmMarkRead": "全部标为已读", "retry": "重试" }, + "command": { + "newPage": "新建页面", + "importPDF": "导入 PDF", + "closeTab": "关闭标签", + "settings": "偏好设置", + "undo": "撤销", + "redo": "重做", + "cut": "剪切", + "copy": "复制", + "paste": "粘贴", + "selectAll": "全选", + "sidebar": "切换左侧面板", + "splitRight": "向右拆分", + "splitDown": "向下拆分", + "mergeGroup": "合并标签组", + "commandPalette": "命令面板", + "overview": "总览", + "feed": "订阅", + "library": "知识库", + "papers": "文献库", + "calendar": "日历", + "attributes": "属性管理", + "search": "搜索", + "nextTab": "下一个标签", + "previousTab": "上一个标签", + "group1": "聚焦第1标签组", + "group2": "聚焦第2标签组", + "group3": "聚焦第3标签组", + "about": "关于知织", + "devtools": "开发者工具" + }, + "menu": { + "file": "文件", + "edit": "编辑", + "view": "视图", + "go": "前往", + "help": "帮助" + }, + "shell": { + "mainNavigation": "主导航", + "menuBar": "菜单栏", + "filter": "筛选标题", + "filterHint": "筛选标题…", + "clearFilter": "清空筛选", + "pinned": "固定", + "independent": "全部独立页", + "untitled": "未命名", + "more": "更多…", + "page": "页面", + "missing": "找不到页面", + "editorGroup": "标签组", + "unsaved": "未保存", + "syncing": "正在同步", + "closeNamed": "关闭{{title}}", + "groupActions": "更多标签组操作", + "close": "关闭", + "closeOthers": "关闭其他", + "closeRight": "关闭右侧", + "closeAll": "关闭全部标签", + "resizePanel": "调整左侧面板宽度", + "resizeGroup": "调整标签组大小", + "trashView": "回收站", + "pinnedView": "已固定", + "calendarView": "研究日历", + "overviewView": "我的花园", + "feedView": "订阅动态", + "targetDeleted": "目标已删除" + }, + "pageAction": { + "open": "打开", + "openSide": "在另一标签组打开", + "pin": "固定到侧栏", + "unpin": "取消固定", + "trash": "移入回收站", + "restore": "恢复", + "purge": "永久删除" + }, + "quickOpen": { + "input": "搜索页面或命令…", + "results": "搜索结果", + "noPages": "没有匹配的页面", + "noCommands": "没有匹配的命令", + "title": "标题", + "body": "正文" + }, + "attributeName": { + "deleted": "已删除", + "independent": "独立保留", + "created_at": "创建时间", + "modified_at": "修改时间", + "recycle_reason": "回收原因", + "recycled_at": "回收时间", + "pinned": "固定到侧栏", + "tags": "标签", + "links": "关联页面", + "paper_files": "附件", + "paper_authors": "作者", + "paper_doi": "DOI", + "paper_year": "发表时间", + "paper_venue": "期刊 / 会议", + "paper_url": "原文地址", + "paper_abstract": "摘要", + "paper_keywords": "关键词", + "source_snapshot": "原始来源", + "reading_position": "阅读位置", + "paper_annotations": "批注", + "annotation_file": "文件", + "annotation_position": "位置", + "annotation_color": "颜色", + "annotation_quote": "原文", + "annotation_context": "上下文", + "annotation_extractor": "提取器版本", + "feed_url": "订阅地址", + "feed_status": "订阅状态", + "feed_refresh": "刷新间隔", + "feed_last_refreshed": "上次成功刷新", + "feed_last_checked": "上次尝试刷新", + "feed_last_added": "上次新增条目数", + "feed_error": "错误", + "feed_failures": "连续失败次数", + "feed_etag": "ETag", + "feed_last_modified": "Last-Modified" + }, "notice": { "reminderTitle": "知织提醒" } diff --git a/main/app/ipc.ts b/main/app/ipc.ts index cbcc059..e1ee060 100644 --- a/main/app/ipc.ts +++ b/main/app/ipc.ts @@ -9,6 +9,9 @@ export function registerAppIPCs(window: BrowserWindow): void { const contents = window.webContents; register(contents, appChannels, { openDevTools: route(typia.createAssert>(invalid), () => contents.openDevTools({ mode: "detach" })), + setFrameColors: route(typia.createAssert>(invalid), (color, symbolColor) => { + if (process.platform !== "darwin" && !window.isDestroyed()) window.setTitleBarOverlay({ color, symbolColor }); + }), editorStarted: route(typia.createAssert>(invalid), () => lifecycle.editorStarted(contents)), beforeQuitResult: route(typia.createAssert>(invalid), (id, blocked) => lifecycle.saveResult(contents, id, blocked)) } satisfies Messages, on); diff --git a/main/knowledge/records.ts b/main/knowledge/records.ts index a3c8188..ed42157 100644 --- a/main/knowledge/records.ts +++ b/main/knowledge/records.ts @@ -3,10 +3,11 @@ import { resolveAttributeDefinition } from "../../shared/attrs/definitions"; import { search } from "../../shared/attrs/format"; import { decodeValue, emptyValue, encodeValue, nullable, record, validUUID } from "../../shared/attrs/values"; import { blockText, payload, validateBlock, validTarget } from "../../shared/content/blocks"; +import { matchRanges } from "../../shared/content/matches"; import { resolveTimeZone } from "../../shared/content/time"; import { LabloomError } from "../../shared/failure"; import { type AttributeDefinition, type AttributeValue } from "../../shared/types/attributes"; -import { pageKinds, type Backlink, type ContentBlock, type LinkTarget, type PageKind, type PageList, type PageObjects, type PageQuery, type PageRecord, type PageSummary, type ResolvedTarget, type Target } from "../../shared/types/content"; +import { pageKinds, type Backlink, type ContentBlock, type LinkTarget, type PageKind, type PageList, type PageObjects, type PageQuery, type PageRecord, type PageSummary, type PageSearchResult, type ResolvedTarget, type Target } from "../../shared/types/content"; import { type blocks, type pages } from "../storage/tables"; import * as workspace from "../workspace-state"; @@ -51,7 +52,7 @@ export function initialize(): void { definitions.set(id, cached); } const names: Record = fileNames ? JSON.parse(fileNames) : {}; - return search(cached.definition, decodeValue(cached.definition, stored), { zone, fileName: id => names[id] }).toLocaleLowerCase(); + return search(cached.definition, decodeValue(cached.definition, stored), { zone, fileName: id => names[id] }); }); sql.function("knowledge_lower", { deterministic: true }, (value: string) => value.toLocaleLowerCase()); @@ -203,6 +204,36 @@ function excerpt(ids: string[], blocks: Record): string { return text.slice(0, 240); } +// The same formatted attribute value can belong to many pages (tags, dates, options). +// Format each distinct value once, then use page_attrs_by_value to find its pages. +const attributeHits = `distinct_values AS MATERIALIZED ( + SELECT attr_id, value FROM page_attrs WHERE value IS NOT NULL GROUP BY attr_id, value +), matched_values AS MATERIALIZED ( + SELECT v.attr_id, v.value FROM distinct_values v JOIN attrs_meta a ON a.id=v.attr_id + WHERE instr(knowledge_lower(${attributeText()}), @keyword)>0 +), attribute_hits AS ( + SELECT p.page_id AS id, min(m.attr_id) AS attr FROM matched_values m + JOIN page_attrs p ON p.attr_id=m.attr_id AND p.value=m.value GROUP BY p.page_id +)`; + +function attributeText(): string { + return `knowledge_search(a.id,a.type,a.name,a.metadata,v.value,@zone, + CASE WHEN a.type IN ('file','files') THEN ( + SELECT json_group_object(f.id,f.original_name) FROM attachments f + JOIN json_each(CASE a.type WHEN 'file' THEN json_array(v.value) ELSE v.value END) j ON j.value=f.id + ) END)`; +} + +const blockHits = `block_hits(id) AS MATERIALIZED ( + SELECT b.id FROM blocks b WHERE instr(knowledge_lower(knowledge_text(b.type,b.content)), @keyword)>0 +), owners(kind,id) AS ( + SELECT 'block', id FROM block_hits + UNION SELECT u.container_kind,u.container_id FROM owners o JOIN sync_refs u ON u.block_id=o.id WHERE o.kind='block' +)`; +const searchMatches = `WITH RECURSIVE ${blockHits}, ${attributeHits}, matches(id) AS ( + SELECT id FROM owners WHERE kind='page' UNION SELECT id FROM attribute_hits +) `; + function listRows(query: PageQuery): { selected: ListRow[]; total: number } { if (!record(query) || (query.kind && !pageKinds.includes(query.kind)) || (query.keyword !== undefined && typeof query.keyword !== "string") || (query.pinned !== undefined && typeof query.pinned !== "boolean") || (query.deleted !== undefined && typeof query.deleted !== "boolean") || @@ -244,20 +275,9 @@ function listRows(query: PageQuery): { selected: ListRow[]; total: number } { const keyword = query.keyword?.trim().toLocaleLowerCase(); let cte = ""; if (keyword) { - cte = `WITH RECURSIVE hits(kind,id) AS ( - SELECT 'block', b.id FROM blocks b WHERE instr(knowledge_lower(knowledge_text(b.type,b.content)), ?) > 0 - UNION SELECT u.container_kind, u.container_id FROM hits h JOIN sync_refs u ON u.block_id=h.id WHERE h.kind='block' - ), matches(id) AS ( - SELECT id FROM hits WHERE kind='page' - UNION SELECT v.page_id FROM page_attrs v JOIN attrs_meta a ON a.id=v.attr_id - WHERE v.value IS NOT NULL AND instr(knowledge_search(a.id,a.type,a.name,a.metadata,v.value,?, - CASE WHEN a.type IN ('file','files') THEN ( - SELECT json_group_object(f.id,f.original_name) FROM attachments f - JOIN json_each(CASE a.type WHEN 'file' THEN json_array(v.value) ELSE v.value END) j ON j.value=f.id - ) END),?) > 0 - ) `; + cte = searchMatches; where.push("p.id IN (SELECT id FROM matches)"); - params.unshift(keyword, resolveTimeZone(workspace.timeZone()), keyword); + params.unshift({ keyword, zone: resolveTimeZone(workspace.timeZone()) }); } const from = " FROM pages p JOIN page_attrs d ON d.page_id=p.id AND d.attr_id='deleted'"; const filter = " WHERE " + where.join(" AND "); @@ -294,6 +314,67 @@ export function list(query: PageQuery = {}): PageList { return { items: summaries(selected), total }; } +type SearchRow = ListRow & { field: "title" | "body" | "attribute"; attr: string | null; name: string | null; text: string | null }; + +// Within each selected page follow only the first matching branch, in document order. +// UNION in owners deduplicates shared subtrees regardless of how often they occur. +const searchSQL = searchMatches + `, ranked AS MATERIALIZED ( + SELECT p.id, p.kind, p.title_block_id AS titleBlockId, p.children, a.attr, s.value AS modified, + CASE WHEN p.title_block_id IN block_hits THEN 'title' + WHEN p.id IN (SELECT id FROM owners WHERE kind='page') THEN 'body' ELSE 'attribute' END AS field, + count(*) OVER() AS total + FROM matches m JOIN pages p ON p.id=m.id + JOIN page_attrs d ON d.page_id=p.id AND d.attr_id='deleted' AND d.value=0 + JOIN page_attrs s ON s.page_id=p.id AND s.attr_id='modified_at' + LEFT JOIN attribute_hits a ON a.id=p.id + ORDER BY (field='title') DESC, s.value DESC, p.id LIMIT @limit OFFSET @offset +), walk(page,kind,id) AS ( + SELECT id,'page',id FROM ranked WHERE field='body' + UNION ALL + SELECT w.page,'block',( + SELECT r.block_id FROM sync_refs r + WHERE r.container_kind=w.kind AND r.container_id=w.id AND r.slot='children' + AND r.block_id IN (SELECT id FROM owners WHERE kind='block') ORDER BY r.position LIMIT 1 + ) FROM walk w WHERE w.kind='page' OR w.id NOT IN block_hits +), body AS ( + SELECT w.page, b.type, b.content FROM walk w JOIN blocks b ON b.id=w.id WHERE w.kind='block' AND w.id IN block_hits +) +SELECT r.*, a.name, CASE r.field WHEN 'body' THEN knowledge_text(b.type,b.content) + WHEN 'attribute' THEN ${attributeText()} END AS text FROM ranked r +LEFT JOIN body b ON b.page=r.id +LEFT JOIN page_attrs v ON r.field='attribute' AND v.page_id=r.id AND v.attr_id=r.attr +LEFT JOIN attrs_meta a ON a.id=v.attr_id +ORDER BY (r.field='title') DESC, r.modified DESC, r.id`; + +export function searchPages(keyword: string, offset = 0, limit = 30): { items: PageSearchResult[]; total: number } { + workspace.requireWorkspace(); + if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(limit) || limit < 1) throw new LabloomError({ kind: "page-invalid-range" }); + keyword = keyword.trim().toLocaleLowerCase(); + if (!keyword) return { items: [], total: 0 }; + const params = { keyword, zone: resolveTimeZone(workspace.timeZone()) }; + const rows = statement(searchSQL).all({ ...params, offset, limit }) as SearchRow[]; + const pages = summaries(rows); + const items = rows.map((row, index): PageSearchResult => { + const page = pages[index]; + if (row.field === "title") return { ...page, match: { field: "title" } }; + const snippet = matchSnippet(row.text!, keyword); + if (row.field === "body") return { ...page, match: { field: "body", snippet } }; + const id = row.attr!; + return { ...page, match: { field: "attribute", id, name: row.name ?? definition(id)!.name, snippet } }; + }); + const total = rows[0]?.total ?? (offset ? statement(searchMatches + + "SELECT count(*) FROM matches m JOIN page_attrs d ON d.page_id=m.id AND d.attr_id='deleted' AND d.value=0").pluck().get(params) as number : 0); + return { items, total }; +} + +function matchSnippet(text: string, keyword: string): string { + const [first, last] = matchRanges(text, keyword).next().value!; + let start = Math.max(0, first - 36), end = Math.min(text.length, last + 36); + if (start && /[\uDC00-\uDFFF]/u.test(text[start])) start--; + if (end < text.length && /[\uDC00-\uDFFF]/u.test(text[end])) end++; + return (start ? "…" : "") + text.slice(start, end) + (end < text.length ? "…" : ""); +} + export function listUpdates(query: PageQuery, unchanged: string[]): PageList & { order: string[] } { workspace.requireWorkspace(); if (!Array.isArray(unchanged) || !unchanged.every(validUUID)) throw new LabloomError({ kind: "page-invalid-ids" }); diff --git a/main/pages/ipc.ts b/main/pages/ipc.ts index 4cff6e1..15a2e97 100644 --- a/main/pages/ipc.ts +++ b/main/pages/ipc.ts @@ -12,6 +12,7 @@ type Args = Parameters; export const routes = { list: route(typia.createAssert>(invalid), records.list), + search: route(typia.createAssert>(invalid), records.searchPages), listUpdates: route(typia.createAssert>(invalid), records.listUpdates), get: route(typia.createAssert>(invalid), papers.get), readObjects: route(typia.createAssert>(invalid), records.readObjects), diff --git a/main/ui/window.ts b/main/ui/window.ts index 53e74e2..9c66787 100644 --- a/main/ui/window.ts +++ b/main/ui/window.ts @@ -19,11 +19,7 @@ export function createWindow(applicationLog: LogFile | null): void { const bounds = settings.get().settings.window; const mainWindow = new BrowserWindow({ ...(process.platform !== "darwin" ? { - titleBarOverlay: { - color: "#fffdf7", - symbolColor: "#302c25", - height: 32 - } + titleBarOverlay: { height: 32 } } : {}), width: bounds.width, height: bounds.height, diff --git a/main/ui/windowFrame.ts b/main/ui/windowFrame.ts index c7a53f4..a8d5202 100644 --- a/main/ui/windowFrame.ts +++ b/main/ui/windowFrame.ts @@ -12,25 +12,17 @@ export function attach(window: BrowserWindow): () => void { const { width, height } = window.getBounds(); settings.update({ window: { width, height, maximized } }); }; - const applyFrame = (): void => { - if (process.platform === "darwin" || window.isDestroyed()) return; - window.setTitleBarOverlay({ color: nativeTheme.shouldUseDarkColors ? "#292923" : "#fffdf7", symbolColor: nativeTheme.shouldUseDarkColors ? "#eee4d1" : "#302c25" }); - }; const applyTheme = (): void => { const theme = settings.get().settings.appearance.theme; if (nativeTheme.themeSource !== theme) nativeTheme.themeSource = theme; - applyFrame(); }; window.on("resize", rememberWindow); window.on("maximize", rememberWindow); window.on("unmaximize", rememberWindow); window.on("restore", rememberWindow); window.on("leave-full-screen", rememberWindow); - nativeTheme.on("updated", applyFrame); applyTheme(); const unsubscribe = settings.subscribe(applyTheme); - window.once("closed", () => { - unsubscribe(); nativeTheme.removeListener("updated", applyFrame); - }); + window.once("closed", unsubscribe); return rememberWindow; } \ No newline at end of file diff --git a/main/workspace-settings.ts b/main/workspace-settings.ts index 5841818..520962f 100644 --- a/main/workspace-settings.ts +++ b/main/workspace-settings.ts @@ -1,9 +1,9 @@ import { LabloomError } from "../shared/failure"; -import { normalizeKeywords, type WorkspaceSettings, type WorkspaceSettingsPatch } from "../shared/settings/workspace"; +import { defaultExpandedGroups, recentPageLimit, normalizeKeywords, type RecentPage, type WorkspaceNavigation, type WorkspaceSettings, type WorkspaceSettingsPatch } from "../shared/settings/workspace"; import * as workspace from "./workspace-state"; import * as data from "./knowledge/records"; import * as commit from "./knowledge/commit"; -import { record } from "../shared/attrs/values"; +import { record, validUUID } from "../shared/attrs/values"; import type { SavedTabs } from "../shared/workspace/tabs"; function checkStoredLayout(value: unknown): void { @@ -11,6 +11,17 @@ function checkStoredLayout(value: unknown): void { } let settings: WorkspaceSettings | undefined; +function recentPages(value: unknown): RecentPage[] { + if (!Array.isArray(value)) return []; + const latest = new Map(); + for (const entry of value) { + if (record(entry) && validUUID(entry.id) && typeof entry.openedAt === "number" && Number.isSafeInteger(entry.openedAt) && entry.openedAt >= 0 && Number.isFinite(new Date(entry.openedAt).getTime())) { + latest.set(entry.id, Math.max(entry.openedAt, latest.get(entry.id) ?? 0)); + } + } + return [...latest].sort((a, b) => b[1] - a[1]).slice(0, recentPageLimit).map(([id, openedAt]) => ({ id, openedAt })); +} + function decode(value: unknown): WorkspaceSettings { const result: WorkspaceSettings = { tabs: null, feedKeywords: [] }; if (!value || typeof value !== "object" || Array.isArray(value)) { @@ -26,6 +37,8 @@ function decode(value: unknown): WorkspaceSettings { console.warn("Invalid workspace tab layout; using defaults", error); } } + if (Array.isArray(input.expandedGroups) && input.expandedGroups.every(key => typeof key === "string")) result.expandedGroups = [...new Set(input.expandedGroups)]; + if (input.recentPages !== undefined) result.recentPages = recentPages(input.recentPages); const keywords = input.feedKeywords; if (keywords !== undefined) { try { @@ -60,7 +73,7 @@ export function get(): WorkspaceSettings { } export function update(patch: WorkspaceSettingsPatch): WorkspaceSettings { workspace.requireWorkspace(); - if (!patch || typeof patch !== "object" || Array.isArray(patch) || Object.keys(patch).some(key => !["tabs", "feedKeywords"].includes(key))) throw new LabloomError({ kind: "invalid-argument" }); + if (!patch || typeof patch !== "object" || Array.isArray(patch) || Object.keys(patch).some(key => !["tabs", "feedKeywords", "expandedGroups", "recentPages"].includes(key))) throw new LabloomError({ kind: "invalid-argument" }); if (Object.hasOwn(patch, "tabs") && patch.tabs !== null) checkStoredLayout(patch.tabs); const keywords = Object.hasOwn(patch, "feedKeywords") ? normalizeKeywords(patch.feedKeywords) : undefined; return commit.run({ history: false, updateModified: false, feed: keywords !== undefined }, context => { @@ -75,7 +88,11 @@ export function update(patch: WorkspaceSettingsPatch): WorkspaceSettings { export function loadTabs(): unknown { return get().tabs; } -export function saveTabs(value: SavedTabs): void { +export function loadNavigation(): WorkspaceNavigation { + const { expandedGroups = [...defaultExpandedGroups], recentPages = [] } = get(); + return { expandedGroups, recentPages }; +} +export function saveTabs(value: SavedTabs, navigation?: WorkspaceNavigation): void { workspace.requireWorkspace(); - update({ tabs: value }); + update(navigation ? { tabs: value, expandedGroups: [...new Set(navigation.expandedGroups)], recentPages: recentPages(navigation.recentPages) } : { tabs: value }); } \ No newline at end of file diff --git a/main/workspace/ipc.ts b/main/workspace/ipc.ts index 801fb02..2e9ca29 100644 --- a/main/workspace/ipc.ts +++ b/main/workspace/ipc.ts @@ -8,6 +8,7 @@ type Args = Parameters>(invalid), workspace.loadTabs), + loadNavigation: route(typia.createAssert>(invalid), workspace.loadNavigation), saveTabs: route(typia.createAssert>(invalid), workspace.saveTabs) } satisfies Routes; export function registerWorkspaceIPCs(window: BrowserWindow): void { diff --git a/package.json b/package.json index 44a6a88..eea510d 100644 --- a/package.json +++ b/package.json @@ -26,6 +26,7 @@ "typecheck": "npm run typecheck:node && npm run svelte-check", "start": "electron-vite preview --config configs/electron.vite.config.ts", "dev": "electron-vite dev --config configs/electron.vite.config.ts", + "dev:components": "vite --config configs/components.preview.ts", "dev:feed": "vite --config configs/feed.preview.ts", "build": "npm run typecheck && electron-vite build --config configs/electron.vite.config.ts", "build:unpack": "npm run build && electron-builder --dir", @@ -43,6 +44,7 @@ "@tiptap/extension-table": "3.31.3", "@tiptap/extension-text": "^3.31.3", "@tiptap/pm": "^3.31.3", + "@vscode/codicons": "0.0.46-24", "better-sqlite3": "^13.0.3", "bits-ui": "^2.19.2", "drizzle-orm": "^0.45.4", @@ -57,8 +59,9 @@ "@electron-toolkit/tsconfig": "^2.0.0", "@eslint/css": "^2.0.0", "@eslint/json": "^2.1.0", - "@stylistic/eslint-plugin": "^5.10.0", + "@fluentui/svg-icons": "^1.1.346", "@napi-rs/canvas": "1.0.9", + "@stylistic/eslint-plugin": "^5.10.0", "@sveltejs/vite-plugin-svelte": "^7.3.1", "@types/better-sqlite3": "^9.6.0", "@types/node": "^22.20.2", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2a77122..e9fa131 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -187,6 +187,9 @@ importers: '@tiptap/pm': specifier: ^3.31.3 version: 3.31.3 + '@vscode/codicons': + specifier: 0.0.46-24 + version: 0.0.46-24 better-sqlite3: specifier: ^13.0.3 version: 13.0.3 @@ -224,6 +227,9 @@ importers: '@eslint/json': specifier: ^2.1.0 version: 2.1.0 + '@fluentui/svg-icons': + specifier: ^1.1.346 + version: 1.1.346 '@napi-rs/canvas': specifier: 1.0.9 version: 1.0.9 @@ -953,6 +959,9 @@ packages: '@floating-ui/utils@0.2.12': resolution: {integrity: sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==} + '@fluentui/svg-icons@1.1.346': + resolution: {integrity: sha512-pR/ksxLi0Y1O8D1Mk/rEF5Z1TIOSFWDOoN4gkgAUkezakHjTYUVru1yG/bRdvlQnUOMCXESIFIq9eGRFsAVYRA==} + '@humanfs/core@0.19.2': resolution: {integrity: sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==} engines: {node: '>=18.18.0'} @@ -1674,6 +1683,9 @@ packages: '@typia/utils@12.2.1': resolution: {integrity: sha512-SI83b5G/Tplk5nxmwjVwazV97AOf1aC6Rrbb3A1PXbauwa+W0Os2+Xmn7KqGgJNm2Iq4chm94CheHKZihZnqiA==} + '@vscode/codicons@0.0.46-24': + resolution: {integrity: sha512-KIDWUYxG6eh+DHRg+3G4bS487T+g1ZkLfB4HylOBbCcHsvLdfLMRM/m92DS1Ljhi8nglLr9ucwwWhHTEAC+DpA==} + '@xmldom/xmldom@0.8.15': resolution: {integrity: sha512-/5NV/vDALVFDXgLmfsy9TRCBlKwO2LNBFzpzvb9iIj+jR+eSc6DLYYvVOdivT/jm7MtU6TebYuRmzEOI7w40UA==} engines: {node: '>=10.0.0'} @@ -4298,6 +4310,8 @@ snapshots: '@floating-ui/utils@0.2.12': {} + '@fluentui/svg-icons@1.1.346': {} + '@humanfs/core@0.19.2': dependencies: '@humanfs/types': 0.15.0 @@ -4887,6 +4901,8 @@ snapshots: dependencies: '@typia/interface': 12.2.1 + '@vscode/codicons@0.0.46-24': {} + '@xmldom/xmldom@0.8.15': {} abbrev@4.0.0: {} diff --git a/renderer/assets/basil--book-outline.svg b/renderer/assets/basil--book-outline.svg deleted file mode 100644 index 3b6fb24..0000000 --- a/renderer/assets/basil--book-outline.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/renderer/assets/carbon--add-large.svg b/renderer/assets/carbon--add-large.svg deleted file mode 100644 index 4fdaec4..0000000 --- a/renderer/assets/carbon--add-large.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/renderer/assets/carbon--ai-agent.svg b/renderer/assets/carbon--ai-agent.svg deleted file mode 100644 index 8f8e721..0000000 --- a/renderer/assets/carbon--ai-agent.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/renderer/assets/carbon--arrow-left.svg b/renderer/assets/carbon--arrow-left.svg deleted file mode 100644 index 1f88576..0000000 --- a/renderer/assets/carbon--arrow-left.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/renderer/assets/carbon--arrow-right.svg b/renderer/assets/carbon--arrow-right.svg deleted file mode 100644 index 5efbabe..0000000 --- a/renderer/assets/carbon--arrow-right.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/renderer/assets/carbon--calendar.svg b/renderer/assets/carbon--calendar.svg deleted file mode 100644 index 3d2e8d0..0000000 --- a/renderer/assets/carbon--calendar.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/renderer/assets/carbon--chevron-down.svg b/renderer/assets/carbon--chevron-down.svg deleted file mode 100644 index f6947aa..0000000 --- a/renderer/assets/carbon--chevron-down.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/renderer/assets/carbon--chevron-up.svg b/renderer/assets/carbon--chevron-up.svg deleted file mode 100644 index 3b2f08f..0000000 --- a/renderer/assets/carbon--chevron-up.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/renderer/assets/carbon--close-large.svg b/renderer/assets/carbon--close-large.svg deleted file mode 100644 index d17eb7c..0000000 --- a/renderer/assets/carbon--close-large.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/renderer/assets/carbon--close.svg b/renderer/assets/carbon--close.svg deleted file mode 100644 index 6cc1a23..0000000 --- a/renderer/assets/carbon--close.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/renderer/assets/carbon--code.svg b/renderer/assets/carbon--code.svg deleted file mode 100644 index 6a58b88..0000000 --- a/renderer/assets/carbon--code.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/renderer/assets/carbon--color-palette.svg b/renderer/assets/carbon--color-palette.svg deleted file mode 100644 index 36cc177..0000000 --- a/renderer/assets/carbon--color-palette.svg +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/renderer/assets/carbon--home.svg b/renderer/assets/carbon--home.svg deleted file mode 100644 index 8dce4a9..0000000 --- a/renderer/assets/carbon--home.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/renderer/assets/carbon--redo.svg b/renderer/assets/carbon--redo.svg deleted file mode 100644 index bf93545..0000000 --- a/renderer/assets/carbon--redo.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/renderer/assets/carbon--rotate-clockwise.svg b/renderer/assets/carbon--rotate-clockwise.svg deleted file mode 100644 index 3fb35ae..0000000 --- a/renderer/assets/carbon--rotate-clockwise.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/renderer/assets/carbon--rss.svg b/renderer/assets/carbon--rss.svg deleted file mode 100644 index 31a7a7c..0000000 --- a/renderer/assets/carbon--rss.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/renderer/assets/carbon--search.svg b/renderer/assets/carbon--search.svg deleted file mode 100644 index 951d1c9..0000000 --- a/renderer/assets/carbon--search.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/renderer/assets/carbon--settings.svg b/renderer/assets/carbon--settings.svg deleted file mode 100644 index 30e3d56..0000000 --- a/renderer/assets/carbon--settings.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/renderer/assets/carbon--text-bold.svg b/renderer/assets/carbon--text-bold.svg deleted file mode 100644 index c61609f..0000000 --- a/renderer/assets/carbon--text-bold.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/renderer/assets/carbon--text-clear-format.svg b/renderer/assets/carbon--text-clear-format.svg deleted file mode 100644 index fd2a7b8..0000000 --- a/renderer/assets/carbon--text-clear-format.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/renderer/assets/carbon--text-color.svg b/renderer/assets/carbon--text-color.svg deleted file mode 100644 index c7a2b6a..0000000 --- a/renderer/assets/carbon--text-color.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/renderer/assets/carbon--text-highlight.svg b/renderer/assets/carbon--text-highlight.svg deleted file mode 100644 index 3434cfd..0000000 --- a/renderer/assets/carbon--text-highlight.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/renderer/assets/carbon--text-italic.svg b/renderer/assets/carbon--text-italic.svg deleted file mode 100644 index ad2266d..0000000 --- a/renderer/assets/carbon--text-italic.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/renderer/assets/carbon--text-strikethrough.svg b/renderer/assets/carbon--text-strikethrough.svg deleted file mode 100644 index fc776db..0000000 --- a/renderer/assets/carbon--text-strikethrough.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/renderer/assets/carbon--text-underline.svg b/renderer/assets/carbon--text-underline.svg deleted file mode 100644 index a29bea0..0000000 --- a/renderer/assets/carbon--text-underline.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/renderer/assets/carbon--undo.svg b/renderer/assets/carbon--undo.svg deleted file mode 100644 index 75008b1..0000000 --- a/renderer/assets/carbon--undo.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/renderer/assets/carbon--zoom-in.svg b/renderer/assets/carbon--zoom-in.svg deleted file mode 100644 index 01a1b1f..0000000 --- a/renderer/assets/carbon--zoom-in.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/renderer/assets/carbon--zoom-out.svg b/renderer/assets/carbon--zoom-out.svg deleted file mode 100644 index 5873366..0000000 --- a/renderer/assets/carbon--zoom-out.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/renderer/assets/codicon--library.svg b/renderer/assets/codicon--library.svg deleted file mode 100644 index 4b88db7..0000000 --- a/renderer/assets/codicon--library.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/renderer/assets/custom--flower.svg b/renderer/assets/custom--flower.svg deleted file mode 100644 index 58f6622..0000000 --- a/renderer/assets/custom--flower.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/renderer/assets/custom--pen.svg b/renderer/assets/custom--pen.svg deleted file mode 100644 index b630449..0000000 --- a/renderer/assets/custom--pen.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/renderer/assets/custom--split-down.svg b/renderer/assets/custom--split-down.svg deleted file mode 100644 index 64ab607..0000000 --- a/renderer/assets/custom--split-down.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/renderer/assets/custom--split-right.svg b/renderer/assets/custom--split-right.svg deleted file mode 100644 index 7c7c373..0000000 --- a/renderer/assets/custom--split-right.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/renderer/assets/custom--star.svg b/renderer/assets/custom--star.svg deleted file mode 100644 index 9868ebc..0000000 --- a/renderer/assets/custom--star.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/renderer/assets/fonts/codicons-CC-BY-4.0.txt b/renderer/assets/fonts/codicons-CC-BY-4.0.txt new file mode 100644 index 0000000..058c1e1 --- /dev/null +++ b/renderer/assets/fonts/codicons-CC-BY-4.0.txt @@ -0,0 +1,403 @@ +Visual Studio Code Codicons — Microsoft Corporation +Source: https://github.com/microsoft/vscode-codicons +Icon artwork and font, unmodified. CC BY 4.0: https://creativecommons.org/licenses/by/4.0/ + +Attribution 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More_considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution 4.0 International Public License ("Public License"). To the +extent this Public License may be interpreted as a contract, You are +granted the Licensed Rights in consideration of Your acceptance of +these terms and conditions, and the Licensor grants You such rights in +consideration of benefits the Licensor receives from making the +Licensed Material available under these terms and conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + d. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + g. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + i. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + j. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + k. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's + License You apply must not prevent recipients of the Adapted + Material from complying with this Public License. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. + +--- + +Git Logo by [Jason Long](https://bsky.app/profile/jasonlong.me) is licensed under the [Creative Commons Attribution 3.0 Unported License](https://creativecommons.org/licenses/by/3.0/). \ No newline at end of file diff --git a/renderer/assets/fonts/codicons-MIT.txt b/renderer/assets/fonts/codicons-MIT.txt new file mode 100644 index 0000000..7caa112 --- /dev/null +++ b/renderer/assets/fonts/codicons-MIT.txt @@ -0,0 +1,25 @@ +Visual Studio Code Codicons — Microsoft Corporation +Source: https://github.com/microsoft/vscode-codicons +Software (including the font stylesheet), MIT. + + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE \ No newline at end of file diff --git a/renderer/assets/fonts/fluentui-system-icons-MIT.txt b/renderer/assets/fonts/fluentui-system-icons-MIT.txt new file mode 100644 index 0000000..1259253 --- /dev/null +++ b/renderer/assets/fonts/fluentui-system-icons-MIT.txt @@ -0,0 +1,24 @@ +Fluent UI System Icons — Microsoft Corporation +Source: https://github.com/microsoft/fluentui-system-icons + +MIT License + +Copyright (c) 2020 Microsoft Corporation + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/renderer/assets/fonts/nunito-OFL.txt b/renderer/assets/fonts/nunito-OFL.txt deleted file mode 100644 index 11a19ad..0000000 --- a/renderer/assets/fonts/nunito-OFL.txt +++ /dev/null @@ -1,93 +0,0 @@ -Copyright 2014 The Nunito Project Authors (https://github.com/googlefonts/nunito) - -This Font Software is licensed under the SIL Open Font License, Version 1.1. -This license is copied below, and is also available with a FAQ at: -http://scripts.sil.org/OFL - - ------------------------------------------------------------ -SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 ------------------------------------------------------------ - -PREAMBLE -The goals of the Open Font License (OFL) are to stimulate worldwide -development of collaborative font projects, to support the font creation -efforts of academic and linguistic communities, and to provide a free and -open framework in which fonts may be shared and improved in partnership -with others. - -The OFL allows the licensed fonts to be used, studied, modified and -redistributed freely as long as they are not sold by themselves. The -fonts, including any derivative works, can be bundled, embedded, -redistributed and/or sold with any software provided that any reserved -names are not used by derivative works. The fonts and derivatives, -however, cannot be released under any other type of license. The -requirement for fonts to remain under this license does not apply -to any document created using the fonts or their derivatives. - -DEFINITIONS -"Font Software" refers to the set of files released by the Copyright -Holder(s) under this license and clearly marked as such. This may -include source files, build scripts and documentation. - -"Reserved Font Name" refers to any names specified as such after the -copyright statement(s). - -"Original Version" refers to the collection of Font Software components as -distributed by the Copyright Holder(s). - -"Modified Version" refers to any derivative made by adding to, deleting, -or substituting -- in part or in whole -- any of the components of the -Original Version, by changing formats or by porting the Font Software to a -new environment. - -"Author" refers to any designer, engineer, programmer, technical -writer or other person who contributed to the Font Software. - -PERMISSION & CONDITIONS -Permission is hereby granted, free of charge, to any person obtaining -a copy of the Font Software, to use, study, copy, merge, embed, modify, -redistribute, and sell modified and unmodified copies of the Font -Software, subject to the following conditions: - -1) Neither the Font Software nor any of its individual components, -in Original or Modified Versions, may be sold by itself. - -2) Original or Modified Versions of the Font Software may be bundled, -redistributed and/or sold with any software, provided that each copy -contains the above copyright notice and this license. These can be -included either as stand-alone text files, human-readable headers or -in the appropriate machine-readable metadata fields within text or -binary files as long as those fields can be easily viewed by the user. - -3) No Modified Version of the Font Software may use the Reserved Font -Name(s) unless explicit written permission is granted by the corresponding -Copyright Holder. This restriction only applies to the primary font name as -presented to the users. - -4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font -Software shall not be used to promote, endorse or advertise any -Modified Version, except to acknowledge the contribution(s) of the -Copyright Holder(s) and the Author(s) or with their explicit written -permission. - -5) The Font Software, modified or unmodified, in part or in whole, -must be distributed entirely under this license, and must not be -distributed under any other license. The requirement for fonts to -remain under this license does not apply to any document created -using the Font Software. - -TERMINATION -This license becomes null and void if any of the above conditions are -not met. - -DISCLAIMER -THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT -OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE -COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL -DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM -OTHER DEALINGS IN THE FONT SOFTWARE. \ No newline at end of file diff --git a/renderer/assets/fonts/nunito.ttf b/renderer/assets/fonts/nunito.ttf deleted file mode 100644 index 2ec1f4b..0000000 Binary files a/renderer/assets/fonts/nunito.ttf and /dev/null differ diff --git a/renderer/components/Editor/Color.svelte b/renderer/components/Editor/Color.svelte index 5de6c30..6b0a89a 100644 --- a/renderer/components/Editor/Color.svelte +++ b/renderer/components/Editor/Color.svelte @@ -2,10 +2,7 @@ format.disabled)}> {#snippet child({ props })} - - - {@html paletteIcon} - + {/snippet} @@ -51,12 +48,11 @@ onclick={() => applyColor(format.name, color.value)} > - - {@html format.icon} + {/each} @@ -76,16 +72,6 @@ background: transparent; font-size: .8125rem; } - .icon { - display: inline-flex; - flex-shrink: 0; - width: 1.125rem; - height: 1.125rem; - } - .icon :global(svg) { - width: 100%; - height: 100%; - } .color-menu { --dc-popover-available-height: var(--bits-popover-content-available-height); width: 17rem; @@ -141,10 +127,11 @@ opacity: .4; } .color-icon { + display: inline-flex; width: 1.375rem; height: 1.375rem; } - .color-icon.background :global(svg) { + .color-icon.background :global(.icon) { color: hsl(from currentColor h s calc(l * .6)); } .color-choice.active { @@ -162,12 +149,10 @@ \ No newline at end of file diff --git a/renderer/components/Tab/Layout.svelte b/renderer/components/Tab/Layout.svelte index 13e5ebb..0850c81 100644 --- a/renderer/components/Tab/Layout.svelte +++ b/renderer/components/Tab/Layout.svelte @@ -10,8 +10,9 @@
- closeSplitSide(path, 0)} onMaxExceeded={() => closeSplitSide(path, 1)} - /> + />
@@ -34,6 +35,8 @@ min-width: 0; min-height: 0; } + .divider { display: flex; flex: none; } + .vertical > .divider { flex-direction: column; } .split.vertical { flex-direction: column; } @@ -41,6 +44,7 @@ + + alt = event.altKey} onkeyup={event => alt = event.altKey} onblur={() => alt = false} /> + + + \ No newline at end of file diff --git a/renderer/components/Tab/TabItem.svelte b/renderer/components/Tab/TabItem.svelte new file mode 100644 index 0000000..ead473e --- /dev/null +++ b/renderer/components/Tab/TabItem.svelte @@ -0,0 +1,50 @@ + + + + {#snippet trigger({ props })} + + {/snippet} + + + \ No newline at end of file diff --git a/renderer/components/Tab/interactions.ts b/renderer/components/Tab/interactions.ts index beef69c..dfd3c0e 100644 --- a/renderer/components/Tab/interactions.ts +++ b/renderer/components/Tab/interactions.ts @@ -13,9 +13,8 @@ export function acceptTabDrop(event: DragEvent): boolean { } export function focusTabGroup(groupId: GroupID): void { - const group = document.querySelector(`[data-group-id="${CSS.escape(groupId)}"]`); - const target = group?.querySelector("[data-tabs-trigger][data-state='active']") - ?? group?.querySelector("[data-open-overview]"); + const group = document.querySelector(`[data-group-id="${CSS.escape(groupId)}"]`); + const target = group?.querySelector("[data-tabs-trigger][data-state='active']") ?? group; target?.focus(); } diff --git a/renderer/components/Tab/page-titles.ts b/renderer/components/Tab/page-titles.ts index dd1cf91..905516d 100644 --- a/renderer/components/Tab/page-titles.ts +++ b/renderer/components/Tab/page-titles.ts @@ -1,42 +1,48 @@ -import { readable, type Readable } from "svelte/store"; -import { failure } from "../../i18n.svelte"; +import { derived, readable, toStore, type Readable } from "svelte/store"; +import { type PageKind } from "../../../shared/types/content"; +import { failure, t } from "../../i18n.svelte"; import { knowledgeState } from "../Knowledge/feedback.svelte"; -const watched = new Map; publish: (title: string) => void }>(); +type Heading = { title: string | undefined | null; kind: PageKind }; +const watched = new Map; publish: (title: string) => void }>(); export function publishTitle(id: string, title: string): void { - watched.get(id)?.publish(title || "未命名"); + watched.get(id)?.publish(title); } +function heading(id: string): Readable { + return { subscribe: run => (watched.get(id)?.store ?? observe(id)).subscribe(run) }; +} export function pageTitle(id: string): Readable { - return { - subscribe(run) { - const store = watched.get(id)?.store ?? observe(id); - return store.subscribe(run); - } - }; + const labels = toStore(() => ({ loading: t("shell.page"), missing: t("shell.missing"), untitled: t("shell.untitled") })); + return derived([heading(id), labels], ([page, text]) => page.title === undefined ? text.loading : page.title === null ? text.missing : page.title || text.untitled); +} +export function pageKind(id: string): Readable { + return derived(heading(id), page => page.kind); } -function observe(id: string): Readable { - const store = readable("页面", set => { - let revision = 0; +function observe(id: string): Readable { + const store = readable({ title: undefined, kind: "editable" }, (_set, update) => { + let revision = 0, edits = 0; async function refresh(): Promise { - const request = ++revision; + const request = ++revision, before = edits; try { const query = { ids: [id], limit: 1 }; const page = (await window.api.pages.list(query)).items[0] ?? (await window.api.pages.list({ ...query, deleted: true })).items[0]; - if (request === revision) set(page ? page.title || "未命名" : "找不到页面"); + if (request === revision) update(current => ({ + title: before === edits ? page?.title ?? null : current.title, kind: page?.kind ?? current.kind + })); } catch (problem) { if (request === revision) knowledgeState.error = failure(problem); } } watched.set(id, { store, publish: title => { - revision++; set(title); + edits++; update(current => ({ ...current, title })); } }); const off = window.api.pages.onChanged(change => { - if (change.titlePages?.includes(id) || change.purged?.includes(id)) void refresh(); + if (change.titlePages?.includes(id) || change.purged?.includes(id) || change.kinds?.[id]) void refresh(); }); void refresh(); return () => { diff --git a/renderer/components/Tab/persistence.svelte.ts b/renderer/components/Tab/persistence.svelte.ts index a85b1f3..394e7ea 100644 --- a/renderer/components/Tab/persistence.svelte.ts +++ b/renderer/components/Tab/persistence.svelte.ts @@ -4,9 +4,23 @@ import { getTabID, getGroupID } from "./ids"; import { tabState } from "./state.svelte"; import { restoreTabState } from "./restore"; +import { defaultExpandedGroups, recentPageLimit, type WorkspaceNavigation } from "../../../shared/settings/workspace"; + +export const navigationState = $state({ expandedGroups: [...defaultExpandedGroups], recentPages: [] }); + +export function recordOpen(id: string): void { + navigationState.recentPages = [{ id, openedAt: Date.now() }, ...navigationState.recentPages.filter(entry => entry.id !== id)].slice(0, recentPageLimit); +} +export function toggleGroup(key: string): void { + const groups = navigationState.expandedGroups; + navigationState.expandedGroups = groups.includes(key) ? groups.filter(item => item !== key) : [...groups, key]; +} + export async function restoreTabs(): Promise { window.api.app.editorStarted(); - const state = restoreTabState(await window.api.workspace.loadTabs()); + const [tabs, navigation] = await Promise.all([window.api.workspace.loadTabs(), window.api.workspace.loadNavigation()]); + Object.assign(navigationState, navigation); + const state = restoreTabState(tabs); if (state) Object.assign(tabState, state); else { const id = getGroupID(), tab = { id: getTabID(), view: copyData(destinationViews.overview) }; @@ -14,5 +28,5 @@ export async function restoreTabs(): Promise { } } export function persistTabs(): Promise { - return window.api.workspace.saveTabs(copyData(tabState)); + return window.api.workspace.saveTabs(copyData(tabState), copyData(navigationState)); } \ No newline at end of file diff --git a/renderer/components/Tab/views.ts b/renderer/components/Tab/views.ts index 8ce95d9..542510e 100644 --- a/renderer/components/Tab/views.ts +++ b/renderer/components/Tab/views.ts @@ -1,5 +1,5 @@ import type { Component } from "svelte"; -import { readable, type Readable } from "svelte/store"; +import { toStore, type Readable } from "svelte/store"; import { type ViewParams } from "../../../shared/workspace/views"; import { workspaceHistory, type HistorySource } from "../../../shared/history/ipc"; import Standalone from "./Standalone.svelte"; @@ -11,6 +11,7 @@ import Overview from "../tabs/Overview.svelte"; import About from "../tabs/About.svelte"; import Settings from "../tabs/Settings.svelte"; import FeedView from "../Feed/FeedView.svelte"; +import { t } from "../../i18n.svelte"; import { pageTitle } from "./page-titles"; export type ViewProps = { @@ -23,18 +24,18 @@ type Definition = { keepMounted: boolean; }; const workspace = (): HistorySource => workspaceHistory; -const named = (name: string) => () => readable(name); +const named = (key: Parameters[0]) => () => toStore(() => t(key)); // Standalone screens also render outside the tab host and take no tab inputs. const standalone = (screen: Component): Component<{ tabId: string }> => (anchor, { tabId }) => Standalone(anchor, { tabId, screen }); const views: { [K in keyof ViewParams]: Definition } = { page: { component: PageView, title: p => pageTitle(p.page.id), history: p => ({ kind: "page", id: p.page.id }), keepMounted: true }, - library: { component: Library, title: p => readable(p.scope === "trash" ? "回收站" : p.scope === "pinned" ? "已固定" : p.pageType?.type === "paper" ? "文献库" : "知识库"), history: workspace, keepMounted: true }, - calendar: { component: Calendar, title: named("研究日历"), history: workspace, keepMounted: true }, - overview: { component: Overview, title: named("我的花园"), history: workspace, keepMounted: false }, - attributes: { component: AttributeManagement, title: named("属性管理"), history: workspace, keepMounted: false }, - feed: { component: standalone(FeedView), title: named("订阅动态"), history: workspace, keepMounted: false }, - settings: { component: standalone(Settings), title: named("偏好设置"), history: workspace, keepMounted: false }, - about: { component: standalone(About), title: named("关于知织"), history: workspace, keepMounted: false } + library: { component: Library, title: p => toStore(() => t(p.scope === "trash" ? "shell.trashView" : p.scope === "pinned" ? "shell.pinnedView" : p.pageType?.type === "paper" ? "command.papers" : "command.library")), history: workspace, keepMounted: true }, + calendar: { component: Calendar, title: named("shell.calendarView"), history: workspace, keepMounted: true }, + overview: { component: Overview, title: named("shell.overviewView"), history: workspace, keepMounted: false }, + attributes: { component: AttributeManagement, title: named("command.attributes"), history: workspace, keepMounted: false }, + feed: { component: standalone(FeedView), title: named("shell.feedView"), history: workspace, keepMounted: false }, + settings: { component: standalone(Settings), title: named("command.settings"), history: workspace, keepMounted: false }, + about: { component: standalone(About), title: named("command.about"), history: workspace, keepMounted: false } }; export function definitionFor(type: K): Definition { return views[type]; diff --git a/renderer/components/base/Button.svelte b/renderer/components/base/Button.svelte new file mode 100644 index 0000000..f1a136b --- /dev/null +++ b/renderer/components/base/Button.svelte @@ -0,0 +1,15 @@ + + + \ No newline at end of file diff --git a/renderer/components/base/Checkbox.svelte b/renderer/components/base/Checkbox.svelte new file mode 100644 index 0000000..076230d --- /dev/null +++ b/renderer/components/base/Checkbox.svelte @@ -0,0 +1,23 @@ + + + pointerFocus = true} + onkeydown={() => pointerFocus = false} onblur={() => pointerFocus = false}> + + {#if indeterminate || checked}{/if} + + {label} + \ No newline at end of file diff --git a/renderer/components/base/ConfirmDialog.svelte b/renderer/components/base/ConfirmDialog.svelte new file mode 100644 index 0000000..6fb7f7d --- /dev/null +++ b/renderer/components/base/ConfirmDialog.svelte @@ -0,0 +1,49 @@ + + + open, changeOpen}> + + + + + {title} + {body} +
+ + {#snippet child({ props })}{/snippet} + + + {#snippet child({ props })}{/snippet} + +
+
+
+
\ No newline at end of file diff --git a/renderer/components/base/IconButton.svelte b/renderer/components/base/IconButton.svelte new file mode 100644 index 0000000..664d413 --- /dev/null +++ b/renderer/components/base/IconButton.svelte @@ -0,0 +1,22 @@ + + + + {#snippet trigger({ props })} + + {/snippet} + \ No newline at end of file diff --git a/renderer/components/base/Input.svelte b/renderer/components/base/Input.svelte new file mode 100644 index 0000000..2d6ddd8 --- /dev/null +++ b/renderer/components/base/Input.svelte @@ -0,0 +1,39 @@ + + + + {#if search}{/if} + pointer = fromPointer()} onblur={() => pointer = false} + oninput={event => { + value = event.currentTarget.value; oninput?.(value); + }} /> + {#if search && value} + + {/if} + \ No newline at end of file diff --git a/renderer/components/base/ListRow.svelte b/renderer/components/base/ListRow.svelte new file mode 100644 index 0000000..b8e1981 --- /dev/null +++ b/renderer/components/base/ListRow.svelte @@ -0,0 +1,35 @@ + + +
+ + {#if actions.length} + + {#each actions as action (action)}{/each} + + {/if} +
\ No newline at end of file diff --git a/renderer/components/base/Menu.svelte b/renderer/components/base/Menu.svelte new file mode 100644 index 0000000..a6dabff --- /dev/null +++ b/renderer/components/base/Menu.svelte @@ -0,0 +1,82 @@ + + + + +{#snippet caption(item: MenuCommand | Submenu)} + + {#if item.icon} + {:else if "checked" in item && item.checked}{/if} + + {item.label} + {#if item.icon && "checked" in item && item.checked}{/if} + {#if "items" in item} + {:else if item.shortcut}{item.shortcut}{/if} +{/snippet} + +{#snippet entries(list: MenuItem[])} + {#each list as item (item)} + {#if "separator" in item} + + {:else if "items" in item} + + {@render caption(item)} + + + {@render entries(item.items)} + + + + {:else if item.checked !== undefined} + {@render caption(item)} + {:else} + {@render caption(item)} + {/if} + {/each} +{/snippet} + +{#if context} + + + + {@render entries(items)} + + +{:else} + + + + {@render entries(items)} + + +{/if} \ No newline at end of file diff --git a/renderer/components/base/Popover.svelte b/renderer/components/base/Popover.svelte new file mode 100644 index 0000000..53c9d09 --- /dev/null +++ b/renderer/components/base/Popover.svelte @@ -0,0 +1,23 @@ + + + + + + + {@render children()} + + + \ No newline at end of file diff --git a/renderer/components/base/Select.svelte b/renderer/components/base/Select.svelte new file mode 100644 index 0000000..94361fe --- /dev/null +++ b/renderer/components/base/Select.svelte @@ -0,0 +1,42 @@ + + + + + + + {#if selected?.icon}{/if} + {selected?.label ?? placeholder ?? ""} + + + + + + {#each options as option (option.value)} + + {#if option.icon}{/if} + {option.label} + {#if value === option.value}{/if} + + {/each} + + + + \ No newline at end of file diff --git a/renderer/components/base/Tooltip.svelte b/renderer/components/base/Tooltip.svelte new file mode 100644 index 0000000..df2d1c1 --- /dev/null +++ b/renderer/components/base/Tooltip.svelte @@ -0,0 +1,23 @@ + + + + + + + + {text}{#if shortcut}{shortcut}{/if} + + + + \ No newline at end of file diff --git a/renderer/components/base/controls.css b/renderer/components/base/controls.css new file mode 100644 index 0000000..29bad05 --- /dev/null +++ b/renderer/components/base/controls.css @@ -0,0 +1,191 @@ +@import "../../styles/ui-tokens.css"; + +/* Reset the native elements before styling so the legacy button/input/kbd rules cannot leak in. */ +.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; + font: normal var(--ui-font-body)/1.3 var(--ui-font-family); + color: var(--ui-text); +} + +.ui-control, .ui-check, .ui-field, .ui-row, .ui-row-main, .ui-menu-item { + display: inline-flex; + align-items: center; + gap: var(--ui-space-2); + min-width: 0; + border-radius: var(--ui-radius-control); + transition: background-color var(--ui-duration-fast), border-color var(--ui-duration-fast), color var(--ui-duration-fast); +} + +.ui-control { + justify-content: center; + height: var(--ui-button-height); + padding-inline: var(--ui-space-3); + border: var(--ui-stroke) solid var(--ui-surface-clear); + background: var(--ui-surface-clear); + white-space: nowrap; + cursor: pointer; +} + +.ui-control[data-variant="secondary"] { border-color: var(--ui-border-input); background: var(--ui-surface-panel); } +.ui-control:hover:enabled, .ui-row:hover { background-color: var(--ui-hover); } +.ui-control[aria-pressed="true"] { background-color: var(--ui-selected); color: var(--ui-text-selected); } +.ui-control:active:enabled, .ui-row:has(.ui-row-main:active) { background-color: var(--ui-pressed); } +.ui-control[data-variant="primary"] { background: var(--ui-accent); color: var(--ui-text-on-accent); } +.ui-control[data-variant="primary"]:is(:hover, :active):enabled { background-color: var(--ui-accent-hover); } +.ui-control[data-variant="danger"] { background: var(--ui-danger); color: var(--ui-text-on-accent); } +.ui-control[data-variant="danger"]:is(:hover, :active):enabled { background-color: var(--ui-danger-hover); } +.ui-control:is([data-variant="primary"], [data-variant="danger"]):active:enabled { box-shadow: inset 0 0 0 var(--ui-stroke) currentColor; } + +.ui-control:disabled, .ui-field:has(input:disabled) { + color: var(--ui-text-disabled); + border-color: var(--ui-border); + background: var(--ui-surface-panel); + opacity: 1; + cursor: default; +} +.ui-control.ui-icon-button { width: var(--ui-button-height); padding: 0; } +.ui-control:focus-visible, .ui-row-main:focus-visible, .ui-field:has(input:focus-visible:not([data-pointer])) { + outline: var(--ui-focus-width) solid var(--ui-focus); + outline-offset: var(--ui-focus-offset); +} + +.ui-field, .ui-control.ui-select { + height: var(--ui-input-height); + padding-inline: var(--ui-space-2); + border: var(--ui-stroke) solid var(--ui-border-input); + background: var(--ui-surface-input); + /* Keep clicks around the input from parking a document caret beside it. */ + user-select: none; +} +.ui-field:hover:not(:has(input:disabled)), .ui-control.ui-select:hover:enabled { border-color: var(--ui-text-secondary); } +.ui-field:has(input[aria-invalid="true"]):not(:has(input:disabled)) { border-color: var(--ui-danger); } +.ui-field-input { + flex: 1 1 auto; + min-width: 0; + width: 100%; + height: 100%; + color: inherit; + cursor: text; + user-select: text; + outline: none; +} +.ui-field-input:focus-visible { outline: none; } +.ui-field-input::placeholder, .ui-select[data-placeholder] { color: var(--ui-text-placeholder); } +.ui-field-input:disabled { cursor: default; color: var(--ui-text-disabled); } +.ui-field-input::-webkit-search-cancel-button { display: none; } +.ui-field .ui-icon-button { width: var(--ui-icon-large); height: var(--ui-icon-large); } +.ui-select .ui-select-label { flex: 1; overflow: hidden; text-overflow: ellipsis; text-align: start; } + +.ui-check { + height: var(--ui-button-height); + gap: var(--ui-space-2); + border-radius: var(--ui-radius-small); + cursor: pointer; +} +.ui-check:focus-visible { outline: none; } +.ui-check:disabled { color: var(--ui-text-disabled); opacity: 1; cursor: default; } +.ui-check-mark { + box-sizing: border-box; + display: inline-grid; + flex: none; + place-items: center; + width: var(--ui-icon-normal); + height: var(--ui-icon-normal); + border: var(--ui-stroke) solid var(--ui-border-check); + border-radius: var(--ui-radius-small); + background: var(--ui-surface-input); +} +.ui-check:is([aria-checked="true"], [aria-checked="mixed"]) .ui-check-mark { + background: var(--ui-accent); + border-color: var(--ui-accent); + color: var(--ui-text-on-accent); +} +.ui-check:hover:enabled .ui-check-mark { border-color: var(--ui-border-check-hover); } +.ui-check:focus-visible:not([data-pointer]) .ui-check-mark { + outline: var(--ui-focus-width) solid var(--ui-focus); + outline-offset: var(--ui-focus-offset); +} +.ui-check:disabled .ui-check-mark { background: var(--ui-surface-panel); border-color: var(--ui-border-input); color: var(--ui-text-disabled); } + +.ui-popup { + display: block; + user-select: none; + border: var(--ui-stroke) solid var(--ui-border-input); + border-radius: var(--ui-radius-panel); + background: var(--ui-surface-popup); + box-shadow: var(--ui-shadow-popup); + animation: ui-appear var(--ui-duration-normal) ease-out; +} +@keyframes ui-appear { from { opacity: 0; } to { opacity: 1; } } + +.ui-menu, .ui-options { + z-index: var(--ui-z-dropdown); + padding: var(--ui-space-2); + min-width: 9em; + max-width: calc(100vw - 2 * var(--ui-space-3)); + max-height: var(--bits-dropdown-menu-content-available-height, var(--bits-context-menu-content-available-height, calc(100vh - 2 * var(--ui-space-3)))); + overflow: auto; +} +.ui-menu[data-context] { z-index: var(--ui-z-context-menu); } +.ui-options { min-width: var(--bits-select-anchor-width); max-height: var(--bits-select-content-available-height); } +.ui-menu-item { + display: flex; + width: 100%; + min-height: var(--ui-row-height); + padding-inline: var(--ui-space-2); + gap: var(--ui-space-3); + border-radius: var(--ui-radius-small); + cursor: default; + white-space: nowrap; +} +.ui-menu-item:is([data-highlighted], [data-state="open"]):not([data-disabled]) { + color: var(--ui-text-on-accent); + background: var(--ui-accent); + outline: none; +} +.ui-menu-item[data-disabled] { color: var(--ui-text-disabled); } +.ui-menu-label { flex: 1; overflow: hidden; text-overflow: ellipsis; } +.ui-menu-leading { width: var(--ui-icon-normal); flex: none; display: inline-flex; } +.ui-shortcut { color: inherit; font-size: var(--ui-font-small); white-space: nowrap; } +.ui-menu-separator { height: var(--ui-stroke); margin: var(--ui-space-2); background: var(--ui-divider); } + +.ui-tooltip, .ui-popover { max-width: calc(100vw - 2 * var(--ui-space-3)); overflow-wrap: anywhere; } +.ui-tooltip { + z-index: var(--ui-z-tooltip); + padding: var(--ui-space-2) var(--ui-space-3); + display: flex; + align-items: center; + gap: var(--ui-space-3); +} +.ui-tooltip .ui-shortcut { color: var(--ui-text-secondary); } +.ui-popover { z-index: var(--ui-z-popover); padding: var(--ui-space-4); max-height: var(--bits-popover-content-available-height); overflow: auto; } +.ui-scrim { position: fixed; inset: 0; z-index: var(--ui-z-dialog); background: var(--ui-surface-scrim); } +.ui-dialog { + position: fixed; + z-index: var(--ui-z-dialog); + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + width: min(28em, calc(100vw - 2 * var(--ui-space-5))); + max-height: calc(100vh - 2 * var(--ui-space-5)); + overflow: auto; + padding: var(--ui-space-5); + box-shadow: var(--ui-shadow-dialog); + overflow-wrap: anywhere; +} +.ui-dialog-title { margin: 0; font: 600 var(--ui-font-title)/1.3 var(--ui-font-family); color: var(--ui-text); } +.ui-dialog-body { margin: var(--ui-space-3) 0 var(--ui-space-5); color: var(--ui-text-secondary); } +.ui-dialog-actions { display: flex; justify-content: flex-end; gap: var(--ui-space-3); } + +.ui-row { display: flex; width: 100%; height: var(--ui-row-height); border-radius: var(--ui-radius-small); } +.ui-row-main { flex: 1; height: 100%; padding-inline: var(--ui-space-2); cursor: pointer; border-radius: inherit; color: inherit; } +.ui-row-main:focus-visible { outline-offset: calc(-1 * var(--ui-focus-width)); } +.ui-row-title, .ui-row-description { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } +.ui-row-description { color: var(--ui-text-secondary); font-size: var(--ui-font-small); } +.ui-row[data-selected] { background-color: var(--ui-selected-inactive); } +.ui-row[data-selected]:is(:focus-within, [data-focused]) { background-color: var(--ui-selected); color: var(--ui-text-selected); } +.ui-row[data-drag-over] { outline: var(--ui-focus-width) dashed var(--ui-focus); outline-offset: calc(-1 * var(--ui-focus-width)); background: var(--ui-hover); } +.ui-row-actions { display: inline-flex; flex: none; align-items: center; opacity: 0; pointer-events: none; } +.ui-row:is(:hover, :focus-within) .ui-row-actions { opacity: 1; pointer-events: auto; } +.ui-row-actions .ui-icon-button { width: var(--ui-icon-large); height: var(--ui-icon-large); } \ No newline at end of file diff --git a/renderer/components/base/modality.ts b/renderer/components/base/modality.ts new file mode 100644 index 0000000..b40a819 --- /dev/null +++ b/renderer/components/base/modality.ts @@ -0,0 +1,9 @@ +// Remembers whether the latest input came from a pointer or the keyboard, so that focus moved by code +// (a popover focusing its first field, say) is drawn the way the user opened it. +let pointer = false; +addEventListener("pointerdown", () => pointer = true, true); +addEventListener("keydown", () => pointer = false, true); + +export function fromPointer(): boolean { + return pointer; +} \ No newline at end of file diff --git a/renderer/components/globalSearch/GSLauncher.svelte b/renderer/components/globalSearch/GSLauncher.svelte index d0c147f..59a90d8 100644 --- a/renderer/components/globalSearch/GSLauncher.svelte +++ b/renderer/components/globalSearch/GSLauncher.svelte @@ -1,88 +1,87 @@ - - + + + shell.search, setOpen} onOpenChangeComplete={finishClose}> + {#snippet child({ props })} - + event.preventDefault()} /> {/snippet} - - {#snippet child({ wrapperProps, props })} -
-
- shell.search = false} /> -
-
- {/snippet} + event.preventDefault()}> + {#if shell.search} + window.api.pages.search(keyword, offset)} + {recent} formatTime={ms => clock.format(ms)} disabled={commandDisabled} + onchoose={selected => { + if (shell.search) { + choice = selected; shell.search = false; + } + }} /> + {/if}
- - - - \ No newline at end of file + \ No newline at end of file diff --git a/renderer/components/globalSearch/GSPopover.svelte b/renderer/components/globalSearch/GSPopover.svelte index 84e7d20..9d6c4c7 100644 --- a/renderer/components/globalSearch/GSPopover.svelte +++ b/renderer/components/globalSearch/GSPopover.svelte @@ -1,127 +1,178 @@ -
- - - {@html search} - - -
-
- {#if showImport} - - {/if} - {#if error}

{message(error)}

{:else if pending}

正在搜索…

{:else} - {#each pages as page, index (page.id)} - - {:else} - {#if !showImport}

没有找到匹配的页面或命令

{/if} - {/each} - {/if} -
-
- Esc 关闭 -
- - - - + \ No newline at end of file + + +
+
+ +
+
{ + if (list.scrollTop + list.clientHeight >= list.scrollHeight - 1) nextPage(); + }}> + {#each options as row, i (row.id)} +
+ selected = i, onmousedown: event => event.preventDefault() }} + onclick={event => choose(i, event.ctrlKey)}> + + {row.detail} + {#if row.snippet}{/if} + + +
+ {/each} +
+ {#if error}

{message(error)}

+ {:else if !options.length && !pending}

{t(commandMode ? "quickOpen.noCommands" : "quickOpen.noPages")}

{/if} +
+ + \ No newline at end of file diff --git a/renderer/components/globalSearch/Highlight.svelte b/renderer/components/globalSearch/Highlight.svelte new file mode 100644 index 0000000..7f630cf --- /dev/null +++ b/renderer/components/globalSearch/Highlight.svelte @@ -0,0 +1,11 @@ + + +{#each matches as [start, end], index (start)}{text.slice(index ? matches[index - 1][1] : 0, start)}{text.slice(start, end)}{/each}{text.slice(matches.at(-1)?.[1] ?? 0)} + + \ No newline at end of file diff --git a/renderer/components/globalSearch/SearchTrigger.svelte b/renderer/components/globalSearch/SearchTrigger.svelte new file mode 100644 index 0000000..7e62b08 --- /dev/null +++ b/renderer/components/globalSearch/SearchTrigger.svelte @@ -0,0 +1,13 @@ + + + + + \ No newline at end of file diff --git a/renderer/components/layout/ActivityBar.svelte b/renderer/components/layout/ActivityBar.svelte new file mode 100644 index 0000000..5c7c01a --- /dev/null +++ b/renderer/components/layout/ActivityBar.svelte @@ -0,0 +1,24 @@ + + + + + \ No newline at end of file diff --git a/renderer/components/layout/App.svelte b/renderer/components/layout/App.svelte index 569e117..870520c 100644 --- a/renderer/components/layout/App.svelte +++ b/renderer/components/layout/App.svelte @@ -1,5 +1,5 @@ {#if startup?.status === "ready"} - +
@@ -21,7 +21,10 @@ + + + {#each menus as menu (menu.id)} - {menu.label} + onremember?.(document.activeElement)} onfocus={event => { + if (event.relatedTarget instanceof Element && !event.relatedTarget.closest(".menubar,[data-menubar-content]")) onremember?.(event.relatedTarget); + }}>{t(`menu.${menu.id}`)} - + {#each menu.items as id (id)} - runCommand(id)}>{commands[id].label}{commands[id].shortcut} + oncommand(id)}> + {commandLabel(id)} + {#if commands[id].shortcut}{commands[id].shortcut}{/if} + {/each} {/each} + - \ No newline at end of file + :global(.menubar) { display: flex; flex: none; } + :global(.menu-trigger[data-state="open"]) { background: var(--ui-hover); } + \ No newline at end of file diff --git a/renderer/components/layout/NavBar.svelte b/renderer/components/layout/NavBar.svelte index 5299fe6..09c67ce 100644 --- a/renderer/components/layout/NavBar.svelte +++ b/renderer/components/layout/NavBar.svelte @@ -1,26 +1,39 @@ + +
- - - - - +
+ oncommand("sidebar")} /> + +
+
{@render children()}
+ - \ No newline at end of file + .titlebar { + -webkit-app-region: drag; + display: grid; + grid-template-columns: minmax(max-content, 1fr) minmax(0, var(--ui-search-width)) minmax(var(--system-controls), 1fr); + align-items: center; + column-gap: var(--ui-space-3); + height: var(--ui-titlebar-height); + flex: none; + --system-controls: max(var(--ui-space-3), calc(100vw - env(titlebar-area-x, 0px) - env(titlebar-area-width, 100vw))); + padding-left: max(var(--ui-space-3), env(titlebar-area-x, 0px)); + background: var(--ui-titlebar-background); + color: var(--ui-titlebar-foreground); + border-bottom: var(--ui-stroke) solid var(--ui-divider); + } + .tools { display: flex; align-items: center; width: fit-content; -webkit-app-region: no-drag; } + .search-launcher { min-width: 0; -webkit-app-region: no-drag; } + \ No newline at end of file diff --git a/renderer/components/layout/PanelGroup.svelte b/renderer/components/layout/PanelGroup.svelte new file mode 100644 index 0000000..3ef3488 --- /dev/null +++ b/renderer/components/layout/PanelGroup.svelte @@ -0,0 +1,21 @@ + + +
+ + {#if expanded}
{@render children()}
{/if} +
+ + \ No newline at end of file diff --git a/renderer/components/layout/SidePanel.svelte b/renderer/components/layout/SidePanel.svelte new file mode 100644 index 0000000..ef262a8 --- /dev/null +++ b/renderer/components/layout/SidePanel.svelte @@ -0,0 +1,20 @@ + + + + + \ No newline at end of file diff --git a/renderer/components/layout/Sidebar.svelte b/renderer/components/layout/Sidebar.svelte index b3500e6..5edd2b4 100644 --- a/renderer/components/layout/Sidebar.svelte +++ b/renderer/components/layout/Sidebar.svelte @@ -1,56 +1,31 @@ - + {#if !shell.collapsed} - - { + + + {#each tags as tag (tag.id)}{/each} + + + { shell.width = value; persistPanel(); }} /> {/if} - + + + - - - - - - \ No newline at end of file + /* Select the closest drawing using the resolved width, including em, rem and CSS variables. */ + @container fluent-icon (min-width: 18px) { + .fluent { mask-image: var(--art-large); } + } + \ No newline at end of file diff --git a/renderer/components/utils/Resizer.svelte b/renderer/components/utils/Resizer.svelte index a29382f..2b30615 100644 --- a/renderer/components/utils/Resizer.svelte +++ b/renderer/components/utils/Resizer.svelte @@ -1,35 +1,30 @@ - - + +
+

知织 / 开发预览

基础组件

+
+
+ + +
+ +
+
+
+
+

交互样例

+
+

按钮

+ + + +
+

图标按钮与复选框

+ report("已选择查找")} /> + bold = !bold} /> + +
+

文本输入

+ + +
+

选择与菜单

+ + + +
+

提示、对话框与浮层

+ {#each ["悬浮提示", "确认对话框", "危险确认", "浮层"] as const as sample (sample)}{/each} +
+

列表行

+ selected = !selected} + actions={[{ icon: "edit", label: "编辑页面 A", onclick: () => report("已选择编辑页面 A") }]} /> +
+
+ +
+

外壳

+

控件状态

+
+

弹出状态

+
+ {#each overlayNames as sample (sample)} +
{sample}
+ {/each} +
+
+
+

颜色与阴影

+
+ {#each colors as name (name)} +
+ {name}{values[name]} +
+ {/each} +
+
+
+

尺寸、层级与动效

+
+ {#each groups as group (group.title)} +

{group.title}

+ {#each group.names as name (name)} +
{name}
+ {#if group.title === "字号"}字 Aa + {:else if group.title === "圆角与描边"} + {:else if group.title === "图标与间距" || group.title === "控件与外壳"}{/if} + {values[name]} +
+ {/each} +
+ {/each} +
+
+
+

图标 {iconNames.length}

+
+ {#each [16, 20] as size (size)} +
+

{size}px 对齐

+
+ + + + +
+

加粗 下划线

+
+ {/each} +
+
+ {#each iconNames as name (name)} + {@const art = fluentIcons[name]} +
+ {#if art}{/if} + {name}{art ? (art.artwork16 ? "Fluent · 16 / 20px 画稿" : "Fluent · 均用 20px 画稿") : "Codicon"} +
+ {/each} +
+
+
\ No newline at end of file diff --git a/renderer/preview/components/OverlayExample.svelte b/renderer/preview/components/OverlayExample.svelte new file mode 100644 index 0000000..eb84c01 --- /dev/null +++ b/renderer/preview/components/OverlayExample.svelte @@ -0,0 +1,85 @@ + + + + +{#if sample === "选择"} + + +
+ +{:else} + {@const danger = sample === "危险确认"} + report(danger ? "已确认删除" : "已确认保存")} oncancel={() => report("已取消")}> + {#snippet trigger({ props })}{/snippet} + +{/if} \ No newline at end of file diff --git a/renderer/preview/components/ShellExample.svelte b/renderer/preview/components/ShellExample.svelte new file mode 100644 index 0000000..eac5781 --- /dev/null +++ b/renderer/preview/components/ShellExample.svelte @@ -0,0 +1,154 @@ + + +{#snippet palette()} +
pages.map((page, i) => ({ ...page, openedAt: Date.UTC(2026, 10, 20, 6 - i) }))} + {disabled} formatTime={ms => format.format(ms)} onchoose={choose} />
+{/snippet} + +
+ overlay = !overlay} /> + {#if overlay}
{ + if (event.key === "Escape") overlay = false; + }} role="presentation">{@render palette()}
{/if} +
+ + {#if !collapsed} + + expanded = !expanded}> + {#each pages.filter(page => page.title.includes(filter)) as page (page.id)} + choose({ page: page.id, otherGroup: event.ctrlKey })} /> + {/each} + + + width = value} /> + {/if} +
+ {#each groups as owner (owner.id)} + + {/each} +
+
+
+

搜索面板

+
+ {#each [["页面结果", "材料"], ["命令", ">拆分"], ["最近打开", ""]] as [label, value] (label)} + + {/each} +
+{@render palette()} + + \ No newline at end of file diff --git a/renderer/preview/components/StateTable.svelte b/renderer/preview/components/StateTable.svelte new file mode 100644 index 0000000..f82702c --- /dev/null +++ b/renderer/preview/components/StateTable.svelte @@ -0,0 +1,84 @@ + + +
+ + {#each headings as heading (heading)}{/each} + + {#each rows as row (row)} + + + {#each states as state (state)} + {@const disabled = state === "disabled"} + + {/each} + + {/each} + +
组件{heading}
{row} +
+ {#if row === "主要按钮" || row === "次要按钮" || row === "文字按钮"} + + {:else if row === "图标按钮" || row.startsWith("开关")} + + {:else if row.startsWith("输入")} + + {:else if row.startsWith("搜索")} + + {:else if row.startsWith("选择")} +
+
+
+ {#each ["选中", "失焦选中", "拖动经过"] as state (state)} +
{state}
+ {/each} +
\ No newline at end of file diff --git a/renderer/preview/components/catalog.css b/renderer/preview/components/catalog.css new file mode 100644 index 0000000..56c6626 --- /dev/null +++ b/renderer/preview/components/catalog.css @@ -0,0 +1,59 @@ +html, body { width: auto; height: auto; min-height: 100%; overflow: visible; } +body { background: var(--ui-surface-window); color: var(--ui-text); font: var(--ui-font-body)/1.5 var(--ui-font-family); user-select: text; } +.catalog-header, .catalog { max-width: 1480px; margin: auto; padding-inline: clamp(16px, 4vw, 64px); } +.catalog-header { display: flex; align-items: center; justify-content: space-between; gap: 24px; padding-block: 32px 24px; border-bottom: 1px solid var(--ui-divider); } +.catalog-header p { margin: 0 0 6px; color: var(--ui-text-secondary); font-size: var(--ui-font-small); } +.catalog-header h1 { margin: 0; font-size: 28px; font-weight: 600; } +.theme-tools, .theme-choice, .examples { display: flex; align-items: center; gap: var(--ui-space-3); flex-wrap: wrap; } +.theme-tools { gap: 18px; } +.theme-choice { padding: 2px; gap: 2px; border: 1px solid var(--ui-border-input); border-radius: var(--ui-radius-control); } +.catalog { padding-block: 0 40px; } +.catalog > section { margin-top: 28px; } +.catalog h2 { margin: 0 0 12px; font-size: var(--ui-font-title); font-weight: 600; } +.catalog h2 small { font-size: var(--ui-font-body); color: var(--ui-text-secondary); font-weight: 400; } +.catalog h3, figcaption { margin: 0 0 10px; color: var(--ui-text-secondary); font-size: var(--ui-font-body); font-weight: 500; } +.live-grid, .overlay-grid, .metric-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 1px; border: 1px solid var(--ui-divider); background: var(--ui-divider); border-radius: var(--ui-radius-panel); overflow: hidden; } +.live-grid > div, .metric-grid > div { padding: 12px 16px; background: var(--ui-surface-window); } +.fields .ui-field { min-width: 92px; flex: 1; } +.feedback { display: block; min-height: 18px; margin-top: 4px; color: var(--ui-text-secondary); } +.table-scroll { overflow-x: auto; border: 1px solid var(--ui-divider); border-radius: var(--ui-radius-panel); } +.state-table { width: 100%; min-width: 760px; border-spacing: 0; table-layout: fixed; font-size: var(--ui-font-body); } +.state-table th, .state-table td { height: 35px; padding: 4px 12px; border-bottom: 1px solid var(--ui-divider); text-align: start; } +.state-table th { font-weight: 500; } +.state-table thead { background: var(--ui-surface-panel); color: var(--ui-text-secondary); } +.state-table tbody tr:last-child > * { border-bottom: 0; } +.state-table td > div { display: flex; align-items: center; } +.state-table :is(.ui-field, .ui-select) { width: 100%; max-width: 156px; } +.state-table .ui-row { max-width: 156px; } +.row-examples { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); margin-top: 10px; gap: 16px; } +.row-examples > div > span { display: block; margin-bottom: 4px; color: var(--ui-text-secondary); font-size: var(--ui-font-small); } +.overlay-grid { grid-template-columns: repeat(auto-fit, minmax(min(290px, 100%), 1fr)); } +.overlay-grid figure { margin: 0; min-width: 0; background: var(--ui-surface-panel); } +.overlay-grid figcaption { margin: 0; padding: 8px 12px; border-bottom: 1px solid var(--ui-divider); } +.overlay-grid iframe { display: block; width: 100%; height: 182px; border: 0; background: var(--ui-surface-window); } +body.specimen { padding: 12px; } +.popover-example { display: grid; justify-items: start; gap: var(--ui-space-3); } +.swatches, .glyphs { display: grid; grid-template-columns: repeat(auto-fill, minmax(210px, 1fr)); border-top: 1px solid var(--ui-divider); } +.swatches > div, .glyphs > div { display: flex; align-items: center; gap: 10px; min-width: 0; padding: 8px 6px; border-bottom: 1px solid var(--ui-divider); } +.swatches i { flex: none; width: 30px; height: 30px; border: 1px solid var(--ui-border-input); border-radius: var(--ui-radius-control); } +.swatches span, .glyph-label, dt, dd { font-family: ui-monospace, Consolas, monospace; font-size: var(--ui-font-small); } +.swatches small { display: block; margin-top: 3px; color: var(--ui-text-secondary); font-size: var(--ui-font-small); overflow-wrap: anywhere; } +.metric-grid dl { margin: 0; } +.metric-grid dl > div { min-height: 23px; display: flex; align-items: center; justify-content: space-between; gap: 6px; } +.metric-grid dd { display: flex; align-items: center; gap: 8px; margin: 0; color: var(--ui-text-secondary); } +.metric-bar, .metric-shape { display: inline-block; background: var(--ui-accent); } +.metric-bar { height: 4px; } +.metric-shape { width: 12px; height: 12px; } +.icon-comparison { display: flex; flex-wrap: wrap; gap: var(--ui-space-6); margin-bottom: var(--ui-space-5); } +.icon-comparison p { margin: var(--ui-space-3) 0 0; } +.icon-comparison p .icon:not(:first-child) { margin-inline-start: var(--ui-space-3); } +.glyphs { grid-template-columns: repeat(auto-fill, minmax(min(210px, 100%), 1fr)); } +.glyphs > div { min-height: 34px; } +.glyphs small { display: block; color: var(--ui-text-secondary); font-size: var(--ui-font-small); } +@media (max-width: 800px) { + .live-grid, .metric-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .catalog-header { flex-wrap: wrap; } +} +@media (max-width: 510px) { + .live-grid, .metric-grid, .row-examples { grid-template-columns: 1fr; } +} \ No newline at end of file diff --git a/renderer/preview/components/index.html b/renderer/preview/components/index.html new file mode 100644 index 0000000..0babe9a --- /dev/null +++ b/renderer/preview/components/index.html @@ -0,0 +1,12 @@ + + + + + + 基础组件 · 知织 + + +
+ + + \ No newline at end of file diff --git a/renderer/preview/components/main.ts b/renderer/preview/components/main.ts new file mode 100644 index 0000000..74ea495 --- /dev/null +++ b/renderer/preview/components/main.ts @@ -0,0 +1,22 @@ +import { mount } from "svelte"; +import "../../styles/layouts.css"; +import "../../styles/colors.css"; +import "../../styles/base.css"; +import "../../styles/elements.css"; +import "../../styles/workspace.css"; +import "./catalog.css"; +import Catalog from "./Catalog.svelte"; +import OverlayExample, { overlayNames } from "./OverlayExample.svelte"; + +const target = document.querySelector("#catalog")!; +const params = new URLSearchParams(location.search); +const sample = overlayNames.find(name => name === params.get("sample")); +if (sample) { + document.documentElement.dataset.theme = params.get("theme") === "dark" ? "dark" : "light"; + document.documentElement.dataset.motion = params.get("motion") === "off" ? "off" : "on"; + document.body.classList.add("specimen"); + mount(OverlayExample, { target, props: { sample, expanded: true } }); +} +else { + mount(Catalog, { target }); +} \ No newline at end of file diff --git a/renderer/styles/base.css b/renderer/styles/base.css index 7a77d91..28337db 100644 --- a/renderer/styles/base.css +++ b/renderer/styles/base.css @@ -1,10 +1,4 @@ -@font-face { - font-family: "Nunito"; - src: url("../assets/fonts/nunito.ttf") format("truetype"); - font-style: normal; - font-weight: 200 900; - font-display: swap; -} +@import "./ui-tokens.css"; @font-face { font-family: "JetBrains Mono"; @@ -25,11 +19,11 @@ } ::selection { - background-color: var(--c-selection); + background-color: var(--ui-text-selection); } ::-moz-selection { - background-color: var(--c-selection); + background-color: var(--ui-text-selection); } body { @@ -39,7 +33,7 @@ body { color: var(--c-ink); background: var(--c-cream); font-size: var(--font-body); - font-family: "Nunito", "PingFang SC", "Microsoft YaHei", ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI Variable Display", "Segoe UI", Helvetica, "Apple Color Emoji", "Noto Sans Arabic", "Noto Sans Hebrew", Arial, sans-serif, "Segoe UI Emoji", "Segoe UI Symbol"; + font-family: var(--ui-font-family); text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; diff --git a/renderer/styles/colors.css b/renderer/styles/colors.css index ec56a24..84fdbec 100644 --- a/renderer/styles/colors.css +++ b/renderer/styles/colors.css @@ -11,16 +11,10 @@ --c-muted: #776e5d; --c-line: #e3dccb; --c-shadow: 3px 4px 0 var(--c-ink); - --c-selection: #f2cc7880; --c-navbar-background: var(--c-paper); - --c-sidebar-background: var(--c-paper); - --c-tab-header-background: #f2ecdd; --c-tab-header-border: #d6ccb7; - --c-side-panel-background: var(--c-paper); - --c-resizer-background: #c5b58e; /* Editor surfaces */ - --dc-c-selection: #f2cc7880; --dc-c-paragraph-background: /*#f0f8ff*/transparent; --dc-c-code-background: #f3ecd9; --dc-c-drop-cursor: #a7782e; @@ -84,23 +78,14 @@ --c-border-focus: #b38c48; /* Search launcher */ - --c-search-trigger-background: #f8f4e9; - --c-search-trigger-border: #c8bda4; - --c-search-trigger-border-hover: #ab9670; --c-search-trigger-text: #776e5d; /* Search popover */ --c-popover-border: #d4c8af; --c-popover-text: #302c25; - --c-search-divider: #e9e1d0; - --c-search-icon: #806b48; --c-search-placeholder: #928671; - --c-search-heading: #776e5d; --c-search-secondary-text: #776e5d; - --c-search-footer-background: #faf6eb; --c-kbd-border: #d9cfba; - --c-popover-shadow: #302c2530; - --c-popover-shadow-soft: #302c2510; } :root[data-theme="dark"] { @@ -117,7 +102,6 @@ --c-muted: #c0b59f; --c-line: #4a463a; --c-shadow: 3px 4px 0 #14150f; - --c-tab-header-background: #20221c; --c-tab-header-border: #68604c; --c-accent: #e0b96d; --c-surface: var(--c-paper); @@ -129,10 +113,8 @@ --c-reader-input-border: #68604c; --c-reader-muted-text: var(--c-muted); --c-reader-error-text: #f3aa91; - --c-search-trigger-background: var(--c-cream); --c-search-trigger-text: var(--c-muted); --c-popover-text: var(--c-ink); - --c-search-footer-background: var(--c-cream); --c-kbd-border: #68604c; --dc-c-surface: var(--c-paper); --dc-c-surface-hover: #37372b; @@ -143,16 +125,9 @@ --dc-c-code-background: #403b2e; --dc-c-placeholder: #a69a85; - --c-search-trigger-border: #68604c; - --c-search-trigger-border-hover: #a69a85; --c-popover-border: #68604c; - --c-search-divider: #4a463a; - --c-search-icon: #b9ae99; --c-search-placeholder: #a69a85; - --c-search-heading: #b9ae99; --c-search-secondary-text: #b9ae99; - --c-selection: #b38b4980; - --dc-c-selection: #b38b4980; --dc-c-accent: #e0b96d; --dc-c-popover-border: #68604c; --dc-c-drop-cursor: #e0b96d; diff --git a/renderer/styles/elements.css b/renderer/styles/elements.css index e6c4e94..26f94e0 100644 --- a/renderer/styles/elements.css +++ b/renderer/styles/elements.css @@ -14,7 +14,7 @@ button { } .tiptap::selection, .tiptap *::selection { - background-color: var(--dc-c-selection); + background-color: var(--ui-text-selection); } .dc-paragraph { diff --git a/renderer/styles/layouts.css b/renderer/styles/layouts.css index 3bf00e2..ff29f62 100644 --- a/renderer/styles/layouts.css +++ b/renderer/styles/layouts.css @@ -1,8 +1,6 @@ :root { --editor-min-height: 180px; --annotation-min-height: 150px; - --titlebar-height: 32px; - --tabbar-height: 35px; --pagebar-height: 28px; --library-toolbar-height: 32px; --library-row-height: 28px; @@ -10,11 +8,7 @@ --menu-row-height: 26px; --property-row-height: 26px; --button-height: 24px; - --activity-width: 48px; - --panel-indent: 8px; --property-label-width: 88px; - --logo-size: 20px; - --search-width: 480px; --control-radius: 4px; --font-body: 13px; --font-secondary: 12px; diff --git a/renderer/styles/ui-tokens.css b/renderer/styles/ui-tokens.css new file mode 100644 index 0000000..4668516 --- /dev/null +++ b/renderer/styles/ui-tokens.css @@ -0,0 +1,137 @@ +/* VS Code Light Modern / Dark Modern. Only the palette contains literal colors. */ +:root { + --ui-p-canvas: #ffffff; + --ui-p-neutral-1: #f8f8f8; + --ui-p-hover: #f2f2f2; + --ui-p-list-selection: #e8e8e8; + --ui-p-neutral-4: #e5e5e5; + --ui-p-neutral-5: #cecece; + --ui-p-neutral-6: #767676; + --ui-p-neutral-7: #616161; + --ui-p-neutral-8: #3b3b3b; + --ui-p-neutral-9: #000000; + --ui-p-field: #ffffff; + --ui-p-check-gray: #cecece; + --ui-p-check-hover-gray: #3b3b3b; + --ui-p-list-selection-inactive: #e5ebf1; + --ui-p-match-blue: #0066bf; + --ui-p-selection-blue: #add6ff; + --ui-p-blue: #005fb8; + --ui-p-blue-hover: #0258a8; + --ui-p-red: #c72e0f; + --ui-p-red-hover: #a4260d; + --ui-p-white: #ffffff; + --ui-p-shadow: #0003; + --ui-p-scrim: #0005; + --ui-p-clear: transparent; +} + +:root[data-theme="dark"] { + --ui-p-canvas: #1f1f1f; + --ui-p-neutral-1: #181818; + --ui-p-hover: #2a2d2e; + --ui-p-list-selection: #04395e; + --ui-p-neutral-4: #2b2b2b; + --ui-p-neutral-5: #3c3c3c; + --ui-p-neutral-6: #989898; + --ui-p-neutral-7: #9d9d9d; + --ui-p-neutral-8: #cccccc; + --ui-p-neutral-9: #ffffff; + --ui-p-field: #313131; + --ui-p-check-gray: #989898; + --ui-p-check-hover-gray: #cccccc; + --ui-p-list-selection-inactive: #37373d; + --ui-p-match-blue: #2aaaff; + --ui-p-selection-blue: #264f78; + --ui-p-blue: #0078d4; + --ui-p-blue-hover: #026ec1; + --ui-p-red: #b63426; + --ui-p-red-hover: #c53b2d; + --ui-p-shadow: #0009; + --ui-p-scrim: #0008; +} + +:root { + --ui-surface-window: var(--ui-p-canvas); + --ui-surface-panel: var(--ui-p-neutral-1); + --ui-surface-popup: var(--ui-p-canvas); + --ui-surface-input: var(--ui-p-field); + --ui-surface-clear: var(--ui-p-clear); + --ui-surface-scrim: var(--ui-p-scrim); + --ui-text: var(--ui-p-neutral-8); + --ui-text-secondary: var(--ui-p-neutral-7); + --ui-text-disabled: var(--ui-p-neutral-6); + --ui-text-placeholder: var(--ui-p-neutral-6); + --ui-text-on-accent: var(--ui-p-white); + --ui-text-selected: var(--ui-p-neutral-9); + --ui-border: var(--ui-p-neutral-4); + --ui-border-input: var(--ui-p-neutral-5); + --ui-border-check: var(--ui-p-check-gray); + --ui-border-check-hover: var(--ui-p-check-hover-gray); + --ui-divider: var(--ui-p-neutral-4); + --ui-hover: var(--ui-p-hover); + --ui-pressed: var(--ui-p-neutral-5); + --ui-text-selection: var(--ui-p-selection-blue); + --ui-selected: var(--ui-p-list-selection); + --ui-selected-inactive: var(--ui-p-list-selection-inactive); + --ui-text-match: var(--ui-p-match-blue); + --ui-titlebar-background: var(--ui-surface-panel); + --ui-titlebar-foreground: var(--ui-text); + --ui-focus: var(--ui-p-blue); + --ui-accent: var(--ui-p-blue); + --ui-accent-hover: var(--ui-p-blue-hover); + --ui-danger: var(--ui-p-red); + --ui-danger-hover: var(--ui-p-red-hover); + --ui-shadow-popup: 0 2px 8px var(--ui-p-shadow); + --ui-shadow-dialog: 0 8px 32px var(--ui-p-shadow); + + --ui-font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", sans-serif; + --ui-font-small: 12px; + --ui-font-body: 14px; + --ui-font-title: 20px; + --ui-titlebar-height: 32px; + --ui-activity-width: 48px; + --ui-activity-item-height: 48px; + --ui-tabbar-height: 35px; + --ui-search-width: 600px; + --ui-search-list-height: 360px; + --ui-tab-min-width: 80px; + --ui-tab-max-width: 210px; + --ui-empty-logo-size: 80px; + --ui-sash-size: 4px; + --ui-sash-delay: 300ms; + --ui-active-border: 2px; + --ui-toolbar-height: 32px; + --ui-row-height: 24px; + --ui-button-height: 26px; + --ui-input-height: 26px; + --ui-icon-small: 12px; + --ui-icon-normal: 16px; + --ui-icon-large: 20px; + --ui-space-1: 2px; + --ui-space-2: 4px; + --ui-space-3: 8px; + --ui-space-4: 12px; + --ui-space-5: 16px; + --ui-space-6: 24px; + --ui-radius-small: 2px; + --ui-radius-control: 4px; + --ui-radius-panel: 6px; + --ui-stroke: 1px; + --ui-focus-width: 1px; + --ui-focus-offset: 1px; + + /* All portalled to the document body, in ascending paint order. */ + --ui-z-dropdown: 100; + --ui-z-popover: 200; + --ui-z-tooltip: 300; + --ui-z-dialog: 400; + --ui-z-context-menu: 500; + --ui-duration-fast: 90ms; + --ui-duration-normal: 150ms; +} + +:root[data-motion="off"] { + --ui-duration-fast: 0ms; + --ui-duration-normal: 0ms; +} \ No newline at end of file diff --git a/shared/app/ipc.ts b/shared/app/ipc.ts index 64ec181..0fe3f9c 100644 --- a/shared/app/ipc.ts +++ b/shared/app/ipc.ts @@ -1,5 +1,6 @@ export type AppCommands = { openDevTools(): void; + setFrameColors(color: string, symbolColor: string): void; editorStarted(): void; beforeQuit(check: () => Promise | boolean): () => void; }; @@ -8,6 +9,7 @@ export type AppMessages = Omit & { }; export const appChannels = { openDevTools: "app:open-devtools", + setFrameColors: "app:set-frame-colors", editorStarted: "app:editor-started", beforeQuitResult: "app:before-quit-result" } as const satisfies Record; diff --git a/shared/attrs/builtins.ts b/shared/attrs/builtins.ts index 9b8e1a6..a1ddeca 100644 --- a/shared/attrs/builtins.ts +++ b/shared/attrs/builtins.ts @@ -61,6 +61,8 @@ export function isBuiltin(id: string): id is BuiltinAttrId { // Presentation overrides stay outside the serializable attribute definitions. export const builtinValueFormats: Partial> = { + created_at: { search: () => "" }, + modified_at: { search: () => "" }, recycle_reason: { search: () => "" }, recycled_at: { search: () => "" }, ...Object.fromEntries(["annotation_file", "annotation_position", "annotation_context", "annotation_extractor", "feed_last_refreshed", "feed_last_checked", "feed_last_added", "feed_error", "feed_failures", "feed_etag", "feed_last_modified"].map(id => [id, { search: () => "" }])) diff --git a/shared/content/commands.ts b/shared/content/commands.ts index 6fee031..6fabcee 100644 --- a/shared/content/commands.ts +++ b/shared/content/commands.ts @@ -1,25 +1,26 @@ export const commands = { - newPage: { label: "新建页面", shortcut: "Ctrl+N" }, importPDF: { label: "导入 PDF", shortcut: "" }, - closeTab: { label: "关闭标签", shortcut: "Ctrl+W" }, settings: { label: "偏好设置", shortcut: "Ctrl+," }, - undo: { label: "撤销", shortcut: "Ctrl+Z" }, redo: { label: "重做", shortcut: "Ctrl+Y" }, - cut: { label: "剪切", shortcut: "Ctrl+X" }, copy: { label: "复制", shortcut: "Ctrl+C" }, - paste: { label: "粘贴", shortcut: "Ctrl+V" }, selectAll: { label: "全选", shortcut: "Ctrl+A" }, - sidebar: { label: "切换左侧面板", shortcut: "Ctrl+Alt+B" }, splitRight: { label: "向右拆分", shortcut: "Ctrl+\\" }, - splitDown: { label: "向下拆分", shortcut: "" }, overview: { label: "总览", shortcut: "" }, - feed: { label: "订阅", shortcut: "" }, library: { label: "知识库", shortcut: "" }, papers: { label: "文献库", shortcut: "" }, - calendar: { label: "日历", shortcut: "" }, attributes: { label: "属性管理", shortcut: "" }, search: { label: "搜索", shortcut: "Ctrl+P" }, - nextTab: { label: "下一个标签", shortcut: "Ctrl+Tab" }, previousTab: { label: "上一个标签", shortcut: "Ctrl+Shift+Tab" }, - group1: { label: "聚焦第1标签组", shortcut: "Ctrl+1" }, group2: { label: "聚焦第2标签组", shortcut: "Ctrl+2" }, group3: { label: "聚焦第3标签组", shortcut: "Ctrl+3" }, - about: { label: "关于知织", shortcut: "" }, devtools: { label: "开发者工具", shortcut: "F12" } + newPage: { shortcut: "Ctrl+N" }, importPDF: { shortcut: "" }, + closeTab: { shortcut: "Ctrl+W" }, settings: { shortcut: "Ctrl+," }, + undo: { shortcut: "Ctrl+Z" }, redo: { shortcut: "Ctrl+Y" }, + cut: { shortcut: "Ctrl+X" }, copy: { shortcut: "Ctrl+C" }, + paste: { shortcut: "Ctrl+V" }, selectAll: { shortcut: "Ctrl+A" }, + sidebar: { shortcut: "Ctrl+Alt+B" }, splitRight: { shortcut: "Ctrl+\\" }, + mergeGroup: { shortcut: "" }, commandPalette: { shortcut: "Ctrl+Shift+P" }, + splitDown: { shortcut: "" }, overview: { shortcut: "" }, + feed: { shortcut: "" }, library: { shortcut: "" }, papers: { shortcut: "" }, + calendar: { shortcut: "" }, attributes: { shortcut: "" }, search: { shortcut: "Ctrl+P" }, + nextTab: { shortcut: "Ctrl+Tab" }, previousTab: { shortcut: "Ctrl+Shift+Tab" }, + group1: { shortcut: "Ctrl+1" }, group2: { shortcut: "Ctrl+2" }, group3: { shortcut: "Ctrl+3" }, + about: { shortcut: "" }, devtools: { shortcut: "F12" } } as const; export type Command = keyof typeof commands; -export const menus: { label: string; items: Command[] }[] = [ - { label: "文件", items: ["newPage", "importPDF", "closeTab", "settings"] }, - { label: "编辑", items: ["undo", "redo", "cut", "copy", "paste", "selectAll"] }, - { label: "视图", items: ["sidebar", "splitRight", "splitDown"] }, - { label: "前往", items: ["overview", "feed", "library", "papers", "calendar", "attributes", "search", "nextTab", "previousTab"] }, - { label: "帮助", items: ["about", "devtools"] } -]; +export const menus = [ + { id: "file", items: ["newPage", "importPDF", "closeTab", "settings"] }, + { id: "edit", items: ["undo", "redo", "cut", "copy", "paste", "selectAll"] }, + { id: "view", items: ["sidebar", "splitRight", "splitDown", "mergeGroup", "commandPalette"] }, + { id: "go", items: ["overview", "feed", "library", "papers", "calendar", "attributes", "search", "nextTab", "previousTab"] }, + { id: "help", items: ["about", "devtools"] } +] as const satisfies ReadonlyArray<{ id: string; items: readonly Command[] }>; export function shortcutCommand(event: Pick): Command | undefined { if (event.isComposing || event.defaultPrevented || event.key === "Process" || event.metaKey) return; const chord = `${event.ctrlKey ? "Ctrl+" : ""}${event.altKey ? "Alt+" : ""}${event.shiftKey ? "Shift+" : ""}${event.key.length === 1 ? event.key.toUpperCase() : event.key}`; diff --git a/shared/content/matches.ts b/shared/content/matches.ts new file mode 100644 index 0000000..d051ec3 --- /dev/null +++ b/shared/content/matches.ts @@ -0,0 +1,25 @@ +// Lowercasing can expand a character (e.g. İ). Keep positions in the original text. +export function* matchRanges(text: string, keyword: string): Generator<[number, number]> { + const folded = text.toLocaleLowerCase(), needle = keyword.toLocaleLowerCase(); + if (!needle) return; + let index = folded.indexOf(needle); + if (index < 0) return; + const original: number[] = []; + if (folded.length !== text.length) { + let offset = 0; + for (const character of text) { + const length = character.toLocaleLowerCase().length; + for (let i = 0; i < length; i++) original.push(offset); + offset += character.length; + } + } + while (index >= 0) { + const end = index + needle.length; + if (original.length) { + const last = original[end - 1]; + yield [original[index], last + (text.codePointAt(last)! > 0xffff ? 2 : 1)]; + } + else yield [index, end]; + index = folded.indexOf(needle, end); + } +} \ No newline at end of file diff --git a/shared/pages/ipc.ts b/shared/pages/ipc.ts index c340003..edfc422 100644 --- a/shared/pages/ipc.ts +++ b/shared/pages/ipc.ts @@ -1,12 +1,13 @@ import type { HistorySource } from "../history/ipc"; import type { AttributeValue } from "../types/attributes"; -import type { Backlink, CommitResult, BlockDeletion, ChangePreview, ContentBlock, EditCommit, KnowledgeChange, Placement, ResolvedTarget, PageList, PageQuery, PageRecord, PageObjects, Target } from "../types/content"; +import { type Backlink, type CommitResult, type BlockDeletion, type ChangePreview, type ContentBlock, type EditCommit, type KnowledgeChange, type Placement, type ResolvedTarget, type PageList, type PageQuery, type PageRecord, type PageObjects, type PageSearchResult, type Target } from "../types/content"; import type { PurgeResult } from "../types/knowledge"; import { type Channels } from "../ipc/contract"; import type { tags } from "typia"; export type PagesAPI = { list(query?: PageQuery): Promise; + search(keyword: string, offset?: number, limit?: number): Promise<{ items: PageSearchResult[]; total: number }>; listUpdates(query: PageQuery, unchanged: string[]): Promise; get(id: string): Promise; readObjects(pageId: string, ids: string[]): Promise; @@ -27,6 +28,7 @@ export type PagesAPI = { export const pagesChannels = { list: "pages:list", + search: "pages:search", listUpdates: "pages:list-updates", get: "pages:get", readObjects: "pages:read-objects", diff --git a/shared/settings/workspace.ts b/shared/settings/workspace.ts index 8756d44..d09fd0b 100644 --- a/shared/settings/workspace.ts +++ b/shared/settings/workspace.ts @@ -1,5 +1,9 @@ import { LabloomError } from "../failure"; -export type WorkspaceSettings = { tabs: unknown | null; feedKeywords: string[] }; +export type RecentPage = { id: string; openedAt: number }; +export type WorkspaceNavigation = { expandedGroups: string[]; recentPages: RecentPage[] }; +export const defaultExpandedGroups = ["pinned", "independent"]; +export const recentPageLimit = 50; +export type WorkspaceSettings = { tabs: unknown | null; feedKeywords: string[] } & Partial; export type WorkspaceSettingsPatch = Partial; export function normalizeKeywords(value: unknown): string[] { if (!Array.isArray(value) || value.some(word => typeof word !== "string")) throw new LabloomError({ kind: "feed-invalid-keywords" }); diff --git a/shared/types/content.ts b/shared/types/content.ts index ee413a8..72dfb03 100644 --- a/shared/types/content.ts +++ b/shared/types/content.ts @@ -26,6 +26,8 @@ export type PageSummary = { excerpt: string; attributes: Record; }; +export type PageMatch = { field: "title" } | { field: "body"; snippet: string } | { field: "attribute"; id: string; name: string; snippet: string }; +export type PageSearchResult = PageSummary & { match: PageMatch }; export type PageRecord = PageSummary & { titleBlockId: string; sharedUses?: Record; diff --git a/shared/workspace/ipc.ts b/shared/workspace/ipc.ts index 359c617..1945b18 100644 --- a/shared/workspace/ipc.ts +++ b/shared/workspace/ipc.ts @@ -1,12 +1,15 @@ import type { SavedTabs } from "../workspace/tabs"; +import { type WorkspaceNavigation } from "../settings/workspace"; import type { Channels } from "../ipc/contract"; export type WorkspaceAPI = { loadTabs(): Promise; - saveTabs(value: SavedTabs): Promise; + loadNavigation(): Promise; + saveTabs(value: SavedTabs, navigation?: WorkspaceNavigation): Promise; }; export const workspaceChannels = { loadTabs: "workspace:load-tabs", + loadNavigation: "workspace:load-navigation", saveTabs: "workspace:save-tabs" } as const satisfies Channels; \ No newline at end of file diff --git a/tests/appearance.test.ts b/tests/appearance.test.ts index 1efd097..4b52af9 100644 --- a/tests/appearance.test.ts +++ b/tests/appearance.test.ts @@ -17,6 +17,7 @@ import * as commit from "../main/knowledge/commit"; import * as events from "../main/knowledge/events"; import { defaultSettings, minWindowHeight, minWindowWidth } from "../shared/settings/defaults"; import { dayToSeconds } from "../shared/content/time"; +import { randomUUID } from "node:crypto"; import { hasFailure } from "./failures"; function folder(): string { @@ -254,4 +255,22 @@ test("workspace keywords are read only from feedKeywords", t => { assert.deepEqual(workspaceSettings.get().feedKeywords, expected); } assert.equal(warnings.mock.callCount(), 1); +}); + +test("workspace navigation restores expanded groups and the last fifty distinct page visits", t => { + const opened = session.open(folder(), "create"); + t.after(() => session.close()); + assert.deepEqual(workspaceSettings.loadNavigation(), { expandedGroups: ["pinned", "independent"], recentPages: [] }); + const tabs = { groups: [], focusedGroupId: "A", layout: { type: "group" as const, groupId: "A" } }; + const entries = Array.from({ length: 55 }, (_, i) => ({ id: randomUUID(), openedAt: i })); + workspaceSettings.saveTabs(tabs, { expandedGroups: ["tag:A"], recentPages: [...entries, { ...entries[1], openedAt: Number.MAX_SAFE_INTEGER }, { ...entries[0], openedAt: 99 }] }); + workspaceSettings.update({ feedKeywords: ["A"] }); + session.close(); session.open(opened.info.path, "open"); + const navigation = workspaceSettings.loadNavigation(); + assert.deepEqual(navigation.expandedGroups, ["tag:A"]); + assert.deepEqual(navigation.recentPages.map(entry => entry.id), [entries[0], ...entries.slice(-49).reverse()].map(entry => entry.id)); + assert.equal(navigation.recentPages[0].openedAt, 99); + workspaceSettings.saveTabs(tabs, { ...navigation, expandedGroups: [] }); + session.close(); session.open(opened.info.path, "open"); + assert.deepEqual(workspaceSettings.loadNavigation().expandedGroups, []); }); \ No newline at end of file diff --git a/tests/content.test.ts b/tests/content.test.ts index a6d7e70..a391450 100644 --- a/tests/content.test.ts +++ b/tests/content.test.ts @@ -12,6 +12,7 @@ import { fingerprint } from "../main/knowledge/attributes"; import * as settings from "../main/settings/store"; import { builtinAttrs, builtinAttrsByPageKind } from "../shared/attrs/builtins"; 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"; @@ -352,19 +353,57 @@ test("keywords and display use the current application timezone on the same open const seconds = 1794071576; service.attributes.write(e.id, { created_at: seconds, modified_at: seconds + 3600, schedule_start: seconds + 7200 }, true); service.attributes.write(a.id, { created_at: 0, modified_at: 0 }, true); - const created = (): string => display({ id: "created_at", ...builtinAttrs.created_at }, service.get(e.id).attributes.created_at, { zone: settings.get().settings.appearance.timeZone }); - assert.equal(created(), "2026-11-08 01:12"); - for (const keyword of ["tags", "true", "modified", anchor, "1794", "17:12", "未开始", "asia"]) assert.equal(service.list({ keyword }).total, 0, keyword); - for (const keyword of ["2026", "01:12", "02:12", "03:12"]) assert.deepEqual(service.list({ keyword }).items.map(p => p.id), [e.id], keyword); + const timestamp = (id: "created_at" | "modified_at"): string => display({ id, ...builtinAttrs[id] }, service.get(e.id).attributes[id], { zone: settings.get().settings.appearance.timeZone }); + assert.equal(timestamp("created_at"), "2026-11-08 01:12"); + assert.equal(timestamp("modified_at"), "2026-11-08 02:12"); + for (const keyword of ["tags", "true", "modified", anchor, "1794", "01:12", "02:12", "17:12", "未开始", "asia"]) assert.equal(service.list({ keyword }).total, 0, keyword); + for (const keyword of ["2026", "03:12"]) assert.deepEqual(service.list({ keyword }).items.map(p => p.id), [e.id], keyword); settings.update({ appearance: { timeZone: "UTC" } }); - assert.equal(created(), "2026-11-07 17:12"); - assert.deepEqual(service.list({ keyword: "17:12" }).items.map(p => p.id), [e.id]); - assert.equal(service.list({ keyword: "01:12" }).total, 0); + assert.equal(timestamp("created_at"), "2026-11-07 17:12"); + assert.equal(timestamp("modified_at"), "2026-11-07 18:12"); + for (const keyword of ["17:12", "18:12", "03:12"]) { + assert.equal(service.list({ keyword }).total, 0, keyword); + assert.equal(service.searchPages(keyword).total, 0, keyword); + } + assert.deepEqual(service.searchPages("19:12").items[0].match, { field: "attribute", id: "schedule_start", name: "开始时间", snippet: "2026-11-07 19:12" }); + + const experimentDay = "custom:" + randomUUID(); + service.setDefinition(experimentDay, { id: experimentDay, name: "实验日期", type: "day", metadata: {} }); + service.attributes.write(a.id, { [experimentDay]: dayToSeconds("2026-11-20") }); + assert.deepEqual(service.list({ keyword: "2026-11-20" }).items.map(page => page.id), [a.id]); + assert.deepEqual(service.searchPages("2026-11-20").items[0].match, { field: "attribute", id: experimentDay, name: "实验日期", snippet: "2026-11-20" }); const tag = randomUUID(), definition = service.attributes.definition("tags"); service.setDefinition("tags", { ...definition, metadata: { ...definition.metadata, options: [{ id: tag, name: "Research" }] } }, randomUUID()); service.commitEdit({ pageId: e.id, batch: 1, blocks: [], attributes: { tags: [tag] } }, pageHistory(e.id)); assert.equal(service.list({ keyword: tag }).total, 0); assert.equal(service.list({ keyword: "research" }).total, 1); + assert.deepEqual(service.searchPages("research").items[0].match, { field: "attribute", id: "tags", name: "标签", snippet: "Research" }); const dt = service.statement("SELECT typeof(value) FROM page_attrs WHERE page_id=? AND attr_id=?").pluck(); for (const id of ["created_at", "modified_at", "schedule_start"]) assert.equal(dt.get(e.id, id), "integer"); +}); + +test("quick open ranks titles, follows the first shared match and pages through live results", t => { + const { service } = fixture(t); + const a = service.create("editable", "A Signal"), b = service.create("editable", "B"), c = service.create("paper", "C"); + const d = service.create("editable", "D"), removed = service.create("editable", "Deleted Signal"); + const block = text(b.blocks[b.children[0]], "No match in the opening paragraph"); + const nested = { id: randomUUID(), type: "paragraph" as const, children: [], payload: payload("paragraph", "前".repeat(80) + "SiGnAl" + "后".repeat(80)) }; + const later = { ...nested, id: randomUUID(), payload: payload("paragraph", "later signal") }; + block.children = [nested.id, later.id]; + assert.equal(edit(service, b, [block, nested, later]).status, "saved"); + assert.equal(edit(service, a, [], [nested.id]).status, "saved"); + assert.equal(edit(service, d, [], [block.id]).status, "saved"); + service.attributes.write(c.id, { paper_authors: "Author SIGNAL" }); + service.attributes.write(removed.id, { deleted: true }, true); + for (const [index, page] of [a, b, c, d].entries()) service.attributes.write(page.id, { modified_at: index + 1 }, true); + const first = service.searchPages(" signal ", 0, 2), next = service.searchPages("SIGNAL", 2, 2); + assert.equal(first.total, 4); + assert.deepEqual([...first.items, ...next.items].map(page => page.id), [a.id, d.id, c.id, b.id]); + assert.deepEqual(first.items[0].match, { field: "title" }); + const body = { field: "body", snippet: "…" + "前".repeat(36) + "SiGnAl" + "后".repeat(36) + "…" }; + assert.deepEqual(first.items[1].match, body); + assert.deepEqual(next.items[1].match, body); + assert.deepEqual(next.items[0].match, { field: "attribute", id: "paper_authors", name: "作者", snippet: "Author SIGNAL" }); + assert.deepEqual(service.searchPages("signal", 4), { items: [], total: 4 }); + assert.deepEqual(service.list({ keyword: "signal" }).items.map(page => page.id), [d.id, c.id, b.id, a.id]); }); \ No newline at end of file diff --git a/tests/perf/bench.ts b/tests/perf/bench.ts index 962f431..ace2c00 100644 --- a/tests/perf/bench.ts +++ b/tests/perf/bench.ts @@ -63,7 +63,8 @@ function workspaceScale(): void { measure("A | read ordinary page", 10, () => () => assert.equal(service.get(target).children.length, 9)); measure("A | first page of list", 20, () => () => assert.equal(service.list({ limit: 30 }).items.length, 30)); measure("A | keyword, 100 matching pages", 1000, () => () => { - const result = service.list({ keyword: "quasar", limit: 30 }); + const result = service.searchPages("quasar", 0, 30); + assert.ok(result.items.every(page => page.match.field === "body" && page.match.snippet === "quasar")); assert.equal(result.items.length, 30); assert.equal(result.total, 100); }); diff --git a/tests/purge.test.ts b/tests/purge.test.ts index e8dc7e7..d1457ab 100644 --- a/tests/purge.test.ts +++ b/tests/purge.test.ts @@ -11,7 +11,8 @@ import { payload } from "../shared/content/blocks"; import { PDF_EXTRACTOR_VERSION } from "../shared/content/pdf-text"; import type { CommitResult } from "../shared/types/content"; import { knownCoordinatePdf } from "./fixtures/pdf-text"; -import { commands, menus, shortcutCommand } from "../shared/content/commands"; +import { createI18n } from "../shared/i18n"; +import { commands, menus, shortcutCommand, type Command } from "../shared/content/commands"; function fixture(t: TestContext): ReturnType & { service: Knowledge; history: History; papers: Papers; purge: Purge } { const ws = createWorkspace(mkdtempSync(join(process.env.LABLOOM_TEST_ROOT!, "purge-"))); @@ -223,6 +224,10 @@ test("menus and shortcut dispatch use the same table, respect editor handling an assert.equal(shortcutCommand(event("b")), undefined); assert.equal(shortcutCommand(event("n", { defaultPrevented: true })), undefined); assert.equal(shortcutCommand(event("n", { isComposing: true })), undefined); - assert.deepEqual(new Set(menus.map(menu => menu.label)), new Set(["文件", "编辑", "视图", "前往", "帮助"])); - assert.ok(menus.flatMap(menu => menu.items).includes("attributes")); + const zh = createI18n("zh-CN"), en = createI18n("en"); + assert.deepEqual(menus.map(menu => zh.t(`menu.${menu.id}`)), ["文件", "编辑", "视图", "前往", "帮助"]); + assert.deepEqual(menus.map(menu => en.t(`menu.${menu.id}`)), ["File", "Edit", "View", "Go", "Help"]); + const items = menus.flatMap(menu => [...menu.items]); + for (const id of ["attributes", "mergeGroup", "commandPalette"] as const) assert.ok(items.includes(id)); + for (const id of items) for (const language of ["zh-CN", "en"]) assert.ok(en.getResource(language, "translation", `command.${id}`)); }); \ No newline at end of file diff --git a/tests/time-precision.test.ts b/tests/time-precision.test.ts index ae9ba3e..e6b0e3b 100644 --- a/tests/time-precision.test.ts +++ b/tests/time-precision.test.ts @@ -152,12 +152,10 @@ test("definition preview and commit share conversion, invalidate undo, and refre }); test("calendar search and grouping stay on the same day after changing zones and reopening", t => { - const { service, database, info, setZone } = fixture(t); + const { service, info, setZone } = fixture(t); const day = dayToSeconds("2026-11-11"); const event = service.create("editable", "A", { schedule_date: day }); const task = service.create("editable", "B", { schedule_date: day, schedule_start: instant }); - // Keep system timestamps from also matching the date keyword under test. - database.prepare("UPDATE page_attrs SET value=? WHERE attr_id IN ('created_at','modified_at')").run(yearToSeconds("2000")); for (const timeZone of [zone, "UTC", "America/New_York"]) { setZone(timeZone); assert.deepEqual(new Set(service.list({ keyword: "2026-11" }).items.map(p => p.id)), new Set([event.id, task.id]));