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.

feat: add app-chrome and variables to editor (#110)

Myles Scolnickdb77ab87e784
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 861ad87fc8..e6316f9bee 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -288,47 +288,55 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {
/>
);
- return (
- <div
- id="App"
- className={clsx(
- connStatus.state === WebSocketState.CLOSED && "disconnected",
- "bg-background w-full h-full text-textColor",
- "flex flex-col",
- appConfig.width === "full" && "config-width-full"
- )}
- >
+ const statusOverlay = (
+ <>
{connStatus.state === WebSocketState.OPEN && isRunning && <RunningIcon />}
{connStatus.state === WebSocketState.CLOSED && <NoiseBackground />}
{connStatus.state === WebSocketState.CLOSED && <DisconnectedIcon />}
+ </>
+ );
+
+ return (
+ <>
+ {statusOverlay}
<div
+ id="App"
className={clsx(
- (isEditing || isPresenting) && "pt-4 sm:pt-12 pb-2 mb-4",
- (isPresenting || isReading) && "sm:pt-8"
+ connStatus.state === WebSocketState.CLOSED && "disconnected",
+ "bg-background w-full h-full text-textColor",
+ "flex flex-col overflow-y-auto overflow-x-hidden",
+ appConfig.width === "full" && "config-width-full"
)}
>
- {isEditing && (
- <div id="Welcome">
- <FilenameForm
- filename={filename}
- setFilename={handleFilenameChange}
- />
- </div>
- )}
- {connStatus.state === WebSocketState.CLOSED && (
- <Disconnected reason={connStatus.reason} />
+ <div
+ className={clsx(
+ (isEditing || isPresenting) && "pt-4 sm:pt-12 pb-2 mb-4",
+ (isPresenting || isReading) && "sm:pt-8"
+ )}
+ >
+ {isEditing && (
+ <div id="Welcome">
+ <FilenameForm
+ filename={filename}
+ setFilename={handleFilenameChange}
+ />
+ </div>
+ )}
+ {connStatus.state === WebSocketState.CLOSED && (
+ <Disconnected reason={connStatus.reason} />
+ )}
+ </div>
+
+ {/* Don't render until we have a single cell */}
+ {cells.present.length > 0 && (
+ <CellsRenderer appConfig={appConfig} mode={viewState.mode}>
+ <SortableCellsProvider disabled={!isEditing}>
+ {editableCellsArray}
+ </SortableCellsProvider>
+ </CellsRenderer>
)}
</div>
- {/* Don't render until we have a single cell */}
- {cells.present.length > 0 && (
- <CellsRenderer appConfig={appConfig} mode={viewState.mode}>
- <SortableCellsProvider disabled={!isEditing}>
- {editableCellsArray}
- </SortableCellsProvider>
- </CellsRenderer>
- )}
-
{(isEditing || isPresenting) && (
<Controls
filename={filename}
@@ -348,13 +356,15 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {
undoAvailable={cells.history.length > 0}
/>
)}
- </div>
+ </>
);
};
+const topLeftStatus =
+ "absolute top-3 left-4 m-0 flex items-center space-x-3 min-h-[28px] no-print pointer-events-auto z-30";
const DisconnectedIcon = () => (
<Tooltip content="App disconnected">
- <div className="app-status-indicator">
+ <div className={topLeftStatus}>
<UnlinkIcon className="closed-app-icon" />
</div>
</Tooltip>
@@ -362,7 +372,7 @@ const DisconnectedIcon = () => (
const RunningIcon = () => (
<div
- className="app-status-indicator"
+ className={topLeftStatus}
title={"Marimo is busy computing. Hang tight!"}
>
<HourglassIcon className="running-app-icon" size={30} strokeWidth={1} />
diff --git a/frontend/src/MarimoApp.tsx b/frontend/src/MarimoApp.tsx
index 838b42d938..e670f2540d 100644
--- a/frontend/src/MarimoApp.tsx
+++ b/frontend/src/MarimoApp.tsx
@@ -11,6 +11,7 @@ import { DayPickerProvider } from "react-day-picker";
import { CommandPallette } from "./editor/CommandPallette";
import { useAppConfig, useUserConfig } from "@/core/state/config";
import { initialMode } from "./core/mode";
+import { AppChrome } from "./editor/chrome/wrapper/app-chrome";
/**
* The root component of the Marimo app.
@@ -23,15 +24,25 @@ export const MarimoApp: React.FC = () => {
initializePlugins();
}, []);
+ const body =
+ initialMode === "read" ? (
+ <>
+ <App userConfig={userConfig} appConfig={appConfig} />
+ <Toaster />
+ </>
+ ) : (
+ <AppChrome>
+ <App userConfig={userConfig} appConfig={appConfig} />
+ <Toaster />
+ <CommandPallette />
+ </AppChrome>
+ );
+
return (
<ErrorBoundary>
<TooltipProvider>
<DayPickerProvider initialProps={{}}>
- <ModalProvider>
- <App userConfig={userConfig} appConfig={appConfig} />
- <Toaster />
- {initialMode !== "read" && <CommandPallette />}
- </ModalProvider>
+ <ModalProvider>{body}</ModalProvider>
</DayPickerProvider>
</TooltipProvider>
</ErrorBoundary>
diff --git a/frontend/src/components/ui/badge.tsx b/frontend/src/components/ui/badge.tsx
index 1f7b1e4aae..026e666610 100644
--- a/frontend/src/components/ui/badge.tsx
+++ b/frontend/src/components/ui/badge.tsx
@@ -5,7 +5,7 @@ import { VariantProps, cva } from "class-variance-authority";
import { cn } from "@/lib/utils";
const badgeVariants = cva(
- "inline-flex items-center border rounded-full px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
+ "inline-flex items-center border rounded-full px-2 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
@@ -14,7 +14,9 @@ const badgeVariants = cva(
secondary:
"bg-secondary hover:bg-secondary/80 border-transparent text-secondary-foreground",
destructive:
- "bg-destructive hover:bg-destructive/80 border-transparent text-destructive-foreground",
+ "bg-[var(--red-2)] border-[var(--red-6)] text-[var(--red-9)] hover:bg-[var(--red-3)]",
+ success:
+ "bg-[var(--grass-2)] border-[var(--grass-5)] text-[var(--grass-9)] hover:bg-[var(--grass-3)]",
outline: "text-foreground",
},
},
diff --git a/frontend/src/components/ui/table.tsx b/frontend/src/components/ui/table.tsx
index dc3f96bfcb..9618f51ae8 100644
--- a/frontend/src/components/ui/table.tsx
+++ b/frontend/src/components/ui/table.tsx
@@ -7,7 +7,7 @@ const Table = React.forwardRef<
HTMLTableElement,
React.HTMLAttributes<HTMLTableElement>
>(({ className, ...props }, ref) => (
- <div className="w-full overflow-auto">
+ <div className="w-full overflow-auto flex-1">
<table
ref={ref}
className={cn("w-full caption-bottom text-sm", className)}
@@ -85,7 +85,7 @@ const TableCell = React.forwardRef<
>(({ className, ...props }, ref) => (
<td
ref={ref}
- className={cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)}
+ className={cn("p-3 align-middle [&:has([role=checkbox])]:pr-0", className)}
{...props}
/>
));
diff --git a/frontend/src/components/variables/variables-table.tsx b/frontend/src/components/variables/variables-table.tsx
new file mode 100644
index 0000000000..4e7bae7e53
--- /dev/null
+++ b/frontend/src/components/variables/variables-table.tsx
@@ -0,0 +1,153 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import React, { memo } from "react";
+import {
+ TableHeader,
+ TableRow,
+ TableHead,
+ TableBody,
+ TableCell,
+ Table,
+} from "../ui/table";
+import { Variables } from "@/core/variables/types";
+import { CellId } from "@/core/model/ids";
+import { CellLink } from "@/editor/links/cell-link";
+import { cn } from "@/lib/utils";
+import { SquareEqualIcon, WorkflowIcon } from "lucide-react";
+import { Badge } from "../ui/badge";
+import { toast } from "../ui/use-toast";
+
+interface Props {
+ className?: string;
+ /**
+ * Used to sort the variables.
+ */
+ cellIds: CellId[];
+ variables: Variables;
+}
+
+export const VariableTable: React.FC<Props> = memo(
+ ({ className, cellIds, variables }) => {
+ const cellIdToIndex = new Map<CellId, number>();
+ cellIds.forEach((id, index) => cellIdToIndex.set(id, index));
+
+ const sortedVariables = Object.values(variables).sort((a, b) => {
+ const aIndex = cellIdToIndex.get(a.declaredBy[0]);
+ const bIndex = cellIdToIndex.get(b.declaredBy[0]);
+ if (aIndex === undefined || bIndex === undefined) {
+ return 0;
+ }
+ return aIndex - bIndex;
+ });
+
+ return (
+ <Table className={cn("w-full overflow-hidden text-sm flex-1", className)}>
+ <TableHeader>
+ <TableRow className="whitespace-nowrap text-xs">
+ <TableHead>Name</TableHead>
+ <TableHead>
+ <div className="flex flex-col gap-1">
+ <span>Type</span>
+ <span>Value</span>
+ </div>
+ </TableHead>
+ <TableHead>
+ <div className="flex flex-col gap-1">
+ <span>Declared By</span>
+ <span>Used By</span>
+ </div>
+ </TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {sortedVariables.map((variable) => (
+ <TableRow key={variable.name}>
+ <TableCell
+ className="font-medium max-w-[130px]"
+ title={variable.name}
+ >
+ <div>
+ <Badge
+ variant={
+ variable.declaredBy.length > 1 ? "destructive" : "outline"
+ }
+ className="rounded-sm text-ellipsis block overflow-hidden max-w-fit cursor-pointer"
+ onClick={() => {
+ navigator.clipboard.writeText(variable.name);
+ toast({ title: "Copied to clipboard" });
+ }}
+ >
+ {variable.name}
+ </Badge>
+ </div>
+ </TableCell>
+ <TableCell className="max-w-[150px]">
+ <div className="text-ellipsis overflow-hidden whitespace-nowrap text-muted-foreground font-mono text-xs">
+ {variable.dataType}
+ </div>
+ <div
+ className="text-ellipsis overflow-hidden whitespace-nowrap"
+ title={variable.value}
+ >
+ {variable.value}
+ </div>
+ </TableCell>
+ <TableCell className="py-1">
+ <div className="flex flex-col gap-1">
+ <div className="flex flex-row overflow-auto gap-2 items-center">
+ <span title="Declared by">
+ <SquareEqualIcon className="w-3.5 h-3.5 text-muted-foreground" />
+ </span>
+
+ {variable.declaredBy.length === 1 ? (
+ <CellLink
+ variant="focus"
+ cellId={variable.declaredBy[0]}
+ />
+ ) : (
+ <div className="text-destructive flex flex-row gap-2">
+ {variable.declaredBy.slice(0, 3).map((cellId, idx) => (
+ <span className="flex" key={cellId}>
+ <CellLink
+ variant="focus"
+ key={cellId}
+ cellId={cellId}
+ className="whitespace-nowrap text-destructive"
+ />
+ {idx < variable.declaredBy.length - 1 && ", "}
+ </span>
+ ))}
+ </div>
+ )}
+ </div>
+ <div className="flex flex-row overflow-auto gap-2 items-baseline">
+ <span title="Used by">
+ <WorkflowIcon className="w-3.5 h-3.5 text-muted-foreground" />
+ </span>
+
+ {variable.usedBy.slice(0, 3).map((cellId, idx) => (
+ <span className="flex" key={cellId}>
+ <CellLink
+ variant="focus"
+ key={cellId}
+ cellId={cellId}
+ className="whitespace-nowrap"
+ />
+ {idx < variable.usedBy.length - 1 && ", "}
+ </span>
+ ))}
+ {variable.usedBy.length > 3 && (
+ <div className="whitespace-nowrap text-muted-foreground text-xs">
+ +{variable.usedBy.length - 3} more
+ </div>
+ )}
+ </div>
+ </div>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ );
+ }
+);
+VariableTable.displayName = "VariableTable";
diff --git a/frontend/src/core/hotkeys/hotkeys.ts b/frontend/src/core/hotkeys/hotkeys.ts
index c37795c641..3774fe147f 100644
--- a/frontend/src/core/hotkeys/hotkeys.ts
+++ b/frontend/src/core/hotkeys/hotkeys.ts
@@ -228,6 +228,11 @@ const DEFAULT_HOT_KEY = {
group: "Navigation",
key: "Mod-Shift-g",
},
+ "global.toggleSidebar": {
+ name: "Toggle helper panel",
+ group: "Navigation",
+ key: "Mod-Shift-s",
+ },
} satisfies Record<string, Hotkey>;
export type HotkeyAction = keyof typeof DEFAULT_HOT_KEY;
diff --git a/frontend/src/core/kernel/messages.tsx b/frontend/src/core/kernel/messages.tsx
index ed67833e6b..e517316c6c 100644
--- a/frontend/src/core/kernel/messages.tsx
+++ b/frontend/src/core/kernel/messages.tsx
@@ -3,6 +3,7 @@
import { LayoutType } from "@/editor/renderers/types";
import { CellConfig, CellStatus } from "../model/cells";
import { CellId } from "../model/ids";
+import { VariableName } from "../variables/types";
export type OutputChannel =
| "output"
@@ -168,4 +169,24 @@ export type OperationMessage =
| {
op: "cell-op";
data: CellMessage;
+ }
+ | {
+ op: "variables";
+ data: {
+ variables: Array<{
+ name: VariableName;
+ declared_by: CellId[];
+ used_by: CellId[];
+ }>;
+ };
+ }
+ | {
+ op: "variable-values";
+ data: {
+ variables: Array<{
+ name: VariableName;
+ datatype?: string;
+ value?: string;
+ }>;
+ };
};
diff --git a/frontend/src/core/model/ids.ts b/frontend/src/core/model/ids.ts
index 09d468a3d6..8d28adac24 100644
--- a/frontend/src/core/model/ids.ts
+++ b/frontend/src/core/model/ids.ts
@@ -2,9 +2,7 @@
/* eslint-disable @typescript-eslint/no-redeclare */
import { invariant } from "@/utils/invariant";
-
-export type TypedNumber<T> = number & { __type__: T };
-export type TypedString<T> = string & { __type__: T };
+import { TypedString } from "./typed";
/**
* A typed CellId
diff --git a/frontend/src/core/model/typed.ts b/frontend/src/core/model/typed.ts
new file mode 100644
index 0000000000..e9cceede3f
--- /dev/null
+++ b/frontend/src/core/model/typed.ts
@@ -0,0 +1,15 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+
+/**
+ * A typed number.
+ * This is a compile-time type only and does not exist at runtime.
+ * It is used to distinguish between different types of numbers.
+ */
+export type TypedNumber<T> = number & { __type__: T };
+
+/**
+ * A typed string.
+ * This is a compile-time type only and does not exist at runtime.
+ * It is used to distinguish between different types of strings.
+ */
+export type TypedString<T> = string & { __type__: T };
diff --git a/frontend/src/core/state/cells.ts b/frontend/src/core/state/cells.ts
index ed28795345..4efafe96f0 100644
--- a/frontend/src/core/state/cells.ts
+++ b/frontend/src/core/state/cells.ts
@@ -372,12 +372,33 @@ function updateCell(
}
const cellsAtom = atom<CellsAndHistory>(initialCellState());
+const cellIdsAtom = atom((get) =>
+ get(cellsAtom).present.map((cell) => cell.key)
+);
+
+const cellErrorsAtom = atom((get) => {
+ const errors = get(cellsAtom)
+ .present.map((cell) =>
+ cell.output?.mimetype === "application/vnd.marimo+error"
+ ? {
+ output: cell.output,
+ cellId: cell.key,
+ }
+ : null
+ )
+ .filter(Boolean);
+ return errors;
+});
/**
* Get the array of cells.
*/
export const useCells = () => useAtomValue(cellsAtom);
+export const useCellIds = () => useAtomValue(cellIdsAtom);
+
+export const useCellErrors = () => useAtomValue(cellErrorsAtom);
+
export const getCells = () => store.get(cellsAtom).present;
/**
diff --git a/frontend/src/core/variables/__tests__/state.test.ts b/frontend/src/core/variables/__tests__/state.test.ts
new file mode 100644
index 0000000000..80eb98d437
--- /dev/null
+++ b/frontend/src/core/variables/__tests__/state.test.ts
@@ -0,0 +1,132 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { beforeEach, describe, expect, it } from "vitest";
+import { CellId } from "@/core/model/ids";
+import { exportedForTesting } from "../state";
+import { VariableName, Variables } from "../types";
+
+const { initialState, reducer, createActions } = exportedForTesting;
+
+const CellIds = {
+ a: "a" as CellId,
+ b: "b" as CellId,
+};
+
+const Names = {
+ x: "x" as VariableName,
+ y: "y" as VariableName,
+};
+
+describe("cell reducer", () => {
+ let state: Variables;
+
+ const actions = createActions((action) => {
+ state = reducer(state, action);
+ });
+
+ beforeEach(() => {
+ state = initialState();
+ });
+
+ it("should set variables", () => {
+ const x = {
+ name: Names.x,
+ declaredBy: [CellIds.a],
+ usedBy: [CellIds.b],
+ };
+ const variables: Variables = {
+ [Names.x]: x,
+ };
+ actions.setVariables([x]);
+ expect(state).toEqual(variables);
+ });
+
+ it("should add variables", () => {
+ const x = {
+ name: Names.x,
+ declaredBy: [CellIds.a],
+ usedBy: [CellIds.b],
+ };
+ const y = {
+ name: Names.y,
+ declaredBy: [CellIds.a],
+ usedBy: [CellIds.b],
+ };
+ actions.addVariables([x, y]);
+ expect(state).toEqual({
+ [Names.x]: x,
+ [Names.y]: y,
+ });
+ });
+
+ it("should set metadata", () => {
+ const x = {
+ name: Names.x,
+ declaredBy: [CellIds.a],
+ usedBy: [CellIds.b],
+ };
+ const variables: Variables = {
+ [Names.x]: x,
+ };
+ actions.setVariables([x]);
+ expect(state).toEqual(variables);
+
+ // add metadata
+ actions.setMetadata([
+ {
+ name: Names.x,
+ value: "1",
+ dataType: "number",
+ },
+ ]);
+ expect(state).toEqual({
+ [Names.x]: {
+ name: Names.x,
+ declaredBy: [CellIds.a],
+ usedBy: [CellIds.b],
+ value: "1",
+ dataType: "number",
+ },
+ });
+
+ // drop unknown metadata
+ actions.setMetadata([
+ {
+ name: Names.x,
+ value: "2",
+ dataType: "number",
+ },
+ {
+ name: Names.y,
+ value: "3",
+ dataType: "number",
+ },
+ ]);
+ expect(state).toEqual({
+ [Names.x]: {
+ name: Names.x,
+ declaredBy: [CellIds.a],
+ usedBy: [CellIds.b],
+ value: "2",
+ dataType: "number",
+ },
+ });
+
+ // can re-add variables
+ actions.addVariables([
+ {
+ name: Names.x,
+ declaredBy: [CellIds.a],
+ usedBy: [],
+ },
+ ]);
+ expect(state).toEqual({
+ [Names.x]: {
+ name: Names.x,
+ declaredBy: [CellIds.a],
+ usedBy: [],
+ value: "2",
+ dataType: "number",
+ },
+ });
+ });
+});
diff --git a/frontend/src/core/variables/state.ts b/frontend/src/core/variables/state.ts
new file mode 100644
index 0000000000..144681fa6f
--- /dev/null
+++ b/frontend/src/core/variables/state.ts
@@ -0,0 +1,79 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+
+import { createReducer } from "@/utils/createReducer";
+import { Variable, VariableName, Variables } from "./types";
+import { atom, useAtomValue, useSetAtom } from "jotai";
+import { useMemo } from "react";
+
+function initialState(): Variables {
+ return {};
+}
+
+const { reducer, createActions } = createReducer(initialState, {
+ setVariables: (state, variables: Variable[]) => {
+ // start with empty state, but keep the old state's metadata
+ const oldVariables = { ...state };
+ const newVariables: Variables = {};
+ for (const variable of variables) {
+ newVariables[variable.name] = {
+ ...oldVariables[variable.name],
+ ...variable,
+ };
+ }
+ return newVariables;
+ },
+ addVariables: (state, variables: Variable[]) => {
+ const newVariables = { ...state };
+ for (const variable of variables) {
+ newVariables[variable.name] = {
+ ...newVariables[variable.name],
+ ...variable,
+ };
+ }
+ return newVariables;
+ },
+ setMetadata: (
+ state,
+ metadata: Array<{ name: VariableName; value?: string; dataType?: string }>
+ ) => {
+ const newVariables = { ...state };
+ for (const { name, value, dataType } of metadata) {
+ if (!newVariables[name]) {
+ continue;
+ }
+
+ newVariables[name] = {
+ ...newVariables[name],
+ value,
+ dataType: dataType,
+ };
+ }
+ return newVariables;
+ },
+});
+
+const variablesAtom = atom(initialState());
+
+/**
+ * React hook to get the variables state.
+ */
+export const useVariables = () => useAtomValue(variablesAtom);
+
+/**
+ * React hook to get the variables actions.
+ */
+export function useVariablesActions() {
+ const setState = useSetAtom(variablesAtom);
+ return useMemo(() => {
+ const actions = createActions((action) => {
+ setState((state) => reducer(state, action));
+ });
+ return actions;
+ }, [setState]);
+}
+
+export const exportedForTesting = {
+ reducer,
+ createActions,
+ initialState,
+};
diff --git a/frontend/src/core/variables/types.ts b/frontend/src/core/variables/types.ts
new file mode 100644
index 0000000000..8d8dcc70d9
--- /dev/null
+++ b/frontend/src/core/variables/types.ts
@@ -0,0 +1,22 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+
+import { CellId } from "../model/ids";
+import { TypedString } from "../model/typed";
+
+export type VariableName = TypedString<"VariableName">;
+
+export interface Variable {
+ name: VariableName;
+ declaredBy: CellId[];
+ usedBy: CellId[];
+ /**
+ * String representation of the value.
+ */
+ value?: string;
+ /**
+ * Type of the value.
+ */
+ dataType?: string;
+}
+
+export type Variables = Record<VariableName, Variable>;
diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsx
index 5721c3a202..59d334b54d 100644
--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx
+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx
@@ -17,6 +17,7 @@ import { useErrorBoundary } from "react-error-boundary";
import { Logger } from "@/utils/Logger";
import { layoutDataAtom, layoutViewAtom } from "../state/layout";
import { deserializeLayout } from "@/editor/renderers/plugins";
+import { useVariablesActions } from "../variables/state";
/**
* WebSocket that connects to the Marimo kernel and handles incoming messages.
@@ -31,6 +32,7 @@ export function useMarimoWebSocket(opts: {
const { showBoundary } = useErrorBoundary();
const { handleCellMessage } = useCellActions();
+ const { setVariables, setMetadata } = useVariablesActions();
const setLayoutView = useSetAtom(layoutViewAtom);
const setLayoutData = useSetAtom(layoutDataAtom);
const [connStatus, setConnStatus] = useAtom(connectionAtom);
@@ -141,6 +143,24 @@ export function useMarimoWebSocket(opts: {
handleCellMessage({ cellId: body.cell_id, message: body });
return;
}
+ case "variables":
+ setVariables(
+ msg.data.variables.map((v) => ({
+ name: v.name,
+ declaredBy: v.declared_by,
+ usedBy: v.used_by,
+ }))
+ );
+ return;
+ case "variable-values":
+ setMetadata(
+ msg.data.variables.map((v) => ({
+ name: v.name,
+ dataType: v.datatype,
+ value: v.value,
+ }))
+ );
+ return;
default:
logNever(msg);
}
diff --git a/frontend/src/css/App.css b/frontend/src/css/App.css
index 607130be69..dd2c22c10e 100644
--- a/frontend/src/css/App.css
+++ b/frontend/src/css/App.css
@@ -51,7 +51,7 @@ html {
}
.disconnected-gradient {
- position: fixed;
+ position: absolute;
top: 0;
left: 0;
width: 100vw;
@@ -70,7 +70,7 @@ html {
}
.noise {
- position: fixed;
+ position: absolute;
top: 0;
left: 0;
width: 100vw;
diff --git a/frontend/src/css/Cell.css b/frontend/src/css/Cell.css
index 062f90720b..8237512a87 100644
--- a/frontend/src/css/Cell.css
+++ b/frontend/src/css/Cell.css
@@ -77,6 +77,14 @@
background-color: var(--red-2);
}
+.Cell.focus-outline {
+ border-color: var(--blue-8);
+ /* custom shadow until our theme overrides can support colored shadow */
+ --tw-shadow: 0 4px 0px -1px var(--blue-8), 0 2px 4px -2px var(--blue-8) !important;
+
+ @apply shadow-lg;
+}
+
.Cell:focus-visible {
/* focus-visible outlines the entire cell body in black, but the cell's
* body is an irregular shape because of psuedo-elements that extend
diff --git a/frontend/src/css/Header.css b/frontend/src/css/Header.css
index 09b17fb21c..94e30b8e65 100644
--- a/frontend/src/css/Header.css
+++ b/frontend/src/css/Header.css
@@ -52,12 +52,6 @@
color: var(--red-11);
}
-.app-status-indicator {
- position: fixed;
- left: 20px;
- top: 12px;
-}
-
.keyboard-shortcut-group {
margin-bottom: 40px;
}
diff --git a/frontend/src/editor/Controls.styles.ts b/frontend/src/editor/Controls.styles.ts
deleted file mode 100644
index 3a5689bad3..0000000000
--- a/frontend/src/editor/Controls.styles.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-/* Copyright 2023 Marimo. All rights reserved. */
-export const topRightControls =
- "fixed top-3 right-3 m-0 flex items-center space-x-3 min-h-[28px] no-print";
-
-export const bottomRightControls =
- "fixed bottom-4 right-4 flex items-center space-x-3 no-print";
-
-export const bottomLeftControls =
- "fixed bottom-4 left-4 m-0 flex items-center space-x-3 no-print";
diff --git a/frontend/src/editor/Controls.tsx b/frontend/src/editor/Controls.tsx
index 1aea9369f3..baff74c760 100644
--- a/frontend/src/editor/Controls.tsx
+++ b/frontend/src/editor/Controls.tsx
@@ -13,7 +13,6 @@ import { KeyboardShortcuts } from "editor/KeyboardShortcuts";
import { ShutdownButton } from "editor/ShutdownButton";
import { RecoveryButton } from "editor/RecoveryButton";
-import * as styles from "./Controls.styles";
import { Tooltip } from "../components/ui/tooltip";
import { renderShortcut } from "../components/shortcuts/renderShortcut";
import { useCellActions } from "../core/state/cells";
@@ -83,7 +82,7 @@ export const Controls = ({
{!presenting && <FindReplace />}
{!closed && (
- <div className={styles.topRightControls}>
+ <div className={topRightControls}>
{presenting && <LayoutSelect />}
<NotebookMenuDropdown filename={filename} />
<AppConfigButton />
@@ -91,7 +90,7 @@ export const Controls = ({
</div>
)}
- <div className={styles.bottomLeftControls}>
+ <div className={bottomLeftControls}>
{closed ? (
<RecoveryButton
filename={filename}
@@ -129,7 +128,7 @@ export const Controls = ({
<KeyboardShortcuts />
</div>
- <div className={styles.bottomRightControls}>
+ <div className={bottomRightControls}>
{undoControl}
{!closed && (
<RunControlButton
@@ -205,3 +204,12 @@ const RunControlButton = ({
</Tooltip>
);
};
+
+const topRightControls =
+ "absolute top-3 right-5 m-0 flex items-center space-x-3 min-h-[28px] no-print pointer-events-auto z-30";
+
+const bottomRightControls =
+ "absolute bottom-5 right-5 flex items-center space-x-3 no-print pointer-events-auto z-30";
+
+const bottomLeftControls =
+ "absolute bottom-5 left-4 m-0 flex items-center space-x-3 no-print pointer-events-auto z-30";
diff --git a/frontend/src/editor/chrome/state.ts b/frontend/src/editor/chrome/state.ts
index 44386d5ea4..7f91adbf6b 100644
--- a/frontend/src/editor/chrome/state.ts
+++ b/frontend/src/editor/chrome/state.ts
@@ -12,7 +12,7 @@ export interface ChromeState {
function initialState(): ChromeState {
return {
- selectedPanel: undefined,
+ selectedPanel: "variables", // initial panel
isOpen: false,
panelLocation: "left",
};
@@ -28,6 +28,7 @@ const { reducer, createActions } = createReducer(initialState, {
}),
openPanel: (state) => ({ ...state, isOpen: true }),
closePanel: (state) => ({ ...state, isOpen: false }),
+ togglePanel: (state) => ({ ...state, isOpen: !state.isOpen }),
setIsOpen: (state, isOpen: boolean) => ({ ...state, isOpen }),
changePanelLocation: (state, panelLocation: "left" | "bottom") => ({
...state,
diff --git a/frontend/src/editor/chrome/wrapper/__tests__/storage.test.ts b/frontend/src/editor/chrome/wrapper/__tests__/storage.test.ts
index ceb602b16b..52e8efa75d 100644
--- a/frontend/src/editor/chrome/wrapper/__tests__/storage.test.ts
+++ b/frontend/src/editor/chrome/wrapper/__tests__/storage.test.ts
@@ -1,11 +1,10 @@
/* Copyright 2023 Marimo. All rights reserved. */
-import Cookies from "js-cookie";
import { beforeEach, expect, describe, it } from "vitest";
import { createStorage } from "../storage";
describe("createStorage", () => {
beforeEach(() => {
- Cookies.remove("test");
+ createStorage("left").setItem("test", "");
});
it("should store and retrieve items correctly when location is left", () => {
@@ -13,7 +12,6 @@ describe("createStorage", () => {
const value = JSON.stringify({ key: [1, 2] });
storage.setItem("test", value);
- expect(Cookies.get("test")).toEqual(value);
const retrieved = storage.getItem("test");
expect(retrieved).toEqual(value);
@@ -22,10 +20,8 @@ describe("createStorage", () => {
it("should store and retrieve items correctly when location is bottom", () => {
const storage = createStorage("bottom");
const value = JSON.stringify({ key: [1, 2] });
- const reversedValue = JSON.stringify({ key: [2, 1] });
storage.setItem("test", value);
- expect(Cookies.get("test")).toEqual(reversedValue);
const retrieved = storage.getItem("test");
expect(retrieved).toEqual(value);
diff --git a/frontend/src/editor/chrome/wrapper/app-chrome.tsx b/frontend/src/editor/chrome/wrapper/app-chrome.tsx
index d57e866c0f..4985eccfc6 100644
--- a/frontend/src/editor/chrome/wrapper/app-chrome.tsx
+++ b/frontend/src/editor/chrome/wrapper/app-chrome.tsx
@@ -8,15 +8,21 @@ import {
} from "react-resizable-panels";
import { Footer } from "./footer";
import "./app-chrome.css";
-import { ErrorsPanel } from "../panels/error-panel";
import { useChromeActions, useChromeState } from "../state";
import { cn } from "@/lib/utils";
import { createStorage } from "./storage";
+import { VariableTable } from "@/components/variables/variables-table";
+import { useVariables } from "@/core/variables/state";
+import { useCellIds } from "@/core/state/cells";
+import { Button } from "@/components/ui/button";
+import { XIcon } from "lucide-react";
export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
const { isOpen, selectedPanel, panelLocation } = useChromeState();
const { setIsOpen } = useChromeActions();
const sidebarRef = React.useRef<ImperativePanelHandle>(null);
+ const variables = useVariables();
+ const cellIds = useCellIds();
// sync sidebar
useEffect(() => {
@@ -34,11 +40,7 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
}, [isOpen]);
const appBody = (
- <Panel
- id="app"
- key={`app-${panelLocation}`}
- style={{ height: "100%", overflow: "auto" }}
- >
+ <Panel id="app" key={`app-${panelLocation}`} className="relative h-full">
{children}
</Panel>
);
@@ -62,11 +64,40 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
collapsible={true}
className="bg-[var(--sage-1)]"
minSize={10}
- defaultSize={20}
- maxSize={30}
+ // We can't make the default size greater than 0, otherwise it will start open
+ defaultSize={0}
+ maxSize={45}
+ onResize={(size, prevSize) => {
+ // This means it started closed and is opening for the first time
+ if (prevSize === 0 && size === 10) {
+ sidebarRef.current?.resize(30);
+ }
+ }}
onCollapse={(collapsed) => setIsOpen(!collapsed)}
>
- {selectedPanel === "errors" && <ErrorsPanel />}
+ <div className="flex flex-col h-full flex-1">
+ <div className="p-3 border-b flex justify-between items-center">
+ <div className="text-sm font-medium text-[var(--sage-11)] uppercase tracking-wide font-semibold flex-1">
+ Variables
+ </div>
+ <Button
+ className="m-0"
+ size="xs"
+ variant="text"
+ onClick={() => setIsOpen(false)}
+ >
+ <XIcon className="w-4 h-4" />
+ </Button>
+ </div>
+ {/* {selectedPanel === "errors" && <ErrorsPanel />} */}
+ {selectedPanel === "variables" && (
+ <VariableTable
+ className="flex-1"
+ cellIds={cellIds}
+ variables={variables}
+ />
+ )}
+ </div>
</Panel>
);
diff --git a/frontend/src/editor/chrome/wrapper/footer.tsx b/frontend/src/editor/chrome/wrapper/footer.tsx
index 366b9e58de..d66ee5e495 100644
--- a/frontend/src/editor/chrome/wrapper/footer.tsx
+++ b/frontend/src/editor/chrome/wrapper/footer.tsx
@@ -1,34 +1,17 @@
/* Copyright 2023 Marimo. All rights reserved. */
import React, { PropsWithChildren } from "react";
-import {
- PanelBottomIcon,
- PanelLeftIcon,
- VariableIcon,
- XCircleIcon,
-} from "lucide-react";
-import { useCells } from "@/core/state/cells";
+import { PanelBottomIcon, PanelLeftIcon, VariableIcon } from "lucide-react";
import { cn } from "@/lib/utils";
import { useChromeActions, useChromeState } from "../state";
+import { Tooltip } from "@/components/ui/tooltip";
export const Footer: React.FC = () => {
const { selectedPanel, panelLocation } = useChromeState();
const { openApplication, changePanelLocation } = useChromeActions();
- const cells = useCells();
- const errors = cells.present
- .map((cell) =>
- cell.output?.mimetype === "application/vnd.marimo+error"
- ? {
- output: cell.output,
- cellId: cell.key,
- }
- : null
- )
- .filter(Boolean);
-
return (
- <footer className="h-6 bg-[var(--sage-3)] flex items-center text-muted-foreground text-md px-6 border-t border-border select-none">
- <FooterItem
+ <footer className="h-10 py-2 bg-background flex items-center text-muted-foreground text-md px-6 border-t border-border select-none">
+ {/* <FooterItem
selected={selectedPanel === "errors"}
onClick={() => openApplication("errors")}
>
@@ -38,22 +21,24 @@ export const Footer: React.FC = () => {
})}
/>
{errors.length}
- </FooterItem>
+ </FooterItem> */}
<FooterItem
+ tooltip="Explore variables"
selected={selectedPanel === "variables"}
onClick={() => openApplication("variables")}
>
- <VariableIcon className={cn("h-4 w-4 mr-1")} />
- {errors.length}
+ <VariableIcon className={cn("h-4 w-4")} />
</FooterItem>
<div className="mx-auto" />
<FooterItem
+ tooltip="Move panel to the left"
selected={panelLocation === "left"}
onClick={() => changePanelLocation("left")}
>
<PanelLeftIcon className="h-4 w-4" />
</FooterItem>
<FooterItem
+ tooltip="Move panel to the bottom"
selected={panelLocation === "bottom"}
onClick={() => changePanelLocation("bottom")}
>
@@ -64,21 +49,26 @@ export const Footer: React.FC = () => {
};
const FooterItem: React.FC<
- PropsWithChildren<{
- selected: boolean;
- onClick: () => void;
- }>
-> = ({ children, onClick, selected }) => {
+ PropsWithChildren<
+ {
+ selected: boolean;
+ tooltip: React.ReactNode;
+ } & React.HTMLAttributes<HTMLDivElement>
+ >
+> = ({ children, tooltip, selected, className, ...rest }) => {
return (
- <div
- className={cn(
- "h-full flex items-center px-2 shadow-inset font-mono cursor-pointer",
- !selected && "hover:bg-[var(--sage-4)]",
- selected && "bg-[var(--sage-6)]"
- )}
- onClick={onClick}
- >
- {children}
- </div>
+ <Tooltip content={tooltip} side="top">
+ <div
+ className={cn(
+ "h-full flex items-center p-2 text-sm mx-[1px] shadow-inset font-mono cursor-pointer rounded",
+ !selected && "hover:bg-[var(--sage-3)]",
+ selected && "bg-[var(--sage-4)]",
+ className
+ )}
+ {...rest}
+ >
+ {children}
+ </div>
+ </Tooltip>
);
};
diff --git a/frontend/src/editor/chrome/wrapper/storage.ts b/frontend/src/editor/chrome/wrapper/storage.ts
index f12ac1f179..56b2f039a6 100644
--- a/frontend/src/editor/chrome/wrapper/storage.ts
+++ b/frontend/src/editor/chrome/wrapper/storage.ts
@@ -1,31 +1,31 @@
/* Copyright 2023 Marimo. All rights reserved. */
import { PanelGroupStorage } from "react-resizable-panels";
import { z } from "zod";
-import Cookies from "js-cookie";
import { Objects } from "@/utils/objects";
const schema = z.record(z.tuple([z.number(), z.number()]));
+let storedValue: string | null = null;
+
/**
* This does 2 things:
- * - stores the storage in Cookies, so it persists across sessions and ports
+ * - stores the storage in memory, so it persists across moving the sidebar
* - flips the order of the store when the direction is flipped, since the helper sidebar
* will either come first or last.
*/
export function createStorage(location: "left" | "bottom"): PanelGroupStorage {
return {
getItem(name) {
- const item = Cookies.get(name);
- if (!item) {
- return item ?? null;
+ if (!storedValue) {
+ return storedValue ?? null;
}
if (location === "left") {
- return item;
+ return storedValue;
}
// flip
try {
- const parsed = schema.parse(JSON.parse(item));
+ const parsed = schema.parse(JSON.parse(storedValue));
return JSON.stringify(
Objects.mapValues(parsed, (value) => {
return value.reverse();
@@ -50,7 +50,7 @@ export function createStorage(location: "left" | "bottom"): PanelGroupStorage {
}
}
- return Cookies.set(name, value);
+ storedValue = value || null;
},
};
}
diff --git a/frontend/src/editor/links/cell-link.tsx b/frontend/src/editor/links/cell-link.tsx
new file mode 100644
index 0000000000..9c58c0b72f
--- /dev/null
+++ b/frontend/src/editor/links/cell-link.tsx
@@ -0,0 +1,52 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { CellId, HTMLCellId } from "@/core/model/ids";
+import { Logger } from "../../utils/Logger";
+import { cn } from "@/lib/utils";
+
+interface Props {
+ cellId: CellId;
+ className?: string;
+ variant?: "destructive" | "focus";
+}
+
+/* Component that adds a link to a cell, for use in a MarimoError. */
+export const CellLink = (props: Props): JSX.Element => {
+ const { className, cellId, variant } = props;
+ const cellName = HTMLCellId.create(cellId);
+
+ return (
+ <div
+ className={cn(
+ "inline-block cursor-pointer text-blue-500 hover:underline",
+ className
+ )}
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+
+ const cell: HTMLElement | null = document.getElementById(cellName);
+
+ if (cell === null) {
+ Logger.error(`Cell ${cellName} not found on page.`);
+ } else {
+ cell.scrollIntoView({ behavior: "smooth", block: "center" });
+
+ if (variant === "destructive") {
+ cell.classList.add("error-outline");
+ setTimeout(() => {
+ cell.classList.remove("error-outline");
+ }, 1500);
+ }
+ if (variant === "focus") {
+ cell.classList.add("focus-outline");
+ setTimeout(() => {
+ cell.classList.remove("focus-outline");
+ }, 1500);
+ }
+ }
+ }}
+ >
+ {cellName}
+ </div>
+ );
+};
diff --git a/frontend/src/editor/output/MarimoErrorOutput.tsx b/frontend/src/editor/output/MarimoErrorOutput.tsx
index 758b2c65df..2365193aa8 100644
--- a/frontend/src/editor/output/MarimoErrorOutput.tsx
+++ b/frontend/src/editor/output/MarimoErrorOutput.tsx
@@ -5,7 +5,6 @@ import { logNever } from "../../utils/assertNever";
import { MarimoError } from "../../core/kernel/messages";
import { Alert } from "../../components/ui/alert";
import { AlertTitle } from "../../components/ui/alert";
-import { CellId } from "@/core/model/ids";
import {
Accordion,
@@ -13,8 +12,8 @@ import {
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion";
-import { Logger } from "../../utils/Logger";
import { Fragment } from "react";
+import { CellLink } from "../links/cell-link";
const Tip = (props: {
className?: string;
@@ -37,32 +36,6 @@ const Tip = (props: {
);
};
-/* Component that adds a link to a cell, for use in a MarimoError. */
-const CellLink = (props: { cellId: CellId }): JSX.Element => {
- const cellName = `cell-${props.cellId}`;
- return (
- <div
- className="inline-block cursor-pointer text-blue-500 hover:underline"
- onClick={(e) => {
- e.stopPropagation();
- e.preventDefault();
- const cell: HTMLElement | null = document.getElementById(cellName);
- if (cell === null) {
- Logger.error(`Cell ${cellName} not found on page.`);
- } else {
- cell.classList.add("error-outline");
- cell.scrollIntoView({ behavior: "smooth", block: "center" });
- setTimeout(() => {
- cell.classList.remove("error-outline");
- }, 1000);
- }
- }}
- >
- {cellName}
- </div>
- );
-};
-
interface Props {
errors: MarimoError[];
className?: string;
diff --git a/frontend/src/editor/renderers/CellArray.tsx b/frontend/src/editor/renderers/CellArray.tsx
index cfaad3da9a..e227158ef7 100644
--- a/frontend/src/editor/renderers/CellArray.tsx
+++ b/frontend/src/editor/renderers/CellArray.tsx
@@ -15,6 +15,7 @@ import { formatEditorViews } from "../../core/codemirror/format";
import { useTheme } from "../../theme/useTheme";
import { VerticalLayoutWrapper } from "./vertical-layout/vertical-layout-wrapper";
import { useDelayVisibility } from "./vertical-layout/useDelayVisiblity";
+import { useChromeActions } from "../chrome/state";
interface CellArrayProps {
cells: CellsAndHistory;
@@ -51,12 +52,14 @@ export const CellArray: React.FC<CellArrayProps> = ({
unfoldAll,
} = useCellActions();
const { theme } = useTheme();
+ const { togglePanel } = useChromeActions();
const { invisible } = useDelayVisibility(cells.present);
// HOTKEYS
useHotkey("global.focusTop", focusTopCell);
useHotkey("global.focusBottom", focusBottomCell);
+ useHotkey("global.toggleSidebar", togglePanel);
useHotkey("global.foldCode", foldAll);
useHotkey("global.unfoldCode", unfoldAll);
useHotkey("global.formatAll", () => {
diff --git a/frontend/src/stories/variables.stories.tsx b/frontend/src/stories/variables.stories.tsx
new file mode 100644
index 0000000000..becac7bc1e
--- /dev/null
+++ b/frontend/src/stories/variables.stories.tsx
@@ -0,0 +1,58 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import type { Meta, StoryObj } from "@storybook/react";
+import { VariableTable } from "@/components/variables/variables-table";
+import { CellId } from "@/core/model/ids";
+
+const meta: Meta<typeof VariableTable> = {
+ title: "VariableTable",
+ component: VariableTable,
+ args: {},
+};
+
+const variables = {
+ a: {
+ name: "a",
+ declaredBy: ["1"],
+ usedBy: ["2"],
+ dataType: "number",
+ value: "1",
+ },
+ b: {
+ name: "b",
+ declaredBy: ["2"],
+ usedBy: ["3"],
+ dataType: "dataframe",
+ value: "<dataframe>",
+ },
+ my_super_super_long_variable_name: {
+ name: "my_super_super_long_variable_name",
+ declaredBy: ["3"],
+ usedBy: Array.from({ length: 15 }, (_, i) => `${i + 4}`),
+ },
+ c: {
+ name: "c",
+ declaredBy: ["4"],
+ dataType: "number",
+ value: "1",
+ usedBy: Array.from({ length: 3 }, (_, i) => `${i + 4}`),
+ },
+ d: {
+ name: "has_error",
+ declaredBy: ["4", "5"],
+ usedBy: Array.from({ length: 3 }, (_, i) => `${i + 4}`),
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof VariableTable>;
+
+export const Primary: Story = {
+ render: () => (
+ <div className="max-w-4xl">
+ <VariableTable
+ variables={variables}
+ cellIds={["2", "1", "3"] as CellId[]}
+ />
+ </div>
+ ),
+};
diff --git a/frontend/tailwind.config.js b/frontend/tailwind.config.js
index 61f8c3fc7f..b7b34f4fc8 100644
--- a/frontend/tailwind.config.js
+++ b/frontend/tailwind.config.js
@@ -11,28 +11,28 @@ module.exports = {
"2xl": "1400px",
},
},
- boxShadow: {
- none: "none",
- // fuzzy shadows
- xxs: "var(--shadow-xxs)",
- xs: "var(--shadow-xs)",
- sm: "var(--shadow-sm)",
- md: "var(--shadow-md)",
- lg: "var(--shadow-lg)",
- xl: "var(--shadow-xl)",
- // solid shadows
- xsSolid:
- "1px 1px 0px 0px var(--tw-shadow-color, var(--base-shadow-darker)), 0px 0px 2px 0px hsl(0deg 0% 25% / 5%)",
- smSolid:
- "2px 2px 0px 0px var(--tw-shadow-color, var(--base-shadow-darker)), 0px 0px 2px 0px hsl(0deg 0% 25% / 5%)",
- mdSolid:
- "4px 4px 0px 0px var(--tw-shadow-color, var(--base-shadow-darker)), 0 0px 4px 0px hsl(0deg 0% 60% / 5%)",
- lgSolid:
- "5px 6px 0px 0px var(--tw-shadow-color, var(--base-shadow-darker)), 0 0px 4px 0px hsl(0deg 0% 75% / 5%)",
- xlSolid:
- "8px 9px 0px 0px var(--tw-shadow-color, var(--base-shadow-darker)), 0 0px 6px 0px hsl(0deg 0% 85% / 5%)",
- },
extend: {
+ boxShadow: {
+ none: "none",
+ // fuzzy shadows
+ xxs: "var(--shadow-xxs)",
+ xs: "var(--shadow-xs)",
+ sm: "var(--shadow-sm)",
+ md: "var(--shadow-md)",
+ lg: "var(--shadow-lg)",
+ xl: "var(--shadow-xl)",
+ // solid shadows
+ xsSolid:
+ "1px 1px 0px 0px var(--tw-shadow-color, var(--base-shadow-darker)), 0px 0px 2px 0px hsl(0deg 0% 25% / 5%)",
+ smSolid:
+ "2px 2px 0px 0px var(--tw-shadow-color, var(--base-shadow-darker)), 0px 0px 2px 0px hsl(0deg 0% 25% / 5%)",
+ mdSolid:
+ "4px 4px 0px 0px var(--tw-shadow-color, var(--base-shadow-darker)), 0 0px 4px 0px hsl(0deg 0% 60% / 5%)",
+ lgSolid:
+ "5px 6px 0px 0px var(--tw-shadow-color, var(--base-shadow-darker)), 0 0px 4px 0px hsl(0deg 0% 75% / 5%)",
+ xlSolid:
+ "8px 9px 0px 0px var(--tw-shadow-color, var(--base-shadow-darker)), 0 0px 6px 0px hsl(0deg 0% 85% / 5%)",
+ },
maxWidth: {
contentWidth: "var(--content-width)",
},
diff --git a/marimo/_messaging/message_types.py b/marimo/_messaging/message_types.py
index 35fe7e0547..765278b99a 100644
--- a/marimo/_messaging/message_types.py
+++ b/marimo/_messaging/message_types.py
@@ -13,7 +13,9 @@ from typing import ClassVar, Dict, Optional, Union, cast
from marimo._ast.cell import CellConfig, CellId_t, CellStatusType
from marimo._messaging.cell_output import CellOutput
from marimo._messaging.completion_option import CompletionOption
+from marimo._output.hypertext import Html
from marimo._plugins.core.web_component import JSONType
+from marimo._plugins.ui._core.ui_element import UIElement
from marimo._server.layout import LayoutConfig
@@ -91,10 +93,21 @@ class VariableValue:
except Exception:
self.datatype = None
try:
- self.value = str(value)[:50]
+ self.value = self._format_value(value)
except Exception:
self.value = None
+ def _stringify(self, value: object) -> str:
+ return str(value)[:50]
+
+ def _format_value(self, value: object) -> str:
+ if isinstance(value, UIElement):
+ return self._stringify(value.value)
+ elif isinstance(value, Html):
+ return self._stringify(value.text)
+ else:
+ return self._stringify(value)
+
@dataclass
class Variables:
diff --git a/marimo/_messaging/test_message_types.py b/marimo/_messaging/test_message_types.py
new file mode 100644
index 0000000000..05e285d6fc
--- /dev/null
+++ b/marimo/_messaging/test_message_types.py
@@ -0,0 +1,17 @@
+# Copyright 2023 Marimo. All rights reserved.
+from marimo._messaging.message_types import VariableValue
+from marimo._output.hypertext import Html
+from marimo._plugins.ui._impl.input import slider
+
+
+def test_value_ui_element() -> None:
+ variable_value = VariableValue(name="s", value=slider(1, 10, value=5))
+ assert variable_value.datatype == "slider"
+ assert variable_value.value == "5"
+
+
+def test_value_html() -> None:
+ h = Html("<span></span>")
+ variable_value = VariableValue(name="h", value=h)
+ assert variable_value.datatype == "Html"
+ assert variable_value.value == h.text
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index b5d5846b68..5a5771e859 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -581,19 +581,20 @@ class Kernel:
with self._install_execution_context(cell_id):
run_result = runner.run(cell_id)
- write_variable_values(
- [
- VariableValue(
- name=variable,
- value=(
- self.globals[variable]
- if variable in self.globals
- else None
- ),
- )
- for variable in self.graph.cells[cell_id].defs
- ]
- )
+ values = [
+ VariableValue(
+ name=variable,
+ value=(
+ self.globals[variable]
+ if variable in self.globals
+ else None
+ ),
+ )
+ for variable in self.graph.cells[cell_id].defs
+ ]
+
+ if values:
+ write_variable_values(values)
cell.set_status(status="idle")
if run_result.success():
@@ -730,6 +731,8 @@ class Kernel:
# store the state and the currently executing cell
assert self.execution_context is not None
self.state_updates[state] = self.execution_context.cell_id
+ # TODO(akshayka): Send VariableValues message for any globals
+ # bound to this state object (just like UI elements)
def delete(self, request: DeleteRequest) -> None:
"""Delete a cell from kernel and graph."""
@@ -842,13 +845,20 @@ class Kernel:
bound_names = get_context().ui_element_registry.bound_names(
object_id
)
+
+ variable_values: list[VariableValue] = []
for name in bound_names:
# subtracting self.graph.definitions[name]: never rerun the
# cell that created the name
+ variable_values.append(
+ VariableValue(name=name, value=component)
+ )
referring_cells.update(
self.graph.get_referring_cells(name)
- self.graph.definitions[name]
)
+ if variable_values:
+ write_variable_values(variable_values)
self._run_cells(
dataflow.transitive_closure(self.graph, referring_cells)
)