A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: Create file browser component (#1106)
Wasim Sandhu37e5350c3d46
diff --git a/docs/api/inputs/file_browser.md b/docs/api/inputs/file_browser.mdnew file mode 100644index 0000000000..b42b6a32a9--- /dev/null+++ b/docs/api/inputs/file_browser.md@@ -0,0 +1,16 @@+# File Browser++```{eval-rst}+.. marimo-embed::+ @app.cell+ def __():+ mo.vstack([mo.ui.file_browser()])+ return+```++```{eval-rst}+.. autoclass:: marimo.ui.file_browser+ :members:++ .. autoclasstoc:: marimo._plugins.ui._impl.input.file_browser+```diff --git a/docs/api/inputs/index.md b/docs/api/inputs/index.mdindex 0bd41c0c0f..931171f09e 100644--- a/docs/api/inputs/index.md+++ b/docs/api/inputs/index.md@@ -16,6 +16,7 @@dictionarydropdownfile+ file_browserformmicrophonemultiselect@@ -49,6 +50,7 @@ powerful notebooks and apps. These elements are available in `marimo.ui`.marimo.ui.dictionarymarimo.ui.dropdownmarimo.ui.file+ marimo.ui.file_browsermarimo.ui.formmarimo.ui.microphonemarimo.ui.multiselectdiff --git a/frontend/src/plugins/impl/FileBrowserPlugin.tsx b/frontend/src/plugins/impl/FileBrowserPlugin.tsxnew file mode 100644index 0000000000..5991c908e7--- /dev/null+++ b/frontend/src/plugins/impl/FileBrowserPlugin.tsx@@ -0,0 +1,304 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { z } from "zod";+import { Table, TableCell, TableRow } from "@/components/ui/table";+import { createPlugin } from "../core/builder";+import { useState } from "react";+import { useAsyncData } from "@/hooks/useAsyncData";+import { rpc } from "../core/rpc";+import { toast } from "@/components/ui/use-toast";+import { NativeSelect } from "@/components/ui/native-select";+import {+ FILE_TYPE_ICONS,+ FileType,+ guessFileType,+} from "@/components/editor/file-tree/types";+import { renderHTML } from "../core/RenderHTML";+import { PathBuilder, Paths } from "@/utils/paths";+import { CornerLeftUp } from "lucide-react";++/**+ * Arguments for a file browser component.+ */+interface Data {+ /** @param initialPath - the path to display on component render */+ initialPath: string;+ /** @param filetypes - filter directory lists by file types */+ filetypes: string[];+ /** @param multiple - whether to allow the user to select multiple files */+ multiple: boolean;+ /** @param label - label for the file browser */+ label: string | null;+ /**+ * @param restrictNavigation - whether to prevent the user from accessing+ * directories outside the initial path+ */+ restrictNavigation: boolean;+}++/**+ * @param id - File id+ * @param path - File path+ * @param name - File name+ * @param is_directory - Whether file is a directory or not+ * @param is_marimo_file - Whether file is a marimo file or not+ */+interface FileInfo {+ id: string;+ path: string;+ name: string;+ is_directory: boolean;+ is_marimo_file: boolean;+}++// eslint-disable-next-line @typescript-eslint/consistent-type-definitions+type PluginFunctions = {+ list_directory: (req: { path: string }) => Promise<{+ files: FileInfo[];+ }>;+};++type S = FileInfo[];++export const FileBrowserPlugin = createPlugin<S>("marimo-file-browser")+ .withData(+ z.object({+ initialPath: z.string(),+ filetypes: z.array(z.string()),+ multiple: z.boolean(),+ label: z.string().nullable(),+ restrictNavigation: z.boolean(),+ }),+ )+ .withFunctions<PluginFunctions>({+ list_directory: rpc+ .input(+ z.object({+ path: z.string(),+ }),+ )+ .output(+ z.object({+ files: z.array(+ z.object({+ id: z.string(),+ path: z.string(),+ name: z.string(),+ is_directory: z.boolean(),+ is_marimo_file: z.boolean(),+ }),+ ),+ }),+ ),+ })+ .renderer((props) => (+ <FileBrowser+ {...props.data}+ {...props.functions}+ value={props.value}+ setValue={props.setValue}+ />+ ));++/**+ * @param value - array of selected (filename, path) tuples+ * @param setValue - sets selected files as component value+ */+interface FileBrowserProps extends Data, PluginFunctions {+ value: S;+ setValue: (value: S) => void;+}++export const FileBrowser = ({+ value,+ setValue,+ initialPath,+ multiple,+ label,+ restrictNavigation,+ list_directory,+}: FileBrowserProps): JSX.Element | null => {+ const [path, setPath] = useState(initialPath);++ const { data, loading, error } = useAsyncData(+ () =>+ list_directory({+ path: path,+ }),+ [path],+ );++ if (error) {+ console.error(error);+ toast({+ title: `Could not load files in directory ${path}`,+ description: error.message,+ variant: "danger",+ });+ }++ if (loading && !data) {+ return null;+ }++ let { files } = data || {};+ if (files === undefined) {+ files = [];+ }++ // For checkbox logic+ const selectedPaths = new Set(value.map((x) => x.path));++ // For displaying selected files+ const selectedFiles = value.map((x) => <li key={x.id}>{x.path}</li>);++ /**+ * Set new path from user input or selection.+ * @param {string} newPath - New path+ */+ function setNewPath(newPath: string) {+ // Navigate to parent directory+ if (newPath === "..") {+ newPath = Paths.dirname(path);+ }++ // If restricting navigation, check if path is outside bounds+ const outsideInitialPath = newPath.length < initialPath.length;+ if (restrictNavigation && outsideInitialPath) {+ toast({+ title: "Access denied",+ description:+ "Access to directories outside initial path is restricted.",+ variant: "danger",+ });+ return;+ }++ setPath(newPath);+ }++ /**+ * Handles file selection.+ * @param {string} path - Path of selected file+ * @param {string} name - Name of selected file+ */+ const selectFile = (path: string, name: string) => {+ const fileInfo: FileInfo = {+ id: path,+ name: name,+ path: path,+ is_directory: false,+ is_marimo_file: false,+ };++ if (multiple) {+ if (selectedPaths.has(path)) {+ setValue(value.filter((x) => x.path !== path));+ } else {+ setValue([...value, fileInfo]);+ }+ } else {+ setValue([fileInfo]);+ }+ };++ // Create rows for directories and files+ const fileRows = [];++ // Parent directory ".." row button+ fileRows.push(+ <TableRow+ className="hover:bg-primary hover:bg-opacity-25"+ key={"Parent directory"}+ onClick={() => setNewPath("..")}+ >+ <TableCell className="w-1/12">+ <CornerLeftUp className="ml-2" size={16} />+ </TableCell>+ <TableCell className="w-11/12">..</TableCell>+ </TableRow>,+ );++ const delimiter = path.includes("/") ? "/" : "\\";+ const pathBuilder = new PathBuilder(delimiter);++ for (const file of files) {+ const filePath = pathBuilder.join(path, file.name);++ // Click handler+ const handleClick = file.is_directory ? setNewPath : selectFile;++ // Table row styles+ const isSelected = selectedPaths.has(filePath);++ const tableRowStyles = isSelected+ ? "bg-primary bg-opacity-25 hover:bg-primary hover:bg-opacity-50"+ : "hover:bg-primary hover:bg-opacity-25";++ // Icon+ const fileType: FileType = file.is_directory+ ? "directory"+ : guessFileType(file.name);++ const Icon = FILE_TYPE_ICONS[fileType];++ fileRows.push(+ <TableRow+ key={file.id}+ className={tableRowStyles}+ onClick={() => handleClick(filePath, file.name)}+ >+ <TableCell className="w-1/12">+ <Icon size={16} className="ml-2" />+ </TableCell>+ <TableCell className="w-11/12">{file.name}</TableCell>+ </TableRow>,+ );+ }++ // Get list of parent directories+ const directories = path.split(delimiter).filter((x) => x !== "");+ directories.push(path);++ const parentDirectories = directories.map((dir, index) => {+ const dirList = directories.slice(0, index);+ return `/${dirList.join(delimiter)}`;+ });++ parentDirectories.reverse();++ label = label ?? "Browse and select file(s)...";++ return (+ <section>+ <span className="markdown">+ <strong>{renderHTML({ html: label })}</strong>+ </span>+ <NativeSelect+ className="mt-3 w-full"+ placeholder={path}+ value={path}+ onChange={(e) => setNewPath(e.target.value)}+ >+ {parentDirectories.map((dir) => (+ <option value={dir} key={dir} selected={dir === path}>+ {dir}+ </option>+ ))}+ </NativeSelect>+ <div+ className="mt-3 overflow-y-auto w-full border"+ style={{ height: "14rem" }}+ >+ <Table className="cursor-pointer table-fixed">{fileRows}</Table>+ </div>+ <aside className="mt-4">+ {value.length > 0 ? (+ <span className="markdown">+ <strong>{value.length} file(s) selected</strong>+ <ul style={{ margin: 0 }}>{selectedFiles}</ul>+ </span>+ ) : null}+ </aside>+ </section>+ );+};diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.tsindex 8981b62eee..db1b6cc89d 100644--- a/frontend/src/plugins/plugins.ts+++ b/frontend/src/plugins/plugins.ts@@ -8,6 +8,7 @@ import { DatePickerPlugin } from "./impl/DatePickerPlugin";import { DictPlugin } from "./impl/DictPlugin";import { DropdownPlugin } from "./impl/DropdownPlugin";import { FileUploadPlugin } from "./impl/FileUploadPlugin";+import { FileBrowserPlugin } from "./impl/FileBrowserPlugin";import { FormPlugin } from "./impl/FormPlugin";import { MultiselectPlugin } from "./impl/MultiselectPlugin";import { NumberPlugin } from "./impl/NumberPlugin";@@ -49,6 +50,7 @@ export const UI_PLUGINS: Array<IPlugin<any, unknown>> = [new CodeEditorPlugin(),new DropdownPlugin(),new FileUploadPlugin(),+ FileBrowserPlugin,FormPlugin,new MicrophonePlugin(),new MultiselectPlugin(),diff --git a/marimo/_plugins/ui/__init__.py b/marimo/_plugins/ui/__init__.pyindex 62f69a5420..cabcd70eb1 100644--- a/marimo/_plugins/ui/__init__.py+++ b/marimo/_plugins/ui/__init__.py@@ -17,6 +17,7 @@ __all__ = ["dictionary","dropdown","file",+ "file_browser","form","anywidget","microphone",@@ -47,6 +48,7 @@ from marimo._plugins.ui._impl.input import (date,dropdown,file,+ file_browser,form,multiselect,number,diff --git a/marimo/_plugins/ui/_impl/input.py b/marimo/_plugins/ui/_impl/input.pyindex e3ec188e03..52a27e08fc 100644--- a/marimo/_plugins/ui/_impl/input.py+++ b/marimo/_plugins/ui/_impl/input.py@@ -4,11 +4,13 @@ from __future__ import annotationsimport base64import dataclassesimport datetime as dt+import osimport tracebackfrom dataclasses import dataclassfrom typing import (Any,Callable,+ Dict,Final,List,Literal,@@ -25,6 +27,8 @@ from marimo._output.rich_help import mddocfrom marimo._plugins.core.web_component import JSONTypefrom marimo._plugins.ui._core.ui_element import S as JSONTypeBound, UIElementfrom marimo._runtime.functions import Function+from marimo._server.files.os_file_system import OSFileSystem+from marimo._server.models.files import FileInfoLOGGER = _loggers.marimo_logger()@@ -898,6 +902,132 @@ class file(UIElement[List[Tuple[str, str]], Sequence[FileUploadResults]]):return self.value[index].contents+@dataclass+class ListDirectoryArgs:+ path: str+++@dataclass+class ListDirectoryResponse:+ files: List[FileInfo]+++@mddoc+class file_browser(UIElement[List[Dict[str, Any]], Sequence[FileInfo]]):+ """+ File browser for browsing and selecting server-side files.++ **Examples.**++ Selecting multiple files:++ ```python+ file_browser = mo.ui.file_browser(path="path/to/dir", multiple=True)++ # Access the selected file path(s):+ file_browser.value[index]++ # Or:+ file_browser.path(index)+ ```++ **Attributes.**++ - `value`: a sequence of file paths representing selected files.++ **Initialization Args.**++ - `initial_path`: the directory to start from.+ - `filetypes`: the file types to display in each directory; for example,+ `filetypes=[".txt", ".csv"]`. If `None`, all files are displayed.+ - `multiple`: if True, allow the user to select multiple files.+ - `restrict_navigation`: if True, prevent the user from navigating+ any level above the given path.+ - `label`: text label for the element+ - `on_change`: optional callback to run when this element's value changes+ """++ _name: Final[str] = "marimo-file-browser"++ def __init__(+ self,+ initial_path: str = "",+ filetypes: Optional[Sequence[str]] = None,+ multiple: bool = True,+ restrict_navigation: bool = False,+ *,+ label: str = "",+ on_change: Optional[Callable[[Sequence[FileInfo]], None]] = None,+ ) -> None:+ self.filetypes = filetypes++ if not initial_path:+ initial_path = os.getcwd()++ super().__init__(+ component_name=file_browser._name,+ initial_value=[],+ label=label,+ args={+ "initial-path": initial_path,+ "filetypes": filetypes if filetypes is not None else [],+ "multiple": multiple,+ "restrict-navigation": restrict_navigation,+ },+ functions=(+ Function(+ name=self.list_directory.__name__,+ arg_cls=ListDirectoryArgs,+ function=self.list_directory,+ ),+ ),+ on_change=on_change,+ )++ def list_directory(self, args: ListDirectoryArgs) -> ListDirectoryResponse:+ files = []+ files_in_path = OSFileSystem().list_files(args.path)++ for file in files_in_path:+ _, extension = os.path.splitext(file.name)++ if self.filetypes and not file.is_directory:+ if extension not in self.filetypes:+ continue++ files.append(file)++ return ListDirectoryResponse(files)++ def _convert_value(+ self, value: list[Dict[str, Any]]+ ) -> Sequence[FileInfo]:+ return tuple(+ FileInfo(+ id=file["id"],+ name=file["name"],+ path=file["path"],+ is_directory=file["is_directory"],+ is_marimo_file=file["is_marimo_file"],+ )+ for file in value+ )++ def name(self, index: int = 0) -> Optional[str]:+ """Get file name at index."""+ if not self.value or index >= len(self.value):+ return None+ else:+ return self.value[index].name++ def path(self, index: int = 0) -> Optional[str]:+ """Get file path at index."""+ if not self.value or index >= len(self.value):+ return None+ else:+ return self.value[index].path++@mddocclass date(UIElement[str, dt.date]):"""