Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

improvement: add CreateFile and CreateFolder to file explorer (#2024)

Myles Scolnick2707add9c7a9
diff --git a/frontend/src/components/editor/actions/useCellActionButton.tsx b/frontend/src/components/editor/actions/useCellActionButton.tsx
index 20be54f7b7..37d4013dae 100644
--- a/frontend/src/components/editor/actions/useCellActionButton.tsx
+++ b/frontend/src/components/editor/actions/useCellActionButton.tsx
@@ -51,13 +51,13 @@ import { MarkdownIcon, PythonIcon } from "../cell/code/icons";
import { aiEnabledAtom, autoInstantiateAtom } from "@/core/config/config";
import { useDeleteCellCallback } from "../cell/useDeleteCell";
import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";
-import type { CellConfig, CellStatus } from "@/core/network/types";
+import type { CellConfig, RuntimeState } from "@/core/network/types";
import { kioskModeAtom } from "@/core/mode";
export interface CellActionButtonProps
extends Pick<CellData, "name" | "config"> {
cellId: CellId;
- status: CellStatus;
+ status: RuntimeState;
hasOutput: boolean;
getEditorView: () => EditorView | null;
}
diff --git a/frontend/src/components/editor/cell/DeleteButton.tsx b/frontend/src/components/editor/cell/DeleteButton.tsx
index 18932ddc28..b5885e083f 100644
--- a/frontend/src/components/editor/cell/DeleteButton.tsx
+++ b/frontend/src/components/editor/cell/DeleteButton.tsx
@@ -3,10 +3,10 @@ import { Trash2Icon } from "lucide-react";
import { Tooltip } from "../../ui/tooltip";
import { Button } from "../../ui/button";
import { cn } from "../../../utils/cn";
-import { CellStatus } from "@/core/network/types";
+import type { RuntimeState } from "@/core/network/types";
export const DeleteButton = (props: {
- status: CellStatus;
+ status: RuntimeState;
appClosed: boolean;
onClick?: (e: React.MouseEvent<HTMLButtonElement>) => void;
}): JSX.Element => {
diff --git a/frontend/src/components/editor/cell/RunButton.tsx b/frontend/src/components/editor/cell/RunButton.tsx
index b77afc151c..9c0c3bb8d4 100644
--- a/frontend/src/components/editor/cell/RunButton.tsx
+++ b/frontend/src/components/editor/cell/RunButton.tsx
@@ -6,7 +6,7 @@ import { renderShortcut } from "../../shortcuts/renderShortcut";
import { cn } from "../../../utils/cn";
import { sendInterrupt } from "@/core/network/requests";
import { useShouldShowInterrupt } from "./useShouldShowInterrupt";
-import { CellStatus, CellConfig } from "@/core/network/types";
+import type { RuntimeState, CellConfig } from "@/core/network/types";
function computeColor(
appClosed: boolean,
@@ -27,7 +27,7 @@ function computeColor(
export const RunButton = (props: {
edited: boolean;
- status: CellStatus;
+ status: RuntimeState;
needsRun: boolean;
appClosed: boolean;
config: CellConfig;
diff --git a/frontend/src/components/editor/file-tree/__tests__/requesting-tree.test.ts b/frontend/src/components/editor/file-tree/__tests__/requesting-tree.test.ts
index cd6b98f474..18e66d6fdf 100644
--- a/frontend/src/components/editor/file-tree/__tests__/requesting-tree.test.ts
+++ b/frontend/src/components/editor/file-tree/__tests__/requesting-tree.test.ts
@@ -108,8 +108,8 @@ describe("RequestingTree", () => {
[
{
"id": "1.1",
- "name": "file2",
- "path": "/root/file2",
+ "name": "file1",
+ "path": "/root/file1",
},
{
"id": "1.2",
@@ -163,6 +163,22 @@ describe("RequestingTree", () => {
`);
});
+ test("createFile should create a new file", async () => {
+ sendCreateFileOrFolder.mockResolvedValue({ success: true });
+
+ await requestingTree.createFile("file3", "1.2");
+ expect(sendCreateFileOrFolder).toHaveBeenCalled();
+ expect(mockOnChange).toHaveBeenCalled();
+ });
+
+ test("createFolder should create a new folder", async () => {
+ sendCreateFileOrFolder.mockResolvedValue({ success: true });
+
+ await requestingTree.createFolder("folder3", "1.2");
+ expect(sendCreateFileOrFolder).toHaveBeenCalled();
+ expect(mockOnChange).toHaveBeenCalled();
+ });
+
test("refreshAll should refresh data for all open folders", async () => {
await requestingTree.refreshAll(["1.1"]);
expect(sendListFiles).toHaveBeenCalled();
diff --git a/frontend/src/components/editor/file-tree/file-explorer.tsx b/frontend/src/components/editor/file-tree/file-explorer.tsx
index 7feca973a2..7b674e4284 100644
--- a/frontend/src/components/editor/file-tree/file-explorer.tsx
+++ b/frontend/src/components/editor/file-tree/file-explorer.tsx
@@ -1,5 +1,10 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { type NodeApi, type NodeRendererProps, Tree } from "react-arborist";
+import {
+ type NodeApi,
+ type NodeRendererProps,
+ Tree,
+ type TreeApi,
+} from "react-arborist";
import React, {
Suspense,
@@ -14,8 +19,11 @@ import {
ChevronDownIcon,
ChevronRightIcon,
CopyIcon,
+ CopyMinusIcon,
Edit3Icon,
ExternalLinkIcon,
+ FilePlus2Icon,
+ FolderPlusIcon,
MoreVerticalIcon,
PlaySquareIcon,
RefreshCcwIcon,
@@ -54,19 +62,51 @@ import { ErrorBanner } from "@/plugins/impl/common/error-banner";
import { Spinner } from "@/components/icons/spinner";
import type { RequestingTree } from "./requesting-tree";
import type { FilePath } from "@/utils/paths";
+import useEvent from "react-use-event-hook";
const RequestingTreeContext = React.createContext<RequestingTree | null>(null);
export const FileExplorer: React.FC<{
height: number;
}> = ({ height }) => {
+ const treeRef = useRef<TreeApi<FileInfo>>(null);
const [tree] = useAtom(treeAtom);
const [data, setData] = useState<FileInfo[]>([]);
- const [openState, setOpenState] = useAtom(openStateAtom);
const [openFile, setOpenFile] = useState<FileInfo | null>(null);
+ const { openPrompt } = useImperativeModal();
+ // Keep external state to remember which folders are open
+ // when this component is unmounted
+ const [openState, setOpenState] = useAtom(openStateAtom);
const { loading, error } = useAsyncData(() => tree.initialize(setData), []);
+ const handleRefresh = useEvent(() => {
+ tree.refreshAll(Object.keys(openState).filter((id) => openState[id]));
+ });
+
+ const handleCreateFolder = useEvent(async () => {
+ openPrompt({
+ title: "Folder name",
+ onConfirm: async (name) => {
+ tree.createFolder(name, null);
+ },
+ });
+ });
+
+ const handleCreateFile = useEvent(async () => {
+ openPrompt({
+ title: "File name",
+ onConfirm: async (name) => {
+ tree.createFile(name, null);
+ },
+ });
+ });
+
+ const handleCollapseAll = useEvent(() => {
+ treeRef.current?.closeAll();
+ setOpenState({});
+ });
+
if (loading) {
return <Spinner size="medium" centered={true} />;
}
@@ -108,13 +148,16 @@ export const FileExplorer: React.FC<{
return (
<>
<Toolbar
- onRefresh={() =>
- tree.refreshAll(Object.keys(openState).filter((id) => openState[id]))
- }
+ onRefresh={handleRefresh}
+ onCreateFile={handleCreateFile}
+ onCreateFolder={handleCreateFolder}
+ onCollapseAll={handleCollapseAll}
+ tree={tree}
/>
<RequestingTreeContext.Provider value={tree}>
<Tree<FileInfo>
width="100%"
+ ref={treeRef}
height={height - 33}
className="h-full"
data={data}
@@ -167,7 +210,21 @@ export const FileExplorer: React.FC<{
const INDENT_STEP = 15;
-const Toolbar = ({ onRefresh }: { onRefresh: () => void }) => {
+interface ToolbarProps {
+ onRefresh: () => void;
+ onCreateFile: () => void;
+ onCreateFolder: () => void;
+ onCollapseAll: () => void;
+ tree: RequestingTree;
+}
+
+const Toolbar = ({
+ tree,
+ onRefresh,
+ onCreateFile,
+ onCreateFolder,
+ onCollapseAll,
+}: ToolbarProps) => {
const { getRootProps, getInputProps } = useFileExplorerUpload({
noDrag: true,
noDragEventsBubbling: true,
@@ -175,6 +232,26 @@ const Toolbar = ({ onRefresh }: { onRefresh: () => void }) => {
return (
<div className="flex items-center justify-end px-2 flex-shrink-0 border-b">
+ <Tooltip content="Add file">
+ <Button
+ data-testid="file-explorer-add-file-button"
+ onClick={onCreateFile}
+ variant="text"
+ size="xs"
+ >
+ <FilePlus2Icon size={16} />
+ </Button>
+ </Tooltip>
+ <Tooltip content="Add folder">
+ <Button
+ data-testid="file-explorer-add-folder-button"
+ onClick={onCreateFolder}
+ variant="text"
+ size="xs"
+ >
+ <FolderPlusIcon size={16} />
+ </Button>
+ </Tooltip>
<Tooltip content="Upload file">
<button
data-testid="file-explorer-upload-button"
@@ -198,6 +275,16 @@ const Toolbar = ({ onRefresh }: { onRefresh: () => void }) => {
<RefreshCcwIcon size={16} />
</Button>
</Tooltip>
+ <Tooltip content="Collapse all folders">
+ <Button
+ data-testid="file-explorer-collapse-button"
+ onClick={onCollapseAll}
+ variant="text"
+ size="xs"
+ >
+ <CopyMinusIcon size={16} />
+ </Button>
+ </Tooltip>
</div>
);
};
@@ -268,7 +355,7 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
: guessFileType(node.data.name);
const Icon = FILE_TYPE_ICONS[fileType];
- const { openConfirm } = useImperativeModal();
+ const { openConfirm, openPrompt } = useImperativeModal();
const tree = useContext(RequestingTreeContext);
const handleOpenMarimoFile = async (
@@ -299,6 +386,119 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
});
};
+ const handleCreateFolder = useEvent(async () => {
+ // If not expanded, then expand
+ node.open();
+ openPrompt({
+ title: "Folder name",
+ onConfirm: async (name) => {
+ tree?.createFolder(name, node.id);
+ },
+ });
+ });
+
+ const handleCreateFile = useEvent(async () => {
+ node.open();
+ openPrompt({
+ title: "File name",
+ onConfirm: async (name) => {
+ tree?.createFile(name, node.id);
+ },
+ });
+ });
+
+ const renderActions = () => {
+ const iconProps = {
+ size: 14,
+ strokeWidth: 1.5,
+ className: "mr-2",
+ };
+ return (
+ <DropdownMenuContent
+ align="end"
+ className="no-print w-[220px]"
+ onClick={(e) => e.stopPropagation()}
+ onCloseAutoFocus={(e) => e.preventDefault()}
+ >
+ {!node.data.isDirectory && (
+ <DropdownMenuItem onSelect={() => node.select()}>
+ <ViewIcon {...iconProps} />
+ Open file
+ </DropdownMenuItem>
+ )}
+ {node.data.isDirectory && (
+ <>
+ <DropdownMenuItem onSelect={() => handleCreateFile()}>
+ <FilePlus2Icon {...iconProps} />
+ Create file
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => handleCreateFolder()}>
+ <FolderPlusIcon {...iconProps} />
+ Create folder
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ </>
+ )}
+ <DropdownMenuItem onSelect={() => node.edit()}>
+ <Edit3Icon {...iconProps} />
+ Rename
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onSelect={() => {
+ toast({ title: "Copied to clipboard" });
+ navigator.clipboard.writeText(node.data.path);
+ }}
+ >
+ <CopyIcon {...iconProps} />
+ Copy path
+ </DropdownMenuItem>
+ {tree && (
+ <DropdownMenuItem
+ onSelect={() => {
+ toast({ title: "Copied to clipboard" });
+ navigator.clipboard.writeText(
+ tree.relativeFromRoot(node.data.path as FilePath),
+ );
+ }}
+ >
+ <CopyIcon {...iconProps} />
+ Copy relative path
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuItem
+ onSelect={() => {
+ toast({
+ title: "Copied to clipboard",
+ description:
+ "Code to open the file has been copied to your clipboard. You can also drag and drop this file into the editor",
+ });
+ const { path } = node.data;
+ const pythonCode = PYTHON_CODE_FOR_FILE_TYPE[fileType](path);
+ navigator.clipboard.writeText(pythonCode);
+ }}
+ >
+ <BracesIcon {...iconProps} />
+ Copy snippet for reading file
+ </DropdownMenuItem>
+ {/* Not shown in WASM */}
+ {node.data.isMarimoFile && !isWasm() && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onSelect={handleOpenMarimoFile}>
+ <PlaySquareIcon {...iconProps} />
+ Open notebook
+ </DropdownMenuItem>
+ </>
+ )}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onSelect={handleDeleteFile} variant="danger">
+ <Trash2Icon {...iconProps} />
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ );
+ };
+
return (
<div
style={style}
@@ -357,79 +557,7 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
/>
</Button>
</DropdownMenuTrigger>
- <DropdownMenuContent
- align="end"
- className="no-print w-[220px]"
- onClick={(e) => e.stopPropagation()}
- onCloseAutoFocus={(e) => e.preventDefault()}
- >
- {!node.data.isDirectory && (
- <DropdownMenuItem onSelect={() => node.select()}>
- <ViewIcon className="mr-2" size={14} strokeWidth={1.5} />
- Open file
- </DropdownMenuItem>
- )}
- <DropdownMenuItem onSelect={() => node.edit()}>
- <Edit3Icon className="mr-2" size={14} strokeWidth={1.5} />
- Rename
- </DropdownMenuItem>
- <DropdownMenuItem
- onSelect={() => {
- toast({ title: "Copied to clipboard" });
- navigator.clipboard.writeText(node.data.path);
- }}
- >
- <CopyIcon className="mr-2" size={14} strokeWidth={1.5} />
- Copy path
- </DropdownMenuItem>
- {tree && (
- <DropdownMenuItem
- onSelect={() => {
- toast({ title: "Copied to clipboard" });
- navigator.clipboard.writeText(
- tree.relativeFromRoot(node.data.path as FilePath),
- );
- }}
- >
- <CopyIcon className="mr-2" size={14} strokeWidth={1.5} />
- Copy relative path
- </DropdownMenuItem>
- )}
- <DropdownMenuItem
- onSelect={() => {
- toast({
- title: "Copied to clipboard",
- description:
- "Code to open the file has been copied to your clipboard. You can also drag and drop this file into the editor",
- });
- const { path } = node.data;
- const pythonCode = PYTHON_CODE_FOR_FILE_TYPE[fileType](path);
- navigator.clipboard.writeText(pythonCode);
- }}
- >
- <BracesIcon className="mr-2" size={14} strokeWidth={1.5} />
- Copy snippet for reading file
- </DropdownMenuItem>
- {/* Not shown in WASM */}
- {node.data.isMarimoFile && !isWasm() && (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuItem onSelect={handleOpenMarimoFile}>
- <PlaySquareIcon
- className="mr-2"
- size={14}
- strokeWidth={1.5}
- />
- Open notebook
- </DropdownMenuItem>
- </>
- )}
- <DropdownMenuSeparator />
- <DropdownMenuItem onSelect={handleDeleteFile} variant="danger">
- <Trash2Icon className="mr-2" size={14} strokeWidth={1.5} />
- Delete
- </DropdownMenuItem>
- </DropdownMenuContent>
+ {renderActions()}
</DropdownMenu>
</span>
</div>
diff --git a/frontend/src/components/editor/file-tree/file-viewer.tsx b/frontend/src/components/editor/file-tree/file-viewer.tsx
index e59c632581..f40f5618d0 100644
--- a/frontend/src/components/editor/file-tree/file-viewer.tsx
+++ b/frontend/src/components/editor/file-tree/file-viewer.tsx
@@ -92,8 +92,9 @@ export const FileViewer: React.FC<Props> = ({ file, onOpenNotebook }) => {
}
const mimeType = data.mimeType || "text/plain";
+ const isEditable = mimeType in mimeToLanguage;
- if (!data.contents) {
+ if (!data.contents && !isEditable) {
// Show details instead of contents
return (
<div className="grid grid-cols-2 gap-2 p-6">
@@ -170,7 +171,7 @@ export const FileViewer: React.FC<Props> = ({ file, onOpenNotebook }) => {
);
}
- if (mimeType === "text/csv") {
+ if (mimeType === "text/csv" && data.contents) {
return (
<>
{header}
diff --git a/frontend/src/components/editor/file-tree/requesting-tree.tsx b/frontend/src/components/editor/file-tree/requesting-tree.tsx
index 9f3eb96ff1..64865c2afa 100644
--- a/frontend/src/components/editor/file-tree/requesting-tree.tsx
+++ b/frontend/src/components/editor/file-tree/requesting-tree.tsx
@@ -6,10 +6,10 @@ import type {
sendDeleteFileOrFolder,
sendRenameFileOrFolder,
} from "@/core/network/requests";
-import { FileInfo, FileUpdateResponse } from "@/core/network/types";
+import type { FileInfo, FileUpdateResponse } from "@/core/network/types";
import { prettyError } from "@/utils/errors";
import { Functions } from "@/utils/functions";
-import { FilePath, PathBuilder } from "@/utils/paths";
+import { type FilePath, PathBuilder } from "@/utils/paths";
import { SimpleTree } from "react-arborist";
export class RequestingTree {
@@ -84,6 +84,8 @@ export class RequestingTree {
.then(this.handleResponse);
this.delegate.update({ id, changes: { name, path: newPath } });
this.onChange(this.delegate.data);
+ // Rename all of its children
+ await this.refreshAll([newPath]);
}
async move(fromIds: string[], parentId: string | null): Promise<void> {
@@ -118,6 +120,46 @@ export class RequestingTree {
await this.refreshAll([parentPath]);
}
+ async createFile(name: string, parentId: string | null): Promise<void> {
+ const parentPath = parentId
+ ? this.delegate.find(parentId)?.data.path ?? parentId
+ : this.rootPath;
+ const newFile = await this.callbacks
+ .createFileOrFolder({ path: parentPath, type: "file", name: name })
+ .then(this.handleResponse);
+ if (!newFile?.info) {
+ return;
+ }
+ this.delegate.create({
+ parentId,
+ index: 0,
+ data: newFile.info,
+ });
+ this.onChange(this.delegate.data);
+ // Refresh the parent folder
+ await this.refreshAll([parentPath]);
+ }
+
+ async createFolder(name: string, parentId: string | null): Promise<void> {
+ const parentPath = parentId
+ ? this.delegate.find(parentId)?.data.path ?? parentId
+ : this.rootPath;
+ const newFolder = await this.callbacks
+ .createFileOrFolder({ path: parentPath, type: "directory", name: name })
+ .then(this.handleResponse);
+ if (!newFolder?.info) {
+ return;
+ }
+ this.delegate.create({
+ parentId,
+ index: 0,
+ data: newFolder.info,
+ });
+ this.onChange(this.delegate.data);
+ // Refresh the parent folder
+ await this.refreshAll([parentPath]);
+ }
+
async delete(id: string): Promise<void> {
const node = this.delegate.find(id);
if (!node) {
@@ -167,14 +209,18 @@ export class RequestingTree {
return path;
};
- private handleResponse = (response: FileUpdateResponse): void => {
+ private handleResponse = (
+ response: FileUpdateResponse,
+ ): FileUpdateResponse | null => {
if (!response.success) {
toast({
title: "Failed",
description: response.message,
});
- return;
+ return null;
}
+
+ return response;
};
}
diff --git a/frontend/src/components/editor/file-tree/types.ts b/frontend/src/components/editor/file-tree/types.ts
index 9c457142b4..125871ec8b 100644
--- a/frontend/src/components/editor/file-tree/types.ts
+++ b/frontend/src/components/editor/file-tree/types.ts
@@ -1,13 +1,16 @@
/* Copyright 2024 Marimo. All rights reserved. */
import {
DatabaseIcon,
+ FileAudioIcon,
FileCodeIcon,
FileIcon,
+ FileImageIcon,
FileJsonIcon,
FileTextIcon,
+ FileVideo2Icon,
+ FolderArchiveIcon,
FolderIcon,
- ImageIcon,
- LucideIcon,
+ type LucideIcon,
} from "lucide-react";
/* Copyright 2024 Marimo. All rights reserved. */
@@ -18,7 +21,11 @@ export type FileType =
| "json"
| "text"
| "image"
+ | "audio"
+ | "video"
| "data"
+ | "pdf"
+ | "zip"
| "unknown";
export function guessFileType(name: string): FileType {
@@ -50,7 +57,24 @@ export function guessFileType(name: string): FileType {
case "toml":
case "yaml":
case "yml":
+ case "wasm":
return "code";
+ case "mp3":
+ case "m4a":
+ case "m4v":
+ case "ogg":
+ case "wav":
+ return "audio";
+ case "mp4":
+ case "webm":
+ case "mkv":
+ return "video";
+ case "pdf":
+ return "pdf";
+ case "zip":
+ case "tar":
+ case "gz":
+ return "zip";
default:
return "unknown";
}
@@ -62,7 +86,11 @@ export const FILE_TYPE_ICONS: Record<FileType, LucideIcon> = {
json: FileJsonIcon,
code: FileCodeIcon,
text: FileTextIcon,
- image: ImageIcon,
+ image: FileImageIcon,
+ audio: FileAudioIcon,
+ video: FileVideo2Icon,
+ pdf: FileCodeIcon,
+ zip: FolderArchiveIcon,
data: DatabaseIcon,
unknown: FileIcon,
};
@@ -79,7 +107,11 @@ export const PYTHON_CODE_FOR_FILE_TYPE: Record<
`with open("${path}", "r") as _f:\n${TAB}_data = json.load(_f)\n`,
code: (path) => `with open("${path}", "r") as _f:\n${TAB}...\n`,
text: (path) => `with open("${path}", "r") as _f:\n${TAB}...\n`,
- image: (path) => `with open("${path}", "rb") as _f:\n${TAB}...\n`,
+ image: (path) => `mo.image("${path}")`,
+ audio: (path) => `mo.audio("${path}")`,
+ video: (path) => `mo.video("${path}")`,
+ pdf: (path) => `with open("${path}", "rb") as _f:\n${TAB}...\n`,
+ zip: (path) => `with open("${path}", "rb") as _f:\n${TAB}...\n`,
data: (path) => `with open("${path}", "r") as _f:\n${TAB}...\n`,
unknown: (path) => `with open("${path}", "r") as _f:\n${TAB}...\n`,
};
diff --git a/frontend/src/components/modal/ImperativeModal.tsx b/frontend/src/components/modal/ImperativeModal.tsx
index 8061b51fc2..4f075a5f65 100644
--- a/frontend/src/components/modal/ImperativeModal.tsx
+++ b/frontend/src/components/modal/ImperativeModal.tsx
@@ -1,5 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import React, { PropsWithChildren } from "react";
+import React, { type PropsWithChildren } from "react";
import { Dialog } from "../ui/dialog";
import {
AlertDialog,
@@ -11,6 +11,8 @@ import {
AlertDialogHeader,
AlertDialogTitle,
} from "../ui/alert-dialog";
+import { Input } from "../ui/input";
+import { Button } from "../ui/button";
interface ModalContextType {
modal: React.ReactNode | null;
@@ -93,6 +95,54 @@ export function useImperativeModal() {
</AlertDialog>,
);
},
+ openPrompt: (opts: {
+ title: React.ReactNode;
+ description?: React.ReactNode;
+ defaultValue?: string;
+ onConfirm: (value: string) => void;
+ }) => {
+ context.setModal(
+ <AlertDialog
+ open={true}
+ onOpenChange={(open) => {
+ if (!open) {
+ closeModal();
+ }
+ }}
+ >
+ <AlertDialogContent>
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ opts.onConfirm(e.currentTarget.prompt.value);
+ closeModal();
+ }}
+ >
+ <AlertDialogHeader>
+ <AlertDialogTitle>{opts.title}</AlertDialogTitle>
+ <AlertDialogDescription>
+ {opts.description}
+ </AlertDialogDescription>
+ <Input
+ defaultValue={opts.defaultValue}
+ className="my-4 h-8"
+ name="prompt"
+ required={true}
+ autoFocus={true}
+ autoComplete="off"
+ />
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel onClick={closeModal}>
+ Cancel
+ </AlertDialogCancel>
+ <Button type="submit">Ok</Button>
+ </AlertDialogFooter>
+ </form>
+ </AlertDialogContent>
+ </AlertDialog>,
+ );
+ },
openConfirm: (opts: {
title: React.ReactNode;
description?: React.ReactNode;
diff --git a/frontend/src/core/cells/__tests__/cell.test.ts b/frontend/src/core/cells/__tests__/cell.test.ts
index be55585fd0..64e0a8ab6b 100644
--- a/frontend/src/core/cells/__tests__/cell.test.ts
+++ b/frontend/src/core/cells/__tests__/cell.test.ts
@@ -1,11 +1,11 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { expect, describe, it } from "vitest";
import { outputIsStale } from "../cell";
-import { OutputMessage } from "@/core/kernel/messages";
-import { Seconds } from "@/utils/time";
-import { CellStatus } from "@/core/network/types";
+import type { OutputMessage } from "@/core/kernel/messages";
+import type { Seconds } from "@/utils/time";
+import type { RuntimeState } from "@/core/network/types";
-const STATUSES: CellStatus[] = [
+const STATUSES: RuntimeState[] = [
"queued",
"running",
"idle",
@@ -41,7 +41,7 @@ describe("outputIsStale", () => {
it("should return true if the cell is loading", () => {
const cell = {
- status: "running" as CellStatus,
+ status: "running" as RuntimeState,
staleInputs: false,
output: null,
runStartTimestamp: null,
@@ -53,7 +53,7 @@ describe("outputIsStale", () => {
it("should return false if the cell is running and output is received after run started", () => {
const cell = {
- status: "running" as CellStatus,
+ status: "running" as RuntimeState,
staleInputs: false,
output: createOutput(),
runStartTimestamp: (Date.now() - 1000) as Seconds, // Output received after run started
@@ -65,7 +65,7 @@ describe("outputIsStale", () => {
it("should return true if the cell status is stale", () => {
const cell = {
- status: "disabled-transitively" as CellStatus,
+ status: "disabled-transitively" as RuntimeState,
staleInputs: true,
output: null,
runStartTimestamp: null,
@@ -77,7 +77,7 @@ describe("outputIsStale", () => {
it("should return false if the cell is interrupted", () => {
const cell = {
- status: "running" as CellStatus,
+ status: "running" as RuntimeState,
staleInputs: false,
output: null,
runStartTimestamp: null,
@@ -89,7 +89,7 @@ describe("outputIsStale", () => {
it("should return true if the cell is running and output is received before run started", () => {
const cell = {
- status: "running" as CellStatus,
+ status: "running" as RuntimeState,
staleInputs: false,
output: createOutput(),
runStartTimestamp: (Date.now() + 1000) as Seconds, // Output received before run started
@@ -101,7 +101,7 @@ describe("outputIsStale", () => {
it("should return false if the cell is idle and output is received", () => {
const cell = {
- status: "idle" as CellStatus,
+ status: "idle" as RuntimeState,
staleInputs: false,
output: createOutput(),
runStartTimestamp: null,
@@ -113,7 +113,7 @@ describe("outputIsStale", () => {
it("should return true if the cell is queued", () => {
const cell = {
- status: "queued" as CellStatus,
+ status: "queued" as RuntimeState,
staleInputs: false,
output: null,
runStartTimestamp: null,
@@ -125,7 +125,7 @@ describe("outputIsStale", () => {
it("should return true if the cell is running but no output is received", () => {
const cell = {
- status: "running" as CellStatus,
+ status: "running" as RuntimeState,
staleInputs: false,
output: null,
runStartTimestamp: Date.now() as Seconds,
@@ -137,7 +137,7 @@ describe("outputIsStale", () => {
it("should return false if the cell is idle and not edited", () => {
const cell = {
- status: "idle" as CellStatus,
+ status: "idle" as RuntimeState,
staleInputs: false,
output: null,
runStartTimestamp: null,
@@ -150,7 +150,7 @@ describe("outputIsStale", () => {
it("should return false if the cell is interrupted but also edited", () => {
// We likely don't get in this state since before a cell is interrupted, it is run and we remove the edited state
const cell = {
- status: "idle" as CellStatus,
+ status: "idle" as RuntimeState,
staleInputs: false,
output: null,
runStartTimestamp: null,
@@ -162,7 +162,7 @@ describe("outputIsStale", () => {
it("should return true if the cell is interrupted but has a stale status", () => {
const cell = {
- status: "disabled-transitively" as CellStatus,
+ status: "disabled-transitively" as RuntimeState,
staleInputs: true,
output: null,
runStartTimestamp: null,
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index 333c657ba2..b83740b87c 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -37,7 +37,7 @@ import {
import { invariant } from "@/utils/invariant";
import type {
CellConfig,
- CellStatus,
+ RuntimeState,
UpdateCellIdsRequest,
} from "../network/types";
import { getUserConfig } from "@/core/config/config";
@@ -996,7 +996,7 @@ export const getCellEditorView = (cellId: CellId) => {
export function isUninstantiated(
autoInstantiate: boolean,
executionTime: number | null,
- status: CellStatus,
+ status: RuntimeState,
errored: boolean,
interrupted: boolean,
stopped: boolean,
diff --git a/frontend/src/core/cells/focus.ts b/frontend/src/core/cells/focus.ts
index 82078a96b3..14a5bafed8 100644
--- a/frontend/src/core/cells/focus.ts
+++ b/frontend/src/core/cells/focus.ts
@@ -3,7 +3,7 @@ import { atom, useAtomValue, useSetAtom } from "jotai";
import type { CellId } from "./ids";
import { type NotebookState, SCRATCH_CELL_ID, notebookAtom } from "./cells";
import type { EditorView } from "@codemirror/view";
-import type { CellConfig, CellStatus } from "../network/types";
+import type { CellConfig, RuntimeState } from "../network/types";
/**
* Holds state for the last focused cell.
@@ -27,7 +27,7 @@ export const lastFocusedCellAtom = atom<{
name: string;
config: CellConfig;
cellId: CellId;
- status: CellStatus;
+ status: RuntimeState;
getEditorView: () => EditorView | null;
hasOutput: boolean;
} | null>((get) => {
diff --git a/frontend/src/core/cells/types.ts b/frontend/src/core/cells/types.ts
index ff2f8f2d01..ba2cb5391e 100644
--- a/frontend/src/core/cells/types.ts
+++ b/frontend/src/core/cells/types.ts
@@ -1,11 +1,11 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { OutputMessage } from "../kernel/messages";
-import { SerializedEditorState } from "../codemirror/types";
-import { Outline } from "./outline";
-import { CellId } from "./ids";
+import type { OutputMessage } from "../kernel/messages";
+import type { SerializedEditorState } from "../codemirror/types";
+import type { Outline } from "./outline";
+import type { CellId } from "./ids";
import { DEFAULT_CELL_NAME } from "./names";
-import { Milliseconds, Seconds } from "@/utils/time";
-import { CellConfig, CellStatus } from "../network/types";
+import type { Milliseconds, Seconds } from "@/utils/time";
+import type { CellConfig, RuntimeState } from "../network/types";
/**
* Create a new cell with default state.
@@ -42,7 +42,7 @@ export function createCellRuntimeState(
outline: null,
output: null,
consoleOutputs: [],
- status: "idle" as CellStatus,
+ status: "idle" as RuntimeState,
staleInputs: false,
interrupted: false,
errored: false,
@@ -83,7 +83,7 @@ export interface CellRuntimeState {
/** messages encoding the cell's console outputs. */
consoleOutputs: Array<WithResponse<OutputMessage>>;
/** current status of the cell */
- status: CellStatus;
+ status: RuntimeState;
/** whether the cell has stale inputs*/
staleInputs: boolean;
/** whether this cell has been interrupted since its last run */
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index 54e76c41b1..c78b596d71 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -15,7 +15,7 @@ export type CellConfig = schemas["CellConfig"];
* idle: not running.
* disabled-transitively: disabled because an ancestor was disabled.
*/
-export type CellStatus = schemas["CellStatus"];
+export type RuntimeState = schemas["RuntimeState"];
export type CodeCompletionRequest = schemas["CodeCompletionRequest"];
export type CreationRequest = schemas["CreationRequest"];
export type DeleteCellRequest = schemas["DeleteCellRequest"];
diff --git a/marimo/_server/files/file_system.py b/marimo/_server/files/file_system.py
index 6d65348662..52c36da0e6 100644
--- a/marimo/_server/files/file_system.py
+++ b/marimo/_server/files/file_system.py
@@ -2,7 +2,7 @@
from __future__ import annotations
from abc import ABC, abstractmethod
-from typing import List, Optional
+from typing import List, Literal, Optional
from marimo._server.models.files import FileDetailsResponse, FileInfo
@@ -32,7 +32,7 @@ class FileSystem(ABC):
def create_file_or_directory(
self,
path: str,
- file_type: str,
+ file_type: Literal["file", "directory"],
name: str,
contents: Optional[bytes],
) -> FileInfo:
diff --git a/marimo/_server/files/os_file_system.py b/marimo/_server/files/os_file_system.py
index 2ab2f64aaa..8bd8b37755 100644
--- a/marimo/_server/files/os_file_system.py
+++ b/marimo/_server/files/os_file_system.py
@@ -6,7 +6,7 @@ import mimetypes
import os
import re
import shutil
-from typing import List, Optional, Union
+from typing import List, Literal, Optional, Union
from marimo._server.files.file_system import FileSystem
from marimo._server.models.files import FileDetailsResponse, FileInfo
@@ -107,7 +107,7 @@ class OSFileSystem(FileSystem):
def create_file_or_directory(
self,
path: str,
- file_type: str,
+ file_type: Literal["file", "directory"],
name: str,
contents: Optional[bytes],
) -> FileInfo:
diff --git a/marimo/_server/models/files.py b/marimo/_server/models/files.py
index a914b2d6d1..740fb4d24e 100644
--- a/marimo/_server/models/files.py
+++ b/marimo/_server/models/files.py
@@ -2,7 +2,7 @@
from __future__ import annotations
from dataclasses import dataclass, field
-from typing import List, Optional
+from typing import List, Literal, Optional
from marimo._server.models.models import BaseResponse
@@ -48,7 +48,7 @@ class FileCreateRequest:
# The path where to create the file or directory
path: str
# 'file' or 'directory'
- type: str
+ type: Literal["file", "directory"]
# The name of the file or directory
name: str
# The contents of the file, base64-encoded
diff --git a/openapi/api.yaml b/openapi/api.yaml
index b6d1d2218a..a6f1ead5db 100644
--- a/openapi/api.yaml
+++ b/openapi/api.yaml
@@ -146,7 +146,7 @@ components:
nullable: true
type: boolean
status:
- $ref: '#/components/schemas/CellStatus'
+ $ref: '#/components/schemas/RuntimeState'
nullable: true
timestamp:
type: number
@@ -177,13 +177,6 @@ components:
- data
- timestamp
type: object
- CellStatus:
- enum:
- - idle
- - queued
- - running
- - disabled-transitively
- type: string
CodeCompletionRequest:
properties:
cellId:
@@ -534,6 +527,9 @@ components:
path:
type: string
type:
+ enum:
+ - file
+ - directory
type: string
required:
- path
@@ -1435,6 +1431,13 @@ components:
required:
- filename
type: object
+ RenameRequest:
+ properties:
+ filename:
+ type: string
+ required:
+ - filename
+ type: object
RunRequest:
properties:
cellIds:
@@ -1465,6 +1468,13 @@ components:
required:
- files
type: object
+ RuntimeState:
+ enum:
+ - idle
+ - queued
+ - running
+ - disabled-transitively
+ type: string
SaveAppConfigurationRequest:
properties:
config:
@@ -1761,7 +1771,7 @@ components:
type: object
info:
title: marimo API
- version: 0.7.9
+ version: 0.7.20
openapi: 3.1.0
paths:
/@file/{filename_and_length}:
diff --git a/openapi/src/api.ts b/openapi/src/api.ts
index 96559c35c4..c71d0d7f92 100644
--- a/openapi/src/api.ts
+++ b/openapi/src/api.ts
@@ -814,7 +814,7 @@ export interface components {
name: "cell-op";
output?: components["schemas"]["CellOutput"];
stale_inputs?: boolean | null;
- status?: components["schemas"]["CellStatus"];
+ status?: components["schemas"]["RuntimeState"];
timestamp: number;
};
CellOutput: {
@@ -831,8 +831,6 @@ export interface components {
mimetype: components["schemas"]["MimeType"];
timestamp: number;
};
- /** @enum {string} */
- CellStatus: "idle" | "queued" | "running" | "disabled-transitively";
CodeCompletionRequest: {
cellId: string;
document: string;
@@ -963,7 +961,8 @@ export interface components {
contents?: string | null;
name: string;
path: string;
- type: string;
+ /** @enum {string} */
+ type: "file" | "directory";
};
FileCreateResponse: {
info?: components["schemas"]["FileInfo"];
@@ -1337,6 +1336,9 @@ export interface components {
RenameFileRequest: {
filename: string;
};
+ RenameRequest: {
+ filename: string;
+ };
RunRequest: {
cellIds: string[];
codes: string[];
@@ -1347,6 +1349,8 @@ export interface components {
RunningNotebooksResponse: {
files: components["schemas"]["MarimoFile"][];
};
+ /** @enum {string} */
+ RuntimeState: "idle" | "queued" | "running" | "disabled-transitively";
SaveAppConfigurationRequest: {
config: {
[key: string]: unknown;
diff --git a/tests/_server/files/test_os_file_system.py b/tests/_server/files/test_os_file_system.py
index 6d6117b861..7009fe9b22 100644
--- a/tests/_server/files/test_os_file_system.py
+++ b/tests/_server/files/test_os_file_system.py
@@ -24,14 +24,16 @@ def fs():
return OSFileSystem()
-def test_create_file(test_dir, fs) -> None:
+def test_create_file(test_dir: str, fs: OSFileSystem) -> None:
test_file_name = "test_file.txt"
fs.create_file_or_directory(test_dir, "file", test_file_name, None)
expected_path = os.path.join(test_dir, test_file_name)
assert os.path.exists(expected_path)
-def test_create_file_with_duplicate_name(test_dir, fs) -> None:
+def test_create_file_with_duplicate_name(
+ test_dir: str, fs: OSFileSystem
+) -> None:
test_file_name = "test_file.txt"
fs.create_file_or_directory(test_dir, "file", test_file_name, None)
# Create a file with the same name
@@ -41,24 +43,24 @@ def test_create_file_with_duplicate_name(test_dir, fs) -> None:
assert os.path.exists(expected_path)
-def test_create_directory(test_dir, fs) -> None:
+def test_create_directory(test_dir: str, fs: OSFileSystem) -> None:
test_dir_name = "test_dir"
fs.create_file_or_directory(test_dir, "directory", test_dir_name, None)
expected_path = os.path.join(test_dir, test_dir_name)
assert os.path.isdir(expected_path)
-def test_create_with_empty_name(test_dir, fs) -> None:
+def test_create_with_empty_name(test_dir: str, fs: OSFileSystem) -> None:
with pytest.raises(ValueError):
fs.create_file_or_directory(test_dir, "file", "", None)
-def test_create_with_disallowed_name(test_dir, fs) -> None:
+def test_create_with_disallowed_name(test_dir: str, fs: OSFileSystem) -> None:
with pytest.raises(ValueError):
fs.create_file_or_directory(test_dir, "file", ".", None)
-def test_list_files(test_dir, fs) -> None:
+def test_list_files(test_dir: str, fs: OSFileSystem) -> None:
# Create a test file and directory
test_create_file(test_dir, fs)
test_create_directory(test_dir, fs)
@@ -66,7 +68,9 @@ def test_list_files(test_dir, fs) -> None:
assert len(files) == 2 # Expecting 1 file and 1 directory
-def test_list_files_with_broken_directory_symlink(test_dir, fs) -> None:
+def test_list_files_with_broken_directory_symlink(
+ test_dir: str, fs: OSFileSystem
+) -> None:
# Create a broken symlink
broken_symlink = os.path.join(test_dir, "broken_symlink")
os.symlink("non_existent_file", broken_symlink)
@@ -74,7 +78,7 @@ def test_list_files_with_broken_directory_symlink(test_dir, fs) -> None:
assert len(files) == 0
-def test_get_details(test_dir, fs) -> None:
+def test_get_details(test_dir: str, fs: OSFileSystem) -> None:
test_file_name = "test_file.txt"
fs.create_file_or_directory(
test_dir,
@@ -90,7 +94,9 @@ def test_get_details(test_dir, fs) -> None:
@pytest.mark.parametrize("encoding", ["utf-8", "iso-8859-1"])
-def test_get_details_marimo_file(test_dir, fs, encoding) -> None:
+def test_get_details_marimo_file(
+ test_dir: str, fs: OSFileSystem, encoding
+) -> None:
test_file_name = "app.py"
content = """
import marimo
@@ -114,7 +120,7 @@ def test_get_details_marimo_file(test_dir, fs, encoding) -> None:
assert file_info.file.is_marimo_file
-def test_open_file(test_dir, fs) -> None:
+def test_open_file(test_dir: str, fs: OSFileSystem) -> None:
test_file_name = "test_file.txt"
test_content = "Hello, World!"
with open(os.path.join(test_dir, test_file_name), "w") as f:
@@ -123,7 +129,7 @@ def test_open_file(test_dir, fs) -> None:
assert content == test_content
-def test_delete_file(test_dir, fs) -> None:
+def test_delete_file(test_dir: str, fs: OSFileSystem) -> None:
test_file_name = "test_file.txt"
file_path = os.path.join(test_dir, test_file_name)
with open(file_path, "w"):
@@ -132,7 +138,7 @@ def test_delete_file(test_dir, fs) -> None:
assert not os.path.exists(file_path)
-def test_move_file(test_dir, fs) -> None:
+def test_move_file(test_dir: str, fs: OSFileSystem) -> None:
original_file_name = "original.txt"
new_file_name = "new.txt"
original_path = os.path.join(test_dir, original_file_name)
@@ -144,7 +150,7 @@ def test_move_file(test_dir, fs) -> None:
assert not os.path.exists(original_path)
-def test_move_with_disallowed_name(test_dir, fs) -> None:
+def test_move_with_disallowed_name(test_dir: str, fs: OSFileSystem) -> None:
original_file_name = "original.txt"
new_file_name = "."
original_path = os.path.join(test_dir, original_file_name)
@@ -155,7 +161,7 @@ def test_move_with_disallowed_name(test_dir, fs) -> None:
fs.move_file_or_directory(original_path, new_path)
-def test_update_file(test_dir, fs) -> None:
+def test_update_file(test_dir: str, fs: OSFileSystem) -> None:
test_file_name = "test_file.txt"
file_path = os.path.join(test_dir, test_file_name)
with open(file_path, "w") as f: