diff --git a/locales/en.json b/locales/en.json index 22f509d..a715224 100644 --- a/locales/en.json +++ b/locales/en.json @@ -432,14 +432,37 @@ "devtools": "Developer Tools", "showNotices": "Show notifications", "blockMenu": "Block menu", - "toggleProperties": "Toggle properties panel" + "toggleProperties": "Toggle properties panel", + "reopenTab": "Reopen Closed Tab", + "keybindings": "Keyboard Shortcuts", + "quit": "Quit", + "find": "Find", + "link": "Link", + "fullscreen": "Toggle Full Screen", + "back": "Go Back", + "forward": "Go Forward", + "closeOtherTabs": "Close Other Tabs", + "closeTabsRight": "Close Tabs to the Right", + "closeAllTabs": "Close All Tabs", + "reapplyForeground": "Reapply Text Color", + "reapplyBackground": "Reapply Background Color", + "convertBlock": "Convert to {{block}}" }, "menu": { "file": "File", "edit": "Edit", "view": "View", "go": "Go", - "help": "Help" + "help": "Help", + "format": "Format", + "window": "Window", + "services": "Services", + "hide": "Hide {{app}}", + "hideOthers": "Hide Others", + "unhide": "Show All", + "minimize": "Minimize", + "zoom": "Zoom", + "front": "Bring All to Front" }, "insertReference": { "inline": "Inline reference", @@ -535,7 +558,9 @@ "fgColor": "Text color", "bgColor": "Background color", "mixed": "Mixed", - "custom": "Custom" + "custom": "Custom", + "linkAddress": "Link Address", + "invalidLink": "Enter an http:// or https:// URL." }, "shell": { "mainNavigation": "Primary Navigation", @@ -952,5 +977,83 @@ "files": "Files", "recurrence": "Repeat", "json": "JSON" + }, + "keybindings": { + "waiting": "Pressed {{keys}}, waiting for the next key", + "search": "Search keyboard shortcuts", + "recordSearch": "Search by Keys", + "menu": "More Actions", + "command": "Command", + "keys": "Keybinding", + "source": "Source", + "defaults": "Default", + "user": "User", + "conflict": "Conflict", + "fixed": "Fixed Keys", + "editor": "Editor", + "table": "Table", + "calendar": "Calendar", + "feed": "Feeds", + "reader": "Reader", + "annotations": "Annotations", + "imageViewer": "Image Viewer", + "combobox": "Combobox", + "attributes": "Manage Attributes", + "settings": "Settings", + "datePicker": "Date Picker", + "clockInput": "Time Input", + "tabs": "Tabs", + "textEditing": "Text Editing", + "edit": "Change Keybinding", + "add": "Add Keybinding", + "remove": "Remove Keybinding", + "reset": "Reset to Default", + "resetAll": "Reset All to Default", + "resetBody": "Reset all keyboard shortcuts for this platform?", + "record": "Record Keybinding", + "firstStep": "The first key needs a modifier or a function key.", + "fixedEdit": "This is a fixed text editing shortcut.", + "equal": "Already used by {{command}}.", + "prefix": "Starts a keybinding for {{command}}.", + "startsWith": "Starts with a keybinding for {{command}}.", + "fixedUse": "Has a fixed use in {{area}}.", + "replace": "Replace", + "replaceBody": "These commands will lose a keybinding:", + "action": { + "navigation": "Move between items", + "movement": "Move or indent blocks", + "selection": "Select items", + "open": "Open", + "openSide": "Open to the side", + "context": "Open context menu", + "remove": "Delete", + "apply": "Confirm", + "cancel": "Cancel or clear selection", + "collapse": "Collapse or expand", + "switchPage": "Previous or next page", + "editTitle": "Edit title", + "pin": "Pin", + "restore": "Restore", + "cell": "Move between cells", + "today": "Go to today", + "zoom": "Zoom in or out", + "search": "Focus reader search", + "edit": "Edit", + "fold": "Fold or unfold block", + "language": "Select code language", + "colors": "Open color picker", + "toolbar": "Focus format toolbar", + "lineBreak": "Insert line break", + "webLink": "Follow link while clicking" + }, + "clear": "Clear", + "save": "Save" + }, + "pageFind": { + "query": "Find in Page", + "count": "{{current}} / {{total}}", + "previous": "Previous Match", + "next": "Next Match", + "close": "Close Find" } } \ No newline at end of file diff --git a/locales/zh-CN.json b/locales/zh-CN.json index 907b221..8717b6e 100644 --- a/locales/zh-CN.json +++ b/locales/zh-CN.json @@ -432,14 +432,37 @@ "devtools": "开发者工具", "showNotices": "显示通知", "blockMenu": "块菜单", - "toggleProperties": "切换属性面板" + "toggleProperties": "切换属性面板", + "reopenTab": "重新打开关闭的标签", + "keybindings": "键盘快捷方式", + "quit": "退出", + "find": "查找", + "link": "链接", + "fullscreen": "切换全屏", + "back": "后退", + "forward": "前进", + "closeOtherTabs": "关闭其他标签", + "closeTabsRight": "关闭右侧标签", + "closeAllTabs": "关闭全部标签", + "reapplyForeground": "重用文字颜色", + "reapplyBackground": "重用背景颜色", + "convertBlock": "转换为{{block}}" }, "menu": { "file": "文件", "edit": "编辑", "view": "视图", "go": "前往", - "help": "帮助" + "help": "帮助", + "format": "格式", + "window": "窗口", + "services": "服务", + "hide": "隐藏{{app}}", + "hideOthers": "隐藏其他", + "unhide": "全部显示", + "minimize": "最小化", + "zoom": "缩放窗口", + "front": "将全部窗口移到前面" }, "insertReference": { "inline": "行内引用", @@ -535,7 +558,9 @@ "fgColor": "文字颜色", "bgColor": "背景颜色", "mixed": "混合", - "custom": "自定义" + "custom": "自定义", + "linkAddress": "网址", + "invalidLink": "请输入以 http:// 或 https:// 开头的网址。" }, "shell": { "mainNavigation": "主导航", @@ -952,5 +977,83 @@ "files": "多个文件", "recurrence": "重复", "json": "JSON" + }, + "keybindings": { + "waiting": "已按下{{keys}},等待下一个键", + "search": "搜索键盘快捷方式", + "recordSearch": "按键搜索", + "menu": "更多操作", + "command": "命令", + "keys": "快捷键", + "source": "来源", + "defaults": "默认", + "user": "用户", + "conflict": "冲突", + "fixed": "固定按键", + "editor": "编辑器", + "table": "表格", + "calendar": "日历", + "feed": "订阅", + "reader": "阅读器", + "annotations": "批注", + "imageViewer": "图片查看器", + "combobox": "组合框", + "attributes": "属性管理", + "settings": "设置", + "datePicker": "日期选择器", + "clockInput": "时间输入框", + "tabs": "标签", + "textEditing": "文字编辑", + "edit": "修改快捷键", + "add": "添加快捷键", + "remove": "删除快捷键", + "reset": "恢复默认", + "resetAll": "全部恢复默认", + "resetBody": "要恢复本平台的全部默认快捷键吗?", + "record": "录入快捷键", + "firstStep": "第一步须使用修饰键或功能键。", + "fixedEdit": "这是固定的文字编辑快捷键。", + "equal": "已被「{{command}}」使用。", + "prefix": "是「{{command}}」快捷键的开头。", + "startsWith": "以「{{command}}」的快捷键开头。", + "fixedUse": "在{{area}}里有固定用途。", + "replace": "替换", + "replaceBody": "以下命令将失去一个快捷键:", + "action": { + "navigation": "在项目间移动", + "movement": "移动或缩进块", + "selection": "选择项目", + "open": "打开", + "openSide": "在侧边打开", + "context": "打开右键菜单", + "remove": "删除", + "apply": "确认", + "cancel": "取消或清除选区", + "collapse": "折叠或展开", + "switchPage": "上一页或下一页", + "editTitle": "编辑标题", + "pin": "钉住", + "restore": "恢复", + "cell": "在单元格间移动", + "today": "转到今天", + "zoom": "放大或缩小", + "search": "聚焦阅读器搜索", + "edit": "编辑", + "fold": "折叠或展开块", + "language": "选择代码语言", + "colors": "打开颜色选择器", + "toolbar": "聚焦格式工具栏", + "lineBreak": "插入换行", + "webLink": "按住修饰键并点击链接" + }, + "clear": "清空", + "save": "保存" + }, + "pageFind": { + "query": "页内查找", + "count": "{{current}} / {{total}}", + "previous": "上一处匹配", + "next": "下一处匹配", + "close": "关闭查找" } } \ No newline at end of file diff --git a/main/app/ipc.ts b/main/app/ipc.ts index 88017e3..2e28b10 100644 --- a/main/app/ipc.ts +++ b/main/app/ipc.ts @@ -1,3 +1,4 @@ +import { hostPlatform } from "../../shared/app/hostPlatform"; import { app, type BrowserWindow } from "electron"; import { machine, type as osType } from "node:os"; import typia from "typia"; @@ -19,10 +20,15 @@ export function registerAppIPCs(window: BrowserWindow): void { })) } satisfies Routes); register(contents, appChannels, { - openDevTools: route(typia.createAssert>(invalid), () => contents.openDevTools({ mode: "detach" })), + openDevTools: route(typia.createAssert>(invalid), () => { + if (contents.isDevToolsOpened()) contents.closeDevTools(); + else contents.openDevTools({ mode: "undocked" }); + }), + toggleFullscreen: route(typia.createAssert>(invalid), () => window.setFullScreen(!window.isFullScreen())), + quit: route(typia.createAssert>(invalid), () => app.quit()), setFrameColors: route(typia.createAssert>(invalid), (color, symbolColor) => { - if (process.platform === "darwin" || window.isDestroyed()) return; - window.setTitleBarOverlay(process.platform === "win32" ? { symbolColor } : { color, symbolColor }); + if (hostPlatform === "mac" || window.isDestroyed()) return; + window.setTitleBarOverlay(hostPlatform === "win" ? { symbolColor } : { color, symbolColor }); }), editorStarted: route(typia.createAssert>(invalid), () => lifecycle.editorStarted(contents)), beforeQuitResult: route(typia.createAssert>(invalid), (id, blocked) => lifecycle.saveResult(contents, id, blocked)) diff --git a/main/index.ts b/main/index.ts index 68d0561..a0a0a64 100644 --- a/main/index.ts +++ b/main/index.ts @@ -7,6 +7,8 @@ import * as startup from "./startup/startup"; import * as session from "./session"; import * as settingsEffects from "./settings/effects"; import * as lifecycle from "./lifecycle"; +import { hostPlatform } from "../shared/app/hostPlatform"; +import { initializeMenu } from "./ui/menu"; import * as windows from "./ui/window"; import * as reminders from "./ui/reminders"; import { openReminderPage } from "../shared/timers/ipc"; @@ -47,6 +49,7 @@ else { app.whenReady().then(() => { app.setAppUserModelId("dev.labloom.app"); startup.restore(); + initializeMenu(); windows.createWindow(applicationLog); }); @@ -62,6 +65,6 @@ else { // Close the app when all windows are closed, except on macOS. There, it's common for applications and their menu bar to stay active until the user quits explicitly with Cmd + Q. app.on("window-all-closed", () => { - if (process.platform !== "darwin") app.quit(); + if (hostPlatform !== "mac") app.quit(); }); } \ No newline at end of file diff --git a/main/settings/file.ts b/main/settings/file.ts index a06d289..23c0f25 100644 --- a/main/settings/file.ts +++ b/main/settings/file.ts @@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto"; import { readFileSync, renameSync } from "node:fs"; import { mkdir, open, rename, unlink } from "node:fs/promises"; import { dirname, join } from "node:path"; +import { repairKeybindings } from "../../shared/content/keybindings"; import { LabloomError } from "../../shared/failure"; import { defaultSettings, settingsVersion } from "../../shared/settings/defaults"; import { type Settings } from "../../shared/settings/Settings"; @@ -31,6 +32,9 @@ export function readSettings(path: string): LoadResult { } if (value && typeof value === "object" && "version" in value && typeof value.version === "number" && value.version > settingsVersion) throw new LabloomError({ kind: "config-newer-version" }); if (value && typeof value === "object" && !("history" in value)) value = { ...value, history: defaultSettings.history }; + if (value && typeof value === "object") { + value = { ...value, keybindings: repairKeybindings("keybindings" in value ? value.keybindings : undefined) }; + } if (validSettings(value)) return { settings: value, savedText: JSON.stringify(value) }; const backup = join(dirname(path), "settings.invalid-" + randomUUID() + ".json"); renameSync(path, backup); diff --git a/main/ui/menu.ts b/main/ui/menu.ts new file mode 100644 index 0000000..a06414e --- /dev/null +++ b/main/ui/menu.ts @@ -0,0 +1,38 @@ +import { app, BrowserWindow, Menu, type MenuItemConstructorOptions } from "electron"; +import { nativeCommand } from "../../shared/app/ipc"; +import { hostPlatform } from "../../shared/app/hostPlatform"; +import { resolveKeybindings } from "../../shared/content/keybindings"; +import { nativeMenu, type NativeMenuItem } from "../../shared/content/nativeMenu"; +import { createI18n, type Translate } from "../../shared/i18n"; +import * as settings from "../settings/store"; + +function menuItem(item: NativeMenuItem): MenuItemConstructorOptions { + const { command, submenu, ...options } = item; + return { + ...options, submenu: submenu?.map(menuItem), + click: command ? (_item, window) => { + const contents = (window instanceof BrowserWindow ? window : BrowserWindow.getFocusedWindow())?.webContents; + if (contents && !contents.isDestroyed()) contents.send(nativeCommand, command); + } : undefined + }; +} +export function initializeMenu(): void { + if (hostPlatform !== "mac") { + Menu.setApplicationMenu(null); + return; + } + const i18n = createI18n("zh-CN"); + let previous = ""; + function update(snapshot: ReturnType): void { + const { appearance, keybindings } = snapshot.settings; + const user = keybindings.mac; + const signature = JSON.stringify([appearance.language, user]); + if (previous === signature) return; + previous = signature; + const t: Translate = (key, options) => i18n.t(key, { ...options, lng: appearance.language }); + Menu.setApplicationMenu(Menu.buildFromTemplate(nativeMenu(hostPlatform, resolveKeybindings(hostPlatform, user), app.name, t).map(menuItem))); + } + update(settings.get()); + const unsubscribe = settings.subscribe(update); + app.once("will-quit", unsubscribe); +} \ No newline at end of file diff --git a/main/ui/window.ts b/main/ui/window.ts index 7fc642f..b5dbb7b 100644 --- a/main/ui/window.ts +++ b/main/ui/window.ts @@ -7,6 +7,8 @@ import * as settings from "../settings/store"; import * as lifecycle from "../lifecycle"; import { registerIPCs } from "../register"; import { attach } from "./windowFrame"; +import { hostPlatform } from "../../shared/app/hostPlatform"; +import { ignoreNativeShortcut } from "../../shared/content/nativeMenu"; let mainWindowRef: BrowserWindow | undefined; function openExternal(url: string): void { @@ -18,8 +20,8 @@ function openExternal(url: string): void { export function createWindow(applicationLog: LogFile | null): void { const bounds = settings.get().settings.window; const mainWindow = new BrowserWindow({ - ...(process.platform !== "darwin" ? { - titleBarOverlay: { height: 32, ...(process.platform === "win32" ? { color: "#00000000" } : {}) } + ...(hostPlatform !== "mac" ? { + titleBarOverlay: { height: 32, ...(hostPlatform === "win" ? { color: "#00000000" } : {}) } } : {}), width: bounds.width, height: bounds.height, @@ -79,33 +81,11 @@ export function createWindow(applicationLog: LogFile | null): void { }); contents.on("before-input-event", (event, input) => { - const command = input.control || input.meta; - const zoom = input.code === "Minus" || input.code === "Equal" || input.code === "NumpadAdd" || input.code === "NumpadSubtract"; - // Keep native shortcuts from consuming the reader and tab key events. - contents.setIgnoreMenuShortcuts( - command && (input.code === "KeyR" || input.code === "KeyW" || zoom) - ); - - if (input.code === "F11") { - event.preventDefault(); - return; - } + // Cocoa still registers menu equivalents when registerAccelerator is false. + // The fixed text editing keys retain their native menu roles. + if (hostPlatform === "mac") contents.setIgnoreMenuShortcuts(ignoreNativeShortcut(hostPlatform, input)); if (input.type !== "keyDown" || input.isComposing) return; - - if (input.code === "F12") { - event.preventDefault(); - if (!input.isAutoRepeat) { - if (!app.isPackaged && !contents.isDevToolsOpened()) { - contents.openDevTools({ mode: "undocked" }); - } - else contents.toggleDevTools(); - } - return; - } - - if (app.isPackaged && input.code === "KeyI" && ((input.control && input.shift) || (input.meta && input.alt))) { - event.preventDefault(); - } + if (app.isPackaged && input.code === "KeyI" && input.control && input.shift) event.preventDefault(); }); // HMR support, do not remove diff --git a/package.json b/package.json index 908b279..d19d117 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,7 @@ "lint:fix": "eslint --config configs/eslint.config.js --fix .", "test": "npm run test:feed && npm run test:db", "test:feed": "node --test configs/feed.test.js", - "test:db": "node --import tsx --test tests/database-tools.test.ts tests/ipc-validators.test.ts && node tests/run-workspace.mjs", + "test:db": "node --import tsx --test tests/database-tools.test.ts tests/ipc-validators.test.ts tests/keybindings.test.ts && node tests/run-workspace.mjs", "perf": "node tests/run-workspace.mjs --perf", "db:generate": "node --import tsx scripts/database.mjs generate", "db:check": "node --import tsx scripts/database.mjs check", diff --git a/preload/index.d.ts b/preload/index.d.ts index a4308b1..69cc2d2 100644 --- a/preload/index.d.ts +++ b/preload/index.d.ts @@ -1,10 +1,12 @@ import { type AppAPI } from "../shared/app"; import { type BridgeAPI } from "../shared/ipc/bridge"; +import { type ShortcutPlatform } from "../shared/app/platform"; declare global { interface Window { getPathForFile(file: File): string; api: AppAPI; bridge: BridgeAPI; + labloomPlatform?: ShortcutPlatform; } } \ No newline at end of file diff --git a/preload/index.ts b/preload/index.ts index 4414cc5..da56716 100644 --- a/preload/index.ts +++ b/preload/index.ts @@ -1,6 +1,7 @@ import { contextBridge, ipcRenderer, webUtils } from "electron"; import { type Channels, type InvokeKeys } from "../shared/ipc/contract"; -import { appChannels, appQueryChannels, attachmentProgress, beforeQuit, feedChanged, historyChanged, pagesChanged, settingsChanged, openReminderPage, pagesChannels, attachmentsChannels, attributesChannels, historyChannels, papersChannels, timersChannels, workspaceChannels, settingsChannels, startupChannels, feedChannels, type AppAPI, type AppCommands, type AppQueries, type BridgeAPI } from "../shared/ipc"; +import { hostPlatform } from "../shared/app/hostPlatform"; +import { appChannels, appQueryChannels, attachmentProgress, beforeQuit, nativeCommand, feedChanged, historyChanged, pagesChanged, settingsChanged, openReminderPage, pagesChannels, attachmentsChannels, attributesChannels, historyChannels, papersChannels, timersChannels, workspaceChannels, settingsChannels, startupChannels, feedChannels, type AppAPI, type AppCommands, type AppQueries, type BridgeAPI } from "../shared/ipc"; function methods(channels: Record, call: (channel: string, ...args: unknown[]) => unknown): API { return Object.fromEntries(Object.entries(channels).map(([key, channel]) => [key, (...args: unknown[]) => call(channel, ...args)])) as API; @@ -18,7 +19,8 @@ const { beforeQuitResult, ...commands } = appChannels; const api: BridgeAPI = { app: { ...invokes(appQueryChannels), - ...methods>(commands, (channel, ...args) => ipcRenderer.send(channel, ...args)), + ...methods>(commands, (channel, ...args) => ipcRenderer.send(channel, ...args)), + onCommand: listener => subscribe(nativeCommand, listener), beforeQuit(check) { const listener = (_event: unknown, id: string): void => { Promise.resolve().then(check).then(block => ipcRenderer.send(beforeQuitResult, id, block !== false)) @@ -46,4 +48,5 @@ const api: BridgeAPI = { }; contextBridge.exposeInMainWorld("bridge", api); +contextBridge.exposeInMainWorld("labloomPlatform", hostPlatform); contextBridge.exposeInMainWorld("getPathForFile", (file: File) => webUtils.getPathForFile(file)); \ No newline at end of file diff --git a/renderer/components/Editor/CodeTools.svelte b/renderer/components/Editor/CodeTools.svelte index 4d6b166..a9ba97e 100644 --- a/renderer/components/Editor/CodeTools.svelte +++ b/renderer/components/Editor/CodeTools.svelte @@ -1,5 +1,5 @@
- + {#snippet trigger({ props })}
-
{@render children()}
+
{@render children()}
+
{waiting}
@@ -29,13 +30,33 @@ min-width: 0; -webkit-app-region: no-drag; } + .search-launcher.waiting { + visibility: hidden; + } + .shortcut-status.waiting { + grid-row: 1; + grid-column: 2 / -1; + } + .shortcut-status { + min-width: 0; + margin-inline-end: var(--system-controls); + overflow: hidden; + text-align: end; + text-overflow: ellipsis; + white-space: nowrap; + font-size: var(--ui-font-small); + user-select: none; + } \ No newline at end of file diff --git a/renderer/components/layout/SidebarGroup.svelte b/renderer/components/layout/SidebarGroup.svelte index c602756..18d5b12 100644 --- a/renderer/components/layout/SidebarGroup.svelte +++ b/renderer/components/layout/SidebarGroup.svelte @@ -8,7 +8,7 @@ title={caption} selected={page.id === currentPage} buttonProps={{ ...props, tabindex: -1, "data-panel-node": "page", "data-panel-key": groupKey + "/" + page.id }} - onclick={event => openPage(page.id, { currentGroup: true, otherGroup: event.ctrlKey })} + onclick={event => openPage(page.id, { currentGroup: true, otherGroup: primaryModifier(event) })} > {#snippet trigger({ props: tip })}{caption}{/snippet} @@ -51,6 +51,7 @@ \ No newline at end of file diff --git a/renderer/components/tabs/Overview.svelte b/renderer/components/tabs/Overview.svelte index 5ea8e5f..e95d511 100644 --- a/renderer/components/tabs/Overview.svelte +++ b/renderer/components/tabs/Overview.svelte @@ -7,7 +7,7 @@
- +
@@ -205,7 +205,7 @@