mirror of
https://seed.radicle.dev/rad:z4V1sjrXqjvFdnCUbxPFqd5p4DtH5.git
synced 2026-11-29 02:00:31 +08:00
Centralise keyboard shortcuts in a registry
A single catalog in lib/shortcuts defines every shortcut's keys and description. Components bind behaviour to it by id for as long as they are mounted, and one listener applies the shared rules for text fields, modals, priority and cycling. The shortcuts modal lists the catalog.
This commit is contained in:
+77
-99
@@ -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 @@
|
||||
}
|
||||
</style>
|
||||
|
||||
<svelte:document
|
||||
onmousedown={dragWindow}
|
||||
onkeydown={e => {
|
||||
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 } });
|
||||
}
|
||||
}} />
|
||||
<svelte:document onmousedown={dragWindow} />
|
||||
<FullscreenModalPortal />
|
||||
|
||||
{#if $activeRouteStore.resource === "booting"}
|
||||
|
||||
@@ -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"}
|
||||
|
||||
@@ -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();
|
||||
},
|
||||
},
|
||||
);
|
||||
</script>
|
||||
|
||||
<style>
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
|
||||
import { hints } from "@app/lib/hints";
|
||||
import { invoke } from "@app/lib/invoke";
|
||||
import { matchesCombo } from "@app/lib/shortcuts.svelte";
|
||||
import * as utils from "@app/lib/utils";
|
||||
|
||||
import Button from "@app/components/Button.svelte";
|
||||
@@ -436,8 +437,7 @@
|
||||
class:inline
|
||||
onkeydown={event => {
|
||||
if (!preview) return;
|
||||
const auxiliarKey = utils.isMac() ? event.metaKey : event.ctrlKey;
|
||||
if (auxiliarKey && event.key === "Enter") {
|
||||
if (matchesCombo(event, "Mod+Enter")) {
|
||||
event.preventDefault();
|
||||
void submit({ comment: body, embeds });
|
||||
}
|
||||
|
||||
@@ -1,20 +1,8 @@
|
||||
<script lang="ts" module>
|
||||
let openActive: (() => void) | undefined;
|
||||
|
||||
// Opens and focuses the search of the list on screen. Returns false when
|
||||
// there is none, or it has nothing to search.
|
||||
export function openListSearch(): boolean {
|
||||
if (openActive === undefined) {
|
||||
return false;
|
||||
}
|
||||
openActive();
|
||||
return true;
|
||||
}
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import type { ComponentProps } from "svelte";
|
||||
|
||||
import { ariaKeyShortcuts, useShortcuts } from "@app/lib/shortcuts.svelte";
|
||||
|
||||
import Button from "@app/components/Button.svelte";
|
||||
import Icon from "@app/components/Icon.svelte";
|
||||
import TextInput from "@app/components/TextInput.svelte";
|
||||
@@ -43,34 +31,26 @@
|
||||
}: Props = $props();
|
||||
/* eslint-enable prefer-const */
|
||||
|
||||
function open() {
|
||||
show = true;
|
||||
// Mounting autofocuses the input, but it may already be open and blurred.
|
||||
requestAnimationFrame(() => {
|
||||
document
|
||||
.querySelector<HTMLInputElement>('input[name="list-search"]')
|
||||
?.focus({ preventScroll: true });
|
||||
});
|
||||
}
|
||||
let input: TextInput | undefined = $state(undefined);
|
||||
|
||||
$effect(() => {
|
||||
if (!hasItems) {
|
||||
return;
|
||||
}
|
||||
openActive = open;
|
||||
return () => {
|
||||
if (openActive === open) {
|
||||
openActive = undefined;
|
||||
}
|
||||
};
|
||||
useShortcuts({
|
||||
shortcut: "filter",
|
||||
enabled: () => hasItems,
|
||||
active: () => input?.hasFocus() ?? false,
|
||||
run: () => {
|
||||
show = true;
|
||||
// Mounting autofocuses the input, but it may already be open and blurred.
|
||||
input?.focus();
|
||||
},
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if hasItems}
|
||||
{#if show}
|
||||
<TextInput
|
||||
bind:this={input}
|
||||
autofocus
|
||||
name="list-search"
|
||||
modShortcuts
|
||||
{onFocus}
|
||||
{onSubmit}
|
||||
onBlur={() => {
|
||||
@@ -84,7 +64,7 @@
|
||||
}}
|
||||
{placeholder}
|
||||
{styleHeight}
|
||||
keyShortcuts="ctrl+f"
|
||||
keyShortcuts={ariaKeyShortcuts("filter")}
|
||||
bind:value>
|
||||
{#snippet left()}
|
||||
<div
|
||||
@@ -99,7 +79,7 @@
|
||||
<Button
|
||||
variant="naked"
|
||||
{styleHeight}
|
||||
keyShortcuts="ctrl+f"
|
||||
keyShortcuts={ariaKeyShortcuts("filter")}
|
||||
onclick={() => (show = true)}>
|
||||
<Icon name={icon} />
|
||||
</Button>
|
||||
|
||||
@@ -22,10 +22,6 @@
|
||||
!window.localStorage,
|
||||
);
|
||||
|
||||
// The list as currently rendered, which the sidebar refreshes on its own,
|
||||
// so it can be newer than the route's sidebar data.
|
||||
let liveRepos: RepoSummary[] | undefined;
|
||||
|
||||
function pinnedFrom(repos: RepoSummary[]): RepoSummary[] {
|
||||
const byRid = new Map(repos.map(r => [r.rid, r]));
|
||||
return pinnedRepoIds.value
|
||||
@@ -34,37 +30,15 @@
|
||||
}
|
||||
|
||||
// The sidebar's top-to-bottom order: pinned repos first, in the order they
|
||||
// were pinned, then the rest. Exported so that the Cmd+1..9 shortcuts land
|
||||
// on the same rows the user is looking at. Deliberately ignores the filter
|
||||
// query, which is transient, so the numbering stays put while typing in it.
|
||||
// Falls back to the given repos while the sidebar isn't mounted.
|
||||
export function sidebarRepoOrder(fallback: RepoSummary[]): RepoSummary[] {
|
||||
return orderRepos(liveRepos ?? fallback);
|
||||
}
|
||||
|
||||
// were pinned, then the rest. Cmd+1..9 follow it, deliberately ignoring the
|
||||
// filter query, which is transient, so the numbering stays put while typing
|
||||
// in it.
|
||||
function orderRepos(repos: RepoSummary[]): RepoSummary[] {
|
||||
return pinnedFrom(repos).concat(
|
||||
repos.filter(r => !pinnedRepoIds.value.includes(r.rid)),
|
||||
);
|
||||
}
|
||||
|
||||
export function openRepoFilter() {
|
||||
filterOpen = true;
|
||||
reposExpanded.value = true;
|
||||
// Opening already focuses the input, but not when it was open and blurred.
|
||||
requestAnimationFrame(() => {
|
||||
document
|
||||
.querySelector<HTMLInputElement>("[data-repo-filter]")
|
||||
?.focus({ preventScroll: true });
|
||||
});
|
||||
}
|
||||
|
||||
export function isRepoFilter(target: EventTarget | null): boolean {
|
||||
return (
|
||||
target instanceof HTMLElement && target.hasAttribute("data-repo-filter")
|
||||
);
|
||||
}
|
||||
|
||||
export function revealRepoInSidebar(rid: string) {
|
||||
if (pinnedRepoIds.value.includes(rid)) return;
|
||||
|
||||
@@ -105,12 +79,16 @@
|
||||
import { show } from "@app/lib/modal";
|
||||
import { repoListScope } from "@app/lib/repoListScope";
|
||||
import * as router from "@app/lib/router";
|
||||
import {
|
||||
ariaKeyShortcuts,
|
||||
modifierHeld,
|
||||
useShortcuts,
|
||||
} from "@app/lib/shortcuts.svelte";
|
||||
import { sidebarCollapsed } from "@app/lib/sidebar.svelte";
|
||||
import {
|
||||
explorerHost,
|
||||
explorerUrl,
|
||||
formatRepositoryId,
|
||||
isMac,
|
||||
} from "@app/lib/utils";
|
||||
|
||||
import AddRepoButton from "@app/components/AddRepoButton.svelte";
|
||||
@@ -150,15 +128,31 @@
|
||||
),
|
||||
);
|
||||
|
||||
let showShortcutNumbers = $state(false);
|
||||
|
||||
function isShortcutModifier(e: KeyboardEvent): boolean {
|
||||
return e.key === (isMac() ? "Meta" : "Control");
|
||||
}
|
||||
|
||||
function hideShortcutNumbers() {
|
||||
showShortcutNumbers = false;
|
||||
}
|
||||
useShortcuts(
|
||||
{
|
||||
shortcut: "filter",
|
||||
// The first filter Cmd+F reaches, ahead of the one in the page.
|
||||
priority: 1,
|
||||
enabled: () => !sidebarCollapsed.value,
|
||||
active: () => document.activeElement === filterInputElement,
|
||||
run: () => {
|
||||
filterOpen = true;
|
||||
reposExpanded.value = true;
|
||||
// Opening focuses the input, but it may already be open and blurred.
|
||||
filterInputElement?.focus({ preventScroll: true });
|
||||
},
|
||||
},
|
||||
{
|
||||
shortcut: "goToRepo",
|
||||
run: (_, index) => {
|
||||
const repo = orderRepos(repos)[index];
|
||||
if (!repo) {
|
||||
return false;
|
||||
}
|
||||
void router.push({ resource: "repo.home", rid: repo.rid });
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
let contextMenu = $state<
|
||||
{ x: number; y: number; repo: RepoSummary; target: HTMLElement } | undefined
|
||||
@@ -179,13 +173,6 @@
|
||||
contextMenu = undefined;
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
liveRepos = repos;
|
||||
return () => {
|
||||
liveRepos = undefined;
|
||||
};
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (filterOpen && filterInputElement) {
|
||||
filterInputElement.focus({ preventScroll: true });
|
||||
@@ -967,19 +954,6 @@
|
||||
}
|
||||
</style>
|
||||
|
||||
<svelte:window
|
||||
onkeydown={e => {
|
||||
if (isShortcutModifier(e)) {
|
||||
showShortcutNumbers = true;
|
||||
}
|
||||
}}
|
||||
onkeyup={e => {
|
||||
if (isShortcutModifier(e)) {
|
||||
hideShortcutNumbers();
|
||||
}
|
||||
}}
|
||||
onblur={hideShortcutNumbers} />
|
||||
|
||||
{#if seededNotReplicated.length > 0 && !sidebarCollapsed.value}
|
||||
<div
|
||||
class="section-header"
|
||||
@@ -1070,7 +1044,7 @@
|
||||
role="none">
|
||||
<input
|
||||
bind:this={filterInputElement}
|
||||
data-repo-filter
|
||||
data-mod-shortcuts
|
||||
class="filter-input"
|
||||
placeholder="Filter repos…"
|
||||
bind:value={filterQuery}
|
||||
@@ -1122,7 +1096,7 @@
|
||||
<button
|
||||
class="filter-button"
|
||||
title={filterOpen ? "Close filter" : "Filter repos"}
|
||||
aria-keyshortcuts="ctrl+f"
|
||||
aria-keyshortcuts={ariaKeyShortcuts("filter")}
|
||||
onclick={() => {
|
||||
if (filterOpen) {
|
||||
filterOpen = false;
|
||||
@@ -1163,7 +1137,7 @@
|
||||
href={router.routeToPath({ resource: "repo.home", rid: repo.rid })}>
|
||||
<span class="avatar">
|
||||
<RepoAvatar name={repo.name} rid={repo.rid} styleWidth="1rem" />
|
||||
{#if showShortcutNumbers && shortcutNumber !== undefined}
|
||||
{#if modifierHeld.value && shortcutNumber !== undefined}
|
||||
<span class="avatar-shortcut">{shortcutNumber}</span>
|
||||
{:else if repo.private}
|
||||
<span class="avatar-lock">
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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") {
|
||||
|
||||
@@ -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<SidebarData> {
|
||||
const [config, repos, notificationCount, seededNotReplicated] =
|
||||
await Promise.all([
|
||||
|
||||
@@ -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<string, ShortcutDoc>;
|
||||
|
||||
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<Binding[]>([]);
|
||||
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<string, string> = {
|
||||
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);
|
||||
};
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
}));
|
||||
</script>
|
||||
|
||||
<style>
|
||||
@@ -81,9 +63,15 @@
|
||||
color: var(--color-text-tertiary);
|
||||
}
|
||||
.description {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
font: var(--txt-body-m-regular);
|
||||
color: var(--color-text-primary);
|
||||
}
|
||||
.note {
|
||||
font: var(--txt-body-s-regular);
|
||||
color: var(--color-text-tertiary);
|
||||
}
|
||||
</style>
|
||||
|
||||
<div
|
||||
@@ -94,16 +82,21 @@
|
||||
<span class="title">Keyboard shortcuts</span>
|
||||
</div>
|
||||
<div class="rows">
|
||||
{#each shortcuts as shortcut (shortcut.description)}
|
||||
{#each rows as row, index (index)}
|
||||
<div class="keys">
|
||||
{#each shortcut.keys as key, index (key)}
|
||||
{#each row.keys as key, index (key)}
|
||||
{#if index > 0}
|
||||
<span class="plus">+</span>
|
||||
{/if}
|
||||
<span class="key">{key}</span>
|
||||
{/each}
|
||||
</div>
|
||||
<span class="description">{shortcut.description}</span>
|
||||
<span class="description">
|
||||
{row.description}
|
||||
{#if row.note}
|
||||
<span class="note">{row.note}</span>
|
||||
{/if}
|
||||
</span>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user