diff --git a/src/App.svelte b/src/App.svelte index 32d76a6cd..c3048e401 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -19,26 +19,17 @@ import { invoke } from "@app/lib/invoke"; import { hide, modalStore, show, toggle } from "@app/lib/modal"; import * as router from "@app/lib/router"; - import { - isLoadedRepoRoute, - sidebarDataOf, - } from "@app/lib/router/definitions"; - import { sidebarCollapsed, toggleSidebar } from "@app/lib/sidebar.svelte"; + import { isLoadedRepoRoute } from "@app/lib/router/definitions"; + import { listenForShortcuts, useShortcuts } from "@app/lib/shortcuts.svelte"; import { setUnlistenNodeEvents, unlistenNodeEvents, } from "@app/lib/startup.svelte"; - import { isMac, isTyping, unreachable } from "@app/lib/utils"; + import { unreachable } from "@app/lib/utils"; import { dragWindow } from "@app/lib/window"; import AppSidebar from "@app/components/AppSidebar.svelte"; import { codeFont } from "@app/components/CodeFontSwitch.svelte"; - import { openListSearch } from "@app/components/FuzzySearch.svelte"; - import { - isRepoFilter, - openRepoFilter, - sidebarRepoOrder, - } from "@app/components/SidebarRepoList.svelte"; import { followSystemTheme, loadTheme, @@ -80,6 +71,79 @@ ); } + onMount(listenForShortcuts); + + useShortcuts( + { + shortcut: "help", + allowInModal: true, + run: () => { + // Only toggle our own modal, so an open modal isn't replaced from + // under the user. + const open = $modalStore?.component; + if (open !== undefined && open !== KeyboardShortcutsModal) { + return false; + } + toggle({ component: KeyboardShortcutsModal, props: {} }); + }, + }, + { + shortcut: "newIssue", + enabled: () => activeRepo !== undefined, + run: () => { + if (activeRepo) { + show({ component: CreateIssueModal, props: { repo: activeRepo } }); + } + }, + }, + { + shortcut: "back", + run: () => window.history.back(), + }, + { + shortcut: "forward", + run: () => window.history.forward(), + }, + { + shortcut: "reload", + allowInModal: true, + run: () => { + // A reload would throw away whatever is being composed in a modal. + if (!modalHasTextEntry()) { + // Matches the sidebar's reload button rather than re-fetching per + // route. + window.location.reload(); + } + }, + }, + { + shortcut: "settings", + allowInModal: true, + run: () => toggle({ component: SettingsView, props: {} }), + }, + { + shortcut: "increaseFontSize", + allowInModal: true, + run: increaseFontSize, + }, + { + shortcut: "decreaseFontSize", + allowInModal: true, + run: decreaseFontSize, + }, + { + shortcut: "resetFontSize", + allowInModal: true, + run: resetFontSize, + }, + { + shortcut: "closeModal", + allowInModal: true, + enabled: () => $modalStore !== undefined, + run: hide, + }, + ); + window .matchMedia("(prefers-color-scheme: dark)") .addEventListener("change", ({ matches }) => { @@ -163,93 +227,7 @@ } - { - const auxiliarKey = isMac() ? e.metaKey : e.ctrlKey; - // Handles the position of the plus key on different keyboard layouts. - const plusKey = e.key === "+" || e.key === "="; - const backKey = isMac() - ? e.metaKey && e.key === "[" - : e.altKey && e.key === "ArrowLeft"; - const forwardKey = isMac() - ? e.metaKey && e.key === "]" - : e.altKey && e.key === "ArrowRight"; - const noModal = $modalStore === undefined; - if (e.key === "Escape") { - hide(); - return; - } - // The first press goes to the sidebar's repo filter, the second one from - // there to the search of the list on screen. - if (auxiliarKey && e.key.toLowerCase() === "f" && noModal) { - if (isRepoFilter(e.target)) { - if (openListSearch()) { - e.preventDefault(); - } - } else if (!isTyping(e.target)) { - e.preventDefault(); - if (sidebarCollapsed.value) { - openListSearch(); - } else { - openRepoFilter(); - } - } - return; - } - if (isTyping(e.target)) { - return; - } - if (auxiliarKey && plusKey) { - increaseFontSize(); - } else if (auxiliarKey && e.key === "-") { - decreaseFontSize(); - } else if (auxiliarKey && e.key.toLowerCase() === "0") { - resetFontSize(); - } else if (auxiliarKey && e.key.toLowerCase() === "r") { - e.preventDefault(); - // A reload would throw away whatever is being composed in a modal. - if (!modalHasTextEntry()) { - // Matches the sidebar's reload button rather than re-fetching per route. - window.location.reload(); - } - } else if (auxiliarKey && /^[1-9]$/.test(e.key) && noModal) { - const repos = sidebarDataOf($activeRouteStore)?.repos; - const repo = repos && sidebarRepoOrder(repos)[Number(e.key) - 1]; - if (repo) { - e.preventDefault(); - void router.push({ resource: "repo.home", rid: repo.rid }); - } - } else if (backKey && noModal) { - e.preventDefault(); - window.history.back(); - } else if (forwardKey && noModal) { - e.preventDefault(); - window.history.forward(); - } else if (auxiliarKey && e.key === ",") { - e.preventDefault(); - toggle({ component: SettingsView, props: {} }); - } else if (auxiliarKey && e.key.toLowerCase() === "b") { - e.preventDefault(); - toggleSidebar(); - } else if (e.key === "?" && !auxiliarKey && !e.altKey) { - // Only toggle our own modal, so an open modal isn't replaced from - // under the user. - const open = $modalStore?.component; - if (open === undefined || open === KeyboardShortcutsModal) { - e.preventDefault(); - toggle({ component: KeyboardShortcutsModal, props: {} }); - } - } else if ( - auxiliarKey && - e.key.toLowerCase() === "n" && - activeRepo && - noModal - ) { - e.preventDefault(); - show({ component: CreateIssueModal, props: { repo: activeRepo } }); - } - }} /> + {#if $activeRouteStore.resource === "booting"} diff --git a/src/components/AppSidebar.svelte b/src/components/AppSidebar.svelte index 48a796e8b..95b65a1eb 100644 --- a/src/components/AppSidebar.svelte +++ b/src/components/AppSidebar.svelte @@ -15,6 +15,7 @@ import { notificationCount } from "@app/lib/notificationCount.svelte"; import * as router from "@app/lib/router"; import type { SidebarData } from "@app/lib/router/definitions"; + import { ariaKeyShortcuts, useShortcuts } from "@app/lib/shortcuts.svelte"; import { commitSidebarWidth, discardSidebarWidthPreview, @@ -78,6 +79,12 @@ } const toggleShortcut = isMac() ? "⌘B" : "Ctrl+B"; + + useShortcuts({ + shortcut: "toggleSidebar", + allowInModal: true, + run: toggleSidebar, + }); const dragStripHeight = isMac() ? "2rem" : "1.75rem"; const mini = $derived(collapsed.value); @@ -607,7 +614,7 @@ title="{collapsed.value ? 'Expand' : 'Collapse'} sidebar ({toggleShortcut})" - keyShortcuts={isMac() ? "Meta+b" : "Control+b"} + keyShortcuts={ariaKeyShortcuts("toggleSidebar")} onclick={toggleSidebar} styleWidth={isMini ? "2rem" : "1.5rem"} styleHeight={isMini ? "2rem" : "1.5rem"} diff --git a/src/components/Changes.svelte b/src/components/Changes.svelte index ad380107b..cba3217bd 100644 --- a/src/components/Changes.svelte +++ b/src/components/Changes.svelte @@ -24,6 +24,7 @@ commentCountsByPath, isCommentableStatus, } from "@app/lib/pierreComments"; + import { useShortcuts } from "@app/lib/shortcuts.svelte"; import { pluralize } from "@app/lib/utils"; import CobCommitTeaser from "@app/components/CobCommitTeaser.svelte"; @@ -468,39 +469,32 @@ void tick().then(revealActiveCommit); } - // Up/Down step through commits; Escape deselects. Ignored while typing. - $effect(() => { - const onKeydown = (e: KeyboardEvent) => { - const el = document.activeElement; - if ( - el instanceof HTMLElement && - (el.tagName === "INPUT" || - el.tagName === "TEXTAREA" || - el.isContentEditable) - ) { - return; - } - if (e.key === "Escape") { - if (selectedCommit) { - e.preventDefault(); - selectRevision({ headId: revision.head, baseId: revision.base }); - void scrollToDiff(); - } - return; - } - if (commitList.length <= 1) return; - const current = commitList.findIndex(c => c.id === selectedCommit); - if (e.key === "ArrowDown") { - e.preventDefault(); - selectCommitAt(current === -1 ? 0 : current + 1); - } else if (e.key === "ArrowUp") { - e.preventDefault(); + useShortcuts( + { + shortcut: "previousCommit", + enabled: () => commitList.length > 1, + run: () => { + const current = commitList.findIndex(c => c.id === selectedCommit); selectCommitAt(current === -1 ? commitList.length - 1 : current - 1); - } - }; - window.addEventListener("keydown", onKeydown); - return () => window.removeEventListener("keydown", onKeydown); - }); + }, + }, + { + shortcut: "nextCommit", + enabled: () => commitList.length > 1, + run: () => { + const current = commitList.findIndex(c => c.id === selectedCommit); + selectCommitAt(current === -1 ? 0 : current + 1); + }, + }, + { + shortcut: "allCommits", + enabled: () => selectedCommit !== undefined, + run: () => { + selectRevision({ headId: revision.head, baseId: revision.base }); + void scrollToDiff(); + }, + }, + ); - { - if (isShortcutModifier(e)) { - showShortcutNumbers = true; - } - }} - onkeyup={e => { - if (isShortcutModifier(e)) { - hideShortcutNumbers(); - } - }} - onblur={hideShortcutNumbers} /> - {#if seededNotReplicated.length > 0 && !sidebarCollapsed.value}
{ if (filterOpen) { filterOpen = false; @@ -1163,7 +1137,7 @@ href={router.routeToPath({ resource: "repo.home", rid: repo.rid })}> - {#if showShortcutNumbers && shortcutNumber !== undefined} + {#if modifierHeld.value && shortcutNumber !== undefined} {shortcutNumber} {:else if repo.private} diff --git a/src/components/TextInput.svelte b/src/components/TextInput.svelte index 18a2bc1b1..67dfca077 100644 --- a/src/components/TextInput.svelte +++ b/src/components/TextInput.svelte @@ -4,7 +4,7 @@ import { onMount } from "svelte"; - import * as utils from "@app/lib/utils"; + import { matchesCombo } from "@app/lib/shortcuts.svelte"; interface Props { autofocus?: boolean; @@ -12,6 +12,9 @@ disabled?: boolean; keyShortcuts?: string; left?: Snippet; + // Lets shortcuts with Mod through while focused, for fields like filters + // that hold nothing worth protecting. + modShortcuts?: boolean; name?: string; onDismiss?: () => void; onFocus?: () => void; @@ -33,6 +36,7 @@ disabled = false, keyShortcuts, left, + modShortcuts = false, name, onDismiss, onFocus, @@ -67,10 +71,16 @@ } }); + export function focus() { + inputElement?.focus({ preventScroll: true }); + } + + export function hasFocus(): boolean { + return focussed; + } + function handleKeydown(event: KeyboardEvent) { - event.stopPropagation(); - const auxiliarKey = utils.isMac() ? event.metaKey : event.ctrlKey; - if (auxiliarKey && event.key === "Enter" && onModifierSubmit) { + if (matchesCombo(event, "Mod+Enter") && onModifierSubmit) { event.preventDefault(); onModifierSubmit(); return; @@ -136,6 +146,7 @@ focussed = false; }} bind:this={inputElement} + data-mod-shortcuts={modShortcuts || undefined} {type} {name} {placeholder} diff --git a/src/components/Textarea.svelte b/src/components/Textarea.svelte index 6da075429..5e1db39e1 100644 --- a/src/components/Textarea.svelte +++ b/src/components/Textarea.svelte @@ -6,7 +6,7 @@ import { onMount, tick } from "svelte"; - import * as utils from "@app/lib/utils"; + import { matchesCombo } from "@app/lib/shortcuts.svelte"; interface Props { draggingOver?: boolean; @@ -110,9 +110,7 @@ }); function handleKeydown(event: KeyboardEvent) { - event.stopPropagation(); - const auxiliarKey = utils.isMac() ? event.metaKey : event.ctrlKey; - if (auxiliarKey && event.key === "Enter") { + if (matchesCombo(event, "Mod+Enter")) { void submit(); } if (event.key === "Escape") { diff --git a/src/lib/router/definitions.ts b/src/lib/router/definitions.ts index 927b01ff4..dce0fc40e 100644 --- a/src/lib/router/definitions.ts +++ b/src/lib/router/definitions.ts @@ -68,12 +68,6 @@ export function isLoadedRepoRoute( ); } -// Every route but `booting` carries the sidebar data, which has no params at -// all, so reach for it through here rather than narrowing at each call site. -export function sidebarDataOf(route: LoadedRoute): SidebarData | undefined { - return route.resource === "booting" ? undefined : route.params.sidebarData; -} - export async function loadSidebarData(): Promise { const [config, repos, notificationCount, seededNotReplicated] = await Promise.all([ diff --git a/src/lib/shortcuts.svelte.ts b/src/lib/shortcuts.svelte.ts new file mode 100644 index 000000000..eb682602c --- /dev/null +++ b/src/lib/shortcuts.svelte.ts @@ -0,0 +1,276 @@ +import { untrack } from "svelte"; +import { get } from "svelte/store"; + +import { modalStore } from "@app/lib/modal"; +import { isMac, modifierKey } from "@app/lib/utils"; + +// A combo is the key, optionally preceded by modifiers: "Mod+F", "Alt+ArrowLeft", +// "?". "Mod" is Cmd on macOS and Ctrl elsewhere. Keys are `KeyboardEvent.key` +// values, except that letters and digits are case-insensitive. +export type Combo = string; + +interface ShortcutDoc { + combos: Combo[]; + description: string; + // Where the shortcut applies, when that isn't everywhere. + note?: string; + // Shown in the shortcuts modal instead of the first combo. + label?: Combo; +} + +// Every shortcut in the app, in the order the shortcuts modal lists them. +// Components bind behaviour to these by id, so the keys live only here. +export const shortcuts = { + help: { combos: ["?"], description: "Keyboard shortcuts" }, + filter: { + combos: ["Mod+F"], + description: "Focus a filter on screen, press again to cycle through them", + }, + newIssue: { + combos: ["Mod+N"], + description: "New issue", + note: "In a repository", + }, + goToRepo: { + combos: Array.from({ length: 9 }, (_, i) => `Mod+${i + 1}`), + label: "Mod+1…9", + description: "Go to the nth repo in the sidebar", + }, + back: { + combos: [isMac() ? "Mod+[" : "Alt+ArrowLeft"], + description: "Go back", + }, + forward: { + combos: [isMac() ? "Mod+]" : "Alt+ArrowRight"], + description: "Go forward", + }, + previousCommit: { + combos: ["ArrowUp"], + description: "Previous commit", + note: "In a patch's changes", + }, + nextCommit: { + combos: ["ArrowDown"], + description: "Next commit", + note: "In a patch's changes", + }, + allCommits: { + combos: ["Escape"], + description: "Show all commits", + note: "In a patch's changes", + }, + toggleSidebar: { combos: ["Mod+B"], description: "Toggle sidebar" }, + settings: { combos: ["Mod+,"], description: "Settings" }, + reload: { combos: ["Mod+R"], description: "Reload" }, + // Covers where the plus key sits on different keyboard layouts. + increaseFontSize: { + combos: ["Mod++", "Mod+="], + label: "Mod++", + description: "Increase font size", + }, + decreaseFontSize: { combos: ["Mod+-"], description: "Decrease font size" }, + resetFontSize: { combos: ["Mod+0"], description: "Reset font size" }, + closeModal: { combos: ["Escape"], description: "Close modal" }, +} satisfies Record; + +export type ShortcutId = keyof typeof shortcuts; + +export interface Binding { + shortcut: ShortcutId; + // Gets the index of the combo that matched. Returning false passes the key + // on to the next binding for it. + run: (event: KeyboardEvent, combo: number) => unknown; + enabled?: () => boolean; + // Whether what the binding acts on already has focus. The next press then + // moves on to the following binding, wrapping around, so repeated presses + // cycle through them. + active?: () => boolean; + allowInModal?: boolean; + // Tried before other bindings for the same keys. Among equals, the most + // recently registered one goes first. + priority?: number; +} + +let registered = $state.raw([]); +let modifierDown = $state(false); + +// Whether Mod is held down in a state where Mod shortcuts would run. +export const modifierHeld = { + get value() { + return modifierDown; + }, +}; + +function register(binding: Binding): () => void { + registered = [...registered, binding]; + return () => { + registered = registered.filter(b => b !== binding); + }; +} + +// Binds shortcuts for the lifetime of the calling component. +export function useShortcuts(...bindings: Binding[]) { + $effect(() => { + // Registering reads the registry it writes to, which would otherwise make + // every registration re-run all of them. + const unregister = untrack(() => bindings.map(register)); + return () => untrack(() => unregister.forEach(fn => fn())); + }); +} + +function parse(combo: Combo): { modifiers: string[]; key: string } { + const parts = combo.split("+"); + // "Mod++" splits into a trailing pair of empty strings. + const key = parts.pop() || "+"; + return { modifiers: parts.filter(Boolean), key }; +} + +function isAlphanumeric(key: string): boolean { + return /^[a-z0-9]$/i.test(key); +} + +export function matchesCombo(event: KeyboardEvent, combo: Combo): boolean { + const { modifiers, key } = parse(combo); + const [mod, otherMod] = isMac() + ? [event.metaKey, event.ctrlKey] + : [event.ctrlKey, event.metaKey]; + if (mod !== modifiers.includes("Mod") || otherMod) return false; + if (event.altKey !== modifiers.includes("Alt")) return false; + // Shift is part of how symbols like "?" and "+" are typed on most layouts. + const symbol = key.length === 1 && !isAlphanumeric(key); + if (!symbol && event.shiftKey !== modifiers.includes("Shift")) return false; + + if (!isAlphanumeric(key)) return event.key === key; + if (event.key.toLowerCase() === key.toLowerCase()) return true; + // On a non-Latin layout, fall back to the key's position on a QWERTY one. + return ( + event.key.length === 1 && + event.key.charCodeAt(0) > 127 && + event.code === (/\d/.test(key) ? `Digit${key}` : `Key${key.toUpperCase()}`) + ); +} + +const keyLabels: Record = { + ArrowLeft: "←", + ArrowRight: "→", + ArrowUp: "↑", + ArrowDown: "↓", + Escape: "esc", +}; + +export function comboKeys(combo: Combo): string[] { + const { modifiers, key } = parse(combo); + const modifierLabels = modifiers.map(m => + m === "Mod" + ? modifierKey() + : m === "Alt" + ? isMac() + ? "⌥" + : "alt" + : m.toLowerCase(), + ); + return [...modifierLabels, keyLabels[key] ?? key.toLowerCase()]; +} + +export function ariaKeyShortcuts(id: ShortcutId): string { + const { modifiers, key } = parse(shortcuts[id].combos[0]); + const modifierNames = modifiers.map(m => + m === "Mod" ? (isMac() ? "Meta" : "Control") : m, + ); + return [...modifierNames, key.length === 1 ? key.toUpperCase() : key].join( + "+", + ); +} + +function isTyping(target: EventTarget | null): boolean { + if (!(target instanceof HTMLElement)) { + return false; + } + const tag = target.tagName.toLowerCase(); + return tag === "input" || tag === "textarea" || target.isContentEditable; +} + +function isModifierKey(event: KeyboardEvent): boolean { + return event.key === (isMac() ? "Meta" : "Control"); +} + +// Fields marked with `data-mod-shortcuts`, like filters, hold nothing worth +// protecting, so shortcuts with Mod still work from them. +function blocksShortcuts(event: KeyboardEvent, modDown: boolean): boolean { + if (!isTyping(event.target)) { + return false; + } + const allowsMod = + event.target instanceof HTMLElement && + event.target.hasAttribute("data-mod-shortcuts"); + return !(allowsMod && modDown); +} + +function onKeydown(event: KeyboardEvent) { + const modalOpen = get(modalStore) !== undefined; + if (isModifierKey(event)) { + modifierDown = !modalOpen && !blocksShortcuts(event, true); + } + const modDown = isMac() ? event.metaKey : event.ctrlKey; + // Keys a component already handled, and anything typed into a field, are + // left alone. + if ( + event.defaultPrevented || + event.isComposing || + blocksShortcuts(event, modDown) + ) { + return; + } + + const candidates = registered + .map((binding, index) => ({ + binding, + index, + combo: (shortcuts[binding.shortcut].combos as Combo[]).findIndex(c => + matchesCombo(event, c), + ), + })) + .filter( + ({ binding, combo }) => + combo !== -1 && + (!modalOpen || binding.allowInModal) && + binding.enabled?.() !== false, + ) + .sort( + (a, b) => + (b.binding.priority ?? 0) - (a.binding.priority ?? 0) || + b.index - a.index, + ); + const active = candidates.findIndex(({ binding }) => binding.active?.()); + const ordered = + active === -1 + ? candidates + : [...candidates.slice(active + 1), ...candidates.slice(0, active + 1)]; + for (const { binding, combo } of ordered) { + if (binding.run(event, combo) !== false) { + event.preventDefault(); + return; + } + } +} + +function onKeyup(event: KeyboardEvent) { + if (isModifierKey(event)) { + modifierDown = false; + } +} + +function onBlur() { + modifierDown = false; +} + +export function listenForShortcuts(): () => void { + document.addEventListener("keydown", onKeydown); + document.addEventListener("keyup", onKeyup); + window.addEventListener("blur", onBlur); + return () => { + document.removeEventListener("keydown", onKeydown); + document.removeEventListener("keyup", onKeyup); + window.removeEventListener("blur", onBlur); + }; +} diff --git a/src/lib/utils.ts b/src/lib/utils.ts index fbc3f51c7..f0f37c59c 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -252,14 +252,6 @@ export function modifierKey() { return isMac() ? "⌘" : "ctrl"; } -export function isTyping(target: EventTarget | null): boolean { - if (!(target instanceof HTMLElement)) { - return false; - } - const tag = target.tagName.toLowerCase(); - return tag === "input" || tag === "textarea" || target.isContentEditable; -} - export function parseNodeId( nid: string, ): { prefix: string; pubkey: string } | undefined { diff --git a/src/modals/KeyboardShortcuts.svelte b/src/modals/KeyboardShortcuts.svelte index b278ff4a7..0fe8b0eb5 100644 --- a/src/modals/KeyboardShortcuts.svelte +++ b/src/modals/KeyboardShortcuts.svelte @@ -2,31 +2,13 @@ import { cubicIn, cubicOut } from "svelte/easing"; import { fly } from "svelte/transition"; - import { isMac, modifierKey } from "@app/lib/utils"; + import { comboKeys, shortcuts } from "@app/lib/shortcuts.svelte"; - type Shortcut = { keys: string[]; description: string }; - - const shortcuts: Shortcut[] = [ - { keys: ["?"], description: "Keyboard shortcuts" }, - { keys: [modifierKey(), "f"], description: "Search the current list" }, - { keys: [modifierKey(), "n"], description: "New issue" }, - { keys: [modifierKey(), "1…9"], description: "Go to the nth repo" }, - { - keys: isMac() ? [modifierKey(), "["] : ["alt", "←"], - description: "Go back", - }, - { - keys: isMac() ? [modifierKey(), "]"] : ["alt", "→"], - description: "Go forward", - }, - { keys: [modifierKey(), "r"], description: "Reload" }, - { keys: [modifierKey(), "b"], description: "Toggle sidebar" }, - { keys: [modifierKey(), ","], description: "Settings" }, - { keys: [modifierKey(), "+"], description: "Increase font size" }, - { keys: [modifierKey(), "-"], description: "Decrease font size" }, - { keys: [modifierKey(), "0"], description: "Reset font size" }, - { keys: ["esc"], description: "Close modal" }, - ]; + const rows = Object.values(shortcuts).map(s => ({ + keys: comboKeys("label" in s ? s.label : s.combos[0]), + description: s.description, + note: "note" in s ? s.note : undefined, + }));
Keyboard shortcuts
- {#each shortcuts as shortcut (shortcut.description)} + {#each rows as row, index (index)}
- {#each shortcut.keys as key, index (key)} + {#each row.keys as key, index (key)} {#if index > 0} + {/if} {key} {/each}
- {shortcut.description} + + {row.description} + {#if row.note} + {row.note} + {/if} + {/each}