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
App chrome (#124)
Myles Scolnick6f72aace248c
diff --git a/frontend/package.json b/frontend/package.jsonindex 11df3388a9..07bf4b5700 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -74,6 +74,7 @@"react-dropzone": "^14.2.3","react-error-boundary": "^4.0.11","react-hook-form": "^7.46.1",+ "react-resizable-panels": "^0.0.53","react-use-event-hook": "^0.9.6","tailwind-merge": "^1.14.0","tailwindcss-animate": "^1.0.7",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex fae682c24e..2d695bac14 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -194,6 +194,9 @@ dependencies:react-hook-form:specifier: ^7.46.1version: 7.46.1([email protected])+ react-resizable-panels:+ specifier: ^0.0.53+ version: 0.0.53([email protected])([email protected])react-use-event-hook:specifier: ^0.9.6version: 0.9.6([email protected])@@ -11811,6 +11814,16 @@ packages:use-callback-ref: 1.3.0(@types/[email protected])([email protected])use-sidecar: 1.1.2(@types/[email protected])([email protected])+ resolution: {integrity: sha512-lGOJF0Hh5+Y+Usi7x8btmBTi+6CQV1/RKxnj6jVrzvJ9vLbftbSoJPzymOuX8ZCFimlEwP2AKsGtQVKG/KieHA==}+ peerDependencies:+ react: ^16.14.0 || ^17.0.0 || ^18.0.0+ react-dom: ^16.14.0 || ^17.0.0 || ^18.0.0+ dependencies:+ react: 18.2.0+ react-dom: 18.2.0([email protected])+ dev: false+resolution: {integrity: sha512-ZWj0fHEMyWkHzKYUr2Bs/4zU6XLmq9HsgBURm7g5pAVfyn49DgUiNgY2d4lXRlYSiCif9YBGpQleewkcqddc7g==}engines: {node: '>=10'}diff --git a/frontend/src/components/ui/tooltip.tsx b/frontend/src/components/ui/tooltip.tsxindex d5e5d66f7c..25d4984486 100644--- a/frontend/src/components/ui/tooltip.tsx+++ b/frontend/src/components/ui/tooltip.tsx@@ -31,16 +31,17 @@ const Tooltip: React.FC<content: React.ReactNode;usePortal?: boolean;children: React.ReactNode;+ side?: TooltipPrimitive.TooltipContentProps["side"];} & React.ComponentPropsWithoutRef<typeof TooltipRoot>-> = ({ content, children, usePortal = true, ...rootProps }) => (+> = ({ content, children, usePortal = true, side, ...rootProps }) => (<TooltipRoot disableHoverableContent={true} {...rootProps}><TooltipTrigger asChild={true}>{children}</TooltipTrigger>{usePortal ? (<TooltipPrimitive.TooltipPortal>- <TooltipContent>{content}</TooltipContent>+ <TooltipContent side={side}>{content}</TooltipContent></TooltipPrimitive.TooltipPortal>) : (- <TooltipContent>{content}</TooltipContent>+ <TooltipContent side={side}>{content}</TooltipContent>)}</TooltipRoot>);diff --git a/frontend/src/editor/chrome/panels/error-panel.tsx b/frontend/src/editor/chrome/panels/error-panel.tsxnew file mode 100644index 0000000000..9a45a3f1ab--- /dev/null+++ b/frontend/src/editor/chrome/panels/error-panel.tsx@@ -0,0 +1,27 @@+/* Copyright 2023 Marimo. All rights reserved. */+import React from "react";+import { useCells } from "../../../core/state/cells";+import { MarimoErrorOutput } from "../../output/MarimoErrorOutput";++export const ErrorsPanel: React.FC = (props) => {+ 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 (+ <div className="flex flex-col gap-3 px-2">+ {errors.map((error) => (+ <div key={error.cellId}>+ <MarimoErrorOutput key={error.cellId} errors={error.output.data} />+ </div>+ ))}+ </div>+ );+};diff --git a/frontend/src/editor/chrome/state.ts b/frontend/src/editor/chrome/state.tsnew file mode 100644index 0000000000..44386d5ea4--- /dev/null+++ b/frontend/src/editor/chrome/state.ts@@ -0,0 +1,68 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { createReducer } from "@/utils/createReducer";+import { atom, useAtomValue, useSetAtom } from "jotai";+import { useMemo } from "react";+import { PanelType } from "./types";++export interface ChromeState {+ selectedPanel: PanelType | undefined;+ isOpen: boolean;+ panelLocation: "left" | "bottom";+}++function initialState(): ChromeState {+ return {+ selectedPanel: undefined,+ isOpen: false,+ panelLocation: "left",+ };+}++const { reducer, createActions } = createReducer(initialState, {+ openApplication: (state, selectedPanel: PanelType) => ({+ ...state,+ selectedPanel,+ // If it was closed, open it+ // If it was open, keep it open unless it was the same application+ isOpen: state.isOpen ? state.selectedPanel !== selectedPanel : true,+ }),+ openPanel: (state) => ({ ...state, isOpen: true }),+ closePanel: (state) => ({ ...state, isOpen: false }),+ setIsOpen: (state, isOpen: boolean) => ({ ...state, isOpen }),+ changePanelLocation: (state, panelLocation: "left" | "bottom") => ({+ ...state,+ panelLocation,+ }),+});++const chromeAtom = atom<ChromeState>(initialState());+export const useChromeState = () => {+ const state = useAtomValue(chromeAtom);+ if (state.isOpen) {+ return state;+ }+ return {+ ...state,+ selectedPanel: undefined,+ };+};++export function useChromeActions() {+ const setState = useSetAtom(chromeAtom);++ return useMemo(() => {+ const actions = createActions((action) => {+ setState((state) => reducer(state, action));+ });+ return actions;+ }, [setState]);+}++/**+ * This is exported for testing purposes only.+ */+export const exportedForTesting = {+ reducer,+ createActions,+ initialState,+};diff --git a/frontend/src/editor/chrome/types.ts b/frontend/src/editor/chrome/types.tsnew file mode 100644index 0000000000..dc7af5dfa9--- /dev/null+++ b/frontend/src/editor/chrome/types.ts@@ -0,0 +1,2 @@+/* Copyright 2023 Marimo. All rights reserved. */+export type PanelType = "errors" | "variables";diff --git a/frontend/src/editor/chrome/wrapper/__tests__/storage.test.ts b/frontend/src/editor/chrome/wrapper/__tests__/storage.test.tsnew file mode 100644index 0000000000..ceb602b16b--- /dev/null+++ b/frontend/src/editor/chrome/wrapper/__tests__/storage.test.ts@@ -0,0 +1,45 @@+/* 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");+ });++ it("should store and retrieve items correctly when location is left", () => {+ const storage = createStorage("left");+ 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);+ });++ 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);+ });++ it("should return null when getting an item that does not exist", () => {+ const storage = createStorage("left");+ const retrieved = storage.getItem("nonexistent");+ expect(retrieved).toBeNull();+ });++ it("should return null when setting an item with invalid value", () => {+ const storage = createStorage("bottom");+ storage.setItem("test", "invalid");+ expect(storage.getItem("test")).toBeNull();+ });+});diff --git a/frontend/src/editor/chrome/wrapper/app-chrome.css b/frontend/src/editor/chrome/wrapper/app-chrome.cssnew file mode 100644index 0000000000..f0311b3a71--- /dev/null+++ b/frontend/src/editor/chrome/wrapper/app-chrome.css@@ -0,0 +1,23 @@+.resize-handle,+.resize-handle-collapsed {+ transition: 250ms linear background-color;+ background-color: var(--sage-3);+ outline: none;+}++.resize-handle.horizontal,+.resize-handle-collapsed.horizontal {+ height: 3px;+}++.resize-handle.vertical,+.resize-handle-collapsed.vertical {+ width: 3px;+}++.resize-handle:hover,+.resize-handle[data-resize-handle-active],+.resize-handle-collapsed:hover,+.resize-handle-collapsed[data-resize-handle-active] {+ background-color: var(--sage-11);+}diff --git a/frontend/src/editor/chrome/wrapper/app-chrome.tsx b/frontend/src/editor/chrome/wrapper/app-chrome.tsxnew file mode 100644index 0000000000..d57e866c0f--- /dev/null+++ b/frontend/src/editor/chrome/wrapper/app-chrome.tsx@@ -0,0 +1,88 @@+/* Copyright 2023 Marimo. All rights reserved. */+import React, { PropsWithChildren, useEffect } from "react";+import {+ PanelGroup,+ Panel,+ PanelResizeHandle,+ ImperativePanelHandle,+} 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";++export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {+ const { isOpen, selectedPanel, panelLocation } = useChromeState();+ const { setIsOpen } = useChromeActions();+ const sidebarRef = React.useRef<ImperativePanelHandle>(null);++ // sync sidebar+ useEffect(() => {+ if (!sidebarRef.current) {+ return;+ }++ const isCurrentlyCollapsed = sidebarRef.current.getCollapsed();+ if (isOpen && isCurrentlyCollapsed) {+ sidebarRef.current.expand();+ }+ if (!isOpen && !isCurrentlyCollapsed) {+ sidebarRef.current.collapse();+ }+ }, [isOpen]);++ const appBody = (+ <Panel+ id="app"+ key={`app-${panelLocation}`}+ style={{ height: "100%", overflow: "auto" }}+ >+ {children}+ </Panel>+ );++ const resizeHandle = (+ <PanelResizeHandle+ className={cn(+ "border-border",+ isOpen ? "resize-handle" : "resize-handle-collapsed",+ panelLocation === "left" ? "vertical" : "horizontal"+ )}+ />+ );++ const helperPane = (+ <Panel+ ref={sidebarRef}+ id="helper"+ key={`helper-${panelLocation}`}+ collapsedSize={0}+ collapsible={true}+ className="bg-[var(--sage-1)]"+ minSize={10}+ defaultSize={20}+ maxSize={30}+ onCollapse={(collapsed) => setIsOpen(!collapsed)}+ >+ {selectedPanel === "errors" && <ErrorsPanel />}+ </Panel>+ );++ return (+ <div className="flex flex-col flex-1 overflow-hidden">+ <PanelGroup+ key={panelLocation}+ autoSaveId={`marimo:chrome`}+ direction={panelLocation === "left" ? "horizontal" : "vertical"}+ storage={createStorage(panelLocation)}+ >+ {panelLocation === "left" ? helperPane : appBody}+ {resizeHandle}+ {panelLocation === "left" ? appBody : helperPane}+ </PanelGroup>+ <Footer />+ </div>+ );+};diff --git a/frontend/src/editor/chrome/wrapper/footer.tsx b/frontend/src/editor/chrome/wrapper/footer.tsxnew file mode 100644index 0000000000..366b9e58de--- /dev/null+++ b/frontend/src/editor/chrome/wrapper/footer.tsx@@ -0,0 +1,84 @@+/* 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 { cn } from "@/lib/utils";+import { useChromeActions, useChromeState } from "../state";++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+ selected={selectedPanel === "errors"}+ onClick={() => openApplication("errors")}+ >+ <XCircleIcon+ className={cn("h-4 w-4 mr-1", {+ "text-destructive": errors.length > 0,+ })}+ />+ {errors.length}+ </FooterItem>+ <FooterItem+ selected={selectedPanel === "variables"}+ onClick={() => openApplication("variables")}+ >+ <VariableIcon className={cn("h-4 w-4 mr-1")} />+ {errors.length}+ </FooterItem>+ <div className="mx-auto" />+ <FooterItem+ selected={panelLocation === "left"}+ onClick={() => changePanelLocation("left")}+ >+ <PanelLeftIcon className="h-4 w-4" />+ </FooterItem>+ <FooterItem+ selected={panelLocation === "bottom"}+ onClick={() => changePanelLocation("bottom")}+ >+ <PanelBottomIcon className="h-4 w-4" />+ </FooterItem>+ </footer>+ );+};++const FooterItem: React.FC<+ PropsWithChildren<{+ selected: boolean;+ onClick: () => void;+ }>+> = ({ children, onClick, selected }) => {+ 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>+ );+};diff --git a/frontend/src/editor/chrome/wrapper/storage.ts b/frontend/src/editor/chrome/wrapper/storage.tsnew file mode 100644index 0000000000..f12ac1f179--- /dev/null+++ b/frontend/src/editor/chrome/wrapper/storage.ts@@ -0,0 +1,56 @@+/* 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()]));++/**+ * This does 2 things:+ * - stores the storage in Cookies, so it persists across sessions and ports+ * - 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 (location === "left") {+ return item;+ }++ // flip+ try {+ const parsed = schema.parse(JSON.parse(item));+ return JSON.stringify(+ Objects.mapValues(parsed, (value) => {+ return value.reverse();+ })+ );+ } catch {+ return null;+ }+ },+ setItem(name, value) {+ if (location !== "left") {+ // flip+ try {+ const parsed = schema.parse(JSON.parse(value));+ value = JSON.stringify(+ Objects.mapValues(parsed, (value) => {+ return value.reverse();+ })+ );+ } catch {+ return null;+ }+ }++ return Cookies.set(name, value);+ },+ };+}diff --git a/frontend/src/stories/app-chrome.stories.tsx b/frontend/src/stories/app-chrome.stories.tsxnew file mode 100644index 0000000000..2b1fae02c3--- /dev/null+++ b/frontend/src/stories/app-chrome.stories.tsx@@ -0,0 +1,25 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { TooltipProvider } from "@/components/ui/tooltip";+import { AppChrome } from "@/editor/chrome/wrapper/app-chrome";+import type { Meta, StoryObj } from "@storybook/react";++const meta: Meta<typeof AppChrome> = {+ title: "AppChrome",+ component: AppChrome,+ args: {},+};++export default meta;+type Story = StoryObj;++export const Primary: Story = {+ render: () => (+ <TooltipProvider>+ <div className="flex top-0 left-0 right-0 bottom-0 absolute">+ <AppChrome>+ <div className="p-5">marimo application</div>+ </AppChrome>+ </div>+ </TooltipProvider>+ ),+};