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: rename files, file viewer, move files (#849)

Myles Scolnick8945925469e8
diff --git a/frontend/src/components/editor/chrome/panels/file-explorer-panel.tsx b/frontend/src/components/editor/chrome/panels/file-explorer-panel.tsx
index 3fe1f38af9..d0f19bac53 100644
--- a/frontend/src/components/editor/chrome/panels/file-explorer-panel.tsx
+++ b/frontend/src/components/editor/chrome/panels/file-explorer-panel.tsx
@@ -4,12 +4,10 @@ import React from "react";
import useResizeObserver from "use-resize-observer";
import { FileExplorer } from "../../file-tree/file-explorer";
-export const FileExplorerPanel: React.FC = (props) => {
+export const FileExplorerPanel: React.FC = () => {
const { ref, height = 1 } = useResizeObserver<HTMLDivElement>();
-
return (
- <div ref={ref} className="h-full">
- <div id="noop-dnd-container" />
+ <div ref={ref} className="flex flex-col flex-1 overflow-hidden">
<FileExplorer height={height} />
</div>
);
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
new file mode 100644
index 0000000000..cd6b98f474
--- /dev/null
+++ b/frontend/src/components/editor/file-tree/__tests__/requesting-tree.test.ts
@@ -0,0 +1,240 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { beforeEach, afterEach, expect, vi, describe, test } from "vitest";
+import { RequestingTree } from "../requesting-tree";
+import { toast } from "@/components/ui/use-toast";
+
+const sendListFiles = vi.fn();
+const sendCreateFileOrFolder = vi.fn();
+const sendDeleteFileOrFolder = vi.fn();
+const sendRenameFileOrFolder = vi.fn();
+
+vi.mock("@/components/ui/use-toast", () => ({
+ toast: vi.fn(),
+}));
+
+describe("RequestingTree", () => {
+ let requestingTree: RequestingTree;
+ const mockOnChange = vi.fn();
+
+ beforeEach(async () => {
+ requestingTree = new RequestingTree({
+ listFiles: sendListFiles,
+ createFileOrFolder: sendCreateFileOrFolder,
+ deleteFileOrFolder: sendDeleteFileOrFolder,
+ renameFileOrFolder: sendRenameFileOrFolder,
+ });
+ sendListFiles.mockResolvedValue({
+ files: [
+ { id: "1.1", name: "file1", path: "/root/file1" },
+ {
+ id: "1.2",
+ name: "folder1",
+ isDirectory: true,
+ path: "/root/folder1",
+ },
+ {
+ id: "1.3",
+ name: "folder2",
+ isDirectory: true,
+ path: "/root/folder2",
+ },
+ ],
+ root: "/root",
+ });
+ await requestingTree.initialize(mockOnChange);
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ test("initialize should load files and set rootPath", async () => {
+ expect(sendListFiles).toHaveBeenCalledWith({ path: "" });
+ expect(mockOnChange).toHaveBeenCalledWith([
+ { id: "1.1", name: "file1", path: "/root/file1" },
+ { id: "1.2", name: "folder1", isDirectory: true, path: "/root/folder1" },
+ { id: "1.3", name: "folder2", isDirectory: true, path: "/root/folder2" },
+ ]);
+ });
+
+ test("expand should load children for a directory", async () => {
+ sendListFiles.mockResolvedValue({
+ files: [{ id: "2", name: "file2", path: "/roo/folder1/file2" }],
+ });
+ const result = await requestingTree.expand("1.2");
+ expect(result).toBe(true);
+ expect(sendListFiles).toHaveBeenCalledWith({ path: "/root/folder1" });
+ expect(mockOnChange).toHaveBeenCalled();
+ expect(mockOnChange.mock.calls.at(-1)[0]).toMatchInlineSnapshot(`
+ [
+ {
+ "id": "1.1",
+ "name": "file1",
+ "path": "/root/file1",
+ },
+ {
+ "children": [
+ {
+ "id": "2",
+ "name": "file2",
+ "path": "/roo/folder1/file2",
+ },
+ ],
+ "id": "1.2",
+ "isDirectory": true,
+ "name": "folder1",
+ "path": "/root/folder1",
+ },
+ {
+ "id": "1.3",
+ "isDirectory": true,
+ "name": "folder2",
+ "path": "/root/folder2",
+ },
+ ]
+ `);
+ });
+
+ test("rename should change the name and path of a file", async () => {
+ sendRenameFileOrFolder.mockResolvedValue({ success: true });
+
+ await requestingTree.rename("1.1", "file2");
+ expect(sendRenameFileOrFolder).toHaveBeenCalledWith({
+ path: "/root/file1",
+ newPath: "/root/file2",
+ });
+ expect(mockOnChange).toHaveBeenCalled();
+ expect(mockOnChange.mock.calls.at(-1)[0]).toMatchInlineSnapshot(`
+ [
+ {
+ "id": "1.1",
+ "name": "file2",
+ "path": "/root/file2",
+ },
+ {
+ "id": "1.2",
+ "isDirectory": true,
+ "name": "folder1",
+ "path": "/root/folder1",
+ },
+ {
+ "id": "1.3",
+ "isDirectory": true,
+ "name": "folder2",
+ "path": "/root/folder2",
+ },
+ ]
+ `);
+ });
+
+ test("move should change the parent of a file", async () => {
+ sendRenameFileOrFolder.mockResolvedValue({ success: true });
+
+ await requestingTree.move(["1.1"], "1.2");
+ expect(sendRenameFileOrFolder).toHaveBeenCalled();
+ expect(mockOnChange).toHaveBeenCalled();
+ expect(mockOnChange.mock.calls.at(-1)[0]).toMatchInlineSnapshot(`
+ [
+ {
+ "id": "1.1",
+ "name": "file1",
+ "path": "/root/file1",
+ },
+ {
+ "children": [
+ {
+ "id": "1.1",
+ "name": "file1",
+ "path": "/root/folder1/file1",
+ },
+ ],
+ "id": "1.2",
+ "isDirectory": true,
+ "name": "folder1",
+ "path": "/root/folder1",
+ },
+ {
+ "id": "1.3",
+ "isDirectory": true,
+ "name": "folder2",
+ "path": "/root/folder2",
+ },
+ ]
+ `);
+ });
+
+ test("refreshAll should refresh data for all open folders", async () => {
+ await requestingTree.refreshAll(["1.1"]);
+ expect(sendListFiles).toHaveBeenCalled();
+ expect(mockOnChange).toHaveBeenCalled();
+ expect(mockOnChange.mock.calls.at(-1)[0]).toMatchInlineSnapshot(`
+ [
+ {
+ "id": "1.1",
+ "name": "file1",
+ "path": "/root/file1",
+ },
+ {
+ "id": "1.2",
+ "isDirectory": true,
+ "name": "folder1",
+ "path": "/root/folder1",
+ },
+ {
+ "id": "1.3",
+ "isDirectory": true,
+ "name": "folder2",
+ "path": "/root/folder2",
+ },
+ ]
+ `);
+ });
+
+ describe("when API fails", () => {
+ test("initialize should handle errors gracefully", async () => {
+ requestingTree = new RequestingTree({
+ listFiles: sendListFiles,
+ createFileOrFolder: sendCreateFileOrFolder,
+ deleteFileOrFolder: sendDeleteFileOrFolder,
+ renameFileOrFolder: sendRenameFileOrFolder,
+ });
+ sendListFiles.mockRejectedValue(new Error("Network error"));
+ await requestingTree.initialize(mockOnChange);
+ expect(toast).toHaveBeenCalledWith({
+ title: "Failed",
+ description: expect.any(String),
+ });
+ });
+
+ test("rename should handle API failure", async () => {
+ sendRenameFileOrFolder.mockResolvedValue({
+ success: false,
+ message: "Error renaming",
+ });
+
+ await requestingTree.rename("1.1", "file2");
+ expect(sendRenameFileOrFolder).toHaveBeenCalledWith({
+ path: "/root/file1",
+ newPath: "/root/file2",
+ });
+ expect(toast).toHaveBeenCalledWith({
+ title: "Failed",
+ description: "Error renaming",
+ });
+ });
+
+ test("move should handle missing parent node gracefully", async () => {
+ await requestingTree.move(["1.x"], "2");
+ expect(sendRenameFileOrFolder).not.toHaveBeenCalled();
+ expect(mockOnChange).toHaveBeenCalledTimes(3);
+ });
+
+ test("refreshAll should handle API errors without crashing", async () => {
+ sendListFiles.mockRejectedValue(new Error("Network error"));
+ await requestingTree.refreshAll(["1.2"]);
+ expect(sendListFiles).toHaveBeenCalled();
+ // Ensure onChange is still called to update UI even if data might not have changed
+ expect(mockOnChange).toHaveBeenCalled();
+ });
+ });
+});
diff --git a/frontend/src/components/editor/file-tree/file-explorer.tsx b/frontend/src/components/editor/file-tree/file-explorer.tsx
index ecbbcae7ca..e2cbc075a0 100644
--- a/frontend/src/components/editor/file-tree/file-explorer.tsx
+++ b/frontend/src/components/editor/file-tree/file-explorer.tsx
@@ -1,14 +1,26 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { NodeApi, NodeRendererProps, Tree, SimpleTree } from "react-arborist";
+import { NodeApi, NodeRendererProps, Tree } from "react-arborist";
-import React from "react";
+import React, { useEffect, useRef, useState } from "react";
import {
+ ArrowLeftIcon,
ChevronDownIcon,
ChevronRightIcon,
+ CopyIcon,
+ Edit3Icon,
+ MoreVerticalIcon,
PlaySquareIcon,
+ RefreshCcwIcon,
+ ViewIcon,
} from "lucide-react";
import { useOnMount } from "@/hooks/useLifecycle";
-import { openFile, sendListFiles } from "@/core/network/requests";
+import {
+ openFile,
+ sendCreateFileOrFolder,
+ sendDeleteFileOrFolder,
+ sendListFiles,
+ sendRenameFileOrFolder,
+} from "@/core/network/requests";
import { FileInfo } from "@/core/network/types";
import {
FILE_TYPE_ICONS,
@@ -17,93 +29,183 @@ import {
guessFileType,
} from "./types";
import { toast } from "@/components/ui/use-toast";
-import { Tooltip } from "@/components/ui/tooltip";
import { useImperativeModal } from "@/components/modal/ImperativeModal";
import { AlertDialogAction } from "@/components/ui/alert-dialog";
import { atom, useAtom } from "jotai";
+import { Button } from "@/components/ui/button";
+
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Tooltip } from "@/components/ui/tooltip";
+import { cn } from "@/utils/cn";
+import { RequestingTree } from "./requesting-tree";
+import { FileViewer } from "./file-viewer";
// State lives outside of the component
// to preserve the state when the component is unmounted
-const treeAtom = atom<SimpleTree<FileInfo>>(new SimpleTree<FileInfo>([]));
+const treeAtom = atom<RequestingTree>(
+ new RequestingTree({
+ listFiles: sendListFiles,
+ createFileOrFolder: sendCreateFileOrFolder,
+ deleteFileOrFolder: sendDeleteFileOrFolder,
+ renameFileOrFolder: sendRenameFileOrFolder,
+ }),
+);
const openStateAtom = atom<Record<string, boolean>>({});
export const FileExplorer: React.FC<{
height: number;
}> = ({ height }) => {
- const [tree, setTree] = useAtom(treeAtom);
+ const [tree] = useAtom(treeAtom);
+ const [data, setData] = useState<FileInfo[]>([]);
const [openState, setOpenState] = useAtom(openStateAtom);
+ const [openFile, setOpenFile] = useState<FileInfo | null>(null);
useOnMount(() => {
- if (tree.data.length > 0) {
- return;
- }
- // Fetch initial data on mount
- sendListFiles({ path: undefined }).then((data) => {
- setTree(new SimpleTree(data.files));
- });
+ void tree.initialize(setData);
});
- // This is a HACK so that we don't opt into react-arborist's drag and drop
- // Their DnD implementation is removable and it causes issues with our
- // our own DnD
- const element = document.getElementById("noop-dnd-container");
- if (!element) {
- return null;
+ if (openFile) {
+ return (
+ <>
+ <div className="flex items-center pl-1 pr-3 flex-shrink-0 border-b justify-between">
+ <Button
+ onClick={() => setOpenFile(null)}
+ variant="text"
+ size="xs"
+ className="mb-0"
+ >
+ <ArrowLeftIcon size={16} />
+ </Button>
+ <span className="font-bold">{openFile.name}</span>
+ </div>
+ <FileViewer file={openFile} />
+ </>
+ );
}
return (
<>
+ <Toolbar
+ onRefresh={() =>
+ tree.refreshAll(Object.keys(openState).filter((id) => openState[id]))
+ }
+ />
<Tree<FileInfo>
width="100%"
- height={height}
+ height={height - 26}
className="h-full"
- data={tree.data}
- dndRootElement={element}
+ data={data}
initialOpenState={openState}
openByDefault={false}
- onToggle={(id) => {
- const node = tree.find(id);
- if (!node) {
- return;
- }
- if (!node.data.isDirectory) {
+ // Hide the drop cursor
+ renderCursor={() => null}
+ // Disable dropping files into files
+ disableDrop={({ parentNode }) => !parentNode.data.isDirectory}
+ onRename={async ({ id, name }) => {
+ await tree.rename(id, name);
+ }}
+ onMove={async ({ dragIds, parentId }) => {
+ await tree.move(dragIds, parentId);
+ }}
+ onSelect={(nodes) => {
+ const first = nodes[0];
+ if (!first) {
return;
}
-
- // We may attempt to load empty directories multiple times
- // but that is fine
- if (node.children && node.children.length > 0) {
- // Already loaded
- return;
+ if (!first.data.isDirectory) {
+ setOpenFile(first.data);
}
-
- sendListFiles({ path: id }).then((data) => {
- tree.update({ id, changes: { children: data.files } });
- setTree(new SimpleTree(tree.data));
+ }}
+ onToggle={async (id) => {
+ const result = await tree.expand(id);
+ if (result) {
const prevOpen = openState[id] ?? false;
setOpenState({ ...openState, [id]: !prevOpen });
- });
+ }
}}
padding={15}
rowHeight={30}
indent={INDENT_STEP}
overscanCount={1000}
- // Disable all interactions
+ // Disable multi-selection
disableMultiSelection={true}
- disableDrag={true}
- disableDrop={true}
- disableEdit={true}
>
{Node}
</Tree>
- <div id="noop-dnd-container" />
</>
);
};
const INDENT_STEP = 15;
-const Node = ({ node, style }: NodeRendererProps<FileInfo>) => {
+const Toolbar = ({ onRefresh }: { onRefresh: () => void }) => {
+ return (
+ <div className="flex items-center justify-end px-2 flex-shrink-0 border-b">
+ <Tooltip content="Refresh">
+ <Button onClick={onRefresh} variant="text" size="xs" className="mb-0">
+ <RefreshCcwIcon size={16} />
+ </Button>
+ </Tooltip>
+ </div>
+ );
+};
+
+const Show = ({ node }: { node: NodeApi<FileInfo> }) => {
+ return (
+ <span
+ className="flex-1"
+ onClick={(e) => {
+ e.stopPropagation();
+ if (node.data.isDirectory) {
+ return;
+ }
+ node.select();
+ }}
+ >
+ {node.data.name}
+ </span>
+ );
+};
+
+const Edit = ({ node }: { node: NodeApi<FileInfo> }) => {
+ const ref = useRef<HTMLInputElement>(null);
+ useEffect(() => {
+ ref.current?.focus();
+ // Select everything, but the extension
+ ref.current?.setSelectionRange(0, node.data.name.lastIndexOf("."));
+ }, [node.data.name]);
+
+ return (
+ <input
+ ref={ref}
+ className="flex-1 bg-transparent border border-border text-muted-foreground"
+ defaultValue={node.data.name}
+ onClick={(e) => e.stopPropagation()}
+ onBlur={() => node.reset()}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ node.reset();
+ }
+ if (e.key === "Enter") {
+ node.submit(e.currentTarget.value);
+ }
+ }}
+ />
+ );
+};
+
+const Node = ({
+ node,
+ style,
+ tree,
+ dragHandle,
+}: NodeRendererProps<FileInfo>) => {
const fileType: FileType = node.data.isDirectory
? "directory"
: guessFileType(node.data.name);
@@ -111,69 +213,117 @@ const Node = ({ node, style }: NodeRendererProps<FileInfo>) => {
const Icon = FILE_TYPE_ICONS[fileType];
const { openConfirm } = useImperativeModal();
+ const handleOpenMarimoFile = async (evt: Event) => {
+ evt.stopPropagation();
+ evt.preventDefault();
+ openConfirm({
+ title: "Open notebook",
+ description:
+ "This will close the current notebook and open the selected notebook. You'll lose all data that's in memory.",
+ confirmAction: (
+ <AlertDialogAction
+ onClick={async () => {
+ await openFile({ path: node.data.path });
+ }}
+ aria-label="Confirm"
+ >
+ Open
+ </AlertDialogAction>
+ ),
+ });
+ };
+
return (
<div
style={style}
- className="flex items-center cursor-pointer ml-1 text-muted-foreground whitespace-nowrap"
+ ref={dragHandle}
+ className={cn(
+ "flex items-center cursor-pointer ml-1 text-muted-foreground whitespace-nowrap group",
+ )}
+ draggable={true}
onClick={(evt) => {
+ evt.stopPropagation();
if (node.data.isDirectory) {
node.toggle();
- evt.stopPropagation();
}
}}
>
<FolderArrow node={node} />
<span
- className="flex items-center gap-2 px-1 py-1 cursor-pointer hover:bg-accent/50 hover:text-accent-foreground rounded-l flex-1"
- draggable={true}
- onDragStart={(e) => {
- const { path } = node.data;
- const pythonCode = PYTHON_CODE_FOR_FILE_TYPE[fileType](path);
- e.dataTransfer.setData("text/plain", pythonCode);
- e.stopPropagation();
- }}
- onClick={() => {
- if (node.data.isDirectory) {
- return;
- }
-
- 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);
- }}
+ className={cn(
+ "flex items-center gap-2 px-1 py-1 cursor-pointer hover:bg-accent/50 hover:text-accent-foreground rounded-l flex-1",
+ node.willReceiveDrop &&
+ node.data.isDirectory &&
+ "bg-accent/80 hover:bg-accent/80 text-accent-foreground",
+ )}
>
<Icon className="w-5 h-5 flex-shrink-0" strokeWidth={1.5} />
- <span className="flex-1">{node.data.name}</span>
- {node.data.isMarimoFile ? (
- <Tooltip content="Open file">
- <PlaySquareIcon
- strokeWidth={1.5}
- onClick={async (e) => {
- e.stopPropagation();
- openConfirm({
- title: "Open notebook",
+ {node.isEditing ? <Edit node={node} /> : <Show node={node} />}
+ <DropdownMenu modal={false}>
+ <DropdownMenuTrigger
+ asChild={true}
+ tabIndex={-1}
+ onClick={(e) => e.stopPropagation()}
+ >
+ <Button
+ variant="text"
+ tabIndex={-1}
+ size="xs"
+ className="mb-0"
+ aria-label="More options"
+ >
+ <MoreVerticalIcon
+ strokeWidth={2}
+ className="w-5 h-5 hidden group-hover:block"
+ />
+ </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",
description:
- "This will close the current notebook and open the selected notebook. You'll lose all data that's in memory.",
- confirmAction: (
- <AlertDialogAction
- onClick={async () => {
- await openFile({ path: node.data.path });
- }}
- aria-label="Confirm"
- >
- Open
- </AlertDialogAction>
- ),
+ "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);
}}
- />
- </Tooltip>
- ) : null}
+ >
+ <CopyIcon className="mr-2" size={14} strokeWidth={1.5} />
+ Copy snippet to clipboard
+ </DropdownMenuItem>
+ {node.data.isMarimoFile && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onSelect={handleOpenMarimoFile}>
+ <PlaySquareIcon
+ className="mr-2"
+ size={14}
+ strokeWidth={1.5}
+ />
+ Open notebook
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </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
new file mode 100644
index 0000000000..532b2bd76e
--- /dev/null
+++ b/frontend/src/components/editor/file-tree/file-viewer.tsx
@@ -0,0 +1,64 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { sendFileDetails } from "@/core/network/requests";
+import { FileInfo } from "@/core/network/types";
+import { useAsyncData } from "@/hooks/useAsyncData";
+import AnyLanguageCodeMirror from "@/plugins/impl/code/any-language-editor";
+import { ErrorBanner } from "@/plugins/impl/common/error-banner";
+import { EditorView } from "@codemirror/view";
+import React from "react";
+
+interface Props {
+ file: FileInfo;
+}
+
+export const FileViewer: React.FC<Props> = ({ file }) => {
+ const { data, loading, error } = useAsyncData(() => {
+ return sendFileDetails({ path: file.path });
+ }, [file.path]);
+
+ if (error) {
+ return <ErrorBanner error={error} />;
+ }
+
+ if (loading || !data) {
+ return null;
+ }
+
+ if (!data.contents) {
+ // Show details instead of contents
+ return (
+ <div className="grid grid-cols-2 gap-2 p-6">
+ <div className="font-bold text-muted-foreground">Name</div>
+ <div>{data.file.name}</div>
+ <div className="font-bold text-muted-foreground">Type</div>
+ <div>{data.mimeType}</div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex-1 overflow-auto">
+ <AnyLanguageCodeMirror
+ language={
+ mimeToLanguage[data.mimeType || "default"] || mimeToLanguage.default
+ }
+ className="border-b"
+ extensions={[EditorView.lineWrapping]}
+ value={data.contents}
+ readOnly={true}
+ />
+ </div>
+ );
+};
+
+const mimeToLanguage: Record<string, string> = {
+ "application/javascript": "javascript",
+ "text/markdown": "markdown",
+ "text/html": "html",
+ "text/css": "css",
+ "text/x-python": "python",
+ "application/json": "json",
+ "application/xml": "xml",
+ "text/x-yaml": "yaml",
+ default: "text",
+};
diff --git a/frontend/src/components/editor/file-tree/requesting-tree.tsx b/frontend/src/components/editor/file-tree/requesting-tree.tsx
new file mode 100644
index 0000000000..0631d50bbc
--- /dev/null
+++ b/frontend/src/components/editor/file-tree/requesting-tree.tsx
@@ -0,0 +1,158 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { toast } from "@/components/ui/use-toast";
+import type {
+ sendListFiles,
+ sendCreateFileOrFolder,
+ sendDeleteFileOrFolder,
+ sendRenameFileOrFolder,
+} from "@/core/network/requests";
+import { FileInfo, FileOperationResponse } from "@/core/network/types";
+import { prettyError } from "@/utils/errors";
+import { Functions } from "@/utils/functions";
+import { FilePath, PathBuilder } from "@/utils/paths";
+import { SimpleTree } from "react-arborist";
+
+export class RequestingTree {
+ private delegate = new SimpleTree<FileInfo>([]);
+
+ constructor(
+ private callbacks: {
+ listFiles: typeof sendListFiles;
+ createFileOrFolder: typeof sendCreateFileOrFolder;
+ deleteFileOrFolder: typeof sendDeleteFileOrFolder;
+ renameFileOrFolder: typeof sendRenameFileOrFolder;
+ },
+ ) {}
+
+ private rootPath: FilePath = "" as FilePath;
+ private onChange: (data: FileInfo[]) => void = Functions.NOOP;
+ private path = new PathBuilder("/");
+
+ initialize = async (onChange: (data: FileInfo[]) => void): Promise<void> => {
+ this.onChange = onChange;
+ if (this.delegate.data.length === 0) {
+ try {
+ const data = await this.callbacks.listFiles({ path: this.rootPath });
+ this.delegate = new SimpleTree(data.files);
+ this.rootPath = data.root;
+ this.path = PathBuilder.guessDeliminator(data.root);
+ } catch (error) {
+ toast({
+ title: "Failed",
+ description: prettyError(error),
+ });
+ }
+ }
+
+ this.onChange(this.delegate.data);
+ };
+
+ async expand(id: string): Promise<boolean> {
+ const node = this.delegate.find(id);
+ if (!node) {
+ return false;
+ }
+ if (!node.data.isDirectory) {
+ return false;
+ }
+
+ // We may attempt to load empty directories multiple times
+ // but that is fine
+ if (node.children && node.children.length > 0) {
+ // Already loaded
+ return true;
+ }
+
+ const data = await this.callbacks.listFiles({ path: node.data.path });
+ this.delegate.update({ id, changes: { children: data.files } });
+ this.onChange(this.delegate.data);
+ return true;
+ }
+
+ async rename(id: string, name: string): Promise<void> {
+ const node = this.delegate.find(id);
+ if (!node) {
+ return;
+ }
+ const currentPath = node.data.path;
+ const newPath = this.path.join(this.path.dirname(currentPath), name);
+ await this.callbacks
+ .renameFileOrFolder({
+ path: currentPath,
+ newPath: newPath,
+ })
+ .then(this.handleResponse);
+ this.delegate.update({ id, changes: { name, path: newPath } });
+ this.onChange(this.delegate.data);
+ }
+
+ async move(fromIds: string[], parentId: string | null): Promise<void> {
+ const parentPath = parentId
+ ? this.delegate.find(parentId)?.data.path ?? parentId
+ : this.rootPath;
+
+ await Promise.all(
+ fromIds.map((id) => {
+ this.delegate.move({ id, parentId, index: 0 });
+ const node = this.delegate.find(id);
+ if (!node) {
+ return Promise.resolve();
+ }
+ const newPath = this.path.join(
+ parentPath,
+ this.path.basename(node.data.path),
+ );
+ this.delegate.update({ id, changes: { path: newPath } });
+ return this.callbacks
+ .renameFileOrFolder({
+ path: node.data.path,
+ newPath: newPath,
+ })
+ .then(this.handleResponse);
+ }),
+ );
+
+ this.onChange(this.delegate.data);
+
+ // Refresh the parent folder
+ await this.refreshAll([parentPath]);
+ }
+
+ refreshAll = async (ids: string[]): Promise<void> => {
+ // For each open folder, refresh
+ const openFolders = [
+ this.rootPath,
+ ...ids.map((id) => this.delegate.find(id)?.data.path),
+ ].filter(Boolean);
+ // Request all folders in parallel, and catch any errors
+ const datas = await Promise.all(
+ openFolders.map((path) =>
+ this.callbacks.listFiles({ path: path }).catch(() => ({ files: [] })),
+ ),
+ );
+
+ for (const [idx, openFolder] of openFolders.entries()) {
+ const data = datas[idx];
+ if (openFolder === this.rootPath) {
+ this.delegate = new SimpleTree(data.files);
+ } else {
+ this.delegate.update({
+ id: openFolder,
+ changes: { children: data.files },
+ });
+ }
+ }
+
+ this.onChange(this.delegate.data);
+ };
+
+ private handleResponse = (response: FileOperationResponse): void => {
+ if (!response.success) {
+ toast({
+ title: "Failed",
+ description: response.message,
+ });
+ return;
+ }
+ };
+}
diff --git a/frontend/src/core/network/requests.ts b/frontend/src/core/network/requests.ts
index 76d4642546..05cf4f8cc0 100644
--- a/frontend/src/core/network/requests.ts
+++ b/frontend/src/core/network/requests.ts
@@ -23,6 +23,11 @@ import {
EditRequests,
SendStdin,
FileListResponse,
+ FileCreateRequest,
+ FileOperationResponse,
+ FileDeleteRequest,
+ FileUpdateRequest,
+ FileDetailsResponse,
} from "./types";
import { invariant } from "@/utils/invariant";
@@ -146,6 +151,30 @@ function createNetworkRequests(): EditRequests & RunRequests {
request,
);
},
+ sendCreateFileOrFolder: (request) => {
+ return API.post<FileCreateRequest, FileOperationResponse>(
+ "/files/create",
+ request,
+ );
+ },
+ sendDeleteFileOrFolder: (request) => {
+ return API.post<FileDeleteRequest, FileOperationResponse>(
+ "/files/delete",
+ request,
+ );
+ },
+ sendRenameFileOrFolder: (request) => {
+ return API.post<FileUpdateRequest, FileOperationResponse>(
+ "/files/update",
+ request,
+ );
+ },
+ sendFileDetails: (request: { path: string }) => {
+ return API.post<{ path: string }, FileDetailsResponse>(
+ "/files/file_details",
+ request,
+ );
+ },
};
}
@@ -169,6 +198,10 @@ export const {
readCode,
openFile,
sendListFiles,
+ sendCreateFileOrFolder,
+ sendDeleteFileOrFolder,
+ sendRenameFileOrFolder,
+ sendFileDetails,
} = isPyodide()
? PyodideBridge.INSTANCE
: isStaticNotebook()
diff --git a/frontend/src/core/network/static-requests.ts b/frontend/src/core/network/static-requests.ts
index fc20f9905f..8593dfd56c 100644
--- a/frontend/src/core/network/static-requests.ts
+++ b/frontend/src/core/network/static-requests.ts
@@ -52,5 +52,9 @@ export function createStaticRequests(): EditRequests & RunRequests {
readCode: throwNotInEditMode,
openFile: throwNotInEditMode,
sendListFiles: throwNotInEditMode,
+ sendCreateFileOrFolder: throwNotInEditMode,
+ sendDeleteFileOrFolder: throwNotInEditMode,
+ sendRenameFileOrFolder: throwNotInEditMode,
+ sendFileDetails: throwNotInEditMode,
};
}
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index cae8eae287..91b7787c60 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -4,6 +4,7 @@ import { LayoutType } from "@/components/editor/renderers/types";
import { CellId } from "../cells/ids";
import { CellConfig } from "../cells/types";
import { RequestId } from "./DeferredRequestRegistry";
+import { FilePath } from "@/utils/paths";
// Ideally this would be generated from server.py, but for now we just
// manually keep them in sync.
@@ -100,7 +101,7 @@ export interface ValueUpdate {
export interface FileInfo {
id: string;
- path: string;
+ path: FilePath;
name: string;
isDirectory: boolean;
isMarimoFile: boolean;
@@ -108,12 +109,38 @@ export interface FileInfo {
}
export interface FileListRequest {
- path: string | undefined;
+ path: FilePath | undefined;
}
export interface FileListResponse {
files: FileInfo[];
- root: string;
+ root: FilePath;
+}
+
+export interface FileCreateRequest {
+ path: FilePath;
+ type: "file" | "directory";
+ name: string;
+}
+
+export interface FileDeleteRequest {
+ path: FilePath;
+}
+
+export interface FileUpdateRequest {
+ path: FilePath;
+ newPath: FilePath;
+}
+
+export interface FileOperationResponse {
+ success: boolean;
+ message: string | undefined;
+}
+
+export interface FileDetailsResponse {
+ file: FileInfo;
+ mimeType: string | undefined;
+ contents: string | undefined;
}
/**
@@ -146,4 +173,14 @@ export interface EditRequests {
openFile: (request: { path: string }) => Promise<null>;
// File explorer requests
sendListFiles: (request: FileListRequest) => Promise<FileListResponse>;
+ sendCreateFileOrFolder: (
+ request: FileCreateRequest,
+ ) => Promise<FileOperationResponse>;
+ sendDeleteFileOrFolder: (
+ request: FileDeleteRequest,
+ ) => Promise<FileOperationResponse>;
+ sendRenameFileOrFolder: (
+ request: FileUpdateRequest,
+ ) => Promise<FileOperationResponse>;
+ sendFileDetails: (request: { path: string }) => Promise<FileDetailsResponse>;
}
diff --git a/frontend/src/core/pyodide/bridge.ts b/frontend/src/core/pyodide/bridge.ts
index ebf141c698..2c2b390aa8 100644
--- a/frontend/src/core/pyodide/bridge.ts
+++ b/frontend/src/core/pyodide/bridge.ts
@@ -5,8 +5,13 @@ import { CellId } from "../cells/ids";
import {
CodeCompletionRequest,
EditRequests,
+ FileCreateRequest,
+ FileDeleteRequest,
+ FileDetailsResponse,
FileListRequest,
FileListResponse,
+ FileOperationResponse,
+ FileUpdateRequest,
FormatRequest,
FormatResponse,
InstantiateRequest,
@@ -67,7 +72,6 @@ export class PyodideBridge implements RunRequests, EditRequests {
this.worker.onmessage = this.handleWorkerMessage;
}
}
-
private setCode = async () => {
// Pass the code to the worker
// If a filename is provided, it will be used to save the file
@@ -274,6 +278,46 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
+ sendCreateFileOrFolder = async (
+ request: FileCreateRequest,
+ ): Promise<FileOperationResponse> => {
+ const response = await this.fetcher.request({
+ functionName: "create_file_or_directory",
+ payload: request,
+ });
+ return response as FileOperationResponse;
+ };
+
+ sendDeleteFileOrFolder = async (
+ request: FileDeleteRequest,
+ ): Promise<FileOperationResponse> => {
+ const response = await this.fetcher.request({
+ functionName: "delete_file_or_directory",
+ payload: request,
+ });
+ return response as FileOperationResponse;
+ };
+
+ sendRenameFileOrFolder = async (
+ request: FileUpdateRequest,
+ ): Promise<FileOperationResponse> => {
+ const response = await this.fetcher.request({
+ functionName: "update_file_or_directory",
+ payload: request,
+ });
+ return response as FileOperationResponse;
+ };
+
+ sendFileDetails = async (request: {
+ path: string;
+ }): Promise<FileDetailsResponse> => {
+ const response = await this.fetcher.request({
+ functionName: "file_details",
+ payload: request,
+ });
+ return response as FileDetailsResponse;
+ };
+
private putControlRequest = async (operation: object) => {
await this.fetcher.request({
functionName: "put_control_request",
diff --git a/frontend/src/core/pyodide/worker/types.ts b/frontend/src/core/pyodide/worker/types.ts
index 086ea7117e..80a75f791f 100644
--- a/frontend/src/core/pyodide/worker/types.ts
+++ b/frontend/src/core/pyodide/worker/types.ts
@@ -2,8 +2,13 @@
import type { RequestId } from "@/core/network/DeferredRequestRegistry";
import type {
CodeCompletionRequest,
+ FileCreateRequest,
+ FileDeleteRequest,
+ FileDetailsResponse,
FileListRequest,
FileListResponse,
+ FileOperationResponse,
+ FileUpdateRequest,
FormatRequest,
FormatResponse,
SaveAppConfigRequest,
@@ -21,10 +26,16 @@ export interface RawBridge {
save_app_config(request: SaveAppConfigRequest): Promise<string>;
rename_file(request: string): Promise<string>;
list_files(request: FileListRequest): Promise<FileListResponse>;
- file_details(request: string): Promise<string>;
- create_file_or_directory(request: string): Promise<string>;
- delete_file_or_directory(request: string): Promise<string>;
- update_file_or_directory(request: string): Promise<string>;
+ file_details(request: { path: string }): Promise<FileDetailsResponse>;
+ create_file_or_directory(
+ request: FileCreateRequest,
+ ): Promise<FileOperationResponse>;
+ delete_file_or_directory(
+ request: FileDeleteRequest,
+ ): Promise<FileOperationResponse>;
+ update_file_or_directory(
+ request: FileUpdateRequest,
+ ): Promise<FileOperationResponse>;
load_packages(request: string): Promise<string>;
read_file(request: string): Promise<string>;
[Symbol.asyncIterator](): AsyncIterator<string>;
diff --git a/frontend/src/core/pyodide/worker/worker.ts b/frontend/src/core/pyodide/worker/worker.ts
index dcfad75f62..45a914adb4 100644
--- a/frontend/src/core/pyodide/worker/worker.ts
+++ b/frontend/src/core/pyodide/worker/worker.ts
@@ -3,6 +3,7 @@
import { bootstrap, startSession } from "./bootstrap";
import type { PyodideInterface } from "pyodide";
import {
+ RawBridge,
SerializedBridge,
WorkerClientPayload,
WorkerServerPayload,
@@ -119,8 +120,8 @@ self.onmessage = async (event: MessageEvent<WorkerServerPayload>) => {
id,
});
- // Sync the filesystem if we're saving or renaming a file
- if (functionName === "save" || functionName === "rename_file") {
+ // Sync the filesystem if we're saving, creating, deleting, or renaming a file
+ if (namesThatRequireSync.has(functionName)) {
await syncFileSystem(self.pyodide);
}
} catch (error) {
@@ -133,6 +134,14 @@ self.onmessage = async (event: MessageEvent<WorkerServerPayload>) => {
}
};
+const namesThatRequireSync = new Set<keyof RawBridge>([
+ "save",
+ "rename_file",
+ "create_file_or_directory",
+ "delete_file_or_directory",
+ "update_file_or_directory",
+]);
+
function postMessage(message: WorkerClientPayload) {
self.postMessage(message);
}
diff --git a/frontend/src/css/Cell.css b/frontend/src/css/Cell.css
index 82e53a6ad4..e2abd5adfb 100644
--- a/frontend/src/css/Cell.css
+++ b/frontend/src/css/Cell.css
@@ -305,15 +305,16 @@
.cm-editor {
font-size: var(--marimo-code-editor-font-size);
+}
+
+/* .Cell is needed to take precedence over codemirror's generated class ... */
+.Cell .cm-editor {
border: 1px solid transparent;
padding: 3px;
/* leave some room for UI elements inside the code editor */
padding-right: 24px;
-}
-/* .Cell is needed to take precedence over codemirror's generated class ... */
-.Cell .cm-editor {
&.cm-focused {
outline: 0;
diff --git a/frontend/src/plugins/impl/CodeEditorPlugin.tsx b/frontend/src/plugins/impl/CodeEditorPlugin.tsx
index 5423d7d403..8fe6af4dbe 100644
--- a/frontend/src/plugins/impl/CodeEditorPlugin.tsx
+++ b/frontend/src/plugins/impl/CodeEditorPlugin.tsx
@@ -4,7 +4,7 @@ import { IPlugin, IPluginProps, Setter } from "../types";
import { Labeled } from "./common/labeled";
import { Theme, useTheme } from "@/theme/useTheme";
-import { lazy } from "react";
+import { LazyAnyLanguageCodeMirror } from "./code/LazyAnyLanguageCodeMirror";
type T = string;
@@ -41,10 +41,6 @@ export class CodeEditorPlugin implements IPlugin<T, Data> {
}
}
-const LazyAnyLanguageCodeMirror = lazy(
- () => import("./code/any-language-editor"),
-);
-
interface CodeEditorComponentProps extends Data {
value: T;
setValue: Setter<T>;
diff --git a/frontend/src/plugins/impl/code/LazyAnyLanguageCodeMirror.tsx b/frontend/src/plugins/impl/code/LazyAnyLanguageCodeMirror.tsx
new file mode 100644
index 0000000000..fe83458632
--- /dev/null
+++ b/frontend/src/plugins/impl/code/LazyAnyLanguageCodeMirror.tsx
@@ -0,0 +1,6 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { lazy } from "react";
+
+export const LazyAnyLanguageCodeMirror = lazy(
+ () => import("./any-language-editor"),
+);
diff --git a/frontend/src/utils/__tests__/path.test.ts b/frontend/src/utils/__tests__/path.test.ts
index dfcafb4492..3dd0b65287 100644
--- a/frontend/src/utils/__tests__/path.test.ts
+++ b/frontend/src/utils/__tests__/path.test.ts
@@ -1,6 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { describe, expect, it } from "vitest";
-import { Paths } from "../paths";
+import { FilePath, PathBuilder, Paths } from "../paths";
describe("Paths", () => {
describe("dirname", () => {
@@ -42,3 +42,82 @@ describe("Paths", () => {
});
});
});
+
+describe("PathBuilder", () => {
+ describe("constructor and guessDeliminator", () => {
+ it('should create instance with "/" delimiter', () => {
+ const pathBuilder = new PathBuilder("/");
+ expect(pathBuilder.join("path", "to", "file")).toBe("path/to/file");
+ });
+
+ it('should create instance with "\\" delimiter', () => {
+ const pathBuilder = new PathBuilder("\\");
+ expect(pathBuilder.join("path", "to", "file")).toBe("path\\to\\file");
+ });
+
+ it('guessDeliminator should choose "/" for paths with "/"', () => {
+ const pathBuilder = PathBuilder.guessDeliminator("path/to/file");
+ expect(pathBuilder.join("path", "to", "file")).toBe("path/to/file");
+ });
+
+ it('guessDeliminator should choose "\\" for paths with "\\"', () => {
+ const pathBuilder = PathBuilder.guessDeliminator("path\\to\\file");
+ expect(pathBuilder.join("path", "to", "file")).toBe("path\\to\\file");
+ });
+ });
+
+ describe("join", () => {
+ it('should join paths with "/"', () => {
+ const pathBuilder = new PathBuilder("/");
+ expect(pathBuilder.join("path", "to", "file")).toBe("path/to/file");
+ });
+
+ it('should join paths with "\\"', () => {
+ const pathBuilder = new PathBuilder("\\");
+ expect(pathBuilder.join("path", "to", "file")).toBe("path\\to\\file");
+ });
+
+ it("should ignore empty strings and null values", () => {
+ const pathBuilder = new PathBuilder("/");
+ expect(pathBuilder.join("", "path", null!, "to", "", "file")).toBe(
+ "path/to/file",
+ );
+ });
+ });
+
+ describe("basename", () => {
+ it('should get basename with "/"', () => {
+ const pathBuilder = new PathBuilder("/");
+ expect(pathBuilder.basename("path/to/file" as FilePath)).toBe("file");
+ });
+
+ it('should get basename with "\\"', () => {
+ const pathBuilder = new PathBuilder("\\");
+ expect(pathBuilder.basename("path\\to\\file" as FilePath)).toBe("file");
+ });
+
+ it("should return empty string if no basename", () => {
+ const pathBuilder = new PathBuilder("/");
+ expect(pathBuilder.basename("/" as FilePath)).toBe("");
+ });
+ });
+
+ describe("dirname", () => {
+ it('should get dirname with "/"', () => {
+ const pathBuilder = new PathBuilder("/");
+ expect(pathBuilder.dirname("path/to/file" as FilePath)).toBe("path/to");
+ });
+
+ it('should get dirname with "\\"', () => {
+ const pathBuilder = new PathBuilder("\\");
+ expect(pathBuilder.dirname("path\\to\\file" as FilePath)).toBe(
+ "path\\to",
+ );
+ });
+
+ it("should return empty string if no dirname (root directory)", () => {
+ const pathBuilder = new PathBuilder("/");
+ expect(pathBuilder.dirname("file" as FilePath)).toBe("");
+ });
+ });
+});
diff --git a/frontend/src/utils/functions.ts b/frontend/src/utils/functions.ts
index 68650b3cb5..aa9cb3d810 100644
--- a/frontend/src/utils/functions.ts
+++ b/frontend/src/utils/functions.ts
@@ -3,6 +3,9 @@ export const Functions = {
NOOP: () => {
return;
},
+ ASYNC_NOOP: async () => {
+ return;
+ },
THROW: () => {
throw new Error("Should not be called");
},
diff --git a/frontend/src/utils/paths.ts b/frontend/src/utils/paths.ts
index ee8c127b99..17cbcf72d7 100644
--- a/frontend/src/utils/paths.ts
+++ b/frontend/src/utils/paths.ts
@@ -1,13 +1,37 @@
/* Copyright 2024 Marimo. All rights reserved. */
+
+import { TypedString } from "./typed";
+
+export type FilePath = TypedString<"FilePath">;
+
export const Paths = {
dirname: (path: string) => {
- const delimiter = path.includes("/") ? "/" : "\\";
- const parts = path.split(delimiter);
- parts.pop();
- return parts.join(delimiter);
+ return PathBuilder.guessDeliminator(path).dirname(path as FilePath);
},
basename: (path: string) => {
- const parts = path.split(/[/\\]/);
- return parts.pop() ?? "";
+ return PathBuilder.guessDeliminator(path).basename(path as FilePath);
},
};
+
+export class PathBuilder {
+ constructor(private deliminator: "/" | "\\") {}
+
+ static guessDeliminator(path: string): PathBuilder {
+ return path.includes("/") ? new PathBuilder("/") : new PathBuilder("\\");
+ }
+
+ join(...paths: string[]): FilePath {
+ return paths.filter(Boolean).join(this.deliminator) as FilePath;
+ }
+
+ basename(path: FilePath): FilePath {
+ const parts = path.split(this.deliminator);
+ return (parts.pop() ?? "") as FilePath;
+ }
+
+ dirname(path: FilePath): FilePath {
+ const parts = path.split(this.deliminator);
+ parts.pop();
+ return parts.join(this.deliminator) as FilePath;
+ }
+}
diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.py
index 5cd2f06da9..52d4a910c6 100644
--- a/marimo/_pyodide/pyodide_session.py
+++ b/marimo/_pyodide/pyodide_session.py
@@ -38,7 +38,6 @@ from marimo._server.models.files import (
FileDeleteRequest,
FileDeleteResponse,
FileDetailsRequest,
- FileDetailsResponse,
FileListRequest,
FileListResponse,
FileUpdateRequest,
@@ -259,8 +258,7 @@ class PyodideBridge:
request: str,
) -> str:
body = parse_raw(json.loads(request), FileDetailsRequest)
- file_info = self.file_system.get_details(body.path)
- response = FileDetailsResponse(file=file_info)
+ response = self.file_system.get_details(body.path)
return json.dumps(deep_to_camel_case(dataclasses.asdict(response)))
def create_file_or_directory(
diff --git a/marimo/_server/api/endpoints/file_explorer.py b/marimo/_server/api/endpoints/file_explorer.py
index 2dc36c2840..323d6da352 100644
--- a/marimo/_server/api/endpoints/file_explorer.py
+++ b/marimo/_server/api/endpoints/file_explorer.py
@@ -50,8 +50,7 @@ async def file_details(
) -> FileDetailsResponse:
"""Get details of a specific file or directory."""
body = await parse_request(request, cls=FileDetailsRequest)
- file_info = file_system.get_details(body.path)
- return FileDetailsResponse(file=file_info)
+ return file_system.get_details(body.path)
@router.post("/create")
diff --git a/marimo/_server/files/file_system.py b/marimo/_server/files/file_system.py
index f2abd19443..833a8bcaf4 100644
--- a/marimo/_server/files/file_system.py
+++ b/marimo/_server/files/file_system.py
@@ -2,7 +2,7 @@
from abc import ABC, abstractmethod
from typing import List
-from marimo._server.models.files import FileInfo
+from marimo._server.models.files import FileDetailsResponse, FileInfo
class FileSystem(ABC):
@@ -17,7 +17,7 @@ class FileSystem(ABC):
pass
@abstractmethod
- def get_details(self, path: str) -> FileInfo:
+ def get_details(self, path: str) -> FileDetailsResponse:
"""Get details of a specific file or directory."""
pass
diff --git a/marimo/_server/files/os_file_system.py b/marimo/_server/files/os_file_system.py
index 1f3bf49223..971a9f1b2e 100644
--- a/marimo/_server/files/os_file_system.py
+++ b/marimo/_server/files/os_file_system.py
@@ -1,10 +1,11 @@
# Copyright 2024 Marimo. All rights reserved.
+import mimetypes
import os
import shutil
from typing import List
from marimo._server.files.file_system import FileSystem
-from marimo._server.models.files import FileInfo
+from marimo._server.models.files import FileDetailsResponse, FileInfo
IGNORE_LIST = [
"__pycache__",
@@ -48,10 +49,10 @@ class OSFileSystem(FileSystem):
return files
- def get_details(self, path: str) -> FileInfo:
+ def get_details(self, path: str) -> FileDetailsResponse:
stat = os.stat(path)
is_directory = os.path.isdir(path)
- return FileInfo(
+ file_info = FileInfo(
id=path,
path=path,
name=os.path.basename(path),
@@ -59,6 +60,11 @@ class OSFileSystem(FileSystem):
is_marimo_file=not is_directory and self._is_marimo_file(path),
last_modified_date=stat.st_mtime,
)
+ contents = self.open_file(path) if not is_directory else None
+ mime_type = mimetypes.guess_type(path)[0]
+ return FileDetailsResponse(
+ file=file_info, contents=contents, mime_type=mime_type
+ )
def _is_marimo_file(self, path: str) -> bool:
if not path.endswith(".py"):
diff --git a/marimo/_server/models/files.py b/marimo/_server/models/files.py
index d25e09fb19..2ba02e8b33 100644
--- a/marimo/_server/models/files.py
+++ b/marimo/_server/models/files.py
@@ -72,12 +72,8 @@ class FileListResponse:
@dataclass
class FileDetailsResponse:
file: FileInfo
-
-
-@dataclass
-class FileOpenResponse:
- # The content of the file
- content: str
+ contents: Optional[str] = None
+ mime_type: Optional[str] = None
@dataclass
diff --git a/tests/_server/files/test_os_file_system.py b/tests/_server/files/test_os_file_system.py
index d5d049df73..dd9f30a3fc 100644
--- a/tests/_server/files/test_os_file_system.py
+++ b/tests/_server/files/test_os_file_system.py
@@ -3,7 +3,7 @@ import unittest
from tempfile import TemporaryDirectory
from marimo._server.files.os_file_system import OSFileSystem
-from marimo._server.models.files import FileInfo
+from marimo._server.models.files import FileDetailsResponse
class TestOSFileSystem(unittest.TestCase):
@@ -44,8 +44,9 @@ class TestOSFileSystem(unittest.TestCase):
file_info = self.fs.get_details(
os.path.join(self.test_dir, test_file_name)
)
- assert isinstance(file_info, FileInfo)
- assert file_info.name == test_file_name
+ assert isinstance(file_info, FileDetailsResponse)
+ assert file_info.file.name == test_file_name
+ assert file_info.mime_type == "text/plain"
def test_get_details_marimo_file(self):
test_file_name = "app.py"
@@ -68,8 +69,8 @@ class TestOSFileSystem(unittest.TestCase):
)
f.close()
file_info = self.fs.get_details(file_path)
- assert isinstance(file_info, FileInfo)
- assert file_info.is_marimo_file
+ assert isinstance(file_info, FileDetailsResponse)
+ assert file_info.file.is_marimo_file
def test_open_file(self):
test_file_name = "test_file.txt"