useKeyboardShortcuts

Register Cmd/Ctrl keyboard shortcuts for send, save, preview, schedule, attach, and mode toggle.

useKeyboardShortcuts listens for a fixed set of Cmd (macOS) or Ctrl shortcuts on document and calls the matching callback. It was built for message and email composers.

Press ⌘/Ctrl + S to save or ⌘/Ctrl + Enter to send.

Import#

typescript
import { useKeyboardShortcuts } from "@reactberry/system";

Usage#

typescript
"use client";

import { useKeyboardShortcuts } from "@reactberry/system";
import { Text } from "@reactberry/system/elements";

export default function Composer({ send, saveDraft }: { send: () => void; saveDraft: () => void }) {
  const { shortcuts } = useKeyboardShortcuts({ onSend: send, onSaveDraft: saveDraft });

  return <Text fontSize="s" color="secondary">Send with {shortcuts.send}</Text>;
}

Examples#

One shortcut#

Pass only the callbacks you need. Here onPreview switches between editing and preview with Cmd/Ctrl + P.

Editing

API#

typescript
function useKeyboardShortcuts(options: {
  onSend?: () => void;
  onSaveDraft?: () => void;
  onPreview?: () => void;
  onSchedule?: () => void;
  onAddAttachment?: () => void;
  onToggleMode?: () => void;
}): { shortcuts: Record<"send" | "saveDraft" | "preview" | "schedule" | "addAttachment" | "toggleMode", string> }

Parameters#

A shortcut is only handled (and the browser default prevented) when its callback is provided.

PropTypeDefaultDescription
onSend
() => void
—

Called on Cmd/Ctrl + Enter.

onSaveDraft
() => void
—

Called on Cmd/Ctrl + S.

onPreview
() => void
—

Called on Cmd/Ctrl + P.

onSchedule
() => void
—

Called on Cmd/Ctrl + Shift + S.

onAddAttachment
() => void
—

Called on Cmd/Ctrl + U.

onToggleMode
() => void
—

Called on Cmd/Ctrl + M.

Returns#

shortcuts is a fixed object of display labels:

PropTypeDefaultDescription
shortcuts.send
string
"⌘+Enter"

Label for onSend.

shortcuts.saveDraft
string
"⌘+S"

Label for onSaveDraft.

shortcuts.preview
string
"⌘+P"

Label for onPreview.

shortcuts.schedule
string
"⌘+⇧+S"

Label for onSchedule.

shortcuts.addAttachment
string
"⌘+U"

Label for onAddAttachment.

shortcuts.toggleMode
string
"⌘+M"

Label for onToggleMode.

Keyboard#

KeyAction
⌘ + EnterorCtrl + Enter

Calls onSend.

⌘ + SorCtrl + S

Calls onSaveDraft.

⌘ + PorCtrl + P

Calls onPreview.

⌘ + Shift + SorCtrl + Shift + S

Calls onSchedule.

⌘ + UorCtrl + U

Calls onAddAttachment.

⌘ + MorCtrl + M

Calls onToggleMode.

Escape

Default action prevented on every press while the hook is mounted. No callback is called.

Notes#

  • The listener is on document, so shortcuts fire wherever focus is on the page.
  • The labels always use ⌘, including on Windows and Linux.
  • Letter shortcuts match lowercase keys, so they do not fire with Caps Lock on.
  • Callbacks should be stable (useCallback); the listener is re-attached when any of them changes.