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 TB and LR tree view to the dependency viewer (#1276)

Myles Scolnickfe1ebd383717
diff --git a/frontend/package.json b/frontend/package.json
index 179b1f39df..4e94cb4d37 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -24,6 +24,7 @@
"@codemirror/state": "^6.4.1",
"@codemirror/theme-one-dark": "^6.1.2",
"@codemirror/view": "^6.26.3",
+ "@dagrejs/dagre": "^1.1.2",
"@dnd-kit/core": "^6.1.0",
"@dnd-kit/modifiers": "^7.0.0",
"@dnd-kit/sortable": "^8.0.0",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index f08bbb3959..a5897d4af2 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -38,6 +38,9 @@ dependencies:
'@codemirror/view':
specifier: ^6.26.3
version: 6.26.3
+ '@dagrejs/dagre':
+ specifier: ^1.1.2
+ version: 1.1.2
'@dnd-kit/core':
specifier: ^6.1.0
@@ -2182,6 +2185,17 @@ packages:
postcss-selector-parser: 6.0.16
dev: true
+ /@dagrejs/[email protected]:
+ resolution: {integrity: sha512-F09dphqvHsbe/6C2t2unbmpr5q41BNPEfJCdn8Z7aEBpVSy/zFQ/b4SWsweQjWNsYMDvE2ffNUN8X0CeFsEGNw==}
+ dependencies:
+ '@dagrejs/graphlib': 2.2.2
+ dev: false
+
+ /@dagrejs/[email protected]:
+ resolution: {integrity: sha512-CbyGpCDKsiTg/wuk79S7Muoj8mghDGAESWGxcSyhHX5jD35vYMBZochYVFzlHxynpE9unpu6O+4ZuhrLxASsOg==}
+ engines: {node: '>17.0.0'}
+ dev: false
+
/@discoveryjs/[email protected]:
resolution: {integrity: sha512-dBVuXR082gk3jsFp7Rd/JI4kytwGHecnCoTtXFb7DB6CNHp4rg5k1bhg0nWdLGLnOV71lmDzGQaLMy8iPLY0pw==}
engines: {node: '>=10.0.0'}
diff --git a/frontend/src/components/dependency-graph/custom-node.tsx b/frontend/src/components/dependency-graph/custom-node.tsx
index 5483427aef..a5231e6248 100644
--- a/frontend/src/components/dependency-graph/custom-node.tsx
+++ b/frontend/src/components/dependency-graph/custom-node.tsx
@@ -2,12 +2,12 @@
import { TinyCode } from "@/components/editor/cell/TinyCode";
import { cn } from "@/utils/cn";
import { useAtomValue } from "jotai";
-import { memo } from "react";
+import React, { memo, useContext } from "react";
import { Handle, Position, useStore } from "reactflow";
import { CustomNodeProps, getNodeHeight } from "./elements";
import { displayCellName } from "@/core/cells/names";
-import { CellId } from "@/core/cells/ids";
import { useCellIds } from "@/core/cells/cells";
+import { LayoutDirection } from "./types";
function getWidth(canvasWidth: number) {
const minWidth = 100;
@@ -16,14 +16,25 @@ function getWidth(canvasWidth: number) {
return Math.min(Math.max(canvasWidth - padding * 2, minWidth), maxWidth);
}
+export const EdgeMarkerContext = React.createContext<LayoutDirection>("LR");
+
+const EQUALITY_CHECK = (
+ prevProps: CustomNodeProps,
+ nextProps: CustomNodeProps,
+) => {
+ const keys: Array<keyof CustomNodeProps> = ["data", "selected", "id"];
+ return keys.every((key) => prevProps[key] === nextProps[key]);
+};
+
export const CustomNode = memo((props: CustomNodeProps) => {
- const { data, selected, id } = props;
+ const { data, selected } = props; // must match the equality check
const cell = useAtomValue(data.atom);
- const cellIndex = useCellIds().indexOf(id as CellId);
+ const cellIndex = useCellIds().indexOf(cell.id);
const nonSelectedColor = "var(--gray-3)";
const selectedColor = "var(--gray-9)";
const color = selected ? selectedColor : nonSelectedColor;
const reactFlowWidth = useStore(({ width }) => width);
+ const edgeMarkers = useContext(EdgeMarkerContext);
const linesOfCode = cell.code.split("\n").length;
return (
@@ -31,13 +42,13 @@ export const CustomNode = memo((props: CustomNodeProps) => {
<Handle
type="target"
id="inputs"
- position={Position.Left}
+ position={edgeMarkers === "LR" ? Position.Left : Position.Top}
style={{ background: color }}
/>
<Handle
type="source"
id="inputs"
- position={Position.Left}
+ position={edgeMarkers === "LR" ? Position.Left : Position.Top}
style={{ background: color }}
/>
<div
@@ -47,7 +58,7 @@ export const CustomNode = memo((props: CustomNodeProps) => {
)}
style={{
height: getNodeHeight(linesOfCode),
- width: getWidth(reactFlowWidth),
+ width: data.forceWidth || getWidth(reactFlowWidth),
}}
>
<div className="text-muted-foreground font-semibold text-xs py-1 px-2 bg-muted border-b">
@@ -58,16 +69,20 @@ export const CustomNode = memo((props: CustomNodeProps) => {
<Handle
type="source"
id="outputs"
- position={Position.Right}
+ position={edgeMarkers === "LR" ? Position.Right : Position.Bottom}
style={{ background: color }}
/>
<Handle
type="target"
id="outputs"
- position={Position.Right}
+ position={edgeMarkers === "LR" ? Position.Right : Position.Bottom}
style={{ background: color }}
/>
</div>
);
-});
+}, EQUALITY_CHECK);
CustomNode.displayName = "CustomNode";
+
+export const nodeTypes = {
+ custom: CustomNode,
+};
diff --git a/frontend/src/components/dependency-graph/dependency-graph-minimap.tsx b/frontend/src/components/dependency-graph/dependency-graph-minimap.tsx
new file mode 100644
index 0000000000..b4f54f3542
--- /dev/null
+++ b/frontend/src/components/dependency-graph/dependency-graph-minimap.tsx
@@ -0,0 +1,190 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import ReactFlow, {
+ Node,
+ Edge,
+ useEdgesState,
+ useNodesState,
+ PanOnScrollMode,
+ useStore,
+ CoordinateExtent,
+} from "reactflow";
+
+import React, {
+ PropsWithChildren,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { nodeTypes } from "@/components/dependency-graph/custom-node";
+import { Variables } from "@/core/variables/types";
+import { CellId } from "@/core/cells/ids";
+import { CellData } from "@/core/cells/types";
+import { Atom } from "jotai";
+
+import { NodeData, VerticalElementsBuilder } from "./elements";
+import useEvent from "react-use-event-hook";
+import { scrollToCell } from "../editor/links/cell-link";
+import { GraphSelectionPanel } from "./panels";
+import { useFitToViewOnDimensionChange } from "./utils/useFitToViewOnDimensionChange";
+
+interface Props {
+ cellIds: CellId[];
+ variables: Variables;
+ cellAtoms: Array<Atom<CellData>>;
+}
+
+const elementsBuilder = new VerticalElementsBuilder();
+
+export const DependencyGraphMinimap: React.FC<PropsWithChildren<Props>> = ({
+ cellIds,
+ variables,
+ cellAtoms,
+ children,
+}) => {
+ // State
+ const { nodes: initialNodes, edges: allEdges } =
+ elementsBuilder.createElements(cellIds, cellAtoms, variables, false);
+ const [edges, setEdges] = useEdgesState([]);
+ const [nodes, setNodes] = useNodesState(initialNodes);
+ const [selectedNodeId, setSelectedNodeId] = useState<CellId>();
+ const [selectedEdge, setSelectedEdge] = useState<Edge>();
+ const hasRenderer = useRef(false);
+
+ // Subscriptions
+ useFitToViewOnDimensionChange();
+ const height = useStore(({ height }) => height);
+
+ // If the cellIds change, update the nodes.
+ const syncChanges = useEvent(
+ (elements: { nodes: Array<Node<NodeData>>; edges: Edge[] }) => {
+ setNodes(elements.nodes);
+ setEdges([]);
+ },
+ );
+
+ // If the cellIds change, update the nodes.
+ // Only on the second render, because the first render is the initial render.
+ useEffect(() => {
+ if (!hasRenderer.current) {
+ hasRenderer.current = true;
+ return;
+ }
+ syncChanges(
+ elementsBuilder.createElements(cellIds, cellAtoms, variables, false),
+ );
+ }, [cellIds, variables, cellAtoms, syncChanges]);
+
+ // If the selected node changes, update the edges.
+ useEffect(() => {
+ if (selectedNodeId) {
+ const selectedEdges = allEdges.filter((edge) => {
+ const { source, target, data } = edge;
+
+ return (
+ (source === selectedNodeId && data.direction === "outputs") ||
+ (target === selectedNodeId && data.direction === "inputs")
+ );
+ });
+ setEdges(selectedEdges);
+ }
+ }, [selectedNodeId, setEdges, allEdges]);
+
+ const translateExtent = useTranslateExtent(nodes, height);
+
+ const renderGraphSelectionPanel = () => {
+ if (selectedEdge) {
+ return (
+ <GraphSelectionPanel
+ selection={{
+ type: "edge",
+ source: selectedEdge.source as CellId,
+ target: selectedEdge.target as CellId,
+ }}
+ variables={variables}
+ edges={edges}
+ />
+ );
+ }
+ if (selectedNodeId) {
+ return (
+ <GraphSelectionPanel
+ selection={{ type: "node", id: selectedNodeId }}
+ variables={variables}
+ edges={edges}
+ />
+ );
+ }
+
+ return null;
+ };
+
+ return (
+ <ReactFlow
+ nodes={nodes}
+ edges={edges}
+ nodeTypes={nodeTypes}
+ translateExtent={translateExtent}
+ onNodeClick={(_event, node) => {
+ const id = node.id;
+ setSelectedNodeId(id as CellId);
+ setSelectedEdge(undefined);
+ setEdges([]);
+ }}
+ onNodeDoubleClick={(_event, node) => {
+ scrollToCell(node.id as CellId, "focus");
+ }}
+ onEdgeClick={(_event, edge) => {
+ setSelectedEdge(edge);
+ }}
+ // On
+ snapToGrid={true}
+ fitView={true}
+ elementsSelectable={true}
+ // Off
+ minZoom={1}
+ maxZoom={1}
+ draggable={false}
+ panOnScrollMode={PanOnScrollMode.Vertical}
+ zoomOnDoubleClick={false}
+ nodesDraggable={false}
+ nodesConnectable={false}
+ nodesFocusable={false}
+ edgesFocusable={false}
+ selectNodesOnDrag={false}
+ panOnDrag={false}
+ preventScrolling={false}
+ zoomOnPinch={false}
+ panOnScroll={true}
+ autoPanOnNodeDrag={false}
+ autoPanOnConnect={false}
+ >
+ {renderGraphSelectionPanel()}
+ {children}
+ </ReactFlow>
+ );
+};
+
+// Limit the extent of the graph to just the visible nodes.
+// The top node and bottom node can be scrolled to the middle of the graph.
+function useTranslateExtent(nodes: Node[], height: number): CoordinateExtent {
+ const PADDING_Y = 10;
+
+ return useMemo<CoordinateExtent>(() => {
+ const top = nodes.reduce(
+ (top, { position }) => Math.min(top, position.y - height / 2 - PADDING_Y),
+ Number.POSITIVE_INFINITY,
+ );
+
+ const bottom = nodes.reduce(
+ (bottom, { position }) =>
+ Math.max(bottom, position.y + height / 2 + PADDING_Y),
+ Number.NEGATIVE_INFINITY,
+ );
+
+ return [
+ [Number.NEGATIVE_INFINITY, top],
+ [Number.POSITIVE_INFINITY, bottom],
+ ];
+ }, [nodes, height]);
+}
diff --git a/frontend/src/components/dependency-graph/dependency-graph-tree.tsx b/frontend/src/components/dependency-graph/dependency-graph-tree.tsx
new file mode 100644
index 0000000000..ebd6d7585d
--- /dev/null
+++ b/frontend/src/components/dependency-graph/dependency-graph-tree.tsx
@@ -0,0 +1,135 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import ReactFlow, {
+ useEdgesState,
+ useNodesState,
+ Controls,
+ Background,
+ BackgroundVariant,
+ Node,
+ Edge,
+} from "reactflow";
+
+import React, { PropsWithChildren, useEffect, useMemo, useState } from "react";
+import {
+ EdgeMarkerContext,
+ nodeTypes,
+} from "@/components/dependency-graph/custom-node";
+import { Variables } from "@/core/variables/types";
+import { CellId } from "@/core/cells/ids";
+import { CellData } from "@/core/cells/types";
+import { Atom } from "jotai";
+
+import { NodeData, TreeElementsBuilder } from "./elements";
+import { layoutElements } from "./utils/layout";
+import { GraphSelection, GraphSettings, LayoutDirection } from "./types";
+import useEvent from "react-use-event-hook";
+import { scrollToCell } from "../editor/links/cell-link";
+import { GraphSelectionPanel } from "./panels";
+import { useFitToViewOnDimensionChange } from "./utils/useFitToViewOnDimensionChange";
+
+interface Props {
+ cellIds: CellId[];
+ variables: Variables;
+ cellAtoms: Array<Atom<CellData>>;
+ layoutDirection: LayoutDirection;
+ settings: GraphSettings;
+}
+
+const elementsBuilder = new TreeElementsBuilder();
+
+export const DependencyGraphTree: React.FC<PropsWithChildren<Props>> = ({
+ cellIds,
+ variables,
+ cellAtoms,
+ children,
+ layoutDirection,
+ settings,
+}) => {
+ const initial = useMemo(() => {
+ let elements = elementsBuilder.createElements(
+ cellIds,
+ cellAtoms,
+ variables,
+ settings.hidePureMarkdown,
+ );
+ elements = layoutElements(elements.nodes, elements.edges, {
+ direction: layoutDirection,
+ });
+
+ return elements;
+ // Only run once
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ const [nodes, setNodes, onNodesChange] = useNodesState(initial.nodes);
+ const [edges, setEdges, onEdgesChange] = useEdgesState(initial.edges);
+
+ const syncChanges = useEvent(
+ (elements: { nodes: Array<Node<NodeData>>; edges: Edge[] }) => {
+ // Layout the elements
+ const result = layoutElements(elements.nodes, elements.edges, {
+ direction: layoutDirection,
+ });
+ setNodes(result.nodes);
+ setEdges(result.edges);
+ },
+ );
+
+ // If the cellIds change, update the nodes.
+ useEffect(() => {
+ syncChanges(
+ elementsBuilder.createElements(
+ cellIds,
+ cellAtoms,
+ variables,
+ settings.hidePureMarkdown,
+ ),
+ );
+ }, [cellIds, variables, cellAtoms, syncChanges, settings.hidePureMarkdown]);
+
+ const [selection, setSelection] = useState<GraphSelection>();
+ useFitToViewOnDimensionChange();
+
+ return (
+ <EdgeMarkerContext.Provider value={layoutDirection}>
+ <ReactFlow
+ nodes={nodes}
+ edges={edges}
+ nodeTypes={nodeTypes}
+ minZoom={0.2}
+ fitViewOptions={{
+ minZoom: 0.5,
+ maxZoom: 1.5,
+ }}
+ onNodeClick={(_event, node) => {
+ setSelection({ type: "node", id: node.id as CellId });
+ }}
+ onEdgeClick={(_event, edge) => {
+ const { source, target } = edge;
+ setSelection({
+ type: "edge",
+ source: source as CellId,
+ target: target as CellId,
+ });
+ }}
+ onNodeDoubleClick={(_event, node) => {
+ scrollToCell(node.id as CellId, "focus");
+ }}
+ fitView={true}
+ onNodesChange={onNodesChange}
+ onEdgesChange={onEdgesChange}
+ zoomOnDoubleClick={false}
+ nodesConnectable={false}
+ >
+ <Background color="#ccc" variant={BackgroundVariant.Dots} />
+ <Controls position="bottom-right" showInteractive={false} />
+ <GraphSelectionPanel
+ selection={selection}
+ variables={variables}
+ edges={edges}
+ />
+ {children}
+ </ReactFlow>
+ </EdgeMarkerContext.Provider>
+ );
+};
diff --git a/frontend/src/components/dependency-graph/dependency-graph.css b/frontend/src/components/dependency-graph/dependency-graph.css
index d2543f8930..317985b749 100644
--- a/frontend/src/components/dependency-graph/dependency-graph.css
+++ b/frontend/src/components/dependency-graph/dependency-graph.css
@@ -9,3 +9,7 @@
.react-flow__handle.react-flow__handle {
@apply border-background;
}
+
+.react-flow__controls.react-flow__controls {
+ bottom: 8px;
+}
diff --git a/frontend/src/components/dependency-graph/dependency-graph.tsx b/frontend/src/components/dependency-graph/dependency-graph.tsx
index bf6dc8ad07..5b4a161ab3 100644
--- a/frontend/src/components/dependency-graph/dependency-graph.tsx
+++ b/frontend/src/components/dependency-graph/dependency-graph.tsx
@@ -1,158 +1,66 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import ReactFlow, {
- Node,
- Edge,
- ReactFlowProvider,
- useEdgesState,
- useNodesState,
- PanOnScrollMode,
- useStore,
- useReactFlow,
- CoordinateExtent,
-} from "reactflow";
+import { ReactFlowProvider } from "reactflow";
-import React, { useEffect, useMemo, useState } from "react";
-import { CustomNode } from "@/components/dependency-graph/custom-node";
+import React from "react";
import { Variables } from "@/core/variables/types";
import { CellId } from "@/core/cells/ids";
import { CellData } from "@/core/cells/types";
-import { Atom } from "jotai";
+import { Atom, atom, useAtom } from "jotai";
+
+import { GraphLayoutView, GraphSettings } from "./types";
+import { DependencyGraphMinimap } from "./dependency-graph-minimap";
+import { GraphToolbar } from "./panels";
+import { DependencyGraphTree } from "./dependency-graph-tree";
import "reactflow/dist/style.css";
import "./dependency-graph.css";
-import { useDebouncedCallback } from "@/hooks/useDebounce";
-import { createElements } from "./elements";
interface Props {
cellIds: CellId[];
variables: Variables;
cellAtoms: Array<Atom<CellData>>;
+ children?: React.ReactNode;
}
-const nodeTypes = {
- custom: CustomNode,
-};
+const graphViewAtom = atom<GraphLayoutView>("_minimap_");
+const graphViewSettings = atom<GraphSettings>({
+ hidePureMarkdown: true,
+});
export const DependencyGraph: React.FC<Props> = (props) => {
- return (
- <ReactFlowProvider>
- <DependencyGraphInternal {...props} />
- </ReactFlowProvider>
- );
-};
-
-const DependencyGraphInternal: React.FC<Props> = ({
- cellIds,
- variables,
- cellAtoms,
-}) => {
- const { nodes: initialNodes, edges: initialEdges } = createElements(
- cellIds,
- cellAtoms,
- variables,
- );
- const [edges, setEdges] = useEdgesState([]);
- const [nodes, setNodes] = useNodesState(initialNodes);
-
- const [allEdges, setAllEdges] = useState<Edge[]>(initialEdges);
- const [selectedNodeId, setSelectedNodeId] = useState<string>();
-
- // If the cellIds change, update the nodes.
- useEffect(() => {
- const { nodes, edges } = createElements(cellIds, cellAtoms, variables);
- setNodes(nodes);
- setAllEdges(edges);
- setEdges([]);
- }, [cellIds, setNodes, variables, cellAtoms, setAllEdges, setEdges]);
-
- // If the selected node changes, update the edges.
- useEffect(() => {
- if (selectedNodeId) {
- const selectedEdges = allEdges.filter((edge) => {
- const { source, target, data } = edge;
-
- return (
- (source === selectedNodeId && data.direction === "outputs") ||
- (target === selectedNodeId && data.direction === "inputs")
- );
- });
- setEdges(selectedEdges);
+ const [layoutDirection, setLayoutDirection] = useAtom(graphViewAtom);
+ const [settings, setSettings] = useAtom(graphViewSettings);
+
+ const renderGraph = () => {
+ if (layoutDirection === "_minimap_") {
+ return (
+ <DependencyGraphMinimap {...props}>
+ <GraphToolbar
+ settings={settings}
+ onSettingsChange={setSettings}
+ view={layoutDirection}
+ onChange={setLayoutDirection}
+ />
+ </DependencyGraphMinimap>
+ );
}
- }, [selectedNodeId, setEdges, allEdges]);
-
- const instance = useReactFlow();
- const [width, height] = useStore(({ width, height }) => [width, height]);
-
- const debounceFitView = useDebouncedCallback(() => {
- instance.fitView({ duration: 100 });
- }, 100);
-
- // When the window is resized, fit the view to the graph.
- useEffect(() => {
- debounceFitView();
- }, [width, height, debounceFitView]);
-
- const translateExtent = useTranslateExtent(nodes, height);
+ return (
+ <DependencyGraphTree
+ {...props}
+ settings={settings}
+ layoutDirection={layoutDirection}
+ >
+ <GraphToolbar
+ settings={settings}
+ onSettingsChange={setSettings}
+ view={layoutDirection}
+ onChange={setLayoutDirection}
+ />
+ </DependencyGraphTree>
+ );
+ };
return (
- <ReactFlow
- nodes={nodes}
- edges={edges}
- nodeTypes={nodeTypes}
- translateExtent={translateExtent}
- onNodeClick={(_event, node) => {
- const id = node.id;
- if (id === selectedNodeId) {
- return;
- }
- setSelectedNodeId(id);
- setEdges([]);
- }}
- // On
- snapToGrid={true}
- fitView={true}
- elementsSelectable={true}
- // Off
- minZoom={1}
- maxZoom={1}
- draggable={false}
- panOnScrollMode={PanOnScrollMode.Vertical}
- zoomOnDoubleClick={false}
- nodesDraggable={false}
- nodesConnectable={false}
- nodesFocusable={false}
- edgesFocusable={false}
- selectNodesOnDrag={false}
- panOnDrag={false}
- preventScrolling={false}
- zoomOnPinch={false}
- panOnScroll={true}
- autoPanOnNodeDrag={false}
- autoPanOnConnect={false}
- />
+ <ReactFlowProvider key={layoutDirection}>{renderGraph()}</ReactFlowProvider>
);
};
-
-// Limit the extent of the graph to just the visible nodes.
-// The top node and bottom node can be scrolled to the middle of the graph.
-function useTranslateExtent(nodes: Node[], height: number): CoordinateExtent {
- const PADDING_Y = 10;
-
- return useMemo<CoordinateExtent>(() => {
- const top = nodes.reduce(
- (top, { position }) => Math.min(top, position.y - height / 2 - PADDING_Y),
- Number.POSITIVE_INFINITY,
- );
-
- const bottom = nodes.reduce(
- (bottom, { position }) =>
- Math.max(bottom, position.y + height / 2 + PADDING_Y),
- Number.NEGATIVE_INFINITY,
- );
-
- return [
- [Number.NEGATIVE_INFINITY, top],
- [Number.POSITIVE_INFINITY, bottom],
- ];
- }, [nodes, height]);
-}
diff --git a/frontend/src/components/dependency-graph/elements.ts b/frontend/src/components/dependency-graph/elements.ts
index e18c9304dd..aa9270644e 100644
--- a/frontend/src/components/dependency-graph/elements.ts
+++ b/frontend/src/components/dependency-graph/elements.ts
@@ -6,9 +6,11 @@ import { store } from "@/core/state/jotai";
import { Variables } from "@/core/variables/types";
import { Edge, MarkerType, Node, NodeProps } from "reactflow";
import { Atom } from "jotai";
+import { Arrays } from "@/utils/arrays";
export interface NodeData {
atom: Atom<CellData>;
+ forceWidth?: number;
}
export type CustomNodeProps = NodeProps<NodeData>;
@@ -17,72 +19,167 @@ export function getNodeHeight(linesOfCode: number) {
return Math.min(linesOfCode * LINE_HEIGHT + 35, 200);
}
-/* Copyright 2024 Marimo. All rights reserved. */
-function createEdge(source: CellId, target: CellId, direction: string): Edge {
- return {
- type: "smoothstep",
- pathOptions: {
- offset: 20,
- borderRadius: 100,
- },
- data: {
- direction: direction,
- },
- // animated: true,
- markerEnd: {
- type: MarkerType.Arrow,
- },
- id: `${source}-${target}-${direction}`,
- source: source,
- sourceHandle: direction,
- targetHandle: direction,
- target: target,
- };
+interface ElementsBuilder {
+ createElements: (
+ cellIds: CellId[],
+ cellAtoms: Array<Atom<CellData>>,
+ variables: Variables,
+ hidePureMarkdown: boolean,
+ ) => { nodes: Array<Node<NodeData>>; edges: Edge[] };
}
-function createNode(
- id: string,
- atom: Atom<CellData>,
- prevY: number,
-): Node<NodeData> {
- const linesOfCode = store.get(atom).code.trim().split("\n").length;
- const height = getNodeHeight(linesOfCode);
- return {
- id: id,
- data: { atom },
- width: 250,
- type: "custom",
- height: height,
- position: { x: 0, y: prevY + 20 },
- };
+export class VerticalElementsBuilder implements ElementsBuilder {
+ private createEdge(source: CellId, target: CellId, direction: string): Edge {
+ return {
+ type: "smoothstep",
+ pathOptions: {
+ offset: 20,
+ borderRadius: 100,
+ },
+ data: {
+ direction: direction,
+ },
+ markerEnd: {
+ type: MarkerType.Arrow,
+ },
+ id: `${source}-${target}-${direction}`,
+ source: source,
+ sourceHandle: direction,
+ targetHandle: direction,
+ target: target,
+ };
+ }
+
+ private createNode(
+ id: string,
+ atom: Atom<CellData>,
+ prevY: number,
+ ): Node<NodeData> {
+ const linesOfCode = store.get(atom).code.trim().split("\n").length;
+ const height = getNodeHeight(linesOfCode);
+ return {
+ id: id,
+ data: { atom },
+ width: 250,
+ type: "custom",
+ height: height,
+ position: { x: 0, y: prevY + 20 },
+ };
+ }
+
+ createElements(
+ cellIds: CellId[],
+ cellAtoms: Array<Atom<CellData>>,
+ variables: Variables,
+ hidePureMarkdown: boolean,
+ ) {
+ let prevY = 0;
+ const nodes: Array<Node<NodeData>> = [];
+ const edges: Edge[] = [];
+ for (const [cellId, cellAtom] of Arrays.zip(cellIds, cellAtoms)) {
+ const node = this.createNode(cellId, cellAtom, prevY);
+ nodes.push(node);
+ prevY = node.position.y + (node.height || 0);
+ }
+
+ const visited = new Set<string>();
+ for (const variable of Object.values(variables)) {
+ const { declaredBy, usedBy } = variable;
+ for (const fromId of declaredBy) {
+ for (const toId of usedBy) {
+ const key = `${fromId}-${toId}`;
+ if (visited.has(key)) {
+ continue;
+ }
+ visited.add(key);
+ edges.push(
+ this.createEdge(fromId, toId, "inputs"),
+ this.createEdge(fromId, toId, "outputs"),
+ );
+ }
+ }
+ }
+ return { nodes, edges };
+ }
}
-export function createElements(
- cellIds: CellId[],
- cellAtoms: Array<Atom<CellData>>,
- variables: Variables,
-) {
- let prevY = 0;
- const nodes: Array<Node<NodeData>> = [];
- const edges: Edge[] = [];
- let index = 0;
- for (const cellId of cellIds) {
- const node = createNode(cellId, cellAtoms[index], prevY);
- nodes.push(node);
- prevY = node.position.y + (node.height || 0);
- index++;
+export class TreeElementsBuilder implements ElementsBuilder {
+ private createEdge(source: CellId, target: CellId): Edge {
+ return {
+ animated: true,
+ markerEnd: {
+ type: MarkerType.ArrowClosed,
+ },
+ id: `${source}-${target}`,
+ // Make thicker
+ style: { strokeWidth: 2 },
+ source: source,
+ sourceHandle: "outputs",
+ targetHandle: "inputs",
+ target: target,
+ };
+ }
+
+ private createNode(id: string, atom: Atom<CellData>): Node<NodeData> {
+ const linesOfCode = store.get(atom).code.trim().split("\n").length;
+ const height = getNodeHeight(linesOfCode);
+ return {
+ id: id,
+ data: { atom, forceWidth: 300 },
+ width: 300,
+ type: "custom",
+ height: height,
+ position: { x: 0, y: 0 },
+ };
}
- for (const variable of Object.values(variables)) {
- const { declaredBy, usedBy } = variable;
- for (const fromId of declaredBy) {
- for (const toId of usedBy) {
- edges.push(
- createEdge(fromId, toId, "inputs"),
- createEdge(fromId, toId, "outputs"),
- );
+ createElements(
+ cellIds: CellId[],
+ cellAtoms: Array<Atom<CellData>>,
+ variables: Variables,
+ hidePureMarkdown: boolean,
+ ) {
+ const nodes: Array<Node<NodeData>> = [];
+ const edges: Edge[] = [];
+
+ const nodesWithEdges = new Set<CellId>();
+ const visited = new Set<string>();
+
+ for (const variable of Object.values(variables)) {
+ // Skip marimo, since likely every cell uses it
+ if (variable.value === "marimo" && variable.name === "mo") {
+ continue;
+ }
+
+ const { declaredBy, usedBy } = variable;
+ for (const fromId of declaredBy) {
+ for (const toId of usedBy) {
+ const key = `${fromId}-${toId}`;
+ if (visited.has(key)) {
+ continue;
+ }
+ visited.add(key);
+ nodesWithEdges.add(fromId);
+ nodesWithEdges.add(toId);
+ edges.push(this.createEdge(fromId, toId));
+ }
}
}
+
+ for (const [cellId, cellAtom] of Arrays.zip(cellIds, cellAtoms)) {
+ // Show every cell
+ if (!hidePureMarkdown) {
+ nodes.push(this.createNode(cellId, cellAtom));
+ }
+
+ const hasEdge = nodesWithEdges.has(cellId);
+ const isMarkdown = store.get(cellAtom).code.trim().startsWith("mo.md");
+ // Show only cells with edges or non-markdown cells
+ if (hasEdge || !isMarkdown) {
+ nodes.push(this.createNode(cellId, cellAtom));
+ }
+ }
+
+ return { nodes, edges };
}
- return { nodes, edges };
}
diff --git a/frontend/src/components/dependency-graph/panels.tsx b/frontend/src/components/dependency-graph/panels.tsx
new file mode 100644
index 0000000000..bbc38c2965
--- /dev/null
+++ b/frontend/src/components/dependency-graph/panels.tsx
@@ -0,0 +1,194 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import React, { memo } from "react";
+import { Edge, Panel } from "reactflow";
+import { Button } from "../ui/button";
+import {
+ Rows3Icon,
+ NetworkIcon,
+ ArrowRightFromLineIcon,
+ ArrowRightIcon,
+ ArrowRightToLineIcon,
+ WorkflowIcon,
+ SquareFunction,
+ SettingsIcon,
+} from "lucide-react";
+import { GraphLayoutView, GraphSelection, GraphSettings } from "./types";
+import { CellId } from "@/core/cells/ids";
+import { CellLink } from "../editor/links/cell-link";
+import { CellLinkList } from "../editor/links/cell-link-list";
+import { VariableName } from "../variables/common";
+import { Variables } from "@/core/variables/types";
+import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
+import { Checkbox } from "../ui/checkbox";
+import { Label } from "../ui/label";
+
+interface Props {
+ view: GraphLayoutView;
+ onChange: (view: GraphLayoutView) => void;
+ settings: GraphSettings;
+ onSettingsChange: (settings: GraphSettings) => void;
+}
+
+export const GraphToolbar: React.FC<Props> = memo(
+ ({ onChange, view, settings, onSettingsChange }) => {
+ const handleSettingChange = <K extends keyof GraphSettings>(
+ key: K,
+ value: GraphSettings[K],
+ ) => {
+ onSettingsChange({ ...settings, [key]: value });
+ };
+
+ const settingsButton = (
+ <Popover>
+ <PopoverTrigger asChild={true}>
+ <Button variant="text" size="xs">
+ <SettingsIcon className="w-4 h-4" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-auto p-2 text-muted-foreground">
+ <div className="font-semibold pb-4">Settings</div>
+ <div className="flex items-center gap-2">
+ <Checkbox
+ data-testid="hide-pure-markdown-checkbox"
+ id="hide-pure-markdown"
+ checked={settings.hidePureMarkdown}
+ onCheckedChange={(checked) =>
+ handleSettingChange("hidePureMarkdown", Boolean(checked))
+ }
+ />
+ <Label htmlFor="hide-pure-markdown">Hide pure markdown</Label>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+
+ return (
+ <Panel position="top-right" className="flex flex-col items-end gap-2">
+ <div className="flex gap-2">
+ <Button
+ variant="outline"
+ className="bg-background"
+ aria-selected={view === "_minimap_"}
+ size="xs"
+ onClick={() => onChange("_minimap_")}
+ >
+ <Rows3Icon className="w-4 h-4 mr-1" />
+ Mini Map
+ </Button>
+ <Button
+ variant="outline"
+ className="bg-background"
+ aria-selected={view === "TB"}
+ size="xs"
+ onClick={() => onChange("TB")}
+ >
+ <NetworkIcon className="w-4 h-4 mr-1" />
+ Vertical Tree
+ </Button>
+ <Button
+ variant="outline"
+ className="bg-background"
+ aria-selected={view === "LR"}
+ size="xs"
+ onClick={() => onChange("LR")}
+ >
+ <NetworkIcon className="w-4 h-4 mr-1 transform -rotate-90" />{" "}
+ Horizontal Tree
+ </Button>
+ </div>
+ {view !== "_minimap_" && settingsButton}
+ </Panel>
+ );
+ },
+);
+GraphToolbar.displayName = "GraphToolbar";
+
+export const GraphSelectionPanel: React.FC<{
+ selection: GraphSelection;
+ edges: Edge[];
+ variables: Variables;
+}> = memo(({ selection, edges, variables }) => {
+ if (!selection) {
+ return null;
+ }
+
+ const renderSelection = () => {
+ if (selection.type === "node") {
+ const inputs = edges.flatMap((edge) =>
+ edge.target === selection.id ? [edge.source as CellId] : [],
+ );
+ const outputs = edges.flatMap((edge) =>
+ edge.source === selection.id ? [edge.target as CellId] : [],
+ );
+ return (
+ <>
+ <div className="font-bold py-2 flex items-center gap-2 border-b px-3">
+ <SquareFunction className="w-5 h-5" />
+ <CellLink cellId={selection.id} />
+ </div>
+ <div className="text-sm flex flex-col p-3 flex-1 justify-center">
+ <div className="flex items-center gap-2">
+ <span title="Inputs">
+ <ArrowRightToLineIcon className="w-4 h-4 mr-2" />
+ </span>
+ <CellLinkList maxCount={3} cellIds={inputs} />
+ </div>
+ <div className="flex items-center gap-2">
+ <span title="Outputs">
+ <ArrowRightFromLineIcon className="w-4 h-4 mr-2" />
+ </span>
+ <CellLinkList maxCount={3} cellIds={outputs} />
+ </div>
+ </div>
+ </>
+ );
+ }
+
+ if (selection.type === "edge") {
+ const variableUsed = Object.values(variables).filter(
+ (variable) =>
+ variable.declaredBy.includes(selection.source) &&
+ variable.usedBy.includes(selection.target),
+ );
+ return (
+ <>
+ <div className="font-bold py-2 flex items-center gap-2 border-b px-3">
+ <WorkflowIcon className="w-4 h-4" />
+ <CellLink cellId={selection.source} />
+ <ArrowRightIcon className="w-4 h-4" />
+ <CellLink cellId={selection.target} />
+ </div>
+ <div className="grid grid-cols-4 gap-3 max-w-[350px] items-center text-sm p-3 flex-1">
+ {variableUsed.map((variable) => (
+ <React.Fragment key={variable.name}>
+ <VariableName
+ declaredBy={variable.declaredBy}
+ name={variable.name}
+ />
+ <div className="text-ellipsis overflow-hidden whitespace-nowrap text-foreground/60 font-mono">
+ {variable.dataType}
+ </div>
+ <div
+ className="text-ellipsis overflow-hidden whitespace-nowrap col-span-2"
+ title={variable.value}
+ >
+ {variable.value}
+ </div>
+ </React.Fragment>
+ ))}
+ </div>
+ </>
+ );
+ }
+ };
+
+ return (
+ <Panel position="bottom-left">
+ <div className="min-h-[100px] shadow-md rounded-md border border-primary/40 my-4 min-w-[200px] bg-[var(--slate-1)] text-muted-foreground/80 flex flex-col">
+ {renderSelection()}
+ </div>
+ </Panel>
+ );
+});
+
+GraphSelectionPanel.displayName = "GraphSelectionPanel";
diff --git a/frontend/src/components/dependency-graph/types.ts b/frontend/src/components/dependency-graph/types.ts
new file mode 100644
index 0000000000..c115505727
--- /dev/null
+++ b/frontend/src/components/dependency-graph/types.ts
@@ -0,0 +1,21 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { CellId } from "@/core/cells/ids";
+
+export type LayoutDirection = "TB" | "LR";
+export type GraphLayoutView = LayoutDirection | "_minimap_";
+
+export type GraphSelection =
+ | {
+ type: "node";
+ id: CellId;
+ }
+ | {
+ type: "edge";
+ source: CellId;
+ target: CellId;
+ }
+ | undefined;
+
+export interface GraphSettings {
+ hidePureMarkdown: boolean;
+}
diff --git a/frontend/src/components/dependency-graph/utils/changes.ts b/frontend/src/components/dependency-graph/utils/changes.ts
new file mode 100644
index 0000000000..100defa65f
--- /dev/null
+++ b/frontend/src/components/dependency-graph/utils/changes.ts
@@ -0,0 +1,54 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import {
+ Node,
+ NodeAddChange,
+ NodeRemoveChange,
+ Edge,
+ EdgeAddChange,
+ EdgeRemoveChange,
+} from "reactflow";
+
+export function getNodeChanges(
+ prevNodes: Node[],
+ nextNodes: Node[],
+): Array<NodeAddChange | NodeRemoveChange> {
+ const changes: Array<NodeAddChange | NodeRemoveChange> = [];
+ const prevNodeIds = new Set(prevNodes.map((node) => node.id));
+ const nextNodeIds = new Set(nextNodes.map((node) => node.id));
+
+ for (const node of prevNodes) {
+ if (!nextNodeIds.has(node.id)) {
+ changes.push({ type: "remove", id: node.id });
+ }
+ }
+
+ for (const node of nextNodes) {
+ if (!prevNodeIds.has(node.id)) {
+ changes.push({ type: "add", item: node });
+ }
+ }
+
+ return changes;
+}
+export function getEdgeChanges(
+ prevEdges: Edge[],
+ nextEdges: Edge[],
+): Array<EdgeAddChange | EdgeRemoveChange> {
+ const changes: Array<EdgeAddChange | EdgeRemoveChange> = [];
+ const prevEdgeIds = new Set(prevEdges.map((edge) => edge.id));
+ const nextEdgeIds = new Set(nextEdges.map((edge) => edge.id));
+
+ for (const edge of prevEdges) {
+ if (!nextEdgeIds.has(edge.id)) {
+ changes.push({ type: "remove", id: edge.id });
+ }
+ }
+
+ for (const edge of nextEdges) {
+ if (!prevEdgeIds.has(edge.id)) {
+ changes.push({ type: "add", item: edge });
+ }
+ }
+
+ return changes;
+}
diff --git a/frontend/src/components/dependency-graph/utils/layout.ts b/frontend/src/components/dependency-graph/utils/layout.ts
new file mode 100644
index 0000000000..15e05a3d4a
--- /dev/null
+++ b/frontend/src/components/dependency-graph/utils/layout.ts
@@ -0,0 +1,41 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { graphlib, layout } from "@dagrejs/dagre";
+import { Edge, Node } from "reactflow";
+import { LayoutDirection } from "../types";
+
+const g = new graphlib.Graph().setDefaultEdgeLabel(() => ({}));
+
+export const layoutElements = (
+ nodes: Node[],
+ edges: Edge[],
+ options: { direction: LayoutDirection },
+) => {
+ g.setGraph({
+ rankdir: options.direction,
+ nodesep: 150,
+ ranksep: 200,
+ // So far, longest-path seems to give the best results as trees are
+ // generally quite wide.
+ ranker: "longest-path",
+ });
+
+ edges.forEach((edge) => g.setEdge(edge.source, edge.target));
+ nodes.forEach((node) =>
+ g.setNode(node.id, {
+ ...node,
+ width: node.width || 0,
+ height: node.height || 0,
+ }),
+ );
+
+ layout(g);
+
+ return {
+ nodes: nodes.map((node) => {
+ const { x, y } = g.node(node.id);
+
+ return { ...node, position: { x, y } };
+ }),
+ edges,
+ };
+};
diff --git a/frontend/src/components/dependency-graph/utils/useFitToViewOnDimensionChange.ts b/frontend/src/components/dependency-graph/utils/useFitToViewOnDimensionChange.ts
new file mode 100644
index 0000000000..50604f5a70
--- /dev/null
+++ b/frontend/src/components/dependency-graph/utils/useFitToViewOnDimensionChange.ts
@@ -0,0 +1,24 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { useDebouncedCallback } from "@/hooks/useDebounce";
+import { useEffect } from "react";
+import { useReactFlow, useStore } from "reactflow";
+
+/**
+ * Call fitToView whenever the dimensions changes
+ */
+export function useFitToViewOnDimensionChange() {
+ const instance = useReactFlow();
+ const width = useStore(({ width }) => width);
+ const height = useStore(({ height }) => height);
+ const debounceFitView = useDebouncedCallback(() => {
+ instance.fitView({ duration: 100 });
+ }, 100);
+
+ // When the window is resized, fit the view to the graph.
+ useEffect(() => {
+ if (!width || !height) {
+ return;
+ }
+ debounceFitView();
+ }, [width, height, debounceFitView]);
+}
diff --git a/frontend/src/components/editor/cell/TinyCode.css b/frontend/src/components/editor/cell/TinyCode.css
index 49c933f79b..99034347c1 100644
--- a/frontend/src/components/editor/cell/TinyCode.css
+++ b/frontend/src/components/editor/cell/TinyCode.css
@@ -6,4 +6,5 @@
.tiny-code .cm-editor .cm-scroller {
line-height: 11px;
+ overflow-x: hidden;
}
diff --git a/frontend/src/components/editor/cell/TinyCode.tsx b/frontend/src/components/editor/cell/TinyCode.tsx
index 3ec064293f..64da99b73b 100644
--- a/frontend/src/components/editor/cell/TinyCode.tsx
+++ b/frontend/src/components/editor/cell/TinyCode.tsx
@@ -12,6 +12,19 @@ interface Props {
className?: string;
}
+const ext = [
+ python(),
+ minimalSetup({
+ syntaxHighlighting: true,
+ // Other options are false
+ highlightSpecialChars: false,
+ history: false,
+ drawSelection: false,
+ defaultKeymap: false,
+ historyKeymap: false,
+ }),
+];
+
export const TinyCode: React.FC<Props> = memo(({ code, className }) => {
const { theme } = useTheme();
@@ -29,18 +42,7 @@ export const TinyCode: React.FC<Props> = memo(({ code, className }) => {
className="tiny-code"
editable={false}
basicSetup={false}
- extensions={[
- python(),
- minimalSetup({
- syntaxHighlighting: true,
- // Other options are false
- highlightSpecialChars: false,
- history: false,
- drawSelection: false,
- defaultKeymap: false,
- historyKeymap: false,
- }),
- ]}
+ extensions={ext}
value={code}
/>
</div>
diff --git a/frontend/src/components/editor/chrome/components/contribute-snippet-button.tsx b/frontend/src/components/editor/chrome/components/contribute-snippet-button.tsx
index 50fc79f330..c772b78d23 100644
--- a/frontend/src/components/editor/chrome/components/contribute-snippet-button.tsx
+++ b/frontend/src/components/editor/chrome/components/contribute-snippet-button.tsx
@@ -14,10 +14,10 @@ import { Textarea } from "@/components/ui/textarea";
import { toast } from "@/components/ui/use-toast";
import { Constants } from "@/core/constants";
import { Input } from "@/components/ui/input";
-import AnyLanguageCodeMirror from "@/plugins/impl/code/any-language-editor";
import { EditorView } from "@codemirror/view";
import { useState } from "react";
import { useTheme } from "@/theme/useTheme";
+import { LazyAnyLanguageCodeMirror } from "@/plugins/impl/code/LazyAnyLanguageCodeMirror";
export const ContributeSnippetButton: React.FC<PropsWithChildren> = ({
children,
@@ -33,6 +33,8 @@ export const ContributeSnippetButton: React.FC<PropsWithChildren> = ({
);
};
+const extensions = [EditorView.lineWrapping];
+
const ContributeSnippetModal: React.FC<{
onClose: () => void;
}> = ({ onClose }) => {
@@ -105,13 +107,13 @@ const ContributeSnippetModal: React.FC<{
autoComplete="off"
/>
<input type="hidden" name="code" value={code} />
- <AnyLanguageCodeMirror
+ <LazyAnyLanguageCodeMirror
theme={theme === "dark" ? "dark" : "light"}
language="python"
className="cm border rounded overflow-hidden"
- extensions={[EditorView.lineWrapping]}
+ extensions={extensions}
value={code}
- onChange={(value) => setCode(value)}
+ onChange={setCode}
/>
</div>
<DialogFooter>
diff --git a/frontend/src/components/editor/chrome/panels/snippets-panel.tsx b/frontend/src/components/editor/chrome/panels/snippets-panel.tsx
index b1ea58a4dc..b484983c7a 100644
--- a/frontend/src/components/editor/chrome/panels/snippets-panel.tsx
+++ b/frontend/src/components/editor/chrome/panels/snippets-panel.tsx
@@ -29,6 +29,8 @@ import { cn } from "@/utils/cn";
import { ContributeSnippetButton } from "../components/contribute-snippet-button";
import { Spinner } from "@/components/icons/spinner";
+const extensions = [EditorView.lineWrapping];
+
export const SnippetsPanel: React.FC = () => {
const [selectedSnippet, setSelectedSnippet] = React.useState<Snippet>();
const {
@@ -176,7 +178,7 @@ const SnippetViewer: React.FC<{ snippet: Snippet }> = ({ snippet }) => {
theme={theme === "dark" ? "dark" : "light"}
language="python"
className="cm border rounded overflow-hidden"
- extensions={[EditorView.lineWrapping]}
+ extensions={extensions}
value={code}
readOnly={true}
/>
diff --git a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
index 6bb16e27ad..af3912666d 100644
--- a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
@@ -117,7 +117,7 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
minSize={10}
// We can't make the default size greater than 0, otherwise it will start open
defaultSize={0}
- maxSize={45}
+ maxSize={75}
onResize={(size, prevSize) => {
// This means it started closed and is opening for the first time
if (prevSize === 0 && size === 10) {
diff --git a/frontend/src/components/editor/links/cell-link-list.tsx b/frontend/src/components/editor/links/cell-link-list.tsx
new file mode 100644
index 0000000000..cef63e99e1
--- /dev/null
+++ b/frontend/src/components/editor/links/cell-link-list.tsx
@@ -0,0 +1,70 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { CellId } from "@/core/cells/ids";
+import React from "react";
+import { CellLink } from "./cell-link";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { useCellIds } from "@/core/cells/cells";
+
+interface Props {
+ maxCount: number;
+ cellIds: CellId[];
+ onClick?: (cellId: CellId) => void;
+}
+
+export const CellLinkList: React.FC<Props> = ({
+ maxCount,
+ cellIds,
+ onClick,
+}) => {
+ const cellIndex = useCellIds();
+ const sortedCellIds = [...cellIds].sort((a, b) => {
+ return cellIndex.indexOf(a) - cellIndex.indexOf(b);
+ });
+
+ if (cellIds.length === 0) {
+ return <div className="text-muted-foreground">--</div>;
+ }
+
+ return (
+ <>
+ {sortedCellIds.slice(0, maxCount).map((cellId, idx) => (
+ <span className="flex" key={cellId}>
+ <CellLink
+ variant="focus"
+ key={cellId}
+ cellId={cellId}
+ className="whitespace-nowrap"
+ onClick={onClick ? () => onClick(cellId) : undefined}
+ />
+ {idx < cellIds.length - 1 && ", "}
+ </span>
+ ))}
+ {cellIds.length > maxCount && (
+ <Popover>
+ <PopoverTrigger asChild={true}>
+ <div className="whitespace-nowrap text-muted-foreground text-xs hover:underline cursor-pointer">
+ +{cellIds.length - maxCount} more
+ </div>
+ </PopoverTrigger>
+ <PopoverContent className="w-auto">
+ <div className="flex flex-col gap-1 py-1">
+ {sortedCellIds.slice(maxCount).map((cellId) => (
+ <CellLink
+ variant="focus"
+ key={cellId}
+ cellId={cellId}
+ className="whitespace-nowrap"
+ onClick={onClick ? () => onClick(cellId) : undefined}
+ />
+ ))}
+ </div>
+ </PopoverContent>
+ </Popover>
+ )}
+ </>
+ );
+};
diff --git a/frontend/src/components/editor/links/cell-link.tsx b/frontend/src/components/editor/links/cell-link.tsx
index 4f167d190e..14242af64a 100644
--- a/frontend/src/components/editor/links/cell-link.tsx
+++ b/frontend/src/components/editor/links/cell-link.tsx
@@ -17,7 +17,6 @@ export const CellLink = (props: Props): JSX.Element => {
const { className, cellId, variant, onClick } = props;
const cellName = useCellNames()[cellId] ?? "";
const cellIndex = useCellIds().indexOf(cellId);
- const cellHtmlId = HTMLCellId.create(cellId);
return (
<div
@@ -28,27 +27,8 @@ export const CellLink = (props: Props): JSX.Element => {
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
-
- const cell: HTMLElement | null = document.getElementById(cellHtmlId);
-
- if (cell === null) {
- Logger.error(`Cell ${cellHtmlId} 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);
- }
-
+ const succeeded = scrollToCell(cellId, variant);
+ if (succeeded) {
onClick?.();
}
}}
@@ -64,3 +44,33 @@ export const CellLinkError = (
): JSX.Element => {
return <CellLink {...props} variant={"destructive"} />;
};
+
+export function scrollToCell(
+ cellId: CellId,
+ variant?: "destructive" | "focus",
+): boolean {
+ const cellHtmlId = HTMLCellId.create(cellId);
+ const cell: HTMLElement | null = document.getElementById(cellHtmlId);
+
+ if (cell === null) {
+ Logger.error(`Cell ${cellHtmlId} not found on page.`);
+ return false;
+ } 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);
+ }
+
+ return true;
+ }
+}
diff --git a/frontend/src/components/ui/button.tsx b/frontend/src/components/ui/button.tsx
index 49a6483216..64ee0af736 100644
--- a/frontend/src/components/ui/button.tsx
+++ b/frontend/src/components/ui/button.tsx
@@ -49,6 +49,7 @@ const buttonVariants = cva(
"border border-slate-300 shadow-smSolid",
"hover:bg-accent hover:text-accent-foreground",
"hover:border-primary",
+ "aria-selected:text-accent-foreground aria-selected:border-primary",
activeCommon,
),
secondary: cn(
diff --git a/frontend/src/components/variables/common.tsx b/frontend/src/components/variables/common.tsx
new file mode 100644
index 0000000000..352186f06b
--- /dev/null
+++ b/frontend/src/components/variables/common.tsx
@@ -0,0 +1,27 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import React from "react";
+import { toast } from "../ui/use-toast";
+import { Badge } from "../ui/badge";
+
+interface Props {
+ name: string;
+ declaredBy: string[];
+}
+
+export const VariableName: React.FC<Props> = ({ name, declaredBy }) => {
+ return (
+ <div className="max-w-[130px]">
+ <Badge
+ title={name}
+ variant={declaredBy.length > 1 ? "destructive" : "outline"}
+ className="rounded-sm text-ellipsis block overflow-hidden max-w-fit cursor-pointer font-medium"
+ onClick={() => {
+ navigator.clipboard.writeText(name);
+ toast({ title: "Copied to clipboard" });
+ }}
+ >
+ {name}
+ </Badge>
+ </div>
+ );
+};
diff --git a/frontend/src/components/variables/variables-table.tsx b/frontend/src/components/variables/variables-table.tsx
index 9825ea220f..74d15c6269 100644
--- a/frontend/src/components/variables/variables-table.tsx
+++ b/frontend/src/components/variables/variables-table.tsx
@@ -13,8 +13,6 @@ import { CellId } from "@/core/cells/ids";
import { CellLink } from "@/components/editor/links/cell-link";
import { cn } from "@/utils/cn";
import { SquareEqualIcon, WorkflowIcon } from "lucide-react";
-import { Badge } from "../ui/badge";
-import { toast } from "../ui/use-toast";
import {
useReactTable,
getCoreRowModel,
@@ -30,6 +28,8 @@ import { sortBy } from "lodash-es";
import { getCellEditorView } from "@/core/cells/cells";
import { goToDefinition } from "@/core/codemirror/find-replace/search-highlight";
import { SearchInput } from "../ui/input";
+import { CellLinkList } from "../editor/links/cell-link-list";
+import { VariableName } from "./common";
interface Props {
className?: string;
@@ -63,21 +63,7 @@ const COLUMNS = [
),
cell: ({ getValue }) => {
const [name, declaredBy] = getValue();
- return (
- <div className="max-w-[130px]">
- <Badge
- title={name}
- variant={declaredBy.length > 1 ? "destructive" : "outline"}
- className="rounded-sm text-ellipsis block overflow-hidden max-w-fit cursor-pointer font-medium"
- onClick={() => {
- navigator.clipboard.writeText(name);
- toast({ title: "Copied to clipboard" });
- }}
- >
- {name}
- </Badge>
- </div>
- );
+ return <VariableName name={name} declaredBy={declaredBy} />;
},
}),
columnDefOf({
@@ -175,23 +161,11 @@ const COLUMNS = [
<WorkflowIcon className="w-3.5 h-3.5 text-muted-foreground" />
</span>
- {usedBy.slice(0, 3).map((cellId, idx) => (
- <span className="flex" key={cellId}>
- <CellLink
- variant="focus"
- key={cellId}
- cellId={cellId}
- className="whitespace-nowrap"
- onClick={() => highlightInCell(cellId)}
- />
- {idx < usedBy.length - 1 && ", "}
- </span>
- ))}
- {usedBy.length > 3 && (
- <div className="whitespace-nowrap text-muted-foreground text-xs">
- +{usedBy.length - 3} more
- </div>
- )}
+ <CellLinkList
+ maxCount={3}
+ cellIds={usedBy}
+ onClick={highlightInCell}
+ />
</div>
</div>
);
diff --git a/frontend/src/plugins/impl/CodeEditorPlugin.tsx b/frontend/src/plugins/impl/CodeEditorPlugin.tsx
index 8fe6af4dbe..b59dc3ebe4 100644
--- a/frontend/src/plugins/impl/CodeEditorPlugin.tsx
+++ b/frontend/src/plugins/impl/CodeEditorPlugin.tsx
@@ -61,7 +61,7 @@ const CodeEditorComponent = (props: CodeEditorComponentProps) => {
editable={!props.disabled}
value={props.value}
language={props.language}
- onChange={(value) => props.setValue(value)}
+ onChange={props.setValue}
/>
</Labeled>
);
diff --git a/frontend/src/plugins/impl/code/any-language-editor.tsx b/frontend/src/plugins/impl/code/any-language-editor.tsx
index 263bdf220d..ade1835066 100644
--- a/frontend/src/plugins/impl/code/any-language-editor.tsx
+++ b/frontend/src/plugins/impl/code/any-language-editor.tsx
@@ -1,11 +1,14 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import ReactCodeMirror, { ReactCodeMirrorProps } from "@uiw/react-codemirror";
+import ReactCodeMirror, {
+ Extension,
+ ReactCodeMirrorProps,
+} from "@uiw/react-codemirror";
import {
loadLanguage,
langs,
LanguageName,
} from "@uiw/codemirror-extensions-langs";
-import React from "react";
+import React, { useMemo } from "react";
import { Logger } from "@/utils/Logger";
import { ErrorBanner } from "../common/error-banner";
@@ -25,6 +28,12 @@ const AnyLanguageCodeMirror: React.FC<
Logger.warn(`Language ${language} not found in CodeMirror.`);
}
+ const finalExtensions = useMemo((): Extension[] => {
+ return [loadLanguage(language as LanguageName), ...extensions].filter(
+ Boolean,
+ );
+ }, [language, extensions]);
+
return (
<>
{isNotSupported && (
@@ -35,13 +44,7 @@ const AnyLanguageCodeMirror: React.FC<
).join(", ")}`}
/>
)}
- <ReactCodeMirror
- {...props}
- extensions={[
- loadLanguage(language as LanguageName),
- ...extensions,
- ].filter(Boolean)}
- />
+ <ReactCodeMirror {...props} extensions={finalExtensions} />
</>
);
};
diff --git a/frontend/src/utils/arrays.ts b/frontend/src/utils/arrays.ts
index e1d840e5fa..bc91b262aa 100644
--- a/frontend/src/utils/arrays.ts
+++ b/frontend/src/utils/arrays.ts
@@ -1,4 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
+import { invariant } from "./invariant";
+
export function arrayDelete<T>(array: T[], index: number): T[] {
return [...array.slice(0, index), ...array.slice(index + 1)];
}
@@ -26,4 +28,12 @@ export function arrayShallowEquals<T>(a: T[], b: T[]): boolean {
export const Arrays = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
EMPTY: [] as any[],
+ zip: <T, U>(a: T[], b: U[]): Array<[T, U]> => {
+ invariant(a.length === b.length, "Arrays must be the same length");
+ const result: Array<[T, U]> = [];
+ for (let i = 0; i < Math.min(a.length, b.length); i++) {
+ result.push([a[i], b[i]]);
+ }
+ return result;
+ },
};
diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.py
index cd123f9976..564275337d 100644
--- a/marimo/_messaging/ops.py
+++ b/marimo/_messaging/ops.py
@@ -355,8 +355,8 @@ class VariableDeclaration:
@dataclass
class VariableValue:
name: str
- datatype: Optional[str]
value: Optional[str]
+ datatype: Optional[str]
def __init__(
self, name: str, value: object, datatype: Optional[str] = None
@@ -365,9 +365,15 @@ class VariableValue:
# Defensively try-catch attribute accesses, which could raise
# exceptions
- try:
- self.datatype = type(value).__name__ if value is not None else None
- except Exception:
+ # If datatype is already defined, don't try to infer it
+ if datatype is None:
+ try:
+ self.datatype = (
+ type(value).__name__ if value is not None else None
+ )
+ except Exception:
+ self.datatype = datatype
+ else:
self.datatype = datatype
try:
diff --git a/marimo/_smoke_tests/bugs/1274.py b/marimo/_smoke_tests/bugs/1274.py
new file mode 100644
index 0000000000..90615681f3
--- /dev/null
+++ b/marimo/_smoke_tests/bugs/1274.py
@@ -0,0 +1,21 @@
+
+
+import marimo
+
+__generated_with = "0.4.7"
+app = marimo.App()
+
+
+async def __():
+ import asyncio
+ print("hello")
+ await asyncio.sleep(1)
+ print("world")
+ await asyncio.sleep(1)
+ print("last one")
+ return asyncio,
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_server/session/test_session_view.py b/tests/_server/session/test_session_view.py
index 62d73188da..d9ec5ff1e4 100644
--- a/tests/_server/session/test_session_view.py
+++ b/tests/_server/session/test_session_view.py
@@ -21,6 +21,7 @@ from marimo._runtime.requests import (
SetUIElementValueRequest,
)
from marimo._server.session.session_view import SessionView
+from marimo._utils.parse_dataclass import parse_raw
cell_id: CellId_t = "cell_1"
@@ -187,6 +188,14 @@ def test_last_run_code() -> None:
assert session_view.last_executed_code[cell_id] == "print('hello')"
+def test_serialize_parse_variable_value() -> None:
+ original = VariableValue(name="var1", value=1)
+ serialized = serialize(original)
+ assert serialized == {"datatype": "int", "name": "var1", "value": "1"}
+ parsed = parse_raw(serialized, VariableValue)
+ assert parsed == original
+
+
def test_add_variables() -> None:
session_view = SessionView()
@@ -218,7 +227,9 @@ def test_add_variables() -> None:
assert session_view.variable_operations.variables[0].name == "var1"
assert session_view.variable_operations.variables[1].name == "var2"
assert session_view.variable_values["var1"].value == "1"
+ assert session_view.variable_values["var1"].datatype == "int"
assert session_view.variable_values["var2"].value == "hello"
+ assert session_view.variable_values["var2"].datatype == "str"
def test_add_cell_op() -> None: