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.

improvement: add Presentation toggling to menu dropdown, allow forcing slides by URL query param (#2010)

Myles Scolnickcbc7729f8e6a
diff --git a/frontend/src/components/editor/actions/useNotebookActions.tsx b/frontend/src/components/editor/actions/useNotebookActions.tsx
index 99f73f7ed2..cb370c6e6f 100644
--- a/frontend/src/components/editor/actions/useNotebookActions.tsx
+++ b/frontend/src/components/editor/actions/useNotebookActions.tsx
@@ -1,7 +1,11 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { kioskModeAtom, runDuringPresentMode } from "@/core/mode";
+import {
+ kioskModeAtom,
+ runDuringPresentMode,
+ viewStateAtom,
+} from "@/core/mode";
import { downloadBlob, downloadHTMLAsImage } from "@/utils/download";
-import { useAtomValue, useSetAtom } from "jotai";
+import { useAtom, useAtomValue, useSetAtom } from "jotai";
import {
ImageIcon,
CommandIcon,
@@ -22,6 +26,9 @@ import {
Undo2Icon,
FileIcon,
Home,
+ PresentationIcon,
+ EditIcon,
+ LayoutTemplateIcon,
} from "lucide-react";
import { commandPaletteAtom } from "../controls/command-palette";
import { useCellActions, useNotebook } from "@/core/cells/cells";
@@ -50,6 +57,10 @@ import { startCase } from "lodash-es";
import { keyboardShortcutsAtom } from "../controls/keyboard-shortcuts";
import { MarkdownIcon } from "@/components/editor/cell/code/icons";
import { Filenames } from "@/utils/filenames";
+import { LAYOUT_TYPES } from "../renderers/types";
+import { displayLayoutName, getLayoutIcon } from "../renderers/layout-select";
+import { useLayoutState, useLayoutActions } from "@/core/layout/layout";
+import { useTogglePresenting } from "@/core/layout/useTogglePresenting";
const NOOP_HANDLER = (event?: Event) => {
event?.preventDefault();
@@ -61,6 +72,7 @@ export function useNotebookActions() {
const { openModal, closeModal } = useImperativeModal();
const { openApplication } = useChromeActions();
const { selectedPanel } = useChromeState();
+ const [viewState] = useAtom(viewStateAtom);
const kioskMode = useAtomValue(kioskModeAtom);
const notebook = useNotebook();
@@ -71,6 +83,9 @@ export function useNotebookActions() {
const disabledCells = disabledCellIds(notebook);
const enabledCells = enabledCellIds(notebook);
+ const { selectedLayout } = useLayoutState();
+ const { setLayoutView } = useLayoutActions();
+ const togglePresenting = useTogglePresenting();
const actions: ActionButton[] = [
{
@@ -218,6 +233,47 @@ export function useNotebookActions() {
}),
},
+ {
+ icon: <PresentationIcon size={14} strokeWidth={1.5} />,
+ label: "Present as",
+ handle: NOOP_HANDLER,
+ dropdown: [
+ {
+ icon:
+ viewState.mode === "present" ? (
+ <EditIcon size={14} strokeWidth={1.5} />
+ ) : (
+ <LayoutTemplateIcon size={14} strokeWidth={1.5} />
+ ),
+ label: "Toggle app view",
+ hotkey: "global.hideCode",
+ handle: () => {
+ togglePresenting();
+ },
+ },
+ ...LAYOUT_TYPES.map((type, idx) => {
+ const Icon = getLayoutIcon(type);
+ return {
+ divider: idx === 0,
+ label: displayLayoutName(type),
+ icon: <Icon size={14} strokeWidth={1.5} />,
+ rightElement: (
+ <div className="w-8 flex justify-end">
+ {selectedLayout === type && <CheckIcon size={14} />}
+ </div>
+ ),
+ handle: () => {
+ setLayoutView(type);
+ // Toggle if it's not in present mode
+ if (viewState.mode === "edit") {
+ togglePresenting();
+ }
+ },
+ };
+ }),
+ ],
+ },
+
{
icon: <ClipboardCopyIcon size={14} strokeWidth={1.5} />,
label: "Copy code to clipboard",
@@ -244,9 +300,9 @@ export function useNotebookActions() {
// send to BE
await saveCellConfig({ configs: newConfigs });
// update on FE
- ids.forEach((cellId) =>
- updateCellConfig({ cellId, config: { disabled: false } }),
- );
+ for (const cellId of ids) {
+ updateCellConfig({ cellId, config: { disabled: false } });
+ }
},
},
{
@@ -261,9 +317,9 @@ export function useNotebookActions() {
// send to BE
await saveCellConfig({ configs: newConfigs });
// update on FE
- ids.forEach((cellId) =>
- updateCellConfig({ cellId, config: { disabled: true } }),
- );
+ for (const cellId of ids) {
+ updateCellConfig({ cellId, config: { disabled: true } });
+ }
},
},
{
diff --git a/frontend/src/components/editor/controls/notebook-menu-dropdown.tsx b/frontend/src/components/editor/controls/notebook-menu-dropdown.tsx
index 598d295781..0fec99b2f4 100644
--- a/frontend/src/components/editor/controls/notebook-menu-dropdown.tsx
+++ b/frontend/src/components/editor/controls/notebook-menu-dropdown.tsx
@@ -13,9 +13,9 @@ import {
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
-import { renderMinimalShortcut } from "../../shortcuts/renderShortcut";
+import { MinimalShortcut } from "../../shortcuts/renderShortcut";
import { useNotebookActions } from "../actions/useNotebookActions";
-import { ActionButton } from "../actions/types";
+import type { ActionButton } from "../actions/types";
import { getMarimoVersion } from "@/core/dom/marimo-tag";
export const NotebookMenuDropdown: React.FC = () => {
@@ -39,7 +39,9 @@ export const NotebookMenuDropdown: React.FC = () => {
<>
{action.icon && <span className="flex-0 mr-2">{action.icon}</span>}
<span className="flex-1">{action.label}</span>
- {action.hotkey && renderMinimalShortcut(action.hotkey)}
+ {action.hotkey && (
+ <MinimalShortcut shortcut={action.hotkey} className="ml-4" />
+ )}
{action.rightElement}
</>
);
@@ -61,7 +63,7 @@ export const NotebookMenuDropdown: React.FC = () => {
return (
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild={true}>{button}</DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="no-print w-[220px]">
+ <DropdownMenuContent align="end" className="no-print w-[240px]">
{actions.map((action) => {
if (action.hidden) {
return null;
@@ -77,7 +79,14 @@ export const NotebookMenuDropdown: React.FC = () => {
</DropdownMenuSubTrigger>
<DropdownMenuPortal>
<DropdownMenuSubContent>
- {action.dropdown.map(renderLeafAction)}
+ {action.dropdown.map((action) => {
+ return (
+ <React.Fragment key={action.label}>
+ {action.divider && <DropdownMenuSeparator />}
+ {renderLeafAction(action)}
+ </React.Fragment>
+ );
+ })}
</DropdownMenuSubContent>
</DropdownMenuPortal>
</DropdownMenuSub>
diff --git a/frontend/src/components/editor/renderers/cells-renderer.tsx b/frontend/src/components/editor/renderers/cells-renderer.tsx
index 9657325708..72ebe28ae0 100644
--- a/frontend/src/components/editor/renderers/cells-renderer.tsx
+++ b/frontend/src/components/editor/renderers/cells-renderer.tsx
@@ -1,11 +1,14 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { flattenTopLevelNotebookCells, useNotebook } from "@/core/cells/cells";
-import React, { PropsWithChildren, memo } from "react";
+import type React from "react";
+import { type PropsWithChildren, memo } from "react";
import { cellRendererPlugins } from "./plugins";
-import { AppConfig } from "@/core/config/config-schema";
-import { AppMode, kioskModeAtom } from "@/core/mode";
+import type { AppConfig } from "@/core/config/config-schema";
+import { type AppMode, kioskModeAtom } from "@/core/mode";
import { useLayoutActions, useLayoutState } from "@/core/layout/layout";
import { useAtomValue } from "jotai";
+import { KnownQueryParams } from "@/core/constants";
+import { type LayoutType, OVERRIDABLE_LAYOUT_TYPES } from "./types";
interface Props {
appConfig: AppConfig;
@@ -24,7 +27,19 @@ export const CellsRenderer: React.FC<PropsWithChildren<Props>> = memo(
return children;
}
- const plugin = cellRendererPlugins.find((p) => p.type === selectedLayout);
+ // We allow overriding the layout type by url params when in 'read' mode,
+ // for example, forcing the 'slides' view.
+ // https://marimo.app/?slug=14ovyr8&mode=run&view-as=slides
+ let finalLayout = selectedLayout;
+ const params = new URLSearchParams(window.location.search);
+ if (mode === "read" && params.has(KnownQueryParams.viewAs)) {
+ const viewAsOverride = params.get(KnownQueryParams.viewAs);
+ if (OVERRIDABLE_LAYOUT_TYPES.includes(viewAsOverride as LayoutType)) {
+ finalLayout = viewAsOverride as LayoutType;
+ }
+ }
+
+ const plugin = cellRendererPlugins.find((p) => p.type === finalLayout);
// Just render children if there is no plugin
if (!plugin) {
@@ -39,7 +54,7 @@ export const CellsRenderer: React.FC<PropsWithChildren<Props>> = memo(
appConfig={appConfig}
mode={mode}
cells={cells}
- layout={layoutData[selectedLayout] || plugin.getInitialLayout(cells)}
+ layout={layoutData[finalLayout] || plugin.getInitialLayout(cells)}
setLayout={setCurrentLayoutData}
/>
);
diff --git a/frontend/src/components/editor/renderers/layout-select.tsx b/frontend/src/components/editor/renderers/layout-select.tsx
index 8e94cc4ca0..ba7f7b2b52 100644
--- a/frontend/src/components/editor/renderers/layout-select.tsx
+++ b/frontend/src/components/editor/renderers/layout-select.tsx
@@ -9,7 +9,7 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
-import type { LayoutType } from "./types";
+import { LAYOUT_TYPES, type LayoutType } from "./types";
import {
SquareIcon,
Grid3x3Icon,
@@ -20,11 +20,11 @@ import { isWasm } from "@/core/wasm/utils";
import { useLayoutActions, useLayoutState } from "@/core/layout/layout";
import { logNever } from "@/utils/assertNever";
import { getFeatureFlag } from "@/core/config/feature-flag";
+import { startCase } from "lodash-es";
export const LayoutSelect: React.FC = () => {
const { selectedLayout } = useLayoutState();
const { setLayoutView } = useLayoutActions();
- const layouts: LayoutType[] = ["vertical", "grid", "slides"];
// Layouts are not supported in WASM mode by default,
// unless the feature flag is enabled
@@ -47,11 +47,11 @@ export const LayoutSelect: React.FC = () => {
<SelectContent>
<SelectGroup>
<SelectLabel>View as</SelectLabel>
- {layouts.map((layout) => (
+ {LAYOUT_TYPES.map((layout) => (
<SelectItem key={layout} value={layout}>
<div className="flex items-center gap-1.5 leading-5">
{renderIcon(layout)}
- <span>{displayName(layout)}</span>
+ <span>{displayLayoutName(layout)}</span>
</div>
</SelectItem>
))}
@@ -62,29 +62,24 @@ export const LayoutSelect: React.FC = () => {
};
function renderIcon(layoutType: LayoutType) {
- switch (layoutType) {
- case "vertical":
- return <ListIcon className="h-4 w-4" />;
- case "grid":
- return <Grid3x3Icon className="h-4 w-4" />;
- case "slides":
- return <PresentationIcon className="h-4 w-4" />;
- default:
- logNever(layoutType);
- return <SquareIcon className="h-4 w-4" />;
- }
+ const Icon = getLayoutIcon(layoutType);
+ return <Icon className="h-4 w-4" />;
}
-function displayName(layoutType: LayoutType) {
+export function getLayoutIcon(layoutType: LayoutType) {
switch (layoutType) {
case "vertical":
- return "Vertical";
+ return ListIcon;
case "grid":
- return "Grid";
+ return Grid3x3Icon;
case "slides":
- return "Slides";
+ return PresentationIcon;
default:
logNever(layoutType);
- return "Unknown";
+ return SquareIcon;
}
}
+
+export function displayLayoutName(layoutType: LayoutType) {
+ return startCase(layoutType);
+}
diff --git a/frontend/src/components/editor/renderers/types.ts b/frontend/src/components/editor/renderers/types.ts
index cbe39e686b..ead06771cb 100644
--- a/frontend/src/components/editor/renderers/types.ts
+++ b/frontend/src/components/editor/renderers/types.ts
@@ -1,8 +1,8 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { AppConfig } from "@/core/config/config-schema";
-import { CellData, CellRuntimeState } from "@/core/cells/types";
-import { ZodType, ZodTypeDef } from "zod";
-import { AppMode } from "@/core/mode";
+import type { AppConfig } from "@/core/config/config-schema";
+import type { CellData, CellRuntimeState } from "@/core/cells/types";
+import type { ZodType, ZodTypeDef } from "zod";
+import type { AppMode } from "@/core/mode";
/**
* The props passed to a cell renderer.
@@ -36,7 +36,16 @@ export interface ICellRendererProps<L> {
setLayout: (layout: L) => void;
}
-export type LayoutType = "grid" | "vertical" | "slides";
+export type LayoutType = "vertical" | "grid" | "slides";
+/**
+ * List of supported layout types, in the order to be displayed.
+ */
+export const LAYOUT_TYPES: LayoutType[] = ["vertical", "grid", "slides"];
+/**
+ * Overridable layout types.
+ * These types can override the current layout via a URL parameter.
+ */
+export const OVERRIDABLE_LAYOUT_TYPES: LayoutType[] = ["slides"];
/**
* A cell renderer plugin.
diff --git a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx
index 4dfd9b1855..4d9eceeb3a 100644
--- a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx
+++ b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx
@@ -35,6 +35,7 @@ import { isWasm } from "@/core/wasm/utils";
import type { CellConfig } from "@/core/network/types";
import { useAtomValue } from "jotai";
import { FloatingOutline } from "../../chrome/panels/outline/floating-outline";
+import { KnownQueryParams } from "@/core/constants";
type VerticalLayout = null;
type VerticalLayoutProps = ICellRendererProps<VerticalLayout>;
@@ -48,7 +49,7 @@ const VerticalLayoutRenderer: React.FC<VerticalLayoutProps> = ({
const kioskMode = useAtomValue(kioskModeAtom);
const urlParams = new URLSearchParams(window.location.search);
- const showCodeDefault = urlParams.get("show-code");
+ const showCodeDefault = urlParams.get(KnownQueryParams.showCode);
const [showCode, setShowCode] = useState(() => {
// Default to showing code if the notebook is static or wasm
return showCodeDefault === null
@@ -68,7 +69,7 @@ const VerticalLayoutRenderer: React.FC<VerticalLayoutProps> = ({
// If it is a static-notebook or wasm-read-only-notebook, code is always included,
// but it can be turned it off via a query parameter (include-code=false)
- const includeCode = urlParams.get("include-code");
+ const includeCode = urlParams.get(KnownQueryParams.includeCode);
return mode === "read" && includeCode !== "false" && cellsHaveCode;
};
diff --git a/frontend/src/components/shortcuts/renderShortcut.tsx b/frontend/src/components/shortcuts/renderShortcut.tsx
index 9f3e283c21..2b7dd26da4 100644
--- a/frontend/src/components/shortcuts/renderShortcut.tsx
+++ b/frontend/src/components/shortcuts/renderShortcut.tsx
@@ -1,5 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { HotkeyAction } from "@/core/hotkeys/hotkeys";
+import type { HotkeyAction } from "@/core/hotkeys/hotkeys";
import { isPlatformMac } from "@/core/hotkeys/shortcuts";
import { Kbd } from "../ui/kbd";
import { DropdownMenuShortcut } from "../ui/dropdown-menu";
@@ -56,15 +56,16 @@ export function renderMinimalShortcut(shortcut: HotkeyAction) {
return <MinimalShortcut shortcut={shortcut} />;
}
-const MinimalShortcut: React.FC<{ shortcut: HotkeyAction }> = ({
- shortcut,
-}) => {
+export const MinimalShortcut: React.FC<{
+ className?: string;
+ shortcut: HotkeyAction;
+}> = ({ className, shortcut }) => {
const hotkeys = useAtomValue(hotkeysAtom);
const hotkey = hotkeys.getHotkey(shortcut);
const keys = hotkey.key.split("-");
return (
- <DropdownMenuShortcut className="flex gap-1 items-center">
+ <DropdownMenuShortcut className={cn("flex gap-1 items-center", className)}>
{keys.map(prettyPrintHotkey).map(([label, symbol]) => {
if (symbol) {
return (
diff --git a/frontend/src/core/constants.ts b/frontend/src/core/constants.ts
index 2df7d49d4a..eb43d9770e 100644
--- a/frontend/src/core/constants.ts
+++ b/frontend/src/core/constants.ts
@@ -3,3 +3,39 @@ export const Constants = {
githubPage: "https://github.com/marimo-team/marimo",
issuesPage: "https://github.com/marimo-team/marimo/issues",
};
+
+export const KnownQueryParams = {
+ /**
+ * When in read mode, if the code should be shown by default
+ */
+ showCode: "show-code",
+ /**
+ * When in read mode, if the code should be hidden by default
+ */
+ includeCode: "include-code",
+ /**
+ * Session ID for the current notebook
+ */
+ sessionId: "session_id",
+ /**
+ * Kiosk mode. If the editor is running in kiosk mode
+ */
+ kiosk: "kiosk",
+ /**
+ * VSCode mode. If the editor is running inside VSCode
+ */
+ vscode: "vscode",
+ /**
+ * File path of the current notebook
+ */
+ filePath: "file",
+ /**
+ * Access token for the current user
+ */
+ accessToken: "access_token",
+ /**
+ * Layout view-as. If the editor is in run-mode, this overrides the current
+ * layout view.
+ */
+ viewAs: "view-as",
+};
diff --git a/frontend/src/core/edit-app.tsx b/frontend/src/core/edit-app.tsx
index 49a2eeafd5..bdc037e11a 100644
--- a/frontend/src/core/edit-app.tsx
+++ b/frontend/src/core/edit-app.tsx
@@ -1,5 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { useCallback, useEffect, useState } from "react";
+import { useEffect, useState } from "react";
import {
sendComponentValues,
@@ -28,7 +28,7 @@ import {
notebookNeedsSave,
} from "./cells/utils";
import type { AppConfig, UserConfig } from "./config/config-schema";
-import { kioskModeAtom, toggleAppMode, viewStateAtom } from "./mode";
+import { kioskModeAtom, viewStateAtom } from "./mode";
import { useHotkey } from "../hooks/useHotkey";
import { useImperativeModal } from "../components/modal/ImperativeModal";
import {
@@ -44,12 +44,11 @@ import { useAutoSave } from "./saving/useAutoSave";
import { useEventListener } from "../hooks/useEventListener";
import { toast } from "../components/ui/use-toast";
import { SortableCellsProvider } from "../components/sort/SortableCellsProvider";
-import { type CellId, HTMLCellId } from "./cells/ids";
import { CellArray } from "../components/editor/renderers/CellArray";
import { RuntimeState } from "./kernel/RuntimeState";
import { CellsRenderer } from "../components/editor/renderers/cells-renderer";
import { getSerializedLayout, useLayoutState } from "./layout/layout";
-import { useAtom, useAtomValue } from "jotai";
+import { useAtomValue } from "jotai";
import { useRunStaleCells } from "../components/editor/cell/useRunCells";
import { formatAll } from "./codemirror/format";
import { cn } from "@/utils/cn";
@@ -61,6 +60,8 @@ import { AppHeader } from "@/components/editor/header/app-header";
import { AppContainer } from "../components/editor/app-container";
import { useJotaiEffect } from "./state/jotai";
import { Paths } from "@/utils/paths";
+import { KnownQueryParams } from "./constants";
+import { useTogglePresenting } from "./layout/useTogglePresenting";
interface AppProps {
userConfig: UserConfig;
@@ -73,7 +74,7 @@ export const EditApp: React.FC<AppProps> = ({ userConfig, appConfig }) => {
useJotaiEffect(cellIdsAtom, CellEffects.onCellIdsChange);
const { setCells, updateCellCode } = useCellActions();
- const [viewState, setViewState] = useAtom(viewStateAtom);
+ const viewState = useAtomValue(viewStateAtom);
const [filename, setFilename] = useFilename();
const [lastSavedNotebook, setLastSavedNotebook] =
useState<LastSavedNotebook>();
@@ -117,9 +118,9 @@ export const EditApp: React.FC<AppProps> = ({ userConfig, appConfig }) => {
updateQueryParams((params) => {
if (name === null) {
- params.delete("file");
+ params.delete(KnownQueryParams.filePath);
} else {
- params.set("file", name);
+ params.set(KnownQueryParams.filePath, name);
}
});
@@ -246,40 +247,7 @@ export const EditApp: React.FC<AppProps> = ({ userConfig, appConfig }) => {
};
const runStaleCells = useRunStaleCells();
-
- // Toggle the array's presenting state, and sets a cell to anchor scrolling to
- const togglePresenting = useCallback(() => {
- const outputAreas = document.getElementsByClassName("output-area");
- const viewportEnd =
- window.innerHeight || document.documentElement.clientHeight;
- let cellAnchor: CellId | null = null;
-
- // Find the first output area that is visible
- // eslint-disable-next-line unicorn/prefer-spread
- for (const elem of Array.from(outputAreas)) {
- const rect = elem.getBoundingClientRect();
- if (
- (rect.top >= 0 && rect.top <= viewportEnd) ||
- (rect.bottom >= 0 && rect.bottom <= viewportEnd)
- ) {
- cellAnchor = HTMLCellId.parse(
- (elem.parentNode as HTMLElement).id as HTMLCellId,
- );
- break;
- }
- }
-
- setViewState((prev) => ({
- mode: toggleAppMode(prev.mode),
- cellAnchor: cellAnchor,
- }));
- requestAnimationFrame(() => {
- if (cellAnchor === null) {
- return;
- }
- document.getElementById(HTMLCellId.create(cellAnchor))?.scrollIntoView();
- });
- }, [setViewState]);
+ const togglePresenting = useTogglePresenting();
// HOTKEYS
useHotkey("global.runStale", () => {
diff --git a/frontend/src/core/kernel/session.ts b/frontend/src/core/kernel/session.ts
index d9c1338ef4..3807401340 100644
--- a/frontend/src/core/kernel/session.ts
+++ b/frontend/src/core/kernel/session.ts
@@ -1,8 +1,9 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { init } from "@paralleldrive/cuid2";
-import { TypedString } from "@/utils/typed";
+import type { TypedString } from "@/utils/typed";
import { updateQueryParams } from "@/utils/urls";
import { Logger } from "@/utils/Logger";
+import { KnownQueryParams } from "../constants";
export type SessionId = TypedString<"SessionId">;
@@ -21,16 +22,18 @@ export function isSessionId(value: string | null): value is SessionId {
const sessionId = (() => {
const url = new URL(window.location.href);
- const id = url.searchParams.get("session_id") as SessionId | null;
+ const id = url.searchParams.get(
+ KnownQueryParams.sessionId,
+ ) as SessionId | null;
if (isSessionId(id)) {
// Remove the session_id from the URL
updateQueryParams((params) => {
// Keep the session_id if we are in kiosk mode
// this is so we can resume the same session if the user refreshes the page
- if (params.has("kiosk")) {
+ if (params.has(KnownQueryParams.kiosk)) {
return;
}
- params.delete("session_id");
+ params.delete(KnownQueryParams.sessionId);
});
Logger.debug("Connecting to existing session", { sessionId: id });
return id;
diff --git a/frontend/src/core/layout/useTogglePresenting.ts b/frontend/src/core/layout/useTogglePresenting.ts
new file mode 100644
index 0000000000..bcc4f452b0
--- /dev/null
+++ b/frontend/src/core/layout/useTogglePresenting.ts
@@ -0,0 +1,49 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { useCallback } from "react";
+import { type CellId, HTMLCellId } from "../cells/ids";
+import { toggleAppMode, viewStateAtom } from "../mode";
+import { useSetAtom } from "jotai";
+
+/**
+ * Toggle the notebook's presentation state and scroll to current visible cell
+ */
+export function useTogglePresenting() {
+ const setViewState = useSetAtom(viewStateAtom);
+
+ // Toggle the array's presenting state, and sets a cell to scroll to
+ const togglePresenting = useCallback(() => {
+ const outputAreas = document.getElementsByClassName("output-area");
+ const viewportEnd =
+ window.innerHeight || document.documentElement.clientHeight;
+ let cellAnchor: CellId | null = null;
+
+ // Find the first output area that is visible
+ // eslint-disable-next-line unicorn/prefer-spread
+ for (const elem of Array.from(outputAreas)) {
+ const rect = elem.getBoundingClientRect();
+ if (
+ (rect.top >= 0 && rect.top <= viewportEnd) ||
+ (rect.bottom >= 0 && rect.bottom <= viewportEnd)
+ ) {
+ cellAnchor = HTMLCellId.parse(
+ (elem.parentNode as HTMLElement).id as HTMLCellId,
+ );
+ break;
+ }
+ }
+
+ setViewState((prev) => ({
+ mode: toggleAppMode(prev.mode),
+ cellAnchor: cellAnchor,
+ }));
+
+ requestAnimationFrame(() => {
+ if (cellAnchor === null) {
+ return;
+ }
+ document.getElementById(HTMLCellId.create(cellAnchor))?.scrollIntoView();
+ });
+ }, [setViewState]);
+
+ return togglePresenting;
+}
diff --git a/frontend/src/core/network/auth.ts b/frontend/src/core/network/auth.ts
index 0d496f76bf..45acb9c71c 100644
--- a/frontend/src/core/network/auth.ts
+++ b/frontend/src/core/network/auth.ts
@@ -1,12 +1,13 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { updateQueryParams } from "@/utils/urls";
+import { KnownQueryParams } from "../constants";
/**
* Remove access_token from the query string.
*/
export function cleanupAuthQueryParams() {
updateQueryParams((params) => {
- params.delete("access_token");
+ params.delete(KnownQueryParams.accessToken);
});
}
diff --git a/frontend/src/core/vscode/vscode-bindings.ts b/frontend/src/core/vscode/vscode-bindings.ts
index 64b4d90064..f26f02751a 100644
--- a/frontend/src/core/vscode/vscode-bindings.ts
+++ b/frontend/src/core/vscode/vscode-bindings.ts
@@ -3,6 +3,7 @@
import { Logger } from "@/utils/Logger";
import { isWasm } from "../wasm/utils";
import { isPlatformMac } from "../hotkeys/shortcuts";
+import { KnownQueryParams } from "../constants";
export const isEmbedded =
// eslint-disable-next-line ssr-friendly/no-dom-globals-in-module-scope
@@ -12,7 +13,9 @@ export const isEmbedded =
// we have to dispatch keyboard events in the parent window.
// See https://github.com/microsoft/vscode/issues/65452#issuecomment-586036474
export function maybeRegisterVSCodeBindings() {
- const isVscode = new URLSearchParams(window.location.search).has("vscode");
+ const isVscode = new URLSearchParams(window.location.search).has(
+ KnownQueryParams.vscode,
+ );
if (!isVscode) {
return;
}
diff --git a/frontend/src/core/websocket/__tests__/createWsUrl.test.ts b/frontend/src/core/websocket/__tests__/createWsUrl.test.ts
index 4be794f420..fbd93dde6f 100644
--- a/frontend/src/core/websocket/__tests__/createWsUrl.test.ts
+++ b/frontend/src/core/websocket/__tests__/createWsUrl.test.ts
@@ -2,6 +2,7 @@
import { describe, expect, it } from "vitest";
import { createWsUrl } from "../createWsUrl";
+import { KnownQueryParams } from "@/core/constants";
describe("createWsUrl", () => {
it("should return a URL with the wss protocol when the baseURI uses https", () => {
@@ -15,7 +16,7 @@ describe("createWsUrl", () => {
const result = createWsUrl(sessionId);
expect(result).toBe("wss://marimo.app/ws?session_id=1234");
const url = new URL(result);
- expect(url.searchParams.get("session_id")).toBe(sessionId);
+ expect(url.searchParams.get(KnownQueryParams.sessionId)).toBe(sessionId);
});
it("should return a URL with the ws protocol when the baseURI uses http", () => {
@@ -29,7 +30,7 @@ describe("createWsUrl", () => {
const result = createWsUrl(sessionId);
expect(result).toBe("ws://marimo.app/ws?session_id=1234");
const url = new URL(result);
- expect(url.searchParams.get("session_id")).toBe(sessionId);
+ expect(url.searchParams.get(KnownQueryParams.sessionId)).toBe(sessionId);
});
it("should work with nested baseURI", () => {
@@ -43,6 +44,6 @@ describe("createWsUrl", () => {
const result = createWsUrl(sessionId);
expect(result).toBe("ws://marimo.app/nested/ws?session_id=1234");
const url = new URL(result);
- expect(url.searchParams.get("session_id")).toBe(sessionId);
+ expect(url.searchParams.get(KnownQueryParams.sessionId)).toBe(sessionId);
});
});
diff --git a/frontend/src/core/websocket/createWsUrl.ts b/frontend/src/core/websocket/createWsUrl.ts
index 9ca0de6611..73c62ba96d 100644
--- a/frontend/src/core/websocket/createWsUrl.ts
+++ b/frontend/src/core/websocket/createWsUrl.ts
@@ -1,4 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
+import { KnownQueryParams } from "../constants";
+
export function createWsUrl(sessionId: string): string {
const baseURI = document.baseURI;
@@ -8,7 +10,7 @@ export function createWsUrl(sessionId: string): string {
url.pathname = `${withoutTrailingSlash(url.pathname)}/ws`;
const searchParams = new URLSearchParams(window.location.search);
- searchParams.set("session_id", sessionId);
+ searchParams.set(KnownQueryParams.sessionId, sessionId);
url.search = searchParams.toString();
return url.toString();