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.

fix: open marimo notebook from the sidebar (#1246)

Myles Scolnick4092c5d888c9
diff --git a/frontend/src/components/app-config/app-config-button.tsx b/frontend/src/components/app-config/app-config-button.tsx
index be66e6738c..3594980b7e 100644
--- a/frontend/src/components/app-config/app-config-button.tsx
+++ b/frontend/src/components/app-config/app-config-button.tsx
@@ -10,7 +10,11 @@ import { UserConfigForm } from "./user-config-form";
import { Tooltip } from "../ui/tooltip";
import { AppConfigForm } from "@/components/app-config/app-config-form";
-export const AppConfigButton = () => {
+interface Props {
+ showAppConfig?: boolean;
+}
+
+export const ConfigButton: React.FC<Props> = ({ showAppConfig = true }) => {
return (
<Popover>
<PopoverTrigger asChild={true}>
@@ -35,8 +39,12 @@ export const AppConfigButton = () => {
// interacting with buttons closes the popover ...
onFocusOutside={(evt) => evt.preventDefault()}
>
- <AppConfigForm />
- <div className="h-px bg-border my-4" />
+ {showAppConfig && (
+ <>
+ <AppConfigForm />
+ <div className="h-px bg-border my-4" />
+ </>
+ )}
<UserConfigForm />
</PopoverContent>
</Popover>
diff --git a/frontend/src/components/editor/controls/Controls.tsx b/frontend/src/components/editor/controls/Controls.tsx
index f4d060a0b3..1b524d8a9d 100644
--- a/frontend/src/components/editor/controls/Controls.tsx
+++ b/frontend/src/components/editor/controls/Controls.tsx
@@ -17,7 +17,7 @@ import { RecoveryButton } from "@/components/editor/RecoveryButton";
import { Tooltip } from "../../ui/tooltip";
import { renderShortcut } from "../../shortcuts/renderShortcut";
import { useCellActions } from "../../../core/cells/cells";
-import { AppConfigButton } from "../../app-config/app-config-button";
+import { ConfigButton } from "../../app-config/app-config-button";
import { LayoutSelect } from "../renderers/layout-select";
import { NotebookMenuDropdown } from "@/components/editor/controls/notebook-menu-dropdown";
import { FindReplace } from "@/components/find-replace/find-replace";
@@ -89,7 +89,7 @@ export const Controls = ({
<div className={topRightControls}>
{presenting && <LayoutSelect />}
<NotebookMenuDropdown />
- <AppConfigButton />
+ <ConfigButton />
<ShutdownButton description="This will terminate the Python kernel. You'll lose all data that's in memory." />
</div>
)}
diff --git a/frontend/src/components/editor/file-tree/file-explorer.tsx b/frontend/src/components/editor/file-tree/file-explorer.tsx
index f3cf5182b7..e5b1cd7138 100644
--- a/frontend/src/components/editor/file-tree/file-explorer.tsx
+++ b/frontend/src/components/editor/file-tree/file-explorer.tsx
@@ -1,7 +1,7 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { NodeApi, NodeRendererProps, Tree } from "react-arborist";
-import React, { useEffect, useRef, useState } from "react";
+import React, { useContext, useEffect, useRef, useState } from "react";
import {
ArrowLeftIcon,
ChevronDownIcon,
@@ -15,7 +15,6 @@ import {
UploadIcon,
ViewIcon,
} from "lucide-react";
-import { openFile } from "@/core/network/requests";
import { FileInfo } from "@/core/network/types";
import {
FILE_TYPE_ICONS,
@@ -25,10 +24,7 @@ import {
} from "./types";
import { toast } from "@/components/ui/use-toast";
import { useImperativeModal } from "@/components/modal/ImperativeModal";
-import {
- AlertDialogAction,
- AlertDialogDestructiveAction,
-} from "@/components/ui/alert-dialog";
+import { AlertDialogDestructiveAction } from "@/components/ui/alert-dialog";
import { useAtom } from "jotai";
import { Button, buttonVariants } from "@/components/ui/button";
@@ -48,6 +44,9 @@ import { isPyodide } from "@/core/pyodide/utils";
import { useAsyncData } from "@/hooks/useAsyncData";
import { ErrorBanner } from "@/plugins/impl/common/error-banner";
import { Spinner } from "@/components/icons/spinner";
+import { RequestingTree } from "./requesting-tree";
+
+const RequestingTreeContext = React.createContext<RequestingTree | null>(null);
export const FileExplorer: React.FC<{
height: number;
@@ -94,53 +93,55 @@ export const FileExplorer: React.FC<{
tree.refreshAll(Object.keys(openState).filter((id) => openState[id]))
}
/>
- <Tree<FileInfo>
- width="100%"
- height={height - 26}
- className="h-full"
- data={data}
- initialOpenState={openState}
- openByDefault={false}
- // Hide the drop cursor
- renderCursor={() => null}
- // Disable dropping files into files
- disableDrop={({ parentNode }) => !parentNode.data.isDirectory}
- onDelete={async ({ ids }) => {
- for (const id of ids) {
- await tree.delete(id);
- }
- }}
- 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;
- }
- if (!first.data.isDirectory) {
- setOpenFile(first.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 multi-selection
- disableMultiSelection={true}
- >
- {Node}
- </Tree>
+ <RequestingTreeContext.Provider value={tree}>
+ <Tree<FileInfo>
+ width="100%"
+ height={height - 33}
+ className="h-full"
+ data={data}
+ initialOpenState={openState}
+ openByDefault={false}
+ // Hide the drop cursor
+ renderCursor={() => null}
+ // Disable dropping files into files
+ disableDrop={({ parentNode }) => !parentNode.data.isDirectory}
+ onDelete={async ({ ids }) => {
+ for (const id of ids) {
+ await tree.delete(id);
+ }
+ }}
+ 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;
+ }
+ if (!first.data.isDirectory) {
+ setOpenFile(first.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 multi-selection
+ disableMultiSelection={true}
+ >
+ {Node}
+ </Tree>
+ </RequestingTreeContext.Provider>
</>
);
};
@@ -235,25 +236,13 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
const Icon = FILE_TYPE_ICONS[fileType];
const { openConfirm } = useImperativeModal();
+ const tree = useContext(RequestingTreeContext);
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>
- ),
- });
+ const path = tree ? tree.relativeFromRoot(node.data.path) : node.data.path;
+ window.open(`/?file=${path}`, "_blank");
};
const handleDeleteFile = async (evt: Event) => {
@@ -327,8 +316,7 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
onClick={(e) => e.stopPropagation()}
onCloseAutoFocus={(e) => e.preventDefault()}
>
- {/* Not shown in Pyodide */}
- {!node.data.isDirectory && !isPyodide() && (
+ {!node.data.isDirectory && (
<DropdownMenuItem onSelect={() => node.select()}>
<ViewIcon className="mr-2" size={14} strokeWidth={1.5} />
Open file
@@ -353,7 +341,8 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
<CopyIcon className="mr-2" size={14} strokeWidth={1.5} />
Copy snippet to clipboard
</DropdownMenuItem>
- {node.data.isMarimoFile && (
+ {/* Not shown in Pyodide */}
+ {node.data.isMarimoFile && !isPyodide() && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem onSelect={handleOpenMarimoFile}>
diff --git a/frontend/src/components/editor/file-tree/requesting-tree.tsx b/frontend/src/components/editor/file-tree/requesting-tree.tsx
index b41354ad1f..49482a925f 100644
--- a/frontend/src/components/editor/file-tree/requesting-tree.tsx
+++ b/frontend/src/components/editor/file-tree/requesting-tree.tsx
@@ -159,6 +159,14 @@ export class RequestingTree {
this.onChange(this.delegate.data);
};
+ public relativeFromRoot = (path: FilePath): FilePath => {
+ const root = withTrailingSlash(this.rootPath);
+ if (path.startsWith(root)) {
+ return path.slice(root.length) as FilePath;
+ }
+ return path;
+ };
+
private handleResponse = (response: FileOperationResponse): void => {
if (!response.success) {
toast({
@@ -169,3 +177,7 @@ export class RequestingTree {
}
};
}
+
+function withTrailingSlash(path: string): string {
+ return path.endsWith("/") ? path : `${path}/`;
+}
diff --git a/frontend/src/components/home/home-page.tsx b/frontend/src/components/home/home-page.tsx
index e8412dd298..dff853b032 100644
--- a/frontend/src/components/home/home-page.tsx
+++ b/frontend/src/components/home/home-page.tsx
@@ -25,6 +25,7 @@ import { Button } from "@/components/ui/button";
import { Tooltip } from "@/components/ui/tooltip";
import { toast } from "@/components/ui/use-toast";
import { RunningNotebooksResponse } from "@/core/network/types";
+import { ConfigButton } from "../app-config/app-config-button";
function tabTarget(path: string) {
// Consistent tab target so we open in the same tab when clicking on the same notebook
@@ -84,7 +85,8 @@ export const HomePage: React.FC = () => {
return (
<Suspense>
{/*<GridBackground />*/}
- <div className="absolute top-3 right-5">
+ <div className="absolute top-3 right-5 flex gap-2 z-10">
+ <ConfigButton showAppConfig={false} />
<ShutdownButton
description={`This will shutdown the notebook server and terminate all running notebooks (${running.files.length}). You'll lose all data that's in memory.`}
/>
diff --git a/frontend/src/components/ui/input.tsx b/frontend/src/components/ui/input.tsx
index d20917455c..3213c917ec 100644
--- a/frontend/src/components/ui/input.tsx
+++ b/frontend/src/components/ui/input.tsx
@@ -5,6 +5,7 @@ import { cn } from "@/utils/cn";
import { useDebounceControlledState } from "@/hooks/useDebounce";
import { Events } from "@/utils/events";
import { NumberField, NumberFieldProps } from "@/components/ui/number-field";
+import { SearchIcon } from "lucide-react";
export type InputProps = React.InputHTMLAttributes<HTMLInputElement> & {
icon?: React.ReactNode;
@@ -102,4 +103,29 @@ export const DebouncedNumberInput = React.forwardRef<
});
DebouncedNumberInput.displayName = "DebouncedNumberInput";
+export const SearchInput = React.forwardRef<
+ HTMLInputElement,
+ InputProps & {
+ rootClassName?: string;
+ icon?: React.ReactNode | null;
+ }
+>(({ className, rootClassName, icon, ...props }, ref) => {
+ return (
+ <div className={cn("flex items-center border-b px-3", rootClassName)}>
+ {icon === null ? null : (
+ <SearchIcon className="mr-2 h-4 w-4 shrink-0 opacity-50" />
+ )}
+ <input
+ ref={ref}
+ className={cn(
+ "placeholder:text-foreground-muted flex h-7 m-1 w-full rounded-md bg-transparent py-3 text-sm outline-none disabled:cursor-not-allowed disabled:opacity-50",
+ className,
+ )}
+ {...props}
+ />
+ </div>
+ );
+});
+SearchInput.displayName = "SearchInput";
+
export { Input };
diff --git a/marimo/_server/api/endpoints/config.py b/marimo/_server/api/endpoints/config.py
index 4bb6652872..407db037f0 100644
--- a/marimo/_server/api/endpoints/config.py
+++ b/marimo/_server/api/endpoints/config.py
@@ -45,7 +45,8 @@ async def save_user_config(
await app_state.session_manager.start_lsp_server()
# Update the kernel's view of the config
- app_state.require_current_session().put_control_request(
- SetUserConfigRequest(body.config)
- )
+ # Session could be None if the user is on the home page
+ session = app_state.get_current_session()
+ if session is not None:
+ session.put_control_request(SetUserConfigRequest(body.config))
return SuccessResponse()
diff --git a/marimo/_server/files/os_file_system.py b/marimo/_server/files/os_file_system.py
index 3bc5bf0652..3a92a49bad 100644
--- a/marimo/_server/files/os_file_system.py
+++ b/marimo/_server/files/os_file_system.py
@@ -4,8 +4,9 @@ from __future__ import annotations
import base64
import mimetypes
import os
+import re
import shutil
-from typing import List, Optional
+from typing import List, Optional, Union
from marimo._server.files.file_system import FileSystem
from marimo._server.models.files import FileDetailsResponse, FileInfo
@@ -30,6 +31,7 @@ class OSFileSystem(FileSystem):
def list_files(self, path: str) -> List[FileInfo]:
files: List[FileInfo] = []
+ folders: List[FileInfo] = []
with os.scandir(path) as it:
for entry in it:
if entry.name in IGNORE_LIST:
@@ -51,12 +53,14 @@ class OSFileSystem(FileSystem):
and self._is_marimo_file(entry.path),
last_modified_date=entry_stat.st_mtime,
)
- files.append(info)
+ if is_directory:
+ folders.append(info)
+ else:
+ files.append(info)
- # Sort by directory first, then by name
- files.sort(key=lambda f: (not f.is_directory, f.name))
-
- return files
+ return sorted(folders, key=natural_sort_file) + sorted(
+ files, key=natural_sort_file
+ )
def _get_file_info(self, path: str) -> FileInfo:
stat = os.stat(path)
@@ -157,3 +161,17 @@ class OSFileSystem(FileSystem):
with open(path, "w") as file:
file.write(contents)
return self.get_details(path).file
+
+
+def natural_sort_file(file: FileInfo) -> List[Union[int, str]]:
+ return natural_sort(file.name)
+
+
+def natural_sort(filename: str) -> List[Union[int, str]]:
+ def convert(text: str) -> Union[int, str]:
+ return int(text) if text.isdigit() else text.lower()
+
+ def alphanum_key(key: str) -> List[Union[int, str]]:
+ return [convert(c) for c in re.split("([0-9]+)", key)]
+
+ return alphanum_key(filename)
diff --git a/marimo/_smoke_tests/bugs/1241.py b/marimo/_smoke_tests/bugs/1241.py
index f1124e48ce..30e824cf8d 100644
--- a/marimo/_smoke_tests/bugs/1241.py
+++ b/marimo/_smoke_tests/bugs/1241.py
@@ -1,3 +1,4 @@
+# Copyright 2024 Marimo. All rights reserved.
import marimo
__generated_with = "0.4.5"
diff --git a/tests/_server/api/endpoints/test_config_endpoints.py b/tests/_server/api/endpoints/test_config_endpoints.py
new file mode 100644
index 0000000000..366727efbc
--- /dev/null
+++ b/tests/_server/api/endpoints/test_config_endpoints.py
@@ -0,0 +1,45 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from tests._server.conftest import get_user_config_manager
+from tests._server.mocks import with_session
+
+if TYPE_CHECKING:
+ from starlette.testclient import TestClient
+
+SESSION_ID = "session-123"
+HEADERS = {
+ "Marimo-Session-Id": SESSION_ID,
+ "Marimo-Server-Token": "fake-token",
+}
+
+
+def test_save_user_config_no_session(client: TestClient) -> None:
+ user_config_manager = get_user_config_manager(client)
+ response = client.post(
+ "/api/kernel/save_user_config",
+ headers=HEADERS,
+ json={
+ "config": user_config_manager.get_config(),
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert response.headers["content-type"] == "application/json"
+ assert "success" in response.json()
+
+
+@with_session(SESSION_ID)
+def test_save_user_config_with_session(client: TestClient) -> None:
+ user_config_manager = get_user_config_manager(client)
+ response = client.post(
+ "/api/kernel/save_user_config",
+ headers=HEADERS,
+ json={
+ "config": user_config_manager.get_config(),
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert response.headers["content-type"] == "application/json"
+ assert "success" in response.json()
diff --git a/tests/_server/files/test_os_file_system.py b/tests/_server/files/test_os_file_system.py
index 563ebae78f..9e1502f6df 100644
--- a/tests/_server/files/test_os_file_system.py
+++ b/tests/_server/files/test_os_file_system.py
@@ -1,10 +1,12 @@
+from __future__ import annotations
+
import os
import unittest
from tempfile import TemporaryDirectory
import pytest
-from marimo._server.files.os_file_system import OSFileSystem
+from marimo._server.files.os_file_system import OSFileSystem, natural_sort
from marimo._server.models.files import FileDetailsResponse
@@ -156,3 +158,28 @@ class TestOSFileSystem(unittest.TestCase):
self.fs.update_file(file_path, new_content)
with open(file_path, "r") as f:
assert f.read() == new_content
+
+
+def test_natural_sort_key() -> None:
+ filenames = [
+ "file1.txt",
+ "file10.txt",
+ "file2.txt",
+ "file20.txt",
+ "1.txt",
+ "10.txt",
+ "2.txt",
+ "20.txt",
+ ]
+ sorted_files = sorted(filenames, key=natural_sort)
+ expected_order = [
+ "1.txt",
+ "2.txt",
+ "10.txt",
+ "20.txt",
+ "file1.txt",
+ "file2.txt",
+ "file10.txt",
+ "file20.txt",
+ ]
+ assert sorted_files == expected_order
diff --git a/tests/_server/mocks.py b/tests/_server/mocks.py
index 2fdb79c176..a24bb4b934 100644
--- a/tests/_server/mocks.py
+++ b/tests/_server/mocks.py
@@ -3,12 +3,11 @@ from __future__ import annotations
import tempfile
from typing import TYPE_CHECKING, Any, Callable, cast
-from unittest.mock import MagicMock
from marimo._config.manager import UserConfigManager
from marimo._server.file_router import AppFileRouter
from marimo._server.model import SessionMode
-from marimo._server.sessions import LspServer, SessionManager
+from marimo._server.sessions import NoopLspServer, SessionManager
if TYPE_CHECKING:
from fastapi.testclient import TestClient
@@ -42,8 +41,7 @@ if __name__ == "__main__":
temp_file.close()
- lsp_server = MagicMock(spec=LspServer)
- lsp_server.is_running.return_value = False
+ lsp_server = NoopLspServer()
sm = SessionManager(
file_router=AppFileRouter.from_filename(temp_file.name),