From db6d7eef5f01f69d576ca7dfb3981b2084dc78f7 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 16:45:30 +0000 Subject: [PATCH 1/2] Build: adapt TLS certificate description to x509-cert 0.3 x509-cert 0.3 (Dependabot, merged) made the TBS certificate fields private; use the accessor methods instead so rc-core compiles again. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017w9FQmmTGCmcWdHRoM2wue --- crates/rc-core/src/protocols/tls.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/rc-core/src/protocols/tls.rs b/crates/rc-core/src/protocols/tls.rs index dbc5da4..003b703 100644 --- a/crates/rc-core/src/protocols/tls.rs +++ b/crates/rc-core/src/protocols/tls.rs @@ -201,9 +201,9 @@ fn describe(cert: &CertificateDer<'_>) -> CertDescription { use x509_cert::der::Decode; match x509_cert::Certificate::from_der(cert.as_ref()) { Ok(c) => CertDescription { - subject: c.tbs_certificate.subject.to_string(), - issuer: c.tbs_certificate.issuer.to_string(), - not_after: c.tbs_certificate.validity.not_after.to_string(), + subject: c.tbs_certificate().subject().to_string(), + issuer: c.tbs_certificate().issuer().to_string(), + not_after: c.tbs_certificate().validity().not_after.to_string(), }, Err(e) => CertDescription { subject: format!("(unparsable certificate: {e})"), From 1df82424b508c3ff32b6bc004df444b723c26b15 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 16:45:31 +0000 Subject: [PATCH 2/2] Keyboard layouts: Norton Commander (default), Total Commander, Rust Commander Rust Commander now offers keyboard layouts. The default is the original Norton Commander layout (1Help 2Menu 3View 4Edit 5Copy 6RenMov 7Mkdir 8Delete 9PullDn 10Quit, Alt+F1/F2 drive, Alt+F3-F7, Ctrl+F3-F6 sorting, Ctrl+O, Ctrl+U, Alt+letter quick search). Total Commander's layout is available too (F2 reread, Shift+F6 rename, Ctrl+D hotlist, Ctrl+S filter, Alt+Down history, Ctrl+Left/Right, Ctrl+Alt+letter quick search), and the previous layout stays selectable as "Rust Commander". - lib/keymaps.ts: the layouts as pure data plus key-event helpers - actions/commands.ts: command registry (run, labels, availability) - function key bar above the status bar with Shift/Ctrl/Alt layers - menus, toolbar, context menu and the F1 list follow the active layout - setting "keymap" (default "norton") and "showKeyBar" in settings.json; View menu, Preferences and the F1 dialog switch the layout - F10 / Alt+F4 quit the desktop app (with confirmation) - unit and smoke tests, docs Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017w9FQmmTGCmcWdHRoM2wue --- README.md | 10 +- crates/rc-api/src/settings.rs | 28 ++ docs/src/getting-started/quick-tour.md | 5 +- docs/src/guide/file-operations.md | 11 +- docs/src/guide/interface.md | 3 +- docs/src/guide/transfers.md | 2 +- docs/src/guide/web-mode.md | 2 +- docs/src/introduction.md | 2 +- docs/src/reference/configuration.md | 2 +- docs/src/reference/keyboard-shortcuts.md | 143 +++++-- src-tauri/capabilities/default.json | 1 + ui/src/App.tsx | 2 + ui/src/actions/commands.ts | 237 +++++++++++ ui/src/actions/shortcuts.ts | 113 ++--- ui/src/api/mock.ts | 2 + ui/src/api/types.ts | 4 + ui/src/components/KeyBar.tsx | 77 ++++ ui/src/components/MenuBar.tsx | 158 ++++--- .../components/dialogs/PreferencesDialog.tsx | 11 + ui/src/components/dialogs/SmallDialogs.tsx | 80 +++- ui/src/components/panel/FileTable.tsx | 22 +- ui/src/components/panel/Panel.tsx | 48 ++- ui/src/components/panel/panelMenu.ts | 39 +- ui/src/i18n/de.ts | 94 +++++ ui/src/i18n/en.ts | 94 +++++ ui/src/lib/keymaps.ts | 385 ++++++++++++++++++ ui/src/store/uiRequests.ts | 45 ++ ui/src/styles/dialogs.css | 1 + ui/src/styles/layout.css | 44 ++ ui/tests/smoke.mjs | 93 ++++- ui/tests/unit.mjs | 83 ++++ 31 files changed, 1607 insertions(+), 234 deletions(-) create mode 100644 ui/src/actions/commands.ts create mode 100644 ui/src/components/KeyBar.tsx create mode 100644 ui/src/lib/keymaps.ts create mode 100644 ui/src/store/uiRequests.ts diff --git a/README.md b/README.md index a97c037..30ebf0a 100644 --- a/README.md +++ b/README.md @@ -32,8 +32,9 @@ SFTP · SCP · FTP/FTPS · WebDAV · S3 · Azure · Google Cloud Storage — on ### 🗂️ Classic commander, modern feel -Two panels, session tabs, bookmarks, drag & drop and full keyboard control -(F2–F8, Ins, Ctrl+…). Light and dark theme, English and German. +Two panels, session tabs, bookmarks, drag & drop and full keyboard control with the +**original Norton Commander layout** and function key bar — or Total Commander's. +Light and dark theme, English and German. @@ -133,8 +134,9 @@ Download the latest version from the See [Installation](docs/src/getting-started/installation.md) for first-start notes, or [build it](#-building) yourself. Start **Rust Commander**, press **Ctrl+N** to open the Site -Manager and connect. The keys work as in every classic commander: **F5** copy, -**F6** move, **F7** new folder, **F8** delete, **F4** edit, **F1** all shortcuts. +Manager and connect. The keys follow the original Norton Commander: **F5** copy, +**F6** move, **F7** new folder, **F8** delete, **F4** edit, **F2** user menu, **F9** menu, +**F1** all shortcuts. *View* → **Keyboard layout** switches to Total Commander. ### On a server (web mode) diff --git a/crates/rc-api/src/settings.rs b/crates/rc-api/src/settings.rs index 2455df3..287b162 100644 --- a/crates/rc-api/src/settings.rs +++ b/crates/rc-api/src/settings.rs @@ -106,6 +106,11 @@ pub struct Settings { pub restore_sessions: bool, /// Continue interrupted transfers after a restart (otherwise they come back paused). pub resume_jobs: bool, + /// Keyboard layout: "norton" (Norton Commander), "total" (Total Commander) or "rust" + /// (the layout of Rust Commander 0.1). Unknown values are treated as "norton". + pub keymap: String, + /// Show the function key bar (F1–F10) above the status bar. + pub show_key_bar: bool, pub transfer: TransferOptions, pub discovery: DiscoverySettings, pub server: ServerSettings, @@ -127,6 +132,8 @@ impl Default for Settings { use_trash: true, restore_sessions: true, resume_jobs: true, + keymap: "norton".into(), + show_key_bar: true, transfer: TransferOptions::default(), discovery: DiscoverySettings::default(), server: ServerSettings::default(), @@ -135,3 +142,24 @@ impl Default for Settings { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keyboard_layout_defaults_to_norton_commander() { + // settings.json written before keyboard layouts existed + let s: Settings = serde_json::from_str(r#"{ "theme": "dark", "showHidden": true }"#).unwrap(); + assert_eq!(s.keymap, "norton"); + assert!(s.show_key_bar); + assert_eq!(s.theme, "dark"); + + let s: Settings = serde_json::from_str(r#"{ "keymap": "total", "showKeyBar": false }"#).unwrap(); + assert_eq!(s.keymap, "total"); + assert!(!s.show_key_bar); + let v = serde_json::to_value(&s).unwrap(); + assert_eq!(v["keymap"], "total"); + assert_eq!(v["showKeyBar"], false); + } +} diff --git a/docs/src/getting-started/quick-tour.md b/docs/src/getting-started/quick-tour.md index 9174381..0398023 100644 --- a/docs/src/getting-started/quick-tour.md +++ b/docs/src/getting-started/quick-tour.md @@ -56,4 +56,7 @@ sessions, a local shell for the local file system. - **Ctrl+Shift+E** opens the [Remote Explorer](../guide/remote-explorer.md) for all your SSH targets. - **Ctrl+B** shows the sidebar with **Nearby** instances on your network. - **Ctrl+Shift+S** opens [Synchronization](../guide/synchronization.md). -- **F1** lists every keyboard shortcut. +- **F1** lists every keyboard shortcut. The keys follow Norton Commander; *View* → + **Keyboard layout** switches to Total Commander or the earlier Rust Commander layout. + The function key bar at the bottom shows what F1–F10 do (hold Shift, Ctrl or Alt for + the other layers). diff --git a/docs/src/guide/file-operations.md b/docs/src/guide/file-operations.md index d6cee6c..9f4d70a 100644 --- a/docs/src/guide/file-operations.md +++ b/docs/src/guide/file-operations.md @@ -3,20 +3,24 @@ All operations work the same on every protocol, as far as the protocol allows (object stores, for example, have no permissions or symlinks). +The keys below are those of the default keyboard layout, Norton Commander. The +[keyboard shortcuts](../reference/keyboard-shortcuts.md) list the Total Commander and +Rust Commander layouts; *View* → **Keyboard layout** switches between them. + | Key | Operation | |---|---| | Enter | Open folder / file | -| F2 | Rename in place | +| Shift+F6 | Rename in place | | F3 / F4 | View / [edit](editor.md) | | Shift+F4 | New file | | F5 / F6 | [Copy / move](transfers.md) to the other panel | -| Shift+F5 / Shift+F6 | Copy / move without the dialog | | F7 | New folder | | F8, Delete | Delete (recursive deletes run as a background job); local files go to the trash | | Shift+F8, Shift+Delete | Delete permanently (local files skip the trash) | | Ctrl+Z | Undo the last rename or move | | Alt+Enter | Properties | | Ctrl+Shift+C | Copy the full path(s) to the clipboard | +| F2 | User menu with your [custom commands](#custom-commands) | *Files* → **Create link…** creates a symbolic link. @@ -82,7 +86,8 @@ can reveal a file in its panel, view or edit it, or copy its path. ## Custom commands *Tools* → **Custom commands…** defines your own commands, which then appear under -*Commands* → **Custom commands**. A command can run on the server of the session or +*Commands* → **Custom commands** and, in the Norton Commander layout, in the user menu +(**F2**). A command can run on the server of the session or locally, once per file or once for the whole selection, show its output and refresh the panel afterwards. diff --git a/docs/src/guide/interface.md b/docs/src/guide/interface.md index 8494e37..e474215 100644 --- a/docs/src/guide/interface.md +++ b/docs/src/guide/interface.md @@ -44,7 +44,8 @@ app you can also drop files from your operating system's file manager. ## Bookmarks -**Ctrl+D** bookmarks the current folder. Bookmarks can apply to the local file system, to a +**Ctrl+D** bookmarks the current folder (in the Total Commander layout it opens the +bookmark list, the "directory hotlist"). Bookmarks can apply to the local file system, to a single site or to every session (for example `/var/log/nginx`). ## Themes and languages diff --git a/docs/src/guide/transfers.md b/docs/src/guide/transfers.md index cc11a69..b23f501 100644 --- a/docs/src/guide/transfers.md +++ b/docs/src/guide/transfers.md @@ -99,6 +99,6 @@ instead of the upload time, so synchronizations by time work with buckets too. ## Web mode: browser uploads and downloads In the [web mode](web-mode.md) there are extra commands for the computer running the -browser: **Upload from this computer…** (Ctrl+U), **Upload folder…** and **Download to +browser: **Upload from this computer…** (Ctrl+U in the Rust Commander keyboard layout), **Upload folder…** and **Download to this computer**. Folders are downloaded as a ZIP stream. diff --git a/docs/src/guide/web-mode.md b/docs/src/guide/web-mode.md index dc64c0b..1f0a08a 100644 --- a/docs/src/guide/web-mode.md +++ b/docs/src/guide/web-mode.md @@ -53,7 +53,7 @@ browser runs on: | Command | | |---|---| -| **Upload from this computer…** (Ctrl+U) | Upload files into the active panel's folder | +| **Upload from this computer…** (Ctrl+U in the Rust Commander layout) | Upload files into the active panel's folder | | **Upload folder…** | Upload a whole folder | | **Download to this computer** | Download the selection; folders are streamed as a ZIP | diff --git a/docs/src/introduction.md b/docs/src/introduction.md index c306231..1a4d1a3 100644 --- a/docs/src/introduction.md +++ b/docs/src/introduction.md @@ -15,7 +15,7 @@ can be opened straight from the app. | Area | Highlights | |---|---| | Protocols | SFTP, SCP, FTP, FTPS (explicit and implicit), WebDAV(S), Amazon S3 and S3-compatible storage (MinIO, Wasabi, R2, Ceph …), Azure Blob Storage, Google Cloud Storage, and other Rust Commander instances | -| Interface | Commander layout with two panels, session tabs, bookmarks, synchronized browsing, directory comparison, full keyboard control (F2–F8, Ins, Ctrl+…), light and dark theme, English and German | +| Interface | Commander layout with two panels, session tabs, bookmarks, synchronized browsing, directory comparison, full keyboard control with the Norton Commander (default) or Total Commander keyboard layout and a function key bar, light and dark theme, English and German | | Transfers | Background queue with pause/resume/cancel/retry, resumable transfers, overwrite rules, **fingerprint comparison before copying**, preserved timestamps and permissions, file masks, speed limit, parallel transfers, server-to-server copies | | Synchronization | One-way or two-way comparison by size, time or checksum, mirror mode, a **checklist** before anything runs, and "keep remote folder up to date" | | Editor | Built-in editor for local and remote files with language detection, **linting**, **formatting**, change markers and a diff view | diff --git a/docs/src/reference/configuration.md b/docs/src/reference/configuration.md index d907cb1..fbf61de 100644 --- a/docs/src/reference/configuration.md +++ b/docs/src/reference/configuration.md @@ -50,7 +50,7 @@ system's temporary folder. | Tab | Settings | |---|---| -| General | Language, theme, hidden files, size format, what double-click / Enter does on a file (edit, open with the default application, copy to the other panel), confirmations before deleting and overwriting, moving deleted local files to the trash, whether the copy/move dialog is shown | +| General | Language, theme, [keyboard layout](keyboard-shortcuts.md) (Norton Commander, Total Commander, Rust Commander) and function key bar, hidden files, size format, what double-click / Enter does on a file (edit, open with the default application, copy to the other panel), confirmations before deleting and overwriting, moving deleted local files to the trash, whether the copy/move dialog is shown | | Transfer | Default transfer settings, number of parallel jobs, reconnecting the sessions and continuing the jobs of the last run | | Editor | Show problems, format when saving, line width for formatting, tab width, word wrap | | Terminal | Font family, font size, scrollback lines | diff --git a/docs/src/reference/keyboard-shortcuts.md b/docs/src/reference/keyboard-shortcuts.md index 2d8a9d3..0f15a01 100644 --- a/docs/src/reference/keyboard-shortcuts.md +++ b/docs/src/reference/keyboard-shortcuts.md @@ -1,9 +1,108 @@ # Keyboard shortcuts -The shortcuts follow the classic commander programs. **F1** shows this list inside the app. -On macOS, **Ctrl** is **⌘**, **Shift** is **⇧** and **Alt** is **⌥**. +Rust Commander offers three keyboard layouts. Choose one under *View* → **Keyboard layout**, +in **Preferences** (Ctrl+,) → *General*, or directly in the shortcut list that **F1** opens. -## Files +| Layout | | +|---|---| +| **Norton Commander** (default) | The original layout of the DOS classic: `1Help 2Menu 3View 4Edit 5Copy 6RenMov 7Mkdir 8Delete 9PullDn 10Quit` | +| **Total Commander** | The layout of the Windows classic: F2 rereads the panel, Shift+F6 renames, Ctrl+D is the directory hotlist | +| **Rust Commander** | The layout of earlier versions of Rust Commander: F2 renames, F9 refreshes | + +The **function key bar** above the status bar shows what F1–F10 do in the chosen layout. +Hold **Shift**, **Ctrl** or **Alt** and it shows that layer, as in Norton Commander; a click +on a key runs its command. *View* → **Function key bar** (or *Preferences* → *General*) +hides it. It is not shown on phones. + +Keys the original programs leave free carry Rust Commander's additional functions (terminal, +synchronization, Remote Explorer …); they are marked with \* in the tables below and in the +app. Functions the originals have but Rust Commander does not (the DOS command line, the +info and quick-view panels, panels on/off, folder tabs) are left unassigned. + +On macOS, **Ctrl** is **⌘**, **Shift** is **⇧** and **Alt** is **⌥**. On Windows and +Linux the operating system may keep some keys for itself (Alt+F4 closes the window in many +desktops). + +## Norton Commander (default) + +| Key | Action | +|---|---| +| F1 | Keyboard shortcuts (help) | +| F2 | User menu: your [custom commands](../guide/file-operations.md#custom-commands) | +| F3 | View | +| F4 | Edit | +| F5 | Copy | +| F6 | Move (RenMov) | +| F7 | New folder | +| F8 / Delete\* | Delete (local files: to the trash) | +| F9 | Open the menu bar (PullDn) | +| F10 | Quit (desktop app) | +| Shift+F4 | New file | +| Shift+F6 | Rename in place | +| Shift+F8 / Shift+Delete\* | Delete permanently | +| Alt+F1 / Alt+F2 | Choose the location (drive, session) of the left / right panel | +| Alt+F3 | View with the external application | +| Alt+F4 | Edit with the external application (desktop app) | +| Alt+F5 | Pack: create an archive | +| Alt+F6 | Unpack: extract the archive here | +| Alt+F7 | Find files | +| Ctrl+F3 / F4 / F5 / F6 | Sort by name / type / date / size (again: reverse) | +| Ctrl+O | Show or hide the terminal (the "user screen") | +| Ctrl+U | Swap panels | +| Ctrl+R | Reread the panel | +| Ctrl+\\ | Root folder | +| Ctrl+PgUp / Ctrl+PgDn | Parent folder / open the folder under the cursor | +| Alt+letter | Quick search: jump to the next file starting with the typed letters | + +Additions (\*): Alt+Enter properties, Alt+← / Alt+→ back / forward, Ctrl+N new session, +Ctrl+F find files, Ctrl+D bookmark this folder, Ctrl+Z undo, Ctrl+H hidden files, Ctrl+T +terminal, Ctrl+L edit the path, Ctrl+Shift+S synchronize, Ctrl+B sidebar, Ctrl+Shift+E +Remote Explorer, Ctrl+J dock, Ctrl+Shift+C copy path, Ctrl+, preferences, Ctrl+P open file, +Ctrl+K compare fingerprints. + +## Total Commander + +| Key | Action | +|---|---| +| F1 | Keyboard shortcuts (help) | +| F2 / Ctrl+R | Reread the panel | +| F3 | View | +| F4 | Edit | +| F5 | Copy | +| F6 | Move | +| F7 | New folder | +| F8 / Delete | Delete (local files: to the trash) | +| Shift+F8 / Shift+Delete | Delete permanently | +| F9 / F10 | Open the menu bar | +| Alt+F4 | Quit (desktop app) | +| Shift+F2 | Compare directories | +| Shift+F4 | New file | +| Shift+F6 | Rename in place | +| Alt+F1 / Alt+F2 | Choose the location (drive, session) of the left / right panel | +| Alt+F3 | View with the external application | +| Alt+F5 | Pack: create an archive | +| Alt+F9 / Alt+F6 | Unpack: extract the archive here | +| Alt+F7 | Find files | +| Alt+Enter | Properties | +| Alt+← / Alt+→ | Back / forward | +| Alt+↓ | Folder history | +| Ctrl+F3 / F4 / F5 / F6 | Sort by name / type / date / size (again: reverse) | +| Ctrl+Num + / Ctrl+Num − | Select all / select none | +| Ctrl+PgUp / Ctrl+PgDn | Parent folder / open the folder under the cursor | +| Ctrl+\\ | Root folder | +| Ctrl+← / Ctrl+→ | Show the folder under the cursor in the left / right panel | +| Ctrl+D | Directory hotlist (bookmarks) | +| Ctrl+F / Ctrl+N | Connect (Site Manager) | +| Ctrl+Shift+F | Disconnect the session of the active panel | +| Ctrl+S | Quick filter | +| Ctrl+U | Swap panels | +| Ctrl+Alt+letter | Quick search | + +Additions (\*): Ctrl+Z undo, Ctrl+H hidden files, Ctrl+T terminal, Ctrl+L edit the path, +Ctrl+Shift+S synchronize, Ctrl+B sidebar, Ctrl+Shift+E Remote Explorer, Ctrl+J dock, +Ctrl+Shift+C copy path, Ctrl+, preferences, Ctrl+P open file, Ctrl+K compare fingerprints. + +## Rust Commander | Key | Action | |---|---| @@ -25,30 +124,11 @@ On macOS, **Ctrl** is **⌘**, **Shift** is **⇧** and **Alt** is **⌥**. | Ctrl+K | Compare fingerprints with the other panel | | Ctrl+P | Open file… | | Ctrl+U | Upload from this computer (web mode) | - -## Navigation and selection - -| Key | Action | -|---|---| -| Tab | Switch panel | -| Backspace | Parent folder | | Alt+← / Alt+→ | Back / forward | | Ctrl+\\ | Root folder | +| Ctrl+PgUp / Ctrl+PgDn | Parent folder / open the folder under the cursor | | Ctrl+L | Edit the path | | Ctrl+R / F9 | Refresh | -| Insert | Toggle selection and move down | -| Space | Toggle selection | -| Ctrl+A | Select all | -| Ctrl+Shift+A | Select none | -| + / − | Select / unselect by mask | -| * | Invert selection | -| A–Z | Jump to a file (type-ahead) | -| Esc | Clear the selection, cancel a drag | - -## Windows and tools - -| Key | Action | -|---|---| | Ctrl+N | New session (Site Manager) | | Ctrl+T | Open terminal | | Ctrl+F | Find files | @@ -61,6 +141,23 @@ On macOS, **Ctrl** is **⌘**, **Shift** is **⇧** and **Alt** is **⌥**. | Ctrl+, | Preferences | | F1 | Keyboard shortcuts | +## File panels (all layouts) + +| Key | Action | +|---|---| +| Tab | Switch panel | +| Enter | Open | +| Backspace | Parent folder | +| Insert | Toggle selection and move down | +| Space | Toggle selection | +| Ctrl+A | Select all | +| Ctrl+Shift+A | Select none | +| + / − | Select / unselect by mask | +| * | Invert selection | +| A–Z | Jump to a file (type-ahead) | +| Shift+F10, Menu key | Context menu | +| Esc | Clear the selection, cancel a drag | + ## Editor | Key | Action | diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index 6a2bf56..67a3905 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -6,6 +6,7 @@ "permissions": [ "core:default", "core:window:allow-set-title", + "core:window:allow-close", "core:webview:allow-internal-toggle-devtools", "dialog:default", "dialog:allow-open", diff --git a/ui/src/App.tsx b/ui/src/App.tsx index 15ca6e9..653c017 100644 --- a/ui/src/App.tsx +++ b/ui/src/App.tsx @@ -20,6 +20,7 @@ import { Splitter } from './components/Splitter'; import { Dock } from './components/dock/Dock'; import { Sidebar } from './components/Sidebar'; import { StatusBar } from './components/StatusBar'; +import { KeyBar } from './components/KeyBar'; import { DialogHost } from './components/DialogHost'; import { PromptHost } from './components/PromptHost'; import { ConflictHost } from './components/ConflictHost'; @@ -168,6 +169,7 @@ function Workbench() { + diff --git a/ui/src/actions/commands.ts b/ui/src/actions/commands.ts new file mode 100644 index 0000000..be07015 --- /dev/null +++ b/ui/src/actions/commands.ts @@ -0,0 +1,237 @@ +// The commands keyboard layouts bind to keys (see lib/keymaps.ts): what each one does, its +// name in menus and the help, its short label in the function key bar, and when it is +// available at all. +import type { TKey } from '../i18n'; +import { tr } from '../i18n'; +import { mode } from '../api/client'; +import type { CommandId } from '../lib/keymaps'; +import { isDirLike } from '../lib/fileTypes'; +import * as P from '../lib/paths'; +import { setLayout, showDock, toggleDock, toggleHidden, toggleSidebar, useApp, type Side } from '../store/app'; +import { confirmDialog, openSingleton } from '../store/dialogs'; +import { hasDirtyTabs } from '../store/editors'; +import { + clearCompare, compareDirectories, focusedEntry, getPanel, goBack, goForward, goRoot, goUp, navigate, PARENT, refresh, selectAll, + selectNone, setSort, type SortKey, +} from '../store/panels'; +import { useTerms } from '../store/terminals'; +import { toast } from '../store/toasts'; +import { requestUi } from '../store/uiRequests'; +import { showContextMenu, type MenuItem } from '../components/Menu'; +import { commandsSubmenu } from '../components/panel/panelMenu'; +import { focusPathBar } from '../components/panel/PathBar'; +import * as ops from './fileOps'; +import { closeSession, openSiteManager } from './sessions'; +import { undoLast } from './undo'; + +export interface Command { + run: (side: Side) => void; + /** Name in menus and the help. */ + label: TKey; + /** Short label in the function key bar. */ + short: TKey; + /** False hides the command in the key bar and lets its keys through. */ + available?: () => boolean; +} + +const info = () => useApp.getState().info; +const desktop = () => info()?.mode === 'desktop'; +const web = () => info()?.mode === 'web'; +const hasTerminal = () => !!info()?.features.terminal; + +// ---------------------------------------------------------------- helpers for single commands + +/** Point below the cursor row of a panel (or its top left corner), for popup menus. */ +function anchorPoint(side: Side): { x: number; y: number } { + const body = document.querySelector(`[data-panel="${side}"] .ft-body`); + const row = body?.querySelector('.ft-row.cursor'); + const r = row?.getBoundingClientRect() ?? body?.getBoundingClientRect(); + if (!r) return { x: 40, y: 80 }; + return row ? { x: r.left + 40, y: r.bottom } : { x: r.left + 40, y: r.top + 8 }; +} + +function popup(side: Side, items: MenuItem[]) { + const { x, y } = anchorPoint(side); + showContextMenu(x, y, items); +} + +export function swapPanels() { + const left = getPanel('left'); + const right = getPanel('right'); + void navigate('left', right.session, right.path, { select: right.cursor }); + void navigate('right', left.session, left.path, { select: left.cursor }); +} + +export function toggleCompare() { + if (getPanel('left').compare) return clearCompare(); + const n = compareDirectories(); + toast.info(n ? tr('compare.found', { n }) : tr('compare.identical')); +} + +function sortBy(side: Side, key: SortKey) { + setSort(side, key); +} + +/** Total Commander's Ctrl+←/→: shows the folder under the cursor (or the current one) in a panel. */ +function showDirIn(side: Side, to: Side) { + const p = getPanel(side); + const e = focusedEntry(side); + let path = p.path; + if (e?.name === PARENT) path = P.parent(p.path) ?? p.path; + else if (e && isDirLike(e)) path = e.path || P.join(p.path, e.name); + void navigate(to, p.session, path); +} + +function openDirUnderCursor(side: Side) { + const e = focusedEntry(side); + if (e && (e.name === PARENT || isDirLike(e))) ops.openEntry(side, e); +} + +function userMenu(side: Side) { + popup(side, [{ label: tr('cmd.userMenu'), header: true }, ...commandsSubmenu(side)]); +} + +function dirHistory(side: Side) { + const p = getPanel(side); + const sessions = useApp.getState().sessions; + const seen = new Set([`${p.session}\n${p.path}`]); + const items: MenuItem[] = []; + for (const loc of [...p.back].reverse()) { + const key = `${loc.session}\n${loc.path}`; + if (seen.has(key)) continue; + seen.add(key); + const s = loc.session === p.session ? null : sessions.find((x) => x.id === loc.session); + if (loc.session !== p.session && !s) continue; // session closed meanwhile + items.push({ label: s ? `${s.name}: ${loc.path}` : loc.path, onClick: () => void navigate(side, loc.session, loc.path) }); + if (items.length >= 20) break; + } + popup(side, [{ label: tr('cmd.dirHistory'), header: true }, ...(items.length ? items : [{ label: tr('history.empty'), disabled: true }])]); +} + +function toggleTerminal(side: Side) { + const st = useApp.getState(); + if (st.dockOpen && st.dockTab === 'terminal') return setLayout({ dockOpen: false }); + if (!useTerms.getState().tabs.some((t) => !t.exited)) return ops.openTerminalHere(side); + showDock('terminal'); +} + +/** The external application: the system default locally, the watched external editor remotely. */ +function openExternal(side: Side, fallback: 'view' | 'edit') { + const e = focusedEntry(side); + const p = getPanel(side); + const i = info(); + if (!e || e.name === PARENT) return; + if (i?.mode === 'desktop') { + if (p.session === 'local' && i.features.openLocal) return ops.openWithSystem(side); + if (p.session !== 'local' && i.features.externalEdit && !isDirLike(e)) return void ops.externalEdit(side, e); + } + if (i?.mode === 'web' && fallback === 'view' && !isDirLike(e)) return void ops.openInBrowser(side); + if (fallback === 'view') ops.viewFocused(side); + else ops.editFocused(side); +} + +function localOnly(side: Side, fn: (side: Side) => unknown) { + if (getPanel(side).session !== 'local') return toast.info(tr('archive.localOnly')); + void fn(side); +} + +async function quit() { + if (mode !== 'desktop') return; + const dirty = hasDirtyTabs(); + const ok = await confirmDialog({ + title: tr('quit.title'), + message: dirty ? tr('quit.unsaved') : tr('quit.message'), + okLabel: tr('quit.ok'), + danger: dirty, + }); + if (!ok) return; + const { getCurrentWindow } = await import('@tauri-apps/api/window'); + await getCurrentWindow().close(); +} + +function disconnect(side: Side) { + const s = getPanel(side).session; + if (s !== 'local') void closeSession(s); +} + +// ---------------------------------------------------------------- the registry + +export const COMMANDS: Record = { + help: { run: () => openSingleton('shortcuts', {}), label: 'help.shortcuts', short: 'key.help' }, + userMenu: { run: userMenu, label: 'cmd.userMenu', short: 'key.userMenu' }, + view: { run: (s) => ops.viewFocused(s), label: 'ops.view', short: 'key.view' }, + viewExternal: { run: (s) => openExternal(s, 'view'), label: 'cmd.viewExternal', short: 'key.viewExternal' }, + edit: { run: (s) => ops.editFocused(s), label: 'ops.edit', short: 'key.edit' }, + editExternal: { run: (s) => openExternal(s, 'edit'), label: 'ops.editExternal', short: 'key.editExternal', available: desktop }, + newFile: { run: (s) => void ops.newFile(s), label: 'ops.newFile', short: 'key.newFile' }, + copy: { run: (s) => ops.copySelection(s, false), label: 'ops.copy', short: 'key.copy' }, + copyQuick: { run: (s) => ops.copySelection(s, false, true), label: 'help.copyNoDialog', short: 'key.copyQuick' }, + move: { run: (s) => ops.copySelection(s, true), label: 'ops.move', short: 'key.move' }, + moveQuick: { run: (s) => ops.copySelection(s, true, true), label: 'help.moveNoDialog', short: 'key.moveQuick' }, + rename: { run: (s) => ops.renameFocused(s), label: 'ops.rename', short: 'key.rename' }, + mkdir: { run: (s) => void ops.makeDir(s), label: 'ops.newFolder', short: 'key.mkdir' }, + delete: { run: (s) => void ops.deleteSelection(s), label: 'common.delete', short: 'key.delete' }, + deletePermanent: { run: (s) => void ops.deleteSelection(s, true), label: 'ops.deletePermanently', short: 'key.deletePermanent' }, + menu: { run: () => requestUi('menubar'), label: 'cmd.menu', short: 'key.menu' }, + quit: { run: () => void quit(), label: 'cmd.quit', short: 'key.quit', available: () => mode === 'desktop' }, + refresh: { run: (s) => void refresh(s), label: 'common.refresh', short: 'key.refresh' }, + toggleHidden: { run: () => toggleHidden(), label: 'view.showHidden', short: 'key.hidden' }, + siteManager: { run: () => openSiteManager(), label: 'session.newSession', short: 'key.connect' }, + disconnect: { run: disconnect, label: 'session.close', short: 'key.disconnect' }, + terminal: { run: (s) => ops.openTerminalHere(s), label: 'terminal.open', short: 'key.terminal', available: hasTerminal }, + toggleTerminal: { run: toggleTerminal, label: 'cmd.toggleTerminal', short: 'key.terminal', available: hasTerminal }, + find: { run: (s) => ops.findFiles(s), label: 'find.title', short: 'key.find' }, + focusPath: { run: (s) => focusPathBar(s), label: 'help.focusPath', short: 'key.path' }, + addBookmark: { run: (s) => void ops.addBookmark(s), label: 'bookmarks.add', short: 'key.bookmark' }, + hotlist: { run: (s) => requestUi(`dropdown:bookmarks-${s}`), label: 'cmd.hotlist', short: 'key.hotlist' }, + sync: { run: () => ops.synchronize(), label: 'sync.title', short: 'key.sync' }, + sidebar: { run: () => setLayout({ sidebarOpen: !useApp.getState().sidebarOpen }), label: 'sidebar.toggle', short: 'key.sidebar' }, + explorer: { run: () => toggleSidebar('explorer'), label: 'explorer.title', short: 'key.explorer' }, + dock: { run: () => toggleDock(), label: 'dock.title', short: 'key.dock' }, + back: { run: (s) => void goBack(s), label: 'nav.back', short: 'key.back' }, + forward: { run: (s) => void goForward(s), label: 'nav.forward', short: 'key.forward' }, + root: { run: (s) => void goRoot(s), label: 'nav.root', short: 'key.root' }, + parentDir: { run: (s) => void goUp(s), label: 'nav.up', short: 'key.up' }, + openDir: { run: openDirUnderCursor, label: 'cmd.openDir', short: 'key.open' }, + dirHistory: { run: dirHistory, label: 'cmd.dirHistory', short: 'key.history' }, + copyPath: { run: (s) => ops.copyPaths(s), label: 'ops.copyPath', short: 'key.copyPath' }, + preferences: { run: () => openSingleton('preferences', {}), label: 'prefs.title', short: 'key.config' }, + openFile: { run: () => ops.openFileDialog(), label: 'openFile.title', short: 'key.openFile' }, + fingerprints: { run: (s) => ops.compareFingerprints(s), label: 'fp.menu', short: 'key.fingerprints' }, + upload: { run: (s) => void ops.uploadFromComputer(s), label: 'web.upload', short: 'key.upload', available: web }, + properties: { run: (s) => void ops.showProperties(s), label: 'ops.properties', short: 'key.properties' }, + undo: { run: () => void undoLast(), label: 'undo.menu', short: 'key.undo' }, + sortName: { run: (s) => sortBy(s, 'name'), label: 'cmd.sortName', short: 'key.sortName' }, + sortExt: { run: (s) => sortBy(s, 'type'), label: 'cmd.sortExt', short: 'key.sortExt' }, + sortTime: { run: (s) => sortBy(s, 'modified'), label: 'cmd.sortTime', short: 'key.sortTime' }, + sortSize: { run: (s) => sortBy(s, 'size'), label: 'cmd.sortSize', short: 'key.sortSize' }, + swapPanels: { run: () => swapPanels(), label: 'view.swapPanels', short: 'key.swap' }, + toLeft: { run: (s) => showDirIn(s, 'left'), label: 'cmd.toLeft', short: 'key.toLeft' }, + toRight: { run: (s) => showDirIn(s, 'right'), label: 'cmd.toRight', short: 'key.toRight' }, + compareDirs: { run: () => toggleCompare(), label: 'compare.title', short: 'key.compare' }, + selectAll: { run: (s) => selectAll(s), label: 'panel.selectAll', short: 'key.selectAll' }, + selectNone: { run: (s) => selectNone(s), label: 'select.none', short: 'key.selectNone' }, + pack: { run: (s) => localOnly(s, ops.createArchive), label: 'archive.create', short: 'key.pack' }, + unpack: { run: (s) => localOnly(s, ops.extractArchive), label: 'archive.extractHere', short: 'key.unpack' }, + driveLeft: { run: () => requestUi('dropdown:session-left'), label: 'cmd.driveLeft', short: 'key.left' }, + driveRight: { run: () => requestUi('dropdown:session-right'), label: 'cmd.driveRight', short: 'key.right' }, + quickFilter: { run: (s) => requestUi(`filter:${s}`), label: 'panel.filter', short: 'key.filter' }, +}; + +export function isAvailable(id: CommandId): boolean { + const c = COMMANDS[id]; + return !c.available || c.available(); +} + +/** Runs a command for the active panel (or `side`). Returns false when it is not available. */ +export function runCommand(id: CommandId, side: Side = useApp.getState().activeSide): boolean { + if (!isAvailable(id)) return false; + COMMANDS[id].run(side); + return true; +} + +/** Puts the keyboard focus back on the file list of the active panel. */ +export function focusActivePanel() { + const side = useApp.getState().activeSide; + document.querySelector(`[data-panel="${side}"] .ft-body`)?.focus(); +} diff --git a/ui/src/actions/shortcuts.ts b/ui/src/actions/shortcuts.ts index 9af94af..7328c26 100644 --- a/ui/src/actions/shortcuts.ts +++ b/ui/src/actions/shortcuts.ts @@ -1,82 +1,55 @@ -// Global keyboard shortcuts (window level). Panel navigation keys live in FileTable. -import { isAnyDialogOpen, openSingleton } from '../store/dialogs'; +// Global keyboard shortcuts (window level), taken from the active keyboard layout (see +// lib/keymaps.ts). Panel navigation keys live in FileTable. +import { isAnyDialogOpen } from '../store/dialogs'; import { usePrompts } from '../store/misc'; import { useEditors } from '../store/editors'; -import { setLayout, toggleDock, toggleHidden, toggleSidebar, useApp } from '../store/app'; -import { goBack, goForward, goRoot, refresh, type Side } from '../store/panels'; +import { useApp } from '../store/app'; import { useContextMenu } from '../components/Menu'; -import { focusPathBar } from '../components/panel/PathBar'; -import * as ops from './fileOps'; -import { openSiteManager } from './sessions'; -import { undoLast } from './undo'; +import { comboFor, comboOf, keymapOf, type CommandId, type Keymap } from '../lib/keymaps'; +import { isAvailable, runCommand } from './commands'; -type Action = (side: Side, e: KeyboardEvent) => void; +export { comboOf }; const isMac = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform); export const MOD = isMac ? '⌘' : 'Ctrl'; -/** Display form of a shortcut ('Ctrl+Shift+S' -> '⌘⇧S' on macOS). */ +const KEY_NAMES: [RegExp, string][] = [ + [/ArrowLeft/g, '←'], + [/ArrowRight/g, '→'], + [/ArrowUp/g, '↑'], + [/ArrowDown/g, '↓'], + [/PageUp/g, 'PgUp'], + [/PageDown/g, 'PgDn'], + [/Num([+\-*/])/g, 'Num $1'], +]; + +/** Display form of a shortcut ('Ctrl+Shift+S' -> '⌘⇧S' on macOS, 'Alt+ArrowDown' -> 'Alt+↓'). */ export function keyLabel(combo: string): string { - if (!isMac) return combo; - return combo.replace(/Ctrl\+/g, '⌘').replace(/Shift\+/g, '⇧').replace(/Alt\+/g, '⌥'); + let s = combo; + for (const [re, name] of KEY_NAMES) s = s.replace(re, name); + if (!isMac) return s; + return s.replace(/Ctrl\+/g, '⌘').replace(/Shift\+/g, '⇧').replace(/Alt\+/g, '⌥'); } -const web = () => useApp.getState().info?.mode === 'web'; +/** The keyboard layout chosen in the preferences. */ +export function activeKeymap(): Keymap { + return keymapOf(useApp.getState().settings?.keymap); +} -export const BINDINGS: Record = { - F2: (s) => ops.renameFocused(s), - F3: (s) => ops.viewFocused(s), - F4: (s) => ops.editFocused(s), - 'Shift+F4': (s) => void ops.newFile(s), - F5: (s) => ops.copySelection(s, false), - 'Shift+F5': (s) => ops.copySelection(s, false, true), - F6: (s) => ops.copySelection(s, true), - 'Shift+F6': (s) => ops.copySelection(s, true, true), - F7: (s) => void ops.makeDir(s), - F8: (s) => void ops.deleteSelection(s), - Delete: (s) => void ops.deleteSelection(s), - // Shift: delete for good instead of moving to the trash. - 'Shift+F8': (s) => void ops.deleteSelection(s, true), - 'Shift+Delete': (s) => void ops.deleteSelection(s, true), - 'Ctrl+Z': () => void undoLast(), - 'Alt+Enter': (s) => void ops.showProperties(s), - 'Ctrl+R': (s) => void refresh(s), - F9: (s) => void refresh(s), - 'Ctrl+H': () => toggleHidden(), - 'Ctrl+N': () => openSiteManager(), - 'Ctrl+T': (s) => ops.openTerminalHere(s), - 'Ctrl+F': (s) => ops.findFiles(s), - 'Ctrl+L': (s) => focusPathBar(s), - 'Ctrl+D': (s) => void ops.addBookmark(s), - 'Ctrl+Shift+S': () => ops.synchronize(), - 'Ctrl+B': () => setLayout({ sidebarOpen: !useApp.getState().sidebarOpen }), - 'Ctrl+Shift+E': () => toggleSidebar('explorer'), - 'Ctrl+J': () => toggleDock(), - 'Alt+ArrowLeft': (s) => void goBack(s), - 'Alt+ArrowRight': (s) => void goForward(s), - 'Ctrl+\\': (s) => void goRoot(s), - 'Ctrl+Shift+C': (s) => ops.copyPaths(s), - 'Ctrl+,': () => openSingleton('preferences', {}), - 'Ctrl+P': () => ops.openFileDialog(), - 'Ctrl+K': (s) => ops.compareFingerprints(s), - 'Ctrl+U': (s) => { - if (web()) void ops.uploadFromComputer(s); - }, - F1: () => openSingleton('shortcuts', {}), -}; +/** Subscribes a component to the keyboard layout (re-renders when it changes). */ +export function useKeymap(): Keymap { + return keymapOf(useApp((s) => s.settings?.keymap)); +} -export function comboOf(e: KeyboardEvent): string { - const parts: string[] = []; - if (e.ctrlKey || e.metaKey) parts.push('Ctrl'); - if (e.altKey) parts.push('Alt'); - if (e.shiftKey) parts.push('Shift'); - let k = e.key; - if (k.length === 1) k = k.toUpperCase(); - if (k === 'Del') k = 'Delete'; - parts.push(k); - return parts.join('+'); +/** Display form of the key that runs `cmd` in the active layout, if there is one. */ +export function shortcutLabel(cmd: CommandId, km: Keymap = activeKeymap()): string | undefined { + const c = comboFor(km, cmd); + return c ? keyLabel(c) : undefined; } +/** Commands that also work while typing in a plain input field outside of dialogs. */ +const ALWAYS: ReadonlySet = new Set(['sidebar', 'dock', 'explorer']); + function blocked(target: EventTarget | null, combo: string): boolean { if (isAnyDialogOpen() || usePrompts.getState().queue.length > 0) return true; if (useEditors.getState().visible) return true; @@ -93,20 +66,18 @@ export function installShortcuts(): () => void { const onKey = (e: KeyboardEvent) => { if (e.defaultPrevented || e.isComposing) return; const combo = comboOf(e); - // a few shortcuts also work while typing in inputs outside of dialogs - const always = combo === 'Ctrl+B' || combo === 'Ctrl+J' || combo === 'Ctrl+Shift+E'; + const cmd = activeKeymap().bindings[combo]; + if (!cmd) return; const target = e.target as HTMLElement | null; if (blocked(target, combo)) { const inPlainInput = !!target?.closest?.('input, select') && !isAnyDialogOpen() && !useEditors.getState().visible && !usePrompts.getState().queue.length; - if (!(always && inPlainInput)) return; + if (!(ALWAYS.has(cmd) && inPlainInput)) return; } - const action = BINDINGS[combo]; - if (!action) return; + if (!isAvailable(cmd)) return; e.preventDefault(); e.stopPropagation(); - action(useApp.getState().activeSide, e); + runCommand(cmd); }; window.addEventListener('keydown', onKey); return () => window.removeEventListener('keydown', onKey); } - diff --git a/ui/src/api/mock.ts b/ui/src/api/mock.ts index 41cb625..2360b3e 100644 --- a/ui/src/api/mock.ts +++ b/ui/src/api/mock.ts @@ -444,6 +444,8 @@ function defaultSettings(): T.Settings { useTrash: true, restoreSessions: true, resumeJobs: true, + keymap: 'norton', + showKeyBar: true, transfer: defaultTransfer(), discovery: { enabled: true, port: 8823, instanceName: 'demo-workstation', intervalSecs: 30 }, server: { autoStart: false, bind: '0.0.0.0', port: 8822, tls: true, allowTerminal: true }, diff --git a/ui/src/api/types.ts b/ui/src/api/types.ts index 1a01d98..7758c11 100644 --- a/ui/src/api/types.ts +++ b/ui/src/api/types.ts @@ -432,6 +432,10 @@ export interface Settings { restoreSessions: boolean; /** Continue interrupted transfers after a restart (otherwise they come back paused). */ resumeJobs: boolean; + /** Keyboard layout (see lib/keymaps.ts). */ + keymap: 'norton' | 'total' | 'rust'; + /** Show the function key bar (F1–F10) above the status bar. */ + showKeyBar: boolean; transfer: TransferOptions; discovery: { enabled: boolean; port: number; instanceName: string; intervalSecs: number }; server: { autoStart: boolean; bind: string; port: number; tls: boolean; allowTerminal: boolean }; diff --git a/ui/src/components/KeyBar.tsx b/ui/src/components/KeyBar.tsx new file mode 100644 index 0000000..57cd6d7 --- /dev/null +++ b/ui/src/components/KeyBar.tsx @@ -0,0 +1,77 @@ +// The function key bar of the classic commanders ("1Help 2Menu 3View …"): shows what F1–F10 +// do in the active keyboard layout, switches to the Shift/Ctrl/Alt layer while a modifier is +// held, and runs the command when a key is clicked. +import { useEffect, useState } from 'react'; +import { useT } from '../i18n'; +import { KEY_BAR_KEYS, keyBarLayer } from '../lib/keymaps'; +import { useApp } from '../store/app'; +import { COMMANDS, isAvailable, runCommand } from '../actions/commands'; +import { keyLabel, useKeymap } from '../actions/shortcuts'; +import { cx } from './ui'; + +interface Mods { + ctrl: boolean; + alt: boolean; + shift: boolean; +} + +const NONE: Mods = { ctrl: false, alt: false, shift: false }; + +function useHeldModifiers(): Mods { + const [mods, setMods] = useState(NONE); + useEffect(() => { + const update = (e: KeyboardEvent) => { + const next = { ctrl: e.ctrlKey || e.metaKey, alt: e.altKey, shift: e.shiftKey }; + setMods((p) => (p.ctrl === next.ctrl && p.alt === next.alt && p.shift === next.shift ? p : next)); + }; + const reset = () => setMods(NONE); + window.addEventListener('keydown', update, true); + window.addEventListener('keyup', update, true); + window.addEventListener('blur', reset); + return () => { + window.removeEventListener('keydown', update, true); + window.removeEventListener('keyup', update, true); + window.removeEventListener('blur', reset); + }; + }, []); + return mods; +} + +export function KeyBar() { + const t = useT(); + const km = useKeymap(); + const show = useApp((s) => s.settings?.showKeyBar ?? true); + const narrow = useApp((s) => s.narrow); + // availability depends on the mode and the features of the backend + useApp((s) => s.info); + const mods = useHeldModifiers(); + if (!show || narrow) return null; + const layer = keyBarLayer(mods); + return ( +
+ {KEY_BAR_KEYS.map((k, i) => { + const combo = layer + k; + const cmd = km.bindings[combo]; + const on = !!cmd && isAvailable(cmd); + return ( + + ); + })} +
+ ); +} diff --git a/ui/src/components/MenuBar.tsx b/ui/src/components/MenuBar.tsx index efbfaaa..c2b83be 100644 --- a/ui/src/components/MenuBar.tsx +++ b/ui/src/components/MenuBar.tsx @@ -7,13 +7,16 @@ import { Undo2, } from 'lucide-react'; import { call, mode, webLogout } from '../api/client'; -import { tr, useT, type TFn } from '../i18n'; +import { useT, type TFn } from '../i18n'; import { cycleTheme, saveSettings, setLayout, setTheme, toggleDock, toggleHidden, toggleSidebar, useApp } from '../store/app'; import { openDialog, openSingleton } from '../store/dialogs'; -import { clearCompare, compareDirectories, getPanel, navigate, other, patchPanel, refresh, selectAll, selectNone, invertSelection, setSort, usePanels, type SortKey } from '../store/panels'; +import { getPanel, navigate, other, patchPanel, refresh, selectAll, selectNone, invertSelection, setSort, usePanels, type SortKey } from '../store/panels'; import * as ops from '../actions/fileOps'; import { closeSession, openSiteManager, reconnectSession, showSessionInfo } from '../actions/sessions'; -import { keyLabel } from '../actions/shortcuts'; +import { keyLabel, shortcutLabel } from '../actions/shortcuts'; +import { swapPanels, toggleCompare } from '../actions/commands'; +import { KEYMAP_IDS, keymapOf } from '../lib/keymaps'; +import { rememberFocus, useOnUiRequest } from '../store/uiRequests'; import { useConnection } from '../api/client'; import { toast } from '../store/toasts'; import { commandsSubmenu } from './panel/panelMenu'; @@ -21,12 +24,6 @@ import { MenuList, type MenuItem } from './Menu'; import { cx, IconButton } from './ui'; import { undoLabel, undoLast, useUndo } from '../actions/undo'; -function swapPanels() { - const { left, right } = usePanels.getState(); - void navigate('left', right.session, right.path, { select: right.cursor }); - void navigate('right', left.session, left.path, { select: left.cursor }); -} - function samePath() { const side = useApp.getState().activeSide; const p = getPanel(side); @@ -35,6 +32,7 @@ function samePath() { export function buildMenus(t: TFn): { id: string; label: string; items: () => MenuItem[] }[] { const k = keyLabel; + const sc = (id: Parameters[0]) => shortcutLabel(id); return [ { id: 'session', @@ -46,12 +44,12 @@ export function buildMenus(t: TFn): { id: string; label: string; items: () => Me const remote = sid !== 'local'; const webUi = st.info?.mode === 'web'; return [ - { label: t('session.newSession'), icon: Plus, shortcut: k('Ctrl+N'), onClick: () => openSiteManager(), testId: 'menu-new-session' }, + { label: t('session.newSession'), icon: Plus, shortcut: sc('siteManager'), onClick: () => openSiteManager(), testId: 'menu-new-session' }, { label: t('sites.manager'), icon: Network, onClick: () => openSiteManager() }, { separator: true }, { label: t('session.info'), icon: Info, disabled: !remote, onClick: () => showSessionInfo(sid) }, { label: t('session.reconnect'), icon: Repeat, disabled: !remote, onClick: () => void reconnectSession(sid) }, - { label: t('session.close'), icon: Unplug, disabled: !remote, onClick: () => void closeSession(sid) }, + { label: t('session.close'), icon: Unplug, disabled: !remote, shortcut: sc('disconnect'), onClick: () => void closeSession(sid) }, { separator: true }, { label: t('tunnels.title'), icon: Route, onClick: () => openSingleton('tunnels', { session: remote ? sid : undefined }) }, { label: t('share.title'), icon: Share2, hidden: webUi, onClick: () => openSingleton('share', {}) }, @@ -69,28 +67,28 @@ export function buildMenus(t: TFn): { id: string; label: string; items: () => Me const webUi = useApp.getState().info?.mode === 'web'; return [ { label: t('ops.open'), icon: FolderOpen, shortcut: 'Enter', onClick: () => ops.openFocused(side) }, - { label: t('ops.edit'), icon: Edit3, shortcut: 'F4', onClick: () => ops.editFocused(side) }, - { label: t('ops.view'), icon: Eye, shortcut: 'F3', onClick: () => ops.viewFocused(side) }, - { label: t('openFile.menu'), icon: FileSearch, shortcut: k('Ctrl+P'), onClick: () => ops.openFileDialog(), testId: 'menu-open-file' }, + { label: t('ops.edit'), icon: Edit3, shortcut: sc('edit'), onClick: () => ops.editFocused(side) }, + { label: t('ops.view'), icon: Eye, shortcut: sc('view'), onClick: () => ops.viewFocused(side) }, + { label: t('openFile.menu'), icon: FileSearch, shortcut: sc('openFile'), onClick: () => ops.openFileDialog(), testId: 'menu-open-file' }, { separator: true }, - { label: t('ops.copy'), icon: Copy, shortcut: 'F5', onClick: () => ops.copySelection(side, false) }, - { label: t('ops.move'), icon: MoveRight, shortcut: 'F6', onClick: () => ops.copySelection(side, true) }, - { label: t('ops.rename'), icon: Pencil, shortcut: 'F2', onClick: () => ops.renameFocused(side) }, - { label: undoLabel() ?? t('undo.menu'), icon: Undo2, shortcut: k('Ctrl+Z'), disabled: !useUndo.getState().last, onClick: () => void undoLast(), testId: 'menu-undo' }, - { label: ops.usesTrash(getPanel(side).session) ? t('ops.trashTitle') : t('common.delete'), icon: Trash2, shortcut: 'F8', danger: true, onClick: () => void ops.deleteSelection(side) }, - { label: t('ops.deletePermanently'), icon: Trash2, shortcut: k('Shift+Delete'), danger: true, hidden: !ops.usesTrash(getPanel(side).session), onClick: () => void ops.deleteSelection(side, true) }, + { label: t('ops.copy'), icon: Copy, shortcut: sc('copy'), onClick: () => ops.copySelection(side, false) }, + { label: t('ops.move'), icon: MoveRight, shortcut: sc('move'), onClick: () => ops.copySelection(side, true) }, + { label: t('ops.rename'), icon: Pencil, shortcut: sc('rename'), onClick: () => ops.renameFocused(side) }, + { label: undoLabel() ?? t('undo.menu'), icon: Undo2, shortcut: sc('undo'), disabled: !useUndo.getState().last, onClick: () => void undoLast(), testId: 'menu-undo' }, + { label: ops.usesTrash(getPanel(side).session) ? t('ops.trashTitle') : t('common.delete'), icon: Trash2, shortcut: sc('delete'), danger: true, onClick: () => void ops.deleteSelection(side) }, + { label: t('ops.deletePermanently'), icon: Trash2, shortcut: sc('deletePermanent'), danger: true, hidden: !ops.usesTrash(getPanel(side).session), onClick: () => void ops.deleteSelection(side, true) }, { separator: true }, - { label: t('ops.newFolder'), icon: FolderPlus, shortcut: 'F7', onClick: () => void ops.makeDir(side) }, - { label: t('ops.newFile'), icon: FilePlus, shortcut: k('Shift+F4'), onClick: () => void ops.newFile(side) }, + { label: t('ops.newFolder'), icon: FolderPlus, shortcut: sc('mkdir'), onClick: () => void ops.makeDir(side) }, + { label: t('ops.newFile'), icon: FilePlus, shortcut: sc('newFile'), onClick: () => void ops.newFile(side) }, { label: t('ops.createLink'), icon: Link2, onClick: () => ops.createSymlink(side) }, { separator: true }, - { label: t('web.upload'), icon: Upload, shortcut: k('Ctrl+U'), hidden: !webUi, onClick: () => void ops.uploadFromComputer(side) }, + { label: t('web.upload'), icon: Upload, shortcut: sc('upload'), hidden: !webUi, onClick: () => void ops.uploadFromComputer(side) }, { label: t('web.uploadFolder'), icon: FolderInput, hidden: !webUi, onClick: () => void ops.uploadFromComputer(side, true) }, { label: t('web.download'), icon: Download, hidden: !webUi, onClick: () => void ops.downloadToComputer(side) }, { separator: true }, - { label: t('ops.copyPath'), icon: ClipboardCopy, shortcut: k('Ctrl+Shift+C'), onClick: () => ops.copyPaths(side) }, + { label: t('ops.copyPath'), icon: ClipboardCopy, shortcut: sc('copyPath'), onClick: () => ops.copyPaths(side) }, { label: t('ops.checksum'), icon: Hash, onClick: () => ops.showChecksum(side) }, - { label: t('ops.properties'), icon: Info, shortcut: k('Alt+Enter'), onClick: () => void ops.showProperties(side) }, + { label: t('ops.properties'), icon: Info, shortcut: sc('properties'), onClick: () => void ops.showProperties(side) }, ]; }, }, @@ -102,16 +100,16 @@ export function buildMenus(t: TFn): { id: string; label: string; items: () => Me const side = st.activeSide; const comparing = !!getPanel('left').compare; return [ - { label: t('find.title'), icon: Search, shortcut: k('Ctrl+F'), onClick: () => ops.findFiles(side) }, - { label: t('sync.title'), icon: FolderSync, shortcut: k('Ctrl+Shift+S'), onClick: () => ops.synchronize(), testId: 'menu-sync' }, + { label: t('find.title'), icon: Search, shortcut: sc('find'), onClick: () => ops.findFiles(side) }, + { label: t('sync.title'), icon: FolderSync, shortcut: sc('sync'), onClick: () => ops.synchronize(), testId: 'menu-sync' }, { label: t('watch.title'), icon: Radar, onClick: () => openDialog('keepUpToDate', {}) }, - { label: comparing ? t('compare.clear') : t('compare.title'), icon: GitCompareArrows, onClick: () => (comparing ? clearCompare() : runCompare()) }, - { label: t('fp.menu'), icon: Fingerprint, shortcut: k('Ctrl+K'), onClick: () => ops.compareFingerprints(side), testId: 'menu-fingerprints' }, + { label: comparing ? t('compare.clear') : t('compare.title'), icon: GitCompareArrows, shortcut: sc('compareDirs'), onClick: () => toggleCompare() }, + { label: t('fp.menu'), icon: Fingerprint, shortcut: sc('fingerprints'), onClick: () => ops.compareFingerprints(side), testId: 'menu-fingerprints' }, { label: t('diff.menu'), icon: GitCompare, onClick: () => ops.diffWithOtherPanel(side) }, { label: t('panel.syncBrowse'), icon: ArrowLeftRight, checked: st.syncBrowse, onClick: () => setLayout({ syncBrowse: !st.syncBrowse }) }, { separator: true }, - { label: t('terminal.open'), icon: SquareTerminal, shortcut: k('Ctrl+T'), hidden: !st.info?.features.terminal, onClick: () => ops.openTerminalHere(side) }, - { label: t('commands.title'), icon: Command, submenu: commandsSubmenu(side) }, + { label: t('terminal.open'), icon: SquareTerminal, shortcut: sc('terminal'), hidden: !st.info?.features.terminal, onClick: () => ops.openTerminalHere(side) }, + { label: t('commands.title'), icon: Command, shortcut: sc('userMenu'), submenu: commandsSubmenu(side) }, { separator: true }, { label: t('select.title'), @@ -130,8 +128,8 @@ export function buildMenus(t: TFn): { id: string; label: string; items: () => Me icon: Archive, hidden: getPanel(side).session !== 'local', submenu: [ - { label: t('archive.extractHere'), onClick: () => void ops.extractArchive(side) }, - { label: t('archive.create'), onClick: () => ops.createArchive(side) }, + { label: t('archive.extractHere'), shortcut: sc('unpack'), onClick: () => void ops.extractArchive(side) }, + { label: t('archive.create'), shortcut: sc('pack'), onClick: () => ops.createArchive(side) }, ], }, ]; @@ -145,13 +143,16 @@ export function buildMenus(t: TFn): { id: string; label: string; items: () => Me const side = st.activeSide; const p = getPanel(side); const theme = st.settings?.theme ?? 'system'; - const sortItem = (key: SortKey, label: string): MenuItem => ({ label, checked: p.sortKey === key, onClick: () => setSort(side, key) }); + const sortShortcut: Partial> = { name: sc('sortName'), type: sc('sortExt'), modified: sc('sortTime'), size: sc('sortSize') }; + const sortItem = (key: SortKey, label: string): MenuItem => ({ label, checked: p.sortKey === key, shortcut: sortShortcut[key], onClick: () => setSort(side, key) }); + const keymap = keymapOf(st.settings?.keymap).id; return [ - { label: t('view.showHidden'), icon: st.settings?.showHidden ? Eye : EyeOff, checked: st.settings?.showHidden, shortcut: k('Ctrl+H'), onClick: () => toggleHidden() }, - { label: t('sidebar.toggle'), icon: PanelLeft, checked: st.sidebarOpen, shortcut: k('Ctrl+B'), onClick: () => setLayout({ sidebarOpen: !st.sidebarOpen }) }, + { label: t('view.showHidden'), icon: st.settings?.showHidden ? Eye : EyeOff, checked: st.settings?.showHidden, shortcut: sc('toggleHidden'), onClick: () => toggleHidden() }, + { label: t('sidebar.toggle'), icon: PanelLeft, checked: st.sidebarOpen, shortcut: sc('sidebar'), onClick: () => setLayout({ sidebarOpen: !st.sidebarOpen }) }, { label: t('nearby.title'), icon: Radar, checked: st.sidebarOpen && st.sidebarView === 'nearby', onClick: () => toggleSidebar('nearby') }, - { label: t('explorer.title'), icon: FolderTree, checked: st.sidebarOpen && st.sidebarView === 'explorer', shortcut: k('Ctrl+Shift+E'), onClick: () => toggleSidebar('explorer'), testId: 'menu-explorer' }, - { label: t('dock.title'), icon: PanelBottom, checked: st.dockOpen, shortcut: k('Ctrl+J'), onClick: () => toggleDock() }, + { label: t('explorer.title'), icon: FolderTree, checked: st.sidebarOpen && st.sidebarView === 'explorer', shortcut: sc('explorer'), onClick: () => toggleSidebar('explorer'), testId: 'menu-explorer' }, + { label: t('dock.title'), icon: PanelBottom, checked: st.dockOpen, shortcut: sc('dock'), onClick: () => toggleDock() }, + { label: t('keybar.show'), icon: Keyboard, checked: st.settings?.showKeyBar ?? true, onClick: () => st.settings && void saveSettings({ ...st.settings, showKeyBar: !(st.settings.showKeyBar ?? true) }), testId: 'menu-keybar' }, { separator: true }, { label: t('view.sortBy'), @@ -172,6 +173,17 @@ export function buildMenus(t: TFn): { id: string; label: string; items: () => Me { label: t('theme.dark'), icon: Moon, checked: theme === 'dark', onClick: () => setTheme('dark') }, ], }, + { + label: t('keymap.title'), + icon: Keyboard, + testId: 'menu-keymap', + submenu: KEYMAP_IDS.map((id) => ({ + label: t(`keymap.${id}`), + checked: keymap === id, + testId: `menu-keymap-${id}`, + onClick: () => st.settings && void saveSettings({ ...st.settings, keymap: id }), + })), + }, { label: t('view.language'), submenu: (['auto', 'en', 'de'] as const).map((l) => ({ @@ -181,10 +193,10 @@ export function buildMenus(t: TFn): { id: string; label: string; items: () => Me })), }, { separator: true }, - { label: t('view.swapPanels'), icon: ArrowLeftRight, onClick: swapPanels }, + { label: t('view.swapPanels'), icon: ArrowLeftRight, shortcut: sc('swapPanels'), onClick: swapPanels }, { label: t('view.samePath'), icon: Columns2, onClick: samePath }, { label: t('view.equalPanels'), icon: Columns2, onClick: () => setLayout({ split: 0.5 }) }, - { label: t('common.refresh'), icon: RefreshCw, shortcut: k('Ctrl+R'), onClick: () => void refresh(side) }, + { label: t('common.refresh'), icon: RefreshCw, shortcut: sc('refresh'), onClick: () => void refresh(side) }, ]; }, }, @@ -195,15 +207,15 @@ export function buildMenus(t: TFn): { id: string; label: string; items: () => Me const st = useApp.getState(); const webUi = st.info?.mode === 'web'; return [ - { label: t('prefs.title'), icon: Settings, shortcut: k('Ctrl+,'), onClick: () => openSingleton('preferences', {}), testId: 'menu-preferences' }, + { label: t('prefs.title'), icon: Settings, shortcut: sc('preferences'), onClick: () => openSingleton('preferences', {}), testId: 'menu-preferences' }, { label: t('commands.manage'), icon: Command, onClick: () => openDialog('commands', { side: st.activeSide }) }, - { label: t('bookmarks.add'), icon: Bookmark, shortcut: k('Ctrl+D'), onClick: () => void ops.addBookmark(st.activeSide) }, + { label: t('bookmarks.add'), icon: Bookmark, shortcut: sc('addBookmark'), onClick: () => void ops.addBookmark(st.activeSide) }, { label: t('tunnels.title'), icon: Route, onClick: () => openSingleton('tunnels', {}) }, { label: t('prefs.knownHosts'), icon: Lock, onClick: () => openSingleton('preferences', { tab: 'security' }) }, { separator: true }, { label: t('share.title'), icon: Share2, hidden: webUi, onClick: () => openSingleton('share', {}) }, { label: t('nearby.title'), icon: Radar, onClick: () => setLayout({ sidebarOpen: true, sidebarView: 'nearby' }) }, - { label: t('explorer.title'), icon: FolderTree, shortcut: k('Ctrl+Shift+E'), onClick: () => setLayout({ sidebarOpen: true, sidebarView: 'explorer' }) }, + { label: t('explorer.title'), icon: FolderTree, shortcut: sc('explorer'), onClick: () => setLayout({ sidebarOpen: true, sidebarView: 'explorer' }) }, ]; }, }, @@ -211,18 +223,13 @@ export function buildMenus(t: TFn): { id: string; label: string; items: () => Me id: 'help', label: t('menu.help'), items: () => [ - { label: t('help.shortcuts'), icon: Keyboard, shortcut: 'F1', onClick: () => openSingleton('shortcuts', {}) }, + { label: t('help.shortcuts'), icon: Keyboard, shortcut: sc('help'), onClick: () => openSingleton('shortcuts', {}) }, { label: t('help.about'), icon: CircleHelp, onClick: () => openSingleton('about', {}) }, ], }, ]; } -function runCompare() { - const n = compareDirectories(); - toast.info(n ? tr('compare.found', { n }) : tr('compare.identical')); -} - export function MenuBar() { const t = useT(); const [open, setOpen] = useState<{ id: string; rect: DOMRect } | null>(null); @@ -239,6 +246,7 @@ export function MenuBar() { const offline = useConnection((s) => s.state === 'offline'); const menus = buildMenus(t); const side = () => useApp.getState().activeSide; + const sc = (id: Parameters[0]) => shortcutLabel(id, keymapOf(settings?.keymap)); const openMenu = (id: string) => { const el = refs.current[id]; @@ -250,6 +258,22 @@ export function MenuBar() { openMenu(menus[(i + dir + menus.length) % menus.length].id); }; + // F9 (PullDn) in the classic layouts: open the first menu, keyboard-navigable; closing it + // gives the focus back to the file list + const restoreFocus = useRef<(() => void) | null>(null); + const close = () => { + setOpen(null); + restoreFocus.current?.(); + restoreFocus.current = null; + }; + useOnUiRequest('menubar', () => { + if (!open) restoreFocus.current = rememberFocus(); + if (narrow) { + const el = refs.current.all; + if (el) setOpen({ id: 'all', rect: el.getBoundingClientRect() }); + } else openMenu(menus[0].id); + }); + const ThemeIcon = settings?.theme === 'dark' ? Moon : settings?.theme === 'light' ? Sun : SunMoon; const current = open && (open.id === 'all' ? null : menus.find((m) => m.id === open.id)); @@ -290,48 +314,48 @@ export function MenuBar() { )}
- openSiteManager()} data-testid="tb-new-session" /> + openSiteManager()} data-testid="tb-new-session" /> - ops.copySelection(side(), false)} data-testid="tb-copy" /> - ops.copySelection(side(), true)} className="hide-narrow" /> - void ops.makeDir(side())} className="hide-narrow" /> - void ops.deleteSelection(side())} className="hide-narrow" /> - ops.editFocused(side())} className="hide-narrow" /> - void ops.showProperties(side())} className="hide-narrow" /> + ops.copySelection(side(), false)} data-testid="tb-copy" /> + ops.copySelection(side(), true)} className="hide-narrow" /> + void ops.makeDir(side())} className="hide-narrow" /> + void ops.deleteSelection(side())} className="hide-narrow" /> + ops.editFocused(side())} className="hide-narrow" /> + void ops.showProperties(side())} className="hide-narrow" /> {webUi && ( <> - void ops.uploadFromComputer(side())} data-testid="tb-upload" /> + void ops.uploadFromComputer(side())} data-testid="tb-upload" /> void ops.downloadToComputer(side())} /> )} - ops.findFiles(side())} className="hide-narrow" /> - ops.synchronize()} data-testid="tb-sync" className="hide-narrow" /> - (comparing ? clearCompare() : runCompare())} className="hide-narrow" /> + ops.findFiles(side())} className="hide-narrow" /> + ops.synchronize()} data-testid="tb-sync" className="hide-narrow" /> + toggleCompare()} className="hide-narrow" /> setLayout({ syncBrowse: !syncBrowse })} className="hide-narrow" /> - {terminal && ops.openTerminalHere(side())} data-testid="tb-terminal" />} + {terminal && ops.openTerminalHere(side())} data-testid="tb-terminal" />}
{narrow ? ( // one button on phones: the sidebar's own tabs switch the view setLayout({ sidebarOpen: !sidebarOpen })} data-testid="tb-sidebar" /> ) : ( <> - toggleSidebar('explorer')} data-testid="tb-explorer" /> + toggleSidebar('explorer')} data-testid="tb-explorer" /> toggleSidebar('nearby')} data-testid="tb-nearby" /> )} - toggleDock()} className="hide-narrow" /> + toggleDock()} className="hide-narrow" /> cycleTheme()} data-testid="tb-theme" /> - openSingleton('preferences', {})} /> + openSingleton('preferences', {})} />
{open && ( <> -
setOpen(null)} /> +
{open.id === 'all' ? ( - ({ label: m.label, submenu: m.items() }))} x={open.rect.left} y={open.rect.bottom} anchor={open.rect} onClose={() => setOpen(null)} /> + ({ label: m.label, submenu: m.items() }))} x={open.rect.left} y={open.rect.bottom} anchor={open.rect} onClose={close} /> ) : ( - current && setOpen(null)} onNavigate={navigateMenu} /> + current && )} )} diff --git a/ui/src/components/dialogs/PreferencesDialog.tsx b/ui/src/components/dialogs/PreferencesDialog.tsx index 7f77718..c6c1e41 100644 --- a/ui/src/components/dialogs/PreferencesDialog.tsx +++ b/ui/src/components/dialogs/PreferencesDialog.tsx @@ -12,6 +12,7 @@ import { useNearby } from '../../store/misc'; import { attempt, toast } from '../../store/toasts'; import { Badge, Button, Checkbox, Dialog, DialogButtons, Field, IconButton, NumberInput, Segmented, Select, Spinner, Tabs, TextInput, type TabDef } from '../ui'; import { TransferOptionsForm } from './common'; +import { KEYMAP_IDS } from '../../lib/keymaps'; type Tab = 'general' | 'transfer' | 'discovery' | 'server' | 'editor' | 'terminal' | 'security'; @@ -225,9 +226,19 @@ export default function PreferencesDialog({ props, close }: { props: DialogProps set('sizeFormat', v)} options={[{ value: 'auto', label: t('prefs.size.auto') }, { value: 'bytes', label: t('prefs.size.bytes') }]} /> + + +
set('showHidden', v)} /> + set('showKeyBar', v)} /> set('confirmDelete', v)} /> {!web && set('useTrash', v)} />} set('confirmOverwrite', v)} /> diff --git a/ui/src/components/dialogs/SmallDialogs.tsx b/ui/src/components/dialogs/SmallDialogs.tsx index 9820923..3c99938 100644 --- a/ui/src/components/dialogs/SmallDialogs.tsx +++ b/ui/src/components/dialogs/SmallDialogs.tsx @@ -5,16 +5,18 @@ import { } from 'lucide-react'; import type { ChecksumAlgo, ExecOutput, Peer, SessionInfo } from '../../api/types'; import { call, mode } from '../../api/client'; -import { useT } from '../../i18n'; +import { useT, type TKey } from '../../i18n'; import * as P from '../../lib/paths'; -import { useApp } from '../../store/app'; +import { patchSettings, useApp } from '../../store/app'; import type { ConfirmProps, DialogPropsMap, InputProps } from '../../store/dialogs'; import { navigate, getPanel, selectByMask, type Side } from '../../store/panels'; import { attempt, toast } from '../../store/toasts'; import { copyText } from '../../actions/fileOps'; import { connectPeer } from '../../actions/sessions'; -import { keyLabel } from '../../actions/shortcuts'; -import { Badge, Button, Checkbox, Dialog, DialogButtons, Field, Segmented, Spinner, TextInput } from '../ui'; +import { keyLabel, useKeymap } from '../../actions/shortcuts'; +import { COMMANDS, isAvailable } from '../../actions/commands'; +import { groupedBindings, KEYMAP_IDS, type KeymapId } from '../../lib/keymaps'; +import { Badge, Button, Checkbox, Dialog, DialogButtons, Field, Segmented, Select, Spinner, TextInput } from '../ui'; type DP = { props: DialogPropsMap[K]; close: () => void }; @@ -330,30 +332,66 @@ export function AboutDialog({ close }: DP<'about'>) { ); } -const SHORTCUT_DOCS: [string, string][] = [ - ['F2', 'ops.rename'], ['F3', 'ops.view'], ['F4', 'ops.edit'], ['Shift+F4', 'ops.newFile'], ['F5', 'ops.copy'], ['Shift+F5', 'help.copyNoDialog'], - ['F6', 'ops.move'], ['Shift+F6', 'help.moveNoDialog'], ['F7', 'ops.newFolder'], ['F8', 'common.delete'], ['Shift+Delete', 'ops.deletePermanently'], ['Ctrl+Z', 'undo.menu'], ['Alt+Enter', 'ops.properties'], - ['Ctrl+R', 'common.refresh'], ['Ctrl+H', 'view.showHidden'], ['Ctrl+N', 'session.newSession'], ['Ctrl+T', 'terminal.open'], ['Ctrl+F', 'find.title'], - ['Ctrl+L', 'help.focusPath'], ['Ctrl+D', 'bookmarks.add'], ['Ctrl+Shift+S', 'sync.title'], ['Ctrl+B', 'sidebar.toggle'], ['Ctrl+Shift+E', 'explorer.title'], ['Ctrl+J', 'dock.title'], - ['Ctrl+Shift+C', 'ops.copyPath'], ['Ctrl+,', 'prefs.title'], ['Alt+←/→', 'help.backForward'], - ['Tab', 'help.switchPanel'], ['Insert / Space', 'help.toggleSelect'], ['Ctrl+A', 'panel.selectAll'], ['+ / −', 'select.byMask'], ['*', 'select.invert'], - ['Backspace', 'nav.up'], ['Enter', 'ops.open'], ['A–Z', 'help.typeAhead'], ['Ctrl+P', 'openFile.title'], ['Ctrl+K', 'fp.menu'], +/** Keys of the file panels; the same in every keyboard layout. */ +const PANEL_DOCS: [string, TKey][] = [ + ['Tab', 'help.switchPanel'], ['Enter', 'ops.open'], ['Backspace', 'nav.up'], ['Insert / Space', 'help.toggleSelect'], + ['Ctrl+A', 'panel.selectAll'], ['Ctrl+Shift+A', 'select.none'], ['+ / −', 'select.byMask'], ['*', 'select.invert'], + ['A–Z', 'help.typeAhead'], ['Shift+F10', 'help.contextMenu'], +]; + +const EDITOR_DOCS: [string, TKey][] = [ ['Ctrl+S', 'editor.save'], ['Shift+Alt+F', 'editor.format'], ['Ctrl+G', 'editor.goToLine'], ['Ctrl+/', 'editor.tools.comment'], ['Ctrl+Shift+M', 'editor.problems'], ['F8', 'help.nextProblem'], ['Ctrl+= / Ctrl+-', 'help.editorZoom'], ]; +function ShortcutRows({ rows }: { rows: { keys: string; label: string; extra?: string }[] }) { + return ( +
+ {rows.map((r) => ( +
+ {r.keys} + + {r.label} + {r.extra && ( + + {' '}* + + )} + +
+ ))} +
+ ); +} + export function ShortcutsDialog({ close }: DP<'shortcuts'>) { const t = useT(); + const km = useKeymap(); + useApp((s) => s.info); // availability of commands + const commands = groupedBindings(km) + .filter((g) => isAvailable(g.cmd)) + .map((g) => ({ keys: g.combos.map(keyLabel).join(' / '), label: t(COMMANDS[g.cmd].label), extra: g.extra ? t('help.extra') : undefined })); + const quick = km.quickSearch === 'alt' ? 'Alt+A–Z' : km.quickSearch === 'ctrlAlt' ? 'Ctrl+Alt+A–Z' : null; + const panel = PANEL_DOCS.map(([k, label]) => ({ keys: keyLabel(k), label: t(label) })); + if (quick) panel.splice(9, 0, { keys: keyLabel(quick), label: t('help.quickSearch') }); return ( -
}> -
- {SHORTCUT_DOCS.map(([k, label]) => ( -
- {keyLabel(k)} - {t(label as Parameters[0])} -
- ))} -
+
}> + + + +
{t('help.layoutKeys')}
+ + {km.extras.length > 0 &&

{t('help.extraNote')}

} +
{t('help.panelKeys')}
+ +
{t('help.editorKeys')}
+ ({ keys: keyLabel(k), label: t(label) }))} /> ); } diff --git a/ui/src/components/panel/FileTable.tsx b/ui/src/components/panel/FileTable.tsx index 2ad51a7..9658d19 100644 --- a/ui/src/components/panel/FileTable.tsx +++ b/ui/src/components/panel/FileTable.tsx @@ -8,6 +8,8 @@ import { CATEGORY_ICON, categoryOf, isDirLike } from '../../lib/fileTypes'; import { formatDate, formatPerms, formatSize } from '../../lib/format'; import * as P from '../../lib/paths'; import { load, save } from '../../lib/storage'; +import { quickSearchChar } from '../../lib/keymaps'; +import { activeKeymap } from '../../actions/shortcuts'; import { setActiveSide, useApp } from '../../store/app'; import { allRows, extendRange, goHome, goUp, invertSelection, other, PARENT, patchPanel, refresh, selectAll, selectNone, selectRange, @@ -343,16 +345,22 @@ export function FileTable({ side, active }: { side: Side; active: boolean }) { } switch (e.key) { case 'ArrowDown': - moveCursor(cursorIdx < 0 ? 0 : cur + 1, e.shiftKey); + // Alt+↓ (folder history) belongs to the keyboard layout + if (e.altKey) handled = false; + else moveCursor(cursorIdx < 0 ? 0 : cur + 1, e.shiftKey); break; case 'ArrowUp': - moveCursor(cur - 1, e.shiftKey); + if (e.altKey) handled = false; + else moveCursor(cur - 1, e.shiftKey); break; case 'PageDown': - moveCursor(cur + page, e.shiftKey); + // Ctrl+PgDn / Ctrl+PgUp (open folder / parent folder) belong to the keyboard layout + if (ctrl) handled = false; + else moveCursor(cur + page, e.shiftKey); break; case 'PageUp': - moveCursor(cur - page, e.shiftKey); + if (ctrl) handled = false; + else moveCursor(cur - page, e.shiftKey); break; case 'Home': if (e.ctrlKey || e.metaKey) void goHome(side); @@ -426,9 +434,11 @@ export function FileTable({ side, active }: { side: Side; active: boolean }) { else ops.selectMask(side, e.key === '+'); handled = true; } - const typed = !ctrl && !e.altKey && e.key.length === 1 && (e.key !== ' ' || !!typeahead); + // Letters jump to a file; so do letters with the layout's quick-search modifier + // (Alt in Norton Commander, Ctrl+Alt in Total Commander). + const typed = !ctrl && !e.altKey && e.key.length === 1 && (e.key !== ' ' || !!typeahead) ? e.key : handled ? null : quickSearchChar(e, activeKeymap().quickSearch); if (!handled && typed) { - const buf = (typeahead + e.key).toLowerCase(); + const buf = (typeahead + typed).toLowerCase(); const start = typeahead ? cur : cur + 1; let found = -1; for (let n = 0; n < rows.length; n++) { diff --git a/ui/src/components/panel/Panel.tsx b/ui/src/components/panel/Panel.tsx index 75fe76e..5f0304f 100644 --- a/ui/src/components/panel/Panel.tsx +++ b/ui/src/components/panel/Panel.tsx @@ -12,6 +12,8 @@ import { reloadBookmarks, setActiveSide, useApp } from '../../store/app'; import { goBack, goForward, goHome, goRoot, goUp, navigate, refresh, setFilter, switchSession, usePanels, viewRows, type Side } from '../../store/panels'; import * as ops from '../../actions/fileOps'; import { openSiteManager } from '../../actions/sessions'; +import { keyLabel, shortcutLabel, useKeymap } from '../../actions/shortcuts'; +import { rememberFocus, useOnUiRequest } from '../../store/uiRequests'; import { attempt } from '../../store/toasts'; import { MenuList, type MenuItem } from '../Menu'; import { cx, IconButton } from '../ui'; @@ -34,9 +36,21 @@ export function SessionDot({ color }: { color?: string | null }) { return ; } -function Dropdown({ button, items, className, title, testId }: { button: ReactNode; items: () => MenuItem[]; className?: string; title?: string; testId?: string }) { +/** `requestKey`: opens when `requestUi(requestKey)` is called (keyboard commands like Alt+F1). */ +function Dropdown({ button, items, className, title, testId, requestKey }: { button: ReactNode; items: () => MenuItem[]; className?: string; title?: string; testId?: string; requestKey?: string }) { const [open, setOpen] = useState(null); const ref = useRef(null); + const restoreFocus = useRef<(() => void) | null>(null); + useOnUiRequest(requestKey, () => { + if (!ref.current) return; + if (!open) restoreFocus.current = rememberFocus(); + setOpen(ref.current.getBoundingClientRect()); + }); + const close = () => { + setOpen(null); + restoreFocus.current?.(); + restoreFocus.current = null; + }; return ( <>