Przeglądaj źródła

Add keyboard shortcuts with a per-person settings page (#612)

* Add keyboard shortcuts with a per-person settings page

* Keep fixed keys and the go-to prefix from being reassigned, and a later choice through a failed save

* Test that shortcuts stay quiet while a confirmation is asking

* Run CI again
Bernt Christian Egeland 2 dni temu
rodzic
commit
252a551154
80 zmienionych plików z 5638 dodań i 247 usunięć
  1. 174 0
      e2e/specs/shortcuts/typing.spec.ts
  2. 16 0
      e2e/support/db.ts
  3. 2 1
      messages/de/navigation.json
  4. 91 0
      messages/de/settings.json
  5. 0 1
      messages/de/vehicles.json
  6. 2 1
      messages/en/navigation.json
  7. 91 0
      messages/en/settings.json
  8. 0 1
      messages/en/vehicles.json
  9. 2 1
      messages/es/navigation.json
  10. 91 0
      messages/es/settings.json
  11. 0 1
      messages/es/vehicles.json
  12. 2 1
      messages/fr/navigation.json
  13. 91 0
      messages/fr/settings.json
  14. 0 1
      messages/fr/vehicles.json
  15. 2 1
      messages/it/navigation.json
  16. 91 0
      messages/it/settings.json
  17. 0 1
      messages/it/vehicles.json
  18. 2 1
      messages/lt/navigation.json
  19. 91 0
      messages/lt/settings.json
  20. 0 1
      messages/lt/vehicles.json
  21. 2 1
      messages/nb/navigation.json
  22. 91 0
      messages/nb/settings.json
  23. 0 1
      messages/nb/vehicles.json
  24. 2 1
      messages/nl/navigation.json
  25. 91 0
      messages/nl/settings.json
  26. 0 1
      messages/nl/vehicles.json
  27. 2 1
      messages/pl/navigation.json
  28. 91 0
      messages/pl/settings.json
  29. 0 1
      messages/pl/vehicles.json
  30. 2 1
      messages/pt-BR/navigation.json
  31. 91 0
      messages/pt-BR/settings.json
  32. 0 1
      messages/pt-BR/vehicles.json
  33. 2 1
      messages/pt-PT/navigation.json
  34. 91 0
      messages/pt-PT/settings.json
  35. 0 1
      messages/pt-PT/vehicles.json
  36. 2 1
      messages/ru/navigation.json
  37. 91 0
      messages/ru/settings.json
  38. 0 1
      messages/ru/vehicles.json
  39. 2 1
      messages/tr/navigation.json
  40. 91 0
      messages/tr/settings.json
  41. 0 1
      messages/tr/vehicles.json
  42. 2 0
      prisma/migrations/20261116081738_add_user_keyboard_shortcuts/migration.sql
  43. 4 0
      prisma/schema/auth.prisma
  44. 128 0
      src/__tests__/features/shortcuts/keys.test.ts
  45. 387 0
      src/__tests__/features/shortcuts/preferences.test.ts
  46. 526 0
      src/__tests__/features/shortcuts/shortcuts-provider.test.tsx
  47. 842 0
      src/__tests__/features/shortcuts/typing-safety.test.tsx
  48. 1 0
      src/__tests__/lib/files/references.test.ts
  49. 1 0
      src/app/(authenticated)/inventory/inventory-client.tsx
  50. 137 118
      src/app/(authenticated)/layout.tsx
  51. 15 0
      src/app/(authenticated)/settings/shortcuts/page.tsx
  52. 1 0
      src/app/(authenticated)/vehicles/[id]/_classic/vehicle-detail-classic.tsx
  53. 1 0
      src/app/(authenticated)/vehicles/[id]/vehicle-detail-client.tsx
  54. 23 2
      src/components/app-sidebar.tsx
  55. 8 7
      src/components/page-header.tsx
  56. 14 1
      src/components/quick-create-menu.tsx
  57. 6 6
      src/components/save-shortcut-listener.tsx
  58. 2 13
      src/components/ui/sidebar.tsx
  59. 13 42
      src/features/calendar/Components/CalendarClient.tsx
  60. 7 9
      src/features/calendar/Components/CalendarToolbar.tsx
  61. 42 8
      src/features/search/Components/SearchCommand.tsx
  62. 7 0
      src/features/search/Lib/open.ts
  63. 2 0
      src/features/settings/Lib/searchIndex/index.ts
  64. 48 0
      src/features/settings/Lib/searchIndex/shortcuts.ts
  65. 2 0
      src/features/settings/Lib/settingsPageIcons.ts
  66. 2 0
      src/features/settings/Lib/settingsPages.ts
  67. 31 0
      src/features/shortcuts/Actions/saveKeyboardShortcuts.ts
  68. 67 0
      src/features/shortcuts/Components/ShortcutKeys.tsx
  69. 157 0
      src/features/shortcuts/Components/ShortcutsHelpDialog.tsx
  70. 409 0
      src/features/shortcuts/Components/ShortcutsProvider.tsx
  71. 417 0
      src/features/shortcuts/Components/ShortcutsSettings.tsx
  72. 11 0
      src/features/shortcuts/Components/SidebarShortcut.tsx
  73. 420 0
      src/features/shortcuts/Lib/keys.ts
  74. 215 0
      src/features/shortcuts/Lib/preferences.ts
  75. 260 0
      src/features/shortcuts/Lib/registry.ts
  76. 15 0
      src/features/shortcuts/Schema/preferences.ts
  77. 7 13
      src/features/vehicles/Components/PlateLookupCommand.tsx
  78. 1 0
      src/features/vehicles/Components/service-detail/ImageCarousel.tsx
  79. 4 2
      src/hooks/use-save-shortcut.ts
  80. 4 0
      src/lib/get-layout-data.ts

+ 174 - 0
e2e/specs/shortcuts/typing.spec.ts

@@ -0,0 +1,174 @@
+import { expect, type Locator, type Page, test } from '@playwright/test'
+import { jobWithCustomer, ownerOrganizationId, setKeyboardShortcuts } from '../../support/db'
+import { settle } from '../../support/hydration'
+import { newWorkOrder, seededVehicleUrl } from '../../support/work-order'
+
+/**
+ * Typing never runs a shortcut.
+ *
+ * The only bare-key shortcuts left are the calendar's single letters; going
+ * to a page is Alt+G, then Alt and a letter, which cannot be typed. The owner
+ * has every shortcut on and types sentences made of exactly those letters
+ * into the places a workshop types all day. The words must arrive and the
+ * address must not change.
+ *
+ * The unit tests (src/__tests__/features/shortcuts/typing-safety.test.tsx)
+ * hold the same promise against each component in jsdom; this file holds it
+ * in a real browser, with real focus and real key events.
+ */
+
+test.describe.configure({ mode: 'serial' })
+
+const OWNER = 'demo@torqvoice.com'
+/** Every letter a bare-key shortcut uses, as words. */
+const SENTENCE = 'gw gq gd dwmyax tjnkp'
+
+test.beforeAll(async () => {
+  await setKeyboardShortcuts(OWNER, {
+    enabled: true,
+    singleKeys: true,
+    goToSequences: true,
+    overrides: {},
+    disabled: [],
+  })
+})
+
+test.afterAll(async () => {
+  await setKeyboardShortcuts(OWNER, null)
+})
+
+/** Types at a person's pace into a field and checks the page did not move. */
+async function typeAndStay(page: Page, field: Locator, read: () => Promise<string>) {
+  await field.scrollIntoViewIfNeeded()
+  await field.click()
+  const before = page.url()
+  await page.keyboard.type(SENTENCE, { delay: 80 })
+  // Long enough for a held-back shortcut or a navigation to show itself.
+  await page.waitForTimeout(700)
+  expect(page.url()).toBe(before)
+  expect(await read()).toContain(SENTENCE)
+}
+
+test('Alt+G then Alt+W opens the work orders, and the bare letters open nothing', async ({
+  page,
+}) => {
+  await page.goto('/customers')
+  await settle(page)
+  const before = page.url()
+  await page.locator('body').click({ position: { x: 5, y: 5 } })
+  await page.keyboard.type('gw gq gg', { delay: 120 })
+  await page.waitForTimeout(700)
+  expect(page.url()).toBe(before)
+
+  await expect(async () => {
+    await page.keyboard.press('Alt+g')
+    await page.keyboard.press('Alt+w')
+    await page.waitForURL(/\/work-orders$/, { timeout: 5_000 })
+  }).toPass({ timeout: 30_000 })
+})
+
+test('a settings field keeps every letter', async ({ page }) => {
+  await page.goto('/settings/company')
+  await settle(page)
+  const field = page.getByRole('textbox').first()
+  await field.fill('')
+  await typeAndStay(page, field, () => field.inputValue())
+  // The form is left unsaved on purpose: nothing about the workshop changes.
+})
+
+test('the search palette keeps every letter', async ({ page }) => {
+  await page.goto('/customers')
+  await settle(page)
+  await page.keyboard.press('Control+k')
+  const field = page.getByRole('dialog').getByRole('combobox')
+  await expect(field).toBeVisible()
+  await typeAndStay(page, field, () => field.inputValue())
+})
+
+test('a field in a dialog keeps every letter, and the page behind stays put', async ({ page }) => {
+  await page.goto('/customers?create=true')
+  await settle(page)
+  const dialog = page
+    .getByRole('dialog')
+    .filter({ has: page.getByRole('textbox') })
+    .last()
+  const field = dialog.getByRole('textbox').first()
+  await typeAndStay(page, field, () => field.inputValue())
+  // With the dialog open and the focus off the field, bare keys still do nothing.
+  const before = page.url()
+  await dialog.getByRole('heading').first().click()
+  await page.keyboard.type('gw', { delay: 120 })
+  await page.waitForTimeout(700)
+  expect(page.url()).toBe(before)
+})
+
+test('a work order note and its rich text keep every letter', async ({ page }) => {
+  const vehicleUrl = await seededVehicleUrl(page)
+  await newWorkOrder(page, vehicleUrl, `Shortcut typing ${Date.now()}`)
+
+  const note = page.locator('textarea').filter({ visible: true }).first()
+  await typeAndStay(page, note, () => note.inputValue())
+
+  const editor = page.locator('[contenteditable="true"]').filter({ visible: true }).first()
+  if (await editor.count()) {
+    await typeAndStay(page, editor, async () => (await editor.textContent()) ?? '')
+  }
+})
+
+test('the message box keeps every letter', async ({ page }) => {
+  const job = await jobWithCustomer(await ownerOrganizationId())
+  await page.goto(`/messages?customerId=${job.customerId}`)
+  await settle(page)
+  const box = page.locator('textarea').filter({ visible: true }).last()
+  await typeAndStay(page, box, () => box.inputValue())
+  // Typed, never sent: no customer hears from this spec.
+  await box.fill('')
+})
+
+test('a scan with no field focused opens nothing', async ({ page }) => {
+  await page.goto('/customers')
+  await settle(page)
+  const before = page.url()
+  // No delay: the characters arrive as a scanner sends them.
+  await page.keyboard.type('gw4471')
+  await page.keyboard.press('Enter')
+  await page.waitForTimeout(700)
+  expect(page.url()).toBe(before)
+})
+
+test('the shortcuts settings page scrolls its list, never the whole page', async ({ page }) => {
+  // The settings layout is one screen tall and only its panes scroll. A
+  // visually hidden element laid out against the page once stretched the
+  // document to three screens here: scrolled to the end of the list, the
+  // wheel carried on and took the header and the menu off the top.
+  await page.goto('/settings/shortcuts')
+  await settle(page)
+  const lastRow = page.getByRole('button', { name: 'Change the shortcut for Previous period' })
+  await lastRow.scrollIntoViewIfNeeded()
+  await lastRow.hover()
+  for (let i = 0; i < 6; i++) await page.mouse.wheel(0, 2_000)
+  await page.waitForTimeout(500)
+
+  const measured = await page.evaluate(() => ({
+    scrollY: window.scrollY,
+    scrollHeight: document.documentElement.scrollHeight,
+    innerHeight: window.innerHeight,
+    scrollWidth: document.documentElement.scrollWidth,
+    innerWidth: window.innerWidth,
+  }))
+  expect(measured.scrollY).toBe(0)
+  expect(measured.scrollHeight).toBeLessThanOrEqual(measured.innerHeight)
+  expect(measured.scrollWidth).toBeLessThanOrEqual(measured.innerWidth)
+  await expect(page.getByRole('heading', { name: 'Settings', exact: true })).toBeInViewport()
+
+  // The same with the help overlay open on top of it.
+  await page.keyboard.press('Control+/')
+  await expect(page.getByRole('dialog', { name: 'Keyboard shortcuts' })).toBeVisible()
+  const withOverlay = await page.evaluate(() => ({
+    scrollY: window.scrollY,
+    scrollHeight: document.documentElement.scrollHeight,
+    innerHeight: window.innerHeight,
+  }))
+  expect(withOverlay.scrollY).toBe(0)
+  expect(withOverlay.scrollHeight).toBeLessThanOrEqual(withOverlay.innerHeight)
+})

+ 16 - 0
e2e/support/db.ts

@@ -2182,3 +2182,19 @@ export async function closuresNamed(
 export async function deleteClosuresNamed(name: string): Promise<void> {
   await withDb((db) => db.query(`delete from workshop_closures where name = $1`, [name]))
 }
+
+/**
+ * Sets a person's own keyboard shortcut choices (users."keyboardShortcuts"),
+ * or clears them with null. The settings page writes the same column.
+ */
+export async function setKeyboardShortcuts(
+  email: string,
+  prefs: Record<string, unknown> | null
+): Promise<void> {
+  await withDb(async (db) => {
+    await db.query(
+      `update users set "keyboardShortcuts" = $2::jsonb where lower(email) = lower($1)`,
+      [email, prefs === null ? null : JSON.stringify(prefs)]
+    )
+  })
+}

+ 2 - 1
messages/de/navigation.json

@@ -42,6 +42,7 @@
     "warranty": "Garantie",
     "workshop": "Werkstatt",
     "appearance": "Erscheinungsbild",
+    "shortcuts": "Tastenkürzel",
     "email": "E-Mail",
     "sms": "SMS",
     "telegram": "Telegram",
@@ -74,7 +75,6 @@
     "inspectionDetails": "Inspektionsdetails"
   },
   "search": "Suchen...",
-  "shortcut": "Ctrl+K",
   "readMore": "Mehr erfahren",
   "newWorkOrder": "Neuer Arbeitsauftrag",
   "quickCreate": {
@@ -129,6 +129,7 @@
     "cancel": "Abbrechen",
     "createCompany": "Unternehmen erstellen",
     "theme": "Design",
+    "keyboardShortcuts": "Tastenkürzel",
     "signOut": "Abmelden",
     "more": "Mehr",
     "auditLog": "Aktivitätsprotokoll",

+ 91 - 0
messages/de/settings.json

@@ -115,6 +115,10 @@
         "title": "Darstellung",
         "description": "Design & Anzeige"
       },
+      "shortcuts": {
+        "title": "Tastenkürzel",
+        "description": "Ihre eigenen Tasten"
+      },
       "data": {
         "title": "Daten",
         "description": "Export & Import-Backup"
@@ -1379,6 +1383,93 @@
       }
     }
   },
+  "shortcuts": {
+    "title": "Tastenkürzel",
+    "description": "Ihre eigenen Tasten. Sie gelten auf jedem Gerät, auf dem Sie sich anmelden.",
+    "enableLabel": "Tastenkürzel verwenden",
+    "enableHint": "Schaltet alle Tastenkürzel auf dieser Seite ein oder aus.",
+    "singleKeysLabel": "Einzelne Buchstabentasten",
+    "singleKeysHint": "Tastenkürzel, die nur aus einem einzelnen Buchstaben bestehen. Nur der Kalender hat sie, etwa W für die Wochenansicht. Schalten Sie sie aus, wenn Sie die Sprachsteuerung nutzen oder sie versehentlich drücken.",
+    "goToSequencesLabel": "{prefix}, dann der Buchstabe einer Seite, öffnet diese Seite",
+    "goToSequencesHint": "Beide Tastendrücke nutzen dieselbe Zusatztaste, daher kann nichts, was Sie tippen, sie auslösen: {example} öffnet {workOrders}. Die Buchstaben stehen unter Gehe zu.",
+    "allTitle": "Alle Tastenkürzel",
+    "allHint": "Wählen Sie Ändern und drücken Sie dann die gewünschten Tasten. Esc bricht ab.",
+    "resetAll": "Alle auf Standard zurücksetzen",
+    "resetAllTitle": "Alle Tastenkürzel zurücksetzen?",
+    "resetAllDescription": "Jede Taste wird auf ihre ursprüngliche Belegung zurückgesetzt, und ausgeschaltete Tastenkürzel werden wieder eingeschaltet.",
+    "change": "Ändern",
+    "cancel": "Abbrechen",
+    "reset": "Zurücksetzen",
+    "resetTo": "Zurück zu {keys}",
+    "resetToNone": "Zurück zu keiner Taste",
+    "changed": "Geändert",
+    "off": "Aus",
+    "noKey": "Keine Taste",
+    "or": "oder",
+    "then": "dann",
+    "pressKeys": "Neue Tasten drücken…",
+    "recordingFor": "Neues Tastenkürzel für {action} wird aufgenommen. Drücken Sie die Tasten, oder Esc zum Abbrechen.",
+    "changeFor": "Tastenkürzel für {action} ändern",
+    "resetFor": "Tastenkürzel für {action} zurücksetzen",
+    "switchFor": "Tastenkürzel für {action}",
+    "clash": "{keys} ist bereits {action} zugewiesen. Verwenden Sie es hier, hat {action} danach keine Taste mehr.",
+    "useHere": "Hier verwenden",
+    "pickAnother": "Andere wählen",
+    "problems": {
+      "reserved": "{keys} ist vom Browser oder System belegt und kann nicht verwendet werden.",
+      "taken": "{keys} ist fest einem anderen Kürzel zugewiesen und kann nicht verschoben werden.",
+      "needsModifier": "Dieses Tastenkürzel gilt auf jeder Seite und braucht deshalb {mod} oder {alt} zusammen mit der Taste.",
+      "invalid": "Diese Taste kann nicht verwendet werden."
+    },
+    "alsoUsedBy": "Auch die Taste für {action}. Nur eines von beiden wird funktionieren.",
+    "goToNote": "Suchen ({keys}) öffnet jede Seite, und {prefix} gefolgt von einem Buchstaben öffnet die wichtigsten. Hier können Sie jeder Seite eine eigene Taste geben.",
+    "announceSet": "{action} ist jetzt {keys}",
+    "announceReset": "{action} ist wieder auf Standard",
+    "announceResetAll": "Alle Tastenkürzel sind wieder auf Standard",
+    "phoneNote": "Tastenkürzel brauchen eine Tastatur. Was Sie hier ändern, gilt auch auf Ihrem Computer.",
+    "saveFailed": "Ihre Tastenkürzel konnten nicht gespeichert werden",
+    "groups": {
+      "general": "Allgemein",
+      "create": "Erstellen",
+      "goTo": "Gehe zu",
+      "calendar": "Kalender",
+      "fixed": "Listen und Fotos"
+    },
+    "scopes": {
+      "global": "Überall in der App",
+      "calendar": "Nur im Kalender"
+    },
+    "actions": {
+      "search": "Suchen",
+      "plateLookup": "Kennzeichenabfrage",
+      "save": "Speichern",
+      "sidebar": "Seitenleiste ein- oder ausblenden",
+      "help": "Tastenkürzel anzeigen",
+      "newInspection": "Neue Inspektion",
+      "calendar_day": "Tagesansicht",
+      "calendar_week": "Wochenansicht",
+      "calendar_month": "Monatsansicht",
+      "calendar_year": "Jahresansicht",
+      "calendar_schedule": "Terminübersicht",
+      "calendar_fourDays": "4-Tage-Ansicht",
+      "calendar_today": "Zu heute",
+      "calendar_next": "Nächster Zeitraum",
+      "calendar_previous": "Vorheriger Zeitraum"
+    },
+    "help": {
+      "title": "Tastenkürzel",
+      "description": "Ihre aktuellen Tasten. Suchen öffnet jede Seite. Tasten ändern oder ausschalten können Sie in den Einstellungen.",
+      "disabledNote": "Tastenkürzel sind ausgeschaltet. Schalten Sie sie in den Einstellungen ein.",
+      "find": "Tastenkürzel suchen",
+      "noMatch": "Kein passendes Tastenkürzel",
+      "customize": "Tastenkürzel ändern",
+      "fixedHint": "immer gleich",
+      "listMove": "In einer Liste bewegen",
+      "listOpen": "Zeile öffnen",
+      "photos": "Nächstes oder vorheriges Foto",
+      "close": "Dialog oder Menü schließen"
+    }
+  },
   "data": {
     "title": "Datenverwaltung",
     "description": "Übernehmen Sie Daten aus Ihrem alten System, laden Sie eine Sicherung von allem herunter oder stellen Sie eine wieder her.",

+ 0 - 1
messages/de/vehicles.json

@@ -562,7 +562,6 @@
   },
   "plateLookup": {
     "open": "Kennzeichenabfrage",
-    "shortcut": "Ctrl+Shift+L",
     "title": "Kennzeichenabfrage",
     "description": "Geben Sie ein Kennzeichen ein, um zu sehen, was Ihre Werkstatt und das Fahrzeugregister darüber wissen",
     "placeholder": "Kennzeichen eingeben",

+ 2 - 1
messages/en/navigation.json

@@ -42,6 +42,7 @@
     "warranty": "Warranty",
     "workshop": "Workshop",
     "appearance": "Appearance",
+    "shortcuts": "Keyboard shortcuts",
     "email": "Email",
     "sms": "SMS",
     "telegram": "Telegram",
@@ -74,7 +75,6 @@
     "inspectionDetails": "Inspection Details"
   },
   "search": "Search...",
-  "shortcut": "Ctrl+K",
   "readMore": "Read more",
   "newWorkOrder": "New Work Order",
   "quickCreate": {
@@ -129,6 +129,7 @@
     "cancel": "Cancel",
     "createCompany": "Create Company",
     "theme": "Theme",
+    "keyboardShortcuts": "Keyboard shortcuts",
     "signOut": "Sign Out",
     "more": "More",
     "auditLog": "Audit Log",

+ 91 - 0
messages/en/settings.json

@@ -115,6 +115,10 @@
         "title": "Appearance",
         "description": "Theme & display"
       },
+      "shortcuts": {
+        "title": "Keyboard shortcuts",
+        "description": "Your own keys"
+      },
       "data": {
         "title": "Data",
         "description": "Export & import backup"
@@ -1379,6 +1383,93 @@
       }
     }
   },
+  "shortcuts": {
+    "title": "Keyboard shortcuts",
+    "description": "Your own keys. They follow you to every device you sign in on.",
+    "enableLabel": "Use keyboard shortcuts",
+    "enableHint": "Turns every shortcut on this page on or off.",
+    "singleKeysLabel": "Single-letter keys",
+    "singleKeysHint": "Shortcuts that are one letter on its own. Only the calendar has them, such as W for the week view. Switch off if you use voice control or press them by accident.",
+    "goToSequencesLabel": "{prefix}, then a page's letter, opens that page",
+    "goToSequencesHint": "Both presses use the same modifier key, so nothing you type can set it off: {example} opens {workOrders}. The letters are listed under Go to.",
+    "allTitle": "All shortcuts",
+    "allHint": "Select Change, then press the keys you want. Esc cancels.",
+    "resetAll": "Reset all to default",
+    "resetAllTitle": "Reset every shortcut?",
+    "resetAllDescription": "Every key goes back to the one it shipped with, and shortcuts you switched off are switched on again.",
+    "change": "Change",
+    "cancel": "Cancel",
+    "reset": "Reset",
+    "resetTo": "Back to {keys}",
+    "resetToNone": "Back to no key",
+    "changed": "Changed",
+    "off": "Off",
+    "noKey": "No key",
+    "or": "or",
+    "then": "then",
+    "pressKeys": "Press the new keys…",
+    "recordingFor": "Recording a new shortcut for {action}. Press the keys, or Escape to cancel.",
+    "changeFor": "Change the shortcut for {action}",
+    "resetFor": "Reset the shortcut for {action}",
+    "switchFor": "Shortcut for {action}",
+    "clash": "{keys} already belongs to {action}. Use it here and that one is left without it.",
+    "useHere": "Use it here",
+    "pickAnother": "Pick another",
+    "problems": {
+      "reserved": "{keys} belongs to the browser or the system and cannot be used.",
+      "taken": "{keys} is fixed to another shortcut and cannot be moved.",
+      "needsModifier": "This shortcut works on every page, so it needs {mod} or {alt} together with the key.",
+      "invalid": "That key cannot be used."
+    },
+    "alsoUsedBy": "Also the key for {action}. Only one of them will work.",
+    "goToNote": "Search ({keys}) opens every page, and {prefix} followed by a letter opens the main ones. Give any page a key of its own here.",
+    "announceSet": "{action} is now {keys}",
+    "announceReset": "{action} is back to its default",
+    "announceResetAll": "Every shortcut is back to its default",
+    "phoneNote": "Shortcuts need a keyboard. Changes you make here apply on your computer too.",
+    "saveFailed": "Could not save your shortcuts",
+    "groups": {
+      "general": "General",
+      "create": "Create",
+      "goTo": "Go to",
+      "calendar": "Calendar",
+      "fixed": "Lists and photos"
+    },
+    "scopes": {
+      "global": "Anywhere in the app",
+      "calendar": "Only on the calendar"
+    },
+    "actions": {
+      "search": "Search",
+      "plateLookup": "Plate lookup",
+      "save": "Save",
+      "sidebar": "Show or hide the sidebar",
+      "help": "Show keyboard shortcuts",
+      "newInspection": "New inspection",
+      "calendar_day": "Day view",
+      "calendar_week": "Week view",
+      "calendar_month": "Month view",
+      "calendar_year": "Year view",
+      "calendar_schedule": "Schedule view",
+      "calendar_fourDays": "4 days view",
+      "calendar_today": "Go to today",
+      "calendar_next": "Next period",
+      "calendar_previous": "Previous period"
+    },
+    "help": {
+      "title": "Keyboard shortcuts",
+      "description": "The keys you have now. Search opens every page. Change or switch off keys in Settings.",
+      "disabledNote": "Keyboard shortcuts are switched off. Switch them on in Settings.",
+      "find": "Find a shortcut",
+      "noMatch": "No shortcut matches",
+      "customize": "Change shortcuts",
+      "fixedHint": "always the same",
+      "listMove": "Move through a list",
+      "listOpen": "Open the row",
+      "photos": "Next or previous photo",
+      "close": "Close a dialog or menu"
+    }
+  },
   "data": {
     "title": "Data Management",
     "description": "Bring data in from your old system, download a backup of everything, or restore one.",

+ 0 - 1
messages/en/vehicles.json

@@ -562,7 +562,6 @@
   },
   "plateLookup": {
     "open": "Plate lookup",
-    "shortcut": "Ctrl+Shift+L",
     "title": "Plate lookup",
     "description": "Type a registration number to see what your workshop and the vehicle registry know about it",
     "placeholder": "Type a plate",

+ 2 - 1
messages/es/navigation.json

@@ -42,6 +42,7 @@
     "warranty": "Garantía",
     "workshop": "Taller",
     "appearance": "Apariencia",
+    "shortcuts": "Atajos de teclado",
     "email": "Correo electrónico",
     "sms": "SMS",
     "telegram": "Telegram",
@@ -74,7 +75,6 @@
     "inspectionDetails": "Detalles de la inspección"
   },
   "search": "Buscar...",
-  "shortcut": "Ctrl+K",
   "readMore": "Más información",
   "newWorkOrder": "Nueva orden de trabajo",
   "quickCreate": {
@@ -129,6 +129,7 @@
     "cancel": "Cancelar",
     "createCompany": "Crear empresa",
     "theme": "Tema",
+    "keyboardShortcuts": "Atajos de teclado",
     "signOut": "Cerrar sesión",
     "more": "Más",
     "auditLog": "Registro de auditoría",

+ 91 - 0
messages/es/settings.json

@@ -115,6 +115,10 @@
         "title": "Apariencia",
         "description": "Tema y visualización"
       },
+      "shortcuts": {
+        "title": "Atajos de teclado",
+        "description": "Sus propias teclas"
+      },
       "data": {
         "title": "Datos",
         "description": "Exportar e importar respaldo"
@@ -1379,6 +1383,93 @@
       }
     }
   },
+  "shortcuts": {
+    "title": "Atajos de teclado",
+    "description": "Sus propias teclas. Le acompañan en cada dispositivo en el que inicie sesión.",
+    "enableLabel": "Usar atajos de teclado",
+    "enableHint": "Activa o desactiva todos los atajos de esta página.",
+    "singleKeysLabel": "Teclas de una sola letra",
+    "singleKeysHint": "Atajos que son una sola letra. Solo el calendario los tiene, como W para la vista semanal. Desactívelos si usa control por voz o los pulsa sin querer.",
+    "goToSequencesLabel": "{prefix} y luego la letra de una página abre esa página",
+    "goToSequencesHint": "Ambas pulsaciones usan la misma tecla modificadora, así que nada de lo que escriba puede activarlas: {example} abre {workOrders}. Las letras aparecen en Ir a.",
+    "allTitle": "Todos los atajos",
+    "allHint": "Seleccione Cambiar y pulse las teclas que desee. Esc cancela.",
+    "resetAll": "Restablecer todos",
+    "resetAllTitle": "¿Restablecer todos los atajos?",
+    "resetAllDescription": "Cada tecla vuelve a la original, y los atajos que desactivó se vuelven a activar.",
+    "change": "Cambiar",
+    "cancel": "Cancelar",
+    "reset": "Restablecer",
+    "resetTo": "Volver a {keys}",
+    "resetToNone": "Volver a sin tecla",
+    "changed": "Cambiado",
+    "off": "Desactivado",
+    "noKey": "Sin tecla",
+    "or": "o",
+    "then": "luego",
+    "pressKeys": "Pulse las nuevas teclas…",
+    "recordingFor": "Grabando un nuevo atajo para {action}. Pulse las teclas, o Esc para cancelar.",
+    "changeFor": "Cambiar el atajo de {action}",
+    "resetFor": "Restablecer el atajo de {action}",
+    "switchFor": "Atajo de {action}",
+    "clash": "{keys} ya está asignado a {action}. Si lo usa aquí, {action} se queda sin él.",
+    "useHere": "Usar aquí",
+    "pickAnother": "Elegir otro",
+    "problems": {
+      "reserved": "{keys} lo usa el navegador o el sistema y no se puede asignar.",
+      "taken": "{keys} está fijado a otro atajo y no se puede mover.",
+      "needsModifier": "Este atajo funciona en todas las páginas, así que necesita {mod} o {alt} junto con la tecla.",
+      "invalid": "Esa tecla no se puede usar."
+    },
+    "alsoUsedBy": "También es la tecla de {action}. Solo uno de los dos funcionará.",
+    "goToNote": "Buscar ({keys}) abre cualquier página y {prefix} seguido de una letra abre las principales. Asigne aquí una tecla propia a cualquier página.",
+    "announceSet": "{action} es ahora {keys}",
+    "announceReset": "{action} vuelve a su valor predeterminado",
+    "announceResetAll": "Todos los atajos vuelven a sus valores predeterminados",
+    "phoneNote": "Los atajos necesitan un teclado. Los cambios que haga aquí se aplican también en su ordenador.",
+    "saveFailed": "No se pudieron guardar sus atajos",
+    "groups": {
+      "general": "General",
+      "create": "Crear",
+      "goTo": "Ir a",
+      "calendar": "Calendario",
+      "fixed": "Listas y fotos"
+    },
+    "scopes": {
+      "global": "En cualquier parte de la aplicación",
+      "calendar": "Solo en el calendario"
+    },
+    "actions": {
+      "search": "Buscar",
+      "plateLookup": "Buscar matrícula",
+      "save": "Guardar",
+      "sidebar": "Mostrar u ocultar la barra lateral",
+      "help": "Mostrar atajos de teclado",
+      "newInspection": "Nueva inspección",
+      "calendar_day": "Vista de día",
+      "calendar_week": "Vista de semana",
+      "calendar_month": "Vista de mes",
+      "calendar_year": "Vista de año",
+      "calendar_schedule": "Vista de agenda",
+      "calendar_fourDays": "Vista de 4 días",
+      "calendar_today": "Ir a hoy",
+      "calendar_next": "Periodo siguiente",
+      "calendar_previous": "Periodo anterior"
+    },
+    "help": {
+      "title": "Atajos de teclado",
+      "description": "Sus teclas actuales. Buscar abre cualquier página. Cambie o desactive teclas en Configuración.",
+      "disabledNote": "Los atajos de teclado están desactivados. Actívelos en Configuración.",
+      "find": "Buscar un atajo",
+      "noMatch": "Ningún atajo coincide",
+      "customize": "Cambiar atajos",
+      "fixedHint": "siempre igual",
+      "listMove": "Moverse por una lista",
+      "listOpen": "Abrir la fila",
+      "photos": "Foto siguiente o anterior",
+      "close": "Cerrar un diálogo o menú"
+    }
+  },
   "data": {
     "title": "Gestión de datos",
     "description": "Traiga datos de su sistema anterior, descargue una copia de seguridad de todo o restaure una.",

+ 0 - 1
messages/es/vehicles.json

@@ -562,7 +562,6 @@
   },
   "plateLookup": {
     "open": "Buscar matrícula",
-    "shortcut": "Ctrl+Shift+L",
     "title": "Buscar matrícula",
     "description": "Escribe una matrícula para ver lo que tu taller y el registro de vehículos saben de ella",
     "placeholder": "Escribe una matrícula",

+ 2 - 1
messages/fr/navigation.json

@@ -42,6 +42,7 @@
     "warranty": "Garantie",
     "workshop": "Atelier",
     "appearance": "Apparence",
+    "shortcuts": "Raccourcis clavier",
     "email": "E-mail",
     "sms": "SMS",
     "telegram": "Telegram",
@@ -74,7 +75,6 @@
     "inspectionDetails": "Détails de l’inspection"
   },
   "search": "Rechercher…",
-  "shortcut": "Ctrl+K",
   "readMore": "En savoir plus",
   "newWorkOrder": "Nouvel ordre de travail",
   "quickCreate": {
@@ -129,6 +129,7 @@
     "cancel": "Annuler",
     "createCompany": "Créer l'entreprise",
     "theme": "Thème",
+    "keyboardShortcuts": "Raccourcis clavier",
     "signOut": "Se déconnecter",
     "more": "Plus",
     "auditLog": "Journal d'audit",

+ 91 - 0
messages/fr/settings.json

@@ -115,6 +115,10 @@
         "title": "Apparence",
         "description": "Theme et affichage"
       },
+      "shortcuts": {
+        "title": "Raccourcis clavier",
+        "description": "Vos propres touches"
+      },
       "data": {
         "title": "Données",
         "description": "Exporter et importer une sauvegarde"
@@ -1379,6 +1383,93 @@
       }
     }
   },
+  "shortcuts": {
+    "title": "Raccourcis clavier",
+    "description": "Vos propres touches. Elles vous suivent sur chaque appareil où vous vous connectez.",
+    "enableLabel": "Utiliser les raccourcis clavier",
+    "enableHint": "Active ou désactive tous les raccourcis de cette page.",
+    "singleKeysLabel": "Touches à une seule lettre",
+    "singleKeysHint": "Raccourcis composés d'une seule lettre. Seul le calendrier en a, comme W pour la vue semaine. Désactivez-les si vous utilisez la commande vocale ou si vous les tapez par erreur.",
+    "goToSequencesLabel": "{prefix}, puis la lettre d'une page, ouvre cette page",
+    "goToSequencesHint": "Les deux appuis utilisent la même touche de modification, donc rien de ce que vous tapez ne peut les déclencher : {example} ouvre {workOrders}. Les lettres sont listées sous Aller à.",
+    "allTitle": "Tous les raccourcis",
+    "allHint": "Choisissez Modifier, puis appuyez sur les touches voulues. Échap annule.",
+    "resetAll": "Tout réinitialiser",
+    "resetAllTitle": "Réinitialiser tous les raccourcis ?",
+    "resetAllDescription": "Chaque touche revient à sa valeur d'origine, et les raccourcis désactivés sont réactivés.",
+    "change": "Modifier",
+    "cancel": "Annuler",
+    "reset": "Réinitialiser",
+    "resetTo": "Revenir à {keys}",
+    "resetToNone": "Revenir à aucune touche",
+    "changed": "Modifié",
+    "off": "Désactivé",
+    "noKey": "Aucune touche",
+    "or": "ou",
+    "then": "puis",
+    "pressKeys": "Appuyez sur les nouvelles touches…",
+    "recordingFor": "Enregistrement d'un nouveau raccourci pour {action}. Appuyez sur les touches, ou sur Échap pour annuler.",
+    "changeFor": "Modifier le raccourci de {action}",
+    "resetFor": "Réinitialiser le raccourci de {action}",
+    "switchFor": "Raccourci de {action}",
+    "clash": "{keys} est déjà attribué à {action}. Si vous l'utilisez ici, {action} n'aura plus de raccourci.",
+    "useHere": "L'utiliser ici",
+    "pickAnother": "En choisir un autre",
+    "problems": {
+      "reserved": "{keys} est réservé au navigateur ou au système et ne peut pas être utilisé.",
+      "taken": "{keys} est réservé à un autre raccourci et ne peut pas être déplacé.",
+      "needsModifier": "Ce raccourci fonctionne sur toutes les pages, il doit donc combiner {mod} ou {alt} avec la touche.",
+      "invalid": "Cette touche ne peut pas être utilisée."
+    },
+    "alsoUsedBy": "C'est aussi la touche de {action}. Un seul des deux fonctionnera.",
+    "goToNote": "Rechercher ({keys}) ouvre n'importe quelle page, et {prefix} suivi d'une lettre ouvre les principales. Attribuez ici une touche propre à n'importe quelle page.",
+    "announceSet": "{action} est maintenant {keys}",
+    "announceReset": "{action} est revenu à sa valeur par défaut",
+    "announceResetAll": "Tous les raccourcis sont revenus à leur valeur par défaut",
+    "phoneNote": "Les raccourcis nécessitent un clavier. Les modifications faites ici s'appliquent aussi sur votre ordinateur.",
+    "saveFailed": "Impossible d'enregistrer vos raccourcis",
+    "groups": {
+      "general": "Général",
+      "create": "Créer",
+      "goTo": "Aller à",
+      "calendar": "Calendrier",
+      "fixed": "Listes et photos"
+    },
+    "scopes": {
+      "global": "Partout dans l'application",
+      "calendar": "Uniquement dans le calendrier"
+    },
+    "actions": {
+      "search": "Rechercher",
+      "plateLookup": "Recherche de plaque",
+      "save": "Enregistrer",
+      "sidebar": "Afficher ou masquer la barre latérale",
+      "help": "Afficher les raccourcis clavier",
+      "newInspection": "Nouvelle inspection",
+      "calendar_day": "Vue jour",
+      "calendar_week": "Vue semaine",
+      "calendar_month": "Vue mois",
+      "calendar_year": "Vue année",
+      "calendar_schedule": "Vue planning",
+      "calendar_fourDays": "Vue 4 jours",
+      "calendar_today": "Aller à aujourd'hui",
+      "calendar_next": "Période suivante",
+      "calendar_previous": "Période précédente"
+    },
+    "help": {
+      "title": "Raccourcis clavier",
+      "description": "Vos touches actuelles. Rechercher ouvre n'importe quelle page. Modifiez ou désactivez des touches dans les Paramètres.",
+      "disabledNote": "Les raccourcis clavier sont désactivés. Activez-les dans les Paramètres.",
+      "find": "Trouver un raccourci",
+      "noMatch": "Aucun raccourci ne correspond",
+      "customize": "Modifier les raccourcis",
+      "fixedHint": "toujours identique",
+      "listMove": "Se déplacer dans une liste",
+      "listOpen": "Ouvrir la ligne",
+      "photos": "Photo suivante ou précédente",
+      "close": "Fermer une boîte de dialogue ou un menu"
+    }
+  },
   "data": {
     "title": "Gestion des données",
     "description": "Récupérez les données de votre ancien système, téléchargez une sauvegarde complète ou restaurez-en une.",

+ 0 - 1
messages/fr/vehicles.json

@@ -562,7 +562,6 @@
   },
   "plateLookup": {
     "open": "Recherche de plaque",
-    "shortcut": "Ctrl+Shift+L",
     "title": "Recherche de plaque",
     "description": "Saisissez une immatriculation pour voir ce que votre atelier et le registre des véhicules en savent",
     "placeholder": "Saisissez une plaque",

+ 2 - 1
messages/it/navigation.json

@@ -42,6 +42,7 @@
     "warranty": "Garanzia",
     "workshop": "Officina",
     "appearance": "Aspetto",
+    "shortcuts": "Scorciatoie da tastiera",
     "email": "Email",
     "sms": "SMS",
     "telegram": "Telegram",
@@ -74,7 +75,6 @@
     "inspectionDetails": "Dettagli ispezione"
   },
   "search": "Cerca...",
-  "shortcut": "Ctrl+K",
   "readMore": "Scopri di più",
   "newWorkOrder": "Nuovo ordine di lavoro",
   "quickCreate": {
@@ -129,6 +129,7 @@
     "cancel": "Annulla",
     "createCompany": "Crea azienda",
     "theme": "Tema",
+    "keyboardShortcuts": "Scorciatoie da tastiera",
     "signOut": "Esci",
     "more": "Altro",
     "auditLog": "Registro attività",

+ 91 - 0
messages/it/settings.json

@@ -115,6 +115,10 @@
         "title": "Aspetto",
         "description": "Tema e visualizzazione"
       },
+      "shortcuts": {
+        "title": "Scorciatoie da tastiera",
+        "description": "I tuoi tasti"
+      },
       "data": {
         "title": "Dati",
         "description": "Esportazione e importazione backup"
@@ -1379,6 +1383,93 @@
       }
     }
   },
+  "shortcuts": {
+    "title": "Scorciatoie da tastiera",
+    "description": "I tuoi tasti. Ti seguono su ogni dispositivo da cui accedi.",
+    "enableLabel": "Usa le scorciatoie da tastiera",
+    "enableHint": "Attiva o disattiva tutte le scorciatoie di questa pagina.",
+    "singleKeysLabel": "Tasti a lettera singola",
+    "singleKeysHint": "Scorciatoie formate da una sola lettera. Solo il calendario le ha, come W per la vista settimana. Disattivale se usi il controllo vocale o le premi per sbaglio.",
+    "goToSequencesLabel": "{prefix}, poi la lettera di una pagina, apre quella pagina",
+    "goToSequencesHint": "Entrambe le pressioni usano lo stesso tasto modificatore, quindi niente di ciò che digiti può attivarle: {example} apre {workOrders}. Le lettere sono elencate sotto Vai a.",
+    "allTitle": "Tutte le scorciatoie",
+    "allHint": "Seleziona Modifica, poi premi i tasti che vuoi. Esc annulla.",
+    "resetAll": "Ripristina tutte",
+    "resetAllTitle": "Ripristinare tutte le scorciatoie?",
+    "resetAllDescription": "Ogni tasto torna a quello originale, e le scorciatoie che hai disattivato vengono riattivate.",
+    "change": "Modifica",
+    "cancel": "Annulla",
+    "reset": "Ripristina",
+    "resetTo": "Torna a {keys}",
+    "resetToNone": "Torna a nessun tasto",
+    "changed": "Modificata",
+    "off": "Disattivata",
+    "noKey": "Nessun tasto",
+    "or": "o",
+    "then": "poi",
+    "pressKeys": "Premi i nuovi tasti…",
+    "recordingFor": "Registrazione di una nuova scorciatoia per {action}. Premi i tasti, o Esc per annullare.",
+    "changeFor": "Modifica la scorciatoia per {action}",
+    "resetFor": "Ripristina la scorciatoia per {action}",
+    "switchFor": "Scorciatoia per {action}",
+    "clash": "{keys} è già assegnato a {action}. Se lo usi qui, {action} rimane senza.",
+    "useHere": "Usalo qui",
+    "pickAnother": "Scegline un altro",
+    "problems": {
+      "reserved": "{keys} è riservato al browser o al sistema e non può essere usato.",
+      "taken": "{keys} è riservato a un'altra scorciatoia e non può essere spostato.",
+      "needsModifier": "Questa scorciatoia funziona in ogni pagina, quindi richiede {mod} o {alt} insieme al tasto.",
+      "invalid": "Questo tasto non può essere usato."
+    },
+    "alsoUsedBy": "È anche il tasto per {action}. Funzionerà solo uno dei due.",
+    "goToNote": "Cerca ({keys}) apre qualsiasi pagina, e {prefix} seguito da una lettera apre quelle principali. Assegna qui un tasto proprio a qualsiasi pagina.",
+    "announceSet": "{action} ora è {keys}",
+    "announceReset": "{action} è tornata a quella predefinita",
+    "announceResetAll": "Tutte le scorciatoie sono tornate a quelle predefinite",
+    "phoneNote": "Le scorciatoie richiedono una tastiera. Le modifiche fatte qui valgono anche sul tuo computer.",
+    "saveFailed": "Impossibile salvare le scorciatoie",
+    "groups": {
+      "general": "Generali",
+      "create": "Crea",
+      "goTo": "Vai a",
+      "calendar": "Calendario",
+      "fixed": "Elenchi e foto"
+    },
+    "scopes": {
+      "global": "Ovunque nell'app",
+      "calendar": "Solo nel calendario"
+    },
+    "actions": {
+      "search": "Cerca",
+      "plateLookup": "Ricerca targa",
+      "save": "Salva",
+      "sidebar": "Mostra o nascondi la barra laterale",
+      "help": "Mostra le scorciatoie da tastiera",
+      "newInspection": "Nuova ispezione",
+      "calendar_day": "Vista giorno",
+      "calendar_week": "Vista settimana",
+      "calendar_month": "Vista mese",
+      "calendar_year": "Vista anno",
+      "calendar_schedule": "Vista agenda",
+      "calendar_fourDays": "Vista 4 giorni",
+      "calendar_today": "Vai a oggi",
+      "calendar_next": "Periodo successivo",
+      "calendar_previous": "Periodo precedente"
+    },
+    "help": {
+      "title": "Scorciatoie da tastiera",
+      "description": "I tasti che usi ora. Cerca apre qualsiasi pagina. Modifica o disattiva i tasti nelle Impostazioni.",
+      "disabledNote": "Le scorciatoie da tastiera sono disattivate. Attivale nelle Impostazioni.",
+      "find": "Trova una scorciatoia",
+      "noMatch": "Nessuna scorciatoia corrisponde",
+      "customize": "Modifica le scorciatoie",
+      "fixedHint": "sempre uguale",
+      "listMove": "Spostarsi in un elenco",
+      "listOpen": "Apri la riga",
+      "photos": "Foto successiva o precedente",
+      "close": "Chiudi una finestra o un menu"
+    }
+  },
   "data": {
     "title": "Gestione dati",
     "description": "Porta i dati dal tuo vecchio sistema, scarica un backup di tutto o ripristinane uno.",

+ 0 - 1
messages/it/vehicles.json

@@ -562,7 +562,6 @@
   },
   "plateLookup": {
     "open": "Ricerca targa",
-    "shortcut": "Ctrl+Shift+L",
     "title": "Ricerca targa",
     "description": "Digita una targa per vedere cosa sanno la tua officina e il registro veicoli",
     "placeholder": "Digita una targa",

+ 2 - 1
messages/lt/navigation.json

@@ -42,6 +42,7 @@
     "warranty": "Garantija",
     "workshop": "Dirbtuvės",
     "appearance": "Išvaizda",
+    "shortcuts": "Spartieji klavišai",
     "email": "El. paštas",
     "sms": "SMS",
     "telegram": "Telegram",
@@ -74,7 +75,6 @@
     "inspectionDetails": "Apžiūros informacija"
   },
   "search": "Ieškoti...",
-  "shortcut": "Ctrl+K",
   "readMore": "Skaityti daugiau",
   "newWorkOrder": "Naujas darbo užsakymas",
   "quickCreate": {
@@ -129,6 +129,7 @@
     "cancel": "Atšaukti",
     "createCompany": "Sukurti įmonę",
     "theme": "Tema",
+    "keyboardShortcuts": "Spartieji klavišai",
     "signOut": "Atsijungti",
     "more": "Daugiau",
     "auditLog": "Audito žurnalas",

+ 91 - 0
messages/lt/settings.json

@@ -115,6 +115,10 @@
         "title": "Išvaizda",
         "description": "Tema ir atvaizdavimas"
       },
+      "shortcuts": {
+        "title": "Spartieji klavišai",
+        "description": "Jūsų pačių klavišai"
+      },
       "data": {
         "title": "Duomenys",
         "description": "Eksportas ir importas atsarginei kopijai"
@@ -1379,6 +1383,93 @@
       }
     }
   },
+  "shortcuts": {
+    "title": "Spartieji klavišai",
+    "description": "Jūsų pačių klavišai. Jie veikia kiekviename įrenginyje, kuriame prisijungiate.",
+    "enableLabel": "Naudoti sparčiuosius klavišus",
+    "enableHint": "Įjungia arba išjungia visus šiame puslapyje esančius sparčiuosius klavišus.",
+    "singleKeysLabel": "Vienos raidės klavišai",
+    "singleKeysHint": "Spartieji klavišai iš vienos raidės. Jie yra tik kalendoriuje, pvz., W savaitės rodiniui. Išjunkite, jei naudojate valdymą balsu arba paspaudžiate juos netyčia.",
+    "goToSequencesLabel": "{prefix}, tada puslapio raidė, atidaro tą puslapį",
+    "goToSequencesHint": "Abu paspaudimai naudoja tą patį modifikavimo klavišą, todėl joks jūsų rašomas tekstas jų nesuaktyvins: {example} atidaro „{workOrders}“. Raidės išvardytos skiltyje „Eiti į“.",
+    "allTitle": "Visi spartieji klavišai",
+    "allHint": "Pasirinkite Keisti, tada paspauskite norimus klavišus. Esc atšaukia.",
+    "resetAll": "Atstatyti visus į numatytuosius",
+    "resetAllTitle": "Atstatyti visus sparčiuosius klavišus?",
+    "resetAllDescription": "Kiekvienas klavišas grąžinamas į pradinį, o išjungti spartieji klavišai vėl įjungiami.",
+    "change": "Keisti",
+    "cancel": "Atšaukti",
+    "reset": "Atstatyti",
+    "resetTo": "Grąžinti {keys}",
+    "resetToNone": "Grąžinti be klavišo",
+    "changed": "Pakeista",
+    "off": "Išjungta",
+    "noKey": "Be klavišo",
+    "or": "arba",
+    "then": "tada",
+    "pressKeys": "Paspauskite naujus klavišus…",
+    "recordingFor": "Įrašomas naujas spartusis klavišas veiksmui {action}. Paspauskite klavišus arba Escape, kad atšauktumėte.",
+    "changeFor": "Keisti veiksmo {action} spartųjį klavišą",
+    "resetFor": "Atstatyti veiksmo {action} spartųjį klavišą",
+    "switchFor": "Veiksmo {action} spartusis klavišas",
+    "clash": "{keys} jau priskirtas veiksmui {action}. Jei naudosite jį čia, tas veiksmas liks be jo.",
+    "useHere": "Naudoti čia",
+    "pickAnother": "Pasirinkti kitą",
+    "problems": {
+      "reserved": "{keys} naudoja naršyklė arba sistema, todėl jo priskirti negalima.",
+      "taken": "{keys} yra pastoviai priskirtas kitam sparčiajam klavišui ir jo perkelti negalima.",
+      "needsModifier": "Šis spartusis klavišas veikia visuose puslapiuose, todėl kartu su klavišu reikia {mod} arba {alt}.",
+      "invalid": "Šio klavišo naudoti negalima."
+    },
+    "alsoUsedBy": "Tai taip pat veiksmo {action} klavišas. Veiks tik vienas iš jų.",
+    "goToNote": "Ieškoti ({keys}) atidaro bet kurį puslapį, o {prefix} ir raidė atidaro pagrindinius. Čia bet kuriam puslapiui galite priskirti savo klavišą.",
+    "announceSet": "{action}: dabar {keys}",
+    "announceReset": "{action}: grąžintas numatytasis",
+    "announceResetAll": "Visi spartieji klavišai grąžinti į numatytuosius",
+    "phoneNote": "Sparčiesiems klavišams reikia klaviatūros. Čia atlikti pakeitimai galioja ir jūsų kompiuteryje.",
+    "saveFailed": "Nepavyko išsaugoti sparčiųjų klavišų",
+    "groups": {
+      "general": "Bendra",
+      "create": "Kurti",
+      "goTo": "Eiti į",
+      "calendar": "Kalendorius",
+      "fixed": "Sąrašai ir nuotraukos"
+    },
+    "scopes": {
+      "global": "Bet kur programoje",
+      "calendar": "Tik kalendoriuje"
+    },
+    "actions": {
+      "search": "Ieškoti",
+      "plateLookup": "Numerio paieška",
+      "save": "Išsaugoti",
+      "sidebar": "Rodyti arba slėpti šoninę juostą",
+      "help": "Rodyti sparčiuosius klavišus",
+      "newInspection": "Nauja apžiūra",
+      "calendar_day": "Dienos rodinys",
+      "calendar_week": "Savaitės rodinys",
+      "calendar_month": "Mėnesio rodinys",
+      "calendar_year": "Metų rodinys",
+      "calendar_schedule": "Tvarkaraščio rodinys",
+      "calendar_fourDays": "4 dienų rodinys",
+      "calendar_today": "Eiti į šiandieną",
+      "calendar_next": "Kitas laikotarpis",
+      "calendar_previous": "Ankstesnis laikotarpis"
+    },
+    "help": {
+      "title": "Spartieji klavišai",
+      "description": "Dabartiniai jūsų klavišai. Ieškoti atidaro bet kurį puslapį. Pakeisti ar išjungti klavišus galite Nustatymuose.",
+      "disabledNote": "Spartieji klavišai išjungti. Įjunkite juos Nustatymuose.",
+      "find": "Ieškoti sparčiojo klavišo",
+      "noMatch": "Atitinkančių sparčiųjų klavišų nėra",
+      "customize": "Keisti sparčiuosius klavišus",
+      "fixedHint": "visada toks pat",
+      "listMove": "Judėti sąraše",
+      "listOpen": "Atidaryti eilutę",
+      "photos": "Kita arba ankstesnė nuotrauka",
+      "close": "Uždaryti langą arba meniu"
+    }
+  },
   "data": {
     "title": "Duomenų valdymas",
     "description": "Perkelkite duomenis iš senos sistemos, atsisiųskite visko atsarginę kopiją arba ją atkurkite.",

+ 0 - 1
messages/lt/vehicles.json

@@ -562,7 +562,6 @@
   },
   "plateLookup": {
     "open": "Numerio paieška",
-    "shortcut": "Ctrl+Shift+L",
     "title": "Numerio paieška",
     "description": "Įveskite registracijos numerį ir pamatysite, ką apie jį žino jūsų dirbtuvės ir transporto priemonių registras",
     "placeholder": "Įveskite numerį",

+ 2 - 1
messages/nb/navigation.json

@@ -42,6 +42,7 @@
     "warranty": "Garanti",
     "workshop": "Verksted",
     "appearance": "Utseende",
+    "shortcuts": "Hurtigtaster",
     "email": "E-post",
     "sms": "SMS",
     "telegram": "Telegram",
@@ -74,7 +75,6 @@
     "inspectionDetails": "Inspeksjonsdetaljer"
   },
   "search": "Søk...",
-  "shortcut": "Ctrl+K",
   "readMore": "Les mer",
   "newWorkOrder": "Ny arbeidsordre",
   "quickCreate": {
@@ -129,6 +129,7 @@
     "cancel": "Avbryt",
     "createCompany": "Opprett firma",
     "theme": "Tema",
+    "keyboardShortcuts": "Hurtigtaster",
     "signOut": "Logg ut",
     "more": "Mer",
     "auditLog": "Aktivitetslogg",

+ 91 - 0
messages/nb/settings.json

@@ -115,6 +115,10 @@
         "title": "Utseende",
         "description": "Tema og visning"
       },
+      "shortcuts": {
+        "title": "Hurtigtaster",
+        "description": "Dine egne taster"
+      },
       "data": {
         "title": "Data",
         "description": "Eksporter og importer sikkerhetskopi"
@@ -1379,6 +1383,93 @@
       }
     }
   },
+  "shortcuts": {
+    "title": "Hurtigtaster",
+    "description": "Dine egne taster. De følger deg til alle enheter du logger inn på.",
+    "enableLabel": "Bruk hurtigtaster",
+    "enableHint": "Slår alle hurtigtastene på denne siden av eller på.",
+    "singleKeysLabel": "Taster med én bokstav",
+    "singleKeysHint": "Hurtigtaster som bare er én bokstav. Bare kalenderen har dem, for eksempel W for ukevisning. Slå av hvis du bruker stemmestyring eller trykker på dem ved et uhell.",
+    "goToSequencesLabel": "{prefix}, så sidens bokstav, åpner den siden",
+    "goToSequencesHint": "Begge trykkene bruker samme modifikatortast, så ingenting du skriver kan utløse dem: {example} åpner {workOrders}. Bokstavene står under Gå til.",
+    "allTitle": "Alle hurtigtaster",
+    "allHint": "Velg Endre, og trykk deretter tastene du vil bruke. Esc avbryter.",
+    "resetAll": "Tilbakestill alle til standard",
+    "resetAllTitle": "Tilbakestille alle hurtigtaster?",
+    "resetAllDescription": "Hver tast går tilbake til den opprinnelige, og hurtigtaster du har slått av, slås på igjen.",
+    "change": "Endre",
+    "cancel": "Avbryt",
+    "reset": "Tilbakestill",
+    "resetTo": "Tilbake til {keys}",
+    "resetToNone": "Tilbake til ingen tast",
+    "changed": "Endret",
+    "off": "Av",
+    "noKey": "Ingen tast",
+    "or": "eller",
+    "then": "så",
+    "pressKeys": "Trykk de nye tastene…",
+    "recordingFor": "Tar opp ny hurtigtast for {action}. Trykk tastene, eller Esc for å avbryte.",
+    "changeFor": "Endre hurtigtasten for {action}",
+    "resetFor": "Tilbakestill hurtigtasten for {action}",
+    "switchFor": "Hurtigtast for {action}",
+    "clash": "{keys} er allerede brukt av {action}. Bruker du den her, står {action} uten.",
+    "useHere": "Bruk den her",
+    "pickAnother": "Velg en annen",
+    "problems": {
+      "reserved": "{keys} tilhører nettleseren eller systemet og kan ikke brukes.",
+      "taken": "{keys} er låst til en annen snarvei og kan ikke flyttes.",
+      "needsModifier": "Denne hurtigtasten virker på alle sider, så den trenger {mod} eller {alt} sammen med tasten.",
+      "invalid": "Den tasten kan ikke brukes."
+    },
+    "alsoUsedBy": "Også tasten for {action}. Bare én av dem vil virke.",
+    "goToNote": "Søk ({keys}) åpner alle sider, og {prefix} etterfulgt av en bokstav åpner de viktigste. Her kan du gi hvilken som helst side sin egen tast.",
+    "announceSet": "{action} er nå {keys}",
+    "announceReset": "{action} er tilbake til standard",
+    "announceResetAll": "Alle hurtigtaster er tilbake til standard",
+    "phoneNote": "Hurtigtaster krever tastatur. Endringer du gjør her, gjelder også på datamaskinen din.",
+    "saveFailed": "Kunne ikke lagre hurtigtastene dine",
+    "groups": {
+      "general": "Generelt",
+      "create": "Opprett",
+      "goTo": "Gå til",
+      "calendar": "Kalender",
+      "fixed": "Lister og bilder"
+    },
+    "scopes": {
+      "global": "Overalt i appen",
+      "calendar": "Bare i kalenderen"
+    },
+    "actions": {
+      "search": "Søk",
+      "plateLookup": "Skiltoppslag",
+      "save": "Lagre",
+      "sidebar": "Vis eller skjul sidemenyen",
+      "help": "Vis hurtigtaster",
+      "newInspection": "Ny inspeksjon",
+      "calendar_day": "Dagsvisning",
+      "calendar_week": "Ukevisning",
+      "calendar_month": "Månedsvisning",
+      "calendar_year": "Årsvisning",
+      "calendar_schedule": "Tidsplanvisning",
+      "calendar_fourDays": "4-dagersvisning",
+      "calendar_today": "Gå til i dag",
+      "calendar_next": "Neste periode",
+      "calendar_previous": "Forrige periode"
+    },
+    "help": {
+      "title": "Hurtigtaster",
+      "description": "Tastene du har nå. Søk åpner alle sider. Endre eller slå av taster i Innstillinger.",
+      "disabledNote": "Hurtigtaster er slått av. Slå dem på i Innstillinger.",
+      "find": "Finn en hurtigtast",
+      "noMatch": "Ingen hurtigtast passer",
+      "customize": "Endre hurtigtaster",
+      "fixedHint": "alltid den samme",
+      "listMove": "Flytt deg i en liste",
+      "listOpen": "Åpne raden",
+      "photos": "Neste eller forrige bilde",
+      "close": "Lukk en dialog eller meny"
+    }
+  },
   "data": {
     "title": "Datahåndtering",
     "description": "Hent inn data fra det gamle systemet ditt, last ned en sikkerhetskopi av alt, eller gjenopprett en.",

+ 0 - 1
messages/nb/vehicles.json

@@ -562,7 +562,6 @@
   },
   "plateLookup": {
     "open": "Skiltoppslag",
-    "shortcut": "Ctrl+Shift+L",
     "title": "Skiltoppslag",
     "description": "Skriv inn et registreringsnummer for å se hva verkstedet og kjøretøyregisteret vet om det",
     "placeholder": "Skriv inn et skilt",

+ 2 - 1
messages/nl/navigation.json

@@ -42,6 +42,7 @@
     "warranty": "Garantie",
     "workshop": "Werkplaats",
     "appearance": "Weergave",
+    "shortcuts": "Sneltoetsen",
     "email": "E-mail",
     "sms": "SMS",
     "telegram": "Telegram",
@@ -74,7 +75,6 @@
     "inspectionDetails": "Inspectiegegevens"
   },
   "search": "Zoeken...",
-  "shortcut": "Ctrl+K",
   "readMore": "Meer lezen",
   "newWorkOrder": "Nieuwe werkorder",
   "quickCreate": {
@@ -129,6 +129,7 @@
     "cancel": "Annuleren",
     "createCompany": "Bedrijf aanmaken",
     "theme": "Thema",
+    "keyboardShortcuts": "Sneltoetsen",
     "signOut": "Uitloggen",
     "more": "Meer",
     "auditLog": "Activiteitenlog",

+ 91 - 0
messages/nl/settings.json

@@ -115,6 +115,10 @@
         "title": "Weergave",
         "description": "Thema en weergave"
       },
+      "shortcuts": {
+        "title": "Sneltoetsen",
+        "description": "Uw eigen toetsen"
+      },
       "data": {
         "title": "Gegevens",
         "description": "Exporteer en importeer back-up"
@@ -1379,6 +1383,93 @@
       }
     }
   },
+  "shortcuts": {
+    "title": "Sneltoetsen",
+    "description": "Uw eigen toetsen. Ze gaan mee naar elk apparaat waarop u inlogt.",
+    "enableLabel": "Sneltoetsen gebruiken",
+    "enableHint": "Zet alle sneltoetsen op deze pagina aan of uit.",
+    "singleKeysLabel": "Toetsen met één letter",
+    "singleKeysHint": "Sneltoetsen die uit één letter bestaan. Alleen de agenda heeft ze, zoals W voor de weekweergave. Zet ze uit als u spraakbesturing gebruikt of ze per ongeluk indrukt.",
+    "goToSequencesLabel": "{prefix}, dan de letter van een pagina, opent die pagina",
+    "goToSequencesHint": "Beide aanslagen gebruiken dezelfde modificatietoets, dus niets wat u typt kan ze activeren: {example} opent {workOrders}. De letters staan onder Ga naar.",
+    "allTitle": "Alle sneltoetsen",
+    "allHint": "Kies Wijzigen en druk daarna op de toetsen die u wilt. Esc annuleert.",
+    "resetAll": "Alles terugzetten naar standaard",
+    "resetAllTitle": "Alle sneltoetsen terugzetten?",
+    "resetAllDescription": "Elke toets gaat terug naar de oorspronkelijke, en sneltoetsen die u hebt uitgezet, gaan weer aan.",
+    "change": "Wijzigen",
+    "cancel": "Annuleren",
+    "reset": "Herstellen",
+    "resetTo": "Terug naar {keys}",
+    "resetToNone": "Terug naar geen toets",
+    "changed": "Gewijzigd",
+    "off": "Uit",
+    "noKey": "Geen toets",
+    "or": "of",
+    "then": "dan",
+    "pressKeys": "Druk op de nieuwe toetsen…",
+    "recordingFor": "Nieuwe sneltoets opnemen voor {action}. Druk op de toetsen, of op Esc om te annuleren.",
+    "changeFor": "Sneltoets voor {action} wijzigen",
+    "resetFor": "Sneltoets voor {action} herstellen",
+    "switchFor": "Sneltoets voor {action}",
+    "clash": "{keys} hoort al bij {action}. Gebruikt u hem hier, dan heeft {action} geen sneltoets meer.",
+    "useHere": "Hier gebruiken",
+    "pickAnother": "Andere kiezen",
+    "problems": {
+      "reserved": "{keys} is van de browser of het systeem en kan niet worden gebruikt.",
+      "taken": "{keys} ligt vast voor een andere sneltoets en kan niet worden verplaatst.",
+      "needsModifier": "Deze sneltoets werkt op elke pagina en heeft daarom {mod} of {alt} samen met de toets nodig.",
+      "invalid": "Die toets kan niet worden gebruikt."
+    },
+    "alsoUsedBy": "Ook de toets voor {action}. Slechts een van beide zal werken.",
+    "goToNote": "Zoeken ({keys}) opent elke pagina en {prefix} gevolgd door een letter opent de belangrijkste. Geef hier elke pagina die u wilt een eigen toets.",
+    "announceSet": "{action} is nu {keys}",
+    "announceReset": "{action} is terug naar de standaard",
+    "announceResetAll": "Alle sneltoetsen zijn terug naar de standaard",
+    "phoneNote": "Sneltoetsen hebben een toetsenbord nodig. Wat u hier wijzigt, geldt ook op uw computer.",
+    "saveFailed": "Uw sneltoetsen konden niet worden opgeslagen",
+    "groups": {
+      "general": "Algemeen",
+      "create": "Aanmaken",
+      "goTo": "Ga naar",
+      "calendar": "Agenda",
+      "fixed": "Lijsten en foto's"
+    },
+    "scopes": {
+      "global": "Overal in de app",
+      "calendar": "Alleen in de agenda"
+    },
+    "actions": {
+      "search": "Zoeken",
+      "plateLookup": "Kenteken opzoeken",
+      "save": "Opslaan",
+      "sidebar": "Zijbalk tonen of verbergen",
+      "help": "Sneltoetsen tonen",
+      "newInspection": "Nieuwe inspectie",
+      "calendar_day": "Dagweergave",
+      "calendar_week": "Weekweergave",
+      "calendar_month": "Maandweergave",
+      "calendar_year": "Jaarweergave",
+      "calendar_schedule": "Planningweergave",
+      "calendar_fourDays": "4-dagenweergave",
+      "calendar_today": "Naar vandaag",
+      "calendar_next": "Volgende periode",
+      "calendar_previous": "Vorige periode"
+    },
+    "help": {
+      "title": "Sneltoetsen",
+      "description": "Uw huidige toetsen. Zoeken opent elke pagina. Wijzig toetsen of zet ze uit in Instellingen.",
+      "disabledNote": "Sneltoetsen staan uit. Zet ze aan in Instellingen.",
+      "find": "Sneltoets zoeken",
+      "noMatch": "Geen sneltoets gevonden",
+      "customize": "Sneltoetsen wijzigen",
+      "fixedHint": "altijd hetzelfde",
+      "listMove": "Door een lijst bewegen",
+      "listOpen": "Rij openen",
+      "photos": "Volgende of vorige foto",
+      "close": "Dialoogvenster of menu sluiten"
+    }
+  },
   "data": {
     "title": "Gegevensbeheer",
     "description": "Haal gegevens uit uw oude systeem, download een back-up van alles of zet er een terug.",

+ 0 - 1
messages/nl/vehicles.json

@@ -562,7 +562,6 @@
   },
   "plateLookup": {
     "open": "Kenteken opzoeken",
-    "shortcut": "Ctrl+Shift+L",
     "title": "Kenteken opzoeken",
     "description": "Typ een kenteken om te zien wat je werkplaats en het voertuigregister erover weten",
     "placeholder": "Typ een kenteken",

+ 2 - 1
messages/pl/navigation.json

@@ -42,6 +42,7 @@
     "warranty": "Gwarancja",
     "workshop": "Warsztat",
     "appearance": "Wygląd",
+    "shortcuts": "Skróty klawiszowe",
     "email": "E-mail",
     "sms": "SMS",
     "telegram": "Telegram",
@@ -74,7 +75,6 @@
     "inspectionDetails": "Szczegóły przeglądu"
   },
   "search": "Szukaj...",
-  "shortcut": "Ctrl+K",
   "readMore": "Dowiedz się więcej",
   "newWorkOrder": "Nowe zlecenie",
   "quickCreate": {
@@ -129,6 +129,7 @@
     "cancel": "Anuluj",
     "createCompany": "Utwórz firmę",
     "theme": "Motyw",
+    "keyboardShortcuts": "Skróty klawiszowe",
     "signOut": "Wyloguj się",
     "more": "Więcej",
     "auditLog": "Dziennik audytu",

+ 91 - 0
messages/pl/settings.json

@@ -115,6 +115,10 @@
         "title": "Wygląd",
         "description": "Motyw i wyświetlanie"
       },
+      "shortcuts": {
+        "title": "Skróty klawiszowe",
+        "description": "Twoje własne klawisze"
+      },
       "data": {
         "title": "Dane",
         "description": "Eksport i import kopii zapasowej"
@@ -1379,6 +1383,93 @@
       }
     }
   },
+  "shortcuts": {
+    "title": "Skróty klawiszowe",
+    "description": "Twoje własne klawisze. Działają na każdym urządzeniu, na którym się zalogujesz.",
+    "enableLabel": "Używaj skrótów klawiszowych",
+    "enableHint": "Włącza lub wyłącza wszystkie skróty z tej strony.",
+    "singleKeysLabel": "Skróty jednoliterowe",
+    "singleKeysHint": "Skróty składające się z samej litery. Ma je tylko kalendarz, np. W dla widoku tygodnia. Wyłącz je, jeśli korzystasz ze sterowania głosowego lub naciskasz je przypadkiem.",
+    "goToSequencesLabel": "{prefix}, potem litera strony, otwiera tę stronę",
+    "goToSequencesHint": "Oba naciśnięcia używają tego samego klawisza modyfikującego, więc nic, co piszesz, ich nie wywoła: {example} otwiera „{workOrders}”. Litery są wymienione w sekcji Przejdź do.",
+    "allTitle": "Wszystkie skróty",
+    "allHint": "Wybierz Zmień, a następnie naciśnij wybrane klawisze. Esc anuluje.",
+    "resetAll": "Przywróć wszystkie domyślne",
+    "resetAllTitle": "Zresetować wszystkie skróty?",
+    "resetAllDescription": "Każdy klawisz wraca do pierwotnego, a wyłączone skróty zostaną ponownie włączone.",
+    "change": "Zmień",
+    "cancel": "Anuluj",
+    "reset": "Resetuj",
+    "resetTo": "Przywróć {keys}",
+    "resetToNone": "Przywróć brak klawisza",
+    "changed": "Zmieniony",
+    "off": "Wyłączony",
+    "noKey": "Brak klawisza",
+    "or": "lub",
+    "then": "potem",
+    "pressKeys": "Naciśnij nowe klawisze…",
+    "recordingFor": "Nagrywanie nowego skrótu dla: {action}. Naciśnij klawisze lub Esc, aby anulować.",
+    "changeFor": "Zmień skrót dla: {action}",
+    "resetFor": "Resetuj skrót dla: {action}",
+    "switchFor": "Skrót dla: {action}",
+    "clash": "{keys} jest już przypisany do: {action}. Jeśli użyjesz go tutaj, tamta akcja zostanie bez skrótu.",
+    "useHere": "Użyj tutaj",
+    "pickAnother": "Wybierz inny",
+    "problems": {
+      "reserved": "{keys} należy do przeglądarki lub systemu i nie może zostać użyty.",
+      "taken": "{keys} jest na stałe przypisany do innego skrótu i nie można go przenieść.",
+      "needsModifier": "Ten skrót działa na każdej stronie, więc wymaga {mod} lub {alt} razem z klawiszem.",
+      "invalid": "Tego klawisza nie można użyć."
+    },
+    "alsoUsedBy": "To także klawisz dla: {action}. Zadziała tylko jeden z nich.",
+    "goToNote": "Szukaj ({keys}) otwiera każdą stronę, a {prefix} z literą otwiera najważniejsze. Tutaj możesz przypisać dowolnej stronie własny klawisz.",
+    "announceSet": "{action}: teraz {keys}",
+    "announceReset": "{action}: przywrócono domyślny",
+    "announceResetAll": "Przywrócono domyślne wszystkie skróty",
+    "phoneNote": "Skróty wymagają klawiatury. Zmiany wprowadzone tutaj obowiązują też na Twoim komputerze.",
+    "saveFailed": "Nie udało się zapisać skrótów",
+    "groups": {
+      "general": "Ogólne",
+      "create": "Utwórz",
+      "goTo": "Przejdź do",
+      "calendar": "Kalendarz",
+      "fixed": "Listy i zdjęcia"
+    },
+    "scopes": {
+      "global": "W całej aplikacji",
+      "calendar": "Tylko w kalendarzu"
+    },
+    "actions": {
+      "search": "Szukaj",
+      "plateLookup": "Sprawdź tablicę",
+      "save": "Zapisz",
+      "sidebar": "Pokaż lub ukryj pasek boczny",
+      "help": "Pokaż skróty klawiszowe",
+      "newInspection": "Nowa inspekcja",
+      "calendar_day": "Widok dnia",
+      "calendar_week": "Widok tygodnia",
+      "calendar_month": "Widok miesiąca",
+      "calendar_year": "Widok roku",
+      "calendar_schedule": "Widok harmonogramu",
+      "calendar_fourDays": "Widok 4 dni",
+      "calendar_today": "Przejdź do dzisiaj",
+      "calendar_next": "Następny okres",
+      "calendar_previous": "Poprzedni okres"
+    },
+    "help": {
+      "title": "Skróty klawiszowe",
+      "description": "Twoje obecne klawisze. Szukaj otwiera każdą stronę. Zmień lub wyłącz klawisze w Ustawieniach.",
+      "disabledNote": "Skróty klawiszowe są wyłączone. Włącz je w Ustawieniach.",
+      "find": "Znajdź skrót",
+      "noMatch": "Brak pasujących skrótów",
+      "customize": "Zmień skróty",
+      "fixedHint": "zawsze takie same",
+      "listMove": "Poruszanie się po liście",
+      "listOpen": "Otwórz wiersz",
+      "photos": "Następne lub poprzednie zdjęcie",
+      "close": "Zamknij okno lub menu"
+    }
+  },
   "data": {
     "title": "Zarządzanie danymi",
     "description": "Przenieś dane ze starego systemu, pobierz kopię zapasową wszystkiego lub ją przywróć.",

+ 0 - 1
messages/pl/vehicles.json

@@ -562,7 +562,6 @@
   },
   "plateLookup": {
     "open": "Sprawdź tablicę",
-    "shortcut": "Ctrl+Shift+L",
     "title": "Sprawdź tablicę",
     "description": "Wpisz numer rejestracyjny, aby zobaczyć, co wie o nim Twój warsztat i rejestr pojazdów",
     "placeholder": "Wpisz tablicę",

+ 2 - 1
messages/pt-BR/navigation.json

@@ -42,6 +42,7 @@
     "warranty": "Garantia",
     "workshop": "Oficina",
     "appearance": "Aparência",
+    "shortcuts": "Atalhos de teclado",
     "email": "E-mail",
     "sms": "SMS",
     "telegram": "Telegram",
@@ -74,7 +75,6 @@
     "inspectionDetails": "Detalhes da Inspeção"
   },
   "search": "Buscar...",
-  "shortcut": "Ctrl+K",
   "readMore": "Saiba mais",
   "newWorkOrder": "Nova Ordem de Serviço",
   "quickCreate": {
@@ -129,6 +129,7 @@
     "cancel": "Cancelar",
     "createCompany": "Criar Empresa",
     "theme": "Tema",
+    "keyboardShortcuts": "Atalhos de teclado",
     "signOut": "Sair",
     "more": "Mais",
     "auditLog": "Registro de auditoria",

+ 91 - 0
messages/pt-BR/settings.json

@@ -115,6 +115,10 @@
         "title": "Aparência",
         "description": "Tema e exibição"
       },
+      "shortcuts": {
+        "title": "Atalhos de teclado",
+        "description": "Suas próprias teclas"
+      },
       "data": {
         "title": "Dados",
         "description": "Exportar e importar backup"
@@ -1379,6 +1383,93 @@
       }
     }
   },
+  "shortcuts": {
+    "title": "Atalhos de teclado",
+    "description": "Suas próprias teclas. Elas acompanham você em todos os dispositivos em que você entrar.",
+    "enableLabel": "Usar atalhos de teclado",
+    "enableHint": "Ativa ou desativa todos os atalhos desta página.",
+    "singleKeysLabel": "Teclas de uma letra só",
+    "singleKeysHint": "Atalhos formados por uma única letra. Só a agenda tem, como W para a visualização da semana. Desative se você usa controle por voz ou aperta essas teclas sem querer.",
+    "goToSequencesLabel": "{prefix} e depois a letra de uma página abre essa página",
+    "goToSequencesHint": "Os dois toques usam a mesma tecla modificadora, então nada do que você digita pode acioná-los: {example} abre {workOrders}. As letras estão listadas em Ir para.",
+    "allTitle": "Todos os atalhos",
+    "allHint": "Selecione Alterar e pressione as teclas desejadas. Esc cancela.",
+    "resetAll": "Redefinir tudo para o padrão",
+    "resetAllTitle": "Redefinir todos os atalhos?",
+    "resetAllDescription": "Cada tecla volta à original, e os atalhos que você desativou são ativados novamente.",
+    "change": "Alterar",
+    "cancel": "Cancelar",
+    "reset": "Redefinir",
+    "resetTo": "Voltar para {keys}",
+    "resetToNone": "Voltar para nenhuma tecla",
+    "changed": "Alterado",
+    "off": "Desativado",
+    "noKey": "Nenhuma tecla",
+    "or": "ou",
+    "then": "depois",
+    "pressKeys": "Pressione as novas teclas…",
+    "recordingFor": "Gravando um novo atalho para {action}. Pressione as teclas, ou Esc para cancelar.",
+    "changeFor": "Alterar o atalho de {action}",
+    "resetFor": "Redefinir o atalho de {action}",
+    "switchFor": "Atalho de {action}",
+    "clash": "{keys} já pertence a {action}. Se você usar aqui, {action} fica sem atalho.",
+    "useHere": "Usar aqui",
+    "pickAnother": "Escolher outro",
+    "problems": {
+      "reserved": "{keys} é do navegador ou do sistema e não pode ser usado.",
+      "taken": "{keys} está fixo em outro atalho e não pode ser movido.",
+      "needsModifier": "Este atalho funciona em todas as páginas, então precisa de {mod} ou {alt} junto com a tecla.",
+      "invalid": "Essa tecla não pode ser usada."
+    },
+    "alsoUsedBy": "Também é a tecla de {action}. Só um deles vai funcionar.",
+    "goToNote": "Buscar ({keys}) abre qualquer página, e {prefix} seguido de uma letra abre as principais. Dê aqui uma tecla própria a qualquer página.",
+    "announceSet": "{action} agora é {keys}",
+    "announceReset": "{action} voltou ao padrão",
+    "announceResetAll": "Todos os atalhos voltaram ao padrão",
+    "phoneNote": "Atalhos precisam de um teclado. As alterações feitas aqui valem também no seu computador.",
+    "saveFailed": "Não foi possível salvar seus atalhos",
+    "groups": {
+      "general": "Geral",
+      "create": "Criar",
+      "goTo": "Ir para",
+      "calendar": "Agenda",
+      "fixed": "Listas e fotos"
+    },
+    "scopes": {
+      "global": "Em qualquer lugar do app",
+      "calendar": "Somente na agenda"
+    },
+    "actions": {
+      "search": "Buscar",
+      "plateLookup": "Consultar placa",
+      "save": "Salvar",
+      "sidebar": "Mostrar ou ocultar a barra lateral",
+      "help": "Mostrar atalhos de teclado",
+      "newInspection": "Nova inspeção",
+      "calendar_day": "Visualização do dia",
+      "calendar_week": "Visualização da semana",
+      "calendar_month": "Visualização do mês",
+      "calendar_year": "Visualização do ano",
+      "calendar_schedule": "Visualização de agenda",
+      "calendar_fourDays": "Visualização de 4 dias",
+      "calendar_today": "Ir para hoje",
+      "calendar_next": "Próximo período",
+      "calendar_previous": "Período anterior"
+    },
+    "help": {
+      "title": "Atalhos de teclado",
+      "description": "Suas teclas atuais. Buscar abre qualquer página. Altere ou desative teclas em Configurações.",
+      "disabledNote": "Os atalhos de teclado estão desativados. Ative em Configurações.",
+      "find": "Encontrar um atalho",
+      "noMatch": "Nenhum atalho encontrado",
+      "customize": "Alterar atalhos",
+      "fixedHint": "sempre igual",
+      "listMove": "Navegar por uma lista",
+      "listOpen": "Abrir a linha",
+      "photos": "Foto seguinte ou anterior",
+      "close": "Fechar uma caixa de diálogo ou menu"
+    }
+  },
   "data": {
     "title": "Gerenciamento de dados",
     "description": "Traga dados do seu sistema antigo, baixe um backup de tudo ou restaure um.",

+ 0 - 1
messages/pt-BR/vehicles.json

@@ -562,7 +562,6 @@
   },
   "plateLookup": {
     "open": "Consultar placa",
-    "shortcut": "Ctrl+Shift+L",
     "title": "Consultar placa",
     "description": "Digite uma placa para ver o que a sua oficina e o registro de veículos sabem sobre ela",
     "placeholder": "Digite uma placa",

+ 2 - 1
messages/pt-PT/navigation.json

@@ -42,6 +42,7 @@
     "warranty": "Garantia",
     "workshop": "Oficina",
     "appearance": "Aspeto",
+    "shortcuts": "Atalhos de teclado",
     "email": "E-mail",
     "sms": "SMS",
     "telegram": "Telegram",
@@ -74,7 +75,6 @@
     "inspectionDetails": "Detalhes da inspeção"
   },
   "search": "Pesquisar...",
-  "shortcut": "Ctrl+K",
   "readMore": "Ler mais",
   "newWorkOrder": "Nova ordem de serviço",
   "quickCreate": {
@@ -129,6 +129,7 @@
     "cancel": "Cancelar",
     "createCompany": "Criar empresa",
     "theme": "Tema",
+    "keyboardShortcuts": "Atalhos de teclado",
     "signOut": "Terminar sessão",
     "more": "Mais",
     "auditLog": "Registo de auditoria",

+ 91 - 0
messages/pt-PT/settings.json

@@ -115,6 +115,10 @@
         "title": "Aspeto",
         "description": "Tema e visualização"
       },
+      "shortcuts": {
+        "title": "Atalhos de teclado",
+        "description": "As suas próprias teclas"
+      },
       "data": {
         "title": "Dados",
         "description": "Exportar e importar cópia de segurança"
@@ -1379,6 +1383,93 @@
       }
     }
   },
+  "shortcuts": {
+    "title": "Atalhos de teclado",
+    "description": "As suas próprias teclas. Acompanham-no em todos os dispositivos em que iniciar sessão.",
+    "enableLabel": "Utilizar atalhos de teclado",
+    "enableHint": "Ativa ou desativa todos os atalhos desta página.",
+    "singleKeysLabel": "Teclas de uma só letra",
+    "singleKeysHint": "Atalhos formados por uma única letra. Só o calendário os tem, como W para a vista de semana. Desative-os se utiliza controlo por voz ou se os carrega sem querer.",
+    "goToSequencesLabel": "{prefix} e depois a letra de uma página abre essa página",
+    "goToSequencesHint": "As duas teclas premidas usam a mesma tecla modificadora, por isso nada do que escreve as pode acionar: {example} abre {workOrders}. As letras estão listadas em Ir para.",
+    "allTitle": "Todos os atalhos",
+    "allHint": "Selecione Alterar e prima as teclas pretendidas. Esc cancela.",
+    "resetAll": "Repor tudo",
+    "resetAllTitle": "Repor todos os atalhos?",
+    "resetAllDescription": "Cada tecla volta à original, e os atalhos que desativou são novamente ativados.",
+    "change": "Alterar",
+    "cancel": "Cancelar",
+    "reset": "Repor",
+    "resetTo": "Voltar a {keys}",
+    "resetToNone": "Voltar a nenhuma tecla",
+    "changed": "Alterado",
+    "off": "Desativado",
+    "noKey": "Nenhuma tecla",
+    "or": "ou",
+    "then": "depois",
+    "pressKeys": "Prima as novas teclas…",
+    "recordingFor": "A gravar um novo atalho para {action}. Prima as teclas, ou Esc para cancelar.",
+    "changeFor": "Alterar o atalho de {action}",
+    "resetFor": "Repor o atalho de {action}",
+    "switchFor": "Atalho de {action}",
+    "clash": "{keys} já pertence a {action}. Se o utilizar aqui, {action} fica sem atalho.",
+    "useHere": "Utilizar aqui",
+    "pickAnother": "Escolher outro",
+    "problems": {
+      "reserved": "{keys} pertence ao navegador ou ao sistema e não pode ser utilizado.",
+      "taken": "{keys} está fixo noutro atalho e não pode ser movido.",
+      "needsModifier": "Este atalho funciona em todas as páginas, por isso precisa de {mod} ou {alt} em conjunto com a tecla.",
+      "invalid": "Essa tecla não pode ser utilizada."
+    },
+    "alsoUsedBy": "É também a tecla de {action}. Só um deles irá funcionar.",
+    "goToNote": "Pesquisar ({keys}) abre qualquer página e {prefix} seguido de uma letra abre as principais. Atribua aqui uma tecla própria a qualquer página.",
+    "announceSet": "{action} é agora {keys}",
+    "announceReset": "{action} voltou à predefinição",
+    "announceResetAll": "Todos os atalhos voltaram à predefinição",
+    "phoneNote": "Os atalhos precisam de um teclado. As alterações feitas aqui aplicam-se também no seu computador.",
+    "saveFailed": "Não foi possível guardar os seus atalhos",
+    "groups": {
+      "general": "Geral",
+      "create": "Criar",
+      "goTo": "Ir para",
+      "calendar": "Calendário",
+      "fixed": "Listas e fotografias"
+    },
+    "scopes": {
+      "global": "Em qualquer parte da aplicação",
+      "calendar": "Apenas no calendário"
+    },
+    "actions": {
+      "search": "Pesquisar",
+      "plateLookup": "Consultar matrícula",
+      "save": "Guardar",
+      "sidebar": "Mostrar ou ocultar a barra lateral",
+      "help": "Mostrar atalhos de teclado",
+      "newInspection": "Nova inspeção",
+      "calendar_day": "Vista de dia",
+      "calendar_week": "Vista de semana",
+      "calendar_month": "Vista de mês",
+      "calendar_year": "Vista de ano",
+      "calendar_schedule": "Vista de agenda",
+      "calendar_fourDays": "Vista de 4 dias",
+      "calendar_today": "Ir para hoje",
+      "calendar_next": "Período seguinte",
+      "calendar_previous": "Período anterior"
+    },
+    "help": {
+      "title": "Atalhos de teclado",
+      "description": "As teclas que tem agora. Pesquisar abre qualquer página. Altere ou desative teclas nas Definições.",
+      "disabledNote": "Os atalhos de teclado estão desativados. Ative-os nas Definições.",
+      "find": "Procurar um atalho",
+      "noMatch": "Nenhum atalho corresponde",
+      "customize": "Alterar atalhos",
+      "fixedHint": "sempre igual",
+      "listMove": "Percorrer uma lista",
+      "listOpen": "Abrir a linha",
+      "photos": "Fotografia seguinte ou anterior",
+      "close": "Fechar uma caixa de diálogo ou menu"
+    }
+  },
   "data": {
     "title": "Gestão de dados",
     "description": "Traga dados do seu sistema antigo, transfira uma cópia de segurança de tudo ou reponha uma.",

+ 0 - 1
messages/pt-PT/vehicles.json

@@ -562,7 +562,6 @@
   },
   "plateLookup": {
     "open": "Consultar matrícula",
-    "shortcut": "Ctrl+Shift+L",
     "title": "Consultar matrícula",
     "description": "Introduza uma matrícula para ver o que a sua oficina e o registo automóvel sabem sobre ela",
     "placeholder": "Introduza uma matrícula",

+ 2 - 1
messages/ru/navigation.json

@@ -42,6 +42,7 @@
     "warranty": "Гарантия",
     "workshop": "Мастерская",
     "appearance": "Внешний вид",
+    "shortcuts": "Горячие клавиши",
     "email": "Эл. почта",
     "sms": "SMS",
     "telegram": "Telegram",
@@ -74,7 +75,6 @@
     "inspectionDetails": "Детали осмотра"
   },
   "search": "Поиск...",
-  "shortcut": "Ctrl+K",
   "readMore": "Подробнее",
   "newWorkOrder": "Новый заказ-наряд",
   "quickCreate": {
@@ -129,6 +129,7 @@
     "cancel": "Отмена",
     "createCompany": "Создать компанию",
     "theme": "Тема",
+    "keyboardShortcuts": "Горячие клавиши",
     "signOut": "Выйти",
     "more": "Ещё",
     "auditLog": "Журнал аудита",

+ 91 - 0
messages/ru/settings.json

@@ -115,6 +115,10 @@
         "title": "Внешний вид",
         "description": "Тема и отображение"
       },
+      "shortcuts": {
+        "title": "Горячие клавиши",
+        "description": "Ваши собственные клавиши"
+      },
       "data": {
         "title": "Данные",
         "description": "Экспорт и импорт резервных копий"
@@ -1379,6 +1383,93 @@
       }
     }
   },
+  "shortcuts": {
+    "title": "Горячие клавиши",
+    "description": "Ваши собственные клавиши. Они действуют на каждом устройстве, где вы входите в систему.",
+    "enableLabel": "Использовать горячие клавиши",
+    "enableHint": "Включает или выключает все сочетания клавиш на этой странице.",
+    "singleKeysLabel": "Клавиши из одной буквы",
+    "singleKeysHint": "Сочетания из одной буквы. Они есть только в календаре, например W для просмотра недели. Отключите их, если пользуетесь голосовым управлением или нажимаете их случайно.",
+    "goToSequencesLabel": "{prefix}, затем буква страницы, открывает эту страницу",
+    "goToSequencesHint": "В обоих нажатиях участвует одна и та же клавиша-модификатор, поэтому набор текста не может их вызвать: {example} открывает «{workOrders}». Буквы перечислены в разделе «Переход».",
+    "allTitle": "Все сочетания клавиш",
+    "allHint": "Нажмите «Изменить», затем нужные клавиши. Esc отменяет.",
+    "resetAll": "Сбросить все к стандартным",
+    "resetAllTitle": "Сбросить все сочетания клавиш?",
+    "resetAllDescription": "Каждая клавиша вернётся к исходной, а отключённые сочетания снова будут включены.",
+    "change": "Изменить",
+    "cancel": "Отмена",
+    "reset": "Сбросить",
+    "resetTo": "Вернуть {keys}",
+    "resetToNone": "Вернуть без клавиши",
+    "changed": "Изменено",
+    "off": "Выкл.",
+    "noKey": "Нет клавиши",
+    "or": "или",
+    "then": "затем",
+    "pressKeys": "Нажмите новые клавиши…",
+    "recordingFor": "Запись нового сочетания для действия «{action}». Нажмите клавиши или Escape для отмены.",
+    "changeFor": "Изменить сочетание для действия «{action}»",
+    "resetFor": "Сбросить сочетание для действия «{action}»",
+    "switchFor": "Сочетание для действия «{action}»",
+    "clash": "{keys} уже назначено действию «{action}». Если использовать его здесь, у того действия сочетания не останется.",
+    "useHere": "Использовать здесь",
+    "pickAnother": "Выбрать другое",
+    "problems": {
+      "reserved": "{keys} занято браузером или системой и не может быть использовано.",
+      "taken": "{keys} закреплено за другим сочетанием, и его нельзя перенести.",
+      "needsModifier": "Это сочетание работает на всех страницах, поэтому к клавише нужно добавить {mod} или {alt}.",
+      "invalid": "Эту клавишу использовать нельзя."
+    },
+    "alsoUsedBy": "Это также клавиша для действия «{action}». Сработает только одно из них.",
+    "goToNote": "Поиск ({keys}) открывает любую страницу, а {prefix} и буква открывают основные. Здесь можно назначить любой странице свою клавишу.",
+    "announceSet": "{action}: теперь {keys}",
+    "announceReset": "{action}: восстановлено стандартное сочетание",
+    "announceResetAll": "Все сочетания клавиш сброшены к стандартным",
+    "phoneNote": "Для горячих клавиш нужна клавиатура. Изменения, сделанные здесь, действуют и на вашем компьютере.",
+    "saveFailed": "Не удалось сохранить сочетания клавиш",
+    "groups": {
+      "general": "Общие",
+      "create": "Создание",
+      "goTo": "Переход",
+      "calendar": "Календарь",
+      "fixed": "Списки и фото"
+    },
+    "scopes": {
+      "global": "Во всём приложении",
+      "calendar": "Только в календаре"
+    },
+    "actions": {
+      "search": "Поиск",
+      "plateLookup": "Поиск по номеру",
+      "save": "Сохранить",
+      "sidebar": "Показать или скрыть боковую панель",
+      "help": "Показать горячие клавиши",
+      "newInspection": "Новый осмотр",
+      "calendar_day": "Просмотр дня",
+      "calendar_week": "Просмотр недели",
+      "calendar_month": "Просмотр месяца",
+      "calendar_year": "Просмотр года",
+      "calendar_schedule": "Расписание",
+      "calendar_fourDays": "Просмотр 4 дней",
+      "calendar_today": "Перейти к сегодня",
+      "calendar_next": "Следующий период",
+      "calendar_previous": "Предыдущий период"
+    },
+    "help": {
+      "title": "Горячие клавиши",
+      "description": "Ваши текущие клавиши. Поиск открывает любую страницу. Изменить или отключить клавиши можно в Настройках.",
+      "disabledNote": "Горячие клавиши отключены. Включите их в Настройках.",
+      "find": "Найти сочетание",
+      "noMatch": "Совпадений нет",
+      "customize": "Изменить сочетания",
+      "fixedHint": "всегда одинаково",
+      "listMove": "Перемещение по списку",
+      "listOpen": "Открыть строку",
+      "photos": "Следующее или предыдущее фото",
+      "close": "Закрыть диалог или меню"
+    }
+  },
   "data": {
     "title": "Управление данными",
     "description": "Перенесите данные из старой системы, скачайте резервную копию всего или восстановите её.",

+ 0 - 1
messages/ru/vehicles.json

@@ -562,7 +562,6 @@
   },
   "plateLookup": {
     "open": "Поиск по номеру",
-    "shortcut": "Ctrl+Shift+L",
     "title": "Поиск по номеру",
     "description": "Введите регистрационный номер, чтобы увидеть, что о нём знают ваша мастерская и реестр транспортных средств",
     "placeholder": "Введите номер",

+ 2 - 1
messages/tr/navigation.json

@@ -42,6 +42,7 @@
     "warranty": "Garanti",
     "workshop": "Atölye",
     "appearance": "Görünüm",
+    "shortcuts": "Klavye kısayolları",
     "email": "E-posta",
     "sms": "SMS",
     "telegram": "Telegram",
@@ -74,7 +75,6 @@
     "inspectionDetails": "Muayene Detayları"
   },
   "search": "Ara...",
-  "shortcut": "Ctrl+K",
   "readMore": "Daha fazla bilgi",
   "newWorkOrder": "Yeni İş Emri",
   "quickCreate": {
@@ -129,6 +129,7 @@
     "cancel": "İptal",
     "createCompany": "Şirket Oluştur",
     "theme": "Tema",
+    "keyboardShortcuts": "Klavye kısayolları",
     "signOut": "Çıkış Yap",
     "more": "Diğer",
     "auditLog": "Denetim günlüğü",

+ 91 - 0
messages/tr/settings.json

@@ -115,6 +115,10 @@
         "title": "Görünüm",
         "description": "Tema & görüntüleme"
       },
+      "shortcuts": {
+        "title": "Klavye kısayolları",
+        "description": "Kendi tuşlarınız"
+      },
       "data": {
         "title": "Veri",
         "description": "Dışa & içe aktarma yedeği"
@@ -1379,6 +1383,93 @@
       }
     }
   },
+  "shortcuts": {
+    "title": "Klavye kısayolları",
+    "description": "Kendi tuşlarınız. Oturum açtığınız her cihazda sizinle gelir.",
+    "enableLabel": "Klavye kısayollarını kullan",
+    "enableHint": "Bu sayfadaki tüm kısayolları açar veya kapatır.",
+    "singleKeysLabel": "Tek harfli tuşlar",
+    "singleKeysHint": "Tek bir harften oluşan kısayollar. Yalnızca takvimde vardır, örneğin hafta görünümü için W. Sesli kontrol kullanıyorsanız veya yanlışlıkla basıyorsanız kapatın.",
+    "goToSequencesLabel": "{prefix}, ardından bir sayfanın harfi, o sayfayı açar",
+    "goToSequencesHint": "Her iki basışta da aynı değiştirici tuş kullanılır, bu yüzden yazdığınız hiçbir şey bunu tetikleyemez: {example}, {workOrders} sayfasını açar. Harfler Git altında listelenir.",
+    "allTitle": "Tüm kısayollar",
+    "allHint": "Değiştir'i seçin, ardından istediğiniz tuşlara basın. Esc iptal eder.",
+    "resetAll": "Tümünü varsayılana sıfırla",
+    "resetAllTitle": "Tüm kısayollar sıfırlansın mı?",
+    "resetAllDescription": "Her tuş ilk haline döner ve kapattığınız kısayollar yeniden açılır.",
+    "change": "Değiştir",
+    "cancel": "İptal",
+    "reset": "Sıfırla",
+    "resetTo": "{keys} olarak geri al",
+    "resetToNone": "Tuşsuz haline geri al",
+    "changed": "Değiştirildi",
+    "off": "Kapalı",
+    "noKey": "Tuş yok",
+    "or": "veya",
+    "then": "ardından",
+    "pressKeys": "Yeni tuşlara basın…",
+    "recordingFor": "{action} için yeni kısayol kaydediliyor. Tuşlara basın ya da iptal etmek için Esc'ye basın.",
+    "changeFor": "{action} kısayolunu değiştir",
+    "resetFor": "{action} kısayolunu sıfırla",
+    "switchFor": "{action} kısayolu",
+    "clash": "{keys} zaten {action} için kullanılıyor. Burada kullanırsanız o işlem kısayolsuz kalır.",
+    "useHere": "Burada kullan",
+    "pickAnother": "Başka seç",
+    "problems": {
+      "reserved": "{keys} tarayıcıya veya sisteme ait olduğu için kullanılamaz.",
+      "taken": "{keys} başka bir kısayola sabitlenmiş ve taşınamaz.",
+      "needsModifier": "Bu kısayol her sayfada çalışır, bu yüzden tuşla birlikte {mod} veya {alt} gerekir.",
+      "invalid": "Bu tuş kullanılamaz."
+    },
+    "alsoUsedBy": "Aynı zamanda {action} tuşu. Yalnızca biri çalışacak.",
+    "goToNote": "Ara ({keys}) her sayfayı açar, {prefix} ve ardından bir harf ise başlıca sayfaları açar. Buradan istediğiniz sayfaya kendi tuşunu verin.",
+    "announceSet": "{action} artık {keys}",
+    "announceReset": "{action} varsayılana döndü",
+    "announceResetAll": "Tüm kısayollar varsayılana döndü",
+    "phoneNote": "Kısayollar için klavye gerekir. Burada yaptığınız değişiklikler bilgisayarınızda da geçerli olur.",
+    "saveFailed": "Kısayollarınız kaydedilemedi",
+    "groups": {
+      "general": "Genel",
+      "create": "Oluştur",
+      "goTo": "Git",
+      "calendar": "Takvim",
+      "fixed": "Listeler ve fotoğraflar"
+    },
+    "scopes": {
+      "global": "Uygulamanın her yerinde",
+      "calendar": "Yalnızca takvimde"
+    },
+    "actions": {
+      "search": "Ara",
+      "plateLookup": "Plaka sorgula",
+      "save": "Kaydet",
+      "sidebar": "Kenar çubuğunu göster veya gizle",
+      "help": "Klavye kısayollarını göster",
+      "newInspection": "Yeni muayene",
+      "calendar_day": "Gün görünümü",
+      "calendar_week": "Hafta görünümü",
+      "calendar_month": "Ay görünümü",
+      "calendar_year": "Yıl görünümü",
+      "calendar_schedule": "Program görünümü",
+      "calendar_fourDays": "4 gün görünümü",
+      "calendar_today": "Bugüne git",
+      "calendar_next": "Sonraki dönem",
+      "calendar_previous": "Önceki dönem"
+    },
+    "help": {
+      "title": "Klavye kısayolları",
+      "description": "Şu anki tuşlarınız. Ara her sayfayı açar. Tuşları Ayarlar'dan değiştirebilir veya kapatabilirsiniz.",
+      "disabledNote": "Klavye kısayolları kapalı. Ayarlar'dan açın.",
+      "find": "Kısayol bul",
+      "noMatch": "Eşleşen kısayol yok",
+      "customize": "Kısayolları değiştir",
+      "fixedHint": "her zaman aynı",
+      "listMove": "Listede gezin",
+      "listOpen": "Satırı aç",
+      "photos": "Sonraki veya önceki fotoğraf",
+      "close": "İletişim kutusunu veya menüyü kapat"
+    }
+  },
   "data": {
     "title": "Veri Yönetimi",
     "description": "Eski sisteminizden veri aktarın, her şeyin yedeğini indirin veya bir yedeği geri yükleyin.",

+ 0 - 1
messages/tr/vehicles.json

@@ -562,7 +562,6 @@
   },
   "plateLookup": {
     "open": "Plaka sorgula",
-    "shortcut": "Ctrl+Shift+L",
     "title": "Plaka sorgula",
     "description": "Atölyenizin ve araç sicilinin bir plaka hakkında bildiklerini görmek için plakayı yazın",
     "placeholder": "Bir plaka yazın",

+ 2 - 0
prisma/migrations/20261116081738_add_user_keyboard_shortcuts/migration.sql

@@ -0,0 +1,2 @@
+-- AlterTable
+ALTER TABLE "users" ADD COLUMN     "keyboardShortcuts" JSONB;

+ 4 - 0
prisma/schema/auth.prisma

@@ -35,6 +35,10 @@ model User {
   /// Per-user dashboard grid layout (card positions/sizes/hidden set).
   /// Null = default layout. Shape validated in dashboardLayoutActions.
   dashboardLayout     Json?
+  /// This person's keyboard shortcuts: only what differs from the defaults
+  /// in features/shortcuts/Lib/registry.ts. Null = every default as shipped.
+  /// Shape validated in features/shortcuts/Schema/preferences.ts.
+  keyboardShortcuts   Json?
 
   sessions                 Session[]
   portalMessages           PortalMessage[]

+ 128 - 0
src/__tests__/features/shortcuts/keys.test.ts

@@ -0,0 +1,128 @@
+import { describe, expect, it } from 'vitest'
+import {
+  comboParts,
+  combosFromEvent,
+  comboText,
+  isReservedCombo,
+} from '@/features/shortcuts/Lib/keys'
+
+type Press = Partial<
+  Pick<KeyboardEvent, 'key' | 'code' | 'ctrlKey' | 'metaKey' | 'altKey' | 'shiftKey'>
+> & { altGraph?: boolean }
+
+function press({ altGraph, ...init }: Press) {
+  return {
+    key: '',
+    code: '',
+    ctrlKey: false,
+    metaKey: false,
+    altKey: false,
+    shiftKey: false,
+    ...init,
+    getModifierState: (name: string) => name === 'AltGraph' && !!altGraph,
+  }
+}
+
+describe('reading a key press', () => {
+  it('reads Alt+W and Alt+Shift+W on Windows and Linux', () => {
+    expect(combosFromEvent(press({ key: 'w', altKey: true }), 'other')).toEqual(['alt+w'])
+    expect(combosFromEvent(press({ key: 'W', altKey: true, shiftKey: true }), 'other')).toEqual([
+      'alt+shift+w',
+    ])
+  })
+
+  it('reads Control as the Alt of a Mac, and still lets Ctrl+K mean search there', () => {
+    expect(combosFromEvent(press({ key: 'w', ctrlKey: true }), 'mac')).toEqual(['alt+w', 'mod+w'])
+    expect(combosFromEvent(press({ key: 'k', metaKey: true }), 'mac')).toEqual(['mod+k'])
+  })
+
+  it('never treats Option on a Mac as a shortcut, because it types characters', () => {
+    expect(combosFromEvent(press({ key: '∑', code: 'KeyW', altKey: true }), 'mac')).toEqual([])
+  })
+
+  it('ignores AltGr, which types @ and € on European keyboards', () => {
+    expect(
+      combosFromEvent(
+        press({ key: '@', code: 'KeyQ', ctrlKey: true, altKey: true, altGraph: true }),
+        'other'
+      )
+    ).toEqual([])
+    expect(combosFromEvent(press({ key: 'q', ctrlKey: true, altKey: true }), 'other')).toEqual([])
+  })
+
+  it('goes by the letter printed on the key, wherever the layout puts it', () => {
+    // AZERTY: the key printed W sits where a US keyboard has Z.
+    expect(combosFromEvent(press({ key: 'w', code: 'KeyZ', altKey: true }), 'other')).toEqual([
+      'alt+w',
+    ])
+  })
+
+  it('finds the slash whether it is its own key or Shift+7', () => {
+    const us = press({ key: '/', code: 'Slash', ctrlKey: true })
+    const norwegian = press({ key: '/', code: 'Digit7', ctrlKey: true, shiftKey: true })
+    expect(combosFromEvent(us, 'other')).toEqual(['mod+/'])
+    expect(combosFromEvent(norwegian, 'other')).toEqual(['mod+/'])
+  })
+
+  it('falls back to where the key sits on a keyboard with no Latin letters', () => {
+    expect(combosFromEvent(press({ key: 'ц', code: 'KeyW', altKey: true }), 'other')).toEqual([
+      'alt+w',
+    ])
+  })
+
+  it('makes nothing of a modifier pressed on its own', () => {
+    expect(combosFromEvent(press({ key: 'Alt', altKey: true }), 'other')).toEqual([])
+    expect(combosFromEvent(press({ key: 'Shift', shiftKey: true }), 'other')).toEqual([])
+  })
+
+  it('treats Caps Lock letters as the plain letter', () => {
+    expect(combosFromEvent(press({ key: 'D' }), 'other')).toEqual(['d'])
+  })
+})
+
+describe('showing a key', () => {
+  it('draws Ctrl and Alt on Windows and Linux', () => {
+    expect(comboParts('mod+shift+l', 'other')).toEqual(['Ctrl', 'Shift', 'L'])
+    expect(comboText('alt+w', 'other')).toBe('Alt+W')
+  })
+
+  it('draws Command and Control on a Mac', () => {
+    expect(comboParts('mod+k', 'mac')).toEqual(['⌘', 'K'])
+    expect(comboParts('alt+w', 'mac')).toEqual(['⌃', 'W'])
+    expect(comboParts('mod+shift+l', 'mac')).toEqual(['⌘', '⇧', 'L'])
+  })
+
+  it('draws arrows as arrows', () => {
+    expect(comboParts('arrowright', 'other')).toEqual(['→'])
+  })
+
+  it('reads a sequence as one key, then the next', () => {
+    expect(comboText('alt+g alt+w', 'other', 'then')).toBe('Alt+G then Alt+W')
+    expect(comboText('alt+g alt+w', 'mac', 'then')).toBe('⌃ G then ⌃ W')
+  })
+})
+
+describe('keys that cannot be taken', () => {
+  it.each([
+    'mod+w',
+    'mod+q',
+    'mod+n',
+    'mod+t',
+    'mod+c',
+    'alt+d',
+    'alt+f',
+    'alt+e',
+    'alt+v',
+    'alt+shift+w',
+    'alt+shift+k',
+    'tab',
+    'enter',
+    'escape',
+  ])('refuses %s', (combo) => {
+    expect(isReservedCombo(combo)).toBe(true)
+  })
+
+  it.each(['alt+w', 'alt+k', 'mod+k', 'mod+/', 'd', 'arrowright'])('allows %s', (combo) => {
+    expect(isReservedCombo(combo)).toBe(false)
+  })
+})

+ 387 - 0
src/__tests__/features/shortcuts/preferences.test.ts

@@ -0,0 +1,387 @@
+import { describe, expect, it } from 'vitest'
+import { hasModifier, isReservedCombo, parseCombo } from '@/features/shortcuts/Lib/keys'
+import {
+  activeKeys,
+  assignedKeys,
+  assignKey,
+  comboProblem,
+  DEFAULT_SHORTCUT_PREFS,
+  findClash,
+  isDefaultShortcutPrefs,
+  matchShortcut,
+  startsSequence,
+  normalizeShortcutPrefs,
+  resetKey,
+  setSwitchedOff,
+  type ShortcutPrefs,
+} from '@/features/shortcuts/Lib/preferences'
+import { SHORTCUTS, type ShortcutDef, shortcutById } from '@/features/shortcuts/Lib/registry'
+import { ACTION_COMMANDS, PAGE_COMMANDS } from '@/features/search/Lib/commands'
+
+const def = (id: string) => shortcutById(id) as ShortcutDef
+const everything = { typing: false, layerOpen: false, available: () => true }
+const match = (combo: string, over: Partial<Parameters<typeof matchShortcut>[1]> = {}) =>
+  matchShortcut([combo], { prefs: DEFAULT_SHORTCUT_PREFS, ...everything, ...over })?.id ?? null
+
+describe('the shortcut registry', () => {
+  it('names every shortcut once', () => {
+    const ids = SHORTCUTS.map((s) => s.id)
+    expect(new Set(ids).size).toBe(ids.length)
+  })
+
+  it('ships no two shortcuts on the same key', () => {
+    const seen = new Map<string, string>()
+    for (const shortcut of SHORTCUTS) {
+      for (const combo of [...shortcut.defaultKeys, ...(shortcut.fixedKeys ?? [])]) {
+        expect(
+          seen.get(combo),
+          `${combo} is on ${seen.get(combo)} and ${shortcut.id}`
+        ).toBeUndefined()
+        seen.set(combo, shortcut.id)
+      }
+    }
+  })
+
+  it('ships only keys a browser will hand over', () => {
+    for (const shortcut of SHORTCUTS) {
+      for (const combo of shortcut.defaultKeys) {
+        expect(parseCombo(combo), combo).not.toBeNull()
+        expect(isReservedCombo(combo), combo).toBe(false)
+      }
+    }
+  })
+
+  it('puts Ctrl or Alt on everything that works on every page', () => {
+    for (const shortcut of SHORTCUTS.filter((s) => s.scope === 'global')) {
+      for (const combo of shortcut.defaultKeys) expect(hasModifier(combo), combo).toBe(true)
+    }
+  })
+
+  it('keeps the keys people already knew', () => {
+    expect(def('general.search').defaultKeys).toEqual(['mod+k'])
+    expect(def('general.plateLookup').defaultKeys).toEqual(['mod+shift+l'])
+    expect(def('general.save').defaultKeys).toEqual(['mod+s'])
+    expect(def('general.sidebar').defaultKeys).toEqual(['mod+b'])
+    expect(def('calendar.week').defaultKeys).toEqual(['w'])
+    expect(activeKeys(def('calendar.next'), DEFAULT_SHORTCUT_PREFS)).toEqual([
+      'j',
+      'n',
+      'arrowright',
+    ])
+    expect(activeKeys(def('calendar.previous'), DEFAULT_SHORTCUT_PREFS)).toEqual([
+      'k',
+      'p',
+      'arrowleft',
+    ])
+  })
+
+  it('creates with Alt and the first letter', () => {
+    expect(def('create.workOrder').defaultKeys).toEqual(['alt+w'])
+    expect(def('create.quote').defaultKeys).toEqual(['alt+q'])
+    expect(def('create.customer').defaultKeys).toEqual(['alt+c'])
+    expect(def('create.part').defaultKeys).toEqual(['alt+p'])
+    expect(def('create.inspection').defaultKeys).toEqual(['alt+i'])
+  })
+
+  it('gives pages no single chord of their own: search and the go-to set open them', () => {
+    for (const shortcut of SHORTCUTS.filter((s) => s.group === 'goTo')) {
+      expect(shortcut.defaultKeys, shortcut.id).toEqual([])
+      expect(activeKeys(shortcut, DEFAULT_SHORTCUT_PREFS), shortcut.id).toEqual(
+        shortcut.sequence ? [shortcut.sequence] : []
+      )
+    }
+  })
+
+  it('points every page and create shortcut at a command the search palette has', () => {
+    const commands = new Map(
+      [...PAGE_COMMANDS, ...ACTION_COMMANDS].map((command) => [command.id, command.href])
+    )
+    for (const shortcut of SHORTCUTS.filter((s) => s.command)) {
+      expect(commands.get(shortcut.command as string), shortcut.id).toBe(shortcut.href)
+    }
+  })
+})
+
+describe('when a shortcut fires', () => {
+  it('fires a chord while typing in a field', () => {
+    expect(match('alt+w', { typing: true })).toBe('create.workOrder')
+    expect(match('mod+k', { typing: true })).toBe('general.search')
+  })
+
+  it('never fires a bare letter while typing', () => {
+    expect(match('w')).toBe('calendar.week')
+    expect(match('w', { typing: true })).toBeNull()
+    expect(match('arrowright', { typing: true })).toBeNull()
+  })
+
+  it('leaves an open dialog alone, except for search, save and the like', () => {
+    expect(match('alt+w', { layerOpen: true })).toBeNull()
+    expect(match('w', { layerOpen: true })).toBeNull()
+    expect(match('mod+k', { layerOpen: true })).toBe('general.search')
+  })
+
+  it('does nothing for a screen that is not there or a page this person cannot open', () => {
+    const available = (s: ShortcutDef) => s.id !== 'calendar.week' && s.id !== 'create.quote'
+    expect(match('w', { available })).toBeNull()
+    expect(match('alt+q', { available })).toBeNull()
+  })
+
+  it('does nothing at all once shortcuts are switched off', () => {
+    const prefs = { ...DEFAULT_SHORTCUT_PREFS, enabled: false }
+    expect(match('alt+w', { prefs })).toBeNull()
+    expect(match('mod+k', { prefs })).toBeNull()
+  })
+
+  it('drops the single letters, and only those, when single-letter keys are off', () => {
+    const prefs = { ...DEFAULT_SHORTCUT_PREFS, singleKeys: false }
+    expect(match('w', { prefs })).toBeNull()
+    expect(match('j', { prefs })).toBeNull()
+    expect(match('arrowright', { prefs })).toBe('calendar.next')
+    expect(match('alt+w', { prefs })).toBe('create.workOrder')
+  })
+
+  it('leaves out one shortcut that was switched off', () => {
+    const prefs = setSwitchedOff(def('create.quote'), true, DEFAULT_SHORTCUT_PREFS)
+    expect(match('alt+q', { prefs })).toBeNull()
+    expect(match('alt+w', { prefs })).toBe('create.workOrder')
+  })
+})
+
+describe('Alt+G, then Alt and a letter', () => {
+  const off = { ...DEFAULT_SHORTCUT_PREFS, goToSequences: false }
+
+  it('opens a page, and is on unless someone switched it off', () => {
+    expect(startsSequence('alt+g', { prefs: DEFAULT_SHORTCUT_PREFS, ...everything })).toBe(true)
+    expect(match('alt+g alt+w')).toBe('goTo.workOrders')
+    expect(match('alt+g alt+q')).toBe('goTo.quotes')
+    expect(match('alt+g alt+g')).toBe('goTo.dashboard')
+    expect(match('alt+g alt+w', { prefs: off })).toBeNull()
+    expect(startsSequence('alt+g', { prefs: off, ...everything })).toBe(false)
+  })
+
+  it('is never made of a bare letter, in either press', () => {
+    for (const shortcut of SHORTCUTS.filter((s) => s.sequence)) {
+      expect(shortcut.sequence, shortcut.id).toMatch(/^alt\+g alt\+[a-z]$/)
+    }
+    expect(match('g w')).toBeNull()
+    expect(match('alt+g w')).toBeNull()
+    expect(match('g alt+w')).toBeNull()
+    expect(startsSequence('g', { prefs: DEFAULT_SHORTCUT_PREFS, ...everything })).toBe(false)
+  })
+
+  it('works with the cursor in a field, like any other chord, but not over a dialog', () => {
+    expect(
+      startsSequence('alt+g', { prefs: DEFAULT_SHORTCUT_PREFS, ...everything, typing: true })
+    ).toBe(true)
+    expect(match('alt+g alt+w', { typing: true })).toBe('goTo.workOrders')
+    expect(
+      startsSequence('alt+g', { prefs: DEFAULT_SHORTCUT_PREFS, ...everything, layerOpen: true })
+    ).toBe(false)
+    expect(match('alt+g alt+w', { layerOpen: true })).toBeNull()
+  })
+
+  it('does not depend on the single-letter switch, having no single letters', () => {
+    const prefs = { ...DEFAULT_SHORTCUT_PREFS, singleKeys: false }
+    expect(match('alt+g alt+w', { prefs })).toBe('goTo.workOrders')
+  })
+
+  it('uses a different letter for every page, and the create letter for the same thing', () => {
+    const sequences = SHORTCUTS.flatMap((s) => (s.sequence ? [s.sequence] : []))
+    expect(new Set(sequences).size).toBe(sequences.length)
+    const letter = (id: string) => def(id).sequence?.slice(-1)
+    expect(letter('goTo.workOrders')).toBe(def('create.workOrder').defaultKeys[0].slice(-1))
+    expect(letter('goTo.quotes')).toBe(def('create.quote').defaultKeys[0].slice(-1))
+    expect(letter('goTo.customers')).toBe(def('create.customer').defaultKeys[0].slice(-1))
+    expect(letter('goTo.vehicles')).toBe(def('create.vehicle').defaultKeys[0].slice(-1))
+    expect(letter('goTo.inventory')).toBe(def('create.part').defaultKeys[0].slice(-1))
+    expect(letter('goTo.inspections')).toBe(def('create.inspection').defaultKeys[0].slice(-1))
+  })
+})
+
+/**
+ * What Windows and the browsers on it already do with a key, from their own
+ * lists (read 16 Nov 2026):
+ *   Windows: support.microsoft.com, "Keyboard shortcuts in Windows"
+ *   Edge:    support.microsoft.com, "Keyboard shortcuts in Microsoft Edge"
+ *   Chrome:  support.google.com/chrome/answer/157179
+ *   Firefox: the letters of its menu bar, which open a menu even when the
+ *            page has handled the key (bugzilla.mozilla.org 367510), and
+ *            bugzilla.mozilla.org 1962297 for Alt+Shift.
+ * A default added later that lands on one of these fails here.
+ */
+describe('defaults against Windows, Edge, Chrome and Firefox', () => {
+  const TAKEN: Record<string, string> = {
+    // Windows itself
+    'alt+tab': 'Windows: switch between windows',
+    'alt+escape': 'Windows: cycle through windows',
+    'alt+f4': 'Windows: close the window',
+    'alt+space': 'Windows: the window menu',
+    'alt+enter': 'Windows: properties; Chrome: search in a new tab',
+    'alt+printscreen': 'Windows: screenshot of the window',
+    'alt+pageup': 'Windows: move up one screen',
+    'alt+pagedown': 'Windows: move down one screen',
+    'alt+arrowleft': 'Windows and every browser: back',
+    'alt+arrowright': 'Windows and every browser: forward',
+    'alt+arrowup': 'File Explorer: up one level',
+    'alt+home': 'Edge, Chrome, Firefox: home page',
+    'alt+a': 'Windows 11: suggested actions',
+    // Edge and Chrome
+    'alt+d': 'Edge, Chrome, Firefox: the address bar',
+    'alt+e': 'Edge, Chrome: the browser menu; Firefox: Edit menu',
+    'alt+f': 'Edge, Chrome: the browser menu; Firefox: File menu',
+    // Firefox menu bar
+    'alt+v': 'Firefox: View menu',
+    'alt+s': 'Firefox: History menu',
+    'alt+b': 'Firefox: Bookmarks menu',
+    'alt+t': 'Firefox: Tools menu',
+    'alt+h': 'Firefox: Help menu',
+    // Ctrl chords no page can take, or that would break editing
+    'mod+w': 'close the tab',
+    'mod+t': 'new tab',
+    'mod+n': 'new window',
+    'mod+q': 'quit (Firefox on Linux)',
+    'mod+tab': 'next tab',
+    'mod+r': 'reload',
+    'mod+l': 'the address bar',
+    'mod+d': 'bookmark the page',
+    'mod+h': 'history',
+    'mod+j': 'downloads',
+    'mod+p': 'print',
+    'mod+f': 'find on the page',
+    'mod+c': 'copy',
+    'mod+v': 'paste',
+    'mod+x': 'cut',
+    'mod+a': 'select all',
+    'mod+z': 'undo',
+    'mod+y': 'redo',
+    'mod+shift+t': 'reopen the closed tab',
+    'mod+shift+n': 'private window',
+    'mod+shift+w': 'close the window',
+    'mod+shift+i': 'developer tools',
+    'mod+shift+delete': 'clear browsing data',
+  }
+
+  // Every press that ships: the single chords, and both halves of each
+  // go-to sequence (Alt+G, then Alt and the letter).
+  const defaults = SHORTCUTS.flatMap((s) =>
+    [...s.defaultKeys, ...(s.fixedKeys ?? []), ...(s.sequence?.split(' ') ?? [])].map((combo) => ({
+      id: s.id,
+      combo,
+    }))
+  )
+
+  it.each(defaults)('$id on $combo is not a Windows or browser key', ({ combo }) => {
+    expect(TAKEN[combo]).toBeUndefined()
+  })
+
+  it.each(defaults)('$id on $combo has no Alt+Shift, AltGr or Windows key', ({ combo }) => {
+    const parsed = parseCombo(combo)
+    expect(parsed).not.toBeNull()
+    // Alt+Shift switches the keyboard language on Windows.
+    expect(parsed?.alt && parsed?.shift).toBeFalsy()
+    // Ctrl+Alt is AltGr on European keyboards.
+    expect(parsed?.mod && parsed?.alt).toBeFalsy()
+    expect(combo).not.toMatch(/meta|win|os\+/)
+  })
+
+  it('refuses every one of those keys when a person tries to record it', () => {
+    for (const combo of Object.keys(TAKEN)) expect(isReservedCombo(combo), combo).toBe(true)
+  })
+
+  it('keeps only the Ctrl chords the app already had, which browsers let a page take', () => {
+    const ctrl = defaults.filter(({ combo }) => combo.startsWith('mod+')).map(({ combo }) => combo)
+    expect([...new Set(ctrl)].sort()).toEqual(['mod+/', 'mod+b', 'mod+k', 'mod+s', 'mod+shift+l'])
+  })
+})
+
+describe('changing a key', () => {
+  it('fires on the new key and no longer on the old one', () => {
+    const prefs = assignKey(def('create.workOrder'), 'alt+n', DEFAULT_SHORTCUT_PREFS)
+    expect(match('alt+n', { prefs })).toBe('create.workOrder')
+    expect(match('alt+w', { prefs })).toBeNull()
+  })
+
+  it('names the shortcut that already holds a key', () => {
+    expect(findClash(def('create.quote'), 'alt+w', DEFAULT_SHORTCUT_PREFS)?.id).toBe(
+      'create.workOrder'
+    )
+    expect(findClash(def('create.quote'), 'alt+z', DEFAULT_SHORTCUT_PREFS)).toBeNull()
+  })
+
+  it('sees a clash with a key on another screen, and with a fixed one', () => {
+    expect(findClash(def('calendar.today'), 'w', DEFAULT_SHORTCUT_PREFS)?.id).toBe('calendar.week')
+    expect(findClash(def('calendar.today'), 'arrowright', DEFAULT_SHORTCUT_PREFS)?.id).toBe(
+      'calendar.next'
+    )
+  })
+
+  it('takes the key from the shortcut that had it', () => {
+    const prefs = assignKey(def('create.quote'), 'alt+w', DEFAULT_SHORTCUT_PREFS)
+    expect(assignedKeys(def('create.quote'), prefs)).toEqual(['alt+w'])
+    expect(assignedKeys(def('create.workOrder'), prefs)).toEqual([])
+    expect(match('alt+w', { prefs })).toBe('create.quote')
+  })
+
+  it('leaves the second key when one of two is taken', () => {
+    const prefs = assignKey(def('calendar.today'), 'j', DEFAULT_SHORTCUT_PREFS)
+    expect(assignedKeys(def('calendar.next'), prefs)).toEqual(['n'])
+  })
+
+  it('goes back to the shipped key on reset', () => {
+    const changed = assignKey(def('create.workOrder'), 'alt+n', DEFAULT_SHORTCUT_PREFS)
+    const prefs = resetKey(def('create.workOrder'), changed)
+    expect(assignedKeys(def('create.workOrder'), prefs)).toEqual(['alt+w'])
+    expect(isDefaultShortcutPrefs(prefs)).toBe(true)
+  })
+
+  it('refuses a browser key, and a bare letter for something that works everywhere', () => {
+    expect(comboProblem(def('create.workOrder'), 'mod+w')).toBe('reserved')
+    expect(comboProblem(def('create.workOrder'), 'w')).toBe('needsModifier')
+    expect(comboProblem(def('calendar.week'), 'v')).toBeNull()
+    expect(comboProblem(def('create.workOrder'), 'alt+n')).toBeNull()
+  })
+
+  it('refuses the first press of the go-to set, which would leave every page key dead', () => {
+    expect(comboProblem(def('create.quote'), 'alt+g')).toBe('taken')
+    expect(normalizeShortcutPrefs({ overrides: { 'create.quote': 'alt+g' } }).overrides).toEqual({})
+  })
+
+  it('refuses a key that is fixed to another shortcut and cannot be taken from it', () => {
+    expect(comboProblem(def('calendar.previous'), 'arrowright')).toBe('taken')
+    expect(comboProblem(def('calendar.next'), 'arrowright')).toBeNull()
+  })
+})
+
+describe('reading stored preferences', () => {
+  it('reads nothing as every default', () => {
+    expect(normalizeShortcutPrefs(null)).toEqual(DEFAULT_SHORTCUT_PREFS)
+    expect(normalizeShortcutPrefs('nonsense')).toEqual(DEFAULT_SHORTCUT_PREFS)
+  })
+
+  it('drops shortcuts that no longer exist and keys that could never work', () => {
+    const prefs = normalizeShortcutPrefs({
+      enabled: true,
+      singleKeys: false,
+      overrides: {
+        'create.workOrder': 'alt+n',
+        'create.quote': 'mod+w',
+        'create.customer': 'c',
+        'gone.shortcut': 'alt+x',
+        'create.part': 42,
+      },
+      disabled: ['create.vehicle', 'gone.shortcut', 'create.vehicle'],
+    } as unknown as ShortcutPrefs)
+    expect(prefs).toEqual({
+      enabled: true,
+      singleKeys: false,
+      goToSequences: true,
+      overrides: { 'create.workOrder': 'alt+n' },
+      disabled: ['create.vehicle'],
+    })
+  })
+
+  it('keeps a shortcut that was left without a key', () => {
+    const prefs = normalizeShortcutPrefs({ overrides: { 'create.workOrder': '' } })
+    expect(assignedKeys(def('create.workOrder'), prefs)).toEqual([])
+  })
+})

+ 526 - 0
src/__tests__/features/shortcuts/shortcuts-provider.test.tsx

@@ -0,0 +1,526 @@
+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { ConfirmProvider } from '@/components/confirm-dialog'
+import { ShortcutKeys } from '@/features/shortcuts/Components/ShortcutKeys'
+import { ShortcutsProvider, useShortcut } from '@/features/shortcuts/Components/ShortcutsProvider'
+import { ShortcutsSettings } from '@/features/shortcuts/Components/ShortcutsSettings'
+
+const push = vi.fn()
+vi.mock('next/navigation', () => ({
+  useRouter: () => ({ push, replace: vi.fn(), refresh: vi.fn(), prefetch: vi.fn() }),
+  usePathname: () => '/',
+  useSearchParams: () => new URLSearchParams(),
+}))
+
+const save = vi.fn(async (input: unknown) => ({ success: true, data: input }))
+vi.mock('@/features/shortcuts/Actions/saveKeyboardShortcuts', () => ({
+  saveKeyboardShortcuts: (input: unknown) => save(input),
+}))
+
+const everyone = { isAdminOrOwner: true }
+
+function Calendar({ onWeek }: { onWeek: () => void }) {
+  useShortcut('calendar.week', onWeek)
+  return null
+}
+
+function App({
+  prefs = null,
+  commands = everyone,
+  children,
+}: {
+  prefs?: unknown
+  commands?: Parameters<typeof ShortcutsProvider>[0]['commands']
+  children?: React.ReactNode
+}) {
+  return (
+    <ConfirmProvider>
+      <ShortcutsProvider initialPrefs={prefs} commands={commands} plateLookupAvailable={false}>
+        {children}
+      </ShortcutsProvider>
+    </ConfirmProvider>
+  )
+}
+
+function press(init: KeyboardEventInit, target: Element = document.body) {
+  const event = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init })
+  act(() => {
+    target.dispatchEvent(event)
+  })
+  return event
+}
+
+/** Real time passing: bare keys are held back a moment, and wait after typing. */
+const pause = (ms: number) => act(() => new Promise<void>((resolve) => setTimeout(resolve, ms)))
+
+beforeEach(() => {
+  push.mockClear()
+  save.mockClear()
+})
+
+describe('keyboard shortcuts in the app', () => {
+  it('opens a new work order on Alt+W', () => {
+    render(<App />)
+    const event = press({ key: 'w', altKey: true })
+    expect(push).toHaveBeenCalledWith('/work-orders?new=1')
+    expect(event.defaultPrevented).toBe(true)
+  })
+
+  it('does nothing on Alt+Shift+W, which belongs to Windows', () => {
+    render(<App />)
+    const event = press({ key: 'W', altKey: true, shiftKey: true })
+    expect(push).not.toHaveBeenCalled()
+    expect(event.defaultPrevented).toBe(false)
+  })
+
+  it('opens the work order list on Alt+G then Alt+W, and a new work order on Alt+W alone', () => {
+    render(<App />)
+    const first = press({ key: 'g', altKey: true })
+    expect(first.defaultPrevented).toBe(true)
+    press({ key: 'w', altKey: true })
+    expect(push).toHaveBeenLastCalledWith('/work-orders')
+
+    // The sequence is spent: the same key on its own creates again.
+    press({ key: 'w', altKey: true })
+    expect(push).toHaveBeenLastCalledWith('/work-orders?new=1')
+    expect(push).toHaveBeenCalledTimes(2)
+  })
+
+  it('still works when Alt is let go between the two presses', () => {
+    render(<App />)
+    press({ key: 'Alt', altKey: true })
+    press({ key: 'g', altKey: true })
+    press({ key: 'Alt', altKey: true })
+    press({ key: 'q', altKey: true })
+    expect(push).toHaveBeenCalledWith('/quotes')
+  })
+
+  it('goes back to creating once the moment after Alt+G has passed', () => {
+    vi.useFakeTimers({ toFake: ['Date'] })
+    try {
+      render(<App />)
+      press({ key: 'g', altKey: true })
+      vi.advanceTimersByTime(1400)
+      press({ key: 'w', altKey: true })
+      expect(push).toHaveBeenLastCalledWith('/work-orders')
+
+      press({ key: 'g', altKey: true })
+      vi.advanceTimersByTime(1600)
+      press({ key: 'w', altKey: true })
+      expect(push).toHaveBeenLastCalledWith('/work-orders?new=1')
+    } finally {
+      vi.useRealTimers()
+    }
+  })
+
+  it('takes a bare letter after Alt+G for what it is, and forgets the Alt+G', () => {
+    render(
+      <App>
+        <input aria-label="Name" />
+      </App>
+    )
+    press({ key: 'g', altKey: true })
+    const typed = press({ key: 'w' }, screen.getByLabelText('Name'))
+    expect(typed.defaultPrevented).toBe(false)
+    expect(push).not.toHaveBeenCalled()
+    press({ key: 'w', altKey: true })
+    expect(push).toHaveBeenLastCalledWith('/work-orders?new=1')
+  })
+
+  it('never opens a page on bare letters, however they are pressed', async () => {
+    render(<App />)
+    for (const keys of ['gw', 'gq', 'gg', 'gk']) {
+      for (const key of keys) {
+        press({ key })
+        await pause(70)
+      }
+    }
+    expect(push).not.toHaveBeenCalled()
+  })
+
+  it('leaves the go-to set alone once it is switched off', () => {
+    render(<App prefs={{ goToSequences: false }} />)
+    const first = press({ key: 'g', altKey: true })
+    expect(first.defaultPrevented).toBe(false)
+    press({ key: 'w', altKey: true })
+    expect(push).toHaveBeenLastCalledWith('/work-orders?new=1')
+  })
+
+  it('is held back by a page that saves before it lets a link through', () => {
+    // What the work order page does while a job has unsaved changes: it
+    // catches the click on a link, saves, and then lets that click through.
+    let held: HTMLAnchorElement | null = null
+    const guard = (event: MouseEvent) => {
+      const anchor = (event.target as Element).closest('a[href]')
+      if (!(anchor instanceof HTMLAnchorElement) || held === anchor) return
+      event.preventDefault()
+      event.stopPropagation()
+      held = anchor
+    }
+    document.addEventListener('click', guard, true)
+    try {
+      render(<App />)
+      press({ key: 'g', altKey: true })
+      press({ key: 'q', altKey: true })
+      expect(push).not.toHaveBeenCalled()
+      expect(held).not.toBeNull()
+
+      // Saved: the page releases the click it was holding.
+      act(() => (held as unknown as HTMLAnchorElement).click())
+      expect(push).toHaveBeenCalledWith('/quotes')
+    } finally {
+      document.removeEventListener('click', guard, true)
+    }
+  })
+
+  it('draws a sequence that repeats a key without React complaining about it', () => {
+    const errors = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+    try {
+      render(
+        <App>
+          <span data-testid="hint">
+            <ShortcutKeys id="goTo.dashboard" />
+          </span>
+        </App>
+      )
+      expect(screen.getByTestId('hint')).toHaveTextContent('AltGthenAltG')
+      expect(errors).not.toHaveBeenCalled()
+    } finally {
+      errors.mockRestore()
+    }
+  })
+
+  it('opens a new quote on Alt+Q', () => {
+    render(<App />)
+    press({ key: 'q', altKey: true })
+    expect(push).toHaveBeenCalledWith('/quotes?create=true')
+  })
+
+  it('works with the cursor in a field, because Alt+W types nothing', () => {
+    render(
+      <App>
+        <input aria-label="Name" />
+      </App>
+    )
+    press({ key: 'w', altKey: true }, screen.getByLabelText('Name'))
+    expect(push).toHaveBeenCalledWith('/work-orders?new=1')
+  })
+
+  it('keeps a letter typed in a field out of the calendar', async () => {
+    const onWeek = vi.fn()
+    render(
+      <App>
+        <Calendar onWeek={onWeek} />
+        <input aria-label="Title" />
+        <textarea aria-label="Notes" />
+        <div contentEditable aria-label="Message" />
+      </App>
+    )
+    for (const label of ['Title', 'Notes', 'Message']) {
+      const event = press({ key: 'w' }, screen.getByLabelText(label))
+      expect(event.defaultPrevented).toBe(false)
+    }
+    expect(onWeek).not.toHaveBeenCalled()
+
+    await pause(600)
+    press({ key: 'w' })
+    await pause(70)
+    expect(onWeek).toHaveBeenCalledTimes(1)
+  })
+
+  it('does not answer the calendar letters on any other screen', () => {
+    render(<App />)
+    const event = press({ key: 'w' })
+    expect(event.defaultPrevented).toBe(false)
+    expect(push).not.toHaveBeenCalled()
+  })
+
+  it('stays quiet while a dialog is open', () => {
+    const onWeek = vi.fn()
+    render(
+      <App>
+        <Calendar onWeek={onWeek} />
+        <div role="dialog" data-state="open">
+          <button type="button">Confirm</button>
+        </div>
+      </App>
+    )
+    press({ key: 'w', altKey: true })
+    press({ key: 'w' })
+    press({ key: 'w' }, screen.getByText('Confirm'))
+    expect(push).not.toHaveBeenCalled()
+    expect(onWeek).not.toHaveBeenCalled()
+  })
+
+  it('has no shortcut for a page this person cannot open', () => {
+    render(<App commands={{ visibleSubjects: ['work_orders'] }} />)
+    press({ key: 'q', altKey: true })
+    expect(push).not.toHaveBeenCalled()
+    press({ key: 'w', altKey: true })
+    expect(push).toHaveBeenCalledWith('/work-orders?new=1')
+  })
+
+  it('uses the key this person chose, everywhere it is shown', () => {
+    render(
+      <App prefs={{ overrides: { 'create.workOrder': 'alt+n' } }}>
+        <span data-testid="hint">
+          <ShortcutKeys id="create.workOrder" />
+        </span>
+      </App>
+    )
+    expect(screen.getByTestId('hint')).toHaveTextContent('AltN')
+    press({ key: 'w', altKey: true })
+    expect(push).not.toHaveBeenCalled()
+    press({ key: 'n', altKey: true })
+    expect(push).toHaveBeenCalledWith('/work-orders?new=1')
+  })
+
+  it('opens the list of shortcuts on Ctrl+/ with the keys this person has', async () => {
+    render(<App prefs={{ overrides: { 'create.quote': 'alt+z' } }} />)
+    press({ key: '/', ctrlKey: true })
+    const dialog = await screen.findByRole('dialog', { name: 'Keyboard shortcuts' })
+    const quote = within(dialog).getByText('New quote').closest('div') as HTMLElement
+    expect(quote).toHaveTextContent('AltZ')
+    expect(within(dialog).getByText('Week view')).toBeInTheDocument()
+    expect(within(dialog).getByRole('link', { name: 'Change shortcuts' })).toHaveAttribute(
+      'href',
+      '/settings/shortcuts'
+    )
+  })
+  it('offers no way to the settings page to someone who is turned away from it', async () => {
+    render(<App commands={{ visibleSubjects: ['work_orders'] }} />)
+    press({ key: '/', ctrlKey: true })
+    const dialog = await screen.findByRole('dialog', { name: 'Keyboard shortcuts' })
+    expect(within(dialog).getByText('New work order')).toBeInTheDocument()
+    expect(within(dialog).queryByRole('link', { name: 'Change shortcuts' })).toBeNull()
+  })
+})
+
+describe('the Keyboard shortcuts settings page', () => {
+  const row = (name: string) => screen.getByText(name).closest('li') as HTMLElement
+
+  it('keeps everything it hides for screen readers inside its own box', () => {
+    // A visually hidden element is absolutely positioned. Left without a
+    // positioned ancestor inside the page it is laid out against the whole
+    // document, below the window, and the settings page starts to scroll as
+    // one (seen in the browser; e2e/specs/shortcuts measures the real page).
+    render(
+      <App>
+        <ShortcutsSettings />
+      </App>
+    )
+    const root = screen.getByTestId('shortcuts-settings')
+    const hidden = Array.from(document.querySelectorAll('.sr-only'))
+    expect(hidden.length).toBeGreaterThan(0)
+    for (const element of hidden) {
+      expect(root.contains(element)).toBe(true)
+      let anchored = false
+      for (let node = element.parentElement; node; node = node.parentElement) {
+        if (/(^|\s)(relative|absolute|fixed|sticky)(\s|$)/.test(node.className)) anchored = true
+        if (node === root) break
+      }
+      expect(anchored).toBe(true)
+    }
+  })
+
+  it('records a new key, shows it and saves it', async () => {
+    render(
+      <App>
+        <ShortcutsSettings />
+      </App>
+    )
+    fireEvent.click(screen.getByRole('button', { name: 'Change the shortcut for New quote' }))
+    const recorder = screen.getByRole('button', { name: /Recording a new shortcut for New quote/ })
+    expect(recorder).toHaveFocus()
+    fireEvent.keyDown(recorder, { key: 'z', altKey: true })
+
+    expect(row('New quote')).toHaveTextContent('AltZ')
+    expect(row('New quote')).toHaveTextContent('Changed')
+    await waitFor(() =>
+      expect(save).toHaveBeenCalledWith(
+        expect.objectContaining({ overrides: { 'create.quote': 'alt+z' } })
+      )
+    )
+    // The key being recorded did not also run as the shortcut it used to be.
+    expect(push).not.toHaveBeenCalled()
+
+    press({ key: 'z', altKey: true })
+    expect(push).toHaveBeenCalledWith('/quotes?create=true')
+  })
+
+  it('says who has the key already and lets the person take it', async () => {
+    render(
+      <App>
+        <ShortcutsSettings />
+      </App>
+    )
+    fireEvent.click(screen.getByRole('button', { name: 'Change the shortcut for New quote' }))
+    fireEvent.keyDown(screen.getByRole('button', { name: /Recording/ }), { key: 'w', altKey: true })
+
+    expect(screen.getByRole('alert')).toHaveTextContent(
+      'Alt+W already belongs to New work order. Use it here and that one is left without it.'
+    )
+    expect(save).not.toHaveBeenCalled()
+
+    fireEvent.click(screen.getByRole('button', { name: 'Use it here' }))
+    expect(row('New quote')).toHaveTextContent('AltW')
+    expect(row('New work order')).toHaveTextContent('No key')
+    await waitFor(() =>
+      expect(save).toHaveBeenCalledWith(
+        expect.objectContaining({
+          overrides: { 'create.quote': 'alt+w', 'create.workOrder': '' },
+        })
+      )
+    )
+  })
+
+  it('refuses a key the browser keeps, and a bare letter for a shortcut that works everywhere', () => {
+    render(
+      <App>
+        <ShortcutsSettings />
+      </App>
+    )
+    fireEvent.click(screen.getByRole('button', { name: 'Change the shortcut for New quote' }))
+    const recorder = screen.getByRole('button', { name: /Recording/ })
+    fireEvent.keyDown(recorder, { key: 'w', ctrlKey: true })
+    expect(screen.getByRole('alert')).toHaveTextContent(
+      'Ctrl+W belongs to the browser or the system and cannot be used.'
+    )
+    fireEvent.keyDown(recorder, { key: 'q' })
+    expect(screen.getByRole('alert')).toHaveTextContent(
+      'it needs Ctrl or Alt together with the key'
+    )
+    expect(save).not.toHaveBeenCalled()
+  })
+
+  it('cancels on Escape and leaves the key as it was', () => {
+    render(
+      <App>
+        <ShortcutsSettings />
+      </App>
+    )
+    fireEvent.click(screen.getByRole('button', { name: 'Change the shortcut for New quote' }))
+    fireEvent.keyDown(screen.getByRole('button', { name: /Recording/ }), { key: 'Escape' })
+    expect(screen.queryByRole('button', { name: /Recording/ })).not.toBeInTheDocument()
+    expect(row('New quote')).toHaveTextContent('AltQ')
+    expect(save).not.toHaveBeenCalled()
+  })
+
+  it('switches one shortcut off', async () => {
+    render(
+      <App>
+        <ShortcutsSettings />
+      </App>
+    )
+    fireEvent.click(screen.getByRole('switch', { name: 'Shortcut for New quote' }))
+    await waitFor(() =>
+      expect(save).toHaveBeenCalledWith(expect.objectContaining({ disabled: ['create.quote'] }))
+    )
+    press({ key: 'q', altKey: true })
+    expect(push).not.toHaveBeenCalled()
+  })
+
+  it('switches the single-letter keys off without touching the rest', () => {
+    const onWeek = vi.fn()
+    render(
+      <App>
+        <Calendar onWeek={onWeek} />
+        <ShortcutsSettings />
+      </App>
+    )
+    fireEvent.click(screen.getByRole('switch', { name: 'Single-letter keys' }))
+    press({ key: 'w' })
+    expect(onWeek).not.toHaveBeenCalled()
+    press({ key: 'w', altKey: true })
+    expect(push).toHaveBeenCalledWith('/work-orders?new=1')
+  })
+
+  it('resets one shortcut, and all of them after asking', async () => {
+    render(
+      <App prefs={{ overrides: { 'create.quote': 'alt+z' }, disabled: ['create.part'] }}>
+        <ShortcutsSettings />
+      </App>
+    )
+    fireEvent.click(screen.getByRole('button', { name: 'Reset the shortcut for New quote' }))
+    expect(row('New quote')).toHaveTextContent('AltQ')
+
+    fireEvent.click(screen.getByRole('button', { name: 'Reset all to default' }))
+    const dialog = await screen.findByRole('alertdialog')
+    fireEvent.click(within(dialog).getByRole('button', { name: 'Reset all to default' }))
+    await waitFor(() =>
+      expect(save).toHaveBeenLastCalledWith(
+        expect.objectContaining({ overrides: {}, disabled: [] })
+      )
+    )
+    expect(screen.getByRole('switch', { name: 'Shortcut for New part' })).toBeChecked()
+  })
+
+  it('leaves the keyboard to a confirmation while it is asking', async () => {
+    const onWeek = vi.fn()
+    render(
+      <App prefs={{ overrides: { 'create.quote': 'alt+z' } }}>
+        <Calendar onWeek={onWeek} />
+        <ShortcutsSettings />
+      </App>
+    )
+    fireEvent.click(screen.getByRole('button', { name: 'Reset all to default' }))
+    const dialog = await screen.findByRole('alertdialog')
+    const focused = (document.activeElement ?? dialog) as HTMLElement
+    press({ key: 'w', altKey: true }, focused)
+    press({ key: 'g', altKey: true }, focused)
+    press({ key: 'w', altKey: true }, focused)
+    press({ key: 'w' }, focused)
+    expect(push).not.toHaveBeenCalled()
+    expect(onWeek).not.toHaveBeenCalled()
+
+    // Escape is the dialog's own key and still answers no.
+    fireEvent.keyDown(focused, { key: 'Escape' })
+    await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull())
+    expect(save).not.toHaveBeenCalled()
+    expect(row('New quote')).toHaveTextContent('AltZ')
+  })
+
+  it('refuses the key that starts the go-to set, and a key fixed to another shortcut', () => {
+    render(
+      <App>
+        <ShortcutsSettings />
+      </App>
+    )
+    fireEvent.click(screen.getByRole('button', { name: 'Change the shortcut for New quote' }))
+    fireEvent.keyDown(screen.getByRole('button', { name: /Recording/ }), { key: 'g', altKey: true })
+    expect(screen.getByRole('alert')).toHaveTextContent(
+      'Alt+G is fixed to another shortcut and cannot be moved.'
+    )
+    expect(screen.queryByRole('button', { name: 'Use it here' })).toBeNull()
+    expect(save).not.toHaveBeenCalled()
+  })
+
+  it('keeps a later choice when an earlier save fails behind it', async () => {
+    save.mockResolvedValueOnce({ success: false, data: null })
+    render(
+      <App>
+        <ShortcutsSettings />
+      </App>
+    )
+    fireEvent.click(screen.getByRole('button', { name: 'Change the shortcut for New quote' }))
+    fireEvent.keyDown(screen.getByRole('button', { name: /Recording/ }), { key: 'z', altKey: true })
+    // Before the first save has answered.
+    fireEvent.click(screen.getByRole('switch', { name: 'Single-letter keys' }))
+    await waitFor(() => expect(save).toHaveBeenCalledTimes(2))
+    await pause(20)
+    expect(screen.getByRole('switch', { name: 'Single-letter keys' })).not.toBeChecked()
+    expect(row('New quote')).toHaveTextContent('AltZ')
+  })
+
+  it('puts the old key back when saving fails', async () => {
+    save.mockResolvedValueOnce({ success: false, data: null })
+    render(
+      <App>
+        <ShortcutsSettings />
+      </App>
+    )
+    fireEvent.click(screen.getByRole('button', { name: 'Change the shortcut for New quote' }))
+    fireEvent.keyDown(screen.getByRole('button', { name: /Recording/ }), { key: 'z', altKey: true })
+    await waitFor(() => expect(row('New quote')).toHaveTextContent('AltQ'))
+  })
+})

+ 842 - 0
src/__tests__/features/shortcuts/typing-safety.test.tsx

@@ -0,0 +1,842 @@
+import { act, fireEvent, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { TagInput } from '@/components/tag-input'
+import {
+  AlertDialog,
+  AlertDialogContent,
+  AlertDialogDescription,
+  AlertDialogTitle,
+} from '@/components/ui/alert-dialog'
+import { Command, CommandInput, CommandItem, CommandList } from '@/components/ui/command'
+import {
+  ContextMenu,
+  ContextMenuContent,
+  ContextMenuItem,
+  ContextMenuTrigger,
+} from '@/components/ui/context-menu'
+import { DateInput } from '@/components/ui/date-input'
+import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog'
+import { Drawer, DrawerContent, DrawerDescription, DrawerTitle } from '@/components/ui/drawer'
+import {
+  DropdownMenu,
+  DropdownMenuContent,
+  DropdownMenuItem,
+  DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu'
+import { Input } from '@/components/ui/input'
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
+import { RichTextEditor } from '@/components/ui/rich-text-editor'
+import { SearchableSelect } from '@/components/ui/searchable-select'
+import {
+  Select,
+  SelectContent,
+  SelectItem,
+  SelectTrigger,
+  SelectValue,
+} from '@/components/ui/select'
+import { Sheet, SheetContent, SheetDescription, SheetTitle } from '@/components/ui/sheet'
+import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
+import { Textarea } from '@/components/ui/textarea'
+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
+import { ShortcutsProvider, useShortcut } from '@/features/shortcuts/Components/ShortcutsProvider'
+
+/**
+ * The promise these tests hold the app to: with every bare-key shortcut
+ * switched on (only the calendar has them now: the go-to set is Alt+G, then
+ * Alt and a letter, and so can never be typed), nothing
+ * a person types into the app, and nothing typed while a dialog or a menu is
+ * open, ever runs a shortcut. Each test types into the real component, at a
+ * person's pace, and checks that the text arrived and the page stayed put.
+ */
+
+const push = vi.fn()
+vi.mock('next/navigation', () => ({
+  useRouter: () => ({ push, replace: vi.fn(), refresh: vi.fn(), prefetch: vi.fn() }),
+  usePathname: () => '/calendar',
+  useSearchParams: () => new URLSearchParams(),
+}))
+vi.mock('@/features/shortcuts/Actions/saveKeyboardShortcuts', () => ({
+  saveKeyboardShortcuts: vi.fn(async (input: unknown) => ({ success: true, data: input })),
+}))
+
+// What jsdom leaves out and Radix and cmdk reach for.
+class ResizeObserverStub {
+  observe() {
+    return undefined
+  }
+  unobserve() {
+    return undefined
+  }
+  disconnect() {
+    return undefined
+  }
+}
+globalThis.ResizeObserver ??= ResizeObserverStub as unknown as typeof ResizeObserver
+Element.prototype.hasPointerCapture ??= () => false
+Element.prototype.setPointerCapture ??= () => undefined
+Element.prototype.releasePointerCapture ??= () => undefined
+Element.prototype.scrollIntoView ??= () => undefined
+
+const calendar = vi.fn()
+
+/** Every calendar letter claimed, as on the calendar page. */
+function CalendarKeys() {
+  useShortcut('calendar.day', () => calendar('day'))
+  useShortcut('calendar.week', () => calendar('week'))
+  useShortcut('calendar.month', () => calendar('month'))
+  useShortcut('calendar.year', () => calendar('year'))
+  useShortcut('calendar.schedule', () => calendar('schedule'))
+  useShortcut('calendar.fourDays', () => calendar('fourDays'))
+  useShortcut('calendar.today', () => calendar('today'))
+  useShortcut('calendar.next', () => calendar('next'))
+  useShortcut('calendar.previous', () => calendar('previous'))
+  return null
+}
+
+function App({ children }: { children?: React.ReactNode }) {
+  return (
+    <ShortcutsProvider
+      initialPrefs={{ goToSequences: true }}
+      commands={{ isAdminOrOwner: true }}
+      plateLookupAvailable={false}
+    >
+      <CalendarKeys />
+      {children}
+    </ShortcutsProvider>
+  )
+}
+
+/** A person's pace: comfortably slower than a scanner, faster than the sequence window. */
+const HUMAN = 70
+const wait = (ms: number) => act(() => new Promise<void>((resolve) => setTimeout(resolve, ms)))
+
+/** Every letter a bare-key shortcut uses, in words a person might type. */
+const SENTENCE = 'gw gq gd gc dwmyax tjnkp'
+
+function nothingFired() {
+  expect(push).not.toHaveBeenCalled()
+  expect(calendar).not.toHaveBeenCalled()
+}
+
+/** Presses bare keys on an element at a person's pace, without typing them. */
+async function pressKeys(target: Element, keys: string) {
+  const events: KeyboardEvent[] = []
+  for (const key of keys) {
+    const event = new KeyboardEvent('keydown', {
+      key: key === ' ' ? ' ' : key,
+      bubbles: true,
+      cancelable: true,
+      composed: true,
+    })
+    act(() => {
+      target.dispatchEvent(event)
+    })
+    events.push(event)
+    await wait(HUMAN)
+  }
+  return events
+}
+
+/** The same, with Alt held: the go-to set and the create chords. */
+async function pressAlt(target: Element, keys: string) {
+  for (const key of keys) {
+    act(() => {
+      target.dispatchEvent(
+        new KeyboardEvent('keydown', { key, altKey: true, bubbles: true, cancelable: true })
+      )
+    })
+    await wait(HUMAN)
+  }
+}
+
+beforeEach(async () => {
+  push.mockClear()
+  calendar.mockClear()
+  // Past the quiet gap the previous test's typing left behind.
+  await wait(10)
+})
+
+describe('the tests can tell a shortcut from no shortcut', () => {
+  it('switches the calendar on a bare letter with the focus on the page', async () => {
+    render(<App />)
+    await pressKeys(document.body, 'm')
+    expect(calendar).toHaveBeenCalledWith('month')
+  })
+
+  it('still works with the focus resting on a button, which uses no letters', async () => {
+    render(
+      <App>
+        <button type="button">Today</button>
+      </App>
+    )
+    screen.getByText('Today').focus()
+    await pressKeys(screen.getByText('Today'), 'w')
+    expect(calendar).toHaveBeenCalledWith('week')
+  })
+
+  it('opens a page on Alt+G then Alt+W, and never on the bare letters', async () => {
+    render(<App />)
+    await pressKeys(document.body, 'gw gq gg')
+    expect(push).not.toHaveBeenCalled()
+    await pressAlt(document.body, 'gw')
+    expect(push).toHaveBeenCalledWith('/work-orders')
+  })
+})
+
+describe('typing into a field never runs a shortcut', () => {
+  it.each([
+    'text',
+    'search',
+    'email',
+    'tel',
+    'url',
+    'password',
+  ])('a %s input keeps every letter', async (type) => {
+    const user = userEvent.setup({ delay: HUMAN })
+    render(
+      <App>
+        <Input type={type} aria-label="Field" />
+      </App>
+    )
+    const field = screen.getByLabelText('Field')
+    await user.click(field)
+    await user.keyboard(SENTENCE)
+    expect(field).toHaveValue(SENTENCE)
+    nothingFired()
+  })
+
+  it.each([
+    'number',
+    'date',
+    'time',
+    'datetime-local',
+    'month',
+    'checkbox',
+    'radio',
+    'range',
+  ])('a %s input is left alone', async (type) => {
+    render(
+      <App>
+        <input type={type} aria-label="Field" />
+      </App>
+    )
+    const field = screen.getByLabelText('Field')
+    field.focus()
+    const events = await pressKeys(field, 'gwgqdwt')
+    expect(events.every((event) => !event.defaultPrevented)).toBe(true)
+    nothingFired()
+  })
+
+  it('a textarea, as in a message or a work order note, keeps every letter', async () => {
+    const user = userEvent.setup({ delay: HUMAN })
+    render(
+      <App>
+        <Textarea aria-label="Message" />
+      </App>
+    )
+    const field = screen.getByLabelText('Message')
+    await user.click(field)
+    await user.keyboard(SENTENCE)
+    expect(field).toHaveValue(SENTENCE)
+    nothingFired()
+  })
+
+  it('the rich text editor keeps every key', async () => {
+    render(
+      <App>
+        <RichTextEditor content="" onChange={vi.fn()} />
+      </App>
+    )
+    const editor = await vi.waitFor(() => {
+      const el = document.querySelector('[contenteditable="true"]')
+      if (!el) throw new Error('editor not mounted')
+      return el as HTMLElement
+    })
+    editor.focus()
+    const events = await pressKeys(editor, 'gwgqdwmt')
+    expect(events.every((event) => !event.defaultPrevented)).toBe(true)
+    nothingFired()
+  })
+
+  it('any contenteditable or ARIA text box keeps every key, however deep the cursor is', async () => {
+    render(
+      <App>
+        <div contentEditable suppressContentEditableWarning aria-label="Canvas text">
+          <p>
+            <span data-testid="deep">text</span>
+          </p>
+        </div>
+        <div role="textbox" tabIndex={0} aria-label="Custom box" />
+        <div role="searchbox" tabIndex={0} aria-label="Custom search" />
+        <div role="spinbutton" tabIndex={0} aria-label="Custom number" />
+      </App>
+    )
+    for (const target of [
+      screen.getByTestId('deep'),
+      screen.getByLabelText('Custom box'),
+      screen.getByLabelText('Custom search'),
+      screen.getByLabelText('Custom number'),
+    ]) {
+      const events = await pressKeys(target, 'gwdw')
+      expect(events.every((event) => !event.defaultPrevented)).toBe(true)
+    }
+    nothingFired()
+  })
+
+  it('a field inside a shadow root keeps every key', async () => {
+    render(
+      <App>
+        <div data-testid="host" />
+      </App>
+    )
+    const host = screen.getByTestId('host')
+    const shadow = host.attachShadow({ mode: 'open' })
+    const field = document.createElement('input')
+    shadow.appendChild(field)
+    field.focus()
+    const events = await pressKeys(field, 'gwdw')
+    expect(events.every((event) => !event.defaultPrevented)).toBe(true)
+    nothingFired()
+  })
+
+  it('a native select keeps its letters for jumping to an option', async () => {
+    render(
+      <App>
+        <select aria-label="Status">
+          <option>Waiting</option>
+          <option>Done</option>
+        </select>
+      </App>
+    )
+    const select = screen.getByLabelText('Status')
+    select.focus()
+    const events = await pressKeys(select, 'gwdw')
+    expect(events.every((event) => !event.defaultPrevented)).toBe(true)
+    nothingFired()
+  })
+
+  it('the date field keeps what is typed', async () => {
+    const user = userEvent.setup({ delay: HUMAN })
+    render(
+      <App>
+        <DateInput value="" onChange={vi.fn()} placeholder="Date" />
+      </App>
+    )
+    const field = screen.getByPlaceholderText('Date')
+    await user.click(field)
+    await user.keyboard('gw 12 dw')
+    nothingFired()
+  })
+
+  it('the tag box keeps every letter', async () => {
+    const user = userEvent.setup({ delay: HUMAN })
+    render(
+      <App>
+        <TagInput
+          value={[]}
+          onChange={vi.fn()}
+          placeholder="Tags"
+          removeLabel={(tag) => `Remove ${tag}`}
+        />
+      </App>
+    )
+    const field = screen.getByPlaceholderText('Tags')
+    await user.click(field)
+    await user.keyboard('gwdw')
+    expect(field).toHaveValue('gwdw')
+    nothingFired()
+  })
+
+  it('the search palette input keeps every letter', async () => {
+    const user = userEvent.setup({ delay: HUMAN })
+    render(
+      <App>
+        <Command>
+          <CommandInput placeholder="Search" />
+          <CommandList>
+            <CommandItem>Work orders</CommandItem>
+          </CommandList>
+        </Command>
+      </App>
+    )
+    const field = screen.getByPlaceholderText('Search')
+    await user.click(field)
+    await user.keyboard('gw gq dw')
+    expect(field).toHaveValue('gw gq dw')
+    nothingFired()
+  })
+})
+
+describe('pickers and lists keep their letters', () => {
+  it('a select, closed with the focus on it and open on its list', async () => {
+    const user = userEvent.setup({ delay: HUMAN })
+    render(
+      <App>
+        <Select>
+          <SelectTrigger aria-label="Technician">
+            <SelectValue placeholder="Pick" />
+          </SelectTrigger>
+          <SelectContent>
+            <SelectItem value="gunnar">Gunnar</SelectItem>
+            <SelectItem value="wenche">Wenche</SelectItem>
+          </SelectContent>
+        </Select>
+      </App>
+    )
+    const trigger = screen.getByLabelText('Technician')
+    trigger.focus()
+    await pressKeys(trigger, 'gw')
+    nothingFired()
+    await user.click(trigger)
+    await pressKeys(document.activeElement ?? document.body, 'gwdw')
+    await pressKeys(document.body, 'gw')
+    nothingFired()
+  })
+
+  it('the searchable select, on its button and in its search box', async () => {
+    const user = userEvent.setup({ delay: HUMAN })
+    render(
+      <App>
+        <SearchableSelect
+          value=""
+          onValueChange={vi.fn()}
+          aria-label="Customer"
+          searchable
+          options={[
+            { value: 'g', label: 'Gunnar Wold' },
+            { value: 'w', label: 'Wenche Dahl' },
+          ]}
+        />
+      </App>
+    )
+    const trigger = screen.getByRole('combobox', { name: 'Customer' })
+    trigger.focus()
+    await pressKeys(trigger, 'gw')
+    nothingFired()
+    await user.click(trigger)
+    await user.keyboard('gw')
+    await pressKeys(document.body, 'gwdw')
+    nothingFired()
+  })
+
+  it('tabs keep the arrow keys the calendar would otherwise take', async () => {
+    render(
+      <App>
+        <Tabs defaultValue="a">
+          <TabsList>
+            <TabsTrigger value="a">Parts</TabsTrigger>
+            <TabsTrigger value="b">Labor</TabsTrigger>
+          </TabsList>
+        </Tabs>
+      </App>
+    )
+    const tab = screen.getByRole('tab', { name: 'Parts' })
+    tab.focus()
+    for (const key of ['ArrowRight', 'ArrowLeft']) fireEvent.keyDown(tab, { key })
+    await pressKeys(tab, 'gw')
+    nothingFired()
+  })
+
+  it('custom lists, trees, grids and menus keep their type-ahead', async () => {
+    render(
+      <App>
+        <div role="listbox" tabIndex={0} aria-label="List">
+          <div role="option" tabIndex={-1} aria-selected="false">
+            Gearbox
+          </div>
+        </div>
+        <div role="tree" tabIndex={0} aria-label="Tree">
+          <div role="treeitem" tabIndex={-1} aria-selected="false">
+            Wheels
+          </div>
+        </div>
+        <div role="grid" tabIndex={0} aria-label="Grid" />
+        <div role="menu" data-state="closed" tabIndex={0} aria-label="Menu" />
+        <div data-shortcuts="off" tabIndex={0} data-testid="opted-out" />
+      </App>
+    )
+    for (const target of [
+      screen.getByText('Gearbox'),
+      screen.getByText('Wheels'),
+      screen.getByLabelText('Grid'),
+      screen.getByLabelText('Menu'),
+      screen.getByTestId('opted-out'),
+    ]) {
+      const events = await pressKeys(target, 'gwdw')
+      expect(events.every((event) => !event.defaultPrevented)).toBe(true)
+    }
+    nothingFired()
+  })
+})
+
+describe('nothing fires while something is open on top of the page', () => {
+  const overlays: [string, React.ReactNode][] = [
+    [
+      'a dialog',
+      <Dialog key="d" open>
+        <DialogContent>
+          <DialogTitle>Edit</DialogTitle>
+          <DialogDescription>Details</DialogDescription>
+          <Input aria-label="Inside" />
+        </DialogContent>
+      </Dialog>,
+    ],
+    [
+      'an alert dialog',
+      <AlertDialog key="a" open>
+        <AlertDialogContent>
+          <AlertDialogTitle>Sure?</AlertDialogTitle>
+          <AlertDialogDescription>Details</AlertDialogDescription>
+        </AlertDialogContent>
+      </AlertDialog>,
+    ],
+    [
+      'a sheet',
+      <Sheet key="s" open>
+        <SheetContent>
+          <SheetTitle>Panel</SheetTitle>
+          <SheetDescription>Details</SheetDescription>
+        </SheetContent>
+      </Sheet>,
+    ],
+    [
+      'a drawer',
+      <Drawer key="w" open>
+        <DrawerContent>
+          <DrawerTitle>More</DrawerTitle>
+          <DrawerDescription>Details</DrawerDescription>
+        </DrawerContent>
+      </Drawer>,
+    ],
+    [
+      'a popover',
+      <Popover key="p" open>
+        <PopoverTrigger>Open</PopoverTrigger>
+        <PopoverContent>Content</PopoverContent>
+      </Popover>,
+    ],
+    [
+      'a dropdown menu',
+      <DropdownMenu key="m" open>
+        <DropdownMenuTrigger>Open</DropdownMenuTrigger>
+        <DropdownMenuContent>
+          <DropdownMenuItem>Week</DropdownMenuItem>
+        </DropdownMenuContent>
+      </DropdownMenu>,
+    ],
+    [
+      'a lightbox of the app’s own',
+      <div key="l" data-shortcut-layer>
+        <img alt="" />
+      </div>,
+    ],
+    [
+      'a modal with no state attribute',
+      <div key="x" role="dialog" aria-modal="true" aria-label="Viewer" />,
+    ],
+  ]
+
+  it.each(overlays)('%s', async (_name, overlay) => {
+    render(<App>{overlay}</App>)
+    await wait(50)
+    // On the page behind it, on whatever it focused, and in a field inside it.
+    await pressKeys(document.body, 'gwdw')
+    await pressKeys(document.activeElement ?? document.body, 'gqmt')
+    nothingFired()
+  })
+
+  it('a context menu', async () => {
+    render(
+      <App>
+        <ContextMenu>
+          <ContextMenuTrigger>Row</ContextMenuTrigger>
+          <ContextMenuContent>
+            <ContextMenuItem>Week</ContextMenuItem>
+          </ContextMenuContent>
+        </ContextMenu>
+      </App>
+    )
+    fireEvent.contextMenu(screen.getByText('Row'))
+    await screen.findByRole('menu')
+    await pressKeys(document.body, 'gwdw')
+    await pressKeys(document.activeElement ?? document.body, 'gwdw')
+    nothingFired()
+  })
+
+  it('a field in a dialog keeps every letter', async () => {
+    const user = userEvent.setup({ delay: HUMAN })
+    render(
+      <App>
+        <Dialog open>
+          <DialogContent>
+            <DialogTitle>Edit</DialogTitle>
+            <DialogDescription>Details</DialogDescription>
+            <Input aria-label="Inside" />
+          </DialogContent>
+        </Dialog>
+      </App>
+    )
+    const field = screen.getByLabelText('Inside')
+    await user.click(field)
+    await user.keyboard(SENTENCE)
+    expect(field).toHaveValue(SENTENCE)
+    nothingFired()
+  })
+
+  it('a tooltip under the mouse does not count: it takes no keys', async () => {
+    render(
+      <App>
+        <TooltipProvider>
+          <Tooltip open>
+            <TooltipTrigger>Hover</TooltipTrigger>
+            <TooltipContent>Hint</TooltipContent>
+          </Tooltip>
+        </TooltipProvider>
+      </App>
+    )
+    await wait(50)
+    await pressKeys(document.body, 'w')
+    expect(calendar).toHaveBeenCalledWith('week')
+  })
+
+  it('the go-to and create chords wait for a dialog to close as well', async () => {
+    render(
+      <App>
+        <div role="dialog" data-state="open" aria-label="Confirm" />
+      </App>
+    )
+    await pressAlt(document.body, 'gw')
+    await pressAlt(document.body, 'q')
+    nothingFired()
+  })
+})
+
+describe('the awkward moments', () => {
+  it('Alt+G on the page, then a bare letter typed into a field', async () => {
+    const user = userEvent.setup({ delay: HUMAN })
+    render(
+      <App>
+        <Input aria-label="Note" />
+      </App>
+    )
+    await pressAlt(document.body, 'g')
+    const field = screen.getByLabelText('Note')
+    await user.click(field)
+    await user.keyboard('w')
+    expect(field).toHaveValue('w')
+    nothingFired()
+  })
+
+  it('Alt+G on the page, then a dialog opens before the letter', async () => {
+    const { rerender } = render(<App />)
+    await pressAlt(document.body, 'g')
+    rerender(
+      <App>
+        <div role="dialog" data-state="open" aria-label="Confirm" />
+      </App>
+    )
+    await pressAlt(document.body, 'w')
+    nothingFired()
+  })
+
+  it('a sentence that outlives its dialog: keys just after it closes are not commands', async () => {
+    const user = userEvent.setup({ delay: HUMAN })
+    const { rerender } = render(
+      <App>
+        <div role="dialog" data-state="open" aria-label="Quick add">
+          <input aria-label="Name" />
+        </div>
+      </App>
+    )
+    const field = screen.getByLabelText('Name')
+    await user.click(field)
+    await user.keyboard('bolt')
+    // Enter saved and closed it; the next keys land on the page.
+    rerender(<App />)
+    await pressKeys(document.body, 'gwdw')
+    nothingFired()
+    // Once the person has stopped, the page answers again.
+    await wait(600)
+    await pressKeys(document.body, 'w')
+    expect(calendar).toHaveBeenCalledWith('week')
+  })
+
+  it('keys right after leaving a field are not commands either', async () => {
+    const user = userEvent.setup({ delay: HUMAN })
+    render(
+      <App>
+        <Input aria-label="Note" />
+      </App>
+    )
+    const field = screen.getByLabelText('Note')
+    await user.click(field)
+    await user.keyboard('torque')
+    act(() => field.blur())
+    await pressKeys(document.body, 'gw')
+    nothingFired()
+  })
+
+  it('Alt+G held until it repeats is still one Alt+G', async () => {
+    render(<App />)
+    act(() => {
+      document.body.dispatchEvent(
+        new KeyboardEvent('keydown', { key: 'g', altKey: true, bubbles: true })
+      )
+      for (let i = 0; i < 5; i++) {
+        document.body.dispatchEvent(
+          new KeyboardEvent('keydown', { key: 'g', altKey: true, repeat: true, bubbles: true })
+        )
+      }
+    })
+    await pressAlt(document.body, 'w')
+    expect(push).toHaveBeenCalledTimes(1)
+    expect(push).toHaveBeenCalledWith('/work-orders')
+  })
+
+  it('Alt+G then a bare key leaves that key its own meaning', async () => {
+    render(<App />)
+    await pressAlt(document.body, 'g')
+    await pressKeys(document.body, 'x')
+    expect(push).not.toHaveBeenCalled()
+    expect(calendar).toHaveBeenCalledWith('fourDays')
+  })
+
+  it('Alt+G then Alt and a letter that opens no page does nothing, and takes nothing', async () => {
+    render(<App />)
+    await pressAlt(document.body, 'g')
+    const event = new KeyboardEvent('keydown', {
+      key: 'z',
+      altKey: true,
+      bubbles: true,
+      cancelable: true,
+    })
+    act(() => {
+      document.body.dispatchEvent(event)
+    })
+    expect(event.defaultPrevented).toBe(false)
+    nothingFired()
+  })
+
+  it('letting go of Alt between the two presses keeps the sequence', async () => {
+    render(<App />)
+    await pressAlt(document.body, 'g')
+    act(() => {
+      document.body.dispatchEvent(
+        new KeyboardEvent('keydown', { key: 'Alt', altKey: true, bubbles: true })
+      )
+    })
+    await wait(HUMAN)
+    await pressAlt(document.body, 'w')
+    expect(push).toHaveBeenCalledWith('/work-orders')
+  })
+
+  it('a click between the two presses is a change of mind', async () => {
+    render(
+      <App>
+        <p>Somewhere</p>
+      </App>
+    )
+    await pressAlt(document.body, 'g')
+    fireEvent.pointerDown(screen.getByText('Somewhere'))
+    await pressAlt(document.body, 'w')
+    // Alt+W on its own: a new work order, not the list.
+    expect(push).toHaveBeenCalledTimes(1)
+    expect(push).toHaveBeenCalledWith('/work-orders?new=1')
+  })
+
+  it('the go-to set works from inside a field without typing anything', async () => {
+    const user = userEvent.setup({ delay: HUMAN })
+    render(
+      <App>
+        <Input aria-label="Note" />
+      </App>
+    )
+    const field = screen.getByLabelText('Note')
+    await user.click(field)
+    await user.keyboard('bolt')
+    await pressAlt(field, 'gq')
+    expect(field).toHaveValue('bolt')
+    expect(push).toHaveBeenCalledWith('/quotes')
+  })
+
+  it('keys of an input method being composed are left alone', async () => {
+    render(<App />)
+    for (const key of ['g', 'w', 'd']) {
+      const event = new KeyboardEvent('keydown', {
+        key,
+        isComposing: true,
+        bubbles: true,
+        cancelable: true,
+      })
+      act(() => {
+        document.body.dispatchEvent(event)
+      })
+      expect(event.defaultPrevented).toBe(false)
+      await wait(HUMAN)
+    }
+    nothingFired()
+  })
+
+  it('the focus is already in the field when a click is followed by fast typing', async () => {
+    const user = userEvent.setup({ delay: null })
+    render(
+      <App>
+        <Textarea aria-label="Message" />
+      </App>
+    )
+    const field = screen.getByLabelText('Message')
+    await user.pointer({ keys: '[MouseLeft>]', target: field })
+    await user.keyboard('gw')
+    await user.pointer({ keys: '[/MouseLeft]', target: field })
+    expect(field).toHaveValue('gw')
+    await wait(HUMAN)
+    nothingFired()
+  })
+})
+
+describe('a barcode scanner is not a person', () => {
+  /** A scanner: every character within a few milliseconds, then Enter. */
+  function scan(code: string, target: Element = document.body) {
+    act(() => {
+      for (const key of [...code, 'Enter']) {
+        target.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }))
+      }
+    })
+  }
+
+  it.each([
+    'gw',
+    'GW4471',
+    'w',
+    'd',
+    'wd40',
+    'tjnkp',
+    '7gq12',
+  ])('scanning "%s" with no field focused runs nothing', async (code) => {
+    render(<App />)
+    scan(code.toLowerCase())
+    await wait(200)
+    nothingFired()
+  })
+
+  it('a scan a few milliseconds a key apart runs nothing', async () => {
+    render(<App />)
+    for (const key of ['g', 'w', '4', '2', 'Enter']) {
+      act(() => {
+        document.body.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true }))
+      })
+      await wait(8)
+    }
+    await wait(200)
+    nothingFired()
+  })
+
+  it('the page answers a person again after a scan', async () => {
+    render(<App />)
+    scan('gw4471')
+    await wait(200)
+    await pressKeys(document.body, 'w')
+    expect(calendar).toHaveBeenCalledWith('week')
+  })
+})

+ 1 - 0
src/__tests__/lib/files/references.test.ts

@@ -64,6 +64,7 @@ const NOT_FILES: Record<string, string> = {
   'EmailAttachment.fileName': 'a label',
   'User.image': 'an avatar URL from a sign-in provider; never an upload',
   'User.dashboardLayout': 'dashboard layout',
+  'User.keyboardShortcuts': 'keyboard shortcut choices',
   'VehicleInspectionStatus.extras': 'what a vehicle registry returned',
   'VehicleSafetyReport.data': 'what a vehicle registry returned',
   'Webhook.url': 'an outbound endpoint',

+ 1 - 0
src/app/(authenticated)/inventory/inventory-client.tsx

@@ -1023,6 +1023,7 @@ export function InventoryClient({
 
       {galleryIndex !== null && galleryImages.length > 0 && (
         <div
+          data-shortcut-layer
           className="fixed inset-0 z-50 flex items-center justify-center bg-black/90"
           onClick={() => setGalleryIndex(null)}
         >

+ 137 - 118
src/app/(authenticated)/layout.tsx

@@ -57,6 +57,8 @@ import { technicianIdsForUser } from '@/features/time-tracking/Lib/timeEntries'
 import { TimeClockProvider } from '@/features/time-tracking/Components/TimeClockProvider'
 import { RealtimeProvider } from '@/features/realtime/RealtimeProvider'
 import { SaveShortcutListener } from '@/components/save-shortcut-listener'
+import { ShortcutsProvider } from '@/features/shortcuts/Components/ShortcutsProvider'
+import { SidebarShortcut } from '@/features/shortcuts/Components/SidebarShortcut'
 import { AnalyticsIdentity } from '@/components/analytics-identity'
 import { WhatsNewProvider } from '@/features/whats-new/Components/WhatsNewProvider'
 import { getWhatsNewFeed } from '@/features/whats-new/Lib/feed.server'
@@ -346,139 +348,156 @@ export default async function DashboardLayout({ children }: { children: React.Re
                 releaseNotesUrl={releaseNotesUrl}
                 feedback={isDemoMode ? null : isCloudMode() ? 'identified' : 'anonymous'}
               >
-                {/* Accent line along the very top of the viewport — the card hairline at
+                {/* One listener for every keyboard shortcut, with this person's
+                    own keys. Told what the search palette is told, so a page
+                    their role cannot open has no shortcut either. */}
+                <ShortcutsProvider
+                  initialPrefs={data.keyboardShortcuts}
+                  plateLookupAvailable={plateLookupAvailable}
+                  commands={{
+                    visibleSubjects,
+                    features,
+                    tireHotelEnabled,
+                    aiEnabled,
+                    isAdminOrOwner: isOwnerOrAdmin,
+                    faultCodesEnabled,
+                  }}
+                >
+                  {/* Accent line along the very top of the viewport — the card hairline at
         page scale: primary on the left, gone by the far edge. Marks where the
         app begins against the browser chrome. */}
-                <div
-                  aria-hidden
-                  className="pointer-events-none fixed inset-x-0 top-0 z-50 h-px bg-linear-to-r from-primary via-primary/35 to-transparent"
-                />
-                {/* For somebody on a keyboard: the first Tab offers a way past
+                  <div
+                    aria-hidden
+                    className="pointer-events-none fixed inset-x-0 top-0 z-50 h-px bg-linear-to-r from-primary via-primary/35 to-transparent"
+                  />
+                  {/* For somebody on a keyboard: the first Tab offers a way past
                     the sidebar's twenty links. Invisible until it has focus. */}
-                <a
-                  href="#main-content"
-                  className="sr-only focus:not-sr-only focus:fixed focus:left-3 focus:top-3 focus:z-[60] focus:rounded-md focus:bg-background focus:px-3 focus:py-2 focus:text-sm focus:font-medium focus:text-foreground focus:shadow-md focus:outline-2 focus:outline-offset-2 focus:outline-foreground"
-                >
-                  {ta('skipToContent')}
-                </a>
-                {/* Watches for a notice posted while this page is already open. Here
+                  <a
+                    href="#main-content"
+                    className="sr-only focus:not-sr-only focus:fixed focus:left-3 focus:top-3 focus:z-[60] focus:rounded-md focus:bg-background focus:px-3 focus:py-2 focus:text-sm focus:font-medium focus:text-foreground focus:shadow-md focus:outline-2 focus:outline-offset-2 focus:outline-foreground"
+                  >
+                    {ta('skipToContent')}
+                  </a>
+                  {/* Watches for a notice posted while this page is already open. Here
               rather than beside the banner because the socket authenticates on
               the session cookie, which the sign-in page does not have. */}
-                <BroadcastLive />
-                {/* The demo banner already occupies the header, and demo image tags
+                  <BroadcastLive />
+                  {/* The demo banner already occupies the header, and demo image tags
         (demo-abc1234) are not versions a visitor should be notified about. */}
-                {!isDemoMode && (
-                  <UpdateBanner
-                    currentVersion={appVersion}
-                    lastSeenVersion={data.lastSeenVersion}
-                    shownVersion={data.updateBannerVersion}
-                    shownAt={data.updateBannerShownAt?.toISOString() ?? null}
-                    releaseNotesUrl={releaseNotesUrl}
-                  />
-                )}
-                <SidebarProvider
-                  defaultOpen={sidebarOpen}
-                  style={
-                    {
-                      '--sidebar-width': '19rem',
-                    } as React.CSSProperties
-                  }
-                >
-                  <DateSettingsProvider
-                    dateFormat={data.dateFormat}
-                    timeFormat={data.timeFormat}
-                    timezone={data.timezone}
-                    weekStartDay={data.weekStartDay}
+                  {!isDemoMode && (
+                    <UpdateBanner
+                      currentVersion={appVersion}
+                      lastSeenVersion={data.lastSeenVersion}
+                      shownVersion={data.updateBannerVersion}
+                      shownAt={data.updateBannerShownAt?.toISOString() ?? null}
+                      releaseNotesUrl={releaseNotesUrl}
+                    />
+                  )}
+                  <SidebarProvider
+                    defaultOpen={sidebarOpen}
+                    style={
+                      {
+                        '--sidebar-width': '19rem',
+                      } as React.CSSProperties
+                    }
                   >
-                    <CurrencySettingsProvider
-                      currencyCode={data.currencyCode}
-                      currencyFormat={data.currencyFormat}
+                    <DateSettingsProvider
+                      dateFormat={data.dateFormat}
+                      timeFormat={data.timeFormat}
+                      timezone={data.timezone}
+                      weekStartDay={data.weekStartDay}
                     >
-                      <ConfirmProvider>
-                        <PlateLookupProvider
-                          value={{
-                            available: plateLookupAvailable,
-                            canCreate: canCreateVehicles,
-                            registryName: plateLookupRegistry,
-                          }}
-                        >
-                          <FeatureHintProvider
-                            initialSeen={seenHints}
-                            pending={[...pendingHints, ...announcements]}
+                      <CurrencySettingsProvider
+                        currencyCode={data.currencyCode}
+                        currencyFormat={data.currencyFormat}
+                      >
+                        <ConfirmProvider>
+                          <PlateLookupProvider
+                            value={{
+                              available: plateLookupAvailable,
+                              canCreate: canCreateVehicles,
+                              registryName: plateLookupRegistry,
+                            }}
                           >
-                            {/* One socket for the whole app: record changes, who
+                            <FeatureHintProvider
+                              initialSeen={seenHints}
+                              pending={[...pendingHints, ...announcements]}
+                            >
+                              {/* One socket for the whole app: record changes, who
                           else is on a record, and the older workshop-wide
                           channels the remaining pages still read. */}
-                            <RealtimeProvider>
-                              <TimeClockProvider technicianIds={technicianIds}>
-                                <SaveShortcutListener />
-                                <AnalyticsIdentity
-                                  userId={data.userId}
-                                  organizationId={data.organizationId}
-                                />
-                                <AppSidebar
-                                  companyLogo={data.companyLogo}
-                                  organizations={data.organizations}
-                                  activeOrgId={data.organizationId}
-                                  isSuperAdmin={data.isSuperAdmin}
-                                  features={features}
-                                  tireHotelEnabled={tireHotelEnabled}
-                                  aiEnabled={aiEnabled}
-                                  faultCodesEnabled={faultCodesEnabled}
-                                  visibleSubjects={visibleSubjects}
-                                  announcement={announcements[0] ?? null}
-                                  isAdminOrOwner={isOwnerOrAdmin}
-                                  counts={sidebarCounts}
-                                  isTechnician={technicianIds.length > 0}
-                                />
-                                <SidebarInset
-                                  id="main-content"
-                                  tabIndex={-1}
-                                  className="outline-none"
-                                >
-                                  {/* A flex column with a real height, so the `flex-1` every
+                              <RealtimeProvider>
+                                <TimeClockProvider technicianIds={technicianIds}>
+                                  <SaveShortcutListener />
+                                  <SidebarShortcut />
+                                  <AnalyticsIdentity
+                                    userId={data.userId}
+                                    organizationId={data.organizationId}
+                                  />
+                                  <AppSidebar
+                                    companyLogo={data.companyLogo}
+                                    organizations={data.organizations}
+                                    activeOrgId={data.organizationId}
+                                    isSuperAdmin={data.isSuperAdmin}
+                                    features={features}
+                                    tireHotelEnabled={tireHotelEnabled}
+                                    aiEnabled={aiEnabled}
+                                    faultCodesEnabled={faultCodesEnabled}
+                                    visibleSubjects={visibleSubjects}
+                                    announcement={announcements[0] ?? null}
+                                    isAdminOrOwner={isOwnerOrAdmin}
+                                    counts={sidebarCounts}
+                                    isTechnician={technicianIds.length > 0}
+                                  />
+                                  <SidebarInset
+                                    id="main-content"
+                                    tabIndex={-1}
+                                    className="outline-none"
+                                  >
+                                    {/* A flex column with a real height, so the `flex-1` every
                           page already writes on its wrapper actually resolves.
                           Without it a page that wants to fill the window (the
                           work board's week timeline) stopped at its content and
                           left the rest of the screen blank. */}
-                                  <div className="flex min-h-0 flex-1 flex-col pb-14 md:pb-0">
-                                    {children}
-                                  </div>
-                                </SidebarInset>
-                                <SearchCommand
-                                  visibleSubjects={visibleSubjects}
-                                  features={features}
-                                  tireHotelEnabled={tireHotelEnabled}
-                                  aiEnabled={aiEnabled}
-                                  isAdminOrOwner={isOwnerOrAdmin}
-                                  isCloud={cloudLinked}
-                                  supportEnabled={supportEnabled}
-                                  isMarine={data.serviceType === 'marine'}
-                                  connectors={searchConnectors}
-                                  faultCodesEnabled={faultCodesEnabled}
-                                />
-                                <PlateLookupCommand />
-                                {isOwnerOrAdmin && <NotificationInitializer />}
-                                <OnlineTracker />
-                                <ConnectionWatcher />
-                                <UpdateWatcher version={buildVersion()} />
-                                <InstallBanner
-                                  appName={appBranding.name}
-                                  iconUrl={appBranding.iconUrl}
-                                />
-                              </TimeClockProvider>
-                            </RealtimeProvider>
-                          </FeatureHintProvider>
-                        </PlateLookupProvider>
-                      </ConfirmProvider>
-                    </CurrencySettingsProvider>
-                  </DateSettingsProvider>
-                </SidebarProvider>
-                <MobileBottomNav
-                  isSuperAdmin={data.isSuperAdmin}
-                  tireHotelEnabled={tireHotelEnabled}
-                />
-                {supportEnabled && <SupportBubble userId={data.userId} />}
+                                    <div className="flex min-h-0 flex-1 flex-col pb-14 md:pb-0">
+                                      {children}
+                                    </div>
+                                  </SidebarInset>
+                                  <SearchCommand
+                                    visibleSubjects={visibleSubjects}
+                                    features={features}
+                                    tireHotelEnabled={tireHotelEnabled}
+                                    aiEnabled={aiEnabled}
+                                    isAdminOrOwner={isOwnerOrAdmin}
+                                    isCloud={cloudLinked}
+                                    supportEnabled={supportEnabled}
+                                    isMarine={data.serviceType === 'marine'}
+                                    connectors={searchConnectors}
+                                    faultCodesEnabled={faultCodesEnabled}
+                                  />
+                                  <PlateLookupCommand />
+                                  {isOwnerOrAdmin && <NotificationInitializer />}
+                                  <OnlineTracker />
+                                  <ConnectionWatcher />
+                                  <UpdateWatcher version={buildVersion()} />
+                                  <InstallBanner
+                                    appName={appBranding.name}
+                                    iconUrl={appBranding.iconUrl}
+                                  />
+                                </TimeClockProvider>
+                              </RealtimeProvider>
+                            </FeatureHintProvider>
+                          </PlateLookupProvider>
+                        </ConfirmProvider>
+                      </CurrencySettingsProvider>
+                    </DateSettingsProvider>
+                  </SidebarProvider>
+                  <MobileBottomNav
+                    isSuperAdmin={data.isSuperAdmin}
+                    tireHotelEnabled={tireHotelEnabled}
+                  />
+                  {supportEnabled && <SupportBubble userId={data.userId} />}
+                </ShortcutsProvider>
               </WhatsNewProvider>
             </WhiteLabelCtaProvider>
           </LicenseExpiryProvider>

+ 15 - 0
src/app/(authenticated)/settings/shortcuts/page.tsx

@@ -0,0 +1,15 @@
+import { redirect } from 'next/navigation'
+import { getAuthContext } from '@/lib/get-auth-context'
+import { settingsPageTitle } from '@/lib/page-title'
+import { ShortcutsSettings } from '@/features/shortcuts/Components/ShortcutsSettings'
+
+export function generateMetadata() {
+  return settingsPageTitle('shortcuts')
+}
+
+export default async function ShortcutsSettingsPage() {
+  const ctx = await getAuthContext()
+  if (!ctx) redirect('/sign-in')
+
+  return <ShortcutsSettings />
+}

+ 1 - 0
src/app/(authenticated)/vehicles/[id]/_classic/vehicle-detail-classic.tsx

@@ -1860,6 +1860,7 @@ export function VehicleDetailClassic({
       {/* Image lightbox */}
       {showImage && vehicle.imageUrl && (
         <div
+          data-shortcut-layer
           className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-4"
           onClick={() => setShowImage(false)}
         >

+ 1 - 0
src/app/(authenticated)/vehicles/[id]/vehicle-detail-client.tsx

@@ -2509,6 +2509,7 @@ export function VehicleDetailClient({
       {/* Image lightbox */}
       {showImage && vehicle.imageUrl && (
         <div
+          data-shortcut-layer
           className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-4"
           onClick={() => setShowImage(false)}
         >

+ 23 - 2
src/components/app-sidebar.tsx

@@ -6,6 +6,9 @@ import Image from 'next/image'
 import { usePathname, useRouter } from 'next/navigation'
 import { toast } from 'sonner'
 import { signOut, useSession } from '@/lib/auth-client'
+import { ShortcutKeys } from '@/features/shortcuts/Components/ShortcutKeys'
+import { useShortcuts } from '@/features/shortcuts/Components/ShortcutsProvider'
+import { goToShortcutForHref } from '@/features/shortcuts/Lib/registry'
 import { resetAnalytics } from '@/lib/analytics'
 import { Avatar, AvatarFallback } from '@/components/ui/avatar'
 import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
@@ -61,6 +64,7 @@ import {
   LogOut,
   Monitor,
   Package,
+  Keyboard,
   Palette,
   Plus,
   Receipt,
@@ -111,6 +115,17 @@ export type SidebarCounts = {
   reminders: number
 }
 
+/** A collapsed sidebar's tooltip: the page, and the key that opens it. */
+function NavTooltip({ label, href }: { label: string; href: string }) {
+  const shortcut = goToShortcutForHref(href)
+  return (
+    <span className="flex items-center gap-2">
+      {label}
+      {shortcut && <ShortcutKeys id={shortcut.id} />}
+    </span>
+  )
+}
+
 type NavItem = {
   titleKey: string
   url: string
@@ -161,6 +176,7 @@ export function AppSidebar({
   isTechnician?: boolean
 }) {
   const pathname = usePathname()
+  const { openHelp: openShortcutsHelp } = useShortcuts()
   const router = useRouter()
   const { data: session } = useSession()
   const { theme, setTheme } = useTheme()
@@ -331,7 +347,7 @@ export function AppSidebar({
         <SidebarMenuButton
           asChild
           isActive={pathname.startsWith('/settings')}
-          tooltip={t('sidebar.settings')}
+          tooltip={{ children: <NavTooltip label={t('sidebar.settings')} href="/settings" /> }}
           className={cn(highlighted && 'ring-2 ring-primary ring-offset-1 ring-offset-sidebar')}
         >
           <Link href="/settings" onClick={closeMobileSidebar}>
@@ -374,7 +390,7 @@ export function AppSidebar({
           <SidebarMenuButton
             asChild
             isActive={isActive}
-            tooltip={t(item.titleKey)}
+            tooltip={{ children: <NavTooltip label={t(item.titleKey)} href={item.url} /> }}
             // Marked while the card is up, so it is obvious which of a dozen
             // links the card is talking about.
             className={cn(
@@ -682,6 +698,11 @@ export function AppSidebar({
                     </Link>
                   </DropdownMenuItem>
                 )}
+                <DropdownMenuItem onSelect={openShortcutsHelp}>
+                  <Keyboard className="mr-2 size-4" />
+                  {t('sidebar.keyboardShortcuts')}
+                  <ShortcutKeys id="general.help" className="ml-auto" />
+                </DropdownMenuItem>
                 <DropdownMenuSub>
                   <DropdownMenuSubTrigger>
                     <Palette className="mr-2 size-4" />

+ 8 - 7
src/components/page-header.tsx

@@ -21,6 +21,9 @@ import { useShowWhiteLabelCta } from '@/components/white-label-cta-context'
 import { useLicenseExpiry } from '@/components/license-expiry-context'
 import { BANNER_PRIORITY, useBannerSlot } from '@/components/banner-slot'
 import { QuickCreateMenu } from '@/components/quick-create-menu'
+import { openSearch } from '@/features/search/Lib/open'
+import { ShortcutKeys } from '@/features/shortcuts/Components/ShortcutKeys'
+import { useShortcutKey } from '@/features/shortcuts/Components/ShortcutsProvider'
 import { DocsLink } from '@/components/docs-link'
 import { RunningClockPill } from '@/features/time-tracking/Components/RunningClockPill'
 import { useServiceType } from '@/components/service-type-context'
@@ -33,15 +36,11 @@ function SearchTrigger() {
     <button
       type="button"
       className="hidden h-8 w-56 cursor-pointer items-center gap-2 rounded-md border bg-muted/50 px-3 text-sm text-muted-foreground transition-colors hover:bg-muted sm:flex"
-      onClick={() => {
-        document.dispatchEvent(new KeyboardEvent('keydown', { key: 'k', metaKey: true }))
-      }}
+      onClick={openSearch}
     >
       <Search className="h-3.5 w-3.5" />
       <span className="flex-1 text-left">{t('search')}</span>
-      <kbd className="rounded border bg-background px-1.5 py-0.5 text-[10px] font-medium">
-        {t('shortcut')}
-      </kbd>
+      <ShortcutKeys id="general.search" />
     </button>
   )
 }
@@ -54,6 +53,7 @@ function SearchTrigger() {
 function PlateTrigger() {
   const t = useTranslations('vehicles.plateLookup')
   const { available } = usePlateLookupAccess()
+  const shortcut = useShortcutKey('general.plateLookup')
   if (!available) return null
   return (
     <button
@@ -61,7 +61,7 @@ function PlateTrigger() {
       className="group flex h-8 cursor-pointer items-center gap-2 rounded-md border bg-muted/50 px-2.5 text-sm text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
       onClick={() => openPlateLookup()}
       aria-label={t('open')}
-      title={`${t('open')} (${t('shortcut')})`}
+      title={shortcut ? `${t('open')} (${shortcut.text})` : t('open')}
     >
       <span
         aria-hidden
@@ -171,6 +171,7 @@ const breadcrumbMap: Record<string, BreadcrumbSegment[]> = {
   '/settings/warranty': [{ key: 'settings', href: '/settings' }, { key: 'warranty' }],
   '/settings/workshop': [{ key: 'settings', href: '/settings' }, { key: 'workshop' }],
   '/settings/appearance': [{ key: 'settings', href: '/settings' }, { key: 'appearance' }],
+  '/settings/shortcuts': [{ key: 'settings', href: '/settings' }, { key: 'shortcuts' }],
   '/settings/email': [{ key: 'settings', href: '/settings' }, { key: 'email' }],
   '/settings/sms': [{ key: 'settings', href: '/settings' }, { key: 'sms' }],
   '/settings/about': [{ key: 'settings', href: '/settings' }, { key: 'about' }],

+ 14 - 1
src/components/quick-create-menu.tsx

@@ -26,6 +26,8 @@ import {
 import { VehiclePickerDialog } from '@/components/vehicle-picker-dialog'
 import { NewInspectionDialog } from '@/features/inspections/Components/NewInspectionDialog'
 import { getTemplates } from '@/features/inspections/Actions/templateActions'
+import { ShortcutKeys } from '@/features/shortcuts/Components/ShortcutKeys'
+import { useShortcut } from '@/features/shortcuts/Components/ShortcutsProvider'
 
 interface TemplateOption {
   id: string
@@ -65,6 +67,11 @@ export function QuickCreateMenu() {
     }
   }
 
+  // The same two dialogs on their shortcuts. The rest of the menu opens a
+  // page, which the shortcut registry does on its own.
+  useShortcut('create.workOrder', handleNewWorkOrder)
+  useShortcut('create.inspection', () => void handleNewInspection())
+
   return (
     <>
       <DropdownMenu>
@@ -78,32 +85,38 @@ export function QuickCreateMenu() {
             {t('quickCreate.title')}
           </Button>
         </DropdownMenuTrigger>
-        <DropdownMenuContent align="end" className="w-48">
+        <DropdownMenuContent align="end" className="w-56">
           <DropdownMenuLabel>{t('quickCreate.title')}</DropdownMenuLabel>
           <DropdownMenuSeparator />
           <DropdownMenuItem onSelect={handleNewWorkOrder}>
             <Wrench className="h-4 w-4" />
             {t('quickCreate.workOrder')}
+            <ShortcutKeys id="create.workOrder" className="ml-auto" />
           </DropdownMenuItem>
           <DropdownMenuItem onSelect={() => router.push('/customers?create=true')}>
             <Users className="h-4 w-4" />
             {t('quickCreate.customer')}
+            <ShortcutKeys id="create.customer" className="ml-auto" />
           </DropdownMenuItem>
           <DropdownMenuItem onSelect={() => router.push('/vehicles?create=true')}>
             <Car className="h-4 w-4" />
             {t('quickCreate.vehicle')}
+            <ShortcutKeys id="create.vehicle" className="ml-auto" />
           </DropdownMenuItem>
           <DropdownMenuItem onSelect={() => router.push('/quotes?create=true')}>
             <FileText className="h-4 w-4" />
             {t('quickCreate.quote')}
+            <ShortcutKeys id="create.quote" className="ml-auto" />
           </DropdownMenuItem>
           <DropdownMenuItem onSelect={() => router.push('/inventory?create=true')}>
             <Package className="h-4 w-4" />
             {t('quickCreate.part')}
+            <ShortcutKeys id="create.part" className="ml-auto" />
           </DropdownMenuItem>
           <DropdownMenuItem onSelect={handleNewInspection}>
             <ClipboardCheck className="h-4 w-4" />
             {t('quickCreate.inspection')}
+            <ShortcutKeys id="create.inspection" className="ml-auto" />
           </DropdownMenuItem>
 
           {/* Everything above creates a record. This creates a person, which

+ 6 - 6
src/components/save-shortcut-listener.tsx

@@ -1,14 +1,11 @@
 'use client'
 
 import { useEffect } from 'react'
+import { useShortcutMatcher } from '@/features/shortcuts/Components/ShortcutsProvider'
 
 const SAVE_BUTTON = '[data-save-shortcut]'
 const OPEN_DIALOG = '[role="dialog"][data-state="open"], [role="alertdialog"][data-state="open"]'
 
-function isSaveShortcut(e: KeyboardEvent) {
-  return (e.ctrlKey || e.metaKey) && !e.altKey && (e.key === 's' || e.key === 'S')
-}
-
 function usable(button: HTMLElement) {
   return !(button as HTMLButtonElement).disabled && button.getClientRects().length > 0
 }
@@ -47,12 +44,15 @@ function press(button: HTMLElement) {
 }
 
 /**
- * Ctrl+S / Cmd+S for everything that saves through a button marked
+ * The save shortcut (Ctrl+S / Cmd+S unless changed) for everything that saves through a button marked
  * `data-save-shortcut`: settings pages and dialogs. The document editors
  * register their own save with `useSaveShortcut`; an open dialog with a save
  * button goes first, then the editor, then a save button on the page.
  */
 export function SaveShortcutListener() {
+  // The key is the person's own, from the shortcut registry. The listeners
+  // stay here because the order they run in is what picks the right save.
+  const isSaveShortcut = useShortcutMatcher('general.save')
   useEffect(() => {
     const topDialog = () => Array.from(document.querySelectorAll(OPEN_DIALOG)).at(-1) ?? null
 
@@ -84,7 +84,7 @@ export function SaveShortcutListener() {
       window.removeEventListener('keydown', dialogFirst, true)
       window.removeEventListener('keydown', pageLast)
     }
-  }, [])
+  }, [isSaveShortcut])
 
   return null
 }

+ 2 - 13
src/components/ui/sidebar.tsx

@@ -26,7 +26,6 @@ const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
 const SIDEBAR_WIDTH = '16rem'
 const SIDEBAR_WIDTH_MOBILE = '18rem'
 const SIDEBAR_WIDTH_ICON = '3rem'
-const SIDEBAR_KEYBOARD_SHORTCUT = 'b'
 
 type SidebarContextProps = {
   state: 'expanded' | 'collapsed'
@@ -89,18 +88,8 @@ function SidebarProvider({
     return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open)
   }, [isMobile, setOpen, setOpenMobile])
 
-  // Adds a keyboard shortcut to toggle the sidebar.
-  React.useEffect(() => {
-    const handleKeyDown = (event: KeyboardEvent) => {
-      if (event.key === SIDEBAR_KEYBOARD_SHORTCUT && (event.metaKey || event.ctrlKey)) {
-        event.preventDefault()
-        toggleSidebar()
-      }
-    }
-
-    window.addEventListener('keydown', handleKeyDown)
-    return () => window.removeEventListener('keydown', handleKeyDown)
-  }, [toggleSidebar])
+  // The keyboard shortcut lives in the shortcut registry
+  // (features/shortcuts), which calls toggleSidebar through SidebarShortcut.
 
   // We add a state so that we can do data-state="expanded" or "collapsed".
   // This makes it easier to style the sidebar with Tailwind classes.

+ 13 - 42
src/features/calendar/Components/CalendarClient.tsx

@@ -40,8 +40,9 @@ import {
 import { compareEvents, isEventDone } from './calendar-utils'
 import { CalendarEventList } from './CalendarEventList'
 import { CalendarSidebar, type TypeFilters } from './CalendarSidebar'
-import { CalendarToolbar, VIEW_SHORTCUTS, type CreateKind } from './CalendarToolbar'
+import { CalendarToolbar, type CreateKind } from './CalendarToolbar'
 import type { DayActions } from './DayContextMenu'
+import { useShortcut } from '@/features/shortcuts/Components/ShortcutsProvider'
 import { type BookingEdit, EventPeekProvider } from './EventPeek'
 import { MonthView } from './MonthView'
 import { ScheduleView } from './ScheduleView'
@@ -294,47 +295,17 @@ export default function CalendarClient({
     setView('day')
   }, [])
 
-  useEffect(() => {
-    const onKey = (e: KeyboardEvent) => {
-      if (e.metaKey || e.ctrlKey || e.altKey) return
-      const target = e.target as HTMLElement | null
-      if (
-        target?.closest(
-          'input, textarea, select, [contenteditable="true"], [role="dialog"], [role="menu"]'
-        )
-      ) {
-        return
-      }
-      const key = e.key.length === 1 ? e.key.toUpperCase() : e.key
-      const viewFor = (Object.keys(VIEW_SHORTCUTS) as CalendarView[]).find(
-        (v) => VIEW_SHORTCUTS[v] === key
-      )
-      if (viewFor) {
-        setView(viewFor)
-        return
-      }
-      switch (key) {
-        case 'T':
-          goToday()
-          break
-        case 'J':
-        case 'N':
-        case 'ArrowRight':
-          goNext()
-          break
-        case 'K':
-        case 'P':
-        case 'ArrowLeft':
-          goPrev()
-          break
-        default:
-          return
-      }
-      e.preventDefault()
-    }
-    document.addEventListener('keydown', onKey)
-    return () => document.removeEventListener('keydown', onKey)
-  }, [goToday, goNext, goPrev])
+  // The calendar's keys. Which key does what, and whether it may fire (not
+  // while typing, not over a dialog), is the shortcut registry's business.
+  useShortcut('calendar.day', () => setView('day'))
+  useShortcut('calendar.week', () => setView('week'))
+  useShortcut('calendar.month', () => setView('month'))
+  useShortcut('calendar.year', () => setView('year'))
+  useShortcut('calendar.schedule', () => setView('schedule'))
+  useShortcut('calendar.fourDays', () => setView('fourDays'))
+  useShortcut('calendar.today', goToday)
+  useShortcut('calendar.next', goNext)
+  useShortcut('calendar.previous', goPrev)
 
   // ── Creating things ────────────────────────────────────────────────────
   const openWorkOrderPicker = useCallback((query?: Record<string, string>) => {

+ 7 - 9
src/features/calendar/Components/CalendarToolbar.tsx

@@ -1,5 +1,6 @@
 'use client'
 
+import { useShortcutKey } from '@/features/shortcuts/Components/ShortcutsProvider'
 import { useTranslations } from 'next-intl'
 import {
   Bell,
@@ -33,14 +34,11 @@ import type { CalendarPreferences } from './useCalendarPreferences'
 
 export type CreateKind = 'workOrder' | 'appointment' | 'reminder' | 'quote' | 'message' | 'timeOff'
 
-/** The keys the view switcher shows and the keyboard listens for. */
-export const VIEW_SHORTCUTS: Record<CalendarView, string> = {
-  day: 'D',
-  week: 'W',
-  month: 'M',
-  year: 'Y',
-  schedule: 'A',
-  fourDays: 'X',
+/** The key that switches to a view, from the shortcut registry, so a changed key reads changed. */
+function ViewShortcut({ view }: { view: CalendarView }) {
+  const shortcut = useShortcutKey(`calendar.${view}`)
+  if (!shortcut) return null
+  return <DropdownMenuShortcut>{shortcut.text}</DropdownMenuShortcut>
 }
 
 const VIEW_ORDER: CalendarView[] = ['day', 'week', 'month', 'year', 'schedule', 'fourDays']
@@ -148,7 +146,7 @@ export function CalendarToolbar({
               {VIEW_ORDER.map((v) => (
                 <DropdownMenuRadioItem key={v} value={v}>
                   {t(`views.${v}`)}
-                  <DropdownMenuShortcut>{VIEW_SHORTCUTS[v]}</DropdownMenuShortcut>
+                  <ViewShortcut view={v} />
                 </DropdownMenuRadioItem>
               ))}
             </DropdownMenuRadioGroup>

+ 42 - 8
src/features/search/Components/SearchCommand.tsx

@@ -13,6 +13,7 @@ import {
   type LucideIcon,
   Package,
   Plug,
+  Keyboard,
   ScanLine,
   Search,
   Users,
@@ -47,6 +48,10 @@ import {
   splitByRanges,
 } from '@/features/search/Lib/matcher'
 import { pushRecent, readRecent, type RecentPick } from '@/features/search/Lib/recent'
+import { SEARCH_OPEN_EVENT } from '@/features/search/Lib/open'
+import { useShortcut, useShortcuts } from '@/features/shortcuts/Components/ShortcutsProvider'
+import { ShortcutKeys } from '@/features/shortcuts/Components/ShortcutKeys'
+import { SHORTCUTS_HELP_COMMAND, shortcutForCommand } from '@/features/shortcuts/Lib/registry'
 import { searchFaultCodes } from '@/features/fault-codes/Actions/searchFaultCodes'
 import {
   isManufacturerCode,
@@ -228,6 +233,12 @@ function Highlight({ text, ranges }: { text: string; ranges: Range[] }) {
   )
 }
 
+/** The shortcut for a page or an action, on the right of its row. */
+function LocalShortcut({ id }: { id: string }) {
+  const shortcut = shortcutForCommand(id)
+  return shortcut ? <ShortcutKeys id={shortcut.id} /> : null
+}
+
 function Kbd({ children }: { children: ReactNode }) {
   return (
     <kbd className="pointer-events-none inline-flex h-5 min-w-5 items-center justify-center rounded border bg-muted px-1 font-mono text-[10px] font-medium text-muted-foreground">
@@ -342,6 +353,8 @@ export function SearchCommand({
   const tIntegrations = useTranslations('integrations')
   const tTire = useTranslations('tireHotel')
   const tPlate = useTranslations('vehicles.plateLookup')
+  const tShortcuts = useTranslations('settings.shortcuts')
+  const { openHelp: openShortcutsHelp } = useShortcuts()
   const tFault = useTranslations('faultCodes.search')
   const tCodes = useTranslations('faultCodes')
   const typeKeyEnabled = useTypeKeyEnabled()
@@ -422,6 +435,24 @@ export function SearchCommand({
       })
     }
 
+    {
+      const title = tShortcuts('help.title')
+      out.push({
+        item: {
+          kind: 'action',
+          id: SHORTCUTS_HELP_COMMAND,
+          href: '#',
+          title,
+          icon: Keyboard,
+          run: openShortcutsHelp,
+        },
+        prepared: prepareItem({
+          title,
+          keywords: ['hotkeys', 'keys', 'shortcut', 'keyboard', 'key bindings', 'cheat sheet'],
+        }),
+      })
+    }
+
     if (canSettings) {
       for (const { item, prepared } of settingsItems) {
         const subtitle = item.description
@@ -476,6 +507,8 @@ export function SearchCommand({
     tSettings,
     tIntegrations,
     tPlate,
+    tShortcuts,
+    openShortcutsHelp,
   ])
 
   const preparedQuery = useMemo(() => prepareQuery(query), [query])
@@ -508,15 +541,13 @@ export function SearchCommand({
     }
   }, [ranked])
 
+  // Opened by its shortcut, and by the header's search box, which has no
+  // other way to reach this component.
+  useShortcut('general.search', () => setOpen((prev) => !prev))
   useEffect(() => {
-    const down = (e: KeyboardEvent) => {
-      if (e.key === 'k' && (e.metaKey || e.ctrlKey)) {
-        e.preventDefault()
-        setOpen((prev) => !prev)
-      }
-    }
-    document.addEventListener('keydown', down)
-    return () => document.removeEventListener('keydown', down)
+    const onOpen = () => setOpen(true)
+    document.addEventListener(SEARCH_OPEN_EVENT, onOpen)
+    return () => document.removeEventListener(SEARCH_OPEN_EVENT, onOpen)
   }, [])
 
   // On opening: forget what the server said last time (records change), read
@@ -722,6 +753,7 @@ export function SearchCommand({
             subtitle={item.subtitle}
             locked={item.locked}
             proLabel={t('pro')}
+            trailing={<LocalShortcut id={item.id} />}
           />
         ))}
       </CommandGroup>
@@ -785,6 +817,7 @@ export function SearchCommand({
                   subtitle={item.subtitle}
                   locked={item.locked}
                   proLabel={t('pro')}
+                  trailing={<LocalShortcut id={item.id} />}
                 />
               ) : (
                 <Row
@@ -833,6 +866,7 @@ export function SearchCommand({
                   icon={item.icon}
                   title={item.title}
                   subtitle={item.subtitle}
+                  trailing={<LocalShortcut id={item.id} />}
                 />
               ))}
           </CommandGroup>

+ 7 - 0
src/features/search/Lib/open.ts

@@ -0,0 +1,7 @@
+/** The event the header's search box fires; the palette listens for it. */
+export const SEARCH_OPEN_EVENT = 'torqvoice:search-open'
+
+/** Opens the search palette from anywhere on the page. */
+export function openSearch() {
+  document.dispatchEvent(new CustomEvent(SEARCH_OPEN_EVENT))
+}

+ 2 - 0
src/features/settings/Lib/searchIndex/index.ts

@@ -16,6 +16,7 @@ import { localizationEntries } from './localization'
 import { maintenanceEntries } from './maintenance'
 import { paymentEntries } from './payment'
 import { reportScheduleEntries } from './reportSchedule'
+import { shortcutsEntries } from './shortcuts'
 import { subscriptionEntries } from './subscription'
 import { supportEntries } from './support'
 import { taxEntries } from './tax'
@@ -44,6 +45,7 @@ export const SETTINGS_SEARCH_INDEX: readonly SettingsEntry[] = [
   ...teamEntries,
   ...localizationEntries,
   ...appearanceEntries,
+  ...shortcutsEntries,
   ...supportEntries,
   ...invoiceEntries,
   ...templatesEntries,

+ 48 - 0
src/features/settings/Lib/searchIndex/shortcuts.ts

@@ -0,0 +1,48 @@
+import type { SettingsEntry } from './types'
+
+/** Keyboard shortcuts: the person's own keys, saved to their account. */
+export const shortcutsEntries: SettingsEntry[] = [
+  {
+    id: 'shortcuts.enable',
+    page: 'shortcuts',
+    title: 'shortcuts.enableLabel',
+    description: 'shortcuts.enableHint',
+    anchor: 'shortcuts-enabled',
+    keywords: ['hotkeys', 'keyboard', 'keys', 'turn off shortcuts', 'disable shortcuts'],
+  },
+  {
+    id: 'shortcuts.singleKeys',
+    page: 'shortcuts',
+    title: 'shortcuts.singleKeysLabel',
+    description: 'shortcuts.singleKeysHint',
+    anchor: 'shortcuts-single-keys',
+    keywords: ['single key', 'letter keys', 'voice control', 'accessibility', 'calendar keys'],
+  },
+  {
+    id: 'shortcuts.goToSequences',
+    page: 'shortcuts',
+    title: 'shortcuts.goToSequencesLabel',
+    description: 'shortcuts.goToSequencesHint',
+    anchor: 'shortcuts-go-to-sequences',
+    // Plain words: search has no keyboard to hand, so it names the Windows keys.
+    values: { prefix: 'Alt+G', example: 'Alt+G, Alt+W', workOrders: 'Work orders' },
+    keywords: ['alt g', 'go to page', 'navigation keys', 'open page', 'sequence', 'jump to'],
+  },
+  {
+    id: 'shortcuts.all',
+    page: 'shortcuts',
+    title: 'shortcuts.allTitle',
+    description: 'shortcuts.allHint',
+    anchor: 'shortcuts-all',
+    keywords: [
+      'change shortcut',
+      'rebind',
+      'key binding',
+      'keybinding',
+      'hotkey',
+      'customize keys',
+      'reset shortcuts',
+      'new work order key',
+    ],
+  },
+]

+ 2 - 0
src/features/settings/Lib/settingsPageIcons.ts

@@ -14,6 +14,7 @@ import {
   Globe,
   Info,
   Key,
+  Keyboard,
   Layout,
   LifeBuoy,
   ListChecks,
@@ -39,6 +40,7 @@ export const SETTINGS_PAGE_ICONS: Record<SettingsPageKey, LucideIcon> = {
   team: UsersRound,
   localization: Globe,
   appearance: Palette,
+  shortcuts: Keyboard,
   support: LifeBuoy,
   invoice: FileText,
   templates: Layout,

+ 2 - 0
src/features/settings/Lib/settingsPages.ts

@@ -15,6 +15,7 @@ export type SettingsPageKey =
   | 'team'
   | 'localization'
   | 'appearance'
+  | 'shortcuts'
   | 'support'
   | 'invoice'
   | 'templates'
@@ -78,6 +79,7 @@ export const SETTINGS_PAGES: SettingsPage[] = [
   { key: 'team', href: '/settings/team', category: 'general' },
   { key: 'localization', href: '/settings/localization', category: 'general' },
   { key: 'appearance', href: '/settings/appearance', category: 'general' },
+  { key: 'shortcuts', href: '/settings/shortcuts', category: 'general' },
   { key: 'support', href: '/settings/support', category: 'general', supportOnly: true },
 
   { key: 'invoice', href: '/settings/invoice', category: 'billing' },

+ 31 - 0
src/features/shortcuts/Actions/saveKeyboardShortcuts.ts

@@ -0,0 +1,31 @@
+'use server'
+
+import { Prisma } from '@/generated/prisma/client'
+import { db } from '@/lib/db'
+import { withAuth } from '@/lib/with-auth'
+import {
+  isDefaultShortcutPrefs,
+  normalizeShortcutPrefs,
+  type ShortcutPrefs,
+} from '../Lib/preferences'
+import { shortcutPrefsSchema } from '../Schema/preferences'
+
+/**
+ * Saves the signed-in person's keyboard shortcuts. They belong to the person,
+ * not the workshop, so the row is found by the session's user and nothing
+ * here depends on a role. Back to every default clears the column.
+ */
+export async function saveKeyboardShortcuts(input: unknown) {
+  return withAuth<ShortcutPrefs>(async (ctx) => {
+    const prefs = normalizeShortcutPrefs(shortcutPrefsSchema.parse(input))
+    await db.user.update({
+      where: { id: ctx.userId },
+      data: {
+        keyboardShortcuts: isDefaultShortcutPrefs(prefs)
+          ? Prisma.DbNull
+          : (prefs as unknown as Prisma.InputJsonValue),
+      },
+    })
+    return prefs
+  })
+}

+ 67 - 0
src/features/shortcuts/Components/ShortcutKeys.tsx

@@ -0,0 +1,67 @@
+'use client'
+
+import { Fragment } from 'react'
+import { useTranslations } from 'next-intl'
+import { cn } from '@/lib/utils'
+import { type Combo, comboParts, comboSteps } from '../Lib/keys'
+import { useShortcutKey, useShortcuts } from './ShortcutsProvider'
+
+/** One key cap, the same chip the search palette draws. */
+export function KeyCap({ children, className }: { children: React.ReactNode; className?: string }) {
+  return (
+    <kbd
+      className={cn(
+        'pointer-events-none inline-flex h-5 min-w-5 items-center justify-center rounded border bg-muted px-1 font-mono text-[10px] font-medium text-muted-foreground',
+        className
+      )}
+    >
+      {children}
+    </kbd>
+  )
+}
+
+/**
+ * A combo as key caps, drawn the same way wherever a key is shown: the menus,
+ * the palette, the help overlay and the settings page. A sequence reads
+ * "G then W".
+ */
+export function ComboCaps({
+  combo,
+  className,
+  capClassName,
+}: {
+  combo: Combo
+  className?: string
+  capClassName?: string
+}) {
+  const { platform } = useShortcuts()
+  const t = useTranslations('settings.shortcuts')
+  return (
+    <span className={cn('inline-flex items-center gap-0.5 whitespace-nowrap', className)}>
+      {comboSteps(combo).map((step, index) => (
+        // By position: Alt+G, then Alt+G again, is a real sequence (the dashboard).
+        <Fragment key={`${index}:${step}`}>
+          {index > 0 && (
+            <span className="px-0.5 font-sans text-[11px] text-muted-foreground">{t('then')}</span>
+          )}
+          {comboParts(step, platform).map((part) => (
+            <KeyCap key={part} className={capClassName}>
+              {part}
+            </KeyCap>
+          ))}
+        </Fragment>
+      ))}
+    </span>
+  )
+}
+
+/**
+ * The key for a shortcut, beside the thing it does: a menu item, a tooltip,
+ * a palette row. Draws nothing when the shortcut is off, has no key or is not
+ * this person's to use, and nothing on a phone, where there is no keyboard.
+ */
+export function ShortcutKeys({ id, className }: { id: string; className?: string }) {
+  const key = useShortcutKey(id)
+  if (!key) return null
+  return <ComboCaps combo={key.combo} className={cn('max-md:hidden', className)} />
+}

+ 157 - 0
src/features/shortcuts/Components/ShortcutsHelpDialog.tsx

@@ -0,0 +1,157 @@
+'use client'
+
+import { Fragment, useMemo, useState } from 'react'
+import Link from 'next/link'
+import { useTranslations } from 'next-intl'
+import { Search } from 'lucide-react'
+import { Button } from '@/components/ui/button'
+import {
+  Dialog,
+  DialogBody,
+  DialogContent,
+  DialogDescription,
+  DialogFooter,
+  DialogHeader,
+  DialogTitle,
+} from '@/components/ui/dialog'
+import { Input } from '@/components/ui/input'
+import { activeKeys } from '../Lib/preferences'
+import { SHORTCUT_GROUPS, SHORTCUTS, type ShortcutGroup } from '../Lib/registry'
+import { ComboCaps } from './ShortcutKeys'
+import { useShortcutLabel, useShortcuts } from './ShortcutsProvider'
+
+type Row = { id: string; label: string; keys: string[] }
+
+/**
+ * Every shortcut this person can use, with the keys they have now rather
+ * than the ones the app shipped with. Opened by its own shortcut, from the
+ * account menu and from the search palette.
+ */
+export function ShortcutsHelpDialog({
+  open,
+  onOpenChange,
+}: {
+  open: boolean
+  onOpenChange: (open: boolean) => void
+}) {
+  const t = useTranslations('settings.shortcuts')
+  const { prefs, isVisible, canCustomize } = useShortcuts()
+  const labelOf = useShortcutLabel()
+  const [query, setQuery] = useState('')
+
+  const groups = useMemo(() => {
+    const needle = query.trim().toLowerCase()
+    const out: { key: ShortcutGroup | 'fixed'; rows: Row[] }[] = []
+    for (const group of SHORTCUT_GROUPS) {
+      const rows: Row[] = []
+      for (const def of SHORTCUTS) {
+        if (def.group !== group || !isVisible(def)) continue
+        const keys = activeKeys(def, prefs)
+        if (keys.length === 0) continue
+        const label = labelOf(def)
+        if (needle && !label.toLowerCase().includes(needle)) continue
+        rows.push({ id: def.id, label, keys })
+      }
+      if (rows.length > 0) out.push({ key: group, rows })
+    }
+    // Keys every list and photo viewer answers to. They are how those widgets
+    // work rather than shortcuts, so they are told here and not offered for change.
+    const fixed: Row[] = [
+      {
+        id: 'fixed.listMove',
+        label: t('help.listMove'),
+        keys: ['arrowup', 'arrowdown', 'home', 'end'],
+      },
+      { id: 'fixed.listOpen', label: t('help.listOpen'), keys: ['enter'] },
+      { id: 'fixed.photos', label: t('help.photos'), keys: ['arrowleft', 'arrowright'] },
+      { id: 'fixed.close', label: t('help.close'), keys: ['escape'] },
+    ].filter((row) => !needle || row.label.toLowerCase().includes(needle))
+    if (fixed.length > 0) out.push({ key: 'fixed', rows: fixed })
+    return out
+  }, [query, prefs, isVisible, labelOf, t])
+
+  return (
+    <Dialog
+      open={open}
+      onOpenChange={(next) => {
+        if (!next) setQuery('')
+        onOpenChange(next)
+      }}
+    >
+      <DialogContent className="sm:max-w-3xl">
+        <DialogHeader>
+          <DialogTitle>{t('help.title')}</DialogTitle>
+          <DialogDescription>
+            {prefs.enabled ? t('help.description') : t('help.disabledNote')}
+          </DialogDescription>
+        </DialogHeader>
+        <DialogBody className="space-y-4">
+          <div className="relative">
+            <Search
+              aria-hidden
+              className="pointer-events-none absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 text-muted-foreground"
+            />
+            <Input
+              value={query}
+              onChange={(e) => setQuery(e.target.value)}
+              placeholder={t('help.find')}
+              aria-label={t('help.find')}
+              className="pl-9"
+            />
+          </div>
+          {groups.length === 0 ? (
+            <p className="py-6 text-center text-sm text-muted-foreground" role="status">
+              {t('help.noMatch')}
+            </p>
+          ) : (
+            <div className="gap-x-8 md:columns-2">
+              {groups.map((group) => (
+                <section key={group.key} className="mb-5 break-inside-avoid">
+                  <h3 className="mb-1 flex items-baseline gap-2 text-xs font-semibold tracking-wide text-muted-foreground uppercase">
+                    {t(`groups.${group.key}`)}
+                    {(group.key === 'calendar' || group.key === 'fixed') && (
+                      <span className="font-normal tracking-normal normal-case">
+                        {t(group.key === 'calendar' ? 'scopes.calendar' : 'help.fixedHint')}
+                      </span>
+                    )}
+                  </h3>
+                  <dl className="divide-y divide-dashed">
+                    {group.rows.map((row) => (
+                      <div
+                        key={row.id}
+                        className="flex items-center justify-between gap-3 py-1.5 text-sm"
+                      >
+                        <dt className="min-w-0">{row.label}</dt>
+                        <dd className="flex shrink-0 items-center gap-1">
+                          {row.keys.map((combo, index) => (
+                            <Fragment key={combo}>
+                              {index > 0 && group.key !== 'fixed' && (
+                                <span className="text-xs text-muted-foreground">{t('or')}</span>
+                              )}
+                              <ComboCaps combo={combo} capClassName="text-foreground" />
+                            </Fragment>
+                          ))}
+                        </dd>
+                      </div>
+                    ))}
+                  </dl>
+                </section>
+              ))}
+            </div>
+          )}
+        </DialogBody>
+        {/* A custom role without settings access is turned away from every
+            settings page, this one included, so the link would lead nowhere. */}
+        {canCustomize && (
+          <DialogFooter>
+            <Button asChild variant="outline">
+              <Link href="/settings/shortcuts" onClick={() => onOpenChange(false)}>
+                {t('help.customize')}
+              </Link>
+            </Button>
+          </DialogFooter>
+        )}
+      </DialogContent>
+    </Dialog>
+  )
+}

+ 409 - 0
src/features/shortcuts/Components/ShortcutsProvider.tsx

@@ -0,0 +1,409 @@
+'use client'
+
+import {
+  createContext,
+  useCallback,
+  useContext,
+  useEffect,
+  useMemo,
+  useRef,
+  useState,
+  type ReactNode,
+} from 'react'
+import { useRouter } from 'next/navigation'
+import { useTranslations } from 'next-intl'
+import { toast } from 'sonner'
+import { useServiceType } from '@/components/service-type-context'
+import {
+  canAccessSubject,
+  type CommandContext,
+  visibleActionCommands,
+  visiblePageCommands,
+} from '@/features/search/Lib/commands'
+import { saveKeyboardShortcuts } from '../Actions/saveKeyboardShortcuts'
+import {
+  type Combo,
+  combosFromEvent,
+  comboText,
+  currentPlatform,
+  detectPlatform,
+  isLayerOpen,
+  claimsPlainKeys,
+  isLoneModifier,
+  isCharacterKey,
+  type Platform,
+} from '../Lib/keys'
+import {
+  activeKeys,
+  DEFAULT_SHORTCUT_PREFS,
+  matchShortcut,
+  startsSequence,
+  normalizeShortcutPrefs,
+  type ShortcutPrefs,
+} from '../Lib/preferences'
+import { type ShortcutDef, shortcutById } from '../Lib/registry'
+import { ShortcutsHelpDialog } from './ShortcutsHelpDialog'
+
+type Handler = () => void
+
+/** How long the first key of a sequence waits for the second. */
+const SEQUENCE_WINDOW_MS = 1500
+
+/**
+ * Characters closer together than this are a scanner, not a person. The
+ * app's own scanner detection (hooks/use-hardware-scanner.ts) calls a scan
+ * anything averaging under 80 ms a key; a person pressing G then W on
+ * purpose is slower than 50 ms, and a scanner is a good deal faster.
+ */
+const SCANNER_BURST_MS = 50
+
+/** After a key went into a field or a dialog, bare keys wait this long. */
+const QUIET_AFTER_TYPING_MS = 500
+
+type ShortcutsContextValue = {
+  prefs: ShortcutPrefs
+  /** For drawing key caps. 'other' until the browser has said what it is. */
+  platform: Platform
+  /** Applies at once and saves in the background; a failed save is undone. */
+  updatePrefs: (next: ShortcutPrefs) => void
+  /** This person may use it: their role, their plan and the modules that are on. */
+  isVisible: (def: ShortcutDef) => boolean
+  /** The settings page is theirs to open: it sits behind the settings gate. */
+  canCustomize: boolean
+  register: (id: string, handler: Handler) => () => void
+  openHelp: () => void
+  /** While the settings page records a key, nothing else answers the keyboard. */
+  setRecording: (recording: boolean) => void
+  isRecording: () => boolean
+}
+
+const noop = () => undefined
+
+// Outside the provider (the designers, tests) everything is a default and
+// nothing can be changed.
+const ShortcutsContext = createContext<ShortcutsContextValue>({
+  prefs: DEFAULT_SHORTCUT_PREFS,
+  platform: 'other',
+  updatePrefs: noop,
+  isVisible: () => true,
+  canCustomize: false,
+  register: () => noop,
+  openHelp: noop,
+  setRecording: noop,
+  isRecording: () => false,
+})
+
+export function useShortcuts() {
+  return useContext(ShortcutsContext)
+}
+
+/**
+ * The one keyboard listener of the signed-in app. Every shortcut in the
+ * registry is matched here; a screen says what its shortcuts do with
+ * `useShortcut`, and a shortcut that only opens a page needs no screen at all.
+ */
+export function ShortcutsProvider({
+  initialPrefs,
+  commands,
+  plateLookupAvailable,
+  children,
+}: {
+  /** User.keyboardShortcuts as stored. */
+  initialPrefs: unknown
+  /** What the search palette is told about this person, for the same reason. */
+  commands: CommandContext
+  plateLookupAvailable: boolean
+  children: ReactNode
+}) {
+  const router = useRouter()
+  const t = useTranslations('settings.shortcuts')
+  const [prefs, setPrefs] = useState(() => normalizeShortcutPrefs(initialPrefs))
+  const [platform, setPlatform] = useState<Platform>('other')
+  const [helpOpen, setHelpOpen] = useState(false)
+  const handlers = useRef(new Map<string, Handler[]>())
+  const recording = useRef(false)
+  const pending = useRef<{ combo: Combo; at: number } | null>(null)
+  const deferred = useRef<number | null>(null)
+  const lastKeyAt = useRef(0)
+  const lastClaimedAt = useRef(0)
+  const prefsRef = useRef(prefs)
+  prefsRef.current = prefs
+
+  useEffect(() => setPlatform(detectPlatform()), [])
+
+  const visibleCommands = useMemo(
+    () =>
+      new Set([
+        ...visiblePageCommands(commands).map((page) => page.id),
+        ...visibleActionCommands(commands).map((action) => action.id),
+      ]),
+    [commands]
+  )
+
+  const isVisible = useCallback(
+    (def: ShortcutDef) => {
+      if (def.id === 'general.plateLookup') return plateLookupAvailable
+      if (def.command) return visibleCommands.has(def.command)
+      if (def.subject) return canAccessSubject(commands, def.subject)
+      return true
+    },
+    [visibleCommands, commands, plateLookupAvailable]
+  )
+
+  const canCustomize = canAccessSubject(commands, 'settings')
+
+  const register = useCallback((id: string, handler: Handler) => {
+    const list = handlers.current.get(id) ?? []
+    handlers.current.set(id, [...list, handler])
+    return () => {
+      const rest = (handlers.current.get(id) ?? []).filter((h) => h !== handler)
+      if (rest.length > 0) handlers.current.set(id, rest)
+      else handlers.current.delete(id)
+    }
+  }, [])
+
+  // Saves run one after another, so a slow early one cannot land on top of a
+  // later choice. A save that fails goes back to what the server last took,
+  // and only when nothing newer is waiting: a later choice that is still on
+  // its way stays on screen and settles itself.
+  const saving = useRef<Promise<unknown>>(Promise.resolve())
+  const saved = useRef(prefs)
+  const latestSave = useRef(0)
+  const updatePrefs = useCallback(
+    (next: ShortcutPrefs) => {
+      const ticket = ++latestSave.current
+      setPrefs(next)
+      saving.current = saving.current
+        .then(() => saveKeyboardShortcuts(next))
+        .then((result) => {
+          if (!result.success) throw new Error(result.error)
+          saved.current = next
+        })
+        .catch(() => {
+          if (ticket === latestSave.current) setPrefs(saved.current)
+          toast.error(t('saveFailed'))
+        })
+    },
+    [t]
+  )
+  const openHelp = useCallback(() => setHelpOpen(true), [])
+
+  useEffect(() => {
+    // Opening a page goes through a click on a real link, not straight to
+    // the router. The work order page holds an unsaved job back by catching
+    // link clicks (save first, then let the click through), and a shortcut
+    // must be held back the same way a click on the sidebar is. A page with
+    // no such guard treats the shortcut exactly as it treats that click.
+    const link = document.createElement('a')
+    link.hidden = true
+    link.tabIndex = -1
+    link.setAttribute('aria-hidden', 'true')
+    link.dataset.shortcutLink = ''
+    const follow = (event: MouseEvent) => {
+      event.preventDefault()
+      const href = link.getAttribute('href')
+      if (href) router.push(href)
+    }
+    link.addEventListener('click', follow)
+    document.body.appendChild(link)
+
+    const run = (def: ShortcutDef) => {
+      const handler = handlers.current.get(def.id)?.at(-1)
+      if (handler) {
+        handler()
+      } else if (def.href) {
+        link.setAttribute('href', def.href)
+        link.click()
+      }
+    }
+    const forget = () => {
+      pending.current = null
+      if (deferred.current !== null) window.clearTimeout(deferred.current)
+      deferred.current = null
+    }
+
+    const onKey = (e: KeyboardEvent) => {
+      // Alt going down on its way to a chord is not a key press of its own:
+      // Alt+G, let go, Alt+W is still one sequence.
+      if (isLoneModifier(e)) return
+      const now = Date.now()
+      const sincePrevious = now - lastKeyAt.current
+      if (!e.repeat) lastKeyAt.current = now
+      // Whatever was waiting (the first key of a sequence, a letter held
+      // back to see whether a scanner is typing) is settled by this key.
+      const first = pending.current
+      const wasDeferred = deferred.current !== null
+      forget()
+
+      // Alt+G held long enough to repeat is still one Alt+G.
+      if (e.repeat && first && combosFromEvent(e, currentPlatform()).includes(first.combo)) {
+        pending.current = first
+        e.preventDefault()
+        return
+      }
+
+      if (e.defaultPrevented || e.isComposing || e.keyCode === 229 || recording.current) return
+      const combos = combosFromEvent(e, currentPlatform())
+      if (combos.length === 0) return
+
+      // A bare key is a shortcut only when nothing else wants it: no field,
+      // no list or menu that uses letters, no dialog or dropdown open, and
+      // none of those in the last moment, so a sentence that outlives its
+      // dialog or its field's focus does not turn into commands.
+      const claimed = claimsPlainKeys(e)
+      const layerOpen = isLayerOpen()
+      if (claimed || layerOpen) lastClaimedAt.current = now
+      const ctx = {
+        prefs: prefsRef.current,
+        typing: claimed || now - lastClaimedAt.current < QUIET_AFTER_TYPING_MS,
+        layerOpen,
+        available: (candidate: ShortcutDef) =>
+          isVisible(candidate) && (handlers.current.has(candidate.id) || !!candidate.href),
+      }
+
+      const character = isCharacterKey(combos[0])
+      // A barcode scanner types like a keyboard, only far faster than a
+      // person, and often with no field focused. Characters that arrive in
+      // such a burst are a scan, never a shortcut.
+      const burst = character && !e.repeat && (sincePrevious < SCANNER_BURST_MS || wasDeferred)
+      if (burst) return
+
+      const sequence =
+        first && !e.repeat && now - first.at < SEQUENCE_WINDOW_MS
+          ? combos.map((combo) => `${first.combo} ${combo}`)
+          : []
+      const def = matchShortcut([...sequence, ...combos], ctx)
+      if (!def) {
+        const start = e.repeat ? undefined : combos.find((combo) => startsSequence(combo, ctx))
+        if (start) {
+          pending.current = { combo: start, at: now }
+          e.preventDefault()
+        }
+        return
+      }
+      e.preventDefault()
+      if (e.repeat) {
+        // Holding the key down pages through the calendar; it should not
+        // open the same dialog ten times.
+        if (def.scope !== 'global') run(def)
+        return
+      }
+      if (character) {
+        // Held back for a moment: if more characters follow at once, it was
+        // the start of a scan and the next key cancels it.
+        deferred.current = window.setTimeout(() => {
+          deferred.current = null
+          run(def)
+        }, SCANNER_BURST_MS)
+        return
+      }
+      run(def)
+    }
+    // A click or a tap between two keys is a change of mind.
+    document.addEventListener('keydown', onKey)
+    document.addEventListener('pointerdown', forget, true)
+    window.addEventListener('blur', forget)
+    return () => {
+      forget()
+      link.removeEventListener('click', follow)
+      link.remove()
+      document.removeEventListener('keydown', onKey)
+      document.removeEventListener('pointerdown', forget, true)
+      window.removeEventListener('blur', forget)
+    }
+  }, [isVisible, router])
+
+  const value = useMemo<ShortcutsContextValue>(
+    () => ({
+      prefs,
+      platform,
+      updatePrefs,
+      isVisible,
+      canCustomize,
+      register,
+      openHelp,
+      setRecording: (on) => {
+        recording.current = on
+      },
+      isRecording: () => recording.current,
+    }),
+    [prefs, platform, updatePrefs, isVisible, canCustomize, register, openHelp]
+  )
+
+  return (
+    <ShortcutsContext.Provider value={value}>
+      <HelpShortcut onOpen={openHelp} />
+      {children}
+      <ShortcutsHelpDialog open={helpOpen} onOpenChange={setHelpOpen} />
+    </ShortcutsContext.Provider>
+  )
+}
+
+function HelpShortcut({ onOpen }: { onOpen: () => void }) {
+  useShortcut('general.help', onOpen)
+  return null
+}
+
+/**
+ * Says what a shortcut does while this component is on screen. The newest
+ * screen to claim a shortcut is the one that answers it.
+ */
+export function useShortcut(id: string, handler: Handler, enabled = true) {
+  const { register } = useShortcuts()
+  const latest = useRef(handler)
+  latest.current = handler
+  useEffect(() => {
+    if (!enabled) return
+    return register(id, () => latest.current())
+  }, [id, enabled, register])
+}
+
+/**
+ * For the few listeners that must stay where they are in the DOM (saving,
+ * which goes dialog first, then editor, then page): tells them whether a key
+ * press is their shortcut, by the person's own keys.
+ */
+export function useShortcutMatcher(id: string): (e: KeyboardEvent) => boolean {
+  const { prefs, isRecording } = useShortcuts()
+  const prefsRef = useRef(prefs)
+  prefsRef.current = prefs
+  return useCallback(
+    (e: KeyboardEvent) => {
+      const def = shortcutById(id)
+      if (!def || isRecording()) return false
+      const keys = activeKeys(def, prefsRef.current)
+      return combosFromEvent(e, currentPlatform()).some((combo) => keys.includes(combo))
+    },
+    [id, isRecording]
+  )
+}
+
+/** The key that fires a shortcut right now, with its words for a tooltip, or null. */
+export function useShortcutKey(id: string): { combo: Combo; text: string } | null {
+  const { prefs, platform, isVisible } = useShortcuts()
+  const t = useTranslations('settings.shortcuts')
+  const def = shortcutById(id)
+  if (!def || !isVisible(def)) return null
+  const combo = activeKeys(def, prefs)[0]
+  if (!combo) return null
+  return { combo, text: comboText(combo, platform, t('then')) }
+}
+
+/** Names a shortcut in the reader's language. */
+export function useShortcutLabel(): (def: ShortcutDef) => string {
+  const tShortcuts = useTranslations('settings.shortcuts.actions')
+  const tSidebar = useTranslations('navigation.sidebar')
+  const tSearch = useTranslations('search.actions')
+  const marine = useServiceType() === 'marine'
+  return useCallback(
+    (def: ShortcutDef) => {
+      const { label } = def
+      if (label.from === 'sidebar') {
+        return tSidebar(marine && label.marineKey ? label.marineKey : label.key)
+      }
+      if (label.from === 'search') return tSearch(label.key)
+      return tShortcuts(label.key)
+    },
+    [tShortcuts, tSidebar, tSearch, marine]
+  )
+}

+ 417 - 0
src/features/shortcuts/Components/ShortcutsSettings.tsx

@@ -0,0 +1,417 @@
+'use client'
+
+import { Fragment, useEffect, useRef, useState } from 'react'
+import { useTranslations } from 'next-intl'
+import { Command, Keyboard, RotateCcw, TriangleAlert } from 'lucide-react'
+import { AppCard } from '@/components/app-card'
+import { useConfirm } from '@/components/confirm-dialog'
+import { Button } from '@/components/ui/button'
+import { Switch } from '@/components/ui/switch'
+import { cn } from '@/lib/utils'
+import { type Combo, comboFromEvent, comboParts, comboText, currentPlatform } from '../Lib/keys'
+import {
+  activeKeys,
+  assignedKeys,
+  assignKey,
+  type ComboProblem,
+  comboProblem,
+  findClash,
+  isChanged,
+  isSwitchedOff,
+  resetKey,
+  setSwitchedOff,
+} from '../Lib/preferences'
+import { SHORTCUT_GROUPS, SHORTCUTS, type ShortcutDef, shortcutById } from '../Lib/registry'
+import { ComboCaps } from './ShortcutKeys'
+import { useShortcutLabel, useShortcuts } from './ShortcutsProvider'
+
+const CAP = 'h-6 min-w-6 px-1.5 text-xs text-foreground'
+
+/** What recording a key ran into, shown under the row until it is settled. */
+type Notice =
+  | { id: string; kind: 'clash'; combo: Combo; other: ShortcutDef }
+  | { id: string; kind: 'problem'; combo: Combo; problem: ComboProblem }
+
+/**
+ * Settings, Keyboard shortcuts: one person's own keys. Every change is saved
+ * as it is made, so there is no Save button to forget.
+ */
+export function ShortcutsSettings() {
+  const t = useTranslations('settings.shortcuts')
+  const { prefs, platform, updatePrefs, isVisible, setRecording } = useShortcuts()
+  const labelOf = useShortcutLabel()
+  const confirm = useConfirm()
+  const [recordingId, setRecordingId] = useState<string | null>(null)
+  const [notice, setNotice] = useState<Notice | null>(null)
+  const [announcement, setAnnouncement] = useState('')
+  const recorder = useRef<HTMLButtonElement>(null)
+
+  const keysText = (combo: Combo) => comboText(combo, platform, t('then'))
+  const searchCombo = activeKeys(shortcutById('general.search') as ShortcutDef, prefs)[0]
+  const searchKeys = searchCombo
+    ? keysText(searchCombo)
+    : labelOf(shortcutById('general.search') as ShortcutDef)
+  // The go-to set in this person's own key names: Alt+G on Windows, ⌃ G on a Mac.
+  const goToWords = {
+    prefix: comboText('alt+g', platform),
+    example: keysText('alt+g alt+w'),
+    workOrders: labelOf(shortcutById('goTo.workOrders') as ShortcutDef),
+  }
+  const modifierNames = {
+    mod: comboParts('mod+a', platform)[0],
+    alt: comboParts('alt+a', platform)[0],
+  }
+
+  // The app's listener stands down while a key is being recorded, or the key
+  // being chosen would also do whatever it does today.
+  useEffect(() => {
+    setRecording(recordingId !== null)
+    if (recordingId) recorder.current?.focus()
+    return () => setRecording(false)
+  }, [recordingId, setRecording])
+
+  const focusChange = (id: string) => {
+    window.setTimeout(() => document.getElementById(`shortcut-change-${id}`)?.focus(), 0)
+  }
+
+  const stopRecording = (id: string) => {
+    setRecordingId(null)
+    focusChange(id)
+  }
+
+  const apply = (def: ShortcutDef, combo: Combo) => {
+    updatePrefs(assignKey(def, combo, prefs))
+    setNotice(null)
+    setAnnouncement(t('announceSet', { action: labelOf(def), keys: keysText(combo) }))
+  }
+
+  const onRecordKey = (def: ShortcutDef, e: React.KeyboardEvent) => {
+    // Tab leaves the recorder, which cancels: nobody is trapped in it.
+    if (e.key === 'Tab') return
+    e.preventDefault()
+    e.stopPropagation()
+    if (e.key === 'Escape') {
+      setNotice(null)
+      stopRecording(def.id)
+      return
+    }
+    const combo = comboFromEvent(e.nativeEvent, currentPlatform())
+    if (!combo) return
+    const problem = comboProblem(def, combo)
+    if (problem) {
+      setNotice({ id: def.id, kind: 'problem', combo, problem })
+      return
+    }
+    if (assignedKeys(def, prefs).length === 1 && assignedKeys(def, prefs)[0] === combo) {
+      setNotice(null)
+      stopRecording(def.id)
+      return
+    }
+    const other = findClash(def, combo, prefs, isVisible)
+    if (other) {
+      setNotice({ id: def.id, kind: 'clash', combo, other })
+      setRecordingId(null)
+      return
+    }
+    apply(def, combo)
+    stopRecording(def.id)
+  }
+
+  const resetAll = async () => {
+    const ok = await confirm({
+      title: t('resetAllTitle'),
+      description: t('resetAllDescription'),
+      confirmLabel: t('resetAll'),
+    })
+    if (!ok) return
+    setNotice(null)
+    updatePrefs({ ...prefs, overrides: {}, disabled: [] })
+    setAnnouncement(t('announceResetAll'))
+  }
+
+  const anythingChanged = Object.keys(prefs.overrides).length > 0 || prefs.disabled.length > 0
+
+  const renderRow = (def: ShortcutDef) => {
+    const label = labelOf(def)
+    const keys = assignedKeys(def, prefs)
+    const off = isSwitchedOff(def, prefs)
+    const changed = isChanged(def, prefs)
+    const recording = recordingId === def.id
+    const rowNotice = notice?.id === def.id ? notice : null
+    // Its own key, then the ones that come with it and cannot be changed here:
+    // the arrows, and its place in "G then a letter" while that set is on.
+    const shown = [
+      ...keys,
+      ...(def.fixedKeys ?? []),
+      ...(def.sequence && prefs.goToSequences ? [def.sequence] : []),
+    ]
+    const duplicate = keys
+      .map((combo) => findClash(def, combo, prefs, isVisible))
+      .find((other) => other !== null)
+
+    return (
+      <li
+        key={def.id}
+        className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-4 gap-y-2 px-5 py-2.5 md:grid-cols-[minmax(0,1fr)_auto_auto_auto]"
+      >
+        <div className={cn('min-w-0 text-sm', off && 'text-muted-foreground')}>
+          <span>{label}</span>
+          {changed && (
+            <span className="ml-2 rounded-full bg-primary/10 px-2 py-0.5 text-[11px] font-medium text-primary">
+              {t('changed')}
+            </span>
+          )}
+          {off && <span className="block text-xs">{t('off')}</span>}
+        </div>
+
+        <div className="col-start-1 row-start-2 flex min-h-8 items-center gap-1.5 md:col-start-2 md:row-start-1 md:justify-end">
+          {recording ? (
+            <button
+              ref={recorder}
+              type="button"
+              aria-label={t('recordingFor', { action: label })}
+              onKeyDown={(e) => onRecordKey(def, e)}
+              onBlur={() => setRecordingId((current) => (current === def.id ? null : current))}
+              className="inline-flex h-8 items-center gap-2 rounded-md border border-dashed border-primary bg-primary/5 px-3 text-sm outline-none focus-visible:ring-[3px] focus-visible:ring-ring-soft"
+            >
+              <span
+                aria-hidden
+                className="h-2 w-2 rounded-full bg-primary motion-safe:animate-pulse"
+              />
+              {t('pressKeys')}
+            </button>
+          ) : shown.length === 0 ? (
+            <span className="text-xs text-muted-foreground">{t('noKey')}</span>
+          ) : (
+            <span className={cn('flex flex-wrap items-center gap-1.5', off && 'opacity-50')}>
+              {shown.map((combo, index) => (
+                <Fragment key={combo}>
+                  {index > 0 && <span className="text-xs text-muted-foreground">{t('or')}</span>}
+                  <ComboCaps combo={combo} capClassName={CAP} />
+                </Fragment>
+              ))}
+            </span>
+          )}
+        </div>
+
+        <div className="col-start-2 row-start-2 flex items-center justify-end gap-1 md:col-start-3 md:row-start-1">
+          {recording ? (
+            // Pressed with the mouse: the recorder's blur has already cancelled.
+            <Button type="button" variant="outline" size="sm" onClick={() => setNotice(null)}>
+              {t('cancel')}
+            </Button>
+          ) : (
+            <>
+              {changed && (
+                <Button
+                  type="button"
+                  variant="ghost"
+                  size="sm"
+                  aria-label={t('resetFor', { action: label })}
+                  title={
+                    def.defaultKeys.length > 0
+                      ? t('resetTo', { keys: def.defaultKeys.map(keysText).join(', ') })
+                      : t('resetToNone')
+                  }
+                  onClick={() => {
+                    setNotice(null)
+                    updatePrefs(resetKey(def, prefs))
+                    setAnnouncement(t('announceReset', { action: label }))
+                  }}
+                >
+                  <RotateCcw aria-hidden className="h-3.5 w-3.5" />
+                  {t('reset')}
+                </Button>
+              )}
+              <Button
+                id={`shortcut-change-${def.id}`}
+                type="button"
+                variant="outline"
+                size="sm"
+                aria-label={t('changeFor', { action: label })}
+                onClick={() => {
+                  setNotice(null)
+                  setRecordingId(def.id)
+                }}
+              >
+                {t('change')}
+              </Button>
+            </>
+          )}
+        </div>
+
+        <Switch
+          className="col-start-2 row-start-1 justify-self-end md:col-start-4"
+          checked={!off}
+          disabled={!prefs.enabled}
+          aria-label={t('switchFor', { action: label })}
+          onCheckedChange={(on) => updatePrefs(setSwitchedOff(def, !on, prefs))}
+        />
+
+        {rowNotice?.kind === 'clash' && (
+          <div
+            role="alert"
+            // A row near the bottom of the window would otherwise ask its
+            // question out of sight.
+            ref={(el) => {
+              el?.scrollIntoView?.({ block: 'nearest' })
+            }}
+            className="col-span-full flex flex-wrap items-center gap-x-3 gap-y-2 rounded-md border border-primary/40 bg-primary/5 px-3 py-2 text-sm"
+          >
+            <TriangleAlert aria-hidden className="h-4 w-4 shrink-0 text-primary" />
+            <span className="min-w-48 flex-1">
+              {t('clash', { keys: keysText(rowNotice.combo), action: labelOf(rowNotice.other) })}
+            </span>
+            <Button
+              type="button"
+              size="sm"
+              onClick={() => {
+                apply(def, rowNotice.combo)
+                focusChange(def.id)
+              }}
+            >
+              {t('useHere')}
+            </Button>
+            <Button
+              type="button"
+              size="sm"
+              variant="outline"
+              onClick={() => {
+                setNotice(null)
+                setRecordingId(def.id)
+              }}
+            >
+              {t('pickAnother')}
+            </Button>
+          </div>
+        )}
+        {rowNotice?.kind === 'problem' && (
+          <p role="alert" className="col-span-full text-sm text-destructive">
+            {t(`problems.${rowNotice.problem}`, {
+              keys: keysText(rowNotice.combo),
+              ...modifierNames,
+            })}
+          </p>
+        )}
+        {!rowNotice && duplicate && (
+          <p className="col-span-full text-xs text-muted-foreground">
+            {t('alsoUsedBy', { action: labelOf(duplicate) })}
+          </p>
+        )}
+      </li>
+    )
+  }
+
+  return (
+    // `relative` is load-bearing. The announcement below is visually hidden,
+    // which means absolutely positioned; with no positioned ancestor it is
+    // laid out against the page instead of this pane, far below the window,
+    // and the whole document starts to scroll.
+    <div className="relative space-y-6" data-testid="shortcuts-settings">
+      <p aria-live="polite" className="sr-only top-0 left-0">
+        {announcement}
+      </p>
+      <p className="rounded-md bg-muted px-3 py-2 text-sm text-muted-foreground md:hidden">
+        {t('phoneNote')}
+      </p>
+
+      <AppCard
+        id="shortcuts-general"
+        icon={Keyboard}
+        title={t('title')}
+        description={t('description')}
+        contentClassName="p-0"
+      >
+        <div className="divide-y">
+          <label className="flex items-center justify-between gap-4 px-5 py-3">
+            <span className="min-w-0 text-sm">
+              <span id="shortcuts-enabled-label">{t('enableLabel')}</span>
+              <span className="block text-xs text-muted-foreground">{t('enableHint')}</span>
+            </span>
+            <Switch
+              id="shortcuts-enabled"
+              aria-labelledby="shortcuts-enabled-label"
+              checked={prefs.enabled}
+              onCheckedChange={(enabled) => updatePrefs({ ...prefs, enabled })}
+            />
+          </label>
+          <label className="flex items-center justify-between gap-4 px-5 py-3">
+            <span className="min-w-0 text-sm">
+              <span id="shortcuts-single-label">{t('singleKeysLabel')}</span>
+              <span className="block text-xs text-muted-foreground">{t('singleKeysHint')}</span>
+            </span>
+            <Switch
+              id="shortcuts-single-keys"
+              aria-labelledby="shortcuts-single-label"
+              checked={prefs.singleKeys}
+              disabled={!prefs.enabled}
+              onCheckedChange={(singleKeys) => updatePrefs({ ...prefs, singleKeys })}
+            />
+          </label>
+          <label className="flex items-center justify-between gap-4 px-5 py-3">
+            <span className="min-w-0 text-sm">
+              <span id="shortcuts-sequences-label">{t('goToSequencesLabel', goToWords)}</span>
+              <span className="block text-xs text-muted-foreground">
+                {t('goToSequencesHint', goToWords)}
+              </span>
+            </span>
+            <Switch
+              id="shortcuts-go-to-sequences"
+              aria-labelledby="shortcuts-sequences-label"
+              checked={prefs.goToSequences}
+              disabled={!prefs.enabled}
+              onCheckedChange={(goToSequences) => updatePrefs({ ...prefs, goToSequences })}
+            />
+          </label>
+        </div>
+      </AppCard>
+
+      <AppCard
+        id="shortcuts-all"
+        icon={Command}
+        title={t('allTitle')}
+        description={t('allHint')}
+        contentClassName="p-0"
+        action={
+          <Button
+            type="button"
+            variant="outline"
+            size="sm"
+            disabled={!anythingChanged}
+            onClick={resetAll}
+          >
+            {t('resetAll')}
+          </Button>
+        }
+      >
+        {SHORTCUT_GROUPS.map((group) => {
+          const defs = SHORTCUTS.filter((def) => def.group === group && isVisible(def))
+          if (defs.length === 0) return null
+          return (
+            <section key={group} aria-labelledby={`shortcuts-group-${group}`}>
+              <div className="flex items-baseline justify-between gap-3 border-y bg-muted/60 px-5 py-2 first:border-t-0">
+                <h3
+                  id={`shortcuts-group-${group}`}
+                  className="text-xs font-semibold tracking-wide text-muted-foreground uppercase"
+                >
+                  {t(`groups.${group}`)}
+                </h3>
+                <span className="text-xs text-muted-foreground">
+                  {t(group === 'calendar' ? 'scopes.calendar' : 'scopes.global')}
+                </span>
+              </div>
+              {group === 'goTo' && (
+                <p className="border-b px-5 py-2 text-xs text-muted-foreground">
+                  {t('goToNote', { keys: searchKeys, ...goToWords })}
+                </p>
+              )}
+              <ul className={cn('divide-y', !prefs.enabled && 'opacity-60')}>
+                {defs.map(renderRow)}
+              </ul>
+            </section>
+          )
+        })}
+      </AppCard>
+    </div>
+  )
+}

+ 11 - 0
src/features/shortcuts/Components/SidebarShortcut.tsx

@@ -0,0 +1,11 @@
+'use client'
+
+import { useSidebar } from '@/components/ui/sidebar'
+import { useShortcut } from './ShortcutsProvider'
+
+/** Shows or hides the sidebar on its shortcut. Sits inside the sidebar's provider. */
+export function SidebarShortcut() {
+  const { toggleSidebar } = useSidebar()
+  useShortcut('general.sidebar', toggleSidebar)
+  return null
+}

+ 420 - 0
src/features/shortcuts/Lib/keys.ts

@@ -0,0 +1,420 @@
+/**
+ * How a key press is named, matched and shown.
+ *
+ * A combo is a canonical string: `mod+`, `alt+`, `shift+` in that order, then
+ * the key (`mod+k`, `alt+shift+w`, `d`, `arrowright`). The two modifiers are
+ * abstract, because the same habit sits on different keys per platform:
+ *
+ *   mod  Ctrl on Windows and Linux, Command on a Mac
+ *   alt  Alt on Windows and Linux, Control on a Mac (Option types characters
+ *        there, so it cannot carry a shortcut)
+ *
+ * The key is the character the layout produces, not the physical key, so an
+ * AZERTY keyboard presses the key that is printed W and a Norwegian one finds
+ * `/` wherever it lives. Layouts that produce no Latin letter (Russian) fall
+ * back to the physical key.
+ *
+ * Two combos with a space between them are a sequence, pressed one after the
+ * other: `alt+g alt+w` is Alt+G, then Alt+W. Only the registry's go-to set
+ * uses them; a person cannot record one.
+ */
+export type Combo = string
+export type Platform = 'mac' | 'other'
+
+type KeyEventLike = Pick<
+  KeyboardEvent,
+  'key' | 'code' | 'ctrlKey' | 'metaKey' | 'altKey' | 'shiftKey'
+> & { getModifierState?: (key: string) => boolean }
+
+const IGNORED_KEYS = new Set([
+  'Shift',
+  'Control',
+  'Alt',
+  'Meta',
+  'AltGraph',
+  'CapsLock',
+  'NumLock',
+  'ScrollLock',
+  'Dead',
+  'Process',
+  'Unidentified',
+  'OS',
+  'Fn',
+  'ContextMenu',
+])
+
+export function detectPlatform(): Platform {
+  if (typeof navigator === 'undefined') return 'other'
+  const hint =
+    (navigator as Navigator & { userAgentData?: { platform?: string } }).userAgentData?.platform ||
+    navigator.platform ||
+    navigator.userAgent ||
+    ''
+  return /mac|iphone|ipad/i.test(hint) ? 'mac' : 'other'
+}
+
+let cachedPlatform: Platform | null = null
+
+/** The platform, looked up once. Only for code that runs on a key press. */
+export function currentPlatform(): Platform {
+  if (typeof navigator === 'undefined') return 'other'
+  cachedPlatform ??= detectPlatform()
+  return cachedPlatform
+}
+
+function keyName(
+  e: KeyEventLike
+): { name: string; isCharacter: boolean; isLetter: boolean } | null {
+  const { key } = e
+  if (!key || IGNORED_KEYS.has(key)) return null
+  if (key === ' ') return { name: 'space', isCharacter: false, isLetter: false }
+  if (key.length > 1) return { name: key.toLowerCase(), isCharacter: false, isLetter: false }
+  if (/^[a-z]$/i.test(key)) return { name: key.toLowerCase(), isCharacter: true, isLetter: true }
+  // A layout with no Latin letters on this key: go by where the key sits.
+  const physical = /^Key([A-Z])$/.exec(e.code ?? '')
+  if (physical && key.charCodeAt(0) > 127) {
+    return { name: physical[1].toLowerCase(), isCharacter: true, isLetter: true }
+  }
+  return { name: key.toLowerCase(), isCharacter: true, isLetter: false }
+}
+
+function build(mod: boolean, alt: boolean, shift: boolean, name: string): Combo {
+  return `${mod ? 'mod+' : ''}${alt ? 'alt+' : ''}${shift ? 'shift+' : ''}${name}`
+}
+
+/**
+ * The combos a key press may stand for, most specific first, or none when the
+ * press cannot be a shortcut (a lone modifier, AltGr, Option on a Mac).
+ *
+ * On a Mac, Control is `alt`; but Ctrl+K and Ctrl+S worked there before the
+ * registry existed, so the same press is offered a second time as `mod`.
+ */
+export function combosFromEvent(e: KeyEventLike, platform: Platform): Combo[] {
+  const key = keyName(e)
+  if (!key) return []
+  // AltGr types characters (@ and € on European layouts) and reports as
+  // Ctrl+Alt on Windows.
+  if (e.getModifierState?.('AltGraph')) return []
+  // Punctuation already says whether Shift was held: `/` is Shift+7 on a
+  // Norwegian keyboard and a key of its own on a US one.
+  const shift = e.shiftKey && (key.isLetter || !key.isCharacter)
+
+  if (platform === 'mac') {
+    if (e.altKey) return []
+    if (e.metaKey && e.ctrlKey) return []
+    if (e.metaKey) return [build(true, false, shift, key.name)]
+    if (e.ctrlKey) {
+      return [build(false, true, shift, key.name), build(true, false, shift, key.name)]
+    }
+    return [build(false, false, shift, key.name)]
+  }
+  if (e.metaKey) return []
+  if (e.ctrlKey && e.altKey) return []
+  return [build(e.ctrlKey, e.altKey, shift, key.name)]
+}
+
+/** The one combo a press records as, for the settings page. */
+export function comboFromEvent(e: KeyEventLike, platform: Platform): Combo | null {
+  return combosFromEvent(e, platform)[0] ?? null
+}
+
+export type ParsedCombo = { mod: boolean; alt: boolean; shift: boolean; key: string }
+
+export function parseCombo(combo: Combo): ParsedCombo | null {
+  const match = /^(mod\+)?(alt\+)?(shift\+)?(.+)$/.exec(combo)
+  if (!match) return null
+  const key = match[4]
+  if (key !== key.toLowerCase() || /\s/.test(key) || key.length > 12) return null
+  if (key.length > 1 && !/^[a-z0-9]+$/.test(key)) return null
+  return { mod: !!match[1], alt: !!match[2], shift: !!match[3], key }
+}
+
+/** The presses of a combo, in order: one for a chord, two for a sequence. */
+export function comboSteps(combo: Combo): Combo[] {
+  return combo.split(' ')
+}
+
+export function isSequence(combo: Combo): boolean {
+  return combo.includes(' ')
+}
+
+/** Ctrl, Command or Alt is part of it, so it can never be typed into a field. */
+export function hasModifier(combo: Combo): boolean {
+  return comboSteps(combo).every((step) => {
+    const parsed = parseCombo(step)
+    return !!parsed && (parsed.mod || parsed.alt)
+  })
+}
+
+const LONE_MODIFIERS = new Set(['Shift', 'Control', 'Alt', 'Meta', 'AltGraph'])
+
+/** Alt, Ctrl, Shift or Command going down on its own, on the way to a chord. */
+export function isLoneModifier(event: Pick<KeyboardEvent, 'key'>): boolean {
+  return LONE_MODIFIERS.has(event.key)
+}
+
+/**
+ * Made of bare printable characters only: what WCAG 2.1.4 calls a character
+ * key shortcut, and so one a person must be able to switch off.
+ */
+export function isCharacterKey(combo: Combo): boolean {
+  return comboSteps(combo).every((step) => {
+    const parsed = parseCombo(step)
+    return !!parsed && !parsed.mod && !parsed.alt && parsed.key.length === 1
+  })
+}
+
+/**
+ * Keys the browser or the system keeps for itself, or that already mean
+ * something on every page. A page cannot take most of these over, and the
+ * rest would break copying, printing or moving through a form.
+ */
+const RESERVED = new Set<Combo>([
+  // Tabs and windows: the browser acts before the page hears of it.
+  'mod+w',
+  'mod+shift+w',
+  'mod+t',
+  'mod+shift+t',
+  'mod+n',
+  'mod+shift+n',
+  'mod+q',
+  'mod+shift+q',
+  'mod+tab',
+  'mod+shift+tab',
+  'mod+r',
+  'mod+shift+r',
+  'mod+l',
+  'mod+h',
+  'mod+j',
+  'mod+d',
+  'mod+o',
+  'mod+u',
+  'mod+shift+i',
+  'mod+shift+j',
+  'mod+shift+c',
+  'mod+shift+delete',
+  // Editing: these belong to whatever field has the cursor.
+  'mod+c',
+  'mod+v',
+  'mod+x',
+  'mod+a',
+  'mod+z',
+  'mod+shift+z',
+  'mod+y',
+  'mod+f',
+  'mod+g',
+  'mod+p',
+  'mod+0',
+  'mod+-',
+  'mod++',
+  'mod+=',
+  // Alt on Windows. Chrome and Edge open their menu on Alt+F and Alt+E and
+  // the address bar on Alt+D. Firefox opens a menu on the letters of its
+  // menu bar (File, Edit, View, History, Bookmarks, Tools, Help) even when
+  // the page has handled the key. Windows 11 uses Alt+A for suggested actions.
+  'alt+f',
+  'alt+e',
+  'alt+d',
+  'alt+v',
+  'alt+s',
+  'alt+b',
+  'alt+t',
+  'alt+h',
+  'alt+a',
+  'alt+enter',
+  'alt+escape',
+  'alt+arrowup',
+  'alt+arrowdown',
+  'alt+pageup',
+  'alt+pagedown',
+  'alt+printscreen',
+  'alt+f4',
+  'alt+arrowleft',
+  'alt+arrowright',
+  'alt+home',
+  'alt+tab',
+  'alt+space',
+])
+
+const RESERVED_KEYS = new Set([
+  'tab',
+  'enter',
+  'escape',
+  'space',
+  'backspace',
+  'delete',
+  'f5',
+  'f11',
+  'f12',
+])
+
+export function isReservedCombo(combo: Combo): boolean {
+  const parsed = parseCombo(combo)
+  if (!parsed) return true
+  if (RESERVED.has(combo)) return true
+  // Alt+Shift is how Windows switches the keyboard language, so a chord
+  // built on it can change the layout under the person's hands.
+  if (parsed.alt && parsed.shift) return true
+  if (/^[1-9]$/.test(parsed.key) && parsed.mod && !parsed.alt) return true
+  return RESERVED_KEYS.has(parsed.key)
+}
+
+const KEY_LABELS: Record<string, string> = {
+  arrowleft: '←',
+  arrowright: '→',
+  arrowup: '↑',
+  arrowdown: '↓',
+  escape: 'Esc',
+  enter: 'Enter',
+  space: 'Space',
+  backspace: 'Backspace',
+  delete: 'Del',
+  home: 'Home',
+  end: 'End',
+  pageup: 'PgUp',
+  pagedown: 'PgDn',
+}
+
+/** The key caps to draw for one press, one string per cap. */
+export function comboParts(combo: Combo, platform: Platform): string[] {
+  const parsed = parseCombo(combo)
+  if (!parsed) return []
+  const mac = platform === 'mac'
+  const parts: string[] = []
+  if (parsed.alt && mac) parts.push('⌃')
+  if (parsed.mod) parts.push(mac ? '⌘' : 'Ctrl')
+  if (parsed.alt && !mac) parts.push('Alt')
+  if (parsed.shift) parts.push(mac ? '⇧' : 'Shift')
+  const label = KEY_LABELS[parsed.key]
+  if (label) parts.push(label)
+  else if (parsed.key.length === 1) parts.push(parsed.key.toUpperCase())
+  else parts.push(parsed.key.charAt(0).toUpperCase() + parsed.key.slice(1))
+  return parts
+}
+
+/**
+ * The combo as one string, for a title attribute or a screen reader. `then`
+ * is the word between the presses of a sequence, in the reader's language.
+ */
+export function comboText(combo: Combo, platform: Platform, then = '→'): string {
+  return comboSteps(combo)
+    .map((step) => comboParts(step, platform).join(platform === 'mac' ? ' ' : '+'))
+    .join(` ${then} `)
+}
+
+/**
+ * Where a bare key (a letter, an arrow, a "G then W") already means
+ * something, so no shortcut may take it:
+ *
+ *  - anything typed into: every input, textarea and select, the rich text
+ *    editors (contenteditable), and the ARIA text roles;
+ *  - widgets that use letters or arrows themselves: comboboxes, lists and
+ *    their options, menus, trees, grids, tabs, radios, sliders, and the
+ *    search palette (cmdk);
+ *  - embedded documents, which have a keyboard of their own;
+ *  - anything a screen marks with `data-shortcuts="off"`.
+ *
+ * A button, a link or a table row uses no letters, so a shortcut still works
+ * with the focus resting on one, as it does on the page itself.
+ */
+const CLAIMS_PLAIN_KEYS = [
+  'input',
+  'textarea',
+  'select',
+  'option',
+  '[contenteditable]:not([contenteditable="false"])',
+  'iframe',
+  'embed',
+  'object',
+  '[role="textbox"]',
+  '[role="searchbox"]',
+  '[role="combobox"]',
+  '[role="spinbutton"]',
+  '[role="slider"]',
+  '[role="listbox"]',
+  '[role="option"]',
+  '[role="menu"]',
+  '[role="menubar"]',
+  '[role="menuitem"]',
+  '[role="menuitemcheckbox"]',
+  '[role="menuitemradio"]',
+  '[role="tree"]',
+  '[role="treeitem"]',
+  '[role="grid"]',
+  '[role="gridcell"]',
+  '[role="tab"]',
+  '[role="radio"]',
+  '[role="application"]',
+  '[cmdk-root]',
+  '[data-shortcuts="off"]',
+].join(', ')
+
+/** An element and everything above it, out through any shadow roots. */
+function withAncestors(start: Element | null): Element[] {
+  const chain: Element[] = []
+  let node: Element | null = start
+  while (node) {
+    chain.push(node)
+    const root = node.parentElement ? null : node.getRootNode()
+    node = node.parentElement ?? (root instanceof ShadowRoot ? root.host : null)
+  }
+  return chain
+}
+
+/** The element that really has the focus, inside a shadow root if need be. */
+function deepActiveElement(): Element | null {
+  if (typeof document === 'undefined') return null
+  let active: Element | null = document.activeElement
+  while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement
+  return active
+}
+
+/**
+ * A bare key pressed here belongs to what has the focus, not to a shortcut.
+ * Asked of both the path the event took (which sees into shadow roots) and
+ * the focused element, so neither a retargeted event nor a key that arrives
+ * while focus is moving can slip past.
+ */
+export function claimsPlainKeys(event: Pick<KeyboardEvent, 'target' | 'composedPath'>): boolean {
+  if (typeof document !== 'undefined' && document.designMode === 'on') return true
+  const path =
+    typeof event.composedPath === 'function'
+      ? event.composedPath().filter((node): node is Element => node instanceof Element)
+      : []
+  const fromTarget = event.target instanceof Element ? withAncestors(event.target) : []
+  const candidates = [...path, ...fromTarget, ...withAncestors(deepActiveElement())]
+  return candidates.some((element) => element.matches(CLAIMS_PLAIN_KEYS))
+}
+
+const OPEN_LAYER = [
+  // Radix and vaul: dialogs, alert dialogs, sheets, drawers and popovers all
+  // render a dialog role; it stays in the page a moment after closing.
+  '[role="dialog"]:not([data-state="closed"])',
+  '[role="alertdialog"]:not([data-state="closed"])',
+  '[aria-modal="true"]',
+  '[data-vaul-drawer]:not([data-state="closed"])',
+  // Dropdown and context menus.
+  '[role="menu"]:not([data-state="closed"])',
+  // Anything Radix floats: selects, comboboxes, date pickers, popovers.
+  '[data-radix-popper-content-wrapper]',
+  // The app's own lightboxes and overlays.
+  '[data-shortcut-layer]',
+].join(', ')
+
+/**
+ * A dialog, sheet, drawer, popover, menu, dropdown or lightbox is up and
+ * owns the keyboard. A tooltip is not one: it opens under the mouse and
+ * takes no keys.
+ */
+export function isLayerOpen(root: ParentNode = document): boolean {
+  for (const layer of root.querySelectorAll(OPEN_LAYER)) {
+    if (
+      layer.matches('[data-radix-popper-content-wrapper]') &&
+      layer.querySelector('[role="tooltip"]')
+    ) {
+      continue
+    }
+    return true
+  }
+  return false
+}

+ 215 - 0
src/features/shortcuts/Lib/preferences.ts

@@ -0,0 +1,215 @@
+import { type Combo, hasModifier, isCharacterKey, isReservedCombo, parseCombo } from './keys'
+import { SHORTCUTS, type ShortcutDef, shortcutById } from './registry'
+
+/**
+ * What one person changed about their shortcuts (User.keyboardShortcuts).
+ * Only differences from the registry are kept, so a default that changes in
+ * a later release reaches everyone who never touched it.
+ */
+export type ShortcutPrefs = {
+  /** Off: no shortcut in the registry does anything. */
+  enabled: boolean
+  /** Off: bare character keys (the calendar's letters) do nothing. */
+  singleKeys: boolean
+  /** On: Alt+G, then Alt and a page's letter, opens that page. */
+  goToSequences: boolean
+  /** Shortcut id to the one key that replaces its defaults; '' is no key. */
+  overrides: Record<string, Combo>
+  /** Shortcut ids switched off. */
+  disabled: string[]
+}
+
+export const DEFAULT_SHORTCUT_PREFS: ShortcutPrefs = {
+  enabled: true,
+  singleKeys: true,
+  goToSequences: true,
+  overrides: {},
+  disabled: [],
+}
+
+export type ComboProblem = 'invalid' | 'reserved' | 'taken' | 'needsModifier'
+
+/**
+ * Keys that cannot be handed over. A fixed key stays with its shortcut
+ * whatever is recorded elsewhere, and the first press of a sequence (Alt+G)
+ * given to something else would fire that instead and leave the whole go-to
+ * set unreachable.
+ */
+function isHeldForGood(def: ShortcutDef, combo: Combo): boolean {
+  return SHORTCUTS.some(
+    (other) =>
+      other.sequence?.startsWith(`${combo} `) ||
+      (other.id !== def.id && other.fixedKeys?.includes(combo))
+  )
+}
+
+/** Why a key cannot be given to this shortcut, or null when it can. */
+export function comboProblem(def: ShortcutDef, combo: Combo): ComboProblem | null {
+  if (!parseCombo(combo)) return 'invalid'
+  if (isReservedCombo(combo)) return 'reserved'
+  if (isHeldForGood(def, combo)) return 'taken'
+  // A shortcut that works on every page would otherwise fire on a letter
+  // meant for nothing in particular.
+  if (def.scope === 'global' && !hasModifier(combo)) return 'needsModifier'
+  return null
+}
+
+/**
+ * Whatever was stored or sent, as preferences that can be trusted: unknown
+ * shortcuts and keys that could never work are dropped rather than refused,
+ * so a shortcut removed from the registry does not break anyone's settings.
+ */
+export function normalizeShortcutPrefs(input: unknown): ShortcutPrefs {
+  if (!input || typeof input !== 'object') return DEFAULT_SHORTCUT_PREFS
+  const raw = input as Record<string, unknown>
+  const overrides: Record<string, Combo> = {}
+  if (raw.overrides && typeof raw.overrides === 'object') {
+    for (const [id, combo] of Object.entries(raw.overrides as Record<string, unknown>)) {
+      const def = shortcutById(id)
+      if (!def || typeof combo !== 'string') continue
+      if (combo === '') {
+        if (def.defaultKeys.length > 0) overrides[id] = ''
+        continue
+      }
+      if (comboProblem(def, combo)) continue
+      if (def.defaultKeys.length === 1 && def.defaultKeys[0] === combo) continue
+      overrides[id] = combo
+    }
+  }
+  const disabled = Array.isArray(raw.disabled)
+    ? [...new Set(raw.disabled.filter((id): id is string => typeof id === 'string'))].filter(
+        (id) => !!shortcutById(id)
+      )
+    : []
+  return {
+    enabled: raw.enabled !== false,
+    singleKeys: raw.singleKeys !== false,
+    goToSequences: raw.goToSequences !== false,
+    overrides,
+    disabled,
+  }
+}
+
+export function isDefaultShortcutPrefs(prefs: ShortcutPrefs): boolean {
+  return (
+    prefs.enabled &&
+    prefs.singleKeys &&
+    prefs.goToSequences &&
+    prefs.disabled.length === 0 &&
+    Object.keys(prefs.overrides).length === 0
+  )
+}
+
+/** The keys a person may change: their own, or the ones it shipped with. */
+export function assignedKeys(def: ShortcutDef, prefs: ShortcutPrefs): Combo[] {
+  const override = prefs.overrides[def.id]
+  if (override === undefined) return def.defaultKeys
+  return override ? [override] : []
+}
+
+export function isChanged(def: ShortcutDef, prefs: ShortcutPrefs): boolean {
+  return prefs.overrides[def.id] !== undefined
+}
+
+export function isSwitchedOff(def: ShortcutDef, prefs: ShortcutPrefs): boolean {
+  return prefs.disabled.includes(def.id)
+}
+
+/** The keys that fire it right now, the fixed ones included. */
+export function activeKeys(def: ShortcutDef, prefs: ShortcutPrefs): Combo[] {
+  if (!prefs.enabled || isSwitchedOff(def, prefs)) return []
+  const keys = [...assignedKeys(def, prefs), ...(def.fixedKeys ?? [])]
+  if (def.sequence && prefs.goToSequences) keys.push(def.sequence)
+  return prefs.singleKeys ? keys : keys.filter((combo) => !isCharacterKey(combo))
+}
+
+/**
+ * The other shortcut that already holds this key, if any. A key is held
+ * whether or not its shortcut is switched off, and whatever screen it works
+ * on: the calendar's W and a global W would fight on the calendar.
+ */
+export function findClash(
+  def: ShortcutDef,
+  combo: Combo,
+  prefs: ShortcutPrefs,
+  consider: (other: ShortcutDef) => boolean = () => true
+): ShortcutDef | null {
+  for (const other of SHORTCUTS) {
+    if (other.id === def.id || !consider(other)) continue
+    const held = [...assignedKeys(other, prefs), ...(other.fixedKeys ?? [])]
+    if (held.includes(combo)) return other
+  }
+  return null
+}
+
+/** Gives `combo` to a shortcut, taking it from whichever one held it. */
+export function assignKey(def: ShortcutDef, combo: Combo, prefs: ShortcutPrefs): ShortcutPrefs {
+  const overrides = { ...prefs.overrides }
+  for (const other of SHORTCUTS) {
+    if (other.id === def.id) continue
+    const keys = assignedKeys(other, prefs)
+    if (!keys.includes(combo)) continue
+    const rest = keys.filter((key) => key !== combo)
+    overrides[other.id] = rest[0] ?? ''
+  }
+  overrides[def.id] = combo
+  return normalizeShortcutPrefs({ ...prefs, overrides })
+}
+
+export function resetKey(def: ShortcutDef, prefs: ShortcutPrefs): ShortcutPrefs {
+  const overrides = { ...prefs.overrides }
+  delete overrides[def.id]
+  return { ...prefs, overrides }
+}
+
+export function setSwitchedOff(
+  def: ShortcutDef,
+  off: boolean,
+  prefs: ShortcutPrefs
+): ShortcutPrefs {
+  const disabled = prefs.disabled.filter((id) => id !== def.id)
+  if (off) disabled.push(def.id)
+  return { ...prefs, disabled }
+}
+
+export type MatchContext = {
+  prefs: ShortcutPrefs
+  /** The cursor is in a field. */
+  typing: boolean
+  /** A dialog, sheet or menu is open. */
+  layerOpen: boolean
+  /** Something can act on it now: a handler on this screen, or a page it opens. */
+  available: (def: ShortcutDef) => boolean
+}
+
+/**
+ * The shortcut a key press stands for right now, or null. The rules that keep
+ * shortcuts out of the way live here: a key without Ctrl or Alt never fires
+ * while typing, and nothing fires over a dialog unless it is meant to.
+ */
+/**
+ * Whether a key press could be the first half of a sequence that would fire
+ * right now: Alt+G, while the go-to set is on and no dialog is open.
+ */
+export function startsSequence(combo: Combo, ctx: MatchContext): boolean {
+  if (!ctx.prefs.enabled || ctx.layerOpen) return false
+  if (ctx.typing && !hasModifier(combo)) return false
+  return SHORTCUTS.some(
+    (def) =>
+      ctx.available(def) && activeKeys(def, ctx.prefs).some((key) => key.startsWith(`${combo} `))
+  )
+}
+
+export function matchShortcut(combos: readonly Combo[], ctx: MatchContext): ShortcutDef | null {
+  if (!ctx.prefs.enabled) return null
+  for (const combo of combos) {
+    if (ctx.typing && !hasModifier(combo)) continue
+    for (const def of SHORTCUTS) {
+      if (ctx.layerOpen && !def.overLayers) continue
+      if (!activeKeys(def, ctx.prefs).includes(combo)) continue
+      if (!ctx.available(def)) continue
+      return def
+    }
+  }
+  return null
+}

+ 260 - 0
src/features/shortcuts/Lib/registry.ts

@@ -0,0 +1,260 @@
+import type { Combo } from './keys'
+
+/**
+ * Every keyboard shortcut in the signed-in app, in the order the help overlay
+ * and the settings page list them. This is the one place that knows a key:
+ * the listener, the hints beside menu items and the settings page all read it.
+ *
+ * A shortcut that opens a page carries its `href` and needs nothing else. One
+ * that does something on a screen (the calendar's views, the search palette)
+ * is given its handler by that screen with `useShortcut`, and does nothing
+ * while the screen is not there.
+ */
+export type ShortcutGroup = 'general' | 'create' | 'goTo' | 'calendar'
+
+export type ShortcutLabel =
+  /** `settings.shortcuts.actions.<key>` */
+  | { from: 'shortcuts'; key: string }
+  /** `navigation.sidebar.<key>`, with the marine word where there is one. */
+  | { from: 'sidebar'; key: string; marineKey?: string }
+  /** `search.actions.<key>` */
+  | { from: 'search'; key: string }
+
+export type ShortcutDef = {
+  id: string
+  group: ShortcutGroup
+  /** Where it works: everywhere, or on one screen only. */
+  scope: 'global' | 'calendar'
+  /** The keys it ships with; a person may replace them with one of their own. */
+  defaultKeys: Combo[]
+  /** Keys that always work beside those and are not offered for change. */
+  fixedKeys?: Combo[]
+  /**
+   * Its place in the go-to set, such as `alt+g alt+w`: Alt+G, then Alt+W.
+   * Works unless the person switched the set off.
+   */
+  sequence?: Combo
+  label: ShortcutLabel
+  /** Opened when nothing on the screen has claimed the shortcut. */
+  href?: string
+  /** The search palette command it mirrors; hidden when that command is. */
+  command?: string
+  /** Permission subject it needs when there is no palette command to go by. */
+  subject?: string
+  /** Works with a dialog or a menu open. Everything else waits until it closes. */
+  overLayers?: boolean
+}
+
+const goTo = (
+  id: string,
+  command: string,
+  href: string,
+  key: string,
+  letter: string | null,
+  marineKey?: string
+): ShortcutDef => ({
+  id: `goTo.${id}`,
+  group: 'goTo',
+  scope: 'global',
+  // No single chord of its own: the search palette opens every page, and
+  // the go-to set (Alt+G, then a letter) the main ones. A person can give
+  // any page a key.
+  defaultKeys: [],
+  sequence: letter ? `alt+g alt+${letter}` : undefined,
+  label: { from: 'sidebar', key, marineKey },
+  href,
+  command,
+})
+
+const calendarView = (view: string, letter: string): ShortcutDef => ({
+  id: `calendar.${view}`,
+  group: 'calendar',
+  scope: 'calendar',
+  defaultKeys: [letter],
+  label: { from: 'shortcuts', key: `calendar_${view}` },
+})
+
+export const SHORTCUTS: readonly ShortcutDef[] = [
+  {
+    id: 'general.search',
+    group: 'general',
+    scope: 'global',
+    defaultKeys: ['mod+k'],
+    label: { from: 'shortcuts', key: 'search' },
+    overLayers: true,
+  },
+  {
+    id: 'general.plateLookup',
+    group: 'general',
+    scope: 'global',
+    defaultKeys: ['mod+shift+l'],
+    label: { from: 'shortcuts', key: 'plateLookup' },
+    overLayers: true,
+  },
+  {
+    id: 'general.save',
+    group: 'general',
+    scope: 'global',
+    defaultKeys: ['mod+s'],
+    label: { from: 'shortcuts', key: 'save' },
+    overLayers: true,
+  },
+  {
+    id: 'general.sidebar',
+    group: 'general',
+    scope: 'global',
+    defaultKeys: ['mod+b'],
+    label: { from: 'shortcuts', key: 'sidebar' },
+    overLayers: true,
+  },
+  {
+    id: 'general.help',
+    group: 'general',
+    scope: 'global',
+    defaultKeys: ['mod+/'],
+    label: { from: 'shortcuts', key: 'help' },
+  },
+
+  // Alt and the first letter of what is being made. Vehicle is the one
+  // exception: Alt+V opens the View menu in Firefox on Windows, so it is K
+  // (as in car, kjøretøy, Kfz).
+  {
+    id: 'create.workOrder',
+    group: 'create',
+    scope: 'global',
+    defaultKeys: ['alt+w'],
+    label: { from: 'search', key: 'newWorkOrder' },
+    href: '/work-orders?new=1',
+    command: 'action:new-work-order',
+  },
+  {
+    id: 'create.quote',
+    group: 'create',
+    scope: 'global',
+    defaultKeys: ['alt+q'],
+    label: { from: 'search', key: 'newQuote' },
+    href: '/quotes?create=true',
+    command: 'action:new-quote',
+  },
+  {
+    id: 'create.customer',
+    group: 'create',
+    scope: 'global',
+    defaultKeys: ['alt+c'],
+    label: { from: 'search', key: 'newCustomer' },
+    href: '/customers?create=true',
+    command: 'action:new-customer',
+  },
+  {
+    id: 'create.vehicle',
+    group: 'create',
+    scope: 'global',
+    defaultKeys: ['alt+k'],
+    label: { from: 'search', key: 'newVehicle' },
+    href: '/vehicles?create=true',
+    command: 'action:new-vehicle',
+  },
+  {
+    id: 'create.part',
+    group: 'create',
+    scope: 'global',
+    defaultKeys: ['alt+p'],
+    label: { from: 'search', key: 'newPart' },
+    href: '/inventory?create=true',
+    command: 'action:new-part',
+  },
+  {
+    id: 'create.inspection',
+    group: 'create',
+    scope: 'global',
+    defaultKeys: ['alt+i'],
+    label: { from: 'shortcuts', key: 'newInspection' },
+    subject: 'inspections',
+  },
+
+  // Pages: hold Alt, press G, then the page's letter. Both presses carry
+  // Alt, so nothing typed and nothing a scanner sends can start or finish
+  // one. The letter is the one that creates the same thing (W work order,
+  // Q quote, C customer, K vehicle, P part, I inspection); G twice is the
+  // dashboard; L is the calendar, O the work board.
+  goTo('dashboard', 'page:dashboard', '/', 'dashboard', 'g'),
+  goTo('workOrders', 'page:work-orders', '/work-orders', 'workOrders', 'w'),
+  goTo('quotes', 'page:quotes', '/quotes', 'quotes', 'q'),
+  goTo('customers', 'page:customers', '/customers', 'customers', 'c'),
+  goTo('vehicles', 'page:vehicles', '/vehicles', 'vehicles', 'k', 'vessels'),
+  goTo('inventory', 'page:inventory', '/inventory', 'inventory', 'p'),
+  goTo('inspections', 'page:inspections', '/inspections', 'inspections', 'i'),
+  goTo('calendar', 'page:calendar', '/calendar', 'calendar', 'l'),
+  goTo('workBoard', 'page:work-board', '/work-board', 'workBoard', 'o'),
+  goTo('messages', 'page:messages', '/messages', 'messages', 'm'),
+  goTo('reminders', 'page:reminders', '/reminders', 'reminders', 'r'),
+  // Not in the set: their own letters (B, R, T, S) are browser keys with
+  // Alt, or already taken. Search opens them, and each can be given a key.
+  goTo('billing', 'page:billing', '/billing', 'billing', null),
+  goTo('reports', 'page:reports', '/reports', 'reports', null),
+  goTo('timesheets', 'page:timesheets', '/timesheets', 'timesheets', null),
+  goTo('settings', 'page:settings', '/settings', 'settings', null),
+  goTo('tireHotel', 'page:tire-hotel', '/tire-hotel', 'tireHotel', null),
+  goTo('laborPresets', 'page:labor-presets', '/labor-presets', 'laborPresets', null),
+  goTo('faultCodes', 'page:fault-codes', '/fault-codes', 'faultCodes', null),
+  goTo('ai', 'page:ai', '/ai', 'aiAssistant', null),
+  goTo('auditLog', 'page:audit-log', '/audit-log', 'auditLog', null),
+
+  // The calendar's own keys, the ones Google Calendar taught everyone.
+  calendarView('day', 'd'),
+  calendarView('week', 'w'),
+  calendarView('month', 'm'),
+  calendarView('year', 'y'),
+  calendarView('schedule', 'a'),
+  calendarView('fourDays', 'x'),
+  {
+    id: 'calendar.today',
+    group: 'calendar',
+    scope: 'calendar',
+    defaultKeys: ['t'],
+    label: { from: 'shortcuts', key: 'calendar_today' },
+  },
+  {
+    id: 'calendar.next',
+    group: 'calendar',
+    scope: 'calendar',
+    defaultKeys: ['j', 'n'],
+    fixedKeys: ['arrowright'],
+    label: { from: 'shortcuts', key: 'calendar_next' },
+  },
+  {
+    id: 'calendar.previous',
+    group: 'calendar',
+    scope: 'calendar',
+    defaultKeys: ['k', 'p'],
+    fixedKeys: ['arrowleft'],
+    label: { from: 'shortcuts', key: 'calendar_previous' },
+  },
+]
+
+export const SHORTCUT_GROUPS: readonly ShortcutGroup[] = ['general', 'create', 'goTo', 'calendar']
+
+const BY_ID = new Map(SHORTCUTS.map((def) => [def.id, def]))
+
+export function shortcutById(id: string): ShortcutDef | undefined {
+  return BY_ID.get(id)
+}
+
+/** The palette row that opens the help overlay. */
+export const SHORTCUTS_HELP_COMMAND = 'action:keyboard-shortcuts'
+
+const BY_COMMAND = new Map<string, ShortcutDef>([
+  ...SHORTCUTS.filter((def) => def.command).map((def) => [def.command as string, def] as const),
+  ['action:plate-lookup', BY_ID.get('general.plateLookup') as ShortcutDef],
+  [SHORTCUTS_HELP_COMMAND, BY_ID.get('general.help') as ShortcutDef],
+])
+
+/** The shortcut that does what a search palette command does, if there is one. */
+export function shortcutForCommand(commandId: string): ShortcutDef | undefined {
+  return BY_COMMAND.get(commandId)
+}
+
+/** The shortcut that opens a page, by the page's address. */
+export function goToShortcutForHref(href: string): ShortcutDef | undefined {
+  return SHORTCUTS.find((def) => def.group === 'goTo' && def.href === href)
+}

+ 15 - 0
src/features/shortcuts/Schema/preferences.ts

@@ -0,0 +1,15 @@
+import { z } from 'zod'
+
+/**
+ * The shape the settings page sends. Which shortcuts exist and which keys
+ * may be used is decided by `normalizeShortcutPrefs`, against the registry.
+ */
+export const shortcutPrefsSchema = z.object({
+  enabled: z.boolean(),
+  singleKeys: z.boolean(),
+  goToSequences: z.boolean().optional(),
+  overrides: z.record(z.string().max(60), z.string().max(40)),
+  disabled: z.array(z.string().max(60)).max(200),
+})
+
+export type ShortcutPrefsInput = z.infer<typeof shortcutPrefsSchema>

+ 7 - 13
src/features/vehicles/Components/PlateLookupCommand.tsx

@@ -25,6 +25,8 @@ import { cn } from '@/lib/utils'
 import { type PlateLookup, lookupPlate } from '../Actions/plateLookupActions'
 import { compactPlate, looksLikePlate } from '../Lib/plate'
 import { VehicleForm } from './VehicleForm'
+import { useShortcut } from '@/features/shortcuts/Components/ShortcutsProvider'
+import { ShortcutKeys } from '@/features/shortcuts/Components/ShortcutKeys'
 
 /**
  * The header's plate lookup: one field, one answer sheet.
@@ -117,7 +119,9 @@ export function PlateLookupCommand() {
     [t]
   )
 
-  // Open on the header button, the shortcut, or a request carrying a plate.
+  useShortcut('general.plateLookup', () => setOpen((prev) => !prev), available)
+
+  // Open on the header button or a request carrying a plate.
   useEffect(() => {
     if (!available) return
     const onEvent = (e: Event) => {
@@ -128,18 +132,8 @@ export function PlateLookupCommand() {
         void run(detail.plate)
       }
     }
-    const onKey = (e: KeyboardEvent) => {
-      if ((e.metaKey || e.ctrlKey) && e.shiftKey && e.key.toLowerCase() === 'l') {
-        e.preventDefault()
-        setOpen((prev) => !prev)
-      }
-    }
     document.addEventListener(PLATE_LOOKUP_EVENT, onEvent)
-    document.addEventListener('keydown', onKey)
-    return () => {
-      document.removeEventListener(PLATE_LOOKUP_EVENT, onEvent)
-      document.removeEventListener('keydown', onKey)
-    }
+    return () => document.removeEventListener(PLATE_LOOKUP_EVENT, onEvent)
   }, [available, run])
 
   useEffect(() => {
@@ -610,7 +604,7 @@ export function PlateLookupCommand() {
               </kbd>
               <span className="ml-1.5">{t('hintClose')}</span>
             </span>
-            <span className="ml-auto hidden sm:inline">{t('shortcut')}</span>
+            <ShortcutKeys id="general.plateLookup" className="ml-auto" />
           </div>
         </DialogContent>
       </Dialog>

+ 1 - 0
src/features/vehicles/Components/service-detail/ImageCarousel.tsx

@@ -43,6 +43,7 @@ export function ImageCarousel({
 
   return (
     <div
+      data-shortcut-layer
       className="fixed inset-0 z-50 flex items-center justify-center bg-black/90"
       onClick={onClose}
       onTouchStart={(e) => {

+ 4 - 2
src/hooks/use-save-shortcut.ts

@@ -1,12 +1,14 @@
 'use client'
 
 import { useEffect } from 'react'
+import { useShortcutMatcher } from '@/features/shortcuts/Components/ShortcutsProvider'
 
 export function useSaveShortcut(onSave: () => void | Promise<void>, enabled = true) {
+  const isSaveShortcut = useShortcutMatcher('general.save')
   useEffect(() => {
     if (!enabled) return
     const handler = (e: KeyboardEvent) => {
-      if ((e.ctrlKey || e.metaKey) && (e.key === 's' || e.key === 'S')) {
+      if (isSaveShortcut(e)) {
         e.preventDefault()
         void onSave()
       }
@@ -15,5 +17,5 @@ export function useSaveShortcut(onSave: () => void | Promise<void>, enabled = tr
     // which sits on the window and steps aside once this has handled the key.
     document.addEventListener('keydown', handler)
     return () => document.removeEventListener('keydown', handler)
-  }, [onSave, enabled])
+  }, [onSave, enabled, isSaveShortcut])
 }

+ 4 - 0
src/lib/get-layout-data.ts

@@ -23,6 +23,8 @@ type AuthResult =
       /** When the "What's new" panel was last opened, and when the account began. */
       whatsNewSeenAt: Date | null
       userCreatedAt: Date | null
+      /** The person's own keyboard shortcuts, as stored; null is every default. */
+      keyboardShortcuts: unknown
       companyLogo: string | undefined
       dateFormat: string | undefined
       timeFormat: string | undefined
@@ -54,6 +56,7 @@ export async function getLayoutData(): Promise<AuthResult> {
         updateBannerShownAt: true,
         whatsNewSeenAt: true,
         createdAt: true,
+        keyboardShortcuts: true,
       },
     }),
   ])
@@ -116,6 +119,7 @@ export async function getLayoutData(): Promise<AuthResult> {
     updateBannerShownAt: user?.updateBannerShownAt ?? null,
     whatsNewSeenAt: user?.whatsNewSeenAt ?? null,
     userCreatedAt: user?.createdAt ?? null,
+    keyboardShortcuts: user?.keyboardShortcuts ?? null,
     companyLogo: orgMap.get(SETTING_KEYS.COMPANY_LOGO) || undefined,
     dateFormat: orgMap.get(SETTING_KEYS.DATE_FORMAT) || undefined,
     timeFormat: orgMap.get(SETTING_KEYS.TIME_FORMAT) || undefined,