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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix keyboard shortcuts for input elements inside shadow DOM (#9105)
Shahmir Varqhab3c01613bad2
diff --git a/frontend/src/components/ui/button.tsx b/frontend/src/components/ui/button.tsxindex efeee61787..51680a2cd6 100644--- a/frontend/src/components/ui/button.tsx+++ b/frontend/src/components/ui/button.tsx@@ -114,11 +114,10 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(const handleKeyPress = React.useCallback((e: KeyboardEvent) => {- if (!keyboardShortcut) {+ if (!keyboardShortcut || e.defaultPrevented) {return;}- // Ignore keyboard events from input elementsif (Events.shouldIgnoreKeyboardEvent(e)) {return;}diff --git a/frontend/src/utils/__tests__/events.test.ts b/frontend/src/utils/__tests__/events.test.tsnew file mode 100644index 0000000000..1150cbbd09--- /dev/null+++ b/frontend/src/utils/__tests__/events.test.ts@@ -0,0 +1,223 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { describe, expect, test } from "vitest";+import { Events } from "../events";++/**+ * Create a minimal fake event with just a target (no composedPath).+ * Simulates synthetic events from libraries like React Aria.+ */+function fakeEvent(target: EventTarget): Pick<Event, "target"> {+ return { target };+}++/**+ * Create a fake native-like KeyboardEvent with composedPath() returning+ * a different element than target — the key scenario for shadow DOM+ * retargeting where target is the shadow host but composedPath()[0]+ * is the real focused element inside the shadow root.+ */+function fakeNativeEvent(+ retargetedHost: EventTarget,+ realTarget: EventTarget,+): KeyboardEvent {+ const event = new KeyboardEvent("keydown");+ Object.defineProperty(event, "target", { value: retargetedHost });+ Object.defineProperty(event, "composedPath", {+ value: () => [realTarget, retargetedHost, document.body, document],+ });+ return event;+}++describe("Events.composedTarget", () => {+ test("returns composedPath()[0] for native events", () => {+ const input = document.createElement("input");+ const host = document.createElement("div");+ const event = fakeNativeEvent(host, input);++ expect(Events.composedTarget(event)).toBe(input);+ });++ test("falls back to e.target when composedPath is absent", () => {+ const div = document.createElement("div");+ const event = fakeEvent(div);++ expect(Events.composedTarget(event)).toBe(div);+ });++ test("falls back to e.target when composedPath returns empty array", () => {+ const div = document.createElement("div");+ const event = new KeyboardEvent("keydown");+ Object.defineProperty(event, "target", { value: div });+ Object.defineProperty(event, "composedPath", { value: () => [] });++ expect(Events.composedTarget(event)).toBe(div);+ });+});++describe("Events.shouldIgnoreKeyboardEvent", () => {+ test("ignores events from <input>", () => {+ const input = document.createElement("input");+ const event = fakeNativeEvent(input, input);+ expect(Events.shouldIgnoreKeyboardEvent(event)).toBe(true);+ });++ test("ignores events from <textarea>", () => {+ const textarea = document.createElement("textarea");+ const event = fakeNativeEvent(textarea, textarea);+ expect(Events.shouldIgnoreKeyboardEvent(event)).toBe(true);+ });++ test("ignores events from <select>", () => {+ const select = document.createElement("select");+ const event = fakeNativeEvent(select, select);+ expect(Events.shouldIgnoreKeyboardEvent(event)).toBe(true);+ });++ test("ignores events from <button>", () => {+ const button = document.createElement("button");+ const event = fakeNativeEvent(button, button);+ expect(Events.shouldIgnoreKeyboardEvent(event)).toBe(true);+ });++ test("ignores events from contentEditable elements", () => {+ const div = document.createElement("div");+ div.setAttribute("contenteditable", "true");+ document.body.append(div);++ const event = fakeNativeEvent(div, div);+ expect(Events.shouldIgnoreKeyboardEvent(event)).toBe(true);++ div.remove();+ });++ test("ignores events from elements with role='textbox'", () => {+ const container = document.createElement("div");+ container.setAttribute("role", "textbox");+ const child = document.createElement("span");+ container.append(child);+ document.body.append(container);++ const event = fakeNativeEvent(child, child);+ expect(Events.shouldIgnoreKeyboardEvent(event)).toBe(true);++ container.remove();+ });++ test("ignores events from inside .cm-editor", () => {+ const editor = document.createElement("div");+ editor.className = "cm-editor";+ const line = document.createElement("div");+ editor.append(line);+ document.body.append(editor);++ const event = fakeNativeEvent(line, line);+ expect(Events.shouldIgnoreKeyboardEvent(event)).toBe(true);++ editor.remove();+ });++ test("does NOT ignore events from a plain <div>", () => {+ const div = document.createElement("div");+ const event = fakeNativeEvent(div, div);+ expect(Events.shouldIgnoreKeyboardEvent(event)).toBe(false);+ });++ describe("shadow DOM retargeting (#4230)", () => {+ test("ignores keydown when real target inside shadow root is <input>", () => {+ const host = document.createElement("marimo-text");+ const input = document.createElement("input");+ // event.target is the shadow host, composedPath()[0] is the real input+ const event = fakeNativeEvent(host, input);+ expect(Events.shouldIgnoreKeyboardEvent(event)).toBe(true);+ });++ test("ignores keydown when real target inside shadow root is <textarea>", () => {+ const host = document.createElement("marimo-text-area");+ const textarea = document.createElement("textarea");+ const event = fakeNativeEvent(host, textarea);+ expect(Events.shouldIgnoreKeyboardEvent(event)).toBe(true);+ });++ test("ignores keydown when real target inside shadow root is <select>", () => {+ const host = document.createElement("marimo-dropdown");+ const select = document.createElement("select");+ const event = fakeNativeEvent(host, select);+ expect(Events.shouldIgnoreKeyboardEvent(event)).toBe(true);+ });++ test("does NOT ignore when shadow DOM real target is a plain <div>", () => {+ const host = document.createElement("marimo-output");+ const div = document.createElement("div");+ const event = fakeNativeEvent(host, div);+ expect(Events.shouldIgnoreKeyboardEvent(event)).toBe(false);+ });+ });++ test("does NOT ignore events from non-marimo custom elements", () => {+ const el = document.createElement("sl-input");+ const event = fakeNativeEvent(el, el);+ expect(Events.shouldIgnoreKeyboardEvent(event)).toBe(false);+ });+});++describe("Events.fromInput", () => {+ test("returns true for <input>", () => {+ const input = document.createElement("input");+ expect(Events.fromInput(fakeEvent(input))).toBe(true);+ });++ test("returns true for <textarea>", () => {+ const textarea = document.createElement("textarea");+ expect(Events.fromInput(fakeEvent(textarea))).toBe(true);+ });++ test("returns true for marimo custom elements", () => {+ const el = document.createElement("marimo-slider");+ expect(Events.fromInput(fakeEvent(el))).toBe(true);+ });++ // jsdom does not implement isContentEditable, so this is tested+ // via shouldIgnoreKeyboardEvent which has a closest() fallback.+ test.skip("returns true for contentEditable", () => {+ const div = document.createElement("div");+ div.setAttribute("contenteditable", "true");+ document.body.append(div);++ expect(Events.fromInput(fakeEvent(div))).toBe(true);++ div.remove();+ });++ test("returns false for plain <div>", () => {+ const div = document.createElement("div");+ expect(Events.fromInput(fakeEvent(div))).toBe(false);+ });++ test("uses composedPath when available (shadow DOM)", () => {+ const host = document.createElement("div");+ const input = document.createElement("input");+ const event = fakeNativeEvent(host, input);+ expect(Events.fromInput(event)).toBe(true);+ });+});++describe("Events.fromCodeMirror", () => {+ test("returns true when target is inside .cm-editor", () => {+ const editor = document.createElement("div");+ editor.className = "cm-editor";+ const line = document.createElement("div");+ editor.append(line);+ document.body.append(editor);++ expect(Events.fromCodeMirror(line)).toBe(true);+ editor.remove();+ });++ test("returns false when target is not inside .cm-editor", () => {+ const div = document.createElement("div");+ document.body.append(div);+ expect(Events.fromCodeMirror(div)).toBe(false);+ div.remove();+ });+});diff --git a/frontend/src/utils/events.ts b/frontend/src/utils/events.tsindex 3f68f0732b..789bb14876 100644--- a/frontend/src/utils/events.ts+++ b/frontend/src/utils/events.ts@@ -37,21 +37,20 @@ export const Events = {* Returns true if the event is coming from a text input*/fromInput: (e: Pick<KeyboardEvent, "target">) => {- const target = e.target as HTMLElement;+ const target = Events.composedTarget(e);return (target.tagName === "INPUT" ||target.tagName === "TEXTAREA" ||target.tagName.startsWith("MARIMO") ||target.isContentEditable ||- Events.fromCodeMirror(e)+ Events.fromCodeMirror(target));},/*** Returns true if the event is coming from a code editor.*/- fromCodeMirror: (e: Pick<KeyboardEvent, "target">) => {- const target = e.target as HTMLElement;+ fromCodeMirror: (target: HTMLElement) => {return target.closest(".cm-editor") !== null;},@@ -60,20 +59,35 @@ export const Events = {* form element or code editor.*/shouldIgnoreKeyboardEvent(e: KeyboardEvent) {- // Check for common form elements where keyboard shortcuts should be ignored+ const target = Events.composedTarget(e);return (- e.target instanceof HTMLInputElement ||- e.target instanceof HTMLTextAreaElement ||- e.target instanceof HTMLSelectElement ||- (e.target instanceof HTMLElement &&- (e.target.isContentEditable ||- e.target.tagName === "BUTTON" ||- e.target.closest("[role='textbox']") !== null ||- e.target.closest("[contenteditable='true']") !== null ||- e.target.closest(".cm-editor") !== null)) // Add check for CodeMirror editor+ target instanceof HTMLInputElement ||+ target instanceof HTMLTextAreaElement ||+ target instanceof HTMLSelectElement ||+ (target instanceof HTMLElement &&+ (target.isContentEditable ||+ target.tagName === "BUTTON" ||+ target.closest("[role='textbox']") !== null ||+ target.closest("[contenteditable='true']") !== null ||+ Events.fromCodeMirror(target))));},+ /**+ * Resolve the real event target, piercing shadow DOM retargeting.+ * Falls back to e.target for synthetic events (e.g. React Aria)+ * that don't expose composedPath.+ *+ * Without this, e.target is the shadow host (e.g. <marimo-text>) rather than the+ * real <input> inside it, so instanceof checks fail. (#4230)+ */+ composedTarget(e: Pick<Event, "target">): HTMLElement {+ if ("composedPath" in e && typeof e.composedPath === "function") {+ return (e.composedPath()[0] ?? e.target) as HTMLElement;+ }+ return e.target as HTMLElement;+ },+hasModifier: (e: Pick<KeyboardEvent, "ctrlKey" | "metaKey" | "altKey" | "shiftKey">,) => {diff --git a/marimo/_smoke_tests/inputs/keyboard_shortcuts.py b/marimo/_smoke_tests/inputs/keyboard_shortcuts.pynew file mode 100644index 0000000000..477d6d9001--- /dev/null+++ b/marimo/_smoke_tests/inputs/keyboard_shortcuts.py@@ -0,0 +1,215 @@+# /// script+# [tool.marimo.runtime]+# auto_instantiate = true+# ///+#+# Smoke test for keyboard_shortcut on ui.button (#4230).+#+# Manual test plan:+# 1. Click into each input/textarea/editor below and press "K".+# 2. The letter "k" should appear in the input — the button must NOT fire.+# 3. Click somewhere neutral (outside any input) and press "K".+# 4. The button SHOULD fire (counter increments).++import marimo++__generated_with = "0.22.0"+app = marimo.App(width="medium")+++def _():+ import marimo as mo++ return (mo,)++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ # Keyboard Shortcut Smoke Test (#4230)++ The **Trigger (K)** button below has `keyboard_shortcut="K"`.+ Pressing **K** while focused in any input should type the letter,+ *not* trigger the button.+ """)+ return+++def _(mo):+ fire_count, set_fire_count = mo.state(0)+++ def _on_click(_: object) -> None:+ set_fire_count(lambda n: n + 1)+++ trigger_button = mo.ui.button(+ label="Trigger action (K)",+ on_click=_on_click,+ keyboard_shortcut="K",+ )+ return fire_count, trigger_button+++def _(fire_count, mo, trigger_button):+ counter = fire_count()+ mo.vstack(+ [+ mo.md(f"**Button fired: {counter} time(s)**"),+ trigger_button,+ mo.md("---"),+ ]+ )+ return+++def _(mo):+ mo.md("""+ ## Edge Case: Single-key shortcut vs text input+ """)+ return+++def _(mo):+ text_input = mo.ui.text(+ label="mo.ui.text — type K here (should NOT fire button)",+ placeholder="type here…",+ )+ text_input+ return+++def _(mo):+ text_area = mo.ui.text_area(+ label="mo.ui.text_area — type K here (should NOT fire button)",+ placeholder="type here…",+ )+ text_area+ return+++def _(mo):+ number_input = mo.ui.number(+ label="mo.ui.number — focus and press K (should NOT fire button)",+ start=0,+ stop=100,+ value=42,+ )+ number_input+ return+++def _(mo):+ dropdown = mo.ui.dropdown(+ label="mo.ui.dropdown — open and press K (should NOT fire button)",+ options=["apple", "kiwi", "kumquat"],+ )+ dropdown+ return+++def _(mo):+ mo.md("""+ ## Edge Case: Modifier-key shortcut+ """)+ return+++def _(mo):+ mod_count, set_mod_count = mo.state(0)+ key = "Cmd-Shift-L"+++ def _on_mod_click(_: object) -> None:+ set_mod_count(lambda n: n + 1)+++ mod_button = mo.ui.button(+ label=f"Trigger with {key}",+ on_click=_on_mod_click,+ keyboard_shortcut=key,+ )+ return key, mod_button, mod_count+++def _(key, mo, mod_button, mod_count):+ mc = mod_count()+ mo.vstack(+ [+ mo.md(f"**{key} button fired: {mc} time(s)**"),+ mod_button,+ mo.md(+ f"Pressing plain **K** in the text input below should type 'k'. "+ f"Only **{key}** should trigger this button."+ ),+ ]+ )+ return+++def _(mo):+ mo.md("""+ ## Edge Case: Multiple buttons with different single-key shortcuts+ """)+ return+++def _(mo):+ a_count, set_a_count = mo.state(0)+ b_count, set_b_count = mo.state(0)++ btn_a = mo.ui.button(+ label="Action A (press Shift-A)",+ on_click=lambda _: set_a_count(lambda n: n + 1),+ keyboard_shortcut="Shift-A",+ )+ btn_b = mo.ui.button(+ label="Action B (press Shift-B)",+ on_click=lambda _: set_b_count(lambda n: n + 1),+ keyboard_shortcut="Shift-B",+ )+ return a_count, b_count, btn_a, btn_b+++def _(a_count, b_count, btn_a, btn_b, mo):+ ac = a_count()+ bc = b_count()+ mo.vstack(+ [+ mo.hstack([btn_a, btn_b]),+ mo.md(f"Shift-A fired: **{ac}** | Shift-B fired: **{bc}**"),+ mo.md(+ "Both buttons should work when no input is focused. "+ "Neither should fire while typing in the text input below."+ ),+ ]+ )+ return+++def _(mo):+ multi_text = mo.ui.text(+ label="Type Shift-A or Shift-B here (buttons should NOT fire)",+ placeholder="type here…",+ )+ multi_text+ return+++if __name__ == "__main__":+ app.run()