A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feature: Hide cell code while editing (#506)
Myles Scolnicke5c24662498f
diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsxindex 34c1c86595..8d6ed61bae 100644--- a/frontend/src/components/editor/Cell.tsx+++ b/frontend/src/components/editor/Cell.tsx@@ -11,11 +11,11 @@ import {useRef,} from "react";-import { sendRun } from "@/core/network/requests";+import { saveCellConfig, sendRun } from "@/core/network/requests";import { autocompletionKeymap } from "@/core/codemirror/cm";import { clearTooltips } from "@/core/codemirror/completion/hints";import { UserConfig } from "../../core/config/config-schema";-import { CellData, CellRuntimeState } from "../../core/cells/types";+import { CellConfig, CellData, CellRuntimeState } from "../../core/cells/types";import { CellActions } from "../../core/cells/cells";import { derefNotNull } from "../../utils/dereference";import { OutputArea } from "./Output";@@ -42,6 +42,7 @@ import { getEditorCodeAsPython } from "@/core/codemirror/language/utils";import { outputIsStale } from "@/core/cells/cell";import { RuntimeState } from "@/core/kernel/RuntimeState";import { isOutputEmpty } from "@/core/cells/outputs";+import { useHotkeysOnElement } from "@/hooks/useHotkey";/*** Imperative interface of the cell.@@ -79,6 +80,9 @@ export interface CellProps| "focusCell"| "moveCell"| "moveToNextCell"+ | "updateCellConfig"+ | "sendToBottom"+ | "sendToTop"> {theme: Theme;showPlaceholder: boolean;@@ -122,6 +126,9 @@ const CellComponent = (focusCell,moveCell,moveToNextCell,+ updateCellConfig,+ sendToBottom,+ sendToTop,userConfig,config: cellConfig,name,@@ -259,6 +266,43 @@ const CellComponent = (});const HTMLId = HTMLCellId.create(cellId);++ // Register hotkeys on the cell instead of the code editor+ // This is in case the code editor is hidden+ useHotkeysOnElement(editing ? cellRef.current : null, {+ "cell.run": handleRun,+ "cell.runAndNewBelow": () => {+ handleRun();+ moveToNextCell({ cellId, before: false });+ },+ "cell.runAndNewAbove": () => {+ handleRun();+ moveToNextCell({ cellId, before: true });+ },+ "cell.createAbove": createAbove,+ "cell.createBelow": createBelow,+ "cell.moveUp": () => moveCell({ cellId, before: true }),+ "cell.moveDown": () => moveCell({ cellId, before: false }),+ "cell.hideCode": () => {+ const newConfig: CellConfig = { hide_code: !cellConfig.hide_code };+ // Fire-and-forget+ void saveCellConfig({ configs: { [cellId]: newConfig } });+ updateCellConfig({ cellId, config: newConfig });+ if (newConfig.hide_code) {+ // Move focus from the editor to the cell+ editorView.current?.contentDOM.blur();+ cellRef.current?.focus();+ } else {+ // Focus the editor+ editorView.current?.focus();+ }+ },+ "cell.focusDown": () => moveToNextCell({ cellId, before: false }),+ "cell.focusUp": () => moveToNextCell({ cellId, before: true }),+ "cell.sendToBottom": () => sendToBottom({ cellId }),+ "cell.sendToTop": () => sendToTop({ cellId }),+ });+if (!editing) {const hidden = errored || interrupted || stopped;return hidden ? null : (@@ -305,21 +349,18 @@ const CellComponent = (>{outputArea}<div className="tray">- <div className="shoulder-left hover-action">- <div className="shoulder-elem-top">- <CreateCellButton- tooltipContent={renderShortcut("cell.createAbove")}- appClosed={appClosed}- onClick={appClosed ? undefined : createAbove}- />- </div>- <div className="shoulder-elem-bottom">- <CreateCellButton- tooltipContent={renderShortcut("cell.createBelow")}- appClosed={appClosed}- onClick={appClosed ? undefined : createBelow}- />- </div>+ <div className="absolute flex flex-col gap-[2px] justify-center h-full left-[-34px] z-2 hover-action">+ <CreateCellButton+ tooltipContent={renderShortcut("cell.createAbove")}+ appClosed={appClosed}+ onClick={appClosed ? undefined : createAbove}+ />+ <div className="flex-1" />+ <CreateCellButton+ tooltipContent={renderShortcut("cell.createBelow")}+ appClosed={appClosed}+ onClick={appClosed ? undefined : createBelow}+ /></div><CellEditortheme={theme}@@ -337,8 +378,10 @@ const CellComponent = (focusCell={focusCell}moveCell={moveCell}moveToNextCell={moveToNextCell}+ updateCellConfig={updateCellConfig}userConfig={userConfig}editorViewRef={editorView}+ hidden={cellConfig.hide_code}/><div className="shoulder-right"><CellStatusComponentdiff --git a/frontend/src/components/editor/actions/useCellActionButton.tsx b/frontend/src/components/editor/actions/useCellActionButton.tsxindex 659ebce7a5..e652e38e3d 100644--- a/frontend/src/components/editor/actions/useCellActionButton.tsx+++ b/frontend/src/components/editor/actions/useCellActionButton.tsx@@ -16,10 +16,12 @@ import {ZapOffIcon,PlayIcon,TextCursorInputIcon,+ EyeIcon,+ EyeOffIcon,} from "lucide-react";import { ActionButton } from "./types";import { MultiIcon } from "@/components/icons/multi-icon";-import { CellData, CellStatus } from "@/core/cells/types";+import { CellConfig, CellData, CellStatus } from "@/core/cells/types";import { CellId } from "@/core/cells/ids";import { saveCellConfig } from "@/core/network/requests";import { EditorView } from "@codemirror/view";@@ -55,12 +57,24 @@ export function useCellActionButtons({const runCell = useRunCell(cellId);const toggleDisabled = async () => {- if (config.disabled) {- await saveCellConfig({ configs: { [cellId]: { disabled: false } } });- updateCellConfig({ cellId, config: { disabled: false } });- } else {- await saveCellConfig({ configs: { [cellId]: { disabled: true } } });- updateCellConfig({ cellId, config: { disabled: true } });+ const newConfig = { disabled: !config.disabled };+ await saveCellConfig({ configs: { [cellId]: newConfig } });+ updateCellConfig({ cellId, config: newConfig });+ };++ const toggleHideCode = async () => {+ const newConfig: CellConfig = { hide_code: !config.hide_code };+ await saveCellConfig({ configs: { [cellId]: newConfig } });+ updateCellConfig({ cellId, config: newConfig });++ // If we're hiding the code, we should blur the editor+ // otherwise, we should focus it+ if (editorView) {+ if (newConfig.hide_code) {+ editorView.contentDOM.blur();+ } else {+ editorView.focus();+ }}};@@ -111,6 +125,16 @@ export function useCellActionButtons({formatEditorViews({ [cellId]: editorView }, updateCellCode);},},+ {+ icon: config.hide_code ? (+ <EyeIcon size={13} strokeWidth={1.5} />+ ) : (+ <EyeOffIcon size={13} strokeWidth={1.5} />+ ),+ label: config.hide_code === true ? "Show code" : "Hide code",+ handle: toggleHideCode,+ hotkey: "cell.hideCode",+ },{icon: config.disabled ? (<ZapIcon size={13} strokeWidth={1.5} />diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsxindex ade4f9865c..0405bfa538 100644--- a/frontend/src/components/editor/cell/code/cell-editor.tsx+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx@@ -15,7 +15,7 @@ import { setupCodeMirror } from "@/core/codemirror/cm";import { AppMode } from "@/core/mode";import useEvent from "react-use-event-hook";import { CellActions, useCellActions } from "@/core/cells/cells";-import { CellRuntimeState, CellData } from "@/core/cells/types";+import { CellRuntimeState, CellData, CellConfig } from "@/core/cells/types";import { SerializedEditorState } from "@/core/codemirror/types";import { UserConfig } from "@/core/config/config-schema";import { Theme } from "@/theme/useTheme";@@ -26,6 +26,9 @@ import {} from "@/core/codemirror/language/extension";import { derefNotNull } from "@/utils/dereference";import { LanguageToggle } from "./language-toggle";+import { cn } from "@/utils/cn";+import { EyeOpenIcon } from "@radix-ui/react-icons";+import { saveCellConfig } from "@/core/network/requests";export interface CellEditorPropsextends Pick<CellRuntimeState, "status">,@@ -38,6 +41,7 @@ export interface CellEditorProps| "focusCell"| "moveCell"| "moveToNextCell"+ | "updateCellConfig"> {runCell: () => void;theme: Theme;@@ -51,6 +55,7 @@ export interface CellEditorProps*/allowFocus: boolean;userConfig: UserConfig;+ hidden?: boolean;}const CellEditorInternal = ({@@ -69,8 +74,10 @@ const CellEditorInternal = ({focusCell,moveCell,moveToNextCell,+ updateCellConfig,userConfig,editorViewRef,+ hidden,}: CellEditorProps) => {const [canUseMarkdown, setCanUseMarkdown] = useState(false);@@ -116,6 +123,13 @@ const CellEditorInternal = ({() => focusCell({ cellId, before: true }),[cellId, focusCell]);+ const toggleHideCode = useEvent(() => {+ const newConfig: CellConfig = { hide_code: !hidden };+ // Fire-and-forget save+ void saveCellConfig({ configs: { [cellId]: newConfig } });+ updateCellConfig({ cellId, config: newConfig });+ return newConfig.hide_code || false;+ });useEffect(() => {if (reading) {@@ -140,6 +154,7 @@ const CellEditorInternal = ({sendToTop,sendToBottom,moveToNextCell,+ toggleHideCode,},completionConfig: userConfig.completion,keymapConfig: userConfig.keymap,@@ -256,6 +271,15 @@ const CellEditorInternal = ({}}, [editing, editorViewRef]);+ const showCode = async () => {+ if (hidden) {+ await saveCellConfig({ configs: { [cellId]: { hide_code: false } } });+ updateCellConfig({ cellId, config: { hide_code: false } });+ // Focus on the editor view+ editorViewRef.current?.focus();+ }+ };+return (<>{canUseMarkdown && (@@ -266,7 +290,15 @@ const CellEditorInternal = ({/></div>)}- <div className="cm" ref={editorViewParentRef} />+ {hidden && (+ <div className="absolute inset-0 z-10" onClick={showCode}>+ <EyeOpenIcon className="hover-action w-5 h-5 text-muted-foreground cursor-pointer absolute left-1/2 top-1/2 transform -translate-x-1/2 -translate-y-1/2 opacity-80 hover:opacity-100" />+ </div>+ )}+ <div+ className={cn("cm", hidden && "opacity-20 h-8 overflow-hidden")}+ ref={editorViewParentRef}+ /></>);};diff --git a/frontend/src/components/editor/renderers/CellArray.tsx b/frontend/src/components/editor/renderers/CellArray.tsxindex c05ae008dd..d1f148a0fe 100644--- a/frontend/src/components/editor/renderers/CellArray.tsx+++ b/frontend/src/components/editor/renderers/CellArray.tsx@@ -20,6 +20,7 @@ import { useTheme } from "../../../theme/useTheme";import { VerticalLayoutWrapper } from "./vertical-layout/vertical-layout-wrapper";import { useDelayVisibility } from "./vertical-layout/useDelayVisiblity";import { useChromeActions } from "../chrome/state";+import { Functions } from "@/utils/functions";interface CellArrayProps {notebook: NotebookState;@@ -42,6 +43,7 @@ export const CellArray: React.FC<CellArrayProps> = ({deleteCell,moveCell,moveToNextCell,+ updateCellConfig,focusCell,createNewCell,focusBottomCell,@@ -49,6 +51,8 @@ export const CellArray: React.FC<CellArrayProps> = ({scrollToTarget,foldAll,unfoldAll,+ sendToBottom,+ sendToTop,} = useCellActions();const { theme } = useTheme();const { togglePanel } = useChromeActions();@@ -64,6 +68,9 @@ export const CellArray: React.FC<CellArrayProps> = ({useHotkey("global.formatAll", () => {formatAll(updateCellCode);});+ // Catch all to avoid native OS behavior+ // Otherwise a user might try to hide a cell and accidentally hide the OS window+ useHotkey("cell.hideCode", Functions.NOOP);const onDeleteCell: typeof deleteCell = useEvent((payload) => {sendDeleteCell(payload.cellId);@@ -101,15 +108,18 @@ export const CellArray: React.FC<CellArrayProps> = ({runStartTimestamp={cell.runStartTimestamp}runElapsedTimeMs={cell.runElapsedTimeMs}serializedEditorState={cell.serializedEditorState}- showDeleteButton={cells.length > 1}+ showDeleteButton={cells.length > 1 && !cell.config.hide_code}createNewCell={createNewCell}deleteCell={onDeleteCell}focusCell={focusCell}moveToNextCell={moveToNextCell}+ updateCellConfig={updateCellConfig}moveCell={moveCell}mode={mode}appClosed={connStatus.state !== WebSocketState.OPEN}ref={notebook.cellHandles[cell.id]}+ sendToBottom={sendToBottom}+ sendToTop={sendToTop}userConfig={userConfig}config={cell.config}name={cell.name}diff --git a/frontend/src/core/App.tsx b/frontend/src/core/App.tsxindex 9e08bfc8f6..bfaffa33dc 100644--- a/frontend/src/core/App.tsx+++ b/frontend/src/core/App.tsx@@ -42,7 +42,7 @@ import { Button } from "../components/ui/button";import { useEvent } from "../hooks/useEvent";import { Logger } from "../utils/Logger";import { useAutoSave } from "./saving/useAutoSave";-import { useWindowEventListener } from "../hooks/useEventListener";+import { useEventListener } from "../hooks/useEventListener";import { toast } from "../components/ui/use-toast";import { SortableCellsProvider } from "../components/sort/SortableCellsProvider";import { CellId, HTMLCellId } from "./cells/ids";@@ -200,7 +200,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {config: userConfig,});- useWindowEventListener("beforeunload", (e: BeforeUnloadEvent) => {+ useEventListener(window, "beforeunload", (e: BeforeUnloadEvent) => {if (isStaticNotebook()) {return;}diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.tsindex 54b12ee2a6..2b4126990a 100644--- a/frontend/src/core/cells/cells.ts+++ b/frontend/src/core/cells/cells.ts@@ -193,7 +193,11 @@ const { reducer, createActions } = createReducer(initialNotebookState, {const focusCellId = state.cellIds[focusIndex];// can scroll immediately, without setting scrollKey in state, because// CellArray won't need to re-render- focusAndScrollCellIntoView(focusCellId, state.cellHandles[focusCellId]);+ focusAndScrollCellIntoView(+ focusCellId,+ state.cellHandles[focusCellId],+ state.cellData[focusCellId].config+ );return state;},focusTopCell: (state) => {@@ -458,7 +462,11 @@ const { reducer, createActions } = createReducer(initialNotebookState, {} else {const nextCellId = state.cellIds[nextCellIndex];// Just focus, no state change- focusAndScrollCellIntoView(nextCellId, state.cellHandles[nextCellId]);+ focusAndScrollCellIntoView(+ nextCellId,+ state.cellHandles[nextCellId],+ state.cellData[nextCellId].config+ );return state;}},@@ -478,7 +486,11 @@ const { reducer, createActions } = createReducer(initialNotebookState, {scrollToBottom();} else {const nextCellId = state.cellIds[index];- focusAndScrollCellIntoView(nextCellId, state.cellHandles[nextCellId]);+ focusAndScrollCellIntoView(+ nextCellId,+ state.cellHandles[nextCellId],+ state.cellData[nextCellId].config+ );}return {diff --git a/frontend/src/core/cells/scrollCellIntoView.ts b/frontend/src/core/cells/scrollCellIntoView.tsindex 7db7e92a15..6294256766 100644--- a/frontend/src/core/cells/scrollCellIntoView.ts+++ b/frontend/src/core/cells/scrollCellIntoView.ts@@ -3,25 +3,34 @@ import { RefObject } from "react";import { Logger } from "../../utils/Logger";import { CellId, HTMLCellId } from "./ids";import { CellHandle } from "@/components/editor/Cell";+import { CellConfig } from "./types";export function focusAndScrollCellIntoView(cellId: CellId,- cell: RefObject<CellHandle>+ cell: RefObject<CellHandle>,+ config: CellConfig) {if (!cell) {return;}- cell.current?.editorView.focus();const element = document.getElementById(HTMLCellId.create(cellId));- if (element) {- element.scrollIntoView({- behavior: "smooth",- block: "center",- });- } else {+ if (!element) {Logger.warn("scrollCellIntoView: element not found");+ return;+ }++ // If the cell's code is hidden, just focus the cell and not the editor.+ if (config.hide_code) {+ element.focus();+ } else {+ cell.current?.editorView.focus();}++ element.scrollIntoView({+ behavior: "smooth",+ block: "center",+ });}/**diff --git a/frontend/src/core/cells/types.ts b/frontend/src/core/cells/types.tsindex 1c47cb7677..f6b1df5ab0 100644--- a/frontend/src/core/cells/types.ts+++ b/frontend/src/core/cells/types.ts@@ -106,4 +106,8 @@ export interface CellConfig {* If true, the cell and its descendants are unable to run.*/disabled?: boolean;+ /**+ * If true, the cell's code is hidden from the notebook.+ */+ hide_code?: boolean;}diff --git a/frontend/src/core/codemirror/__tests__/setup.test.ts b/frontend/src/core/codemirror/__tests__/setup.test.tsindex ec0d2f31c5..e98af981a7 100644--- a/frontend/src/core/codemirror/__tests__/setup.test.ts+++ b/frontend/src/core/codemirror/__tests__/setup.test.ts@@ -33,6 +33,7 @@ function setup(config: Partial<CodeMirrorSetupOpts> = {}): Extension[] {sendToTop: namedFunction("sendToTop"),sendToBottom: namedFunction("sendToBottom"),moveToNextCell: namedFunction("moveToNextCell"),+ toggleHideCode: namedFunction("toggleHideCode"),},cellCodeCallbacks: {updateCellCode: namedFunction("updateCellCode"),diff --git a/frontend/src/core/codemirror/cells/extensions.ts b/frontend/src/core/codemirror/cells/extensions.tsindex 0d8d1dbad0..203af168e7 100644--- a/frontend/src/core/codemirror/cells/extensions.ts+++ b/frontend/src/core/codemirror/cells/extensions.ts@@ -1,12 +1,14 @@/* Copyright 2023 Marimo. All rights reserved. */import { HOTKEYS } from "@/core/hotkeys/hotkeys";import { EditorView, KeyBinding, keymap } from "@codemirror/view";-import { CellId } from "@/core/cells/ids";+import { CellId, HTMLCellId } from "@/core/cells/ids";import { Extension, Prec } from "@codemirror/state";import { formatKeymapExtension } from "../extensions";import { CellActions } from "@/core/cells/cells";import { getEditorCodeAsPython } from "../language/utils";import { formattingChangeEffect } from "../format";+import { clearTooltips } from "../completion/hints";+import { closeCompletion } from "@codemirror/autocomplete";export interface MovementCallbacksextends Pick<CellActions, "sendToTop" | "sendToBottom" | "moveToNextCell"> {@@ -18,6 +20,7 @@ export interface MovementCallbacksmoveDown: () => void;focusUp: () => void;focusDown: () => void;+ toggleHideCode: () => boolean;}/**@@ -39,12 +42,14 @@ export function cellMovementBundle(sendToTop,sendToBottom,moveToNextCell,+ toggleHideCode,} = callbacks;const hotkeys: KeyBinding[] = [{key: HOTKEYS.getHotkey("cell.run").key,preventDefault: true,+ stopPropagation: true,run: () => {onRun();return true;@@ -53,6 +58,7 @@ export function cellMovementBundle({key: HOTKEYS.getHotkey("cell.runAndNewBelow").key,preventDefault: true,+ stopPropagation: true,run: (ev) => {onRun();ev.contentDOM.blur();@@ -63,6 +69,7 @@ export function cellMovementBundle({key: HOTKEYS.getHotkey("cell.runAndNewAbove").key,preventDefault: true,+ stopPropagation: true,run: (ev) => {onRun();ev.contentDOM.blur();@@ -73,6 +80,7 @@ export function cellMovementBundle({key: HOTKEYS.getHotkey("cell.delete").key,preventDefault: true,+ stopPropagation: true,run: (cm) => {// Cannot delete non-empty cells for safetyif (cm.state.doc.length === 0) {@@ -89,6 +97,7 @@ export function cellMovementBundle({key: HOTKEYS.getHotkey("cell.moveDown").key,preventDefault: true,+ stopPropagation: true,run: () => {moveDown();return true;@@ -97,6 +106,7 @@ export function cellMovementBundle({key: HOTKEYS.getHotkey("cell.moveUp").key,preventDefault: true,+ stopPropagation: true,run: () => {moveUp();return true;@@ -105,6 +115,7 @@ export function cellMovementBundle({key: HOTKEYS.getHotkey("cell.focusDown").key,preventDefault: true,+ stopPropagation: true,run: () => {focusDown();return true;@@ -113,6 +124,7 @@ export function cellMovementBundle({key: HOTKEYS.getHotkey("cell.focusUp").key,preventDefault: true,+ stopPropagation: true,run: () => {focusUp();return true;@@ -121,6 +133,7 @@ export function cellMovementBundle({key: HOTKEYS.getHotkey("cell.sendToBottom").key,preventDefault: true,+ stopPropagation: true,run: () => {sendToBottom({ cellId });return true;@@ -129,6 +142,7 @@ export function cellMovementBundle({key: HOTKEYS.getHotkey("cell.sendToTop").key,preventDefault: true,+ stopPropagation: true,run: () => {sendToTop({ cellId });return true;@@ -137,6 +151,7 @@ export function cellMovementBundle({key: HOTKEYS.getHotkey("cell.createAbove").key,preventDefault: true,+ stopPropagation: true,run: (ev) => {ev.contentDOM.blur();createAbove();@@ -146,12 +161,32 @@ export function cellMovementBundle({key: HOTKEYS.getHotkey("cell.createBelow").key,preventDefault: true,+ stopPropagation: true,run: (ev) => {ev.contentDOM.blur();createBelow();return true;},},+ {+ key: HOTKEYS.getHotkey("cell.hideCode").key,+ preventDefault: true,+ stopPropagation: true,+ run: (ev) => {+ const isHidden = toggleHideCode();+ closeCompletion(ev);+ clearTooltips(ev);+ // If we are newly hidden, blur the editor+ if (isHidden) {+ ev.contentDOM.blur();+ // Focus on the parent element+ document.getElementById(HTMLCellId.create(cellId))?.focus();+ } else {+ ev.contentDOM.focus();+ }+ return true;+ },+ },];// Highest priority so that we can override the default keymapdiff --git a/frontend/src/core/hotkeys/__tests__/shortcuts.test.ts b/frontend/src/core/hotkeys/__tests__/shortcuts.test.tsnew file mode 100644index 0000000000..41d7fcf68c--- /dev/null+++ b/frontend/src/core/hotkeys/__tests__/shortcuts.test.ts@@ -0,0 +1,85 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { expect, describe, it } from "vitest";+import { parseShortcut } from "../shortcuts";++describe("parseShortcut", () => {+ it("should recognize single key shortcuts", () => {+ const shortcut = parseShortcut("a");+ const event = new KeyboardEvent("keydown", { key: "a" });+ expect(shortcut(event)).toBe(true);+ });++ it("should recognize combined Ctrl key shortcuts", () => {+ const shortcut = parseShortcut("Ctrl-a");+ const event = new KeyboardEvent("keydown", { key: "a", ctrlKey: true });+ expect(shortcut(event)).toBe(true);+ });++ it("should recognize combined Shift key shortcuts", () => {+ const shortcut = parseShortcut("Shift-a");+ const event = new KeyboardEvent("keydown", { key: "a", shiftKey: true });+ expect(shortcut(event)).toBe(true);+ });++ it("should recognize combined Cmd key shortcuts", () => {+ const shortcut = parseShortcut("Cmd-a");+ const event = new KeyboardEvent("keydown", { key: "a", metaKey: true });+ expect(shortcut(event)).toBe(true);+ });++ it("should recognize Space key shortcuts", () => {+ const shortcut = parseShortcut("Space");+ const event = new KeyboardEvent("keydown", { code: "Space" });+ expect(shortcut(event)).toBe(true);+ });++ it("should not recognize incorrect single key shortcuts", () => {+ const shortcut = parseShortcut("a");+ const event = new KeyboardEvent("keydown", { key: "b" });+ expect(shortcut(event)).toBe(false);+ });++ it("should not recognize incorrect combined key shortcuts", () => {+ const shortcut = parseShortcut("Ctrl-a");+ const event = new KeyboardEvent("keydown", { key: "a" }); // Missing ctrlKey+ expect(shortcut(event)).toBe(false);+ });++ it("should not recognize shortcuts with additional keys pressed", () => {+ const shortcut = parseShortcut("a");+ const event = new KeyboardEvent("keydown", { key: "a", shiftKey: true });+ expect(shortcut(event)).toBe(false);+ });++ it("should not recognize shortcuts when Shift is not part of the shortcut but is pressed", () => {+ const shortcut = parseShortcut("Ctrl-a");+ const event = new KeyboardEvent("keydown", {+ key: "a",+ ctrlKey: true,+ shiftKey: true,+ });+ expect(shortcut(event)).toBe(false);+ });++ it("should not recognize shortcuts when Ctrl is not part of the shortcut but is pressed", () => {+ const event = new KeyboardEvent("keydown", {+ key: "Enter",+ shiftKey: true,+ ctrlKey: true,+ });++ expect(parseShortcut("Shift-Enter")(event)).toBe(false);+ expect(parseShortcut("Ctrl-Shift-Enter")(event)).toBe(true);+ });++ it("should not recognize shortcuts when Cmd is not part of the shortcut but is pressed", () => {+ const event = new KeyboardEvent("keydown", {+ key: "Enter",+ shiftKey: true,+ metaKey: true,+ });++ expect(parseShortcut("Shift-Enter")(event)).toBe(false);+ expect(parseShortcut("Cmd-Shift-Enter")(event)).toBe(true);+ });+});diff --git a/frontend/src/core/hotkeys/hotkeys.ts b/frontend/src/core/hotkeys/hotkeys.tsindex 3524b31086..99a3bd4c8d 100644--- a/frontend/src/core/hotkeys/hotkeys.ts+++ b/frontend/src/core/hotkeys/hotkeys.ts@@ -163,6 +163,11 @@ const DEFAULT_HOT_KEY = {group: "Editing",key: "Shift-Backspace",},+ "cell.hideCode": {+ name: "Hide cell code",+ group: "Editing",+ key: "Mod-h",+ },// Global Actions"global.hideCode": {diff --git a/frontend/src/core/hotkeys/shortcuts.ts b/frontend/src/core/hotkeys/shortcuts.tsindex bf908b9862..e77c9c16b9 100644--- a/frontend/src/core/hotkeys/shortcuts.ts+++ b/frontend/src/core/hotkeys/shortcuts.ts@@ -42,6 +42,7 @@ export function parseShortcut(shortcut: string): (e: KeyboardEvent) => boolean {satisfied &&= e.key.toLowerCase() === character.toLowerCase();break;}+if (!satisfied) {return false;}@@ -49,6 +50,12 @@ export function parseShortcut(shortcut: string): (e: KeyboardEvent) => boolean {if (!keys.includes("Shift")) {satisfied &&= !e.shiftKey;}+ if (!keys.includes("Ctrl")) {+ satisfied &&= !e.ctrlKey;+ }+ if (!keys.includes("Cmd")) {+ satisfied &&= !e.metaKey;+ }return satisfied;};}diff --git a/frontend/src/css/Cell.css b/frontend/src/css/Cell.cssindex dc90f55445..d213fa428d 100644--- a/frontend/src/css/Cell.css+++ b/frontend/src/css/Cell.css@@ -182,25 +182,6 @@}/* -------------------------- Shoulders/Buttons ---------------------------- */- .shoulder-left {- position: absolute;- left: -34px;- display: flex;- flex-direction: column;- gap: 4px;- justify-content: center;- height: 100%;- z-index: 2;- }-- .shoulder-elem-top {- margin-bottom: auto;- }-- .shoulder-elem-bottom {- vertical-align: bottom;- }-.shoulder-right {display: inline-flex;flex-direction: column;diff --git a/frontend/src/hooks/useEventListener.ts b/frontend/src/hooks/useEventListener.tsindex 3d4a70d951..0149b584fd 100644--- a/frontend/src/hooks/useEventListener.ts+++ b/frontend/src/hooks/useEventListener.ts@@ -1,9 +1,19 @@/* Copyright 2023 Marimo. All rights reserved. */import { useRef, useEffect } from "react";-export function useEventListener<K extends keyof DocumentEventMap>(- type: K,- listener: (ev: DocumentEventMap[K]) => unknown,+type Target = Document | HTMLElement | Window | null;+type EventMap<T extends Target> = T extends Document+ ? DocumentEventMap+ : T extends HTMLElement+ ? HTMLElementEventMap+ : T extends Window+ ? WindowEventMap+ : never;++export function useEventListener<T extends Target, K extends keyof EventMap<T>>(+ target: T,+ type: K & string,+ listener: (ev: EventMap<T>[K]) => unknown,options?: boolean | AddEventListenerOptions): void {const savedListener = useRef(listener);@@ -13,34 +23,16 @@ export function useEventListener<K extends keyof DocumentEventMap>(}, [listener]);useEffect(() => {- const eventListener = (event: DocumentEventMap[K]) =>- savedListener.current(event);- document.addEventListener(type, eventListener, options);+ if (!target) {+ return;+ }- return () => {- document.removeEventListener(type, eventListener, options);- };- }, [type, options]);-}--export function useWindowEventListener<K extends keyof WindowEventMap>(- type: K,- listener: (ev: WindowEventMap[K]) => unknown,- options?: boolean | AddEventListenerOptions-): void {- const savedListener = useRef(listener);-- useEffect(() => {- savedListener.current = listener;- }, [listener]);-- useEffect(() => {- const eventListener = (event: WindowEventMap[K]) =>- savedListener.current(event);- window.addEventListener(type, eventListener, options);+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const eventListener = (event: any) => savedListener.current(event);+ target.addEventListener(type, eventListener, options);return () => {- window.removeEventListener(type, eventListener, options);+ target.removeEventListener(type, eventListener, options);};- }, [type, options]);+ }, [type, target, options]);}diff --git a/frontend/src/hooks/useHotkey.ts b/frontend/src/hooks/useHotkey.tsindex ec9c2f493c..6938f58a07 100644--- a/frontend/src/hooks/useHotkey.ts+++ b/frontend/src/hooks/useHotkey.ts@@ -6,6 +6,9 @@ import { useEventListener } from "./useEventListener";import { useEvent } from "./useEvent";import { useSetRegisteredAction } from "../core/hotkeys/actions";import { HOTKEYS, HotkeyAction } from "@/core/hotkeys/hotkeys";+import { Objects } from "@/utils/objects";++type HotkeyHandler = () => boolean | void | undefined | Promise<void>;/*** Registers a hotkey listener for the given shortcut.@@ -28,12 +31,13 @@ export function useHotkey(// Prevent default if the callback does not return falseif (response !== false) {e.preventDefault();+ e.stopPropagation();}}});// Register keydown listener- useEventListener("keydown", listener);+ useEventListener(document, "keydown", listener);// Register with the shortcut registryuseEffect(() => {@@ -42,3 +46,26 @@ export function useHotkey(// eslint-disable-next-line react-hooks/exhaustive-deps}, [memoizeCallback, shortcut]);}++/**+ * Registers a hotkey listener on a given element.+ */+export function useHotkeysOnElement<T extends HotkeyAction>(+ element: HTMLElement | null,+ handlers: Record<T, HotkeyHandler>+) {+ useEventListener(element, "keydown", (e) => {+ for (const [shortcut, callback] of Objects.entries(handlers)) {+ const key = HOTKEYS.getHotkey(shortcut).key;+ if (parseShortcut(key)(e)) {+ console.log("Satisfied", key, e);+ const response = callback();+ // Prevent default if the callback does not return false+ if (response !== false) {+ e.preventDefault();+ e.stopPropagation();+ }+ }+ }+ });+}diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsxindex 076d444d56..ad3e90ddbe 100644--- a/frontend/src/stories/cell.stories.tsx+++ b/frontend/src/stories/cell.stories.tsx@@ -41,6 +41,9 @@ const props: CellProps = {focusCell: Logger.log,moveCell: Logger.log,moveToNextCell: Logger.log,+ sendToBottom: Logger.log,+ sendToTop: Logger.log,+ updateCellConfig: Logger.log,config: {},userConfig: {completion: {diff --git a/marimo/_ast/app.py b/marimo/_ast/app.pyindex cd469e7800..4e1e7f6f39 100644--- a/marimo/_ast/app.py+++ b/marimo/_ast/app.py@@ -103,6 +103,7 @@ class App:func: Optional[CellFuncTypeBound] = None,*,disabled: bool = False,+ hide_code: bool = False,**kwargs: Any,) -> Union[Callable[[CellFuncType], CellFunction[CellFuncTypeBound]],@@ -134,6 +135,8 @@ class App:"""del kwargs+ cell_config = CellConfig(disabled=disabled, hide_code=hide_code)+if func is None:# If the decorator was used with parentheses, func will be None,# and we return a decorator that takes the decorated function as an@@ -142,7 +145,7 @@ class App:func: CellFuncTypeBound,) -> CellFunction[CellFuncTypeBound]:cell_function = cell_factory(func)- cell_function.cell.configure(CellConfig(disabled=disabled))+ cell_function.cell.configure(cell_config)self._register_cell(cell_function)return cell_function@@ -154,7 +157,7 @@ class App:# If the decorator was used without parentheses, func will be the# decorated functioncell_function = cell_factory(func)- cell_function.cell.configure(CellConfig(disabled=disabled))+ cell_function.cell.configure(cell_config)self._register_cell(cell_function)return cell_functiondiff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.pyindex 9055bd40dc..b46a966b4c 100644--- a/marimo/_ast/cell.py+++ b/marimo/_ast/cell.py@@ -40,6 +40,9 @@ class CellConfig:# but they can still be added to the graph.disabled: bool = False+ # If True, the cell is hidden from the editor.+ hide_code: bool = False+@classmethoddef from_dict(cls, kwargs: dict[str, Any]) -> CellConfig:return cls(**{k: v for k, v in kwargs.items() if k in CellConfigKeys})diff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.pyindex 600304d390..c04b06a22d 100644--- a/marimo/_ast/codegen.py+++ b/marimo/_ast/codegen.py@@ -30,7 +30,17 @@ def _multiline_tuple(elems: Sequence[str]) -> str:def _to_decorator(config: Optional[CellConfig]) -> str:- if config is None or config == CellConfig():+ if config is None:+ return "@app.cell"++ # Removed defaults. If the cell's config is the default config,+ # don't include it in the decorator.+ if not config.disabled:+ del config.disabled+ if not config.hide_code:+ del config.hide_code++ if config == CellConfig():return "@app.cell"else:return (diff --git a/marimo/_smoke_tests/third_party/seaborn.py b/marimo/_smoke_tests/third_party/seaborn.pyindex 20d0f681a4..545b9d1aa4 100644--- a/marimo/_smoke_tests/third_party/seaborn.py+++ b/marimo/_smoke_tests/third_party/seaborn.py@@ -1,11 +1,10 @@-# Copyright 2023 Marimo. All rights reserved.import marimo-__generated_with = "0.1.0"+__generated_with = "0.1.69"app = marimo.App()[email protected](hide_code=True)def __():import seaborn as snsdiff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.pyindex f1c938452b..d6896ed912 100644--- a/tests/_ast/test_app.py+++ b/tests/_ast/test_app.py@@ -275,3 +275,21 @@ class TestApp:def test_app_config_extra_args_ignored() -> None:app = App(width="full", fake_config="foo")assert app._config.asdict() == {"width": "full", "layout_file": None}++ @staticmethod+ def test_cell_config() -> None:+ app = App()++ @app.cell(disabled=True)+ def _() -> tuple[int]:+ __x__ = 0+ return (__x__,)++ @app.cell(hide_code=True)+ def _(__x__: int) -> None:+ assert __x__ == 0+ return++ configs = tuple(app._configs())+ assert configs[0].disabled+ assert configs[1].hide_codediff --git a/tests/_ast/test_codegen.py b/tests/_ast/test_codegen.pyindex b8c6aaf79c..d0a6223be7 100644--- a/tests/_ast/test_codegen.py+++ b/tests/_ast/test_codegen.py@@ -336,6 +336,36 @@ class TestToFunctionDef:)assert fndef == expected+ def test_with_all_config(self) -> None:+ code = "x = 0"+ cell = parse_cell(code)+ cell = cell.configure(CellConfig(disabled=True, hide_code=True))+ fndef = codegen.to_functiondef(cell, "foo")+ expected = "\n".join(+ [+ "@app.cell(disabled=True, hide_code=True)",+ "def foo():",+ " x = 0",+ " return x,",+ ]+ )+ assert fndef == expected++ def test_should_remove_defaults(self) -> None:+ code = "x = 0"+ cell = parse_cell(code)+ cell = cell.configure(CellConfig(disabled=False, hide_code=False))+ fndef = codegen.to_functiondef(cell, "foo")+ expected = "\n".join(+ [+ "@app.cell",+ "def foo():",+ " x = 0",+ " return x,",+ ]+ )+ assert fndef == expected+def test_recover() -> None:cells = {