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.

fix: improve keyboard access and form labels (#11477)

Kiran Gadhave2ff23acbef36
diff --git a/frontend/src/components/ai/__tests__/ai-model-dropdown.test.tsx b/frontend/src/components/ai/__tests__/ai-model-dropdown.test.tsx
new file mode 100644
index 0000000000..dd770e44a3
--- /dev/null
+++ b/frontend/src/components/ai/__tests__/ai-model-dropdown.test.tsx
@@ -0,0 +1,63 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { fireEvent, render, screen } from "@testing-library/react";
+import { createStore, Provider } from "jotai";
+import { expect, it, vi } from "vitest";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { getKnownModelMaps } from "@/core/ai/model-registry";
+import { AIModelDropdown } from "../ai-model-dropdown";
+import * as aiUtils from "../ai-utils";
+
+vi.mock("@/core/ai/config", () => ({
+ useAIConfigActions: () => ({ saveModelChange: vi.fn() }),
+}));
+vi.mock("@/components/app-config/state", () => ({
+ useOpenSettingsToTab: () => ({ handleClick: vi.fn() }),
+}));
+
+it.each(["Enter", " "])(
+ "selects a model with %j while ArrowRight retains information access",
+ async (key) => {
+ const knownModel = [...getKnownModelMaps().modelMap.values()].find(
+ (model) => model.provider === "openai",
+ );
+ if (!knownModel) {
+ throw new Error("Expected a known OpenAI model");
+ }
+ const model = { ...knownModel, capabilities: [] };
+ vi.spyOn(aiUtils, "listModelsForAiSettings").mockReturnValue([
+ [model.provider, [model]],
+ ]);
+ const onSelect = vi.fn();
+ render(
+ <Provider store={createStore()}>
+ <TooltipProvider>
+ <AIModelDropdown
+ forRole="chat"
+ placeholder="Choose model"
+ onSelect={onSelect}
+ />
+ </TooltipProvider>
+ </Provider>,
+ );
+ fireEvent.keyDown(screen.getByRole("button", { name: "Choose model" }), {
+ key: "ArrowDown",
+ });
+ fireEvent.keyDown(
+ await screen.findByRole("menuitem", { name: /OpenAI$/ }),
+ { key: "ArrowRight" },
+ );
+ const option = await screen.findByRole("menuitem", {
+ name: (name) => name.endsWith(model.name),
+ });
+ fireEvent.keyDown(option, { key: "ArrowRight" });
+ expect(
+ await screen.findByRole("heading", { name: model.name }),
+ ).toBeInTheDocument();
+ expect(onSelect).not.toHaveBeenCalled();
+ fireEvent.keyDown(option, { key });
+ expect(onSelect).toHaveBeenCalledExactlyOnceWith(
+ `${model.provider}/${model.model}`,
+ );
+ },
+);
diff --git a/frontend/src/components/ai/ai-model-dropdown.tsx b/frontend/src/components/ai/ai-model-dropdown.tsx
index a7e1d9b30a..9656d98850 100644
--- a/frontend/src/components/ai/ai-model-dropdown.tsx
+++ b/frontend/src/components/ai/ai-model-dropdown.tsx
@@ -276,13 +276,18 @@ const ProviderDropdownContent = ({
const qualifiedModelId: QualifiedModelId = `${provider}/${model.model}`;
return (
<DropdownMenuSub key={qualifiedModelId}>
- <DropdownMenuSubTrigger showChevron={false} className="py-2">
- <div
- className="flex items-center gap-2 w-full cursor-pointer"
- onClick={() => {
+ <DropdownMenuSubTrigger
+ showChevron={false}
+ className="py-2"
+ onClick={() => onSelect(qualifiedModelId)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
onSelect(qualifiedModelId);
- }}
- >
+ }
+ }}
+ >
+ <div className="flex items-center gap-2 w-full cursor-pointer">
<AiModelDropdownItem model={model} provider={provider} />
</div>
</DropdownMenuSubTrigger>
diff --git a/frontend/src/components/chat/acp/__tests__/session-tabs.test.tsx b/frontend/src/components/chat/acp/__tests__/session-tabs.test.tsx
new file mode 100644
index 0000000000..733586f88a
--- /dev/null
+++ b/frontend/src/components/chat/acp/__tests__/session-tabs.test.tsx
@@ -0,0 +1,43 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { fireEvent, render, screen } from "@testing-library/react";
+import { createStore, Provider } from "jotai";
+import { expect, it, vi } from "vitest";
+import { SessionTabs } from "../session-tabs";
+import { addSession, agentSessionStateAtom } from "../state";
+
+vi.mock("../agent-selector", () => ({ AgentSelector: () => null }));
+
+it("keeps session selection and close as separate named buttons", () => {
+ const first = addSession(
+ { sessions: [], activeTabId: null },
+ { agentId: "claude", firstMessage: "First" },
+ ).sessions[0];
+ const second = addSession(
+ { sessions: [], activeTabId: null },
+ { agentId: "codex", firstMessage: "Second" },
+ ).sessions[0];
+ const store = createStore();
+ store.set(agentSessionStateAtom, {
+ sessions: [first, second],
+ activeTabId: first.tabId,
+ });
+ render(
+ <Provider store={store}>
+ <SessionTabs />
+ </Provider>,
+ );
+ const select = screen.getByRole("button", {
+ name: /Second$/,
+ pressed: false,
+ });
+ select.focus();
+ expect(select).toHaveFocus();
+ fireEvent.click(select);
+ expect(select).toHaveAttribute("aria-pressed", "true");
+ fireEvent.click(screen.getByRole("button", { name: "Close First" }));
+ expect(store.get(agentSessionStateAtom).activeTabId).toBe(second.tabId);
+ expect(
+ store.get(agentSessionStateAtom).sessions.map((session) => session.title),
+ ).toEqual(["Second"]);
+});
diff --git a/frontend/src/components/chat/acp/blocks.tsx b/frontend/src/components/chat/acp/blocks.tsx
index 3e9d8a5f45..e061e34984 100644
--- a/frontend/src/components/chat/acp/blocks.tsx
+++ b/frontend/src/components/chat/acp/blocks.tsx
@@ -337,6 +337,7 @@ export const PlansBlock = (props: { data: PlanNotificationEvent[] }) => {
>
<input
type="checkbox"
+ aria-label={item.content}
checked={item.status === "completed"}
readOnly={true}
className="accent-primary h-4 w-4 rounded border border-muted-foreground/30"
diff --git a/frontend/src/components/chat/acp/session-tabs.tsx b/frontend/src/components/chat/acp/session-tabs.tsx
index f6c5183648..3ebb37e36c 100644
--- a/frontend/src/components/chat/acp/session-tabs.tsx
+++ b/frontend/src/components/chat/acp/session-tabs.tsx
@@ -32,17 +32,22 @@ const SessionTab: React.FC<SessionTabProps> = memo(
"flex items-center gap-1 px-2 py-1 text-xs border-r border-border bg-muted/30 hover:bg-muted/50 cursor-pointer min-w-0",
isActive && "bg-background border-b-0 relative z-1",
)}
- onClick={() => onSelect(session.tabId)}
>
- <div className="flex items-center gap-1 min-w-0 flex-1">
+ <button
+ type="button"
+ aria-pressed={isActive}
+ onClick={() => onSelect(session.tabId)}
+ className="flex items-center gap-1 min-w-0 flex-1 text-left focus-visible:outline focus-visible:outline-ring"
+ >
<span className="text-muted-foreground text-[10px] font-medium">
<AiProviderIcon provider={session.agentId} className="h-3 w-3" />
</span>
<span className="truncate" title={session.title}>
{session.title}
</span>
- </div>
+ </button>
<Button
+ aria-label={`Close ${session.title}`}
variant="ghost"
size="sm"
className="h-4 w-4 p-0 hover:bg-destructive/20 hover:text-destructive shrink-0"
diff --git a/frontend/src/components/data-table/TableTopBar.tsx b/frontend/src/components/data-table/TableTopBar.tsx
index 1c3ce40c1b..f7699d1350 100644
--- a/frontend/src/components/data-table/TableTopBar.tsx
+++ b/frontend/src/components/data-table/TableTopBar.tsx
@@ -76,6 +76,7 @@ export const TableTopBar = <TData,>({
<input
ref={inputRef}
type="text"
+ aria-label="Search table"
className="h-6 border-none bg-transparent focus:outline-hidden text-sm w-full min-w-0"
value={internalValue}
onKeyDown={(e) => {
@@ -90,6 +91,7 @@ export const TableTopBar = <TData,>({
{reloading && <Spinner size="small" />}
{internalValue && (
<Button
+ aria-label="Clear table search"
variant="text"
size="xs"
className="h-5 w-5 p-0 shrink-0"
diff --git a/frontend/src/components/data-table/__tests__/data-table.test.tsx b/frontend/src/components/data-table/__tests__/data-table.test.tsx
index a9180d2296..b3fdd46ab6 100644
--- a/frontend/src/components/data-table/__tests__/data-table.test.tsx
+++ b/frontend/src/components/data-table/__tests__/data-table.test.tsx
@@ -260,6 +260,7 @@ describe("DataTable", () => {
);
const cells = within(screen.getAllByRole("row")[1]).getAllByRole("cell");
+ cells[1].scrollIntoView = vi.fn();
// Start a pending hover-show on cell A, then focus cell B before it fires.
fireEvent.mouseOver(cells[0], { buttons: 0 });
fireEvent.focus(cells[1]);
diff --git a/frontend/src/components/data-table/__tests__/keyboard-selection.test.tsx b/frontend/src/components/data-table/__tests__/keyboard-selection.test.tsx
new file mode 100644
index 0000000000..ea9fd07009
--- /dev/null
+++ b/frontend/src/components/data-table/__tests__/keyboard-selection.test.tsx
@@ -0,0 +1,188 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { act, fireEvent, render, screen, within } from "@testing-library/react";
+import { useState } from "react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { copyToClipboard } from "@/utils/copy";
+import type { CellSelectionState } from "../cell-selection/types";
+import { DataTable } from "../data-table";
+
+vi.mock("@/utils/copy", () => ({ copyToClipboard: vi.fn() }));
+
+function SelectableTable({ multiple = false }: { multiple?: boolean }) {
+ const [selection, setSelection] = useState<CellSelectionState>([]);
+ return (
+ <TooltipProvider>
+ <DataTable
+ data={[{ name: "Alice" }, { name: "Bob" }]}
+ columns={[{ accessorKey: "name", header: "Name" }]}
+ totalRows={2}
+ totalColumns={1}
+ pagination={false}
+ selection={multiple ? "multi-cell" : "single-cell"}
+ cellSelection={selection}
+ onCellSelectionChange={setSelection}
+ />
+ </TooltipProvider>
+ );
+}
+
+describe("table keyboard access", () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.clearAllMocks();
+ });
+
+ it("includes the initial focused cell when extending a keyboard range", () => {
+ render(<SelectableTable />);
+ const [alice, bob] = screen.getAllByRole("gridcell");
+ act(() => alice.focus());
+ fireEvent.keyDown(alice, { key: "ArrowDown", shiftKey: true });
+ fireEvent.keyDown(bob, { key: "c", ctrlKey: true });
+ expect(copyToClipboard).toHaveBeenLastCalledWith("Alice\nBob", undefined);
+ fireEvent.keyDown(bob, { key: "ArrowUp", shiftKey: true });
+ fireEvent.keyDown(alice, { key: "c", ctrlKey: true });
+ expect(copyToClipboard).toHaveBeenLastCalledWith("Alice", undefined);
+ });
+
+ it.each(["Enter", " "])(
+ "copies the activated cell with %s, including after an older selection",
+ (key) => {
+ render(<SelectableTable />);
+ const [alice, bob] = screen.getAllByRole("gridcell");
+ for (const [cell, value] of [
+ [alice, "Alice"],
+ [bob, "Bob"],
+ ] as const) {
+ act(() => cell.focus());
+ fireEvent.keyDown(cell, { key });
+ fireEvent.keyDown(cell, { key: "c", ctrlKey: true });
+ expect(copyToClipboard).toHaveBeenLastCalledWith(value, undefined);
+ expect(cell).toHaveAttribute("aria-selected", "true");
+ }
+ },
+ );
+
+ it("moves focus and activation together inside a shadow root", () => {
+ vi.useFakeTimers();
+ const host = document.createElement("div");
+ document.body.append(host);
+ const shadow = host.attachShadow({ mode: "open" });
+ const container = document.createElement("div");
+ shadow.append(container);
+ const view = render(<SelectableTable />, { container });
+ try {
+ const [alice, bob] = within(container).getAllByRole("gridcell");
+ alice.scrollIntoView = vi.fn();
+ bob.scrollIntoView = vi.fn();
+ act(() => alice.focus());
+ fireEvent.keyDown(alice, { key: "ArrowDown" });
+ act(() => vi.runAllTimers());
+ expect(shadow.activeElement).toBe(bob);
+ fireEvent.keyDown(bob, { key: " " });
+ expect(bob).toHaveAttribute("aria-selected", "true");
+ expect(alice).toHaveAttribute("aria-selected", "false");
+ } finally {
+ view.unmount();
+ host.remove();
+ }
+ });
+
+ it("does not move focus away from a nested control after navigation", () => {
+ vi.useFakeTimers();
+ render(<SelectableTable />);
+ const [alice, bob] = screen.getAllByRole("gridcell");
+ alice.scrollIntoView = vi.fn();
+ bob.scrollIntoView = vi.fn();
+ const button = document.createElement("button");
+ alice.append(button);
+ act(() => alice.focus());
+ fireEvent.keyDown(alice, { key: "ArrowDown" });
+ act(() => {
+ button.focus();
+ vi.runAllTimers();
+ });
+ expect(button).toHaveFocus();
+ });
+
+ it("ignores stale scheduled focus when moving between cells", () => {
+ vi.useFakeTimers();
+ render(<SelectableTable />);
+ const [alice, bob] = screen.getAllByRole("gridcell");
+ alice.scrollIntoView = vi.fn();
+ bob.scrollIntoView = vi.fn();
+ act(() => {
+ alice.focus();
+ bob.focus();
+ vi.runAllTimers();
+ });
+ expect(bob).toHaveFocus();
+ expect(alice.scrollIntoView).not.toHaveBeenCalled();
+ expect(bob.scrollIntoView).toHaveBeenCalledOnce();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+ it.each([false, true])(
+ "selects focused cells without a preceding click (multiple=%s)",
+ (multiple) => {
+ render(<SelectableTable multiple={multiple} />);
+ const [alice, bob] = screen.getAllByRole("gridcell");
+ alice.focus();
+ fireEvent.keyDown(alice, { key: "Enter" });
+ expect(alice).toHaveAttribute("aria-selected", "true");
+ bob.focus();
+ fireEvent.keyDown(bob, { key: " " });
+ expect(bob).toHaveAttribute("aria-selected", "true");
+ expect(alice).toHaveAttribute("aria-selected", String(multiple));
+ fireEvent.keyDown(bob, { key: " " });
+ expect(bob).toHaveAttribute("aria-selected", "false");
+ },
+ );
+
+ it("does not intercept keys from embedded buttons", () => {
+ const select = vi.fn();
+ render(
+ <TooltipProvider>
+ <DataTable
+ data={[{ name: "Alice" }]}
+ columns={[
+ {
+ accessorKey: "name",
+ cell: () => <button type="button">Open person</button>,
+ },
+ ]}
+ totalRows={1}
+ totalColumns={1}
+ pagination={false}
+ selection="single-cell"
+ onCellSelectionChange={select}
+ />
+ </TooltipProvider>,
+ );
+ const button = screen.getByRole("button", { name: "Open person" });
+ for (const key of ["Enter", " ", "ArrowDown"]) {
+ expect(fireEvent.keyDown(button, { key })).toBe(true);
+ }
+ expect(select).not.toHaveBeenCalled();
+ });
+
+ it("names search controls and clears a query", () => {
+ render(
+ <TooltipProvider>
+ <DataTable
+ data={[{ name: "Alice" }]}
+ columns={[{ accessorKey: "name" }]}
+ totalRows={1}
+ totalColumns={1}
+ pagination={false}
+ showSearch={true}
+ onSearchQueryChange={vi.fn()}
+ />
+ </TooltipProvider>,
+ );
+ const search = screen.getByRole("textbox", { name: "Search table" });
+ fireEvent.change(search, { target: { value: "Alice" } });
+ fireEvent.click(screen.getByRole("button", { name: "Clear table search" }));
+ expect(search).toHaveValue("");
+ });
+});
diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsx
index c54b86aa16..599def6478 100644
--- a/frontend/src/components/data-table/data-table.tsx
+++ b/frontend/src/components/data-table/data-table.tsx
@@ -402,6 +402,12 @@ const DataTableInternal = <TData,>({
</Banner>
)}
<Table
+ role={table.options.enableCellSelection ? "grid" : undefined}
+ aria-multiselectable={
+ table.options.enableCellSelection
+ ? table.options.enableMultiCellSelection
+ : undefined
+ }
className={cn(
"relative",
columns.length <= AUTO_WIDTH_MAX_COLUMNS ? "w-auto" : "w-full",
diff --git a/frontend/src/components/data-table/range-focus/atoms.ts b/frontend/src/components/data-table/range-focus/atoms.ts
index dc649686c1..d5e13a37d3 100644
--- a/frontend/src/components/data-table/range-focus/atoms.ts
+++ b/frontend/src/components/data-table/range-focus/atoms.ts
@@ -244,15 +244,13 @@ const {
cellId: nextCell.id,
};
- if (isShiftKey && state.selectedStartCell) {
- const cellsInRange = getCellsBetween(
- table,
- state.selectedStartCell,
- newCell,
- );
+ if (isShiftKey) {
+ const anchor = state.selectedStartCell ?? currentCell;
+ const cellsInRange = getCellsBetween(table, anchor, newCell);
return {
...state,
selectedCells: new Set(cellsInRange),
+ selectedStartCell: anchor,
focusedCell: newCell,
};
} else {
diff --git a/frontend/src/components/data-table/range-focus/use-cell-range-selection.ts b/frontend/src/components/data-table/range-focus/use-cell-range-selection.ts
index 53fe28a251..0bff3456cf 100644
--- a/frontend/src/components/data-table/range-focus/use-cell-range-selection.ts
+++ b/frontend/src/components/data-table/range-focus/use-cell-range-selection.ts
@@ -45,45 +45,71 @@ export const useCellRangeSelection = <TData>({
},
);
- const handleCellsKeyDown = useEvent((e: React.KeyboardEvent<HTMLElement>) => {
- switch (e.key) {
- case "c":
- if (Events.isMetaOrCtrl(e)) {
- handleCopy();
- }
- break;
- case "ArrowDown":
- e.preventDefault();
- navigate(e, "down");
- break;
- case "ArrowUp":
- e.preventDefault();
- navigate(e, "up");
- break;
- case "ArrowLeft":
- e.preventDefault();
- navigate(e, "left");
- break;
- case "ArrowRight":
- e.preventDefault();
- navigate(e, "right");
- break;
- case "Enter":
- e.preventDefault();
- actions.toggleCurrentRowSelection(table);
- break;
- case "Escape":
- actions.clearSelection();
- break;
- case "a":
- if (e.metaKey || e.ctrlKey) {
- e.preventDefault();
- actions.selectAllCells(table);
- }
- break;
- }
+ const handleCellFocus = useEvent((cell: Cell<TData, unknown>) => {
+ actions.setFocusedCell({
+ cellId: cell.id,
+ rowId: cell.row.id,
+ columnId: cell.column.id,
+ });
});
+ const handleCellsKeyDown = useEvent(
+ (e: React.KeyboardEvent<HTMLElement>, cell: Cell<TData, unknown>) => {
+ if (e.defaultPrevented || isInteractiveTarget(e)) {
+ return;
+ }
+ switch (e.key) {
+ case "c":
+ if (Events.isMetaOrCtrl(e)) {
+ handleCopy();
+ }
+ break;
+ case "ArrowDown":
+ e.preventDefault();
+ navigate(e, "down");
+ break;
+ case "ArrowUp":
+ e.preventDefault();
+ navigate(e, "up");
+ break;
+ case "ArrowLeft":
+ e.preventDefault();
+ navigate(e, "left");
+ break;
+ case "ArrowRight":
+ e.preventDefault();
+ navigate(e, "right");
+ break;
+ case "Enter":
+ case " ":
+ e.preventDefault();
+ updateSelection(
+ {
+ cellId: cell.id,
+ rowId: cell.row.id,
+ columnId: cell.column.id,
+ },
+ false,
+ );
+ if (table.options.enableCellSelection) {
+ cell.toggleSelected?.();
+ } else if (cell.row.getCanSelect()) {
+ cell.row.toggleSelected();
+ }
+ break;
+ case "Escape":
+ actions.clearSelection();
+ break;
+ case "a":
+ if (e.metaKey || e.ctrlKey) {
+ e.preventDefault();
+ actions.selectAllCells(table);
+ }
+ break;
+ }
+ },
+ );
+
const handleCellMouseDown = useEvent(
(e: React.MouseEvent, cell: Cell<TData, unknown>) => {
// Right-clicks will trigger context menu, so avoid updating selected cells
@@ -122,6 +148,7 @@ export const useCellRangeSelection = <TData>({
handleCellMouseOver,
handleCopy,
handleCellsKeyDown,
+ handleCellFocus,
updateSelection,
clearSelection: actions.clearSelection,
};
@@ -148,7 +175,7 @@ const CONTENT_WRAPPER_MARIMO_TAGS: ReadonlySet<string> = new Set([
* shadow host (e.g. `<marimo-lazy>`), hiding any genuinely interactive
* descendants rendered inside the shadow tree.
*/
-export function isInteractiveTarget(e: React.MouseEvent): boolean {
+export function isInteractiveTarget(e: React.SyntheticEvent): boolean {
const path: readonly EventTarget[] =
typeof e.nativeEvent?.composedPath === "function"
? e.nativeEvent.composedPath()
diff --git a/frontend/src/components/data-table/range-focus/use-scroll-into-view.ts b/frontend/src/components/data-table/range-focus/use-scroll-into-view.ts
index c6b92c43a3..6d983daafa 100644
--- a/frontend/src/components/data-table/range-focus/use-scroll-into-view.ts
+++ b/frontend/src/components/data-table/range-focus/use-scroll-into-view.ts
@@ -1,6 +1,6 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { atom } from "jotai";
+import { atom, useStore } from "jotai";
import { useJotaiEffect } from "@/core/state/jotai";
import { Logger } from "@/utils/Logger";
import { cellSelectionStateAtom } from "./atoms";
@@ -15,14 +15,21 @@ const focusedCellAtom = atom((get) => get(cellSelectionStateAtom).focusedCell);
export function useScrollIntoViewOnFocus(
root: React.RefObject<HTMLElement | null>,
) {
+ const store = useStore();
useJotaiEffect(focusedCellAtom, (focusedCell) => {
if (!focusedCell?.cellId) {
return;
}
const scroll = () => {
+ if (
+ !root.current ||
+ store.get(focusedCellAtom)?.cellId !== focusedCell.cellId
+ ) {
+ return;
+ }
// Check if this cell contains the CellRangeSelectionIndicator with our cellId
- const indicator = root.current?.querySelector(
+ const indicator = root.current?.querySelector<HTMLElement>(
`[data-cell-id="${focusedCell.cellId}"]`,
);
if (!indicator) {
@@ -33,6 +40,18 @@ export function useScrollIntoViewOnFocus(
return;
}
+ const focusRoot = root.current.getRootNode();
+ const activeElement =
+ focusRoot instanceof ShadowRoot || focusRoot instanceof Document
+ ? focusRoot.activeElement
+ : null;
+ if (
+ root.current.contains(activeElement) &&
+ activeElement?.matches("td[data-cell-id]")
+ ) {
+ indicator.focus({ preventScroll: true });
+ }
+
indicator.scrollIntoView({
behavior: "smooth",
block: "nearest",
diff --git a/frontend/src/components/data-table/renderers.tsx b/frontend/src/components/data-table/renderers.tsx
index 395cd76f71..e35b006d5f 100644
--- a/frontend/src/components/data-table/renderers.tsx
+++ b/frontend/src/components/data-table/renderers.tsx
@@ -124,6 +124,7 @@ export const DataTableBody = <TData,>({
handleCellMouseUp,
handleCellMouseOver,
handleCellsKeyDown,
+ handleCellFocus,
handleCopy: handleCopyAllCells,
} = useCellRangeSelection({ table });
@@ -147,10 +148,16 @@ export const DataTableBody = <TData,>({
return (
<TableCell
tabIndex={0}
+ role={table.options.enableCellSelection ? "gridcell" : undefined}
+ aria-selected={
+ table.options.enableCellSelection
+ ? cell.getIsSelected?.()
+ : undefined
+ }
{...getCellDomProps(cell.id)}
key={cell.id}
className={cn(
- "whitespace-pre truncate outline-hidden border-r border-r-border/75",
+ "whitespace-pre truncate outline-hidden focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring border-r border-r-border/75",
!fixedWidth && "max-w-[300px]",
cell.column.getColumnWrapping &&
cell.column.getColumnWrapping?.() === "wrap" &&
@@ -169,7 +176,13 @@ export const DataTableBody = <TData,>({
hoverTooltip.handleCellMouseOver(e, cell);
}}
onMouseLeave={hoverTooltip.handleCellMouseLeave}
- onFocus={(e) => hoverTooltip.handleCellFocus(e, cell)}
+ onFocus={(e) => {
+ if (e.target === e.currentTarget) {
+ handleCellFocus(cell);
+ }
+ hoverTooltip.handleCellFocus(e, cell);
+ }}
+ onKeyDown={(e) => handleCellsKeyDown(e, cell)}
onBlur={hoverTooltip.handleCellBlur}
onContextMenu={() => handleContextMenu(cell)}
>
@@ -264,11 +277,7 @@ export const DataTableBody = <TData,>({
return rows.map((row) => renderRow(row));
};
- const tableBody = (
- <TableBody onKeyDown={handleCellsKeyDown} ref={tableRef}>
- {renderRows()}
- </TableBody>
- );
+ const tableBody = <TableBody ref={tableRef}>{renderRows()}</TableBody>;
return (
<>
diff --git a/frontend/src/components/data-table/row-viewer-panel/__tests__/row-viewer.test.tsx b/frontend/src/components/data-table/row-viewer-panel/__tests__/row-viewer.test.tsx
index 9a5e2aa79c..84beb7894d 100644
--- a/frontend/src/components/data-table/row-viewer-panel/__tests__/row-viewer.test.tsx
+++ b/frontend/src/components/data-table/row-viewer-panel/__tests__/row-viewer.test.tsx
@@ -1,6 +1,6 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { render, screen } from "@testing-library/react";
+import { fireEvent, render, screen } from "@testing-library/react";
import { Provider } from "jotai";
import { describe, expect, it, vi } from "vitest";
import { TooltipProvider } from "@/components/ui/tooltip";
@@ -17,6 +17,29 @@ const renderWithProviders = (component: React.ReactNode) => {
};
describe("RowExpandedPanel", () => {
+ it("preserves Space activation on navigation buttons", async () => {
+ const select = vi.fn();
+ const navigate = vi.fn();
+ renderWithProviders(
+ <RowViewerPanel
+ rowIdx={0}
+ setRowIdx={navigate}
+ totalRows={2}
+ fieldTypes={[["name", ["string", "string"]]]}
+ getRow={async () => ({ rows: [{ name: "Alice" }] })}
+ isSelectable={true}
+ isRowSelected={false}
+ handleRowSelectionChange={select}
+ />,
+ );
+ await screen.findByText("Alice");
+ const next = screen.getByRole("button", { name: "Next row" });
+ expect(fireEvent.keyDown(next, { key: " " })).toBe(true);
+ expect(select).not.toHaveBeenCalled();
+ fireEvent.click(next);
+ expect(navigate).toHaveBeenCalledExactlyOnceWith(1);
+ });
+
const mockFieldTypes: FieldTypesWithExternalType = [
["name", ["string", "string"]],
["age", ["number", "number"]],
diff --git a/frontend/src/components/data-table/row-viewer-panel/row-viewer.tsx b/frontend/src/components/data-table/row-viewer-panel/row-viewer.tsx
index 7eb75a4163..9f84a28566 100644
--- a/frontend/src/components/data-table/row-viewer-panel/row-viewer.tsx
+++ b/frontend/src/components/data-table/row-viewer-panel/row-viewer.tsx
@@ -37,6 +37,7 @@ import type { GetRowResult } from "@/plugins/impl/DataTablePlugin";
import { Objects } from "@/utils/objects";
import { NAMELESS_COLUMN_PREFIX, renderCellValue } from "../columns";
import { prettifyRowCount } from "../pagination";
+import { isInteractiveTarget } from "../range-focus/use-cell-range-selection";
import {
type FieldTypesWithExternalType,
INDEX_COLUMN_NAME,
@@ -102,8 +103,7 @@ export const RowViewerPanel: React.FC<RowViewerPanelProps> = ({
}
const handleKeyDown = (e: KeyboardEvent) => {
- // Don't intercept keys when typing in an input
- if (e.target instanceof HTMLInputElement) {
+ if (e.defaultPrevented || isInteractiveTarget(e)) {
return;
}
switch (e.key) {
diff --git a/frontend/src/components/datasources/datasources.tsx b/frontend/src/components/datasources/datasources.tsx
index dd41299172..c18af29e64 100644
--- a/frontend/src/components/datasources/datasources.tsx
+++ b/frontend/src/components/datasources/datasources.tsx
@@ -284,6 +284,7 @@ export const DataSources: React.FC = () => {
{hasSearch && (
<button
type="button"
+ aria-label="Clear table search"
className="float-right border-b px-2 m-0 h-full hover:bg-accent hover:text-accent-foreground"
onClick={() => setSearchValue("")}
>
diff --git a/frontend/src/components/editor/__tests__/package-alert.test.tsx b/frontend/src/components/editor/__tests__/package-alert.test.tsx
index 72f03903b0..5e77b39d15 100644
--- a/frontend/src/components/editor/__tests__/package-alert.test.tsx
+++ b/frontend/src/components/editor/__tests__/package-alert.test.tsx
@@ -27,10 +27,12 @@ function mountPackageAlert({
configuredManager,
sandboxBackend,
source = "kernel",
+ packages = ["polars"],
}: {
configuredManager: PackageManagerName;
sandboxBackend: "uv" | "pixi" | null;
source?: "kernel" | "server";
+ packages?: string[];
}) {
const store = createStore();
const client = MockRequestClient.create();
@@ -55,7 +57,7 @@ function mountPackageAlert({
packageAlert: {
id: "missing-package",
kind: "missing",
- packages: ["polars"],
+ packages,
isolated: true,
source,
},
@@ -97,6 +99,25 @@ it("keeps the configured package manager selectable outside a sandbox", () => {
expect(managerSelect).not.toBeDisabled();
});
+it("removes an extra absent from available choices through a keyboard menu item", async () => {
+ const client = mountPackageAlert({
+ configuredManager: "uv",
+ sandboxBackend: null,
+ packages: ["polars[dev]"],
+ });
+ fireEvent.keyDown(screen.getByRole("button", { name: "dev" }), {
+ key: "ArrowDown",
+ });
+ const remove = await screen.findByRole("menuitem", { name: "Remove dev" });
+ fireEvent.keyDown(remove, { key: "Enter" });
+ fireEvent.click(screen.getByTestId("install-packages-button"));
+ expect(client.sendInstallMissingPackages).toHaveBeenCalledExactlyOnceWith({
+ manager: "uv",
+ source: "kernel",
+ versions: { polars: "" },
+ });
+});
+
it("installs a selected version in a Pixi sandbox", () => {
const client = mountPackageAlert({
configuredManager: "uv",
diff --git a/frontend/src/components/editor/cell/collapse.tsx b/frontend/src/components/editor/cell/collapse.tsx
index e77adbb118..d518b62611 100644
--- a/frontend/src/components/editor/cell/collapse.tsx
+++ b/frontend/src/components/editor/cell/collapse.tsx
@@ -67,10 +67,12 @@ export const CollapsedCellBanner: React.FC<{
const states = getDescendantsStatus(notebook, cellId);
return (
- <div
+ <button
+ type="button"
+ aria-label={`Expand ${count} collapsed ${count === 1 ? "cell" : "cells"}`}
onClick={onClick}
className={cn(
- "flex items-center justify-between w-[calc(100%-2rem)] h-9 bg-muted rounded-b mx-4 opacity-80 hover:opacity-100 cursor-pointer",
+ "flex items-center justify-between w-[calc(100%-2rem)] h-9 bg-muted rounded-b mx-4 opacity-80 hover:opacity-100 cursor-pointer focus-visible:outline focus-visible:outline-ring",
)}
>
<Toolbar
@@ -102,7 +104,7 @@ export const CollapsedCellBanner: React.FC<{
</>
}
/>
- </div>
+ </button>
);
});
CollapsedCellBanner.displayName = "CollapsedCellBanner";
diff --git a/frontend/src/components/editor/chrome/panels/outline/__tests__/outline-keyboard.test.tsx b/frontend/src/components/editor/chrome/panels/outline/__tests__/outline-keyboard.test.tsx
new file mode 100644
index 0000000000..0feefedf6b
--- /dev/null
+++ b/frontend/src/components/editor/chrome/panels/outline/__tests__/outline-keyboard.test.tsx
@@ -0,0 +1,84 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { fireEvent, render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import type { OutlineItem } from "@/core/cells/outline";
+import { MiniMap, OutlineList } from "../floating-outline";
+import { scrollToOutlineItem } from "../useActiveOutline";
+
+vi.mock("../useActiveOutline", () => ({ scrollToOutlineItem: vi.fn() }));
+
+const items: OutlineItem[] = [
+ { name: "First", level: 1, by: { id: "first" } },
+ { name: "Second", html: "<em>Second</em>", level: 2, by: { id: "second" } },
+];
+
+describe("outline keyboard navigation", () => {
+ it.each([
+ { Component: MiniMap, role: "button" },
+ { Component: OutlineList, role: "link" },
+ ])(
+ "keeps the focused $role when other headings change",
+ ({ Component, role }) => {
+ const duplicate: OutlineItem = {
+ name: "Repeated second",
+ level: 2,
+ by: { id: "second" },
+ };
+ const initial = [...items, duplicate];
+ const props = {
+ activeHeaderId: undefined,
+ activeOccurrences: undefined,
+ };
+ const { rerender } = render(<Component {...props} items={initial} />);
+ const focused = screen.getByRole(role, { name: "Repeated second" });
+ focused.focus();
+
+ for (const by of [{ id: "inserted" }, { path: "second" }]) {
+ const inserted: OutlineItem = { name: "Inserted", level: 1, by };
+ rerender(<Component {...props} items={[inserted, ...initial]} />);
+ expect(screen.getByRole(role, { name: "Repeated second" })).toBe(
+ focused,
+ );
+ expect(focused).toHaveFocus();
+ }
+
+ rerender(
+ <Component {...props} items={[items[1], duplicate, items[0]]} />,
+ );
+ expect(screen.getByRole(role, { name: "Repeated second" })).toBe(focused);
+ expect(focused).toHaveFocus();
+ fireEvent.click(focused);
+ expect(scrollToOutlineItem).toHaveBeenLastCalledWith(duplicate, 1);
+ },
+ );
+
+ it("activates plain and rich headings with Enter", () => {
+ render(
+ <OutlineList
+ items={items}
+ activeHeaderId={undefined}
+ activeOccurrences={undefined}
+ />,
+ );
+ items.forEach((item) => {
+ const link = screen.getByRole("link", { name: item.name });
+ expect(link).toHaveAttribute("tabindex", "0");
+ fireEvent.keyDown(link, { key: "Enter" });
+ expect(scrollToOutlineItem).toHaveBeenLastCalledWith(item, 0);
+ });
+ });
+
+ it("names each minimap button", () => {
+ render(
+ <MiniMap
+ items={items}
+ activeHeaderId={undefined}
+ activeOccurrences={undefined}
+ />,
+ );
+ const button = screen.getByRole("button", { name: "Second" });
+ fireEvent.click(button);
+ expect(scrollToOutlineItem).toHaveBeenLastCalledWith(items[1], 0);
+ });
+});
diff --git a/frontend/src/components/editor/chrome/panels/outline/floating-outline.tsx b/frontend/src/components/editor/chrome/panels/outline/floating-outline.tsx
index d21577cd4d..62f2d07509 100644
--- a/frontend/src/components/editor/chrome/panels/outline/floating-outline.tsx
+++ b/frontend/src/components/editor/chrome/panels/outline/floating-outline.tsx
@@ -17,6 +17,8 @@ export const FloatingOutline: React.FC = () => {
findOutlineElements(items),
);
const [isHovered, setIsHovered] = React.useState(false);
+ const [isFocused, setIsFocused] = React.useState(false);
+ const isVisible = isHovered || isFocused;
// Hide if < 2 items
// It's kinda useless to have an outline with only one item
@@ -29,6 +31,12 @@ export const FloatingOutline: React.FC = () => {
<div
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
+ onFocus={() => setIsFocused(true)}
+ onBlur={(e) => {
+ if (!e.currentTarget.contains(e.relatedTarget)) {
+ setIsFocused(false);
+ }
+ }}
className={cn(
"fixed top-[25vh] right-8 z-10000 print:hidden",
// Hide on small screens
@@ -36,9 +44,10 @@ export const FloatingOutline: React.FC = () => {
)}
>
<OutlineList
+ inert={!isVisible}
className={cn(
"-top-4 max-h-[70vh] bg-background rounded-lg shadow-lg absolute overflow-auto transition-all duration-300 w-[300px] border",
- isHovered ? "left-[-280px] opacity-100" : "left-[300px] opacity-0",
+ isVisible ? "left-[-280px] opacity-100" : "left-[300px] opacity-0",
)}
items={items}
activeHeaderId={activeHeaderId}
@@ -62,17 +71,20 @@ export const MiniMap: React.FC<{
const seen = new Map<string, number>();
return (
<div className="flex flex-col gap-4 items-end max-h-[70vh] overflow-hidden">
- {items.map((item, idx) => {
+ {items.map((item) => {
const identifier = "id" in item.by ? item.by.id : item.by.path;
+ const selector = JSON.stringify(item.by);
// Keep track of how many times we've seen this selector
- const occurrences = seen.get(identifier) ?? 0;
- seen.set(identifier, occurrences + 1);
+ const occurrences = seen.get(selector) ?? 0;
+ seen.set(selector, occurrences + 1);
return (
- <div
- key={`${identifier}-${idx}`}
+ <button
+ type="button"
+ aria-label={item.name}
+ key={`${selector}-${occurrences}`}
className={cn(
- "h-[2px] bg-muted-foreground/60",
+ "h-[2px] bg-muted-foreground/60 focus-visible:outline focus-visible:outline-ring",
item.level === 1 && "w-5",
item.level === 2 && "w-4",
item.level === 3 && "w-3",
@@ -91,24 +103,31 @@ export const MiniMap: React.FC<{
export const OutlineList: React.FC<{
className?: string;
+ inert?: boolean;
items: OutlineItem[];
activeHeaderId: string | undefined;
activeOccurrences: number | undefined;
-}> = ({ items, activeHeaderId, activeOccurrences, className }) => {
+}> = ({ items, activeHeaderId, activeOccurrences, className, inert }) => {
// Map of selector to its occurrences
const seen = new Map<string, number>();
return (
- <div className={cn("flex flex-col overflow-auto py-4 pl-2", className)}>
- {items.map((item, idx) => {
+ <div
+ inert={inert}
+ className={cn("flex flex-col overflow-auto py-4 pl-2", className)}
+ >
+ {items.map((item) => {
const identifier = "id" in item.by ? item.by.id : item.by.path;
+ const selector = JSON.stringify(item.by);
// Keep track of how many times we've seen this selector
- const occurrences = seen.get(identifier) ?? 0;
- seen.set(identifier, occurrences + 1);
+ const occurrences = seen.get(selector) ?? 0;
+ seen.set(selector, occurrences + 1);
- const key = `${identifier}-${idx}`;
+ const key = `${selector}-${occurrences}`;
const sharedProps = {
+ role: "link",
+ tabIndex: 0,
className: cn(
- "px-2 py-1 cursor-pointer hover:bg-accent/50 hover:text-accent-foreground rounded-l",
+ "px-2 py-1 cursor-pointer hover:bg-accent/50 hover:text-accent-foreground rounded-l focus-visible:outline focus-visible:outline-ring",
item.level === 1 && "font-semibold",
item.level === 2 && "ml-3",
item.level === 3 && "ml-6",
@@ -118,6 +137,12 @@ export const OutlineList: React.FC<{
"text-accent-foreground",
),
onClick: () => scrollToOutlineItem(item, occurrences),
+ onKeyDown: (e: React.KeyboardEvent) => {
+ if (e.target === e.currentTarget && e.key === "Enter") {
+ e.preventDefault();
+ scrollToOutlineItem(item, occurrences);
+ }
+ },
};
if (item.html) {
diff --git a/frontend/src/components/editor/chrome/panels/outline/useActiveOutline.tsx b/frontend/src/components/editor/chrome/panels/outline/useActiveOutline.tsx
index 7ab83c1156..6103788746 100644
--- a/frontend/src/components/editor/chrome/panels/outline/useActiveOutline.tsx
+++ b/frontend/src/components/editor/chrome/panels/outline/useActiveOutline.tsx
@@ -113,9 +113,10 @@ export function findOutlineElements(items: OutlineItem[]) {
return items
.map((item) => {
const identifier = "id" in item.by ? item.by.id : item.by.path;
+ const selector = JSON.stringify(item.by);
// Keep track of how many times we've seen this selector
- const occurrences = seen.get(identifier) ?? 0;
- seen.set(identifier, occurrences + 1);
+ const occurrences = seen.get(selector) ?? 0;
+ seen.set(selector, occurrences + 1);
const el = findOutlineItem(item, occurrences);
if (!el) {
diff --git a/frontend/src/components/editor/chrome/panels/secrets-panel.tsx b/frontend/src/components/editor/chrome/panels/secrets-panel.tsx
index cd2c63e197..651fc3400e 100644
--- a/frontend/src/components/editor/chrome/panels/secrets-panel.tsx
+++ b/frontend/src/components/editor/chrome/panels/secrets-panel.tsx
@@ -66,6 +66,7 @@ const SecretsPanel: React.FC = () => {
<div className="flex justify-start h-8 border-b">
<button
type="button"
+ aria-label="Add environment variable"
className="border-r px-2 m-0 h-full hover:bg-accent hover:text-accent-foreground"
onClick={() =>
openModal(
diff --git a/frontend/src/components/editor/chrome/panels/snippets-panel.tsx b/frontend/src/components/editor/chrome/panels/snippets-panel.tsx
index cb07490c7f..4fbcd371e3 100644
--- a/frontend/src/components/editor/chrome/panels/snippets-panel.tsx
+++ b/frontend/src/components/editor/chrome/panels/snippets-panel.tsx
@@ -71,7 +71,11 @@ const SnippetsPanel: React.FC = () => {
rootClassName="flex-1 border-r"
/>
<ContributeSnippetButton>
- <button className="float-right px-2 m-0 h-full hover:bg-accent hover:text-accent-foreground">
+ <button
+ type="button"
+ aria-label="Contribute snippet"
+ className="float-right px-2 m-0 h-full hover:bg-accent hover:text-accent-foreground"
+ >
<PlusIcon className="h-4 w-4" />
</button>
</ContributeSnippetButton>
diff --git a/frontend/src/components/editor/controls/__tests__/keyboard-shortcuts.test.tsx b/frontend/src/components/editor/controls/__tests__/keyboard-shortcuts.test.tsx
new file mode 100644
index 0000000000..13e061ed77
--- /dev/null
+++ b/frontend/src/components/editor/controls/__tests__/keyboard-shortcuts.test.tsx
@@ -0,0 +1,61 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import { createStore, Provider } from "jotai";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { userConfigAtom } from "@/core/config/config";
+import { defaultUserConfig } from "@/core/config/config-schema";
+import { getDefaultHotkey } from "@/core/hotkeys/hotkeys";
+import {
+ KeyboardShortcuts,
+ keyboardShortcutsAtom,
+} from "../keyboard-shortcuts";
+
+const saveUserConfig = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
+vi.mock("@/core/network/requests", () => ({
+ useRequestClient: () => ({ saveUserConfig }),
+}));
+
+describe("shortcut recorder keyboard navigation", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("allows Tab navigation and Reset without saving a shortcut", async () => {
+ const store = createStore();
+ const config = defaultUserConfig();
+ store.set(userConfigAtom, {
+ ...config,
+ keymap: { ...config.keymap, overrides: { "cell.run": "Ctrl-9" } },
+ });
+ store.set(keyboardShortcutsAtom, true);
+ render(
+ <Provider store={store}>
+ <TooltipProvider>
+ <KeyboardShortcuts />
+ </TooltipProvider>
+ </Provider>,
+ );
+ const edit = screen.getByRole("button", {
+ name: `Edit shortcut: ${getDefaultHotkey("cell.run").name}`,
+ });
+ act(() => edit.focus());
+ fireEvent.click(edit, { detail: 0 });
+ const recorder = screen.getByPlaceholderText(
+ getDefaultHotkey("cell.run").name,
+ );
+ expect(recorder).toHaveFocus();
+ expect(fireEvent.keyDown(recorder, { key: "Tab" })).toBe(true);
+ expect(fireEvent.keyDown(recorder, { key: "Tab", shiftKey: true })).toBe(
+ true,
+ );
+ expect(recorder).toBeInTheDocument();
+ expect(saveUserConfig).not.toHaveBeenCalled();
+ const reset = screen.getByRole("button", { name: /^Reset to default:/ });
+ act(() => reset.focus());
+ expect(reset).toHaveFocus();
+ await act(async () => fireEvent.click(reset, { detail: 0 }));
+ expect(saveUserConfig).toHaveBeenCalledExactlyOnceWith({
+ config: { keymap: { ...config.keymap, overrides: {} } },
+ });
+ });
+});
diff --git a/frontend/src/components/editor/controls/keyboard-shortcuts.tsx b/frontend/src/components/editor/controls/keyboard-shortcuts.tsx
index 0090e39f28..a048dc9c80 100644
--- a/frontend/src/components/editor/controls/keyboard-shortcuts.tsx
+++ b/frontend/src/components/editor/controls/keyboard-shortcuts.tsx
@@ -134,6 +134,9 @@ export const KeyboardShortcuts: React.FC = () => {
defaultValue={newShortcut.join("+")}
placeholder={hotkey.name}
onKeyDown={(e) => {
+ if (e.key === "Tab" && !e.metaKey && !e.ctrlKey && !e.altKey) {
+ return;
+ }
e.preventDefault();
const next: string[] = [];
@@ -189,6 +192,7 @@ export const KeyboardShortcuts: React.FC = () => {
autoFocus={true}
endAdornment={
<Button
+ aria-label="Cancel shortcut recording"
variant="text"
size="xs"
className="mb-0"
@@ -206,13 +210,14 @@ export const KeyboardShortcuts: React.FC = () => {
Press a key combination
</span>
{defaultHotkey.key !== hotkey.key && (
- <span
+ <button
+ type="button"
className="text-xs cursor-pointer text-primary"
onClick={handleResetShortcut}
>
Reset to default:{" "}
<span className="font-mono">{defaultHotkey.key}</span>
- </span>
+ </button>
)}
</div>
</div>
@@ -228,13 +233,17 @@ export const KeyboardShortcuts: React.FC = () => {
className="grid grid-cols-[auto_2fr_3fr] gap-2 items-center"
>
{hotkeys.isEditable(action) ? (
- <EditIcon
- className="cursor-pointer opacity-60 hover:opacity-100 text-muted-foreground w-3 h-3"
+ <button
+ type="button"
+ aria-label={`Edit shortcut: ${hotkey.name}`}
+ className="cursor-pointer opacity-60 hover:opacity-100 text-muted-foreground w-3 h-3 focus-visible:outline focus-visible:outline-ring"
onClick={() => {
setNewShortcut([]);
setEditingShortcut(action);
}}
- />
+ >
+ <EditIcon className="w-3 h-3" />
+ </button>
) : (
<div className="w-3 h-3" />
)}
diff --git a/frontend/src/components/editor/file-tree/__tests__/file-explorer-navigation.test.tsx b/frontend/src/components/editor/file-tree/__tests__/file-explorer-navigation.test.tsx
index def21d3d80..e10cdbd14e 100644
--- a/frontend/src/components/editor/file-tree/__tests__/file-explorer-navigation.test.tsx
+++ b/frontend/src/components/editor/file-tree/__tests__/file-explorer-navigation.test.tsx
@@ -17,6 +17,7 @@ import { TooltipProvider } from "@/components/ui/tooltip";
import { requestClientAtom } from "@/core/network/requests";
import type { FileInfo, FileSearchResponse } from "@/core/network/types";
import { Deferred } from "@/utils/Deferred";
+import { openNotebook } from "@/utils/links";
import type { FilePath } from "@/utils/paths";
import { TreeDndProvider } from "../dnd-wrapper";
import { FileExplorer } from "../file-explorer";
@@ -29,6 +30,11 @@ vi.mock("../file-viewer", () => ({
FileViewer: ({ file }: { file: FileInfo }) => <div>Preview: {file.name}</div>,
}));
+vi.mock("@/utils/links", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/utils/links")>()),
+ openNotebook: vi.fn(),
+}));
+
function file(name: string, isDirectory = false): FileInfo {
return {
id: name,
@@ -91,6 +97,47 @@ beforeEach(() => {
});
describe("file browser navigation", () => {
+ it("tabs into the notebook action, returns to its row, and exits the tree", async () => {
+ client.sendListFiles.mockResolvedValue({
+ root: "/workspace",
+ files: [
+ { ...file("notebook.py"), isMarimoFile: true },
+ file("notes.txt"),
+ ],
+ });
+ render(
+ <>
+ <FileExplorer height={300} />
+ <button type="button">After tree</button>
+ </>,
+ { wrapper },
+ );
+ const row = await screen.findByRole("treeitem", { name: "notebook.py" });
+ act(() => row.focus());
+ fireEvent.keyDown(row, { key: "Tab" });
+ const open = screen.getByRole("button", {
+ name: "Open notebook notebook.py",
+ });
+ expect(open).toHaveFocus();
+ fireEvent.keyDown(open, { key: "Tab", shiftKey: true });
+ expect(row).toHaveFocus();
+ fireEvent.keyDown(row, { key: "Tab" });
+ for (const key of ["Enter", " "]) {
+ expect(fireEvent.keyDown(open, { key })).toBe(true);
+ expect(
+ screen.queryByText("Preview: notebook.py"),
+ ).not.toBeInTheDocument();
+ }
+ fireEvent.click(open);
+ expect(openNotebook).toHaveBeenCalledExactlyOnceWith("notebook.py");
+ fireEvent.keyDown(open, { key: "Tab" });
+ expect(screen.getByRole("button", { name: "After tree" })).toHaveFocus();
+ const plain = screen.getByRole("treeitem", { name: "notes.txt" });
+ act(() => plain.focus());
+ fireEvent.keyDown(plain, { key: "Tab" });
+ expect(screen.getByRole("button", { name: "After tree" })).toHaveFocus();
+ });
+
it("debounces the first character, subsequent edits, and searches after clearing", async () => {
render(<FileExplorer height={300} />, { wrapper });
const input = await screen.findByRole("textbox", {
diff --git a/frontend/src/components/editor/file-tree/file-explorer.tsx b/frontend/src/components/editor/file-tree/file-explorer.tsx
index c741dc9e29..1858a146e5 100644
--- a/frontend/src/components/editor/file-tree/file-explorer.tsx
+++ b/frontend/src/components/editor/file-tree/file-explorer.tsx
@@ -263,6 +263,27 @@ export const FileExplorer: React.FC<{
event.target instanceof Element
? event.target.getAttribute("role")
: null;
+ if (event.key === "Tab" && event.target instanceof HTMLElement) {
+ if (!event.shiftKey && role === "treeitem") {
+ const action = event.target.querySelector<HTMLButtonElement>(
+ '[data-file-tree-action="open"]',
+ );
+ if (action) {
+ event.preventDefault();
+ event.stopPropagation();
+ action.focus();
+ return;
+ }
+ } else if (
+ event.shiftKey &&
+ event.target.dataset.fileTreeAction === "open"
+ ) {
+ event.preventDefault();
+ event.stopPropagation();
+ event.target.closest<HTMLElement>('[role="treeitem"]')?.focus();
+ return;
+ }
+ }
if (query.trim() || (role !== "treeitem" && role !== "tree")) {
return;
}
@@ -637,13 +658,24 @@ const Show = ({
<span className="flex-1 overflow-hidden text-ellipsis">
{node.data.name}
{node.data.isMarimoFile && node.data.isPrimaryRoot && !isWasm() && (
- <span
+ <button
+ type="button"
+ aria-label={`Open notebook ${node.data.name}`}
data-testid="file-explorer-open-marimo-button"
- className="shrink-0 ml-2 text-sm hidden group-hover:inline hover:underline"
+ data-file-tree-action="open"
+ onKeyDown={(event) => {
+ if (event.key !== "Tab") {
+ event.stopPropagation();
+ }
+ }}
+ className={cn(
+ "shrink-0 ml-2 text-sm hidden group-hover:inline group-focus-within:inline hover:underline",
+ node.isFocused && "inline",
+ )}
onClick={onOpenMarimoFile}
>
open <ExternalLinkIcon className="inline ml-1" size={12} />
- </span>
+ </button>
)}
</span>
);
diff --git a/frontend/src/components/editor/file-tree/file-name-input.tsx b/frontend/src/components/editor/file-tree/file-name-input.tsx
index 4804be085f..701949f5a8 100644
--- a/frontend/src/components/editor/file-tree/file-name-input.tsx
+++ b/frontend/src/components/editor/file-tree/file-name-input.tsx
@@ -28,6 +28,7 @@ export const FileNameInput = <T extends FileInfo>({
return (
<input
ref={ref}
+ aria-label="File name"
className="flex-1 bg-transparent border border-border text-muted-foreground"
defaultValue={node.data.name}
onClick={(e) => e.stopPropagation()}
diff --git a/frontend/src/components/editor/header/status.tsx b/frontend/src/components/editor/header/status.tsx
index 3a3da00157..74925a8389 100644
--- a/frontend/src/components/editor/header/status.tsx
+++ b/frontend/src/components/editor/header/status.tsx
@@ -85,15 +85,38 @@ const RunningIcon = () => {
? "Scratchpad is running"
: "Jump to running cell";
+ const icon = (
+ <HourglassIcon className="running-app-icon" size={30} strokeWidth={1} />
+ );
+
+ if (scratchpadOnly) {
+ return (
+ <Tooltip content={tooltip} side="right">
+ <span
+ className={topLeftStatus}
+ data-testid="loading-indicator"
+ // Execution progress is advisory status, not a form result.
+ // eslint-disable-next-line jsx-a11y/prefer-tag-over-role
+ role="status"
+ aria-label={tooltip}
+ >
+ {icon}
+ </span>
+ </Tooltip>
+ );
+ }
+
return (
<Tooltip content={tooltip} side="right">
- <div
- className={topLeftStatus}
+ <button
+ type="button"
+ aria-label={tooltip}
+ className={cn(topLeftStatus, "bg-transparent border-0 p-0")}
data-testid="loading-indicator"
- onClick={scratchpadOnly ? undefined : notebookScrollToRunning}
+ onClick={notebookScrollToRunning}
>
- <HourglassIcon className="running-app-icon" size={30} strokeWidth={1} />
- </div>
+ {icon}
+ </button>
</Tooltip>
);
};
diff --git a/frontend/src/components/editor/links/__tests__/cell-link.test.tsx b/frontend/src/components/editor/links/__tests__/cell-link.test.tsx
new file mode 100644
index 0000000000..ac605d7de7
--- /dev/null
+++ b/frontend/src/components/editor/links/__tests__/cell-link.test.tsx
@@ -0,0 +1,146 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import { useState } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { cellId } from "@/__tests__/branded";
+import { HTMLCellId, SCRATCH_CELL_ID } from "@/core/cells/ids";
+import { goToCellLine } from "@/core/codemirror/go-to-definition/utils";
+import { CellLink, CellLinkTraceback } from "../cell-link";
+
+const showCellIfHidden = vi.hoisted(() => vi.fn());
+const targetId = cellId("target");
+
+vi.mock("@/core/cells/cells", () => ({
+ useCellActions: () => ({ showCellIfHidden }),
+ useCellIds: () => ({ inOrderIds: [targetId] }),
+ useCellNames: () => ({ [targetId]: "Target" }),
+}));
+vi.mock("@/core/saving/filename", () => ({ useFilename: () => "notebook.py" }));
+vi.mock("@/core/codemirror/go-to-definition/utils", () => ({
+ goToCellLine: vi.fn(),
+}));
+
+function flushNavigation() {
+ act(() => vi.advanceTimersToNextFrame());
+}
+
+describe("CellLink navigation", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.clearAllMocks();
+ showCellIfHidden.mockReset();
+ });
+ afterEach(() => vi.useRealTimers());
+
+ it("focuses, scrolls, and highlights the target on keyboard activation", () => {
+ render(
+ <>
+ <CellLink cellId={targetId} />
+ <div
+ id={HTMLCellId.create(targetId)}
+ tabIndex={-1}
+ data-testid="target"
+ />
+ </>,
+ );
+ const target = screen.getByTestId("target");
+ target.scrollIntoView = vi.fn();
+ const focus = vi.spyOn(target, "focus");
+ const link = screen.getByRole("link");
+ expect(link).toHaveAttribute("href", `#${target.id}`);
+ link.focus();
+ // Native anchors emit a click with detail=0 when activated with Enter.
+ expect(fireEvent.click(link, { detail: 0 })).toBe(false);
+ flushNavigation();
+
+ expect(showCellIfHidden).toHaveBeenCalledExactlyOnceWith({
+ cellId: targetId,
+ });
+ expect(target).toHaveFocus();
+ expect(focus).toHaveBeenCalledWith({ preventScroll: true });
+ expect(target.scrollIntoView).toHaveBeenCalledExactlyOnceWith({
+ behavior: "smooth",
+ block: "center",
+ });
+ expect(target).toHaveClass("focus-outline");
+ });
+
+ it("reveals a hidden destination before moving focus", () => {
+ function HiddenCell() {
+ const [visible, setVisible] = useState(false);
+ showCellIfHidden.mockImplementation(() => setVisible(true));
+ return (
+ <>
+ <CellLink cellId={targetId} skipScroll={true} />
+ {visible && (
+ <div
+ id={HTMLCellId.create(targetId)}
+ tabIndex={-1}
+ data-testid="target"
+ />
+ )}
+ </>
+ );
+ }
+ render(<HiddenCell />);
+ expect(screen.queryByTestId("target")).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("link"));
+ flushNavigation();
+ expect(screen.getByTestId("target")).toHaveFocus();
+ });
+
+ it.each([
+ { metaKey: true },
+ { ctrlKey: true },
+ { shiftKey: true },
+ { altKey: true },
+ { button: 1 },
+ ])("preserves browser activation for %o", (modifiers) => {
+ render(<CellLink cellId={targetId} />);
+ const link = screen.getByRole("link");
+ link.focus();
+ expect(fireEvent.click(link, modifiers)).toBe(true);
+ flushNavigation();
+ expect(showCellIfHidden).not.toHaveBeenCalled();
+ expect(link).toHaveFocus();
+ });
+
+ it("lets traceback line navigation choose the final focus", () => {
+ render(
+ <>
+ <CellLinkTraceback cellId={targetId} lineNumber={7} />
+ <div
+ id={HTMLCellId.create(targetId)}
+ tabIndex={-1}
+ data-testid="target"
+ >
+ <textarea aria-label="Editor" />
+ </div>
+ </>,
+ );
+ const target = screen.getByTestId("target");
+ target.scrollIntoView = vi.fn();
+ const editor = screen.getByRole("textbox", { name: "Editor" });
+ vi.mocked(goToCellLine).mockImplementation(() => {
+ expect(target).toHaveFocus();
+ editor.focus();
+ return true;
+ });
+ fireEvent.click(screen.getByRole("link"));
+ flushNavigation();
+ expect(goToCellLine).toHaveBeenCalledExactlyOnceWith(targetId, 7);
+ expect(editor).toHaveFocus();
+ expect(target.scrollIntoView).not.toHaveBeenCalled();
+ });
+
+ it("keeps scratch references non-navigable", () => {
+ render(
+ <CellLink cellId={SCRATCH_CELL_ID} formatCellName={() => "scratch"} />,
+ );
+ expect(screen.queryByRole("link")).not.toBeInTheDocument();
+ fireEvent.click(screen.getByText("scratch"));
+ flushNavigation();
+ expect(showCellIfHidden).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/components/editor/links/cell-link.tsx b/frontend/src/components/editor/links/cell-link.tsx
index e6c1c48d69..34f5a71281 100644
--- a/frontend/src/components/editor/links/cell-link.tsx
+++ b/frontend/src/components/editor/links/cell-link.tsx
@@ -7,7 +7,9 @@ import { displayCellName } from "@/core/cells/names";
import { goToCellLine } from "@/core/codemirror/go-to-definition/utils";
import { useFilename } from "@/core/saving/filename";
import { cn } from "@/utils/cn";
+import { Events } from "@/utils/events";
import { Logger } from "../../../utils/Logger";
+import { focusCell } from "../navigation/focus-utils";
interface Props {
cellId: CellId;
@@ -29,14 +31,20 @@ export const CellLink = (props: Props): JSX.Element => {
const formatName = formatCellName ?? ((name: string) => name);
return (
- <div
+ // Reveal hidden cells before scrolling and focusing the destination.
+ // react-doctor-disable-next-line react-doctor/no-prevent-default
+ <a
+ href={
+ cellId === SCRATCH_CELL_ID ? undefined : `#${HTMLCellId.create(cellId)}`
+ }
className={cn(
- "inline-block cursor-pointer text-link hover:underline",
+ "inline-block cursor-pointer text-left text-link hover:underline focus-visible:outline focus-visible:outline-ring",
className,
)}
- role="link"
- tabIndex={-1}
onClick={(e) => {
+ if (e.defaultPrevented || e.button !== 0 || Events.hasModifier(e)) {
+ return;
+ }
// Scratch causes a crash since scratch is not registered like a
// normal cell.
if (cellId === SCRATCH_CELL_ID) {
@@ -48,13 +56,14 @@ export const CellLink = (props: Props): JSX.Element => {
requestAnimationFrame(() => {
const succeeded = scrollAndHighlightCell(cellId, variant, skipScroll);
if (succeeded) {
+ focusCell(cellId, { preventScroll: true });
onClick?.();
}
});
}}
>
{formatName(displayCellName(cellName, cellIndex))}
- </div>
+ </a>
);
};
diff --git a/frontend/src/components/editor/navigation/focus-utils.ts b/frontend/src/components/editor/navigation/focus-utils.ts
index c693a30fcf..38de58f25e 100644
--- a/frontend/src/components/editor/navigation/focus-utils.ts
+++ b/frontend/src/components/editor/navigation/focus-utils.ts
@@ -19,10 +19,10 @@ export function focusCellEditor(
}
}
-export function focusCell(cellId: CellId): void {
+export function focusCell(cellId: CellId, options?: FocusOptions): void {
const element = document.getElementById(HTMLCellId.create(cellId));
if (element) {
- tryFocus(element);
+ tryFocus(element, options);
} else {
Logger.warn(`[CellFocusManager] focusCell: element not found: ${cellId}`);
}
@@ -48,9 +48,9 @@ export function isAnyCellFocused(): boolean {
);
}
-export function tryFocus(dom: HTMLElement) {
+export function tryFocus(dom: HTMLElement, options?: FocusOptions) {
try {
- dom.focus();
+ dom.focus(options);
} catch {
Logger.warn("[CellFocusManager] element may not be focusable", dom);
}
diff --git a/frontend/src/components/editor/notebook-cell.tsx b/frontend/src/components/editor/notebook-cell.tsx
index f5b53dfe9c..c215aac2b3 100644
--- a/frontend/src/components/editor/notebook-cell.tsx
+++ b/frontend/src/components/editor/notebook-cell.tsx
@@ -525,13 +525,22 @@ const EditableCellComponent = ({
isMarkdownCodeHidden &&
isEmptyMarkdownContent &&
!needsRun && (
+ // Preserve pointer double-click editing; keyboard and assistive clicks activate directly.
+ // react-doctor-disable-next-line react-doctor/prefer-tag-over-role
<div
+ // eslint-disable-next-line jsx-a11y/prefer-tag-over-role
role="button"
- aria-label="Double-click to edit markdown"
+ aria-label="Edit markdown"
className="relative cursor-pointer px-3 py-2"
onDoubleClick={showHiddenCodeIfMarkdown}
+ onClick={(e) => {
+ if (e.detail === 0) {
+ showHiddenCodeIfMarkdown();
+ }
+ }}
onKeyDown={(e) => {
- if (e.key === "Enter") {
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
showHiddenCodeIfMarkdown();
}
}}
diff --git a/frontend/src/components/editor/output/MarimoTracebackOutput.tsx b/frontend/src/components/editor/output/MarimoTracebackOutput.tsx
index de7e240949..951317783d 100644
--- a/frontend/src/components/editor/output/MarimoTracebackOutput.tsx
+++ b/frontend/src/components/editor/output/MarimoTracebackOutput.tsx
@@ -248,21 +248,22 @@ export const replaceTracebackFilenames = (domNode: DOMNode) => {
<Tooltip content={tooltipContent}>
<button
type="button"
+ aria-label={
+ debuggerEnabled ? "Toggle breakpoint" : "Insert breakpoint"
+ }
className="ml-1 p-1 rounded-sm hover:bg-muted transition-colors inline"
+ onClick={() => {
+ if (debuggerEnabled && !isStaticNotebook()) {
+ toggleBreakpoint(info.cellId, info.lineNumber);
+ return;
+ }
+ const view = getCellEditorView(info.cellId);
+ if (view) {
+ insertDebuggerAtLine(view, info.lineNumber);
+ }
+ }}
>
- <BugPlayIcon
- onClick={() => {
- if (debuggerEnabled && !isStaticNotebook()) {
- toggleBreakpoint(info.cellId, info.lineNumber);
- return;
- }
- const view = getCellEditorView(info.cellId);
- if (view) {
- insertDebuggerAtLine(view, info.lineNumber);
- }
- }}
- className="h-3 w-3"
- />
+ <BugPlayIcon className="h-3 w-3" />
</button>
</Tooltip>
)}
@@ -272,7 +273,8 @@ export const replaceTracebackFilenames = (domNode: DOMNode) => {
}
if (info?.kind === "file") {
return (
- <div
+ <button
+ type="button"
className="inline-block cursor-pointer text-destructive hover:underline"
onClick={() => {
getRequestClient().openFile({
@@ -282,7 +284,7 @@ export const replaceTracebackFilenames = (domNode: DOMNode) => {
}}
>
<span className="nb">"{info.filePath}"</span>
- </div>
+ </button>
);
}
};
diff --git a/frontend/src/components/editor/output/__tests__/traceback.test.tsx b/frontend/src/components/editor/output/__tests__/traceback.test.tsx
index 64b70194ff..d7a97c3531 100644
--- a/frontend/src/components/editor/output/__tests__/traceback.test.tsx
+++ b/frontend/src/components/editor/output/__tests__/traceback.test.tsx
@@ -1,11 +1,12 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { render } from "@testing-library/react";
+import { fireEvent, render, screen } from "@testing-library/react";
import { Provider } from "jotai";
import { beforeAll, beforeEach, describe, expect, test, vi } from "vitest";
import { MockRequestClient } from "@/__mocks__/requests";
import { Tracebacks } from "@/__mocks__/tracebacks";
import { cellId } from "@/__tests__/branded";
+import { toggleBreakpoint } from "@/core/codemirror/cells/debugger-state";
import { TooltipProvider } from "@/components/ui/tooltip";
import { initialModeAtom } from "@/core/mode";
import { requestClientAtom } from "@/core/network/requests";
@@ -19,7 +20,32 @@ import {
const cid = cellId("1");
+vi.mock("@/core/config/feature-flag", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/core/config/feature-flag")>()),
+ getFeatureFlag: (flag: string) => flag === "debugger",
+}));
+vi.mock("@/core/codemirror/cells/debugger-state", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("@/core/codemirror/cells/debugger-state")
+ >()),
+ toggleBreakpoint: vi.fn(),
+}));
+
describe("traceback component", () => {
+ test("activates the breakpoint from the named button itself", () => {
+ render(
+ <Provider store={store}>
+ <TooltipProvider>
+ <MarimoTracebackOutput traceback={Tracebacks.raw} cellId={cid} />
+ </TooltipProvider>
+ </Provider>,
+ );
+ const buttons = screen.getAllByRole("button", {
+ name: "Toggle breakpoint",
+ });
+ fireEvent.click(buttons[0]);
+ expect(toggleBreakpoint).toHaveBeenCalledOnce();
+ });
beforeEach(() => {
vi.resetAllMocks();
store.set(initialModeAtom, "edit");
diff --git a/frontend/src/components/editor/package-alert.tsx b/frontend/src/components/editor/package-alert.tsx
index e4c88bd9d1..6d65fed1f8 100644
--- a/frontend/src/components/editor/package-alert.tsx
+++ b/frontend/src/components/editor/package-alert.tsx
@@ -55,6 +55,7 @@ import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
+ DropdownMenuItem,
DropdownMenuTrigger,
} from "../ui/dropdown-menu";
import { ExternalLink } from "../ui/links";
@@ -592,14 +593,18 @@ const ExtrasSelector: React.FC<ExtrasSelectorProps> = ({
<div className="p-2 bg-popover border-b border-border">
<div className="flex flex-wrap gap-1 p-1 min-h-[24px]">
{selectedExtras.map((extra) => (
- <span
+ <DropdownMenuItem
key={extra}
+ aria-label={`Remove ${extra}`}
className="inline-flex items-center gap-1 px-1 py-0.5 text-sm font-mono border border-muted-foreground/30 hover:border-muted-foreground/60 rounded-sm cursor-pointer group transition-colors"
- onClick={() => handleExtraToggle(extra, false)}
+ onSelect={(e) => {
+ e.preventDefault();
+ handleExtraToggle(extra, false);
+ }}
>
{extra}
<XIcon className="w-3 h-3 opacity-60 group-hover:opacity-100" />
- </span>
+ </DropdownMenuItem>
))}
</div>
</div>
diff --git a/frontend/src/components/scratchpad/scratchpad.test.tsx b/frontend/src/components/scratchpad/scratchpad.test.tsx
new file mode 100644
index 0000000000..04d07fc922
--- /dev/null
+++ b/frontend/src/components/scratchpad/scratchpad.test.tsx
@@ -0,0 +1,95 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { EditorView } from "@codemirror/view";
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import { createStore, Provider } from "jotai";
+import { type ComponentProps, useEffect, useRef } from "react";
+import { expect, it, vi } from "vitest";
+import type { CellEditor } from "@/components/editor/cell/code/cell-editor";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { SCRATCH_CELL_ID } from "@/core/cells/ids";
+import { ScratchPad } from "./scratchpad";
+import {
+ historyVisibleAtom,
+ scratchpadHistoryAtom,
+} from "./scratchpad-history";
+
+const state = vi.hoisted(() => ({
+ editor: null as EditorView | null,
+ updateCellCode: vi.fn(),
+}));
+
+vi.mock("@/core/cells/cells", () => ({
+ useNotebook: () => ({ cellRuntime: {}, cellData: {} }),
+ useCellActions: () => ({
+ createNewCell: vi.fn(),
+ updateCellCode: state.updateCellCode,
+ }),
+}));
+vi.mock("@/core/cells/focus", () => ({ useLastFocusedCellId: () => null }));
+vi.mock("@/core/network/requests", () => ({
+ useRequestClient: () => ({ sendRunScratchpad: vi.fn() }),
+}));
+vi.mock("@/components/editor/chrome/panels/panel-context", () => ({
+ usePanelOrientation: () => "vertical",
+ usePanelSection: () => "sidebar",
+}));
+vi.mock("@/components/editor/Output", () => ({ OutputArea: () => null }));
+vi.mock("@/components/editor/output/console/ConsoleOutput", () => ({
+ ConsoleOutput: () => null,
+}));
+vi.mock("@/plugins/impl/code/LazyAnyLanguageCodeMirror", () => ({
+ LazyAnyLanguageCodeMirror: () => null,
+}));
+vi.mock("@/components/shortcuts/renderShortcut", () => ({
+ renderShortcut: () => "",
+}));
+vi.mock("@/components/editor/cell/code/cell-editor", () => ({
+ CellEditor: ({ setEditorView }: ComponentProps<typeof CellEditor>) => {
+ const parent = useRef<HTMLDivElement>(null);
+ const setView = useRef(setEditorView);
+ useEffect(() => {
+ const view = new EditorView({
+ parent: parent.current ?? undefined,
+ extensions: [
+ EditorView.contentAttributes.of({
+ "aria-label": "Scratchpad editor",
+ }),
+ ],
+ });
+ state.editor = view;
+ setView.current(view);
+ return () => {
+ view.destroy();
+ state.editor = null;
+ };
+ }, []);
+ return <div ref={parent} />;
+ },
+}));
+
+it("focuses the editor after recalling history", () => {
+ const store = createStore();
+ store.set(scratchpadHistoryAtom, ["print(42)"]);
+ store.set(historyVisibleAtom, true);
+ render(
+ <Provider store={store}>
+ <TooltipProvider>
+ <ScratchPad />
+ </TooltipProvider>
+ </Provider>,
+ );
+ const recall = screen.getByRole("button", { name: "Recall code" });
+ act(() => recall.focus());
+ fireEvent.click(recall, { detail: 0 });
+ expect(recall).not.toBeInTheDocument();
+ expect(
+ screen.getByRole("textbox", { name: "Scratchpad editor" }),
+ ).toHaveFocus();
+ expect(state.editor?.state.doc.toString()).toBe("print(42)");
+ expect(state.updateCellCode).toHaveBeenCalledExactlyOnceWith({
+ cellId: SCRATCH_CELL_ID,
+ code: "print(42)",
+ formattingChange: false,
+ });
+});
diff --git a/frontend/src/components/scratchpad/scratchpad.tsx b/frontend/src/components/scratchpad/scratchpad.tsx
index 2dfd9208d8..d9e2304a71 100644
--- a/frontend/src/components/scratchpad/scratchpad.tsx
+++ b/frontend/src/components/scratchpad/scratchpad.tsx
@@ -123,6 +123,7 @@ export const ScratchPad: React.FC = () => {
insert: item,
},
});
+ ev.focus();
}
});
@@ -136,11 +137,23 @@ export const ScratchPad: React.FC = () => {
<div className="absolute inset-0 z-100 bg-background p-3 border-none overflow-auto">
<div className="overflow-auto flex flex-col gap-3">
{history.map((item) => (
+ // The Recall code button provides keyboard access without making the code preview a button.
+ // react-doctor-disable-next-line react-doctor/click-events-have-key-events, react-doctor/no-static-element-interactions
<div
key={item}
- className="border rounded-md hover:shadow-sm cursor-pointer hover:border-input overflow-hidden"
+ className="relative border rounded-md hover:shadow-sm cursor-pointer hover:border-input overflow-hidden"
onClick={() => handleSelectHistoryItem(item)}
>
+ <button
+ type="button"
+ className="sr-only focus:not-sr-only focus:absolute focus:right-1 focus:top-1 focus:z-10 focus:bg-background focus:px-2 focus:py-1 focus:outline focus:outline-ring"
+ onClick={(e) => {
+ e.stopPropagation();
+ handleSelectHistoryItem(item);
+ }}
+ >
+ Recall code
+ </button>
<Suspense>
<LazyAnyLanguageCodeMirror
language="python"
diff --git a/frontend/src/components/tracing/tracing-keyboard.test.tsx b/frontend/src/components/tracing/tracing-keyboard.test.tsx
new file mode 100644
index 0000000000..c3022ee70a
--- /dev/null
+++ b/frontend/src/components/tracing/tracing-keyboard.test.tsx
@@ -0,0 +1,85 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import { createStore, Provider } from "jotai";
+import { describe, expect, it, vi } from "vitest";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { type Run, type RunId, runsAtom } from "@/core/cells/runs";
+import { Tracing } from "./tracing";
+
+vi.mock("react-vega", () => ({ useVegaEmbed: () => undefined }));
+vi.mock("vega-lite", () => ({ compile: () => ({ spec: {} }) }));
+vi.mock("@/components/editor/chrome/panels/panel-context", () => ({
+ usePanelSection: () => "sidebar",
+}));
+
+const run: Run = {
+ runId: "run-1" as RunId,
+ runStartTime: 1_704_067_200,
+ cellRuns: new Map(),
+};
+
+describe("trace disclosure keyboard focus", () => {
+ it.each([false, true])(
+ "keeps the header focused across toggles (inline=%s)",
+ (inline) => {
+ const store = createStore();
+ store.set(runsAtom, {
+ runIds: [run.runId],
+ runMap: new Map([[run.runId, run]]),
+ });
+ render(
+ <Provider store={store}>
+ <TooltipProvider>
+ <Tracing />
+ </TooltipProvider>
+ </Provider>,
+ );
+ if (inline) {
+ fireEvent.click(screen.getByRole("checkbox", { name: "Inline chart" }));
+ }
+ const header = screen.getByRole("button", { name: /^Run -/ });
+ act(() => header.focus());
+ for (const expanded of [false, true, false]) {
+ // Native buttons emit a click with detail=0 for keyboard activation.
+ fireEvent.click(header, { detail: 0 });
+ expect(screen.getByRole("button", { name: /^Run -/ })).toBe(header);
+ expect(header).toHaveFocus();
+ expect(header).toHaveAttribute("aria-expanded", String(expanded));
+ }
+ },
+ );
+
+ it("does not steal focus when a newer run expands automatically", () => {
+ const store = createStore();
+ store.set(runsAtom, {
+ runIds: [run.runId],
+ runMap: new Map([[run.runId, run]]),
+ });
+ render(
+ <Provider store={store}>
+ <TooltipProvider>
+ <Tracing />
+ </TooltipProvider>
+ </Provider>,
+ );
+ const header = screen.getByRole("button", { name: /^Run -/ });
+ act(() => header.focus());
+ const newer: Run = {
+ ...run,
+ runId: "run-2" as RunId,
+ runStartTime: run.runStartTime + 1,
+ };
+ act(() => {
+ store.set(runsAtom, {
+ runIds: [newer.runId, run.runId],
+ runMap: new Map([
+ [run.runId, run],
+ [newer.runId, newer],
+ ]),
+ });
+ });
+ expect(header).toHaveFocus();
+ expect(header).toHaveAttribute("aria-expanded", "false");
+ });
+});
diff --git a/frontend/src/components/tracing/tracing.tsx b/frontend/src/components/tracing/tracing.tsx
index bb0fddce4b..fb53d9664a 100644
--- a/frontend/src/components/tracing/tracing.tsx
+++ b/frontend/src/components/tracing/tracing.tsx
@@ -52,6 +52,7 @@ export const Tracing: React.FC = () => {
const { theme } = useTheme();
const [chartPosition, setChartPosition] = useState<ChartPosition>("above");
+ const chartPositionId = React.useId();
const panelSection = usePanelSection();
const toggleChartPosition = () => {
@@ -76,11 +77,12 @@ export const Tracing: React.FC = () => {
<div className="py-1 px-2 overflow-y-scroll h-full">
<div className="flex flex-row justify-start gap-3">
<div className="flex flex-row gap-1 items-center">
- <label htmlFor="chartPosition" className="text-xs">
+ <label htmlFor={chartPositionId} className="text-xs">
Inline chart
</label>
<input
type="checkbox"
+ id={chartPositionId}
name="chartPosition"
data-testid="chartPosition"
onClick={toggleChartPosition}
@@ -163,28 +165,31 @@ const TraceBlock: React.FC<{
const chevron = <Icon height={16} className="inline" />;
const traceTitle = (
- <span className="text-sm cursor-pointer" onClick={onToggleExpanded}>
+ <button
+ type="button"
+ aria-expanded={isExpanded}
+ className="text-sm cursor-pointer"
+ onClick={onToggleExpanded}
+ >
Run - {formatLogTimestamp(run.runStartTime)}
{chevron}
- </span>
+ </button>
);
- if (!isExpanded) {
- return (
- <div key={run.runId} className="flex flex-col">
- <pre className="font-mono font-semibold">{traceTitle}</pre>
- </div>
- );
- }
-
return (
- <TraceBlockBody
- key={run.runId}
- run={run}
- chartPosition={chartPosition}
- theme={theme}
- title={traceTitle}
- />
+ <div
+ className={cn(
+ "grid grid-cols-1",
+ isExpanded &&
+ chartPosition === "sideBySide" &&
+ "grid-cols-[auto_minmax(0,1fr)] grid-rows-[auto_1fr]",
+ )}
+ >
+ <pre className="font-mono font-semibold">{traceTitle}</pre>
+ {isExpanded && (
+ <TraceBlockBody run={run} chartPosition={chartPosition} theme={theme} />
+ )}
+ </div>
);
};
@@ -192,8 +197,7 @@ const TraceBlockBody: React.FC<{
run: Run;
chartPosition: ChartPosition;
theme: ResolvedTheme;
- title: React.ReactNode;
-}> = ({ run, chartPosition, theme, title }) => {
+}> = ({ run, chartPosition, theme }) => {
const [hoveredCellId, setHoveredCellId] = useState<CellId | null>();
const vegaRef = useRef<HTMLDivElement>(null);
const { ref, width = 300 } = useResizeObserver<HTMLDivElement>();
@@ -264,16 +268,22 @@ const TraceBlockBody: React.FC<{
}, [embed]);
const traceRows = (
- <TraceRows
- run={run}
- hoveredCellId={hoveredCellId}
- hiddenInputElementId={hiddenInputElementId}
- />
+ <div className="font-mono font-semibold">
+ <TraceRows
+ run={run}
+ hoveredCellId={hoveredCellId}
+ hiddenInputElementId={hiddenInputElementId}
+ />
+ </div>
);
const chartElement = (
<div
- className={chartPosition === "sideBySide" ? "-mt-0.5 flex-1" : ""}
+ className={
+ chartPosition === "sideBySide"
+ ? "-mt-0.5 col-start-2 row-start-1 row-span-2 min-w-0"
+ : "min-w-0"
+ }
ref={ref}
>
<Suspense>
@@ -284,24 +294,18 @@ const TraceBlockBody: React.FC<{
if (chartPosition === "above") {
return (
- <div key={run.runId} className="flex flex-col">
- <pre className="font-mono font-semibold">
- {title}
- {chartElement}
- {traceRows}
- </pre>
- </div>
+ <>
+ {chartElement}
+ {traceRows}
+ </>
);
}
return (
- <div key={run.runId} className="flex flex-row">
- <pre className="font-mono font-semibold">
- {title}
- {traceRows}
- </pre>
+ <>
+ {traceRows}
{chartElement}
- </div>
+ </>
);
};
diff --git a/frontend/src/components/ui/__tests__/draggable-popover.test.tsx b/frontend/src/components/ui/__tests__/draggable-popover.test.tsx
new file mode 100644
index 0000000000..9eae7a3585
--- /dev/null
+++ b/frontend/src/components/ui/__tests__/draggable-popover.test.tsx
@@ -0,0 +1,24 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { fireEvent, render, screen } from "@testing-library/react";
+import { expect, it } from "vitest";
+import { DraggablePopover } from "../draggable-popover";
+
+it("moves from the keyboard handle without intercepting child input arrows", () => {
+ render(
+ <DraggablePopover open={true}>
+ <input aria-label="Filter" />
+ </DraggablePopover>,
+ );
+ const handle = screen.getByRole("button", {
+ name: "Move popup with arrow keys",
+ });
+ const popup = screen.getByRole("dialog");
+ fireEvent.keyDown(handle, { key: "ArrowRight" });
+ fireEvent.keyDown(handle, { key: "ArrowDown" });
+ expect(popup).toHaveStyle({ left: "10px", top: "10px" });
+ expect(
+ fireEvent.keyDown(screen.getByRole("textbox"), { key: "ArrowLeft" }),
+ ).toBe(true);
+ expect(popup).toHaveStyle({ left: "10px", top: "10px" });
+});
diff --git a/frontend/src/components/ui/draggable-popover.tsx b/frontend/src/components/ui/draggable-popover.tsx
index 1f7082f287..518b4262c8 100644
--- a/frontend/src/components/ui/draggable-popover.tsx
+++ b/frontend/src/components/ui/draggable-popover.tsx
@@ -53,14 +53,36 @@ export const DraggablePopover = ({
top: position.y,
}}
>
- <div
+ <button
+ type="button"
+ aria-label="Move popup with arrow keys"
onMouseDown={handleMouseDown}
+ onKeyDown={(e) => {
+ const directions: Record<
+ string,
+ { x: number; y: number } | undefined
+ > = {
+ ArrowLeft: { x: -10, y: 0 },
+ ArrowRight: { x: 10, y: 0 },
+ ArrowUp: { x: 0, y: -10 },
+ ArrowDown: { x: 0, y: 10 },
+ };
+ const offset = directions[e.key];
+ if (offset) {
+ e.preventDefault();
+ e.stopPropagation();
+ setPosition((previous) => ({
+ x: previous.x + offset.x,
+ y: previous.y + offset.y,
+ }));
+ }
+ }}
className={`flex items-center justify-center absolute top-0 left-1/2 -translate-x-1/2 ${
isDragging ? "cursor-grabbing" : "cursor-grab"
}`}
>
<GripHorizontalIcon className="h-5 w-5 mt-1 text-muted-foreground/40" />
- </div>
+ </button>
{children}
</PopoverContent>
</Popover>
diff --git a/frontend/src/plugins/impl/chat/chat-ui.tsx b/frontend/src/plugins/impl/chat/chat-ui.tsx
index 322e99fa2f..46e4eca37c 100644
--- a/frontend/src/plugins/impl/chat/chat-ui.tsx
+++ b/frontend/src/plugins/impl/chat/chat-ui.tsx
@@ -495,7 +495,7 @@ export const Chatbot: React.FC<Props> = (props) => {
: undefined,
})}
</div>
- <div className="flex justify-end text-xs gap-2 invisible group-hover:visible">
+ <div className="flex justify-end text-xs gap-2 opacity-0 group-hover:opacity-100 focus-within:opacity-100">
<CopyClipboardIcon
value={textContent}
className="h-3 w-3"
@@ -503,6 +503,7 @@ export const Chatbot: React.FC<Props> = (props) => {
/>
<button
type="button"
+ aria-label="Delete message"
onClick={() => handleDelete(message.id)}
className="text-xs text-(--slate-9) hover:text-(--slate-11)"
>
diff --git a/frontend/src/plugins/impl/data-explorer/components/column-summary.tsx b/frontend/src/plugins/impl/data-explorer/components/column-summary.tsx
index e104d152f4..33f7702e9d 100644
--- a/frontend/src/plugins/impl/data-explorer/components/column-summary.tsx
+++ b/frontend/src/plugins/impl/data-explorer/components/column-summary.tsx
@@ -60,7 +60,9 @@ export const ColumnSummary: React.FC<Props> = ({ schema }) => {
field: field,
});
return (
- <span
+ <button
+ type="button"
+ aria-pressed={selectedField === field}
key={field}
className={cn(
"hover:bg-muted self-start px-2 py-2 rounded flex flex-row gap-1 items-center cursor-pointer lg:justify-center text-sm truncate shrink-0 overflow-hidden",
@@ -81,7 +83,7 @@ export const ColumnSummary: React.FC<Props> = ({ schema }) => {
({cardinality})
</span>
)}
- </span>
+ </button>
);
})}
{hasMore && (
diff --git a/frontend/src/plugins/impl/data-frames/__tests__/sidebar.test.tsx b/frontend/src/plugins/impl/data-frames/__tests__/sidebar.test.tsx
new file mode 100644
index 0000000000..e3f621b205
--- /dev/null
+++ b/frontend/src/plugins/impl/data-frames/__tests__/sidebar.test.tsx
@@ -0,0 +1,160 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import { useState } from "react";
+import { expect, it, vi } from "vitest";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { Sidebar, TransformPanel } from "../panel";
+import { type TransformType, TransformTypeSchema } from "../schema";
+
+const transform: TransformType = { type: "select_columns", column_ids: [] };
+
+it("selects and deletes transforms through independent buttons", () => {
+ const onSelect = vi.fn();
+ const onDelete = vi.fn();
+ render(
+ <Sidebar
+ items={[{ id: "first", transform }]}
+ selected={0}
+ onSelect={onSelect}
+ onDelete={onDelete}
+ onAdd={vi.fn()}
+ />,
+ );
+ const select = screen.getByRole("button", { name: "Select Columns" });
+ expect(select).toHaveAttribute("aria-pressed", "true");
+ fireEvent.click(select);
+ expect(onSelect).toHaveBeenCalledExactlyOnceWith(0);
+ const remove = screen.getByRole("button", {
+ name: "Delete Select Columns transform 1",
+ });
+ remove.focus();
+ expect(remove).toHaveFocus();
+ fireEvent.click(remove);
+ expect(onDelete).toHaveBeenCalledExactlyOnceWith(0);
+ expect(onSelect).toHaveBeenCalledOnce();
+});
+
+it("preserves focused rows across value edits and removal of earlier duplicates", () => {
+ const first = { id: "first", transform };
+ const second = { id: "second", transform };
+ const props = {
+ selected: 1,
+ onSelect: vi.fn(),
+ onDelete: vi.fn(),
+ onAdd: vi.fn(),
+ };
+ const { rerender } = render(<Sidebar {...props} items={[first, second]} />);
+ const focused = screen.getAllByRole("button", { name: "Select Columns" })[1];
+ act(() => focused.focus());
+ const edited = {
+ ...second,
+ transform: TransformTypeSchema.parse({
+ ...transform,
+ column_ids: ["name"],
+ }),
+ };
+ rerender(<Sidebar {...props} items={[first, edited]} />);
+ expect(screen.getAllByRole("button", { name: "Select Columns" })[1]).toBe(
+ focused,
+ );
+ expect(focused).toHaveFocus();
+
+ rerender(<Sidebar {...props} items={[edited]} selected={0} />);
+ expect(screen.getByRole("button", { name: "Select Columns" })).toBe(focused);
+ expect(focused).toHaveFocus();
+ fireEvent.click(focused);
+ expect(props.onSelect).toHaveBeenLastCalledWith(0);
+});
+
+it.each([
+ { count: 3, removed: 0, destination: 1 },
+ { count: 3, removed: 1, destination: 0 },
+ { count: 3, removed: 2, destination: 1 },
+ { count: 1, removed: 0, destination: undefined },
+])(
+ "moves focus after deleting row $removed of $count",
+ ({ count, removed, destination }) => {
+ function Example() {
+ const [items, setItems] = useState(
+ Array.from({ length: count }, (_, index) => ({
+ id: `transform-${index}`,
+ transform,
+ })),
+ );
+ return (
+ <Sidebar
+ items={items}
+ selected={undefined}
+ onSelect={vi.fn()}
+ onDelete={(index) =>
+ setItems((current) => current.filter((_, i) => i !== index))
+ }
+ onAdd={vi.fn()}
+ />
+ );
+ }
+ render(<Example />);
+ const selectButtons = screen.getAllByRole("button", {
+ name: "Select Columns",
+ });
+ const target =
+ destination === undefined
+ ? screen.getByRole("button", { name: "Add" })
+ : selectButtons[destination];
+ const remove = screen.getByRole("button", {
+ name: `Delete Select Columns transform ${removed + 1}`,
+ });
+ act(() => remove.focus());
+ fireEvent.click(remove, { detail: 0 });
+ expect(remove).not.toBeInTheDocument();
+ expect(target).toHaveFocus();
+ },
+);
+
+it("uses persistent field-array IDs in the transformation panel", () => {
+ render(
+ <TooltipProvider>
+ <TransformPanel
+ initialValue={{ transforms: [transform, transform] }}
+ columns={new Map()}
+ lazy={true}
+ onChange={vi.fn()}
+ onInvalidChange={vi.fn()}
+ getColumnValues={async () => ({ values: [], too_many_values: false })}
+ />
+ </TooltipProvider>,
+ );
+ const survivor = screen.getAllByRole("button", { name: "Select Columns" })[1];
+ const remove = screen.getByRole("button", {
+ name: "Delete Select Columns transform 1",
+ });
+ act(() => remove.focus());
+ fireEvent.click(remove, { detail: 0 });
+ expect(screen.getByRole("button", { name: "Select Columns" })).toBe(survivor);
+ expect(survivor).toHaveFocus();
+ expect(survivor).toHaveAttribute("aria-pressed", "true");
+});
+
+it("does not move focus when deletion starts outside the focused row", () => {
+ render(
+ <>
+ <input aria-label="Transform setting" />
+ <Sidebar
+ items={[{ id: "first", transform }]}
+ selected={0}
+ onSelect={vi.fn()}
+ onDelete={vi.fn()}
+ onAdd={vi.fn()}
+ />
+ </>,
+ );
+ const input = screen.getByRole("textbox", { name: "Transform setting" });
+ act(() => input.focus());
+ fireEvent.click(
+ screen.getByRole("button", {
+ name: "Delete Select Columns transform 1",
+ }),
+ );
+ expect(input).toHaveFocus();
+});
diff --git a/frontend/src/plugins/impl/data-frames/panel.tsx b/frontend/src/plugins/impl/data-frames/panel.tsx
index e788464356..446b54cdd5 100644
--- a/frontend/src/plugins/impl/data-frames/panel.tsx
+++ b/frontend/src/plugins/impl/data-frames/panel.tsx
@@ -25,6 +25,7 @@ import React, {
useEffect,
useImperativeHandle,
useMemo,
+ useRef,
} from "react";
import { useFieldArray, useForm } from "react-hook-form";
import useEvent from "react-use-event-hook";
@@ -187,7 +188,10 @@ export const TransformPanel: React.FC<Props> = ({
className="relative flex flex-row max-h-[400px] overflow-hidden bg-background"
>
<Sidebar
- items={form.watch("transforms")}
+ items={transformsField.fields.map((field, index) => ({
+ id: field.id,
+ transform: transforms[index],
+ }))}
selected={selectedTransform}
onSelect={(index) => {
setSelectedTransform(index);
@@ -274,7 +278,7 @@ export const TransformPanel: React.FC<Props> = ({
};
interface SidebarProps {
- items: TransformType[];
+ items: { id: string; transform: TransformType }[];
selected: number | undefined;
onSelect: (index: number) => void;
onDelete: (index: number) => void;
@@ -288,34 +292,56 @@ export const Sidebar: React.FC<SidebarProps> = ({
onSelect,
onDelete,
}) => {
+ const selectionButtons = useRef(new Map<string, HTMLButtonElement>());
+ const addButton = useRef<HTMLButtonElement>(null);
+
return (
<div className="flex flex-col overflow-y-hidden w-[180px] shadow-xs h-full">
<div className="flex flex-col overflow-y-auto grow">
- {items.map((item, idx) => {
+ {items.map(({ id, transform }, idx) => {
return (
<div
- key={`${JSON.stringify(item)}-${idx}`}
- onClick={() => {
- onSelect(idx);
- }}
+ key={id}
className={cn(
- "flex flex-row min-h-[40px] items-center px-2 cursor-pointer hover:bg-accent/50 text-sm overflow-hidden hover-actions-parent border border-muted border-l-2 border-l-transparent",
+ "group flex flex-row min-h-[40px] items-center px-2 cursor-pointer hover:bg-accent/50 text-sm overflow-hidden border border-muted border-l-2 border-l-transparent",
{
"border-l-primary bg-accent text-accent-foreground":
selected === idx,
},
)}
>
- <div className="grow text-ellipsis">
- {Strings.startCase(item.type)}
- </div>
- <Trash2Icon
- className="w-3 h-3 hover-action text-muted-foreground hover:text-destructive"
- onClick={(e) => {
+ <button
+ ref={(button) => {
+ if (button) {
+ selectionButtons.current.set(id, button);
+ } else {
+ selectionButtons.current.delete(id);
+ }
+ }}
+ type="button"
+ className="grow text-left text-ellipsis py-2 focus-visible:outline focus-visible:outline-ring"
+ aria-pressed={selected === idx}
+ onClick={() => onSelect(idx)}
+ >
+ {Strings.startCase(transform.type)}
+ </button>
+ <button
+ type="button"
+ aria-label={`Delete ${Strings.startCase(transform.type)} transform ${idx + 1}`}
+ className="opacity-0 group-hover:opacity-100 focus-visible:opacity-100 text-muted-foreground hover:text-destructive focus-visible:outline focus-visible:outline-ring"
+ onClick={(event) => {
+ if (event.currentTarget.matches(":focus")) {
+ const neighbor = items[idx - 1] ?? items[idx + 1];
+ const target = neighbor
+ ? selectionButtons.current.get(neighbor.id)
+ : addButton.current;
+ target?.focus();
+ }
onDelete(idx);
- e.stopPropagation();
}}
- />
+ >
+ <Trash2Icon className="w-3 h-3" />
+ </button>
</div>
);
})}
@@ -323,6 +349,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
<div className="flex flex-row shrink-0">
<AddTransformDropdown onAdd={onAdd}>
<Button
+ ref={addButton}
data-testid="marimo-plugin-data-frames-add-transform"
variant="text"
className="w-full rounded-none m-0 hover:text-accent-foreground"