Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: add keyboard shortcut to buttons (#2819)

Shahmir Varqha0af94f897ac9
diff --git a/frontend/e2e-tests/py/components.py b/frontend/e2e-tests/py/components.py
index 4e710c3cb4..86674279b5 100644
--- a/frontend/e2e-tests/py/components.py
+++ b/frontend/e2e-tests/py/components.py
@@ -1,6 +1,6 @@
import marimo
-__generated_with = "0.5.2"
+__generated_with = "0.9.15"
app = marimo.App()
@@ -14,7 +14,7 @@ def __(mo):
def __(basic_ui_elements, mo):
mo.md(
f"""### Basic elements
-
+
{basic_ui_elements}
"""
)
@@ -25,7 +25,7 @@ def __(basic_ui_elements, mo):
def __(basic_ui_elements, construct_element, show_element):
selected_element = construct_element(basic_ui_elements.value)
show_element(selected_element)
- return selected_element,
+ return (selected_element,)
@app.cell
@@ -49,7 +49,7 @@ def __(composite_elements, mo):
def __(composite_elements, construct_element, show_element):
composite_element = construct_element(composite_elements.value)
show_element(composite_element)
- return composite_element,
+ return (composite_element,)
@app.cell
@@ -70,7 +70,7 @@ def __(mo):
'reused-in-json': 'reused-in-json',
}.items())),
)
- return composite_elements,
+ return (composite_elements,)
@app.cell
@@ -117,7 +117,7 @@ def __(file_area, file_button, mo):
).batch(name=mo.ui.text(), date=mo.ui.date())
elif value == mo.ui.button:
return mo.ui.button(
- value=0, label="click me", on_click=lambda value: value + 1
+ value=0, label="click me", on_click=lambda value: value + 1, keyboard_shortcut="Cmd-l"
)
elif value == mo.ui.checkbox:
return mo.ui.checkbox(label="check me")
@@ -181,7 +181,7 @@ def __(file_area, file_button, mo):
elif value == mo.ui.text_area:
return mo.ui.text_area()
return None
- return construct_element,
+ return (construct_element,)
@app.cell
@@ -189,7 +189,7 @@ def __(mo):
def show_element(element):
if element is not None:
return mo.hstack([element], justify="center")
- return show_element,
+ return (show_element,)
@app.cell
@@ -213,13 +213,13 @@ def __(mo):
The element's current value is {printed_value}
"""
)
- return value,
+ return (value,)
@app.cell
def __():
import marimo as mo
- return mo,
+ return (mo,)
if __name__ == "__main__":
diff --git a/frontend/src/components/ui/button.tsx b/frontend/src/components/ui/button.tsx
index cd0751ee32..3462dc4886 100644
--- a/frontend/src/components/ui/button.tsx
+++ b/frontend/src/components/ui/button.tsx
@@ -4,6 +4,8 @@ import { Slot } from "@radix-ui/react-slot";
import { type VariantProps, cva } from "class-variance-authority";
import { cn } from "@/utils/cn";
+import { parseShortcut } from "@/core/hotkeys/shortcuts";
+import { useEventListener } from "@/hooks/useEventListener";
const activeCommon = "active:shadow-xsSolid";
@@ -90,10 +92,40 @@ export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
Omit<VariantProps<typeof buttonVariants>, "disabled"> {
asChild?: boolean;
+ keyboardShortcut?: string;
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
- ({ className, variant, size, asChild = false, ...props }, ref) => {
+ (
+ { className, variant, size, asChild = false, keyboardShortcut, ...props },
+ ref,
+ ) => {
+ const buttonRef = React.useRef<HTMLButtonElement>(null);
+
+ React.useImperativeHandle(
+ ref,
+ // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style
+ () => buttonRef.current as HTMLButtonElement,
+ );
+
+ const handleKeyPress = React.useCallback(
+ (e: KeyboardEvent) => {
+ if (!keyboardShortcut) {
+ return;
+ }
+ if (parseShortcut(keyboardShortcut)(e)) {
+ e.preventDefault();
+ e.stopPropagation();
+ if (buttonRef?.current && !buttonRef.current.disabled) {
+ buttonRef.current.click();
+ }
+ }
+ },
+ [keyboardShortcut],
+ );
+
+ useEventListener(document, "keydown", handleKeyPress);
+
const Comp = asChild ? Slot : "button";
return (
<Comp
@@ -106,7 +138,7 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
}),
className,
)}
- ref={ref}
+ ref={buttonRef}
{...props}
/>
);
diff --git a/frontend/src/core/hotkeys/__tests__/shortcuts.test.ts b/frontend/src/core/hotkeys/__tests__/shortcuts.test.ts
index b8d33ff009..33740ec68a 100644
--- a/frontend/src/core/hotkeys/__tests__/shortcuts.test.ts
+++ b/frontend/src/core/hotkeys/__tests__/shortcuts.test.ts
@@ -27,6 +27,12 @@ describe("parseShortcut", () => {
expect(shortcut(event)).toBe(true);
});
+ it("should recognize Arrow key shortcuts", () => {
+ const shortcut = parseShortcut("ArrowRight");
+ const event = new KeyboardEvent("keydown", { key: "ArrowRight" });
+ expect(shortcut(event)).toBe(true);
+ });
+
it("should recognize Space key shortcuts", () => {
const shortcut = parseShortcut("Space");
const event = new KeyboardEvent("keydown", { code: "Space" });
@@ -99,4 +105,42 @@ describe("parseShortcut", () => {
expect(parseShortcut("Shift-Enter")(event)).toBe(false);
expect(parseShortcut("Alt-Shift-Enter")(event)).toBe(true);
});
+
+ it("should not recognize shortcuts when one part is missing", () => {
+ const missingShift = new KeyboardEvent("keydown", {
+ key: "a",
+ ctrlKey: true,
+ });
+ const missingCtrl = new KeyboardEvent("keydown", {
+ key: "a",
+ shiftKey: true,
+ });
+ const missingSpecial = new KeyboardEvent("keydown", { key: "a" });
+ const missingLetter = new KeyboardEvent("keydown", {
+ ctrlKey: true,
+ shiftKey: true,
+ });
+ const correctEvent = new KeyboardEvent("keydown", {
+ key: "a",
+ ctrlKey: true,
+ shiftKey: true,
+ });
+
+ expect(parseShortcut("Ctrl-Shift-A")(missingShift)).toBe(false);
+ expect(parseShortcut("Ctrl-Shift-A")(missingCtrl)).toBe(false);
+ expect(parseShortcut("Ctrl-Shift-A")(missingSpecial)).toBe(false);
+ expect(parseShortcut("Ctrl-Shift-A")(missingLetter)).toBe(false);
+ expect(parseShortcut("Ctrl-Shift-A")(correctEvent)).toBe(true);
+ });
+
+ it("should recognize + as a separator", () => {
+ const event = new KeyboardEvent("keydown", {
+ key: "a",
+ ctrlKey: true,
+ shiftKey: true,
+ });
+
+ expect(parseShortcut("Ctrl+Shift+a")(event)).toBe(true);
+ expect(parseShortcut("Ctrl+A")(event)).toBe(false);
+ });
});
diff --git a/frontend/src/core/hotkeys/shortcuts.ts b/frontend/src/core/hotkeys/shortcuts.ts
index 2e58269735..df6def122f 100644
--- a/frontend/src/core/hotkeys/shortcuts.ts
+++ b/frontend/src/core/hotkeys/shortcuts.ts
@@ -20,48 +20,64 @@ export function isPlatformMac() {
return /mac/i.test(platform);
}
-export function parseShortcut(shortcut: string): (e: KeyboardEvent) => boolean {
- const keys = shortcut.split("-");
- return (e: KeyboardEvent) => {
- let satisfied = true;
- for (const character of keys) {
- switch (character) {
- case "Ctrl":
- satisfied &&= e.ctrlKey;
- break;
- case "Cmd":
- satisfied &&= e.metaKey;
- break;
- case "Shift":
- satisfied &&= e.shiftKey;
- break;
- case "Alt":
- satisfied &&= e.altKey;
- break;
- case "Space":
- satisfied &&= e.code === "Space";
- break;
- default:
- satisfied &&= e.key.toLowerCase() === character.toLowerCase();
- break;
- }
-
- if (!satisfied) {
- return false;
- }
- }
- if (!keys.includes("Shift")) {
- satisfied &&= !e.shiftKey;
- }
- if (!keys.includes("Ctrl")) {
- satisfied &&= !e.ctrlKey;
- }
- if (!keys.includes("Cmd")) {
- satisfied &&= !e.metaKey;
+function areKeysPressed(keys: string[], e: KeyboardEvent): boolean {
+ let satisfied = true;
+ for (const key of keys) {
+ switch (key) {
+ case "ctrl":
+ satisfied &&= e.ctrlKey;
+ break;
+ case "meta":
+ satisfied &&= e.metaKey;
+ break;
+ case "shift":
+ satisfied &&= e.shiftKey;
+ break;
+ case "alt":
+ satisfied &&= e.altKey;
+ break;
+ case "space":
+ satisfied &&= e.code === "Space";
+ break;
+ default:
+ satisfied &&= e.key.toLowerCase() === key;
+ break;
}
- if (!keys.includes("Alt")) {
- satisfied &&= !e.altKey;
+
+ if (!satisfied) {
+ return false;
}
- return satisfied;
+ }
+
+ if (!keys.includes("shift")) {
+ satisfied &&= !e.shiftKey;
+ }
+ if (!keys.includes("ctrl")) {
+ satisfied &&= !e.ctrlKey;
+ }
+ if (!keys.includes("meta")) {
+ satisfied &&= !e.metaKey;
+ }
+ if (!keys.includes("alt")) {
+ satisfied &&= !e.altKey;
+ }
+
+ return satisfied;
+}
+
+function normalizeKey(key: string): string {
+ const specialKeys: { [key: string]: string } = {
+ control: "ctrl",
+ command: "meta",
+ cmd: "meta",
+ option: "alt",
+ return: "enter",
};
+ return specialKeys[key.toLowerCase()] || key.toLowerCase();
+}
+
+export function parseShortcut(shortcut: string): (e: KeyboardEvent) => boolean {
+ const separator = shortcut.includes("+") ? "+" : "-";
+ const keys = shortcut.split(separator).map(normalizeKey);
+ return (e: KeyboardEvent) => areKeysPressed(keys, e);
}
diff --git a/frontend/src/plugins/impl/ButtonPlugin.tsx b/frontend/src/plugins/impl/ButtonPlugin.tsx
index ed626eb88b..1dd92b093d 100644
--- a/frontend/src/plugins/impl/ButtonPlugin.tsx
+++ b/frontend/src/plugins/impl/ButtonPlugin.tsx
@@ -7,6 +7,7 @@ import { renderHTML } from "../core/RenderHTML";
import { type Intent, zodIntent } from "./common/intent";
import { cn } from "@/utils/cn";
import { Tooltip, TooltipProvider } from "@/components/ui/tooltip";
+import { KeyboardHotkeys } from "@/components/shortcuts/renderShortcut";
interface Data {
label: string;
@@ -14,6 +15,7 @@ interface Data {
disabled: boolean;
fullWidth: boolean;
tooltip?: string;
+ keyboardShortcut?: string;
}
export class ButtonPlugin implements IPlugin<number, Data> {
@@ -25,11 +27,12 @@ export class ButtonPlugin implements IPlugin<number, Data> {
disabled: z.boolean().default(false),
fullWidth: z.boolean().default(false),
tooltip: z.string().optional(),
+ keyboardShortcut: z.string().optional(),
});
render(props: IPluginProps<number, Data>): JSX.Element {
const {
- data: { disabled, kind, label, fullWidth, tooltip },
+ data: { disabled, kind, label, fullWidth, tooltip, keyboardShortcut },
} = props;
// value counts number of times button was clicked
const button = (
@@ -38,6 +41,7 @@ export class ButtonPlugin implements IPlugin<number, Data> {
variant={kindToButtonVariant(kind)}
disabled={disabled}
size="xs"
+ keyboardShortcut={keyboardShortcut}
className={cn({
"w-full": fullWidth,
})}
@@ -54,10 +58,19 @@ export class ButtonPlugin implements IPlugin<number, Data> {
</Button>
);
- if (tooltip) {
+ const tooltipContent =
+ keyboardShortcut && !tooltip ? (
+ <KeyboardHotkeys shortcut={keyboardShortcut} />
+ ) : (
+ tooltip
+ );
+
+ if (tooltipContent) {
return (
<TooltipProvider>
- <Tooltip content={tooltip}>{button}</Tooltip>
+ <Tooltip content={tooltipContent} delayDuration={200}>
+ {button}
+ </Tooltip>
</TooltipProvider>
);
}
diff --git a/marimo/_plugins/ui/_impl/input.py b/marimo/_plugins/ui/_impl/input.py
index cb7758cad6..952e3d2f8a 100644
--- a/marimo/_plugins/ui/_impl/input.py
+++ b/marimo/_plugins/ui/_impl/input.py
@@ -1123,6 +1123,7 @@ class button(UIElement[Any, Any]):
- `on_change`: optional callback to run when this element's value changes
- `full_width`: whether the input should take up the full width of its
container
+ - `keyboard_shortcut`: keyboard shortcut to trigger the button (e.g. 'Ctrl-L')
"""
_name: Final[str] = "marimo-button"
@@ -1138,6 +1139,7 @@ class button(UIElement[Any, Any]):
label: str = "click here",
on_change: Optional[Callable[[Any], None]] = None,
full_width: bool = False,
+ keyboard_shortcut: Optional[str] = None,
) -> None:
self._on_click = (lambda _: value) if on_click is None else on_click
self._initial_value = value
@@ -1152,6 +1154,7 @@ class button(UIElement[Any, Any]):
"disabled": disabled,
"tooltip": tooltip,
"full-width": full_width,
+ "keyboard-shortcut": keyboard_shortcut,
},
on_change=on_change,
)
diff --git a/marimo/_plugins/ui/_impl/run_button.py b/marimo/_plugins/ui/_impl/run_button.py
index 4cfc8b957f..8c6ad85d9b 100644
--- a/marimo/_plugins/ui/_impl/run_button.py
+++ b/marimo/_plugins/ui/_impl/run_button.py
@@ -55,6 +55,7 @@ class run_button(UIElement[Any, Any]):
- `on_change`: optional callback to run when this element's value changes
- `full_width`: whether the input should take up the full width of its
container
+ - `keyboard_shortcut`: keyboard shortcut to trigger the button (e.g. 'Ctrl-L')
"""
# We reuse the button plugin on the frontend, UI/logic are the same
@@ -69,6 +70,7 @@ class run_button(UIElement[Any, Any]):
label: str = "click to run",
on_change: Optional[Callable[[Any], None]] = None,
full_width: bool = False,
+ keyboard_shortcut: Optional[str] = None,
) -> None:
self._initial_value = False
super().__init__(
@@ -81,6 +83,7 @@ class run_button(UIElement[Any, Any]):
"disabled": disabled,
"tooltip": tooltip,
"full-width": full_width,
+ "keyboard-shortcut": keyboard_shortcut,
},
on_change=on_change,
)