Shortcut recorder
Record a modifier chord into a native text field, with cancellation, clearing and caller-defined conflicts.
pnpm dlx shadcn@latest add @haze/shortcut-recorder---
import { cn } from "../../../lib/haze/utils";
interface Props {
id: string;
name?: string;
label?: string;
value?: string;
reserved?: string[];
disabled?: boolean;
class?: string;
[key: string]: unknown;
}
const { id, name = id, label = "Open quick search", value = "Ctrl+K", reserved = ["Ctrl+R", "Meta+R", "Ctrl+W", "Meta+W"], disabled, class: className, ...rest } = Astro.props;
const button = "inline-flex min-h-8 cursor-pointer items-center justify-center rounded-lg border border-frame bg-field px-3 text-[0.8125rem]/5 font-medium text-foreground transition-[background-color,scale] duration-150 ease-snappy hover:bg-accent hover:shadow-key active:scale-[0.97] active:duration-75 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring disabled:opacity-50 [&[hidden]]:hidden";
---
<div data-haze-shortcut-recorder data-reserved={JSON.stringify(reserved)} class={cn("grid min-w-0 gap-2", className)}>
<label for={id} class="text-[0.8125rem]/5 font-medium">{label}</label>
<input {...rest} id={id} name={name} value={value} disabled={disabled} type="text" autocomplete="off" spellcheck="false" data-shortcut-field aria-describedby={`${id}-hint ${id}-status`} class="h-10 w-full min-w-0 rounded-lg border border-frame-input bg-field px-3 font-mono text-sm text-foreground transition-[border-color,background-color,box-shadow] duration-150 ease-snappy hover:border-frame-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden aria-[busy=true]:border-foreground disabled:cursor-not-allowed disabled:bg-muted disabled:opacity-50" />
<div class="flex flex-wrap gap-2"><button data-shortcut-record type="button" aria-pressed="false" disabled={disabled} hidden class={button}>Record shortcut</button><button data-shortcut-clear type="button" disabled={disabled} hidden class={button}>Clear</button></div>
<p id={`${id}-hint`} class="text-[0.8125rem]/5 text-muted-foreground">Use a modifier and a key, such as Ctrl+K. Escape cancels recording.</p>
<div data-shortcut-conflict hidden class="flex flex-wrap items-center gap-2 [&[hidden]]:hidden"><button data-shortcut-accept type="button" class={button}>Use anyway</button><button data-shortcut-cancel type="button" class={button}>Cancel</button></div>
<p id={`${id}-status`} data-shortcut-status role="status" class="text-[0.8125rem]/5 text-muted-foreground empty:sr-only"></p>
</div>
<script>
function initShortcutRecorders() {
document.querySelectorAll<HTMLElement>("[data-haze-shortcut-recorder]").forEach(root => {
if (root.hasAttribute("data-enhanced")) return;
const field = root.querySelector<HTMLInputElement>("[data-shortcut-field]");
const record = root.querySelector<HTMLButtonElement>("[data-shortcut-record]");
const clear = root.querySelector<HTMLButtonElement>("[data-shortcut-clear]");
const conflict = root.querySelector<HTMLElement>("[data-shortcut-conflict]");
const status = root.querySelector<HTMLElement>("[data-shortcut-status]");
if (!field || !record || !clear || !conflict || !status) return;
const reserved = JSON.parse(root.dataset.reserved ?? "[]") as string[];
const originalReadOnly = field.readOnly;
let recording = false;
let previous = field.value;
let pending = "";
const stop = () => { recording = false; field.readOnly = originalReadOnly; record.setAttribute("aria-pressed", "false"); field.setAttribute("aria-busy", "false"); record.textContent = "Record shortcut"; };
const save = (value: string) => {
field.value = value;
conflict.hidden = true;
stop();
field.dispatchEvent(new Event("input", { bubbles: true }));
field.dispatchEvent(new Event("change", { bubbles: true }));
status.textContent = value ? `Shortcut recorded: ${value.replaceAll("+", " ")}.` : "Shortcut cleared.";
record.focus();
if (!matchMedia("(prefers-reduced-motion: reduce)").matches) field.animate([{ opacity: .65, translate: "0 2px" }, { opacity: 1, translate: "0 0" }], { duration: 200 });
};
record.hidden = false;
clear.hidden = false;
if (originalReadOnly) { record.disabled = true; clear.disabled = true; }
record.addEventListener("click", () => {
if (recording) { stop(); status.textContent = "Recording cancelled."; return; }
previous = field.value;
conflict.hidden = true;
recording = true;
field.readOnly = true;
record.setAttribute("aria-pressed", "true");
field.setAttribute("aria-busy", "true");
record.textContent = "Cancel recording";
status.textContent = "Recording. Press your shortcut, or Escape to cancel.";
field.focus();
});
field.addEventListener("keydown", event => {
if (!recording || event.isComposing) return;
if (event.key === "Tab") { stop(); status.textContent = "Recording cancelled."; return; }
event.preventDefault();
event.stopPropagation();
if (event.key === "Escape") { field.value = previous; stop(); status.textContent = "Recording cancelled."; record.focus(); return; }
if (event.repeat || ["Control", "Alt", "Shift", "Meta"].includes(event.key)) return;
if (!event.ctrlKey && !event.altKey && !event.metaKey && !/^F\d{1,2}$/.test(event.key)) { status.textContent = "Add Ctrl, Alt or Command to a letter shortcut."; return; }
const key = event.key === " " ? "Space" : event.key.length === 1 ? event.key.toUpperCase() : event.key;
pending = [...(event.ctrlKey ? ["Ctrl"] : []), ...(event.altKey ? ["Alt"] : []), ...(event.shiftKey ? ["Shift"] : []), ...(event.metaKey ? ["Meta"] : []), key].join("+");
stop();
if (reserved.some(value => value.toLowerCase() === pending.toLowerCase())) { conflict.hidden = false; status.textContent = `${pending.replaceAll("+", " ")} is reserved. Choose Use anyway or Cancel.`; root.querySelector<HTMLButtonElement>("[data-shortcut-accept]")?.focus(); }
else save(pending);
});
clear.addEventListener("click", () => save(""));
root.querySelector("[data-shortcut-accept]")?.addEventListener("click", () => save(pending));
root.querySelector("[data-shortcut-cancel]")?.addEventListener("click", () => { field.value = previous; conflict.hidden = true; status.textContent = "Shortcut unchanged."; record.focus(); });
field.addEventListener("blur", event => { if (recording && event.relatedTarget !== record) { stop(); status.textContent = "Recording cancelled."; } });
root.setAttribute("data-enhanced", "");
});
}
initShortcutRecorders();
if (!document.documentElement.hasAttribute("data-haze-shortcut-recorder-listener")) {
document.documentElement.setAttribute("data-haze-shortcut-recorder-listener", "");
document.addEventListener("astro:page-load", initShortcutRecorders);
}
</script>When to use
- A preferences page lets people choose keyboard shortcuts
- A reserved combination should be explained before it replaces the current chord
When not to use
- Use kbd to display an existing shortcut without editing it
- Use input for arbitrary text that should not capture key combinations
Installation
Add the Haze registry to components.json once, then install Shortcut recorder with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/shortcut-recordernpx shadcn@latest add @haze/shortcut-recorderyarn dlx shadcn@latest add @haze/shortcut-recorderbunx --bun shadcn@latest add @haze/shortcut-recorderFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Unique caller-supplied prefix for this component and its related elements. |
| name | string | id | Form submission name. |
| label | string | "Open quick search" | Visible name of the command being configured. |
| value | string | "Ctrl+K" | Initial chord written with plus separators. |
| reserved | string[] | Ctrl+R, Meta+R, Ctrl+W, Meta+W | Case-insensitive chord strings that require Use anyway confirmation. |
| disabled | boolean | – | Disables the native control and its enhancement. |
| class | string | – | Additional classes for the component root. |
| ...attributes | native control attributes | – | Other attributes are forwarded to the real form control. |
Keyboard interactions
- Enter or Space on Record
- Begin capturing the next modifier chord.
- Ctrl, Alt or Command plus a key
- Record a combination; function keys may be used alone.
- Escape, Tab
- Cancel recording and keep the previous shortcut.
Accessibility
- Recording starts only from an explicit button; Tab and Escape leave the capture mode.
- The native text field stays editable outside recording and remains usable with no JavaScript.
- Conflicts keep the prior chord until Use anyway is chosen, with the outcome announced in the linked status text.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Shortcut recorder" with `npx shadcn@latest add @haze/shortcut-recorder`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import ShortcutRecorder from "@/components/haze/ui/shortcut-recorder.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/shortcut-recorder.md
Customize with real content
Adapt the Haze shortcut-recorder ui for our product. Replace the demo values of these props with our real content: id, name, label, value, reserved, disabled, class, ...attributes. Keep the layout, the heading level rules and these accessibility details: Recording starts only from an explicit button; Tab and Escape leave the capture mode. The native text field stays editable outside recording and remains usable with no JavaScript. Conflicts keep the prior chord until Use anyway is chosen, with the outcome announced in the linked status text. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using shortcut-recorder, check it fits: use it when a preferences page lets people choose keyboard shortcuts; a reserved combination should be explained before it replaces the current chord. Avoid it when use kbd to display an existing shortcut without editing it; use input for arbitrary text that should not capture key combinations. Alternatives: @haze/kbd, @haze/input.
Dependencies
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.