Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: Button shortcut prop — hotkeys via useShortcutKeys with keycap badge, KeyboardKeys enum, dialog guard
aashu12f97afac041
diff --git a/packages/react/src/Button.tsx b/packages/react/src/Button.tsxindex f7c9041390..465222cd88 100644--- a/packages/react/src/Button.tsx+++ b/packages/react/src/Button.tsx@@ -2,9 +2,14 @@ import { Slot, Slottable } from "@radix-ui/react-slot";import type { VariantProps } from "class-variance-authority";import { cva } from "class-variance-authority";import type { ButtonHTMLAttributes, ReactElement } from "react";-import { cloneElement, forwardRef } from "react";+import { cloneElement, forwardRef, useCallback, useRef } from "react";+import type { ShortcutInput } from "./hooks/useShortcutKeys";+import { useShortcutKeys } from "./hooks/useShortcutKeys";+import { ShortcutKey } from "./ShortcutKey";import { Spinner } from "./Spinner";import { cn } from "./utils/cn";+import { hasOpenDialog, isInsideOpenDialog } from "./utils/dialog";+import { mergeRefs } from "./utils/react";export const buttonVariants = cva([@@ -122,6 +127,16 @@ export interface ButtonPropsleftIcon?: ReactElement;rightIcon?: ReactElement;isRound?: boolean;+ /**+ * Keyboard binding(s) that click this button — a react-hotkeys-hook string+ * like `"mod+s"` or `"enter"` (or a structured `ShortcutDefinition` for+ * per-platform combos), or an array of alternatives that all trigger the+ * action; the badge shows the first. Inert while the button is disabled or+ * loading, and while a dialog the button isn't inside is open.+ */+ shortcut?: ShortcutInput | ShortcutInput[];+ /** Keep the hotkey active but hide the visual key badge. */+ hideShortcutKey?: boolean;}const Button = forwardRef<HTMLButtonElement, ButtonProps>(@@ -137,12 +152,44 @@ const Button = forwardRef<HTMLButtonElement, ButtonProps>(isRound = false,leftIcon,rightIcon,+ shortcut,+ hideShortcutKey = false,children,...props},ref) => {const Comp = asChild ? Slot : "button";+ const innerRef = useRef<HTMLButtonElement>(null);+ // The badge shows the first binding; the rest are silent alternatives.+ const primaryShortcut = Array.isArray(shortcut) ? shortcut[0] : shortcut;+ const badgeShortcut =+ !hideShortcutKey && !isIcon && !isLoading ? primaryShortcut : undefined;++ // While any dialog is open, only buttons inside one respond to their+ // shortcut — a background ⌘S must not fire under a confirmation modal.+ const dialogGuard = useCallback(+ () => !hasOpenDialog() || isInsideOpenDialog(innerRef.current),+ []+ );++ // Ref-click (not a direct onClick call) so type="submit" buttons submit+ // their form, and a disabled element's click() stays a native no-op.+ // preventDefault first: when THIS button has focus, a bare Enter/Space+ // would also activate it natively — one keypress, two clicks — and for+ // combos it suppresses browser defaults like ⌘S's save dialog.+ const clickSelf = useCallback((event: KeyboardEvent) => {+ event.preventDefault();+ innerRef.current?.click();+ }, []);++ useShortcutKeys({+ shortcut,+ action: clickSelf,+ guard: dialogGuard,+ disabled: Boolean(isDisabled || props.disabled || isLoading)+ });+return (<Comp{...props}@@ -160,7 +207,7 @@ const Button = forwardRef<HTMLButtonElement, ButtonProps>(type={asChild ? undefined : (props.type ?? "button")}disabled={isDisabled || props.disabled}role={asChild ? undefined : "button"}- ref={ref}+ ref={mergeRefs(ref, innerRef)}>{isLoading && (<Spinner className={cn("size-4 flex-shrink-0", !isIcon && "mr-2")} />@@ -175,7 +222,16 @@ const Button = forwardRef<HTMLButtonElement, ButtonProps>({/* An icon button's icon arrives as children — while loading, thespinner must REPLACE it or both clip inside the square hit area. */}{isIcon && isLoading ? null : <Slottable>{children}</Slottable>}- {rightIcon &&+ {badgeShortcut && (+ <ShortcutKey+ shortcut={badgeShortcut}+ variant={size === "lg" ? "medium" : "small"}+ />+ )}+ {/* The badge owns the trailing slot — a rightIcon next to it reads+ cluttered, so the badge wins while it's visible. */}+ {!badgeShortcut &&+ rightIcon &&cloneElement(rightIcon, {className: !rightIcon.props?.size? cn("ml-2 h-4 w-4 flex-shrink-0", rightIcon.props.className)diff --git a/packages/react/src/ShortcutKey.tsx b/packages/react/src/ShortcutKey.tsxindex 700f2a4450..3aff39577a 100644--- a/packages/react/src/ShortcutKey.tsx+++ b/packages/react/src/ShortcutKey.tsx@@ -1,26 +1,49 @@import { Fragment } from "react";+import type { IconType } from "react-icons";import {+ LuArrowBigUp,LuChevronDown,LuChevronLeft,LuChevronRight,- LuChevronUp+ LuChevronUp,+ LuCommand,+ LuCornerDownLeft,+ LuDelete,+ LuOption,+ LuSpace} from "react-icons/lu";-import type { Modifier, ShortcutDefinition } from "./hooks/useShortcutKeys";+import type { Modifier, ShortcutInput } from "./hooks/useShortcutKeys";+import { parseShortcut } from "./hooks/useShortcutKeys";import { useOperatingSystem } from "./OperatingSystem";import { cn } from "./utils/cn";export const shortcutKeyVariants = {small:- "text-[0.6rem] font-medium min-w-[17px] rounded-[2px] px-1 ml-1 -mr-0.5 grid place-content-center border border-dimmed/40 text-text-dimmed group-hover:text-text-bright/80 group-hover:border-dimmed/60 transition uppercase",+ "flex h-4 min-w-4 items-center justify-center gap-0.5 rounded-[3px] border border-current/25 bg-white/10 px-1 ml-1.5 -mr-0.5 text-[0.65rem] font-medium uppercase text-current/80 shadow-sm backdrop-blur-sm",medium:- "text-[0.75rem] font-medium min-w-[17px] rounded-[2px] px-1 ml-1 -mr-0.5 grid place-content-center border border-dimmed/40 text-text-dimmed group-hover:text-text-bright/80 group-hover:border-dimmed/60 transition uppercase"+ "flex h-4.5 min-w-4.5 items-center justify-center gap-0.5 rounded-[3px] border border-current/25 bg-white/10 px-1 ml-1.5 -mr-0.5 text-[0.75rem] font-medium uppercase text-current/80 shadow-sm backdrop-blur-sm"};export type ShortcutKeyVariant = keyof typeof shortcutKeyVariants;+/**+ * Keys that render as a centered SVG instead of a letter — an icon beats a+ * text glyph for optical centering inside the keycap. Anything not listed+ * falls back to its text form.+ */+export const SHORTCUT_KEY_ICON_MAP: Partial<Record<string, IconType>> = {+ enter: LuCornerDownLeft,+ space: LuSpace,+ backspace: LuDelete,+ arrowup: LuChevronUp,+ arrowdown: LuChevronDown,+ arrowleft: LuChevronLeft,+ arrowright: LuChevronRight+};+type ShortcutKeyProps = {- shortcut: ShortcutDefinition;+ shortcut: ShortcutInput;variant: ShortcutKeyVariant;className?: string;};@@ -32,53 +55,70 @@ export const ShortcutKey = ({}: ShortcutKeyProps) => {const { platform } = useOperatingSystem();const isMac = platform === "mac";- let relevantShortcut =- "mac" in shortcut ? (isMac ? shortcut.mac : shortcut.windows) : shortcut;+ const relevantShortcut = parseShortcut(shortcut, isMac);+ if (!relevantShortcut) return null;const modifiers = relevantShortcut.modifiers ?? [];- const character = keyString(relevantShortcut.key, isMac, variant);+ const character = keyString(String(relevantShortcut.key), isMac, variant);return (<span className={cn(shortcutKeyVariants[variant], className)}>{modifiers.map((k) => (- <Fragment key={k}>{modifierString(k, isMac)}</Fragment>+ <Fragment key={k}>{modifierNode(k, isMac, variant)}</Fragment>))}{character}</span>);};-function keyString(key: String, isMac: boolean, size: "small" | "medium") {+function iconClassName(size: ShortcutKeyVariant) {+ return size === "small" ? "size-2.5 shrink-0" : "size-3 shrink-0";+}++function keyString(key: string, isMac: boolean, size: ShortcutKeyVariant) {key = key.toLowerCase();- const className = size === "small" ? "w-2.5 h-4" : "w-3 h-5";+ const Icon = SHORTCUT_KEY_ICON_MAP[key];+ if (Icon) {+ return <Icon className={iconClassName(size)} aria-hidden="true" />;+ }switch (key) {- case "enter":- return isMac ? "↵" : key;- case "arrowdown":- return <LuChevronDown className={className} />;- case "arrowup":- return <LuChevronUp className={className} />;- case "arrowleft":- return <LuChevronLeft className={className} />;- case "arrowright":- return <LuChevronRight className={className} />;+ case "escape":+ return "esc";default:return key;}}-function modifierString(modifier: Modifier, isMac: boolean) {+function modifierNode(+ modifier: Modifier,+ isMac: boolean,+ size: ShortcutKeyVariant+) {+ const className = iconClassName(size);+ if (isMac) {+ switch (modifier) {+ case "alt":+ return <LuOption className={className} aria-hidden="true" />;+ case "ctrl":+ return "⌃";+ case "meta":+ case "mod":+ return <LuCommand className={className} aria-hidden="true" />;+ case "shift":+ return <LuArrowBigUp className={className} aria-hidden="true" />;+ }+ }switch (modifier) {case "alt":- return isMac ? "⌥" : "Alt+";+ return "Alt+";case "ctrl":- return isMac ? "⌃" : "Ctrl+";+ return "Ctrl+";case "meta":- return isMac ? "⌘" : "⊞+";+ return "⊞+";case "shift":- return isMac ? "⇧" : "Shift+";+ return "Shift+";case "mod":- return isMac ? "⌘" : "Ctrl+";+ return "Ctrl+";}}diff --git a/packages/react/src/__tests__/useShortcutKeys.test.ts b/packages/react/src/__tests__/useShortcutKeys.test.tsnew file mode 100644index 0000000000..4367868331--- /dev/null+++ b/packages/react/src/__tests__/useShortcutKeys.test.ts@@ -0,0 +1,102 @@+import { describe, expect, it } from "vitest";+import {+ KeyboardKeys,+ parseShortcut,+ resolveShortcutKeys+} from "../hooks/useShortcutKeys";++describe("resolveShortcutKeys", () => {+ it("returns [] for undefined", () => {+ expect(resolveShortcutKeys(undefined, true)).toEqual([]);+ });++ it("resolves a single shortcut without modifiers", () => {+ expect(resolveShortcutKeys({ key: KeyboardKeys.S }, true)).toEqual(["s"]);+ });++ it("resolves modifiers into a joined combo string", () => {+ expect(+ resolveShortcutKeys({ key: KeyboardKeys.S, modifiers: ["mod"] }, true)+ ).toEqual(["mod+s"]);+ expect(+ resolveShortcutKeys(+ { key: KeyboardKeys.Enter, modifiers: ["shift", "alt"] },+ false+ )+ ).toEqual(["shift+alt+enter"]);+ });++ it("resolves an array of alternatives, preserving order", () => {+ expect(+ resolveShortcutKeys(+ [{ key: KeyboardKeys.Space }, { key: KeyboardKeys.Enter }],+ true+ )+ ).toEqual(["space", "enter"]);+ });++ it("picks the mac arm of a dual-platform definition on mac", () => {+ const definition = {+ mac: { key: KeyboardKeys.Enter, modifiers: ["meta" as const] },+ windows: { key: KeyboardKeys.Enter, modifiers: ["ctrl" as const] }+ };+ expect(resolveShortcutKeys(definition, true)).toEqual(["meta+enter"]);+ expect(resolveShortcutKeys(definition, false)).toEqual(["ctrl+enter"]);+ });++ it("accepts plain string keys alongside the enum", () => {+ expect(resolveShortcutKeys({ key: "f2" }, true)).toEqual(["f2"]);+ });++ it("passes string bindings through, lowercased and trimmed", () => {+ expect(resolveShortcutKeys("mod+S", true)).toEqual(["mod+s"]);+ expect(resolveShortcutKeys("mod + s", true)).toEqual(["mod+s"]);+ expect(resolveShortcutKeys(["space", "Enter"], true)).toEqual([+ "space",+ "enter"+ ]);+ expect(resolveShortcutKeys(" ", true)).toEqual([]);+ });++ it("mixes string and structured bindings", () => {+ expect(+ resolveShortcutKeys(+ ["mod+s", { key: KeyboardKeys.Enter, modifiers: ["shift"] }],+ true+ )+ ).toEqual(["mod+s", "shift+enter"]);+ });+});++describe("parseShortcut", () => {+ it("splits a string binding into modifiers and key", () => {+ expect(parseShortcut("mod+s", true)).toEqual({+ key: "s",+ modifiers: ["mod"]+ });+ expect(parseShortcut("ctrl+shift+enter", false)).toEqual({+ key: "enter",+ modifiers: ["ctrl", "shift"]+ });+ });++ it("treats a bare key as modifier-free", () => {+ expect(parseShortcut("enter", true)).toEqual({+ key: "enter",+ modifiers: []+ });+ });++ it("keeps a lone modifier-looking token as the key", () => {+ expect(parseShortcut("mod", true)).toEqual({ key: "mod", modifiers: [] });+ });++ it("picks the platform arm of a structured definition", () => {+ const definition = {+ mac: { key: KeyboardKeys.Enter, modifiers: ["meta" as const] },+ windows: { key: KeyboardKeys.Enter, modifiers: ["ctrl" as const] }+ };+ expect(parseShortcut(definition, true)).toEqual(definition.mac);+ expect(parseShortcut(definition, false)).toEqual(definition.windows);+ });+});diff --git a/packages/react/src/hooks/useShortcutKeys.ts b/packages/react/src/hooks/useShortcutKeys.tsindex ffc6ca537a..19244a99ff 100644--- a/packages/react/src/hooks/useShortcutKeys.ts+++ b/packages/react/src/hooks/useShortcutKeys.ts@@ -3,8 +3,80 @@ import { useOperatingSystem } from "../OperatingSystem";export type Modifier = "alt" | "ctrl" | "meta" | "shift" | "mod";+/**+ * Key names react-hotkeys-hook matches against (lowercased `KeyboardEvent.key`,+ * plus its `space` alias). Use these for `Shortcut.key` so combos are+ * autocomplete-safe instead of stringly-typed.+ */+export enum KeyboardKeys {+ // Control+ Enter = "enter",+ Escape = "escape",+ Space = "space",+ Tab = "tab",+ Backspace = "backspace",+ Delete = "delete",++ // Navigation+ ArrowUp = "arrowup",+ ArrowDown = "arrowdown",+ ArrowLeft = "arrowleft",+ ArrowRight = "arrowright",+ Home = "home",+ End = "end",+ PageUp = "pageup",+ PageDown = "pagedown",++ // Punctuation+ Slash = "slash",+ Period = "period",+ Comma = "comma",+ Minus = "minus",+ Equal = "equal",++ // Letters+ A = "a",+ B = "b",+ C = "c",+ D = "d",+ E = "e",+ F = "f",+ G = "g",+ H = "h",+ I = "i",+ J = "j",+ K = "k",+ L = "l",+ M = "m",+ N = "n",+ O = "o",+ P = "p",+ Q = "q",+ R = "r",+ S = "s",+ T = "t",+ U = "u",+ V = "v",+ W = "w",+ X = "x",+ Y = "y",+ Z = "z",++ // Digits+ Digit0 = "0",+ Digit1 = "1",+ Digit2 = "2",+ Digit3 = "3",+ Digit4 = "4",+ Digit5 = "5",+ Digit6 = "6",+ Digit7 = "7",+ Digit8 = "8",+ Digit9 = "9"+}+export type Shortcut = {- key: string;+ key: string | KeyboardKeys;modifiers?: Modifier[];enabledOnInputElements?: boolean;};@@ -16,55 +88,104 @@ export type ShortcutDefinition =}| Shortcut;+/**+ * A binding is either the react-hotkeys-hook string form ("mod+s", "enter")+ * or a structured definition (which can carry separate mac/windows combos).+ */+export type ShortcutInput = string | ShortcutDefinition;+type useShortcutKeysProps = {- shortcut: ShortcutDefinition | undefined;+ /** One binding, or several alternatives that all trigger the same action. */+ shortcut: ShortcutInput | ShortcutInput[] | undefined;action: (event: KeyboardEvent) => void;disabled?: boolean;enabledOnInputElements?: boolean;+ /** Runs before `action`; returning false skips the action (the event is untouched). */+ guard?: (event: KeyboardEvent) => boolean;};+const MODIFIER_TOKENS = new Set(["alt", "ctrl", "meta", "shift", "mod"]);++/**+ * Resolve one binding to the structured `Shortcut` shape (used by the+ * `ShortcutKey` badge renderer). A string binding like `"mod+s"` splits into+ * leading modifier tokens plus the key; a dual-platform definition picks its+ * mac/windows arm.+ */+export function parseShortcut(+ shortcut: ShortcutInput,+ isMac: boolean+): Shortcut | undefined {+ if (typeof shortcut === "string") {+ const tokens = shortcut+ .toLowerCase()+ .split("+")+ .map((token) => token.trim())+ .filter(Boolean);+ if (tokens.length === 0) return undefined;+ const modifiers: Modifier[] = [];+ while (tokens.length > 1 && MODIFIER_TOKENS.has(tokens[0] ?? "")) {+ modifiers.push(tokens.shift() as Modifier);+ }+ return { key: tokens.join("+"), modifiers };+ }+ if ("mac" in shortcut) {+ return isMac ? shortcut.mac : shortcut.windows;+ }+ return "key" in shortcut ? shortcut : undefined;+}++/**+ * Normalize one-or-many bindings into the key strings react-hotkeys-hook+ * consumes (e.g. `"mod+s"`, `"enter"`). String bindings pass through+ * (lowercased); structured definitions pick their platform arm and join+ * modifiers.+ */+export function resolveShortcutKeys(+ shortcut: ShortcutInput | ShortcutInput[] | undefined,+ isMac: boolean+): string[] {+ if (!shortcut) return [];+ const bindings = Array.isArray(shortcut) ? shortcut : [shortcut];+ return bindings.flatMap((binding) => {+ const resolved = parseShortcut(binding, isMac);+ if (!resolved) return [];+ return resolved.modifiers?.length+ ? resolved.modifiers.join("+") + "+" + resolved.key+ : String(resolved.key);+ });+}+export function useShortcutKeys({shortcut,action,disabled = false,- enabledOnInputElements+ enabledOnInputElements,+ guard}: useShortcutKeysProps) {const { platform } = useOperatingSystem();const isMac = platform === "mac";- const relevantShortcut: Shortcut | undefined =- shortcut && "mac" in shortcut- ? isMac- ? shortcut.mac- : shortcut.windows- : shortcut && "key" in shortcut- ? shortcut- : undefined;-- const keys = createKeysFromShortcut(relevantShortcut);++ const firstBinding = Array.isArray(shortcut) ? shortcut[0] : shortcut;+ const firstShortcut = firstBinding+ ? parseShortcut(firstBinding, isMac)+ : undefined;++ const keys = resolveShortcutKeys(shortcut, isMac);useHotkeys(keys,- (event, hotkeysEvent) => {+ (event) => {+ if (guard && !guard(event)) return;action(event);},{enabled: !disabled,+ // With multiple bindings, only the FIRST one's `enabledOnInputElements`+ // is honored — the options apply to the whole registration.enableOnFormTags:- enabledOnInputElements ?? relevantShortcut?.enabledOnInputElements,+ enabledOnInputElements ?? firstShortcut?.enabledOnInputElements,enableOnContentEditable:- enabledOnInputElements ?? relevantShortcut?.enabledOnInputElements+ enabledOnInputElements ?? firstShortcut?.enabledOnInputElements});}--function createKeysFromShortcut(shortcut: Shortcut | undefined) {- if (!shortcut) {- return [];- }-- const modifiers = shortcut.modifiers;- const character = shortcut.key;-- return modifiers- ? modifiers.map((k) => k).join("+") + "+" + character- : character;-}diff --git a/packages/react/src/index.tsx b/packages/react/src/index.tsxindex 5596e610e5..527b603433 100644--- a/packages/react/src/index.tsx+++ b/packages/react/src/index.tsx@@ -155,8 +155,10 @@ import { generateHTML, HTML } from "./HTML";import type {Modifier,Shortcut,- ShortcutDefinition+ ShortcutDefinition,+ ShortcutInput} from "./hooks/useShortcutKeys";+import { KeyboardKeys } from "./hooks/useShortcutKeys";import { IconButton } from "./IconButton";import type { InputProps } from "./Input";import {@@ -342,6 +344,7 @@ import {import { TruncatedTooltipText } from "./TruncatedTooltipText";import { TVColorBars } from "./TVColorBars";import { cn } from "./utils/cn";+import { hasOpenDialog, isInsideOpenDialog } from "./utils/dialog";import { copyToClipboard } from "./utils/dom";import { getValidChildren, reactNodeToString } from "./utils/react";import { VStack } from "./VStack";@@ -567,7 +570,10 @@ export {SelectTrigger,SelectValue,Separator,+ KeyboardKeys,ShortcutKey,+ hasOpenDialog,+ isInsideOpenDialog,Sidebar,SidebarContent,SidebarFooter,@@ -659,6 +665,7 @@ export type {OperatingSystemPlatform,Shortcut,ShortcutDefinition,+ ShortcutInput,TextareaProps,ExpiredEntityPolicy,TrackedEntityOption,diff --git a/packages/react/src/utils/dialog.ts b/packages/react/src/utils/dialog.tsnew file mode 100644index 0000000000..0af4021da8--- /dev/null+++ b/packages/react/src/utils/dialog.ts@@ -0,0 +1,15 @@+// Radix stamps open dialogs (Modal, Drawer, ModalDrawer, …) with this+// attribute pair. Keep the selector here — it is an implementation detail of+// Radix that must not be hand-written at call sites.+const OPEN_DIALOG_SELECTOR = '[role="dialog"][data-state="open"]';++export function hasOpenDialog(): boolean {+ return document.querySelector(OPEN_DIALOG_SELECTOR) !== null;+}++export function isInsideOpenDialog(element: Element | null): boolean {+ if (!element) return false;+ return Array.from(document.querySelectorAll(OPEN_DIALOG_SELECTOR)).some(+ (dialog) => dialog.contains(element)+ );+}