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.

mo.ui.matrix: type-to-edit cells and modifier-key scrubbing (#10520)

vincent d warmerdam5c3646a538e8
diff --git a/frontend/src/plugins/impl/MatrixPlugin.tsx b/frontend/src/plugins/impl/MatrixPlugin.tsx
index d8c3facb67..331e726a1f 100644
--- a/frontend/src/plugins/impl/MatrixPlugin.tsx
+++ b/frontend/src/plugins/impl/MatrixPlugin.tsx
@@ -54,6 +54,40 @@ export class MatrixPlugin implements IPlugin<T, Data> {
}
const PIXELS_PER_STEP = 10;
+const COARSE_MULTIPLIER = 10;
+const FINE_MULTIPLIER = 0.1;
+
+/** Step multiplier from modifier keys: shift = coarse, alt = fine. */
+const stepMultiplier = (e: { shiftKey: boolean; altKey: boolean }): number => {
+ if (e.shiftKey) {
+ return COARSE_MULTIPLIER;
+ }
+ if (e.altKey) {
+ return FINE_MULTIPLIER;
+ }
+ return 1;
+};
+
+/**
+ * Strip floating-point noise from step arithmetic (e.g. 3 * 0.1).
+ * The noise tolerance scales with the step so that legitimately tiny
+ * results (e.g. from a 2e-14 step) are preserved, while noise left over
+ * from arithmetic on ordinary magnitudes (e.g. the 5.55e-17 residue of
+ * 0.3 - 3 * 0.1) still snaps away.
+ */
+const cleanFloat = (x: number, step: number): number => {
+ const rounded = Number(x.toFixed(12));
+ const tolerance =
+ Number.EPSILON * Math.max(Math.abs(x), Math.abs(step)) * 100;
+ return Math.abs(x - rounded) <= tolerance ? rounded : x;
+};
+
+interface EditState {
+ row: number;
+ col: number;
+ text: string;
+ selectAll: boolean;
+}
interface MatrixComponentProps extends Data {
value: T;
@@ -80,6 +114,7 @@ const MatrixComponent = ({
col: number;
startX: number;
startValue: number;
+ multiplier: number;
} | null>(null);
const [activeCell, setActiveCell] = useState<{
row: number;
@@ -95,6 +130,16 @@ const MatrixComponent = ({
}, [value]);
const displayValue = activeCell == null ? value : draft;
+ // Editing state is mirrored in a ref so that the blur fired while
+ // committing (refocusing the cell unmounts the input) can't commit twice.
+ const [editing, setEditingState] = useState<EditState | null>(null);
+ const editingRef = useRef<EditState | null>(null);
+ const inputRef = useRef<HTMLInputElement | null>(null);
+ const setEditing = useCallback((edit: EditState | null) => {
+ editingRef.current = edit;
+ setEditingState(edit);
+ }, []);
+
const formatValue = (val: number) =>
scientific ? val.toExponential(precision) : val.toFixed(precision);
@@ -112,22 +157,131 @@ const MatrixComponent = ({
[minValue, maxValue],
);
+ // The single mutation chokepoint for every edit path (drag, arrow, type).
+ // Bounds are enforced here so no path can escape them. In symmetric mode
+ // the pair must stay equal *and* respect both cells' bounds, so the shared
+ // value is clamped to the intersection of the two ranges. Returns null
+ // when the clamped value is already in place, so callers can skip
+ // redundant updates.
+ const withCellValue = useCallback(
+ (base: T, row: number, col: number, newValue: number): T | null => {
+ const mirrored = symmetric && row !== col;
+ let clamped = clampValue(newValue, row, col);
+ if (mirrored) {
+ clamped = clampValue(clamped, col, row);
+ }
+ if (clamped === base[row][col]) {
+ return null;
+ }
+ const copy = base.map((r) => [...r]);
+ copy[row][col] = clamped;
+ if (mirrored) {
+ copy[col][row] = clamped;
+ }
+ return copy;
+ },
+ [symmetric, clampValue],
+ );
+
+ const startEditing = useCallback(
+ (row: number, col: number, seed?: string) => {
+ if (disabled[row][col]) {
+ return;
+ }
+ dragState.current = null;
+ setActiveCell(null);
+ setEditing({
+ row,
+ col,
+ text: seed ?? String(value[row][col]),
+ selectAll: seed == null,
+ });
+ },
+ [disabled, value, setEditing],
+ );
+
+ // Callback ref: focus the input when it mounts. When editing starts from
+ // a typed character, place the caret after the seed instead of selecting.
+ const focusInput = useCallback((el: HTMLInputElement | null) => {
+ inputRef.current = el;
+ if (el) {
+ el.focus();
+ if (editingRef.current?.selectAll) {
+ el.select();
+ } else {
+ el.setSelectionRange(el.value.length, el.value.length);
+ }
+ }
+ }, []);
+
+ const commitEdit = useCallback(
+ (refocusCell: boolean) => {
+ const edit = editingRef.current;
+ if (!edit) {
+ return;
+ }
+ const cell = refocusCell ? inputRef.current?.closest("td") : null;
+ setEditing(null);
+ const text = edit.text.trim();
+ const parsed = Number(text);
+ // Typed values are clamped to bounds but not snapped to `step`,
+ // so exact values like 2.32e7 survive.
+ if (text !== "" && Number.isFinite(parsed)) {
+ const copy = withCellValue(value, edit.row, edit.col, parsed);
+ if (copy) {
+ setDraft(copy);
+ setValue(copy);
+ }
+ }
+ cell?.focus();
+ },
+ [value, withCellValue, setValue, setEditing],
+ );
+
+ const cancelEdit = useCallback(() => {
+ const cell = inputRef.current?.closest("td");
+ setEditing(null);
+ cell?.focus();
+ }, [setEditing]);
+
+ const handleInputKeyDown = useCallback(
+ (e: React.KeyboardEvent) => {
+ e.stopPropagation();
+ if (e.key === "Enter") {
+ e.preventDefault();
+ commitEdit(true);
+ } else if (e.key === "Escape") {
+ e.preventDefault();
+ cancelEdit();
+ }
+ },
+ [commitEdit, cancelEdit],
+ );
+
const handlePointerDown = useCallback(
- (e: React.PointerEvent, row: number, col: number) => {
- if (disabled[row][col] || !(e.target instanceof Element)) {
+ (e: React.PointerEvent<HTMLTableCellElement>, row: number, col: number) => {
+ if (
+ disabled[row][col] ||
+ editing != null ||
+ !(e.target instanceof Element)
+ ) {
return;
}
e.preventDefault();
+ // preventDefault also suppresses the browser's click-to-focus, so
+ // focus the cell explicitly to keep keyboard stepping reachable.
+ e.currentTarget.focus();
e.target.setPointerCapture(e.pointerId);
dragState.current = {
row,
col,
startX: e.clientX,
startValue: displayValue[row][col],
+ multiplier: stepMultiplier(e),
};
setActiveCell({ row, col });
},
- [disabled, displayValue],
+ [disabled, editing, displayValue],
);
const handlePointerMove = useCallback(
@@ -136,26 +290,32 @@ const MatrixComponent = ({
if (!state) {
return;
}
+ const multiplier = stepMultiplier(e);
+ if (multiplier !== state.multiplier) {
+ // Rebase so toggling a modifier mid-drag rescales future movement
+ // instead of jumping the value.
+ state.startX = e.clientX;
+ state.startValue = displayValue[state.row][state.col];
+ state.multiplier = multiplier;
+ }
const { row, col, startX, startValue } = state;
const dx = e.clientX - startX;
- const cellStep = step[row][col];
+ const cellStep = step[row][col] * multiplier;
const steps = Math.round(dx / PIXELS_PER_STEP);
- const rawValue = startValue + steps * cellStep;
- const newValue = clampValue(rawValue, row, col);
-
- if (newValue !== displayValue[row][col]) {
- const copy = displayValue.map((r) => [...r]);
- copy[row][col] = newValue;
- if (symmetric && row !== col) {
- copy[col][row] = newValue;
- }
+ const copy = withCellValue(
+ displayValue,
+ row,
+ col,
+ cleanFloat(startValue + steps * cellStep, cellStep),
+ );
+ if (copy) {
setDraft(copy);
if (!debounce) {
setValue(copy);
}
}
},
- [step, clampValue, displayValue, symmetric, debounce, setValue],
+ [step, displayValue, withCellValue, debounce, setValue],
);
const handlePointerUp = useCallback(() => {
@@ -168,27 +328,61 @@ const MatrixComponent = ({
const handleKeyDown = useCallback(
(e: React.KeyboardEvent, row: number, col: number) => {
- if (e.key === "ArrowUp" || e.key === "ArrowDown") {
- if (disabled[row][col]) {
- return;
- }
+ if (disabled[row][col]) {
+ return;
+ }
+ if (e.key === "Enter" || e.key === "F2") {
e.preventDefault();
- const cellStep = step[row][col];
- const delta = e.key === "ArrowUp" ? cellStep : -cellStep;
- const newValue = clampValue(displayValue[row][col] + delta, row, col);
-
- if (newValue !== displayValue[row][col]) {
- const copy = displayValue.map((r) => [...r]);
- copy[row][col] = newValue;
- if (symmetric && row !== col) {
- copy[col][row] = newValue;
- }
- setDraft(copy);
- setValue(copy);
- }
+ startEditing(row, col);
+ return;
+ }
+ // Typing a number starts editing, seeded with the typed character.
+ if (
+ e.key.length === 1 &&
+ /[\d.+-]/.test(e.key) &&
+ !e.ctrlKey &&
+ !e.metaKey &&
+ !e.altKey
+ ) {
+ e.preventDefault();
+ startEditing(row, col, e.key);
+ return;
+ }
+ const cellStep = step[row][col];
+ let delta: number;
+ switch (e.key) {
+ // Right/left mirror up/down, matching the horizontal drag direction
+ // (and the native slider convention).
+ case "ArrowUp":
+ case "ArrowRight":
+ delta = cellStep * stepMultiplier(e);
+ break;
+ case "ArrowDown":
+ case "ArrowLeft":
+ delta = -cellStep * stepMultiplier(e);
+ break;
+ case "PageUp":
+ delta = cellStep * COARSE_MULTIPLIER;
+ break;
+ case "PageDown":
+ delta = -cellStep * COARSE_MULTIPLIER;
+ break;
+ default:
+ return;
+ }
+ e.preventDefault();
+ const copy = withCellValue(
+ displayValue,
+ row,
+ col,
+ cleanFloat(displayValue[row][col] + delta, delta),
+ );
+ if (copy) {
+ setDraft(copy);
+ setValue(copy);
}
},
- [disabled, step, displayValue, clampValue, symmetric, setValue],
+ [disabled, startEditing, step, displayValue, withCellValue, setValue],
);
const hasRowLabels = rowLabels != null && rowLabels.length > 0;
@@ -238,6 +432,10 @@ const MatrixComponent = ({
const isDisabled = disabled[i][j];
const isActive =
activeCell?.row === i && activeCell?.col === j;
+ const cellEdit =
+ editing != null && editing.row === i && editing.col === j
+ ? editing
+ : null;
const rowLabel = rowLabels?.[i] ?? `Row ${i + 1}`;
const colLabel = columnLabels?.[j] ?? `Column ${j + 1}`;
return (
@@ -247,24 +445,47 @@ const MatrixComponent = ({
"relative text-center min-w-14 h-8 px-2 transition-colors touch-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-hidden",
isDisabled
? "cursor-default text-muted-foreground"
- : "cursor-ew-resize text-link hover:bg-accent",
- isActive && "bg-accent",
+ : cellEdit
+ ? "cursor-text"
+ : "cursor-ew-resize text-link hover:bg-accent",
+ (isActive || cellEdit != null) && "bg-accent",
j === 0 && "bracket-l",
j === numCols - 1 && "bracket-r",
i === 0 && "bracket-t",
i === numRows - 1 && "bracket-b",
)}
tabIndex={isDisabled ? -1 : 0}
+ title={String(cellValue)}
aria-label={`${rowLabel}, ${colLabel}`}
aria-valuenow={cellValue}
aria-valuemin={minValue?.[i]?.[j]}
aria-valuemax={maxValue?.[i]?.[j]}
aria-disabled={isDisabled || undefined}
onPointerDown={(e) => handlePointerDown(e, i, j)}
+ onDoubleClick={() => startEditing(i, j)}
onKeyDown={(e) => handleKeyDown(e, i, j)}
data-testid={`matrix-cell-${i}-${j}`}
>
- {formatValue(cellValue)}
+ {cellEdit ? (
+ <input
+ ref={focusInput}
+ className="bg-transparent text-center font-mono text-sm text-foreground outline-none select-text"
+ style={{
+ width: `${Math.max(cellEdit.text.length + 2, 6)}ch`,
+ }}
+ value={cellEdit.text}
+ onChange={(e) =>
+ setEditing({ ...cellEdit, text: e.target.value })
+ }
+ onKeyDown={handleInputKeyDown}
+ onBlur={() => commitEdit(false)}
+ onPointerDown={(e) => e.stopPropagation()}
+ aria-label={`Edit ${rowLabel}, ${colLabel}`}
+ data-testid={`matrix-input-${i}-${j}`}
+ />
+ ) : (
+ formatValue(cellValue)
+ )}
</td>
);
})}
diff --git a/frontend/src/plugins/impl/__tests__/MatrixPlugin.test.tsx b/frontend/src/plugins/impl/__tests__/MatrixPlugin.test.tsx
index 3751854cf7..718f75a523 100644
--- a/frontend/src/plugins/impl/__tests__/MatrixPlugin.test.tsx
+++ b/frontend/src/plugins/impl/__tests__/MatrixPlugin.test.tsx
@@ -177,7 +177,7 @@ describe("MatrixPlugin", () => {
it("validates with zod schema", () => {
const plugin = new MatrixPlugin();
- const result = plugin.validator.safeParse({
+ const payload = {
initialValue: [
[1, 2],
[3, 4],
@@ -198,8 +198,12 @@ describe("MatrixPlugin", () => {
[false, false],
[false, false],
],
- });
- expect(result.success).toBe(true);
+ };
+ // debounce is optional and defaults off
+ expect(plugin.validator.parse(payload).debounce).toBe(false);
+ expect(plugin.validator.safeParse({ ...payload, step: null }).success).toBe(
+ false,
+ );
});
it("displays values in scientific notation", () => {
@@ -297,6 +301,26 @@ describe("MatrixPlugin", () => {
]);
});
+ it("ArrowUp preserves significant digits in large cell values", () => {
+ const plugin = new MatrixPlugin();
+ const setValueMock = vi.fn();
+ const props = makeProps({
+ value: [
+ [1_234_567_890_123, 0],
+ [0, 0],
+ ],
+ setValue: setValueMock,
+ });
+ const { getByTestId } = render(plugin.render(props));
+
+ fireEvent.keyDown(getByTestId("matrix-cell-0-0"), { key: "ArrowUp" });
+
+ expect(setValueMock).toHaveBeenCalledWith([
+ [1_234_567_890_124, 0],
+ [0, 0],
+ ]);
+ });
+
it("ArrowDown decrements cell value", () => {
const plugin = new MatrixPlugin();
const setValueMock = vi.fn();
@@ -317,6 +341,45 @@ describe("MatrixPlugin", () => {
]);
});
+ it("ArrowRight and ArrowLeft step like ArrowUp and ArrowDown", () => {
+ const plugin = new MatrixPlugin();
+ const setValueMock = vi.fn();
+ const props = makeProps({
+ value: [
+ [5, 0],
+ [0, 0],
+ ],
+ setValue: setValueMock,
+ });
+ const { getByTestId } = render(plugin.render(props));
+ const cell = getByTestId("matrix-cell-0-0");
+
+ fireEvent.keyDown(cell, { key: "ArrowRight" });
+ expect(setValueMock).toHaveBeenLastCalledWith([
+ [6, 0],
+ [0, 0],
+ ]);
+
+ // Modifier scaling applies to the horizontal pair too: 5 - 10x step
+ fireEvent.keyDown(cell, { key: "ArrowLeft", shiftKey: true });
+ expect(setValueMock).toHaveBeenLastCalledWith([
+ [-5, 0],
+ [0, 0],
+ ]);
+ });
+
+ it("clicking a cell focuses it for keyboard stepping", () => {
+ const plugin = new MatrixPlugin();
+ const props = makeProps();
+ const { getByTestId } = render(plugin.render(props));
+ const cell = getByTestId("matrix-cell-0-0");
+
+ fireEvent.pointerDown(cell, { clientX: 100, pointerId: 1 });
+ fireEvent.pointerUp(getByTestId("marimo-plugin-matrix"));
+
+ expect(document.activeElement).toBe(cell);
+ });
+
it("disabled cells ignore pointer and keyboard input", () => {
const plugin = new MatrixPlugin();
const setValueMock = vi.fn();
@@ -386,6 +449,38 @@ describe("MatrixPlugin", () => {
]);
});
+ it("with debounce, defers setValue until the drag ends", () => {
+ const plugin = new MatrixPlugin();
+ const setValueMock = vi.fn();
+ const props = makeProps({
+ value: [
+ [0, 0],
+ [0, 0],
+ ],
+ setValue: setValueMock,
+ data: {
+ ...makeProps().data,
+ debounce: true,
+ },
+ });
+ const { getByTestId } = render(plugin.render(props));
+ const cell = getByTestId("matrix-cell-0-0");
+ const container = getByTestId("marimo-plugin-matrix");
+
+ fireEvent.pointerDown(cell, { clientX: 100, pointerId: 1 });
+ fireEvent.pointerMove(container, { clientX: 130 });
+
+ // The dragged value renders locally but is not emitted yet.
+ expect(cell.textContent).toBe("3.0");
+ expect(setValueMock).not.toHaveBeenCalled();
+
+ fireEvent.pointerUp(container);
+ expect(setValueMock).toHaveBeenCalledExactlyOnceWith([
+ [3, 0],
+ [0, 0],
+ ]);
+ });
+
it("sets aria attributes on cells", () => {
const plugin = new MatrixPlugin();
const props = makeProps({
@@ -413,3 +508,445 @@ describe("MatrixPlugin", () => {
expect(cell.getAttribute("tabindex")).toBe("0");
});
});
+
+describe("MatrixPlugin cell editing", () => {
+ it("double-click opens an editor prefilled with the exact value", () => {
+ const plugin = new MatrixPlugin();
+ const props = makeProps();
+ const { getByTestId } = render(plugin.render(props));
+
+ fireEvent.doubleClick(getByTestId("matrix-cell-0-0"));
+
+ const input = getByTestId("matrix-input-0-0") as HTMLInputElement;
+ expect(input.value).toBe("1");
+ });
+
+ it("commits a typed scientific-notation value on Enter", () => {
+ const plugin = new MatrixPlugin();
+ const setValueMock = vi.fn();
+ const props = makeProps({ setValue: setValueMock });
+ const { getByTestId, queryByTestId } = render(plugin.render(props));
+
+ fireEvent.doubleClick(getByTestId("matrix-cell-0-0"));
+ const input = getByTestId("matrix-input-0-0");
+ fireEvent.change(input, { target: { value: "2.32e7" } });
+ fireEvent.keyDown(input, { key: "Enter" });
+
+ // Exactly once: the blur fired while refocusing the cell must not
+ // commit a second time.
+ expect(setValueMock).toHaveBeenCalledExactlyOnceWith([
+ [23_200_000, 2],
+ [3, 4],
+ ]);
+ expect(queryByTestId("matrix-input-0-0")).toBeNull();
+ });
+
+ it("does not snap typed values to step", () => {
+ const plugin = new MatrixPlugin();
+ const setValueMock = vi.fn();
+ const props = makeProps({ setValue: setValueMock });
+ const { getByTestId } = render(plugin.render(props));
+
+ fireEvent.doubleClick(getByTestId("matrix-cell-0-0"));
+ const input = getByTestId("matrix-input-0-0");
+ fireEvent.change(input, { target: { value: "2.5" } });
+ fireEvent.keyDown(input, { key: "Enter" });
+
+ // step is 1, but the typed value is exact
+ expect(setValueMock).toHaveBeenCalledWith([
+ [2.5, 2],
+ [3, 4],
+ ]);
+ });
+
+ it("commits on blur", () => {
+ const plugin = new MatrixPlugin();
+ const setValueMock = vi.fn();
+ const props = makeProps({ setValue: setValueMock });
+ const { getByTestId, queryByTestId } = render(plugin.render(props));
+
+ fireEvent.doubleClick(getByTestId("matrix-cell-0-0"));
+ const input = getByTestId("matrix-input-0-0");
+ fireEvent.change(input, { target: { value: "42" } });
+ fireEvent.blur(input);
+
+ expect(setValueMock).toHaveBeenCalledWith([
+ [42, 2],
+ [3, 4],
+ ]);
+ expect(queryByTestId("matrix-input-0-0")).toBeNull();
+ });
+
+ it("Escape cancels without committing", () => {
+ const plugin = new MatrixPlugin();
+ const setValueMock = vi.fn();
+ const props = makeProps({ setValue: setValueMock });
+ const { getByTestId, queryByTestId } = render(plugin.render(props));
+
+ fireEvent.doubleClick(getByTestId("matrix-cell-0-0"));
+ const input = getByTestId("matrix-input-0-0");
+ fireEvent.change(input, { target: { value: "42" } });
+ fireEvent.keyDown(input, { key: "Escape" });
+
+ expect(setValueMock).not.toHaveBeenCalled();
+ expect(queryByTestId("matrix-input-0-0")).toBeNull();
+ });
+
+ it("discards invalid input and closes the editor", () => {
+ const plugin = new MatrixPlugin();
+ const setValueMock = vi.fn();
+ const props = makeProps({ setValue: setValueMock });
+ const { getByTestId, queryByTestId } = render(plugin.render(props));
+
+ fireEvent.doubleClick(getByTestId("matrix-cell-0-0"));
+ const input = getByTestId("matrix-input-0-0");
+ fireEvent.change(input, { target: { value: "abc" } });
+ fireEvent.keyDown(input, { key: "Enter" });
+
+ expect(setValueMock).not.toHaveBeenCalled();
+ expect(queryByTestId("matrix-input-0-0")).toBeNull();
+ });
+
+ it("clamps typed values to bounds", () => {
+ const plugin = new MatrixPlugin();
+ const setValueMock = vi.fn();
+ const props = makeProps({
+ setValue: setValueMock,
+ data: {
+ ...makeProps().data,
+ maxValue: [
+ [10, 10],
+ [10, 10],
+ ],
+ },
+ });
+ const { getByTestId } = render(plugin.render(props));
+
+ fireEvent.doubleClick(getByTestId("matrix-cell-0-0"));
+ const input = getByTestId("matrix-input-0-0");
+ fireEvent.change(input, { target: { value: "50" } });
+ fireEvent.keyDown(input, { key: "Enter" });
+
+ expect(setValueMock).toHaveBeenCalledWith([
+ [10, 2],
+ [3, 4],
+ ]);
+ });
+
+ it("mirrors typed values in symmetric mode", () => {
+ const plugin = new MatrixPlugin();
+ const setValueMock = vi.fn();
+ const props = makeProps({
+ value: [
+ [0, 0],
+ [0, 0],
+ ],
+ setValue: setValueMock,
+ data: {
+ ...makeProps().data,
+ symmetric: true,
+ },
+ });
+ const { getByTestId } = render(plugin.render(props));
+
+ fireEvent.doubleClick(getByTestId("matrix-cell-0-1"));
+ const input = getByTestId("matrix-input-0-1");
+ fireEvent.change(input, { target: { value: "7" } });
+ fireEvent.keyDown(input, { key: "Enter" });
+
+ expect(setValueMock).toHaveBeenCalledWith([
+ [0, 7],
+ [7, 0],
+ ]);
+ });
+
+ it("keeps the symmetric mirror within the transpose cell's bounds", () => {
+ // Asymmetric per-cell bounds on a symmetric matrix: [0][1] allows up to
+ // 100, but its transpose [1][0] is capped at 5. Editing [0][1] must not
+ // smuggle an out-of-bounds value into the mirror, and the pair must stay
+ // equal — so the shared value is clamped to the intersection (max 5).
+ const plugin = new MatrixPlugin();
+ const setValueMock = vi.fn();
+ const props = makeProps({
+ value: [
+ [0, 0],
+ [0, 0],
+ ],
+ setValue: setValueMock,
+ data: {
+ ...makeProps().data,
+ symmetric: true,
+ maxValue: [
+ [100, 100],
+ [5, 100],
+ ],
+ },
+ });
+ const { getByTestId } = render(plugin.render(props));
+
+ fireEvent.doubleClick(getByTestId("matrix-cell-0-1"));
+ const input = getByTestId("matrix-input-0-1");
+ fireEvent.change(input, { target: { value: "7" } });
+ fireEvent.keyDown(input, { key: "Enter" });
+
+ expect(setValueMock).toHaveBeenCalledWith([
+ [0, 5],
+ [5, 0],
+ ]);
+ });
+
+ it("emits nothing when clamping leaves the value unchanged", () => {
+ // Already at the transpose's cap of 5: dragging or typing past it must
+ // not fire setValue with an identical matrix.
+ const plugin = new MatrixPlugin();
+ const setValueMock = vi.fn();
+ const props = makeProps({
+ value: [
+ [0, 5],
+ [5, 0],
+ ],
+ setValue: setValueMock,
+ data: {
+ ...makeProps().data,
+ symmetric: true,
+ maxValue: [
+ [100, 100],
+ [5, 100],
+ ],
+ },
+ });
+ const { getByTestId } = render(plugin.render(props));
+ const cell = getByTestId("matrix-cell-0-1");
+ const container = getByTestId("marimo-plugin-matrix");
+
+ fireEvent.pointerDown(cell, { clientX: 100, pointerId: 1 });
+ fireEvent.pointerMove(container, { clientX: 130 });
+ fireEvent.pointerUp(container);
+
+ fireEvent.doubleClick(cell);
+ const input = getByTestId("matrix-input-0-1");
+ fireEvent.change(input, { target: { value: "7" } });
+ fireEvent.keyDown(input, { key: "Enter" });
+
+ expect(setValueMock).not.toHaveBeenCalled();
+ });
+
+ it("Enter opens the editor from the keyboard", () => {
+ const plugin = new MatrixPlugin();
+ const props = makeProps();
+ const { getByTestId } = render(plugin.render(props));
+
+ fireEvent.keyDown(getByTestId("matrix-cell-0-0"), { key: "Enter" });
+
+ const input = getByTestId("matrix-input-0-0") as HTMLInputElement;
+ expect(input.value).toBe("1");
+ });
+
+ it("typing a digit starts editing seeded with that digit", () => {
+ const plugin = new MatrixPlugin();
+ const props = makeProps();
+ const { getByTestId } = render(plugin.render(props));
+
+ fireEvent.keyDown(getByTestId("matrix-cell-0-0"), { key: "5" });
+
+ const input = getByTestId("matrix-input-0-0") as HTMLInputElement;
+ expect(input.value).toBe("5");
+ });
+
+ it("does not open an editor on disabled cells", () => {
+ const plugin = new MatrixPlugin();
+ const props = makeProps({
+ data: {
+ ...makeProps().data,
+ disabled: [
+ [true, false],
+ [false, false],
+ ],
+ },
+ });
+ const { getByTestId, queryByTestId } = render(plugin.render(props));
+
+ fireEvent.doubleClick(getByTestId("matrix-cell-0-0"));
+ expect(queryByTestId("matrix-input-0-0")).toBeNull();
+
+ fireEvent.keyDown(getByTestId("matrix-cell-0-0"), { key: "Enter" });
+ expect(queryByTestId("matrix-input-0-0")).toBeNull();
+ });
+});
+
+describe("MatrixPlugin modifier scrubbing", () => {
+ it("shift+drag scrubs at 10x step", () => {
+ const plugin = new MatrixPlugin();
+ const setValueMock = vi.fn();
+ const props = makeProps({
+ value: [
+ [0, 0],
+ [0, 0],
+ ],
+ setValue: setValueMock,
+ });
+ const { getByTestId } = render(plugin.render(props));
+ const cell = getByTestId("matrix-cell-0-0");
+ const container = getByTestId("marimo-plugin-matrix");
+
+ fireEvent.pointerDown(cell, { clientX: 100, pointerId: 1, shiftKey: true });
+ fireEvent.pointerMove(container, { clientX: 130, shiftKey: true });
+ fireEvent.pointerUp(container);
+
+ expect(setValueMock).toHaveBeenCalledWith([
+ [30, 0],
+ [0, 0],
+ ]);
+ });
+
+ it("alt+drag scrubs at 0.1x step", () => {
+ const plugin = new MatrixPlugin();
+ const setValueMock = vi.fn();
+ const props = makeProps({
+ value: [
+ [0, 0],
+ [0, 0],
+ ],
+ setValue: setValueMock,
+ });
+ const { getByTestId } = render(plugin.render(props));
+ const cell = getByTestId("matrix-cell-0-0");
+ const container = getByTestId("marimo-plugin-matrix");
+
+ fireEvent.pointerDown(cell, { clientX: 100, pointerId: 1, altKey: true });
+ fireEvent.pointerMove(container, { clientX: 130, altKey: true });
+ fireEvent.pointerUp(container);
+
+ expect(setValueMock).toHaveBeenCalledWith([
+ [0.3, 0],
+ [0, 0],
+ ]);
+ });
+
+ it("pressing shift mid-drag rescales future movement without jumping", () => {
+ const plugin = new MatrixPlugin();
+ const setValueMock = vi.fn();
+ const props = makeProps({
+ value: [
+ [0, 0],
+ [0, 0],
+ ],
+ setValue: setValueMock,
+ });
+ const { getByTestId } = render(plugin.render(props));
+ const cell = getByTestId("matrix-cell-0-0");
+ const container = getByTestId("marimo-plugin-matrix");
+
+ fireEvent.pointerDown(cell, { clientX: 100, pointerId: 1 });
+ fireEvent.pointerMove(container, { clientX: 130 }); // +3
+ fireEvent.pointerMove(container, { clientX: 130, shiftKey: true }); // rebase
+ fireEvent.pointerMove(container, { clientX: 160, shiftKey: true }); // +30
+ fireEvent.pointerUp(container);
+
+ expect(setValueMock).toHaveBeenLastCalledWith([
+ [33, 0],
+ [0, 0],
+ ]);
+ });
+
+ it("shift+ArrowUp increments by 10x step", () => {
+ const plugin = new MatrixPlugin();
+ const setValueMock = vi.fn();
+ const props = makeProps({
+ value: [
+ [5, 0],
+ [0, 0],
+ ],
+ setValue: setValueMock,
+ });
+ const { getByTestId } = render(plugin.render(props));
+
+ fireEvent.keyDown(getByTestId("matrix-cell-0-0"), {
+ key: "ArrowUp",
+ shiftKey: true,
+ });
+
+ expect(setValueMock).toHaveBeenCalledWith([
+ [15, 0],
+ [0, 0],
+ ]);
+ });
+
+ it("alt+ArrowDown decrements by 0.1x step", () => {
+ const plugin = new MatrixPlugin();
+ const setValueMock = vi.fn();
+ const props = makeProps({
+ value: [
+ [5, 0],
+ [0, 0],
+ ],
+ setValue: setValueMock,
+ });
+ const { getByTestId } = render(plugin.render(props));
+
+ fireEvent.keyDown(getByTestId("matrix-cell-0-0"), {
+ key: "ArrowDown",
+ altKey: true,
+ });
+
+ expect(setValueMock).toHaveBeenCalledWith([
+ [4.9, 0],
+ [0, 0],
+ ]);
+ });
+
+ it("keeps tiny step values instead of rounding them to zero", () => {
+ // 2e-14 sits below the absolute noise threshold for values of ordinary
+ // magnitude; the tolerance must scale with the step to preserve it.
+ const plugin = new MatrixPlugin();
+ const setValueMock = vi.fn();
+ const props = makeProps({
+ value: [
+ [0, 0],
+ [0, 0],
+ ],
+ setValue: setValueMock,
+ data: {
+ ...makeProps().data,
+ step: [
+ [2e-14, 1],
+ [1, 1],
+ ],
+ },
+ });
+ const { getByTestId } = render(plugin.render(props));
+
+ fireEvent.keyDown(getByTestId("matrix-cell-0-0"), { key: "ArrowUp" });
+
+ expect(setValueMock).toHaveBeenCalledWith([
+ [2e-14, 0],
+ [0, 0],
+ ]);
+ });
+
+ it("PageUp and PageDown step by 10x", () => {
+ const plugin = new MatrixPlugin();
+ const setValueMock = vi.fn();
+ const props = makeProps({
+ value: [
+ [5, 0],
+ [0, 0],
+ ],
+ setValue: setValueMock,
+ });
+ const { getByTestId } = render(plugin.render(props));
+ const cell = getByTestId("matrix-cell-0-0");
+
+ fireEvent.keyDown(cell, { key: "PageUp" });
+ expect(setValueMock).toHaveBeenCalledWith([
+ [15, 0],
+ [0, 0],
+ ]);
+
+ fireEvent.keyDown(cell, { key: "PageDown" });
+ expect(setValueMock).toHaveBeenCalledWith([
+ [-5, 0],
+ [0, 0],
+ ]);
+ });
+});
diff --git a/marimo/_plugins/ui/_impl/matrix.py b/marimo/_plugins/ui/_impl/matrix.py
index d7f9dfeb3e..6921353e4f 100644
--- a/marimo/_plugins/ui/_impl/matrix.py
+++ b/marimo/_plugins/ui/_impl/matrix.py
@@ -303,7 +303,12 @@ class matrix(
"""An interactive matrix/vector editor.
A matrix UI element in which each entry is a slider: click and drag
- horizontally on an entry to increment or decrement its value. The matrix
+ horizontally on an entry to increment or decrement its value. Hold
+ shift while dragging (or pressing arrow keys) to move in 10x coarser
+ steps, or alt/option for 10x finer steps. To type an exact value,
+ including scientific notation like `2.32e7`, double-click an entry or
+ press Enter while it is focused; typed values are clamped to any
+ bounds but are not snapped to `step`. The matrix
can be configured in many ways, including element-wise bounds, element-wise
steps, an element-wise disable mask, and symmetry enforcement. These
configuration values may be any array-like object, including as lists,