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
Wide mode (#7)
Myles Scolnickc0cb9e5cf7ec
diff --git a/frontend/index.html b/frontend/index.htmlindex 5ac407bace..72487a6b54 100644--- a/frontend/index.html+++ b/frontend/index.html@@ -19,7 +19,8 @@</script><marimo-filename hidden>{{ filename }}</marimo-filename><marimo-mode data-mode={{ mode }} hidden></marimo-mode>- <marimo-config data-config='{{ config }}' hidden></marimo-config>+ <marimo-user-config data-config='{{ user_config }}' hidden></marimo-user-config>+ <marimo-app-config data-config='{{ app_config }}' hidden></marimo-app-config><title>{{ title }}</title></head><body>diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex bd579e5e03..4fa055ba89 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -22,7 +22,7 @@ import { useMarimoWebSocket } from "./core/websocket/useMarimoWebSocket";import { useCellActions, useCells } from "./core/state/cells";import { Disconnected } from "./editor/Disconnected";import { derefNotNull } from "./utils/dereference";-import { UserConfig } from "./core/config";+import { AppConfig, UserConfig } from "./core/config";import { AppMode, toggleAppMode } from "./core/mode";import { useHotkey } from "./hooks/useHotkey";import { Tooltip } from "./components/ui/tooltip";@@ -48,6 +48,7 @@ import { RuntimeState } from "./core/RuntimeState";interface AppProps {initialMode: AppMode;userConfig: UserConfig;+ appConfig: AppConfig;}/**@@ -65,7 +66,11 @@ interface ViewState {cellAnchor: CellId | null;}-export const App: React.FC<AppProps> = ({ initialMode, userConfig }) => {+export const App: React.FC<AppProps> = ({+ initialMode,+ userConfig,+ appConfig,+}) => {const cells = useCells();const { setCells } = useCellActions();const [viewState, setViewState] = useState<ViewState>({@@ -297,6 +302,7 @@ export const App: React.FC<AppProps> = ({ initialMode, userConfig }) => {connStatus={connStatus}mode={viewState.mode}userConfig={userConfig}+ appConfig={appConfig}/>);@@ -305,7 +311,8 @@ export const App: React.FC<AppProps> = ({ initialMode, userConfig }) => {id="App"className={clsx(connStatus.state === WebSocketState.CLOSED && "disconnected",- "bg-background w-full h-full text-textColor"+ "bg-background w-full h-full text-textColor",+ appConfig.width === "full" && "config-width-full")}>{connStatus.state === WebSocketState.OPEN && isRunning && <RunningIcon />}diff --git a/frontend/src/MarimoApp.tsx b/frontend/src/MarimoApp.tsxindex 94391425ef..d1a6c8ef7b 100644--- a/frontend/src/MarimoApp.tsx+++ b/frontend/src/MarimoApp.tsx@@ -10,7 +10,7 @@ import { Toaster } from "./components/ui/toaster";import { ModalProvider } from "./components/modal/ImperativeModal";import { DayPickerProvider } from "react-day-picker";import { CommandPallette } from "./editor/CommandPallette";-import { useUserConfig } from "./core/state/user-config";+import { useAppConfig, useUserConfig } from "@/core/state/config";interface MarimoAppProps {/**@@ -24,6 +24,7 @@ interface MarimoAppProps {*/export const MarimoApp: React.FC<MarimoAppProps> = ({ initialMode }) => {const [userConfig] = useUserConfig();+ const [appConfig] = useAppConfig();useEffect(() => {initializePlugins();@@ -34,7 +35,11 @@ export const MarimoApp: React.FC<MarimoAppProps> = ({ initialMode }) => {<TooltipProvider><DayPickerProvider initialProps={{}}><ModalProvider>- <App initialMode={initialMode} userConfig={userConfig} />+ <App+ initialMode={initialMode}+ userConfig={userConfig}+ appConfig={appConfig}+ /><Toaster />{initialMode !== "read" && <CommandPallette />}</ModalProvider>diff --git a/frontend/src/components/app-config/app-config-button.tsx b/frontend/src/components/app-config/app-config-button.tsxindex 3108fa9aeb..924b21d06b 100644--- a/frontend/src/components/app-config/app-config-button.tsx+++ b/frontend/src/components/app-config/app-config-button.tsx@@ -8,6 +8,7 @@ import { Button } from "../../editor/inputs/Inputs";import { SettingsIcon } from "lucide-react";import { UserConfigForm } from "./user-config-form";import { Tooltip } from "../ui/tooltip";+import { AppConfigForm } from "@/components/app-config/app-config-form";export const AppConfigButton = () => {return (@@ -26,6 +27,8 @@ export const AppConfigButton = () => {</Button></PopoverTrigger><PopoverContent className="w-80" align="end" side="bottom">+ <AppConfigForm />+ <div className="h-px bg-gray-200 dark:bg-gray-700 my-4" /><UserConfigForm /></PopoverContent></Popover>diff --git a/frontend/src/components/app-config/app-config-form.tsx b/frontend/src/components/app-config/app-config-form.tsxnew file mode 100644index 0000000000..b45ad4d993--- /dev/null+++ b/frontend/src/components/app-config/app-config-form.tsx@@ -0,0 +1,61 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { zodResolver } from "@hookform/resolvers/zod";+import { useForm } from "react-hook-form";+import {+ Form,+ FormControl,+ FormField,+ FormItem,+ FormLabel,+} from "@/components/ui/form";+import { AppConfig, AppConfigSchema } from "../../core/config";+import { toast } from "../ui/use-toast";+import { useAppConfig } from "@/core/state/config";+import { Switch } from "@/components/ui/switch";+import { saveAppConfig } from "@/core/network/requests";++export const AppConfigForm: React.FC = () => {+ const [config, setConfig] = useAppConfig();++ // Create form+ const form = useForm<AppConfig>({+ resolver: zodResolver(AppConfigSchema),+ defaultValues: config,+ });++ const onSubmit = async (values: AppConfig) => {+ await saveAppConfig({ config: values })+ .then(() => {+ setConfig(values);+ })+ .catch(() => {+ setConfig(values);+ toast({ title: "Failed to save" });+ });+ };++ return (+ <Form {...form}>+ <form onChange={form.handleSubmit(onSubmit)} className="space-y-4">+ <FormField+ control={form.control}+ name="width"+ render={({ field }) => (+ <FormItem className="flex flex-row items-center space-x-2 space-y-0">+ <FormControl>+ <Switch+ checked={field.value === "full"}+ size="sm"+ onCheckedChange={(checked) => {+ return field.onChange(checked === true ? "full" : "normal");+ }}+ />+ </FormControl>+ <FormLabel className="font-normal">Full-width</FormLabel>+ </FormItem>+ )}+ />+ </form>+ </Form>+ );+};diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsxindex 477a4c74a3..0ff555acda 100644--- a/frontend/src/components/app-config/user-config-form.tsx+++ b/frontend/src/components/app-config/user-config-form.tsx@@ -15,7 +15,7 @@ import { Checkbox } from "../ui/checkbox";import { Input } from "../ui/input";import { toast } from "../ui/use-toast";import { saveUserConfig } from "../../core/network/requests";-import { useUserConfig } from "../../core/state/user-config";+import { useUserConfig } from "../../core/state/config";import { ThemeToggle } from "./theme-toggle";export const UserConfigForm: React.FC = () => {diff --git a/frontend/src/components/ui/switch.tsx b/frontend/src/components/ui/switch.tsxindex 9bd12451ca..8c90860937 100644--- a/frontend/src/components/ui/switch.tsx+++ b/frontend/src/components/ui/switch.tsx@@ -3,24 +3,50 @@ import * as React from "react";import * as SwitchPrimitives from "@radix-ui/react-switch";import { cn } from "@/lib/utils";+import { cva, VariantProps } from "class-variance-authority";++const switchVariants = cva(+ "peer inline-flex shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-accent data-[state=unchecked]:bg-input",+ {+ variants: {+ size: {+ default: "h-[1.5rem] w-[2.75rem] mb-1",+ sm: "h-[1.125rem] w-[2.125rem]",+ },+ },+ defaultVariants: {+ size: "default",+ },+ }+);++const switchThumbVariants = cva(+ "pointer-events-none block rounded-full bg-background shadow-xs ring-0 transition-transform",+ {+ variants: {+ size: {+ default:+ "h-5 w-5 data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0",+ sm: "h-3.5 w-3.5 data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0",+ },+ },+ defaultVariants: {+ size: "default",+ },+ }+);const Switch = React.forwardRef<React.ElementRef<typeof SwitchPrimitives.Root>,- React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>->(({ className, ...props }, ref) => (+ React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root> &+ VariantProps<typeof switchVariants>+>(({ className, size, ...props }, ref) => (<SwitchPrimitives.Root- className={cn(- "peer inline-flex h-[1.5rem] w-[2.75rem] mb-1 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-accent data-[state=unchecked]:bg-input",- className- )}+ className={cn(switchVariants({ size }), className)}{...props}ref={ref}>- <SwitchPrimitives.Thumb- className={cn(- "pointer-events-none block h-5 w-5 rounded-full bg-background shadow-xs ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0"- )}- />+ <SwitchPrimitives.Thumb className={cn(switchThumbVariants({ size }))} /></SwitchPrimitives.Root>));Switch.displayName = SwitchPrimitives.Root.displayName;diff --git a/frontend/src/core/config.ts b/frontend/src/core/config.tsindex 3e66cff874..ca0a3174ac 100644--- a/frontend/src/core/config.ts+++ b/frontend/src/core/config.ts@@ -2,39 +2,55 @@import { z } from "zod";import { assertExists } from "../utils/assertExists";-const SaveConfigSchema = z.object({- autosave: z.enum(["off", "after_delay"]),- autosave_delay: z- .number()- .nonnegative()- // Ensure that the delay is at least 1 second- .transform((millis) => Math.max(millis, 1000)),-});--const CompletionConfigSchema = z.object({- activate_on_typing: z.boolean(),-});-export const UserConfigSchema = z.object({- completion: CompletionConfigSchema,- save: SaveConfigSchema,+ completion: z.object({+ activate_on_typing: z.boolean(),+ }),+ save: z.object({+ autosave: z.enum(["off", "after_delay"]),+ autosave_delay: z+ .number()+ .nonnegative()+ // Ensure that the delay is at least 1 second+ .transform((millis) => Math.max(millis, 1000)),+ }),});export type UserConfig = z.infer<typeof UserConfigSchema>;-export type SaveConfig = z.infer<typeof SaveConfigSchema>;-export type CompletionConfig = z.infer<typeof CompletionConfigSchema>;+export type SaveConfig = UserConfig["save"];+export type CompletionConfig = UserConfig["completion"];-export function getAppConfig() {- const tag = document.querySelector<HTMLElement>("marimo-config");- assertExists(tag, "internal-error: marimo-config tag not found");+export const AppConfigSchema = z.object({+ width: z.enum(["full", "normal"]).default("normal"),+});+export type AppConfig = z.infer<typeof AppConfigSchema>;- const configData = tag.dataset.config;- assertExists(configData, "internal-error: missing config");+export function getAppConfig() {+ try {+ return AppConfigSchema.parse(JSON.parse(getConfig("app")));+ } catch (error) {+ throw new Error(+ `Marimo got an unexpected value in the configuration file: ${error}`+ );+ }+}+export function getUserConfig() {try {- return UserConfigSchema.parse(JSON.parse(configData));+ return UserConfigSchema.parse(JSON.parse(getConfig("user")));} catch (error) {throw new Error(`Marimo got an unexpected value in the configuration file: ${error}`);}}++function getConfig(kind: "user" | "app") {+ const tagName = kind === "user" ? "marimo-user-config" : "marimo-app-config";+ const tag = document.querySelector<HTMLElement>(tagName);+ assertExists(tag, `internal-error: ${tagName} tag not found`);++ const configData = tag.dataset.config;+ assertExists(configData, "internal-error: missing config");++ return configData;+}diff --git a/frontend/src/core/network/requests.ts b/frontend/src/core/network/requests.tsindex ab3ed88870..8a045f0297 100644--- a/frontend/src/core/network/requests.ts+++ b/frontend/src/core/network/requests.ts@@ -14,6 +14,7 @@ import {SendDirectoryAutocompleteResponse,SetComponentValuesRequest,SaveUserConfigRequest,+ SaveAppConfigRequest,} from "./types";interface ValueUpdate {@@ -108,3 +109,7 @@ export async function sendCodeCompletionRequest(export function saveUserConfig(request: SaveUserConfigRequest) {return API.post<SaveUserConfigRequest>("/kernel/save_user_config/", request);}++export function saveAppConfig(request: SaveAppConfigRequest) {+ return API.post<SaveAppConfigRequest>("/kernel/save_app_config/", request);+}diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.tsindex 49bc3c0cdc..ab7b984911 100644--- a/frontend/src/core/network/types.ts+++ b/frontend/src/core/network/types.ts@@ -1,6 +1,6 @@/* Copyright 2023 Marimo. All rights reserved. */-import { UserConfig } from "../config";-import { CellId } from "../model/ids";+import { AppConfig, UserConfig } from "../../core/config";+import { CellId } from "../../core/model/ids";export interface DeleteRequest {cellId: CellId;@@ -70,3 +70,7 @@ export interface CodeCompletionRequest {export interface SaveUserConfigRequest {config: UserConfig;}++export interface SaveAppConfigRequest {+ config: AppConfig;+}diff --git a/frontend/src/core/state/config.ts b/frontend/src/core/state/config.tsnew file mode 100644index 0000000000..611b4987b4--- /dev/null+++ b/frontend/src/core/state/config.ts@@ -0,0 +1,27 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { atom, useAtom } from "jotai";+import { AppConfig, UserConfig, getAppConfig, getUserConfig } from "../config";++/**+ * Atom for storing the user config.+ */+const userConfigAtom = atom<UserConfig>(getUserConfig());++/**+ * Returns the user config.+ */+export function useUserConfig() {+ return useAtom(userConfigAtom);+}++/**+ * Atom for storing the app config.+ */+const appConfigAtom = atom<AppConfig>(getAppConfig());++/**+ * Returns the app config.+ */+export function useAppConfig() {+ return useAtom(appConfigAtom);+}diff --git a/frontend/src/core/state/user-config.ts b/frontend/src/core/state/user-config.tsdeleted file mode 100644index aaa2cdcdda..0000000000--- a/frontend/src/core/state/user-config.ts+++ /dev/null@@ -1,15 +0,0 @@-/* Copyright 2023 Marimo. All rights reserved. */-import { atom, useAtom } from "jotai";-import { UserConfig, getAppConfig } from "../config";--/**- * Atom for storing the user config.- */-const userConfigAtom = atom<UserConfig>(getAppConfig());--/**- * Returns the user config.- */-export function useUserConfig() {- return useAtom(userConfigAtom);-}diff --git a/frontend/src/css/Cell.css b/frontend/src/css/Cell.cssindex 8b924a3c43..2c9b258773 100644--- a/frontend/src/css/Cell.css+++ b/frontend/src/css/Cell.css@@ -352,7 +352,7 @@}.OutputArea {- padding: 0.5% 4%;+ padding: 0.25rem 1.85rem;border: 1px solid transparent;border-bottom: 1px solid var(--gray-5);}diff --git a/frontend/src/css/md.css b/frontend/src/css/md.cssindex d307dfb752..f79e85ad21 100644--- a/frontend/src/css/md.css+++ b/frontend/src/css/md.css@@ -39,6 +39,11 @@text-align: center;}+.config-width-full .markdown h1 {+ /* In full-width display, centered headings look odd */+ text-align: start;+}+.markdown h2 {/* provide by the browser, but removed from 'reset' */display: block;diff --git a/frontend/src/editor/renderers/CellArray.tsx b/frontend/src/editor/renderers/CellArray.tsxindex 53afe1057d..f96d847d99 100644--- a/frontend/src/editor/renderers/CellArray.tsx+++ b/frontend/src/editor/renderers/CellArray.tsx@@ -6,7 +6,7 @@ import { Cell } from "editor/Cell";import { RuntimeState } from "../../core/RuntimeState";import { ConnectionStatus, WebSocketState } from "../../core/websocket/types";import { CellsAndHistory, useCellActions } from "../../core/state/cells";-import { UserConfig } from "../../core/config";+import { AppConfig, UserConfig } from "../../core/config";import { AppMode } from "../../core/mode";import { useHotkey } from "../../hooks/useHotkey";import { useEvent } from "../../hooks/useEvent";@@ -19,6 +19,7 @@ interface CellArrayProps {cells: CellsAndHistory;mode: AppMode;userConfig: UserConfig;+ appConfig: AppConfig;connStatus: ConnectionStatus;}@@ -31,6 +32,7 @@ export const CellArray: React.FC<CellArrayProps> = ({cells,mode,userConfig,+ appConfig,connStatus,}) => {const {@@ -96,7 +98,9 @@ export const CellArray: React.FC<CellArrayProps> = ({return (<divclassName={cn(- "max-w-contentWidth m-auto pb-12",+ "m-auto pb-12",+ appConfig.width === "full" && "px-24",+ appConfig.width !== "full" && "max-w-contentWidth",// Hide the cells for a fake loading effect, to avoid flickeringinvisible && "invisible")}diff --git a/frontend/src/stories/switch.stories.mdx b/frontend/src/stories/switch.stories.mdxindex c7140cf7d4..dc452d7bf9 100644--- a/frontend/src/stories/switch.stories.mdx+++ b/frontend/src/stories/switch.stories.mdx@@ -11,3 +11,8 @@ import { Switch } from "@/components/ui/switch";<Switch id="airplane-mode" /><Label htmlFor="airplane-mode">Airplane Mode</Label></div>++<div className="flex items-center align-middle space-x-2">+ <Switch id="airplane-mode" size="sm" />+ <Label htmlFor="airplane-mode">Small Switch</Label>+</div>diff --git a/marimo/_ast/app.py b/marimo/_ast/app.pyindex a5404667f7..6f40d700f6 100644--- a/marimo/_ast/app.py+++ b/marimo/_ast/app.py@@ -5,7 +5,8 @@ import builtinsimport itertoolsimport textwrapfrom collections.abc import Sequence-from typing import Any, Optional+from dataclasses import asdict, dataclass+from typing import Any, Iterable, Literal, Optionalfrom marimo._ast.cell import (CellFunction,@@ -24,6 +25,39 @@ from marimo._output.rich_help import mddocfrom marimo._runtime.dataflow import DirectedGraph, topological_sort+@dataclass+class _AppConfig:+ """Program-specific configuration.++ Configuration for frontends or runtimes that is specific to+ a single marimo program.+ """++ width: Literal["normal", "full"] = "normal"++ def asdict(self) -> dict[str, Any]:+ return asdict(self)++ def update(self, updates: dict[str, Any]) -> None:+ config_dict = asdict(self)+ for key in updates:+ if key in config_dict:+ self.__setattr__(key, updates[key])+++@dataclass+class CellData:+ """A cell together with some metadata"""++ cell_id: CellId_t+ # User code comprising the cell+ code: str+ # User-provided name for cell (or default)+ name: str+ # Callable cell, or None if cell was not parsable+ cell_function: Optional[CellFunction]++@mddocclass App:"""A marimo app.@@ -34,11 +68,16 @@ class App:This class has no public API, but this may change in the future."""- def __init__(self) -> None:- # cell is unparsable <=> its value in self._cell_functions is None- self._cell_functions: dict[CellId_t, Optional[CellFunction]] = {}- self._cell_names: dict[CellId_t, str] = {}- self._codes: dict[CellId_t, str] = {}+ def __init__(self, **kwargs: Any) -> None:+ # Take `AppConfig` as kwargs for forward/backward compatibility;+ # unrecognized settings will just be dropped, instead of raising+ # a TypeError.+ self._config = _AppConfig()+ for key in asdict(self._config):+ if key in kwargs:+ self._config.__setattr__(key, kwargs.pop("width"))++ self._cell_data: dict[CellId_t, CellData] = {}self._registration_order: list[CellId_t] = []self._cell_id_counter = 0@@ -57,11 +96,25 @@ class App:def cell(self, f: cell_func_t) -> CellFunction:cell_function = cell_factory(f)cell_id = self._create_cell_id(cell_function)- self._cell_functions[cell_id] = cell_function- self._cell_names[cell_id] = f.__name__- self._codes[cell_id] = cell_function.cell.code+ self._cell_data[cell_id] = CellData(+ cell_id=cell_id,+ code=cell_function.cell.code,+ name=f.__name__,+ cell_function=cell_function,+ )return cell_function+ def _names(self) -> Iterable[str]:+ return (cell_data.name for cell_data in self._cell_data.values())++ def _codes(self) -> Iterable[str]:+ return (cell_data.code for cell_data in self._cell_data.values())++ def _cell_functions(self) -> Iterable[Optional[CellFunction]]:+ return (+ cell_data.cell_function for cell_data in self._cell_data.values()+ )+def _validate_args(self) -> None:"""Validate the args of each cell function.@@ -75,13 +128,11 @@ class App:"""defs = set(itertools.chain.from_iterable(- f.cell.defs- for f in self._cell_functions.values()- if f is not None+ f.cell.defs for f in self._cell_functions() if f is not None))unshadowed_builtins = set(builtins.__dict__.keys()).difference(defs)- for f in self._cell_functions.values():+ for f in self._cell_functions():if f is None:continueexpected_args = f.cell.refs - unshadowed_builtins@@ -99,7 +150,7 @@ class App:def _unparsable_cell(self, code: str, name: Optional[str] = None) -> None:cell_id = self._create_cell_id(None)- self._cell_names[cell_id] = name if name is not None else "__"+ name = name if name is not None else "__"# - code.split("\n")[1:-1] disregards first and last lines, which are# empty# - line[4:] removes leading indent in multiline string@@ -108,7 +159,9 @@ class App:code = "\n".join([line[4:].replace('\\"', '"') for line in code.split("\n")[1:-1]])- self._codes[cell_id] = code+ self._cell_data[cell_id] = CellData(+ cell_id=cell_id, code=code, name=name, cell_function=None+ )self._unparsable = Truedef _maybe_initialize(self) -> None:@@ -118,13 +171,13 @@ class App:# were registered with the appself._cell_ids = [# exclude unparseable cells from graph- cid- for cid, f in self._cell_functions.items()- if f is not None+ cell_data.cell_id+ for cell_data in self._cell_data.values()+ if cell_data.cell_function is not None]self._graph = DirectedGraph()for cell_id in self._cell_ids:- cell_function = self._cell_functions[cell_id]+ cell_function = self._cell_data[cell_id].cell_functionassert cell_function is not Noneself._graph.register_cell(cell_id, cell_function.cell)self._defs = self._graph.definitions.keys()@@ -180,7 +233,8 @@ class App:outputs = {cid: execute_cell(cell_function.cell, glbls)for cid in self._execution_order- if (cell_function := self._cell_functions[cid]) is not None+ if (cell_function := self._cell_data[cid].cell_function)+ is not None}# Return# - the outputs, sorted in the order that cells were added to thediff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.pyindex 15dcfce0fa..1d59aad19f 100644--- a/marimo/_ast/codegen.py+++ b/marimo/_ast/codegen.py@@ -5,14 +5,15 @@ import builtinsimport importlib.utilimport jsonfrom collections.abc import Sequence-from typing import Optional, Union+from typing import Any, Optional, Unionfrom marimo import __version__-from marimo._ast.app import App+from marimo._ast.app import App, _AppConfigfrom marimo._ast.cell import Cell, parse_cellfrom marimo._ast.visitor import NameINDENT = " "+MAX_LINE_LENGTH = 80def indent_text(text: str) -> str:@@ -42,7 +43,7 @@ def to_functiondef(decorator = "@app.cell"signature = f"def {name}({args}):"- if len(INDENT + signature) >= 80:+ if len(INDENT + signature) >= MAX_LINE_LENGTH:signature = f"def {name}{_multiline_tuple(refs)}:"fndef = decorator + "\n" + signature + "\n"body = indent_text(cell.code)@@ -58,7 +59,7 @@ def to_functiondef(returns += ", ".join(defs)fndef += (returns- if len(INDENT + returns) <= 80+ if len(INDENT + returns) <= MAX_LINE_LENGTHelse (indent_text("return " + _multiline_tuple(defs))))else:@@ -85,7 +86,33 @@ def generate_unparseable_cell(code: str, name: Optional[str]) -> str:)-def generate_filecontents(codes: list[str], names: list[str]) -> str:+def generate_app_constructor(config: Optional[_AppConfig]) -> str:+ def _format_arg(arg: Any) -> str:+ if isinstance(arg, str):+ return f'"{arg}"'+ else:+ return str(arg)++ default_config = _AppConfig().asdict()+ updates = {}+ # only include a config setting if it's not a default setting, to+ # avoid unnecessary edits to the app file+ if config is not None:+ updates = config.asdict()+ for key in default_config:+ if updates[key] == default_config[key]:+ updates.pop(key)++ kwargs = [f"{key}={_format_arg(value)}" for key, value in updates.items()]+ app_constructor = "app = marimo.App(" + ", ".join(kwargs) + ")"+ if len(app_constructor) >= MAX_LINE_LENGTH:+ app_constructor = "app = marimo.App" + _multiline_tuple(kwargs)+ return app_constructor+++def generate_filecontents(+ codes: list[str], names: list[str], config: Optional[_AppConfig] = None+) -> str:"""Translates a sequences of codes (cells) to a Python file"""cell_function_data: list[Union[Cell, str]] = []defs: set[Name] = set()@@ -111,7 +138,7 @@ def generate_filecontents(codes: list[str], names: list[str]) -> str:+ "\n\n"+ f'__generated_with = "{__version__}"'+ "\n"- + "app = marimo.App()"+ + generate_app_constructor(config)+ "\n\n\n"+ "\n\n\n".join(fndefs)+ "\n\n\n"@@ -127,17 +154,16 @@ class MarimoFileError(Exception):pass-# TODO refactor to return cell_ids as well?-def get_codes(filename: Optional[str]) -> tuple[list[str], list[str]]:- """Get lists of codes and names from a marimo-generated module"""+def get_app(filename: Optional[str]) -> Optional[App]:+ """Load and return app from a marimo-generated module"""if filename is None:- return [""], ["__"]+ return Nonewith open(filename, "r", encoding="utf-8") as f:contents = f.read().strip()if not contents:- return [""], ["__"]+ return Nonespec = importlib.util.spec_from_file_location("marimo_app", filename)if spec is None:@@ -151,10 +177,9 @@ def get_codes(filename: Optional[str]) -> tuple[list[str], list[str]]:if not isinstance(marimo_app.app, App):raise MarimoFileError("`app` attribute must be of type `marimo.App`.")- marimo_app.app._validate_args()- return list(marimo_app.app._codes.values()), list(- marimo_app.app._cell_names.values()- )+ app = marimo_app.app+ app._validate_args()+ return appRECOVERY_CELL_MARKER = "ↁ"diff --git a/marimo/_ast/test_app.py b/marimo/_ast/test_app.pyindex 32a52e455f..76c2730b33 100644--- a/marimo/_ast/test_app.py+++ b/marimo/_ast/test_app.py@@ -37,12 +37,12 @@ class TestApp:z = y + 1return y, z- cell_names = tuple(app._cell_names.values())+ cell_names = tuple(app._names())assert cell_names[0] == "one"assert cell_names[1] == "two"assert cell_names[2] == "__"- codes = tuple(app._codes.values())+ codes = tuple(app._codes())assert codes[0] == "x = 0\nx"assert codes[1] == "a = x + z\na + 1"assert codes[2] == "y = x + 1\nz = y + 1"@@ -232,3 +232,18 @@ class TestApp:returnapp.run()++ @staticmethod+ def test_app_width_config() -> None:+ app = App(width="full")+ assert app._config.width == "full"++ @staticmethod+ def test_app_width_default() -> None:+ app = App()+ assert app._config.width == "normal"++ @staticmethod+ def test_app_config_extra_args_ignored() -> None:+ app = App(width="full", fake_config="foo")+ assert app._config.asdict() == {"width": "full"}diff --git a/marimo/_ast/test_codegen.py b/marimo/_ast/test_codegen.pyindex ba0f7f19ee..3b37441f15 100644--- a/marimo/_ast/test_codegen.py+++ b/marimo/_ast/test_codegen.py@@ -134,11 +134,10 @@ class TestGeneration:class TestGetCodes:@staticmethoddef test_get_codes() -> None:- codes, names = codegen.get_codes(- get_filepath("test_generate_filecontents")- )- assert names == ["one", "two", "three", "four", "five"]- assert codes == [+ app = codegen.get_app(get_filepath("test_generate_filecontents"))+ assert app is not None+ assert list(app._names()) == ["one", "two", "three", "four", "five"]+ assert list(app._codes()) == ["import numpy as np","x = 0\nxx = 1","y = x + 1",@@ -149,70 +148,68 @@ class TestGetCodes:@staticmethoddef test_get_codes_with_name_error() -> None:# name mo is not defined --- make sure this file is still parseable- codes, names = codegen.get_codes(- get_filepath("test_get_codes_with_name_error")- )- assert names == ["one"]- assert codes == [+ app = codegen.get_app(get_filepath("test_get_codes_with_name_error"))+ assert app is not None+ assert list(app._names()) == ["one"]+ assert list(app._codes()) == ["mo",]@staticmethoddef test_get_codes_multiline_fndef() -> None:- codes, names = codegen.get_codes(- get_filepath("test_get_codes_multiline_fndef")- )- assert names == ["one"]- assert codes == [+ app = codegen.get_app(get_filepath("test_get_codes_multiline_fndef"))+ assert app is not None+ assert list(app._names()) == ["one"]+ assert list(app._codes()) == ["# comment\nx = 0 + a + b + c + d",]@staticmethoddef test_get_codes_messy() -> None:- codes, names = codegen.get_codes(get_filepath("test_get_codes_messy"))- assert names == ["__"]- assert codes == [+ app = codegen.get_app(get_filepath("test_get_codes_messy"))+ assert app is not None+ assert list(app._names()) == ["__"]+ assert list(app._codes()) == ["# comment\n# another comment\n\n# yet another comment\n"+ "x = 0 + a + b + c + d",]@staticmethoddef test_get_codes_single_line_fn() -> None:- codes, names = codegen.get_codes(- get_filepath("test_get_codes_single_line_fn")- )- assert names == ["one"]- assert codes == ["c = a + b; print(c); "]+ app = codegen.get_app(get_filepath("test_get_codes_single_line_fn"))+ assert app is not None+ assert list(app._names()) == ["one"]+ assert list(app._codes()) == ["c = a + b; print(c); "]@staticmethoddef test_get_codes_multiline_string() -> None:- codes, names = codegen.get_codes(- get_filepath("test_get_codes_multiline_string")- )- assert names == ["one"]- assert codes == ['c = """\n a, b"""; ']+ app = codegen.get_app(get_filepath("test_get_codes_multiline_string"))+ assert app is not None+ assert list(app._names()) == ["one"]+ assert list(app._codes()) == ['c = """\n a, b"""; ']@staticmethoddef test_get_codes_comment_after_sig() -> None:- codes, names = codegen.get_codes(- get_filepath("test_get_codes_comment_after_sig")- )- assert names == ["one"]- assert codes == ['print("hi")']+ app = codegen.get_app(get_filepath("test_get_codes_comment_after_sig"))+ assert app is not None+ assert list(app._names()) == ["one"]+ assert list(app._codes()) == ['print("hi")']@staticmethoddef test_get_codes_empty() -> None:- codes, names = codegen.get_codes(get_filepath("test_get_codes_empty"))- assert names == ["one", "two"]- assert [c.strip() for c in codes] == ["", ""]+ app = codegen.get_app(get_filepath("test_get_codes_empty"))+ assert app is not None+ assert list(app._names()) == ["one", "two"]+ assert [c.strip() for c in app._codes()] == ["", ""]@staticmethoddef test_get_codes_syntax_error() -> None:- codes, names = codegen.get_codes(+ app = codegen.get_app(get_filepath("test_generate_filecontents_with_syntax_error"))- assert names == ["one", "two", "__", "__"]- assert codes == [+ assert app is not None+ assert list(app._names()) == ["one", "two", "__", "__"]+ assert list(app._codes()) == ["import numpy as np","_ error","'all good'",diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.pyindex db4c8daea0..bd8cec483c 100644--- a/marimo/_cli/cli.py+++ b/marimo/_cli/cli.py@@ -197,7 +197,7 @@ def edit()# module correctness check - don't start the server# if we can't import the module- codegen.get_codes(name)+ codegen.get_app(name)else:# write empty filetry:@@ -265,7 +265,7 @@ def run(port: Optional[int], headless: bool, name: str) -> None:raise click.UsageError("Invalid NAME - %s is not a file" % name)# correctness check - don't start the server if we can't import the module- codegen.get_codes(name)+ codegen.get_app(name)asyncio.run(start_server(diff --git a/marimo/_cli/test_ipynb_to_marimo.py b/marimo/_cli/test_ipynb_to_marimo.pyindex 860cb4b957..eb69d96be3 100644--- a/marimo/_cli/test_ipynb_to_marimo.py+++ b/marimo/_cli/test_ipynb_to_marimo.py@@ -20,7 +20,9 @@ def get_codes(ipynb_name: str) -> tuple[Sequence[str], Sequence[str]]:with tempfile.NamedTemporaryFile(mode="w", suffix=".py") as f:f.write(contents)f.seek(0)- return codegen.get_codes(f.name)+ app = codegen.get_app(f.name)+ assert app is not None+ return list(app._codes()), list(app._names())def test_markdown() -> None:diff --git a/marimo/_server/api/__init__.py b/marimo/_server/api/__init__.pyindex b0e1bd47c4..3bcbbc3e11 100644--- a/marimo/_server/api/__init__.py+++ b/marimo/_server/api/__init__.py@@ -8,6 +8,7 @@ __all__ = ["InterruptHandler","RenameHandler","RunHandler",+ "SaveAppConfigurationHandler","SaveHandler","SaveUserConfigurationHandler","SetUIElementValueHandler",@@ -24,5 +25,6 @@ from marimo._server.api.interrupt import InterruptHandlerfrom marimo._server.api.rename import RenameHandlerfrom marimo._server.api.run import RunHandlerfrom marimo._server.api.save import SaveHandler+from marimo._server.api.save_app_config import SaveAppConfigurationHandlerfrom marimo._server.api.save_user_config import SaveUserConfigurationHandlerfrom marimo._server.api.set_ui_element_value import SetUIElementValueHandlerdiff --git a/marimo/_server/api/instantiate.py b/marimo/_server/api/instantiate.pyindex e9f2f04821..883c3cc883 100644--- a/marimo/_server/api/instantiate.py+++ b/marimo/_server/api/instantiate.py@@ -6,6 +6,7 @@ from typing import Anyimport tornado.web+from marimo._ast.app import Appfrom marimo._runtime import requestsfrom marimo._server import sessionsfrom marimo._server.api.model import parse_raw@@ -29,12 +30,22 @@ class InstantiateHandler(tornado.web.RequestHandler):session = sessions.require_session_from_header(self.request.headers)args = parse_raw(self.request.body, Instantiate)mgr = sessions.get_manager()- app_data = mgr.app_data()+ app = mgr.load_app()+ execution_requests: tuple[requests.ExecutionRequest, ...]+ if app is None:+ # Instantiating an empty app+ # TODO(akshayka): In this case, don't need to run anything ...+ execution_requests = (+ requests.ExecutionRequest(App()._create_cell_id(None), ""),+ )+ else:+ execution_requests = tuple(+ requests.ExecutionRequest(cell_data.cell_id, cell_data.code)+ for cell_data in app._cell_data.values()+ )+request = requests.CreationRequest(- execution_requests=tuple(- requests.ExecutionRequest(cid, cell_data.code)- for cid, cell_data in app_data.items()- ),+ execution_requests=execution_requests,set_ui_element_value_request=requests.SetUIElementValueRequest(zip(args.object_ids, args.values)),diff --git a/marimo/_server/api/save.py b/marimo/_server/api/save.pyindex b4fbb133ed..9be8522b28 100644--- a/marimo/_server/api/save.py+++ b/marimo/_server/api/save.py@@ -47,7 +47,9 @@ class SaveHandler(tornado.web.RequestHandler):)else:# try to save the app under the name `filename`- contents = codegen.generate_filecontents(codes, names)+ contents = codegen.generate_filecontents(+ codes, names, config=mgr.app_config+ )LOGGER.debug("Saving app to %s", filename)try:with open(filename, "w", encoding="utf-8") as f:diff --git a/marimo/_server/api/save_app_config.py b/marimo/_server/api/save_app_config.pynew file mode 100644index 0000000000..ca43da708c--- /dev/null+++ b/marimo/_server/api/save_app_config.py@@ -0,0 +1,51 @@+# Copyright 2023 Marimo. All rights reserved.+from __future__ import annotations++from dataclasses import dataclass+from typing import Any++import tornado.web++from marimo import _loggers+from marimo._ast import codegen+from marimo._server import sessions+from marimo._server.api.model import parse_raw+from marimo._server.api.status import HTTPStatus++LOGGER = _loggers.marimo_logger()+++@dataclass+class SaveAppConfiguration:+ # partial app config+ config: dict[str, Any]+++class SaveAppConfigurationHandler(tornado.web.RequestHandler):+ """Save app configuration to session manager."""++ @sessions.requires_edit+ def post(self) -> None:+ mgr = sessions.get_manager()+ args = parse_raw(self.request.body, SaveAppConfiguration)+ mgr.update_app_config(args.config)+ # Update the file with the latest app config+ # TODO(akshayka): Only change the `app = marimo.App` line (at top level+ # of file), instead of overwriting the whole file.+ app = mgr.load_app()+ if app is not None and mgr.filename is not None:+ codes = list(app._codes())+ names = list(app._names())++ # Try to save the app under the name `mgr.filename`+ contents = codegen.generate_filecontents(+ codes, names, config=mgr.app_config+ )+ try:+ with open(mgr.filename, "w", encoding="utf-8") as f:+ f.write(contents)+ except Exception as e:+ raise tornado.web.HTTPError(+ HTTPStatus.SERVER_ERROR,+ reason="Failed to save file: {0}".format(str(e)),+ ) from ediff --git a/marimo/_server/server.py b/marimo/_server/server.pyindex e2e3189d96..55fb071ea1 100644--- a/marimo/_server/server.py+++ b/marimo/_server/server.py@@ -111,12 +111,17 @@ class MainHandler(tornado.web.RequestHandler):"_", " "))+ user_config = get_configuration()+ app_config = (+ mgr.app_config.asdict() if mgr.app_config is not None else {}+ )self.render("index.html",title=title,filename=mgr.filename if mgr.filename is not None else "",mode="read" if mgr.mode == sessions.SessionMode.RUN else "edit",- config=json.dumps(get_configuration()),+ user_config=json.dumps(user_config),+ app_config=json.dumps(app_config),)@@ -223,6 +228,10 @@ async def start_server(r"/api/kernel/save_user_config/",api.SaveUserConfigurationHandler,),+ (+ r"/api/kernel/save_app_config/",+ api.SaveAppConfigurationHandler,+ ),(r"/(favicon\.ico)",tornado.web.StaticFileHandler,diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.pyindex 795ea780e5..0b3c5614c3 100644--- a/marimo/_server/sessions.py+++ b/marimo/_server/sessions.py@@ -21,7 +21,6 @@ import queueimport signalimport sysimport threading-from dataclasses import dataclassfrom enum import Enumfrom multiprocessing import connectionfrom typing import Any, Callable, Optional@@ -33,7 +32,7 @@ import tornado.websocketfrom marimo import _loggersfrom marimo._ast import codegen-from marimo._ast.cell import CellId_t+from marimo._ast.app import App, _AppConfigfrom marimo._messaging.message_types import KernelReady, serializefrom marimo._output.formatters.formatters import register_formattersfrom marimo._runtime import requests, runtime@@ -89,14 +88,21 @@ class IOSocketHandler(tornado.websocket.WebSocketHandler):mgr = get_manager()codes: tuple[str, ...]names: tuple[str, ...]- app_data = mgr.app_data()- if mgr.mode == SessionMode.EDIT:- codes = tuple(cell_data.code for cell_data in app_data.values())- names = tuple(cell_data.name for cell_data in app_data.values())+ app = mgr.load_app()+ if app is None:+ codes = ("",)+ names = ("__",)+ elif mgr.mode == SessionMode.EDIT:+ codes = tuple(+ cell_data.code for cell_data in app._cell_data.values()+ )+ names = tuple(+ cell_data.name for cell_data in app._cell_data.values()+ )else:# Don't send code to frontend in run mode- codes = tuple("" for _ in app_data)- names = tuple("" for _ in app_data)+ codes = tuple("" for _ in app._cell_data)+ names = tuple("" for _ in app._cell_data)self.write_op(op=KernelReady.name,data=serialize(KernelReady(codes=codes, names=names)),@@ -318,12 +324,6 @@ class SessionMode(Enum):RUN = 1-@dataclass-class CellData:- code: str- name: str--class SessionManager:"""Mapping from client session IDs to sessions.@@ -347,15 +347,21 @@ class SessionManager:self.development_mode = development_modeself.quiet = quietself.sessions: dict[str, Session] = {}+ self.app_config: Optional[_AppConfig]- def app_data(self) -> dict[CellId_t, CellData]:- # TODO(akshayka): remove assumption that cell ids are indices- codes, names = codegen.get_codes(self.filename)- cell_ids = [CellId_t(i) for i in range(len(codes))]- return {- cid: CellData(code, name)- for cid, code, name in zip(cell_ids, codes, names)- }+ if (app := self.load_app()) is not None:+ self.app_config = app._config+ else:+ self.app_config = None++ def load_app(self) -> Optional[App]:+ return codegen.get_app(self.filename)++ def update_app_config(self, config: dict[str, Any]) -> None:+ if self.app_config is not None:+ self.app_config.update(config)+ else:+ self.app_config = _AppConfig(**config)def rename(self, filename: Optional[str]) -> None:"""Register a change in filename.diff --git a/pyproject.toml b/pyproject.tomlindex 412250e17a..52744e9ced 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -43,13 +43,14 @@ dev = ["mypy~=1.4.1","ruff~=0.0.275",# For docs- "pypandoc",- "autoclasstoc",- "sphinx",- "sphinx-copybutton",- "sphinx-new-tab-link",+ "pypandoc~=1.11",+ "autoclasstoc~=1.6.0",+ # furo raises an error during docs build when sphinx is upgraded+ "sphinx==7.0.1",+ "sphinx-copybutton~=0.5.2",+ "sphinx-new-tab-link~=0.1.1","myst_parser~=2.0.0",- "furo"+ "furo==2023.5.20"][project.urls]