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.
Import#
import { useKeyboardShortcuts } from "@reactberry/system";
Usage#
"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.
API#
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.
| Prop | Type | Default | Description |
|---|---|---|---|
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:
| Prop | Type | Default | Description |
|---|---|---|---|
shortcuts.send | string | "⌘+Enter" | Label for |
shortcuts.saveDraft | string | "⌘+S" | Label for |
shortcuts.preview | string | "⌘+P" | Label for |
shortcuts.schedule | string | "⌘+⇧+S" | Label for |
shortcuts.addAttachment | string | "⌘+U" | Label for |
shortcuts.toggleMode | string | "⌘+M" | Label for |
Keyboard#
| Key | Action |
|---|---|
⌘ + 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.