Skip to content

📧✨ Beautiful email. For everyone.

feat: customizable keyboard shortcuts (#17)

Paul Koeckfd126ab5396d
diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsx
index 20775ec..84c6ce5 100644
--- a/apps/desktop/src/renderer/src/App.tsx
+++ b/apps/desktop/src/renderer/src/App.tsx
@@ -1,7 +1,6 @@
import { useEffect, useMemo, useRef, useState, lazy, Suspense } from 'react'
import { useInfiniteQuery, useQueries, useQuery } from '@tanstack/react-query'
import { useNavigate, useSearch } from '@tanstack/react-router'
-import { useHotkey, useHotkeySequence } from '@tanstack/react-hotkeys'
import {
Inbox,
Search,
@@ -28,6 +27,7 @@ import {
MailMinus,
FolderInput,
ShieldX,
+ ShieldCheck,
Reply,
ReplyAll,
Forward,
@@ -90,7 +90,7 @@ import {
} from './AppDialogs'
import { messageText } from './message-text'
import { selectConversation } from './selection'
-import { useCharacterKey } from './character-key'
+import { ShortcutHint, useShortcutHandlers, useShortcutText, useShortcuts } from './shortcuts'
import { emptyListState } from './empty-states'
import { AccountMark } from './AccountMark'
import { HintIconButton } from './HintIconButton'
@@ -176,6 +176,8 @@ export function App() {
}
const notify = (text: string, tone?: Toast['tone']) => setToast({ text, tone })
const fail = (error: unknown) => notify(friendlyError(error), 'error')
+ const shortcuts = useShortcuts()
+ const keys = useShortcutText()
const explain = ({ account, reason }: { account: { name: string }; reason: string }) =>
notify((accounts.length > 1 ? account.name + ' · ' : '') + reason, 'info')
const account = accounts.find((a) => a.id === route.account),
@@ -906,125 +908,115 @@ export function App() {
: 'star',
)
const hasTarget = !!route.thread || !!selected.size || !!focused
- const on = { conflictBehavior: 'replace', enabled: !blocked } as const
- useHotkey('Mod+K', () => setPaletteOpen((p) => !p), {
- conflictBehavior: 'replace',
- enabled: !composer,
- ignoreInputs: false,
- })
- useHotkey('Mod+,', () => openSettings(), { ...on, ignoreInputs: false })
- useHotkey('[', () => setCollapsed((c) => !c), on)
- useHotkey('C', () => void compose(), on)
- useHotkey('/', focusSearch, on)
- useHotkey('J', () => step(1), on)
- useHotkey('K', () => step(-1), on)
- useHotkey('ArrowDown', () => step(1), on)
- useHotkey('ArrowUp', () => step(-1), on)
- useHotkey(
- 'Enter',
- () => {
- const c = conversations.find((c) => c.key === focused) || conversations[0]
- if (c && !route.thread) open(c)
- },
- on,
- )
- useHotkey(
- 'O',
- () => {
- const c = conversations.find((c) => c.key === focused) || conversations[0]
- if (c && !route.thread) open(c)
- },
- on,
- )
- useHotkey(
- 'Escape',
- () => {
- if (route.thread) back()
- else if (draftSelected.size) setDraftSelected(new Set())
- else if (selected.size || allMatching) {
- setSelected(new Set())
- setAllMatching(false)
- } else if (searchOpen || route.q) {
- setSearch('')
- setSearchOpen(false)
- if (route.q) go({ q: undefined }, false)
- }
- },
- on,
- )
- useHotkey(
- 'X',
- () => {
- if (focused) toggle(focused)
- },
- { ...on, enabled: !blocked && !route.thread },
- )
- useHotkey(
- 'Shift+X',
- () => {
- if (focused) toggle(focused, true)
- },
- { ...on, enabled: !blocked && !route.thread },
- )
- useHotkey(
- 'Mod+A',
- () => {
- if (view === 'drafts')
- return setDraftSelected(new Set(draftItems.filter(deletable).map((item) => item.key)))
- setSelected(new Set(conversations.map((c) => c.key)))
- setAllMatching(false)
- },
- { ...on, enabled: !blocked && !route.thread },
- )
+ const openFocused = () => {
+ const c = conversations.find((c) => c.key === focused) || conversations[0]
+ if (c && !route.thread) open(c)
+ }
// In Drafts, the trash keys delete the selected drafts rather than moving conversations.
const trashKey = () => (view === 'drafts' ? discardDrafts(draftSelected) : void act('trash'))
const canTrash = !blocked && (view === 'drafts' ? !!draftSelected.size : hasTarget)
- useHotkey('E', () => void act('archive'), { ...on, enabled: !blocked && hasTarget })
- useHotkey('Backspace', trashKey, { ...on, enabled: canTrash })
- useHotkey('Delete', trashKey, { ...on, enabled: canTrash })
- useCharacterKey('#', trashKey, canTrash)
- useCharacterKey('!', () => void act('spam'), !blocked && hasTarget)
- useCharacterKey('?', () => setHelp(true), !blocked)
- useHotkey('U', () => void act('unread'), { ...on, enabled: !blocked && hasTarget })
- useHotkey('Shift+U', () => void act('unread'), { ...on, enabled: !blocked && hasTarget })
- useHotkey('Shift+I', () => void act('read'), { ...on, enabled: !blocked && hasTarget })
- useHotkey('S', toggleStar, { ...on, enabled: !blocked && hasTarget })
- useHotkey('V', () => openMove(targets()), {
- ...on,
- enabled: !blocked && hasTarget && !allMatching,
- })
- useHotkey('Z', () => void undo(), { ...on, enabled: !blocked && canUndo })
- useHotkey('Mod+Z', () => void undo(), { ...on, enabled: !blocked && canUndo })
- useHotkey(
- 'R',
- () => {
- if (latest) void compose(latest)
- },
- { ...on, enabled: !blocked && !!route.thread },
- )
- useHotkey(
- 'A',
- () => {
- if (latest) void compose(latest, 'replyAll')
- },
- { ...on, enabled: !blocked && !!route.thread },
- )
- useHotkey(
- 'F',
- () => {
- if (latest) void compose(latest, 'forward')
+ const canAct = !blocked && hasTarget
+ const inList = !blocked && !route.thread
+ const inThread = !blocked && !!route.thread && !!latest
+ const inMailList = inList && view !== 'drafts'
+ const toggleUnread = () =>
+ setFilters((current) => ({ ...current, unread: current.unread ? undefined : true }))
+ const toggleDensity = () =>
+ setDensity((current) => (current === 'compact' ? 'comfortable' : 'compact'))
+ const createFolder = () => setFolderDialog({ operation: 'create', accountId: route.account })
+ useShortcutHandlers(
+ shortcuts.bindings,
+ {
+ commandMenu: {
+ run: () => setPaletteOpen((p) => !p),
+ enabled: !composer,
+ ignoreInputs: false,
+ },
+ settings: { run: () => openSettings(), ignoreInputs: false },
+ toggleSidebar: { run: () => setCollapsed((c) => !c) },
+ compose: { run: () => void compose() },
+ search: { run: focusSearch },
+ refresh: {
+ run: () => void refresh(),
+ enabled: true,
+ // F5 must refresh mail instead of reloading the app even when search has focus.
+ // Keep custom letter bindings quiet while typing; modifier chords remain available.
+ ignoreInputs: (binding) =>
+ !binding.every((chord) =>
+ /(^|\+)(Mod|Ctrl|Control|Meta|Alt)\+|^(Shift\+)?F\d+$/.test(chord),
+ ),
+ },
+ filter: { run: () => setFilterOpen(true), enabled: inMailList },
+ toggleUnread: { run: toggleUnread, enabled: inMailList },
+ toggleDensity: { run: toggleDensity, enabled: inMailList },
+ createFolder: { run: createFolder, enabled: !blocked && !!accounts.length },
+ next: { run: () => step(1) },
+ previous: { run: () => step(-1) },
+ open: { run: openFocused },
+ back: {
+ run: () => {
+ if (route.thread) back()
+ else if (draftSelected.size) setDraftSelected(new Set())
+ else if (selected.size || allMatching) {
+ setSelected(new Set())
+ setAllMatching(false)
+ } else if (searchOpen || route.q) {
+ setSearch('')
+ setSearchOpen(false)
+ if (route.q) go({ q: undefined }, false)
+ }
+ },
+ },
+ select: {
+ run: () => {
+ if (focused) toggle(focused)
+ },
+ enabled: inList,
+ },
+ selectRange: {
+ run: () => {
+ if (focused) toggle(focused, true)
+ },
+ enabled: inList,
+ },
+ selectAll: {
+ run: () => {
+ if (view === 'drafts')
+ return setDraftSelected(new Set(draftItems.filter(deletable).map((item) => item.key)))
+ setSelected(new Set(conversations.map((c) => c.key)))
+ setAllMatching(false)
+ },
+ enabled: inList,
+ },
+ archive: { run: () => void act('archive'), enabled: canAct },
+ trash: { run: trashKey, enabled: canTrash },
+ spam: { run: () => void act('spam'), enabled: canAct },
+ notSpam: { run: () => void act('notSpam'), enabled: canAct && view !== 'drafts' },
+ restore: { run: () => void act('restore'), enabled: canAct && view !== 'drafts' },
+ shortcuts: { run: () => setHelp(true) },
+ unread: { run: () => void act('unread'), enabled: canAct },
+ read: { run: () => void act('read'), enabled: canAct },
+ star: { run: toggleStar, enabled: canAct },
+ move: { run: () => openMove(targets()), enabled: canAct && !allMatching },
+ undo: { run: () => void undo(), enabled: !blocked && canUndo },
+ reply: { run: () => latest && void compose(latest), enabled: inThread },
+ replyAll: { run: () => latest && void compose(latest, 'replyAll'), enabled: inThread },
+ forward: { run: () => latest && void compose(latest, 'forward'), enabled: inThread },
+ unsubscribe: {
+ run: () => void unsubscribe(),
+ enabled: !blocked && unsubscribeState === 'available',
+ },
+ goInbox: { run: () => go({ view: 'inbox' }) },
+ goStarred: { run: () => go({ view: 'starred' }) },
+ goSent: { run: () => go({ view: 'sent' }) },
+ goDrafts: { run: () => go({ view: 'drafts' }) },
+ goArchive: { run: () => go({ view: 'archive' }) },
+ goSpam: { run: () => go({ view: 'junk' }) },
+ goTrash: { run: () => go({ view: 'trash' }) },
+ goAll: { run: () => go({ view: 'all' }) },
},
- { ...on, enabled: !blocked && !!route.thread },
+ !blocked,
)
- useHotkey('Mod+U', () => void unsubscribe(), {
- ...on,
- enabled: !blocked && unsubscribeState === 'available',
- })
- useHotkeySequence(['G', 'I'], () => go({ view: 'inbox' }), on)
- useHotkeySequence(['G', 'S'], () => go({ view: 'starred' }), on)
- useHotkeySequence(['G', 'T'], () => go({ view: 'sent' }), on)
- useHotkeySequence(['G', 'D'], () => go({ view: 'drafts' }), on)
- useHotkeySequence(['G', 'A'], () => go({ view: 'archive' }), on)
const suggestions = useMemo(() => {
// People you hear from most come first; your own addresses never appear.
const own = new Set(accounts.map((a) => a.email.toLowerCase()))
@@ -1050,7 +1042,7 @@ export function App() {
fail(e)
}
}
- const commandTarget = route.thread || selected.size || focused
+ const commandTarget = view !== 'drafts' && (route.thread || selected.size || focused)
const limited = (action: MailAction) => {
const reason = commandTarget ? unavailable(action) : undefined
return reason ? { disabled: true, description: reason } : {}
@@ -1061,7 +1053,7 @@ export function App() {
id: 'archive',
label: 'Archive',
icon: Archive,
- key: 'E',
+ key: keys('archive'),
run: () => void act('archive'),
...limited('archive'),
},
@@ -1069,7 +1061,7 @@ export function App() {
id: 'trash',
label: 'Move to trash',
icon: Trash2,
- key: '#',
+ key: keys('trash'),
keywords: 'delete',
run: () => void act('trash'),
...limited('trash'),
@@ -1078,21 +1070,21 @@ export function App() {
id: 'read',
label: 'Mark as read',
icon: MailOpen,
- key: 'Shift I',
+ key: keys('read'),
run: () => void act('read'),
},
{
id: 'unread',
label: 'Mark as unread',
icon: Mail,
- key: 'U',
+ key: keys('unread'),
run: () => void act('unread'),
},
{
id: 'star',
label: 'Star or unstar',
icon: Star,
- key: 'S',
+ key: keys('star'),
keywords: 'flag favorite',
run: toggleStar,
},
@@ -1102,7 +1094,7 @@ export function App() {
id: 'move',
label: 'Move to folder…',
icon: FolderInput,
- key: 'V',
+ key: keys('move'),
keywords: 'label file',
run: () => openMove(targets()),
...limited('move'),
@@ -1113,32 +1105,50 @@ export function App() {
id: 'spam',
label: 'Mark as spam',
icon: ShieldX,
- key: '!',
+ key: keys('spam'),
keywords: 'junk',
run: () => void act('spam'),
...limited('spam'),
},
+ {
+ id: 'not-spam',
+ label: 'Not spam',
+ icon: ShieldCheck,
+ key: keys('notSpam'),
+ keywords: 'junk',
+ run: () => void act('notSpam'),
+ ...limited('notSpam'),
+ },
+ {
+ id: 'restore',
+ label: 'Restore to inbox',
+ icon: Inbox,
+ key: keys('restore'),
+ keywords: 'recover unarchive',
+ run: () => void act('restore'),
+ ...limited('restore'),
+ },
...(latest && route.thread
? [
{
id: 'reply',
label: 'Reply',
icon: Reply,
- key: 'R',
+ key: keys('reply'),
run: () => void compose(latest),
},
{
id: 'reply-all',
label: 'Reply all',
icon: ReplyAll,
- key: 'A',
+ key: keys('replyAll'),
run: () => void compose(latest, 'replyAll'),
},
{
id: 'forward',
label: 'Forward',
icon: Forward,
- key: 'F',
+ key: keys('forward'),
run: () => void compose(latest, 'forward'),
},
]
@@ -1149,7 +1159,7 @@ export function App() {
id: 'unsubscribe',
label: 'Unsubscribe from mailing list',
icon: MailMinus,
- key: 'Ctrl U',
+ key: keys('unsubscribe'),
keywords: 'newsletter opt out stop',
run: () => void unsubscribe(),
...(unsubscribeState === 'pending'
@@ -1171,7 +1181,7 @@ export function App() {
group: 'Suggested',
label: 'Undo “' + toast.text + '”',
icon: Undo2,
- key: 'Z',
+ key: keys('undo'),
run: () => void undo(),
},
]
@@ -1182,7 +1192,7 @@ export function App() {
group: 'Mail',
label: 'Compose a message',
icon: PenLine,
- key: 'C',
+ key: keys('compose'),
keywords: 'new write email',
run: () => void compose(),
},
@@ -1191,7 +1201,7 @@ export function App() {
group: 'Mail',
label: 'Search mail',
icon: Search,
- key: '/',
+ key: keys('search'),
keywords: 'find',
run: focusSearch,
},
@@ -1200,18 +1210,49 @@ export function App() {
group: 'Mail',
label: 'Check for new mail',
icon: RefreshCw,
+ key: keys('refresh'),
keywords: 'refresh sync reload',
run: () => void refresh(),
},
+ ...(view !== 'drafts' && !route.thread
+ ? [
+ {
+ id: 'filter',
+ group: 'Mail',
+ label: 'Filter conversations…',
+ icon: SlidersHorizontal,
+ key: keys('filter'),
+ run: () => setFilterOpen(true),
+ },
+ {
+ id: 'unread-view',
+ group: 'Mail',
+ label: filters.unread ? 'Show all messages' : 'Show only unread messages',
+ icon: Mail,
+ key: keys('toggleUnread'),
+ keywords: 'filter',
+ run: toggleUnread,
+ },
+ ]
+ : []),
...views.map((v) => ({
id: 'view-' + v.id,
group: 'Go to',
label: v.title,
icon: v.icon,
- key: v.key,
+ key: v.shortcut && keys(v.shortcut),
keywords: 'go open view ' + (v.id === 'junk' ? 'junk' : ''),
run: () => go({ view: v.id }),
})),
+ {
+ id: 'view-all',
+ group: 'Go to',
+ label: 'All mail',
+ icon: Mail,
+ key: keys('goAll'),
+ keywords: 'go open view',
+ run: () => go({ view: 'all' }),
+ },
...(accounts.length > 1
? [
{
@@ -1250,8 +1291,10 @@ export function App() {
group: 'Folders',
label: 'Create a folder…',
icon: FolderPlus,
+ key: keys('createFolder'),
keywords: 'new folder',
- run: () => setFolderDialog({ operation: 'create' }),
+ run: createFolder,
+ disabled: !accounts.length,
},
...(['dark', 'light', 'system'] as const).map((theme) => ({
id: 'theme-' + theme,
@@ -1267,15 +1310,16 @@ export function App() {
group: 'Preferences',
label: density === 'compact' ? 'Comfortable density' : 'Compact density',
icon: Rows3,
+ key: keys('toggleDensity'),
keywords: 'display rows spacing list',
- run: () => setDensity(density === 'compact' ? 'comfortable' : 'compact'),
+ run: toggleDensity,
},
{
id: 'sidebar',
group: 'Preferences',
label: collapsed ? 'Expand sidebar' : 'Collapse sidebar',
icon: collapsed ? PanelLeftOpen : PanelLeftClose,
- key: '[',
+ key: keys('toggleSidebar'),
keywords: 'navigation panel hide show',
run: () => setCollapsed(!collapsed),
},
@@ -1284,7 +1328,7 @@ export function App() {
group: 'Preferences',
label: 'Settings',
icon: SettingsIcon,
- key: 'Ctrl ,',
+ key: keys('settings'),
keywords: 'preferences options',
run: () => openSettings(),
},
@@ -1309,10 +1353,18 @@ export function App() {
group: 'Help',
label: 'Keyboard shortcuts',
icon: Keyboard,
- key: '?',
+ key: keys('shortcuts'),
keywords: 'help keys hotkeys',
run: () => setHelp(true),
},
+ {
+ id: 'shortcut-settings',
+ group: 'Help',
+ label: 'Customize keyboard shortcuts',
+ icon: Keyboard,
+ keywords: 'hotkeys keys bindings change edit',
+ run: () => openSettings('shortcuts'),
+ },
]
const activeIndex = conversations.findIndex(
(c) => c.id === route.thread && c.accountId === route.threadAccount,
@@ -1514,7 +1566,11 @@ export function App() {
{route.q && <p>Results for “{route.q}”</p>}
</div>
<div className="list-heading-actions">
- <IconButton label="Refresh mail" onClick={() => void refresh()}>
+ <IconButton
+ label="Refresh mail"
+ shortcut={keys('refresh')}
+ onClick={() => void refresh()}
+ >
<RefreshCw
size={15}
className={mail.isFetching && !mail.isFetchingNextPage ? 'spin' : ''}
@@ -1522,7 +1578,7 @@ export function App() {
</IconButton>
<IconButton
label="Search mail"
- shortcut="/"
+ shortcut={keys('search')}
onClick={() => {
setSearchOpen(!searchOpen)
requestAnimationFrame(() => searchInput.current?.focus())
@@ -1636,13 +1692,19 @@ export function App() {
<button
aria-pressed={!!filters.unread}
className={filters.unread ? 'active' : ''}
+ title={keys('toggleUnread')}
onClick={() => setFilters((f) => ({ ...f, unread: true }))}
>
Unread
</button>
</div>
<div className="list-toolbar-actions">
- <Button variant="ghost" size="small" onClick={() => setFilterOpen(true)}>
+ <Button
+ variant="ghost"
+ size="small"
+ title={keys('filter')}
+ onClick={() => setFilterOpen(true)}
+ >
<SlidersHorizontal size={13} />
Filter{hasFilters && <span className="filter-dot" />}
</Button>
@@ -1668,7 +1730,7 @@ export function App() {
<span className="toolbar-divider" />
<HintIconButton
label="Archive selected"
- shortcut="E"
+ shortcut={keys('archive')}
disabled={busy}
hint={unavailable('archive')}
onClick={() => void act('archive')}
@@ -1677,6 +1739,7 @@ export function App() {
</HintIconButton>
<IconButton
label="Mark selected read"
+ shortcut={keys('read')}
disabled={busy}
onClick={() => void act('read')}
>
@@ -1684,6 +1747,7 @@ export function App() {
</IconButton>
<HintIconButton
label="Trash selected"
+ shortcut={keys('trash')}
disabled={busy}
hint={unavailable('trash')}
onClick={() => void act('trash')}
@@ -1702,19 +1766,32 @@ export function App() {
</Button>
}
>
- <MenuItem onClick={() => void act('unread')}>Mark unread</MenuItem>
- <MenuItem onClick={() => void act('star')}>Star</MenuItem>
+ <MenuItem onClick={() => void act('unread')}>
+ Mark unread
+ <ShortcutHint id="unread" className="menu-shortcut" />
+ </MenuItem>
+ <MenuItem onClick={() => void act('star')}>
+ Star
+ <ShortcutHint id="star" className="menu-shortcut" />
+ </MenuItem>
<MenuItem
onClick={() => openMove(targets())}
disabled={allMatching || !!unavailable('move')}
>
Move to folder
+ <ShortcutHint id="move" className="menu-shortcut" />
</MenuItem>
<MenuItem onClick={() => void act('spam')} disabled={!!unavailable('spam')}>
Mark spam
+ <ShortcutHint id="spam" className="menu-shortcut" />
+ </MenuItem>
+ <MenuItem onClick={() => void act('notSpam')} disabled={!!unavailable('notSpam')}>
+ Not spam
+ <ShortcutHint id="notSpam" className="menu-shortcut" />
</MenuItem>
<MenuItem onClick={() => void act('restore')} disabled={!!unavailable('restore')}>
Restore to inbox
+ <ShortcutHint id="restore" className="menu-shortcut" />
</MenuItem>
{view === 'trash' && (
<MenuItem
@@ -1736,7 +1813,7 @@ export function App() {
<span className="toolbar-divider" />
<IconButton
label="Clear selection"
- shortcut="Esc"
+ shortcut={keys('back')}
disabled={busy}
onClick={() => {
setSelected(new Set())
@@ -1856,9 +1933,9 @@ export function App() {
{hasSearchFilters && (
<Button onClick={() => setFilters({})}>Clear filters</Button>
)}
- {view === 'inbox' && !route.q && !hasFilters && (
+ {view === 'inbox' && !route.q && !hasFilters && keys('compose') && (
<span className="empty-hint">
- <kbd>C</kbd> Write a message
+ <ShortcutHint id="compose" /> Write a message
</span>
)}
</EmptyState>
@@ -1921,12 +1998,12 @@ export function App() {
onClick={() => setHelp(true)}
aria-label="Show keyboard shortcuts"
>
- <kbd>J</kbd>
- <kbd>K</kbd>
+ <ShortcutHint id="next" />
+ <ShortcutHint id="previous" />
<span>Navigate</span>
- <kbd>↵</kbd>
+ <ShortcutHint id="open" />
<span>Open</span>
- <kbd>?</kbd>
+ <ShortcutHint id="shortcuts" className="footer-help-keys" />
<span>Shortcuts</span>
</button>
</footer>
@@ -1951,7 +2028,7 @@ export function App() {
<span>{toast.text}</span>
{canUndo && (
<button className="toast-undo" onClick={() => void undo()}>
- Undo <kbd>Z</kbd>
+ Undo <ShortcutHint id="undo" />
</button>
)}
<button
diff --git a/apps/desktop/src/renderer/src/AppDialogs.tsx b/apps/desktop/src/renderer/src/AppDialogs.tsx
index 5c65c43..a695241 100644
--- a/apps/desktop/src/renderer/src/AppDialogs.tsx
+++ b/apps/desktop/src/renderer/src/AppDialogs.tsx
@@ -1,63 +1,7 @@
import { Fragment, useState } from 'react'
import { Button, DatePicker, Modal, Switch } from '@inlark/ui'
import type { MailAction, Mailbox, MailQuery } from '@inlark/core'
-
-const shortcutSections: [string, [string, string][]][] = [
- [
- 'Navigate',
- [
- ['Next / previous conversation', 'J K'],
- ['Open conversation', 'Enter'],
- ['Back to list', 'Esc'],
- ['Search mail', '/'],
- ['Command menu', 'Ctrl K'],
- ['Toggle sidebar', '['],
- ],
- ],
- [
- 'Go to',
- [
- ['Inbox', 'G I'],
- ['Starred', 'G S'],
- ['Sent', 'G T'],
- ['Drafts', 'G D'],
- ['Archive', 'G A'],
- ],
- ],
- [
- 'Organize',
- [
- ['Archive', 'E'],
- ['Move to trash', '#'],
- ['Delete selected drafts', '#'],
- ['Mark as spam', '!'],
- ['Move to folder', 'V'],
- ['Unsubscribe from mailing list', 'Ctrl U'],
- ['Star or unstar', 'S'],
- ['Mark unread / read', 'U ⇧I'],
- ['Undo last action', 'Z'],
- ],
- ],
- [
- 'Select',
- [
- ['Select conversation', 'X'],
- ['Select a range', '⇧X'],
- ['Select all loaded', 'Ctrl A'],
- ['Clear selection', 'Esc'],
- ],
- ],
- [
- 'Write',
- [
- ['Compose', 'C'],
- ['Reply', 'R'],
- ['Reply all', 'A'],
- ['Forward', 'F'],
- ['Send message', 'Ctrl ↵'],
- ],
- ],
-]
+import { ShortcutEditor } from './ShortcutEditor'
export function ShortcutDialog({ open, onClose }: { open: boolean; onClose: () => void }) {
return (
@@ -67,26 +11,10 @@ export function ShortcutDialog({ open, onClose }: { open: boolean; onClose: () =
if (!value) onClose()
}}
title="Keyboard shortcuts"
- description="Shortcuts are paused while you type in a field."
+ description="Click any keys to change them, or + to add another. Letter shortcuts are paused while you type in a field."
className="shortcut-modal"
>
- <div className="shortcut-sections">
- {shortcutSections.map(([section, items]) => (
- <section key={section}>
- <h3>{section}</h3>
- {items.map(([label, keys]) => (
- <div className="shortcut-row" key={label}>
- <span>{label}</span>
- <span className="shortcut-keys">
- {keys.split(' ').map((key) => (
- <kbd key={key}>{key}</kbd>
- ))}
- </span>
- </div>
- ))}
- </section>
- ))}
- </div>
+ <ShortcutEditor />
</Modal>
)
}
diff --git a/apps/desktop/src/renderer/src/Composer.tsx b/apps/desktop/src/renderer/src/Composer.tsx
index ec4cc95..81bfc49 100644
--- a/apps/desktop/src/renderer/src/Composer.tsx
+++ b/apps/desktop/src/renderer/src/Composer.tsx
@@ -2,7 +2,6 @@ import { useEffect, useRef, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { useForm } from '@tanstack/react-form'
import { Dialog } from '@base-ui/react/dialog'
-import { useHotkey } from '@tanstack/react-hotkeys'
import { useEditor, useEditorState, EditorContent } from '@tiptap/react'
import StarterKit from '@tiptap/starter-kit'
import Placeholder from '@tiptap/extension-placeholder'
@@ -32,6 +31,7 @@ import { api, isDemo } from './api'
import { localSaveDraft, localDeleteDraft } from './cache'
import { RecipientField } from './RecipientField'
import { formatBytes } from './mail-date'
+import { bindingText, useShortcutHandlers, useShortcutText, useShortcuts } from './shortcuts'
/** Plain wording for a finished send; the Drafts view offers recovery for anything left over. */
function sentMessage(result: SendResult): string {
@@ -95,6 +95,9 @@ export function Composer({
notify: (message: string, tone?: 'error' | 'info') => void
onSaved: () => void
}) {
+ const shortcuts = useShortcuts()
+ const keys = useShortcutText()
+ const sendShortcut = shortcuts.bindings.send[0]
const [draft, setDraft] = useState(initial),
[state, setState] = useState(
initial.status === 'uncertain'
@@ -118,6 +121,8 @@ export function Composer({
queryFn: () => api.identities(draft.accountId),
})
const locked = sending || draft.status === 'uncertain' || draft.status === 'sent'
+ const lockedRef = useRef(locked)
+ lockedRef.current = locked
// A failed send is kept apart from the draft, so a later autosave can't clear the explanation.
const [sendError, setSendError] = useState<Pick<Draft, 'error' | 'errorKind'>>()
const shown = sendError ? { ...draft, ...sendError } : draft
@@ -318,10 +323,34 @@ export function Composer({
setSending(false)
}
}
- useHotkey('Mod+Enter', () => void send(), {
- conflictBehavior: 'replace',
- ignoreInputs: false,
- enabled: !linkOpen && !discardOpen,
+ const attachFiles = async () => {
+ try {
+ const attachments = await api.stageAttachments()
+ // The file picker can outlive the composer or a send. Never change a locked draft.
+ if (!alive.current || lockedRef.current) return
+ update({ attachments: [...latest.current.attachments, ...attachments] })
+ } catch (error) {
+ notify(friendlyError(error))
+ }
+ }
+ const focusRecipient = (field: 'cc' | 'bcc') => {
+ setShowCc(true)
+ requestAnimationFrame(() => document.getElementById('compose-' + field)?.focus())
+ }
+ const canEdit = !linkOpen && !discardOpen && !locked
+ useShortcutHandlers(shortcuts.bindings, {
+ // Keep the library's input-aware defaults: modifier shortcuts work while writing,
+ // but a custom letter or sequence must not send or discard a draft as someone types.
+ send: { run: () => void send(), enabled: !linkOpen && !discardOpen && !sending },
+ attachFiles: { run: () => void attachFiles(), enabled: canEdit },
+ showCc: { run: () => focusRecipient('cc'), enabled: canEdit },
+ showBcc: { run: () => focusRecipient('bcc'), enabled: canEdit },
+ expandComposer: {
+ run: () => setExpanded((current) => !current),
+ enabled: !linkOpen && !discardOpen,
+ },
+ saveClose: { run: () => void close(), enabled: !linkOpen && !discardOpen && !sending },
+ discardDraft: { run: () => setDiscardOpen(true), enabled: canEdit },
})
const addressField = (name: 'to' | 'cc' | 'bcc', label: string) => (
<RecipientField
@@ -338,10 +367,11 @@ export function Composer({
<button
type="button"
className="compose-cc-toggle"
+ title={keys('showCc')}
+ disabled={locked}
onClick={(event) => {
event.stopPropagation()
- setShowCc(true)
- requestAnimationFrame(() => document.getElementById('compose-cc')?.focus())
+ focusRecipient('cc')
}}
>
Cc / Bcc
@@ -394,6 +424,7 @@ export function Composer({
</span>
<IconButton
label={expanded ? 'Restore composer size' : 'Expand composer'}
+ shortcut={keys('expandComposer')}
onClick={() => setExpanded(!expanded)}
>
<ArrowUpRight size={14} />
@@ -404,6 +435,7 @@ export function Composer({
variant="ghost"
size="icon"
aria-label="Save and close"
+ title={keys('saveClose')}
disabled={sending}
/>
}
@@ -579,14 +611,8 @@ export function Composer({
<span className="toolbar-divider" />
<IconButton
label="Attach files"
- onClick={async () => {
- try {
- const attachments = await api.stageAttachments()
- update({ attachments: [...latest.current.attachments, ...attachments] })
- } catch (error) {
- notify(friendlyError(error))
- }
- }}
+ shortcut={keys('attachFiles')}
+ onClick={() => void attachFiles()}
>
<Paperclip size={15} />
</IconButton>
@@ -607,11 +633,12 @@ export function Composer({
: isDemo
? 'Simulate send'
: 'Send message'}
- <span className="send-shortcut">Ctrl ↵</span>
+ {sendShortcut && <span className="send-shortcut">{bindingText(sendShortcut)}</span>}
</Button>
<span className="compose-account">{account.email}</span>
<IconButton
label="Discard draft"
+ shortcut={keys('discardDraft')}
onClick={() => setDiscardOpen(true)}
disabled={locked}
>
diff --git a/apps/desktop/src/renderer/src/ConversationRow.tsx b/apps/desktop/src/renderer/src/ConversationRow.tsx
index 69de3a9..fe5c2ae 100644
--- a/apps/desktop/src/renderer/src/ConversationRow.tsx
+++ b/apps/desktop/src/renderer/src/ConversationRow.tsx
@@ -6,6 +6,7 @@ import { SenderAvatar } from './SenderAvatar'
import { AccountMark } from './AccountMark'
import { HintIconButton } from './HintIconButton'
import { actionLimit } from './account-limits'
+import { useShortcutText } from './shortcuts'
export function senderLabel(conversation: Conversation) {
return conversation.from.map((sender) => sender.name || sender.email.split('@')[0]).join(', ')
@@ -40,6 +41,7 @@ export function ConversationRow({
onTrash?: () => void
onToggleRead: () => void
}) {
+ const keys = useShortcutText()
const moveLimit = actionLimit(a, 'move')
return (
<div
@@ -102,7 +104,7 @@ export function ConversationRow({
<div className="row-quick-actions" onClick={(event) => event.stopPropagation()}>
<IconButton
label={c.unread ? 'Mark as read' : 'Mark as unread'}
- shortcut={c.unread ? 'Shift I' : 'U'}
+ shortcut={keys(c.unread ? 'read' : 'unread')}
disabled={busy}
onClick={onToggleRead}
>
@@ -111,7 +113,7 @@ export function ConversationRow({
{onArchive && (
<HintIconButton
label="Archive"
- shortcut="E"
+ shortcut={keys('archive')}
disabled={busy}
hint={moveLimit}
onClick={onArchive}
@@ -122,7 +124,7 @@ export function ConversationRow({
{onTrash && (
<HintIconButton
label="Move to trash"
- shortcut="#"
+ shortcut={keys('trash')}
disabled={busy}
hint={moveLimit}
onClick={onTrash}
diff --git a/apps/desktop/src/renderer/src/DraftList.tsx b/apps/desktop/src/renderer/src/DraftList.tsx
index 93768ca..d0a69ed 100644
--- a/apps/desktop/src/renderer/src/DraftList.tsx
+++ b/apps/desktop/src/renderer/src/DraftList.tsx
@@ -2,6 +2,7 @@ import { ArrowUpRight, FileText, Trash2, X } from '@inlark/ui/icons'
import { Checkbox, IconButton } from '@inlark/ui'
import type { Account, Draft, Message } from '@inlark/core'
import { shortDate } from './mail-date'
+import { useShortcutText } from './shortcuts'
export type DraftItem =
{ kind: 'local'; key: string; draft: Draft } | { kind: 'server'; key: string; message: Message }
@@ -25,6 +26,7 @@ export function DraftRows({
onSelect: (key: string, range: boolean) => void
onDelete: (keys: string[]) => void
}) {
+ const keys = useShortcutText()
return (
<div className={'draft-rows' + (selected.size ? ' selecting' : '')}>
{items.map((item) => {
@@ -65,7 +67,11 @@ export function DraftRows({
<span className="draft-actions">
<ArrowUpRight size={14} aria-hidden="true" />
{canDelete && (
- <IconButton label="Delete draft" shortcut="#" onClick={() => onDelete([item.key])}>
+ <IconButton
+ label="Delete draft"
+ shortcut={keys('trash')}
+ onClick={() => onDelete([item.key])}
+ >
<Trash2 size={15} />
</IconButton>
)}
@@ -90,6 +96,7 @@ export function DraftSelectionBar({
onDelete: () => void
onClear: () => void
}) {
+ const keys = useShortcutText()
return (
<div className="selection-bar" role="region" aria-label="Selection actions">
<div className="selection-summary">
@@ -105,13 +112,13 @@ export function DraftSelectionBar({
<span className="toolbar-divider" />
<IconButton
label={count > 1 ? 'Delete drafts' : 'Delete draft'}
- shortcut="#"
+ shortcut={keys('trash')}
onClick={onDelete}
>
<Trash2 size={16} />
</IconButton>
<span className="toolbar-divider" />
- <IconButton label="Clear selection" shortcut="Esc" onClick={onClear}>
+ <IconButton label="Clear selection" shortcut={keys('back')} onClick={onClear}>
<X size={14} />
</IconButton>
</div>
diff --git a/apps/desktop/src/renderer/src/Reader.tsx b/apps/desktop/src/renderer/src/Reader.tsx
index 1e7f91b..9c95b6f 100644
--- a/apps/desktop/src/renderer/src/Reader.tsx
+++ b/apps/desktop/src/renderer/src/Reader.tsx
@@ -44,6 +44,7 @@ import { formatBytes, longDate, messageDate } from './mail-date'
import { AccountMark } from './AccountMark'
import { HintIconButton } from './HintIconButton'
import { actionLimit } from './account-limits'
+import { ShortcutHint, useShortcutText } from './shortcuts'
const formatAddress = (a: { name: string; email: string }) =>
a.name ? a.name + ' <' + a.email + '>' : a.email
@@ -555,7 +556,7 @@ function UnsubscribeButton({ state, onClick }: { state: UnsubscribeState; onClic
<Tooltip.Positioner sideOffset={7}>
<Tooltip.Popup className="tooltip">
Unsubscribe from this mailing list
- <kbd>Ctrl U</kbd>
+ <ShortcutHint id="unsubscribe" />
</Tooltip.Popup>
</Tooltip.Positioner>
</Tooltip.Portal>
@@ -595,6 +596,7 @@ export function Reader({
onUnsubscribe,
loading = false,
}: ReaderProps) {
+ const keys = useShortcutText()
const last = messages[messages.length - 1]
const initiallyExpanded = () =>
new Set(
@@ -651,7 +653,7 @@ export function Reader({
<HintIconButton
disabled={busy}
label="Archive"
- shortcut="E"
+ shortcut={keys('archive')}
hint={moveLimit}
onClick={() => onAction('archive')}
>
@@ -660,7 +662,7 @@ export function Reader({
<HintIconButton
disabled={busy}
label="Move to trash"
- shortcut="#"
+ shortcut={keys('trash')}
hint={moveLimit}
onClick={() => onAction('trash')}
>
@@ -669,7 +671,7 @@ export function Reader({
<IconButton
disabled={busy}
label="Mark unread"
- shortcut="U"
+ shortcut={keys('unread')}
onClick={() => onAction('unread')}
>
<Mail size={16} />
@@ -678,7 +680,7 @@ export function Reader({
disabled={busy}
aria-pressed={starred}
label={starred ? 'Remove star' : 'Star conversation'}
- shortcut="S"
+ shortcut={keys('star')}
onClick={() => onAction(starred ? 'unstar' : 'star')}
>
<Star size={16} className={starred ? 'starred' : ''} />
@@ -698,20 +700,22 @@ export function Reader({
<MenuItem onClick={onMove} disabled={!!moveLimit}>
<FolderInput size={14} />
Move to folder
- <kbd className="menu-shortcut">V</kbd>
+ <ShortcutHint id="move" className="menu-shortcut" />
</MenuItem>
<MenuItem onClick={() => onAction('spam')} disabled={!!moveLimit}>
<ShieldX size={14} />
Mark as spam
- <kbd className="menu-shortcut">!</kbd>
+ <ShortcutHint id="spam" className="menu-shortcut" />
</MenuItem>
<MenuItem onClick={() => onAction('notSpam')} disabled={!!moveLimit}>
<ShieldCheck size={14} />
Not spam
+ <ShortcutHint id="notSpam" className="menu-shortcut" />
</MenuItem>
<MenuItem onClick={() => onAction('restore')} disabled={!!moveLimit}>
<Inbox size={14} />
Restore to inbox
+ <ShortcutHint id="restore" className="menu-shortcut" />
</MenuItem>
{moveLimit && <p className="menu-note">{moveLimit}</p>}
</Dropdown>
@@ -725,13 +729,18 @@ export function Reader({
<span role="status">{busy ? 'Updating…' : position}</span>
<IconButton
label="Previous conversation"
- shortcut="K"
+ shortcut={keys('previous')}
onClick={onPrevious}
disabled={!onPrevious}
>
<ChevronUp size={16} />
</IconButton>
- <IconButton label="Next conversation" shortcut="J" onClick={onNext} disabled={!onNext}>
+ <IconButton
+ label="Next conversation"
+ shortcut={keys('next')}
+ onClick={onNext}
+ disabled={!onNext}
+ >
<ChevronDown size={16} />
</IconButton>
</div>
@@ -904,18 +913,18 @@ export function Reader({
<span>
<strong>Reply to {last.from[0]?.name || last.from[0]?.email || 'sender'}</strong>
</span>
- <kbd>R</kbd>
+ <ShortcutHint id="reply" />
</button>
<div className="reply-bar">
<Button variant="ghost" onClick={() => onReply(last, 'replyAll')}>
<ReplyAll size={14} />
Reply all
- <kbd>A</kbd>
+ <ShortcutHint id="replyAll" />
</Button>
<Button variant="ghost" onClick={() => onReply(last, 'forward')}>
<Forward size={14} />
Forward
- <kbd>F</kbd>
+ <ShortcutHint id="forward" />
</Button>
</div>
</div>
diff --git a/apps/desktop/src/renderer/src/Settings.tsx b/apps/desktop/src/renderer/src/Settings.tsx
index 4b3e88f..afb0819 100644
--- a/apps/desktop/src/renderer/src/Settings.tsx
+++ b/apps/desktop/src/renderer/src/Settings.tsx
@@ -15,6 +15,7 @@ import {
Folder,
Send,
SquarePen,
+ Keyboard,
} from '@inlark/ui/icons'
import { Button, Dropdown, EmptyState, MenuItem, Modal, Select, Switch } from '@inlark/ui'
import {
@@ -31,6 +32,7 @@ import { SignatureSettings } from './SignatureSettings'
import { AccountSetup, type SetupMode } from './AccountSetup'
import { FolderMappingsDialog } from './FolderMappings'
import { IndexingMeter } from './IndexingMeter'
+import { ShortcutEditor } from './ShortcutEditor'
/** A miniature of the app window in one theme. */
function ThemePreview({ theme, className }: { theme: 'dark' | 'light'; className?: string }) {
@@ -209,6 +211,7 @@ export function SettingsPanel({
['general', 'General', SlidersHorizontal],
['accounts', 'Accounts', Mail],
['signatures', 'Signatures', PenLine],
+ ['shortcuts', 'Shortcuts', Keyboard],
['about', 'About', Info],
].map(([id, name, Icon]) => {
const Component = Icon as typeof Mail
@@ -556,6 +559,15 @@ export function SettingsPanel({
)}
</>
)}
+ {tab === 'shortcuts' && (
+ <>
+ <h3>Keyboard shortcuts</h3>
+ <p className="settings-lead">
+ Click any keys to change them, or + to add another. Changes save right away.
+ </p>
+ <ShortcutEditor />
+ </>
+ )}
{tab === 'about' && (
<>
<div className="about-hero">
diff --git a/apps/desktop/src/renderer/src/ShortcutEditor.tsx b/apps/desktop/src/renderer/src/ShortcutEditor.tsx
new file mode 100644
index 0000000..7572740
--- /dev/null
+++ b/apps/desktop/src/renderer/src/ShortcutEditor.tsx
@@ -0,0 +1,433 @@
+import { Fragment, useEffect, useRef, useState } from 'react'
+import { Button, IconButton, Modal } from '@inlark/ui'
+import { friendlyError } from '@inlark/core'
+import { AlertCircle, Plus, Search, Undo2, X } from '@inlark/ui/icons'
+import {
+ bindingName,
+ chordFromEvent,
+ defaultBindings,
+ findConflicts,
+ isCustomized,
+ sameBinding,
+ shortcutDefinitions,
+ shortcutSections,
+ useShortcuts,
+ ShortcutKeys,
+ type Binding,
+ type ShortcutBindings,
+ type ShortcutConflict,
+ type ShortcutDefinition,
+ type ShortcutId,
+} from './shortcuts'
+
+/** How long a single key waits for a second one, so sequences like G then I can be recorded. */
+const sequenceWait = 1000
+
+const shortcutName = (definition: ShortcutDefinition) =>
+ definition.section === 'Go to' ? 'Go to ' + definition.label : definition.label
+const nameOf = (id: ShortcutId) =>
+ shortcutName(shortcutDefinitions.find((definition) => definition.id === id)!)
+
+/** A plain character may be the first key of a sequence; anything with Ctrl or Alt finishes at once. */
+const canStartSequence = (chord: string) => /^(Shift\+)?.$/u.test(chord)
+
+/** Captures the next shortcut pressed, before anything else in the app can react to it. */
+function ShortcutRecorder({
+ label,
+ onRecord,
+ onCancel,
+}: {
+ label: string
+ onRecord: (binding: Binding) => void
+ onCancel: () => void
+}) {
+ const [steps, setSteps] = useState<Binding>([])
+ const ref = useRef<HTMLSpanElement>(null)
+ const state = useRef({ steps, done: false, onRecord, onCancel })
+ state.current.onRecord = onRecord
+ state.current.onCancel = onCancel
+ useEffect(() => {
+ ref.current?.focus()
+ let timer: number | undefined
+ const finish = (binding?: Binding) => {
+ window.clearTimeout(timer)
+ if (state.current.done) return
+ state.current.done = true
+ if (binding?.length) state.current.onRecord(binding)
+ else state.current.onCancel()
+ }
+ const listener = (event: KeyboardEvent) => {
+ // Tab still moves focus, which finishes recording.
+ if (event.key === 'Tab') return
+ event.preventDefault()
+ event.stopImmediatePropagation()
+ if (event.repeat) return
+ if (event.key === 'Escape') return finish()
+ const chord = chordFromEvent(event)
+ if (!chord) return
+ window.clearTimeout(timer)
+ const next = [...state.current.steps, chord]
+ if (next.length > 1 || !canStartSequence(chord)) return finish(next)
+ state.current.steps = next
+ setSteps(next)
+ timer = window.setTimeout(() => finish(next), sequenceWait)
+ }
+ window.addEventListener('keydown', listener, true)
+ return () => {
+ window.removeEventListener('keydown', listener, true)
+ window.clearTimeout(timer)
+ }
+ }, [])
+ return (
+ <span
+ ref={ref}
+ tabIndex={0}
+ role="textbox"
+ aria-label={'Press a new shortcut for ' + label}
+ className="shortcut-recorder"
+ onBlur={() => {
+ if (state.current.done) return
+ state.current.done = true
+ if (state.current.steps.length) onRecord(state.current.steps)
+ else onCancel()
+ }}
+ >
+ {steps.length ? (
+ <>
+ <ShortcutKeys binding={steps} />
+ <span className="shortcut-then">then…</span>
+ <span
+ className="shortcut-recorder-timer"
+ style={{ animationDuration: sequenceWait + 'ms' }}
+ />
+ </>
+ ) : (
+ 'Press keys…'
+ )}
+ </span>
+ )
+}
+
+type Recording = { id: ShortcutId; index?: number }
+type Notice =
+ | { id: ShortcutId; kind: 'recording' }
+ | { id: ShortcutId; kind: 'duplicate' }
+ | {
+ id: ShortcutId
+ kind: 'conflict'
+ index?: number
+ binding: Binding
+ conflicts: ShortcutConflict[]
+ }
+
+/**
+ * Lists every shortcut with all of its keys. Click keys to change them, add more with +, and
+ * restore the defaults per shortcut or all at once. Changes save immediately.
+ */
+export function ShortcutEditor({ autoFocus }: { autoFocus?: boolean }) {
+ const { bindings, save } = useShortcuts()
+ const [query, setQuery] = useState('')
+ const [recording, setRecording] = useState<Recording>()
+ const [notice, setNotice] = useState<Notice>()
+ const [confirmReset, setConfirmReset] = useState(false)
+ const [error, setError] = useState<string>()
+ const persist = (next: ShortcutBindings) => {
+ setError(undefined)
+ save(next).catch((e) => setError(friendlyError(e)))
+ }
+ const focus = (id: string) => requestAnimationFrame(() => document.getElementById(id)?.focus())
+ const elementId = (id: ShortcutId, index?: number) =>
+ 'shortcut-' + id + '-' + (index === undefined ? 'add' : index)
+
+ const apply = (
+ id: ShortcutId,
+ change: (current: Binding[]) => Binding[],
+ taken: ShortcutConflict[] = [],
+ ) => {
+ const next: ShortcutBindings = { ...bindings }
+ for (const conflict of taken)
+ next[conflict.id] = next[conflict.id].filter((b) => !sameBinding(b, conflict.binding))
+ next[id] = change(next[id])
+ persist(next)
+ }
+ const place = (index: number | undefined, binding: Binding) => (current: Binding[]) =>
+ index === undefined
+ ? [...current, binding]
+ : current.map((existing, i) => (i === index ? binding : existing))
+
+ const record = ({ id, index }: Recording, binding: Binding) => {
+ setRecording(undefined)
+ setNotice(undefined)
+ focus(elementId(id, index))
+ const current = bindings[id]
+ if (index !== undefined && sameBinding(current[index], binding)) return
+ if (current.some((existing, i) => i !== index && sameBinding(existing, binding)))
+ return setNotice({ id, kind: 'duplicate' })
+ const conflicts = findConflicts(bindings, id, binding)
+ if (conflicts.length) return setNotice({ id, kind: 'conflict', index, binding, conflicts })
+ apply(id, place(index, binding))
+ }
+ const startRecording = (next: Recording) => {
+ setRecording(next)
+ setNotice({ id: next.id, kind: 'recording' })
+ }
+ const restore = (id: ShortcutId) => {
+ const defaults = defaultBindings(id)
+ // Defaults win back keys that were handed to another shortcut in the meantime.
+ apply(
+ id,
+ () => defaults,
+ defaults.flatMap((binding) => findConflicts(bindings, id, binding)),
+ )
+ setNotice(undefined)
+ }
+
+ const search = query.trim().toLowerCase()
+ const matches = shortcutDefinitions.filter((definition) =>
+ [definition.label, definition.section, 'description' in definition && definition.description]
+ .filter(Boolean)
+ .some((text) => String(text).toLowerCase().includes(search)),
+ )
+ const customized = shortcutDefinitions.some(({ id }) => isCustomized(bindings, id))
+
+ return (
+ <div className="shortcut-editor">
+ <div className="shortcut-toolbar">
+ <label className="shortcut-search">
+ <Search size={14} />
+ <input
+ autoFocus={autoFocus}
+ type="search"
+ value={query}
+ placeholder="Search shortcuts"
+ aria-label="Search shortcuts"
+ onChange={(event) => setQuery(event.target.value)}
+ onKeyDown={(event) => {
+ // Clear the search first; a second Escape closes the dialog.
+ if (event.key === 'Escape' && query) {
+ event.stopPropagation()
+ setQuery('')
+ }
+ }}
+ />
+ </label>
+ {customized && (
+ <Button size="small" variant="ghost" onClick={() => setConfirmReset(true)}>
+ <Undo2 size={13} />
+ Restore all defaults
+ </Button>
+ )}
+ </div>
+ {error && (
+ <p className="form-error shortcut-error" role="alert">
+ <AlertCircle size={14} />
+ <span>Couldn’t save your shortcuts. {error}</span>
+ </p>
+ )}
+ <div className="shortcut-sections">
+ {shortcutSections.map((section) => {
+ const items = matches.filter((definition) => definition.section === section)
+ if (!items.length) return null
+ return (
+ <section key={section}>
+ <h3>{section}</h3>
+ {items.map((definition) => {
+ const { id } = definition
+ const name = shortcutName(definition)
+ const list = bindings[id]
+ const rowNotice = notice?.id === id ? notice : undefined
+ return (
+ <div
+ className={
+ 'shortcut-item' + (recording?.id === id ? ' shortcut-item-recording' : '')
+ }
+ key={id}
+ >
+ <div className="shortcut-row">
+ <span className="shortcut-label">
+ {definition.label}
+ {'description' in definition && <small>{definition.description}</small>}
+ </span>
+ <span className="shortcut-bindings">
+ {list.map((binding, index) =>
+ recording?.id === id && recording.index === index ? (
+ <ShortcutRecorder
+ key={index}
+ label={name}
+ onRecord={(next) => record({ id, index }, next)}
+ onCancel={() => {
+ setRecording(undefined)
+ setNotice(undefined)
+ focus(elementId(id, index))
+ }}
+ />
+ ) : (
+ <span className="shortcut-binding" key={index}>
+ <button
+ id={elementId(id, index)}
+ className="shortcut-binding-keys"
+ aria-label={'Change ' + bindingName(binding) + ' for ' + name}
+ onClick={() => startRecording({ id, index })}
+ onKeyDown={(event) => {
+ if (event.key === 'Backspace' || event.key === 'Delete') {
+ event.preventDefault()
+ apply(id, (current) => current.filter((_, i) => i !== index))
+ focus(elementId(id, list.length > 1 ? 0 : undefined))
+ }
+ }}
+ >
+ <ShortcutKeys binding={binding} />
+ </button>
+ <button
+ className="shortcut-remove"
+ aria-label={'Remove ' + bindingName(binding) + ' from ' + name}
+ title="Remove"
+ onClick={() => {
+ apply(id, (current) => current.filter((_, i) => i !== index))
+ setNotice(undefined)
+ }}
+ >
+ <X size={10} />
+ </button>
+ </span>
+ ),
+ )}
+ {recording?.id === id && recording.index === undefined ? (
+ <ShortcutRecorder
+ label={name}
+ onRecord={(next) => record({ id }, next)}
+ onCancel={() => {
+ setRecording(undefined)
+ setNotice(undefined)
+ focus(elementId(id))
+ }}
+ />
+ ) : list.length ? (
+ <IconButton
+ id={elementId(id)}
+ className="shortcut-add"
+ label={'Add another shortcut'}
+ aria-label={'Add a shortcut for ' + name}
+ onClick={() => startRecording({ id })}
+ >
+ <Plus size={13} />
+ </IconButton>
+ ) : (
+ <button
+ id={elementId(id)}
+ className="shortcut-empty"
+ aria-label={'Add a shortcut for ' + name}
+ onClick={() => startRecording({ id })}
+ >
+ <Plus size={12} />
+ Add shortcut
+ </button>
+ )}
+ {isCustomized(bindings, id) && (
+ <IconButton
+ className="shortcut-reset"
+ label="Restore default"
+ aria-label={'Restore the default shortcut for ' + name}
+ onClick={() => restore(id)}
+ >
+ <Undo2 size={13} />
+ </IconButton>
+ )}
+ </span>
+ </div>
+ {rowNotice?.kind === 'recording' && (
+ <p className="shortcut-notice" role="status">
+ Press the keys you want to use, or Esc to cancel. For a sequence like{' '}
+ <ShortcutKeys binding={['G', 'I']} />, press the second key right after the
+ first.
+ </p>
+ )}
+ {rowNotice?.kind === 'duplicate' && (
+ <p className="shortcut-notice" role="status">
+ That’s already a shortcut for {name}.
+ </p>
+ )}
+ {rowNotice?.kind === 'conflict' && (
+ <div className="shortcut-notice shortcut-conflict" role="alert">
+ <p>
+ <ShortcutKeys binding={rowNotice.binding} /> conflicts with{' '}
+ {rowNotice.conflicts.map((conflict, index) => (
+ <Fragment key={conflict.id + index}>
+ {index > 0 && ', '}
+ <strong>{nameOf(conflict.id)}</strong>
+ {rowNotice.conflicts.length === 1 &&
+ !sameBinding(conflict.binding, rowNotice.binding) && (
+ <>
+ {' '}
+ (<ShortcutKeys binding={conflict.binding} />)
+ </>
+ )}
+ </Fragment>
+ ))}
+ .
+ </p>
+ <span className="shortcut-conflict-actions">
+ <Button
+ size="small"
+ variant="ghost"
+ onClick={() => {
+ setNotice(undefined)
+ focus(elementId(id, rowNotice.index))
+ }}
+ >
+ Cancel
+ </Button>
+ <Button
+ size="small"
+ onClick={() => {
+ apply(
+ id,
+ place(rowNotice.index, rowNotice.binding),
+ rowNotice.conflicts,
+ )
+ setNotice(undefined)
+ focus(elementId(id, rowNotice.index))
+ }}
+ >
+ Use for {name}
+ </Button>
+ </span>
+ </div>
+ )}
+ </div>
+ )
+ })}
+ </section>
+ )
+ })}
+ {!matches.length && (
+ <p className="shortcut-no-results">No shortcuts match “{query.trim()}”.</p>
+ )}
+ </div>
+ <Modal
+ open={confirmReset}
+ onOpenChange={setConfirmReset}
+ title="Restore default shortcuts?"
+ description="Every shortcut goes back to its original keys. Your changes are removed."
+ >
+ <div className="modal-actions">
+ <Button onClick={() => setConfirmReset(false)}>Cancel</Button>
+ <Button
+ variant="primary"
+ onClick={() => {
+ persist(
+ Object.fromEntries(
+ shortcutDefinitions.map(({ id }) => [id, defaultBindings(id)]),
+ ) as ShortcutBindings,
+ )
+ setNotice(undefined)
+ setConfirmReset(false)
+ }}
+ >
+ Restore defaults
+ </Button>
+ </div>
+ </Modal>
+ </div>
+ )
+}
diff --git a/apps/desktop/src/renderer/src/ShortcutsProvider.tsx b/apps/desktop/src/renderer/src/ShortcutsProvider.tsx
new file mode 100644
index 0000000..0c21595
--- /dev/null
+++ b/apps/desktop/src/renderer/src/ShortcutsProvider.tsx
@@ -0,0 +1,34 @@
+import { useMemo, type ReactNode } from 'react'
+import { useQuery } from '@tanstack/react-query'
+import type { Bootstrap } from '@inlark/core'
+import { api } from './api'
+import { queryClient } from './cache'
+import { ShortcutsContext, overridesFor, resolveShortcuts, type ShortcutsValue } from './shortcuts'
+
+/** Provides the saved shortcuts everywhere, including the settings and the shortcuts dialog. */
+export function ShortcutsProvider({ children }: { children: ReactNode }) {
+ const { data } = useQuery({ queryKey: ['bootstrap'], queryFn: () => api.bootstrap() })
+ const saved = data?.settings.shortcuts
+ const value = useMemo<ShortcutsValue>(
+ () => ({
+ bindings: resolveShortcuts(saved),
+ save: async (bindings) => {
+ const current = queryClient.getQueryData<Bootstrap>(['bootstrap'])
+ if (!current) return
+ const next = { ...current.settings, shortcuts: overridesFor(bindings) }
+ queryClient.setQueryData<Bootstrap>(['bootstrap'], { ...current, settings: next })
+ try {
+ await api.settings(next)
+ } catch (error) {
+ queryClient.setQueryData<Bootstrap>(
+ ['bootstrap'],
+ (old) => old && { ...old, settings: { ...old.settings, shortcuts: saved } },
+ )
+ throw error
+ }
+ },
+ }),
+ [saved],
+ )
+ return <ShortcutsContext.Provider value={value}>{children}</ShortcutsContext.Provider>
+}
diff --git a/apps/desktop/src/renderer/src/Sidebar.tsx b/apps/desktop/src/renderer/src/Sidebar.tsx
index 74cbc1f..6bf039c 100644
--- a/apps/desktop/src/renderer/src/Sidebar.tsx
+++ b/apps/desktop/src/renderer/src/Sidebar.tsx
@@ -23,15 +23,16 @@ import { Wordmark } from '@inlark/ui/components/wordmark'
import type { Account, Mailbox, View } from '@inlark/core'
import appIcon from '../../../resources/icon-mark.svg?no-inline'
import { AccountMark } from './AccountMark'
+import { ShortcutHint, useShortcutText, type ShortcutId } from './shortcuts'
-export const views: { id: View; title: string; icon: typeof Inbox; key?: string }[] = [
- { id: 'inbox', title: 'Inbox', icon: Inbox, key: 'G I' },
- { id: 'starred', title: 'Starred', icon: Star, key: 'G S' },
- { id: 'sent', title: 'Sent', icon: Send, key: 'G T' },
- { id: 'drafts', title: 'Drafts', icon: FileText, key: 'G D' },
- { id: 'archive', title: 'Archive', icon: Archive, key: 'G A' },
- { id: 'junk', title: 'Spam', icon: ShieldX },
- { id: 'trash', title: 'Trash', icon: Trash2 },
+export const views: { id: View; title: string; icon: typeof Inbox; shortcut?: ShortcutId }[] = [
+ { id: 'inbox', title: 'Inbox', icon: Inbox, shortcut: 'goInbox' },
+ { id: 'starred', title: 'Starred', icon: Star, shortcut: 'goStarred' },
+ { id: 'sent', title: 'Sent', icon: Send, shortcut: 'goSent' },
+ { id: 'drafts', title: 'Drafts', icon: FileText, shortcut: 'goDrafts' },
+ { id: 'archive', title: 'Archive', icon: Archive, shortcut: 'goArchive' },
+ { id: 'junk', title: 'Spam', icon: ShieldX, shortcut: 'goSpam' },
+ { id: 'trash', title: 'Trash', icon: Trash2, shortcut: 'goTrash' },
]
const statusLabel: Record<Account['status'], string> = {
connecting: 'connecting',
@@ -80,6 +81,7 @@ export function Sidebar({
folder?: Mailbox,
) => void
}) {
+ const keys = useShortcutText()
const go = onNavigate
// Transient connecting states already show a spinner on the account row.
const unavailable = accounts.filter((a) => a.status !== 'connected' && a.status !== 'connecting')
@@ -121,10 +123,15 @@ export function Sidebar({
{!collapsed && <Wordmark className="brand-wordmark" />}
</div>
<div className="sidebar-tools">
- <IconButton label="Search and commands" shortcut="Ctrl K" onClick={onSearch}>
+ <IconButton label="Search and commands" shortcut={keys('commandMenu')} onClick={onSearch}>
<Search size={14} />
</IconButton>
- <IconButton className="sidebar-compose" label="Compose" shortcut="C" onClick={onCompose}>
+ <IconButton
+ className="sidebar-compose"
+ label="Compose"
+ shortcut={keys('compose')}
+ onClick={onCompose}
+ >
<SquarePen size={16} />
</IconButton>
</div>
@@ -145,7 +152,7 @@ export function Sidebar({
title={
v.title +
(v.id === 'inbox' ? ' · ' + unreadCount + ' unread' : '') +
- (v.key ? ' · ' + v.key : '')
+ (v.shortcut && keys(v.shortcut) ? ' · ' + keys(v.shortcut) : '')
}
aria-current={
view === v.id && !route.account && !route.folder && !route.q ? 'page' : undefined
@@ -352,13 +359,17 @@ export function Sidebar({
)}
<div className="sidebar-footer">
{collapsed && (
- <IconButton label="Expand sidebar" shortcut="[" onClick={onToggleCollapsed}>
+ <IconButton
+ label="Expand sidebar"
+ shortcut={keys('toggleSidebar')}
+ onClick={onToggleCollapsed}
+ >
<PanelLeftOpen size={15} />
</IconButton>
)}
<button
className="nav-item"
- title="Settings · Ctrl ,"
+ title={'Settings' + (keys('settings') ? ' · ' + keys('settings') : '')}
aria-label="Settings"
onClick={() => onSettings('general')}
>
@@ -366,12 +377,16 @@ export function Sidebar({
{!collapsed && (
<>
<span>Settings</span>
- <kbd>Ctrl ,</kbd>
+ <ShortcutHint id="settings" />
</>
)}
</button>
{!collapsed && (
- <IconButton label="Collapse sidebar" shortcut="[" onClick={onToggleCollapsed}>
+ <IconButton
+ label="Collapse sidebar"
+ shortcut={keys('toggleSidebar')}
+ onClick={onToggleCollapsed}
+ >
<PanelLeftClose size={15} />
</IconButton>
)}
diff --git a/apps/desktop/src/renderer/src/character-key.ts b/apps/desktop/src/renderer/src/character-key.ts
deleted file mode 100644
index 1b00a52..0000000
--- a/apps/desktop/src/renderer/src/character-key.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { useEffect, useRef } from 'react'
-
-const typing = (element: Element | null) =>
- element instanceof HTMLInputElement ||
- element instanceof HTMLTextAreaElement ||
- element instanceof HTMLSelectElement ||
- (element instanceof HTMLElement && element.isContentEditable)
-
-/**
- * Binds a shortcut to the character a key produces rather than its position, so `?`, `#` and
- * `!` work on every keyboard layout whether or not they need Shift.
- */
-export function useCharacterKey(characters: string, handler: () => void, enabled = true) {
- const latest = useRef(handler)
- latest.current = handler
- useEffect(() => {
- if (!enabled) return
- const listener = (event: KeyboardEvent) => {
- if (
- event.defaultPrevented ||
- event.ctrlKey ||
- event.metaKey ||
- event.altKey ||
- !characters.includes(event.key) ||
- typing(document.activeElement)
- )
- return
- event.preventDefault()
- latest.current()
- }
- document.addEventListener('keydown', listener)
- return () => document.removeEventListener('keydown', listener)
- }, [characters, enabled])
-}
diff --git a/apps/desktop/src/renderer/src/main.tsx b/apps/desktop/src/renderer/src/main.tsx
index f7a7503..fde74a7 100644
--- a/apps/desktop/src/renderer/src/main.tsx
+++ b/apps/desktop/src/renderer/src/main.tsx
@@ -11,6 +11,7 @@ import {
import { TooltipProvider } from '@inlark/ui'
import { queryClient, restoreCache } from './cache'
import { App } from './App'
+import { ShortcutsProvider } from './ShortcutsProvider'
import '@inlark/ui/styles.css'
import './styles.css'
@@ -83,7 +84,9 @@ void restoreCache().finally(() =>
<ErrorBoundary>
<QueryClientProvider client={queryClient}>
<TooltipProvider delay={500}>
- <RouterProvider router={router} />
+ <ShortcutsProvider>
+ <RouterProvider router={router} />
+ </ShortcutsProvider>
</TooltipProvider>
</QueryClientProvider>
</ErrorBoundary>
diff --git a/apps/desktop/src/renderer/src/shortcuts.tsx b/apps/desktop/src/renderer/src/shortcuts.tsx
new file mode 100644
index 0000000..f38df2a
--- /dev/null
+++ b/apps/desktop/src/renderer/src/shortcuts.tsx
@@ -0,0 +1,338 @@
+import { Fragment, createContext, useContext } from 'react'
+import {
+ detectPlatform,
+ formatForDisplay,
+ normalizeHotkey,
+ normalizeRegisterableHotkey,
+ parseKeyboardEvent,
+ useHotkeys,
+ useHotkeySequences,
+ validateHotkey,
+ type Hotkey,
+ type UseHotkeyDefinition,
+ type UseHotkeySequenceDefinition,
+} from '@tanstack/react-hotkeys'
+
+/** One way to trigger a shortcut: a single chord such as `Mod+K`, or a sequence such as `G I`. */
+export type Binding = string[]
+
+export const shortcutSections = ['Navigate', 'Go to', 'Organize', 'Select', 'Write', 'App'] as const
+
+export const shortcutDefinitions = [
+ { id: 'next', section: 'Navigate', label: 'Next conversation', defaults: [['J'], ['ArrowDown']] },
+ {
+ id: 'previous',
+ section: 'Navigate',
+ label: 'Previous conversation',
+ defaults: [['K'], ['ArrowUp']],
+ },
+ { id: 'open', section: 'Navigate', label: 'Open conversation', defaults: [['Enter'], ['O']] },
+ {
+ id: 'back',
+ section: 'Navigate',
+ label: 'Back to list',
+ description: 'Also clears the selection or search.',
+ defaults: [['Escape']],
+ },
+ { id: 'search', section: 'Navigate', label: 'Search mail', defaults: [['/']] },
+ { id: 'filter', section: 'Navigate', label: 'Filter conversations', defaults: [['Shift+F']] },
+ {
+ id: 'toggleUnread',
+ section: 'Navigate',
+ label: 'Toggle unread-only view',
+ defaults: [['Shift+L']],
+ },
+ { id: 'commandMenu', section: 'Navigate', label: 'Command menu', defaults: [['Mod+K']] },
+ { id: 'toggleSidebar', section: 'Navigate', label: 'Toggle sidebar', defaults: [['[']] },
+ { id: 'goInbox', section: 'Go to', label: 'Inbox', defaults: [['G', 'I']] },
+ { id: 'goStarred', section: 'Go to', label: 'Starred', defaults: [['G', 'S']] },
+ { id: 'goSent', section: 'Go to', label: 'Sent', defaults: [['G', 'T']] },
+ { id: 'goDrafts', section: 'Go to', label: 'Drafts', defaults: [['G', 'D']] },
+ { id: 'goArchive', section: 'Go to', label: 'Archive', defaults: [['G', 'A']] },
+ { id: 'goSpam', section: 'Go to', label: 'Spam', defaults: [['G', 'J']] },
+ { id: 'goTrash', section: 'Go to', label: 'Trash', defaults: [['G', 'B']] },
+ { id: 'goAll', section: 'Go to', label: 'All mail', defaults: [['G', 'M']] },
+ { id: 'archive', section: 'Organize', label: 'Archive', defaults: [['E']] },
+ {
+ id: 'trash',
+ section: 'Organize',
+ label: 'Move to trash',
+ description: 'In Drafts, deletes the selected drafts.',
+ defaults: [['#'], ['Backspace'], ['Delete']],
+ },
+ { id: 'spam', section: 'Organize', label: 'Mark as spam', defaults: [['!']] },
+ { id: 'notSpam', section: 'Organize', label: 'Not spam', defaults: [['Shift+N']] },
+ { id: 'restore', section: 'Organize', label: 'Restore to inbox', defaults: [['Shift+E']] },
+ { id: 'move', section: 'Organize', label: 'Move to folder', defaults: [['V']] },
+ { id: 'createFolder', section: 'Organize', label: 'Create a folder', defaults: [] },
+ {
+ id: 'unsubscribe',
+ section: 'Organize',
+ label: 'Unsubscribe from mailing list',
+ defaults: [['Mod+U']],
+ },
+ { id: 'star', section: 'Organize', label: 'Star or unstar', defaults: [['S']] },
+ { id: 'unread', section: 'Organize', label: 'Mark as unread', defaults: [['U'], ['Shift+U']] },
+ { id: 'read', section: 'Organize', label: 'Mark as read', defaults: [['Shift+I']] },
+ { id: 'undo', section: 'Organize', label: 'Undo last action', defaults: [['Z'], ['Mod+Z']] },
+ { id: 'select', section: 'Select', label: 'Select conversation', defaults: [['X']] },
+ { id: 'selectRange', section: 'Select', label: 'Select a range', defaults: [['Shift+X']] },
+ { id: 'selectAll', section: 'Select', label: 'Select all loaded', defaults: [['Mod+A']] },
+ { id: 'compose', section: 'Write', label: 'Compose', defaults: [['C']] },
+ { id: 'reply', section: 'Write', label: 'Reply', defaults: [['R']] },
+ { id: 'replyAll', section: 'Write', label: 'Reply all', defaults: [['A']] },
+ { id: 'forward', section: 'Write', label: 'Forward', defaults: [['F']] },
+ { id: 'send', section: 'Write', label: 'Send message', defaults: [['Mod+Enter']] },
+ {
+ id: 'attachFiles',
+ section: 'Write',
+ label: 'Attach files',
+ description: 'While composing a message.',
+ defaults: [['Mod+Shift+A']],
+ },
+ { id: 'showCc', section: 'Write', label: 'Show and focus Cc', defaults: [['Mod+Shift+C']] },
+ { id: 'showBcc', section: 'Write', label: 'Show and focus Bcc', defaults: [['Mod+Shift+B']] },
+ {
+ id: 'expandComposer',
+ section: 'Write',
+ label: 'Expand or restore composer',
+ defaults: [['Mod+Shift+F']],
+ },
+ {
+ id: 'saveClose',
+ section: 'Write',
+ label: 'Save and close draft',
+ defaults: [['Mod+Shift+Enter']],
+ },
+ {
+ id: 'discardDraft',
+ section: 'Write',
+ label: 'Discard draft',
+ description: 'Asks for confirmation before deleting.',
+ defaults: [['Mod+Shift+Backspace']],
+ },
+ { id: 'refresh', section: 'App', label: 'Refresh mail', defaults: [['Mod+R'], ['F5']] },
+ { id: 'toggleDensity', section: 'App', label: 'Toggle message density', defaults: [] },
+ { id: 'settings', section: 'App', label: 'Open settings', defaults: [['Mod+,']] },
+ { id: 'shortcuts', section: 'App', label: 'Keyboard shortcuts', defaults: [['?']] },
+] as const satisfies readonly {
+ id: string
+ section: (typeof shortcutSections)[number]
+ label: string
+ description?: string
+ defaults: readonly (readonly string[])[]
+}[]
+
+export type ShortcutId = (typeof shortcutDefinitions)[number]['id']
+export type ShortcutDefinition = (typeof shortcutDefinitions)[number]
+export type ShortcutBindings = Record<ShortcutId, Binding[]>
+/** Saved changes from the defaults, keyed by shortcut. An empty list means “no shortcut”. */
+export type ShortcutOverrides = Record<string, Binding[]>
+
+export const platform = detectPlatform()
+
+const definitionById = new Map<string, ShortcutDefinition>(
+ shortcutDefinitions.map((definition) => [definition.id, definition]),
+)
+export const defaultBindings = (id: ShortcutId): Binding[] =>
+ definitionById.get(id)!.defaults.map((binding) => [...binding])
+
+const bindingKey = (binding: Binding) =>
+ binding.map((chord) => normalizeHotkey(chord as Hotkey, platform)).join(' ')
+export const sameBinding = (a: Binding, b: Binding) => bindingKey(a) === bindingKey(b)
+const sameBindings = (a: Binding[], b: Binding[]) =>
+ a.length === b.length && a.every((binding, index) => sameBinding(binding, b[index]))
+
+export function resolveShortcuts(overrides: ShortcutOverrides = {}): ShortcutBindings {
+ const bindings = Object.fromEntries(
+ shortcutDefinitions.map(({ id }) => {
+ // Skip malformed keys so one bad saved value can't break registering the rest.
+ const saved = overrides[id]?.filter((binding) =>
+ binding.every((chord) => validateHotkey(chord as Hotkey).valid),
+ )
+ return [id, saved || defaultBindings(id)]
+ }),
+ ) as ShortcutBindings
+ // A newly introduced default must never take keys someone already assigned to another action.
+ const customized = new Set(
+ shortcutDefinitions.filter(({ id }) => overrides[id]).map(({ id }) => id),
+ )
+ if (customized.size)
+ for (const { id } of shortcutDefinitions)
+ if (!customized.has(id))
+ bindings[id] = bindings[id].filter(
+ (binding) =>
+ !findConflicts(bindings, id, binding).some((conflict) => customized.has(conflict.id)),
+ )
+ return bindings
+}
+
+/** Records only what differs from the defaults, so improved defaults still reach everyone else. */
+export function overridesFor(bindings: ShortcutBindings): ShortcutOverrides {
+ return Object.fromEntries(
+ shortcutDefinitions
+ .filter(({ id }) => !sameBindings(bindings[id], defaultBindings(id)))
+ .map(({ id }) => [id, bindings[id]]),
+ )
+}
+
+export const isCustomized = (bindings: ShortcutBindings, id: ShortcutId) =>
+ !sameBindings(bindings[id], defaultBindings(id))
+
+/** The keys of one chord as they read on this platform, such as `['⌘', 'K']` or `['Ctrl', 'K']`. */
+export const chordKeys = (chord: string) =>
+ formatForDisplay(chord as Hotkey, { platform, parts: true })
+
+/** A compact label for tooltips and menus, such as `Ctrl K` or `G I`. */
+export const bindingText = (binding: Binding) =>
+ binding.map((chord) => chordKeys(chord).join(' ')).join(' ')
+
+/** Reads a binding aloud, such as “Control K” or “G then I”. */
+export const bindingName = (binding: Binding) =>
+ binding
+ .map((chord) =>
+ formatForDisplay(chord as Hotkey, { platform, useSymbols: false, parts: true }).join(' '),
+ )
+ .join(' then ')
+
+/**
+ * The chord a keydown produces, or nothing for keys that can't start a shortcut yet (modifiers,
+ * dead keys, composition). Characters are recorded rather than key positions so `#` and `?` mean
+ * the same thing on every layout.
+ */
+export function chordFromEvent(event: KeyboardEvent): string | undefined {
+ if (event.isComposing || ['Dead', 'Unidentified', 'Process', 'AltGraph'].includes(event.key))
+ return
+ const parsed = parseKeyboardEvent(event, platform)
+ if (!parsed.key || ['Control', 'Shift', 'Alt', 'Meta'].includes(parsed.key)) return
+ let key = parsed.key
+ let { ctrl, alt } = parsed
+ // AltGr types characters; it is not a Ctrl+Alt shortcut.
+ if (event.getModifierState?.('AltGraph')) ctrl = alt = false
+ // Option and Alt change the character a key types, so use the key's position for letters and digits.
+ const position = /^Key([A-Z])$|^Digit(\d)$/.exec(event.code)
+ if (alt && position) key = position[1] || position[2]
+ // Shift is part of a character such as # or ? on some layouts and not others; matching allows both.
+ const shift = parsed.shift && !(key.length === 1 && !/\p{Letter}/u.test(key))
+ const chord = normalizeRegisterableHotkey(
+ { key, ctrl, alt, shift, meta: parsed.meta },
+ platform,
+ ) as string
+ return validateHotkey(chord as Hotkey).valid ? chord : undefined
+}
+
+export type ShortcutConflict = { id: ShortcutId; binding: Binding }
+
+/**
+ * Other shortcuts that would fire instead of, or alongside, this binding: the same keys, or a
+ * sequence that one starts with the other.
+ */
+export function findConflicts(
+ bindings: ShortcutBindings,
+ id: ShortcutId,
+ binding: Binding,
+): ShortcutConflict[] {
+ const keys = binding.map((chord) => bindingKey([chord]))
+ return shortcutDefinitions.flatMap(({ id: other }) =>
+ other === id
+ ? []
+ : bindings[other]
+ .filter((existing) => {
+ const steps = existing.map((chord) => bindingKey([chord]))
+ const length = Math.min(steps.length, keys.length)
+ return steps.slice(0, length).join(' ') === keys.slice(0, length).join(' ')
+ })
+ .map((existing) => ({ id: other, binding: existing })),
+ )
+}
+
+export type ShortcutsValue = {
+ bindings: ShortcutBindings
+ /** Shows the change at once, and puts it back (and rejects) if it cannot be saved. */
+ save: (bindings: ShortcutBindings) => Promise<void>
+}
+export const ShortcutsContext = createContext<ShortcutsValue>({
+ bindings: resolveShortcuts(),
+ save: async () => {},
+})
+
+export const useShortcuts = () => useContext(ShortcutsContext)
+
+/** The label of a shortcut's first binding, for tooltips and hints. */
+export function useShortcutText() {
+ const { bindings } = useShortcuts()
+ return (id: ShortcutId) => {
+ const first = bindings[id][0]
+ return first ? bindingText(first) : undefined
+ }
+}
+
+export type ShortcutHandler = {
+ run: () => void
+ /** Defaults to the hook's `enabled`. */
+ enabled?: boolean
+ ignoreInputs?: boolean | ((binding: Binding) => boolean)
+}
+
+/** Registers every binding of each handled shortcut. */
+export function useShortcutHandlers(
+ bindings: ShortcutBindings,
+ handlers: Partial<Record<ShortcutId, ShortcutHandler>>,
+ enabled = true,
+) {
+ const hotkeys: UseHotkeyDefinition[] = []
+ const sequences: UseHotkeySequenceDefinition[] = []
+ for (const [id, handler] of Object.entries(handlers) as [ShortcutId, ShortcutHandler][]) {
+ const options = {
+ conflictBehavior: 'replace',
+ enabled: handler.enabled ?? enabled,
+ } as const
+ for (const binding of bindings[id]) {
+ const bindingOptions = {
+ ...options,
+ ...(handler.ignoreInputs !== undefined && {
+ ignoreInputs:
+ typeof handler.ignoreInputs === 'function'
+ ? handler.ignoreInputs(binding)
+ : handler.ignoreInputs,
+ }),
+ }
+ if (binding.length === 1)
+ hotkeys.push({
+ hotkey: binding[0] as Hotkey,
+ callback: handler.run,
+ options: bindingOptions,
+ })
+ else
+ sequences.push({
+ sequence: binding as Hotkey[],
+ callback: handler.run,
+ options: bindingOptions,
+ })
+ }
+ }
+ useHotkeys(hotkeys)
+ useHotkeySequences(sequences)
+}
+
+/** The keys of a binding, with “then” between the steps of a sequence. */
+export function ShortcutKeys({ binding, className }: { binding: Binding; className?: string }) {
+ return (
+ <span className={'shortcut-keys' + (className ? ' ' + className : '')}>
+ {binding.map((chord, step) => (
+ <Fragment key={step}>
+ {step > 0 && <span className="shortcut-then">then</span>}
+ {chordKeys(chord).map((key, index) => (
+ <kbd key={index}>{key}</kbd>
+ ))}
+ </Fragment>
+ ))}
+ </span>
+ )
+}
+
+/** The first keys of a shortcut, or nothing when it has none. */
+export function ShortcutHint({ id, className }: { id: ShortcutId; className?: string }) {
+ const binding = useShortcuts().bindings[id][0]
+ return binding ? <ShortcutKeys binding={binding} className={className} /> : null
+}
diff --git a/apps/desktop/src/renderer/src/styles.css b/apps/desktop/src/renderer/src/styles.css
index 9a42903..6926d81 100644
--- a/apps/desktop/src/renderer/src/styles.css
+++ b/apps/desktop/src/renderer/src/styles.css
@@ -798,7 +798,7 @@ svg.starred {
.footer-shortcuts:hover {
color: var(--text);
}
-.footer-shortcuts span {
+.footer-shortcuts > span:not(.shortcut-keys) {
margin-right: 9px;
}
.list-footer kbd {
@@ -2693,7 +2693,7 @@ fieldset.compose-format:disabled {
.density-compact .row-subject {
font-size: 12px;
}
- .footer-shortcuts kbd:not(:last-of-type) {
+ .footer-shortcuts > .shortcut-keys:not(.footer-help-keys) {
display: none;
}
.reader-toolbar {
@@ -3102,9 +3102,64 @@ fieldset.compose-format:disabled {
color: var(--muted);
}
-/* ——— Shortcut sheet ——— */
+/* ——— Shortcut editor ——— */
.shortcut-modal {
- width: min(720px, calc(100vw - 40px));
+ width: min(760px, calc(100vw - 40px));
+}
+.shortcut-editor {
+ display: flex;
+ flex-direction: column;
+ gap: 18px;
+}
+.shortcut-toolbar {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+}
+/* In the dialog the search stays in reach while the list scrolls. */
+.shortcut-modal .shortcut-toolbar {
+ position: sticky;
+ top: -23px;
+ z-index: 2;
+ margin: -10px 0 -6px;
+ padding: 10px 0;
+ background: var(--surface);
+}
+.shortcut-search {
+ flex: 1;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ height: 32px;
+ padding: 0 10px;
+ color: var(--muted);
+ background: var(--field);
+ border: 1px solid var(--border-strong);
+ border-radius: 7px;
+ transition:
+ border-color 120ms,
+ box-shadow 120ms;
+}
+.shortcut-search:focus-within {
+ border-color: var(--accent-solid);
+ box-shadow: 0 0 0 3px var(--accent-tint);
+}
+.shortcut-search input {
+ height: 100%;
+ padding: 0;
+ font-size: 12px;
+ background: none;
+ border: 0;
+}
+.shortcut-search input::-webkit-search-cancel-button {
+ display: none;
+}
+.shortcut-toolbar > .button {
+ flex-shrink: 0;
+ color: var(--secondary);
+}
+.shortcut-error {
+ margin: 0;
}
.shortcut-sections {
columns: 2 280px;
@@ -3115,24 +3170,241 @@ fieldset.compose-format:disabled {
margin-bottom: 22px;
}
.shortcut-sections h3 {
- margin: 0 0 8px;
+ margin: 0 0 4px;
font-size: 11px;
font-weight: 500;
color: var(--muted);
}
+.shortcut-item {
+ break-inside: avoid;
+ border-bottom: 1px solid var(--border);
+}
.shortcut-row {
display: flex;
align-items: center;
justify-content: space-between;
- gap: 16px;
- min-height: 30px;
+ gap: 12px;
+ min-height: 34px;
font-size: 12px;
color: var(--secondary);
- border-bottom: 1px solid var(--border);
}
-.shortcut-keys {
+.shortcut-label {
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+ padding: 6px 0;
+}
+.shortcut-label small {
+ font-size: 10px;
+ color: var(--faint);
+}
+.shortcut-bindings {
display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: flex-end;
+ gap: 2px;
+ padding: 4px 0;
+}
+.shortcut-keys {
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
+}
+.shortcut-then {
+ margin: 0 1px;
+ font-size: 10px;
+ color: var(--faint);
+}
+.shortcut-binding {
+ position: relative;
+ display: inline-flex;
+}
+.shortcut-binding-keys {
+ display: inline-flex;
+ align-items: center;
+ padding: 3px;
+ background: none;
+ border: 0;
+ border-radius: 6px;
+ transition: background 120ms;
+}
+.shortcut-binding-keys:hover,
+.shortcut-binding-keys:focus-visible {
+ background: var(--hover);
+}
+.shortcut-binding-keys:focus-visible {
+ outline-offset: 0;
+}
+.shortcut-binding-keys kbd {
+ transition:
+ color 120ms,
+ border-color 120ms;
+}
+.shortcut-binding-keys:hover kbd,
+.shortcut-binding-keys:focus-visible kbd {
+ color: var(--text);
+ border-color: var(--muted);
+}
+/* Sits on the corner of its keys, so removing one never shifts the others. */
+.shortcut-remove {
+ position: absolute;
+ top: -3px;
+ right: -3px;
+ display: grid;
+ place-items: center;
+ width: 14px;
+ height: 14px;
+ padding: 0;
+ color: var(--muted);
+ background: var(--raised);
+ border: 1px solid var(--border-strong);
+ border-radius: 50%;
+ opacity: 0;
+ transform: scale(0.8);
+ transition:
+ opacity 120ms,
+ transform 120ms,
+ color 120ms;
+}
+.shortcut-binding:hover .shortcut-remove,
+.shortcut-binding:focus-within .shortcut-remove {
+ opacity: 1;
+ transform: none;
+}
+.shortcut-remove:hover {
+ color: var(--red);
+ border-color: color-mix(in srgb, var(--red) 45%, transparent);
+}
+.shortcut-bindings > .button {
+ width: 24px;
+ height: 24px;
+ min-height: 24px;
+ padding: 4px;
+ color: var(--muted);
+}
+.shortcut-add {
+ opacity: 0;
+ transition: opacity 120ms;
+}
+.shortcut-item:hover .shortcut-add,
+.shortcut-item:focus-within .shortcut-add {
+ opacity: 1;
+}
+.shortcut-bindings > .shortcut-reset {
+ color: var(--accent);
+}
+.shortcut-empty {
+ display: inline-flex;
+ align-items: center;
gap: 4px;
+ height: 24px;
+ padding: 0 8px;
+ font-size: 11px;
+ color: var(--faint);
+ background: none;
+ border: 1px dashed var(--border-strong);
+ border-radius: 6px;
+ transition:
+ color 120ms,
+ border-color 120ms;
+}
+.shortcut-empty:hover {
+ color: var(--text);
+ border-color: var(--muted);
+}
+.shortcut-recorder {
+ position: relative;
+ overflow: hidden;
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ height: 24px;
+ margin: 0 2px;
+ padding: 0 9px;
+ font-size: 11px;
+ color: var(--accent);
+ background: var(--accent-tint);
+ border: 1px solid var(--accent-solid);
+ border-radius: 6px;
+ box-shadow: 0 0 0 3px var(--accent-tint);
+ animation: shortcut-listen 1.6s ease-in-out infinite;
+}
+.shortcut-recorder:focus-visible {
+ outline: none;
+}
+.shortcut-recorder kbd {
+ color: var(--accent);
+ border-color: color-mix(in srgb, var(--accent) 40%, transparent);
+}
+.shortcut-recorder .shortcut-then {
+ color: inherit;
+}
+/* Counts down the moment left to add a second key. */
+.shortcut-recorder-timer {
+ position: absolute;
+ inset: auto 0 0;
+ height: 2px;
+ background: var(--accent-solid);
+ transform-origin: left;
+ animation: shortcut-timer linear forwards;
+}
+@keyframes shortcut-listen {
+ 50% {
+ border-color: color-mix(in srgb, var(--accent-solid) 45%, transparent);
+ }
+}
+@keyframes shortcut-timer {
+ to {
+ transform: scaleX(0);
+ }
+}
+@media (prefers-reduced-motion: reduce) {
+ .shortcut-recorder {
+ animation: none;
+ }
+}
+.shortcut-notice {
+ margin: 0 0 10px;
+ font-size: 11px;
+ line-height: 1.7;
+ color: var(--muted);
+}
+.shortcut-notice kbd {
+ height: 16px;
+ min-width: 16px;
+ font-size: 9px;
+}
+.shortcut-conflict {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 8px 12px;
+ padding: 8px 10px;
+ color: var(--secondary);
+ background: color-mix(in srgb, var(--star) 7%, transparent);
+ border: 1px solid color-mix(in srgb, var(--star) 22%, transparent);
+ border-radius: 7px;
+}
+.shortcut-conflict p {
+ flex: 1 1 180px;
+ margin: 0;
+}
+.shortcut-conflict strong {
+ font-weight: 500;
+ color: var(--text-strong);
+}
+.shortcut-conflict-actions {
+ display: flex;
+ gap: 6px;
+ margin-left: auto;
+}
+.shortcut-no-results {
+ margin: 0;
+ padding: 28px 0;
+ font-size: 12px;
+ text-align: center;
+ color: var(--muted);
}
/* ——— Settings ——— */
diff --git a/packages/core/src/model.ts b/packages/core/src/model.ts
index dbea908..869c32c 100644
--- a/packages/core/src/model.ts
+++ b/packages/core/src/model.ts
@@ -202,6 +202,11 @@ export interface Settings {
signatures: Record<string, string>
/** Where the reader goes after a conversation leaves the current view. */
afterArchive?: 'next' | 'previous' | 'list'
+ /**
+ * Keyboard shortcuts changed from their defaults, by action. Each binding is a list of chords
+ * pressed in turn, such as `['Mod+K']` or `['G', 'I']`; an empty list turns a shortcut off.
+ */
+ shortcuts?: Record<string, string[][]>
}
export const defaultSettings: Settings = {
theme: 'dark',
diff --git a/packages/core/src/schemas.ts b/packages/core/src/schemas.ts
index 22216a2..d932454 100644
--- a/packages/core/src/schemas.ts
+++ b/packages/core/src/schemas.ts
@@ -171,6 +171,9 @@ export const settingsSchema = z.object({
defaultAccountId: id.optional(),
signatures: z.record(z.string(), z.string().max(100_000)),
afterArchive: z.enum(['next', 'previous', 'list']).optional(),
+ shortcuts: z
+ .record(z.string().max(64), z.array(z.array(z.string().min(1).max(64)).min(1).max(4)).max(16))
+ .optional(),
})
export const ipcSchemas = {
bootstrap: z.tuple([]),
diff --git a/tests/shortcuts.test.ts b/tests/shortcuts.test.ts
new file mode 100644
index 0000000..c71455b
--- /dev/null
+++ b/tests/shortcuts.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from 'vitest'
+import {
+ defaultBindings,
+ findConflicts,
+ overridesFor,
+ resolveShortcuts,
+ shortcutDefinitions,
+} from '../apps/desktop/src/renderer/src/shortcuts'
+
+describe('shortcut defaults and saved preferences', () => {
+ it('has no conflicting default chords or sequence prefixes', () => {
+ const bindings = resolveShortcuts()
+ for (const { id } of shortcutDefinitions)
+ for (const binding of bindings[id]) expect(findConflicts(bindings, id, binding)).toEqual([])
+ })
+
+ it('adds new actions without changing existing customized or disabled shortcuts', () => {
+ const saved = { archive: [['W']], trash: [], goInbox: [['G', 'H']] }
+ const bindings = resolveShortcuts(saved)
+ expect(bindings.archive).toEqual(saved.archive)
+ expect(bindings.trash).toEqual([])
+ expect(bindings.goInbox).toEqual(saved.goInbox)
+ expect(bindings.refresh).toEqual([['Mod+R'], ['F5']])
+ expect(bindings.goSpam).toEqual([['G', 'J']])
+ expect(bindings.attachFiles).toEqual([['Mod+Shift+A']])
+ expect(overridesFor(bindings)).toEqual(saved)
+ })
+
+ it('round-trips customized refresh bindings and opt-in actions', () => {
+ const saved = { refresh: [['Mod+Shift+R'], ['G', 'R']], createFolder: [['Shift+C']] }
+ expect(overridesFor(resolveShortcuts(saved))).toEqual(saved)
+ expect(resolveShortcuts({ refresh: [] }).refresh).toEqual([])
+ expect(defaultBindings('refresh')).toEqual([['Mod+R'], ['F5']])
+ })
+
+ it('gives saved assignments priority over conflicting new defaults', () => {
+ const bindings = resolveShortcuts({ archive: [['Mod+R']], compose: [['G', 'J']] })
+ expect(bindings.archive).toEqual([['Mod+R']])
+ expect(bindings.compose).toEqual([['G', 'J']])
+ expect(bindings.refresh).toEqual([['F5']])
+ expect(bindings.goSpam).toEqual([])
+ expect(resolveShortcuts({ archive: [['G']] }).goTrash).toEqual([])
+ // Removing that customization makes the default available again.
+ expect(resolveShortcuts().refresh).toEqual(defaultBindings('refresh'))
+ })
+
+ it('detects conflicts when assigning new actions to existing keys or sequences', () => {
+ const bindings = resolveShortcuts()
+ expect(findConflicts(bindings, 'refresh', ['R'])).toEqual([{ id: 'reply', binding: ['R'] }])
+ expect(findConflicts(bindings, 'createFolder', ['G'])).toContainEqual({
+ id: 'goTrash',
+ binding: ['G', 'B'],
+ })
+ })
+})