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: modernize filename dropdown (#1153)

Myles Scolnickca3fcc2407c4
diff --git a/frontend/src/components/editor/DirCompletionInput.tsx b/frontend/src/components/editor/DirCompletionInput.tsx
deleted file mode 100644
index 36538aecaf..0000000000
--- a/frontend/src/components/editor/DirCompletionInput.tsx
+++ /dev/null
@@ -1,246 +0,0 @@
-/* Copyright 2024 Marimo. All rights reserved. */
-import {
- createRef,
- useEffect,
- useImperativeHandle,
- useRef,
- useState,
-} from "react";
-
-import { Input } from "./inputs/Inputs";
-import { Logger } from "../../utils/Logger";
-import { Functions } from "../../utils/functions";
-import { cn } from "../../utils/cn";
-import { sendListFiles } from "@/core/network/requests";
-import { Paths } from "@/utils/paths";
-import { useAsyncData } from "@/hooks/useAsyncData";
-
-export interface DirCompletionInputHandle {
- suggestions: string[];
-}
-
-interface DirCompletionInputProps
- extends React.InputHTMLAttributes<HTMLInputElement> {
- flexibleWidth?: boolean;
- resetOnBlur?: boolean;
- placeholderText?: string;
- initialValue?: string | null;
- onFocusCallback?: () => void;
- onBlurCallback?: () => void;
- onChangeCallback?: (value: string) => void;
- handle?: React.RefObject<DirCompletionInputHandle>;
-}
-
-export const DirCompletionInput = ({
- flexibleWidth = false,
- resetOnBlur = false,
- placeholderText = "",
- initialValue = null,
- onFocusCallback = Functions.NOOP,
- onBlurCallback = Functions.NOOP,
- onChangeCallback = Functions.NOOP,
- handle = createRef(),
- ...rest
-}: DirCompletionInputProps): JSX.Element => {
- const [value, setValue] = useState(initialValue);
- const [suggestions, setSuggestions] = useState<string[]>([]);
- const [activeSuggestion, setActiveSuggestion] = useState<number | null>(null);
- const [focused, setFocused] = useState<boolean>(false);
-
- useImperativeHandle(handle, () => ({
- get suggestions() {
- return suggestions;
- },
- }));
- const ref = useRef<HTMLInputElement>(null);
- const activeSuggestionRef = useRef<HTMLLIElement | null>(null);
-
- useEffect(() => {
- setValue(initialValue);
- }, [initialValue]);
-
- function onFocus(e: React.FocusEvent<HTMLInputElement>) {
- setFocused(true);
- onFocusCallback();
- }
-
- async function onBlur(e: React.FocusEvent<HTMLInputElement>) {
- // focus should be removed before value is reset, to avoid a race
- // condition in which suggestions are fetched when not needed
- setFocused(false);
- if (resetOnBlur) {
- e.preventDefault();
- setValue(initialValue);
- }
- onBlurCallback();
- }
-
- async function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
- setValue(e.target.value);
- onChangeCallback(e.target.value);
- }
-
- const dirname = Paths.dirname(value || "");
- const basename = Paths.basename(value || "");
- const filteredSuggestions = suggestions.filter((suggestion) =>
- suggestion.startsWith(basename),
- );
-
- useAsyncData(async () => {
- if (!focused) {
- setActiveSuggestion(null);
- setSuggestions([]);
- return;
- }
-
- const data = await sendListFiles({ path: dirname });
- // Only set suggestions if this token has not been invalidated
- setActiveSuggestion(null);
- const relativePaths = data.files.map((path) =>
- path.path.slice(data.root.length + 1),
- );
- setSuggestions(relativePaths);
- }, [dirname, focused]);
-
- function chooseSuggestion(index: number) {
- const prefix = value === null ? "" : value;
- const completion = suggestions[index].slice(basename.length);
- setValue(`${prefix + completion}/`);
- if (ref.current != null) {
- ref.current.focus();
- }
- }
-
- function handleSuggestionMouseDown(
- index: number,
- e: React.MouseEvent<HTMLLIElement>,
- ) {
- e.preventDefault();
- if (e.button === 0 && !suggestions[index].endsWith(".py")) {
- chooseSuggestion(index);
- }
- }
-
- function onKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
- switch (e.key) {
- case "Down":
- case "ArrowDown":
- setActiveSuggestion((i) =>
- i == null ? 0 : (i + 1) % suggestions.length,
- );
- e.preventDefault();
- break;
- case "Up":
- case "ArrowUp":
- setActiveSuggestion((i) =>
- i === null || i === 0 ? suggestions.length - 1 : i - 1,
- );
- e.preventDefault();
- break;
- case "Enter":
- case "ArrowRight":
- if (activeSuggestion === null) {
- break;
- }
- e.preventDefault();
- e.stopPropagation();
- if (!suggestions[activeSuggestion].endsWith(".py")) {
- chooseSuggestion(activeSuggestion);
- }
- break;
- case "Esc":
- case "Escape":
- if (ref.current !== null) {
- ref.current.blur();
- }
- e.preventDefault();
- break;
- default:
- break;
- }
- }
-
- useEffect(() => {
- if (activeSuggestion !== null && activeSuggestionRef.current != null) {
- const elem = activeSuggestionRef.current;
- const parent = elem.parentElement;
- if (parent === null) {
- Logger.error("Expected elem to have parent; elem:", elem);
- } else {
- const scrollOffset = parent.scrollTop;
- const visibleRange = [scrollOffset, scrollOffset + parent.offsetHeight];
- if (elem.offsetTop < visibleRange[0]) {
- activeSuggestionRef.current.scrollIntoView(/* alignToTop = */ true);
- } else if (elem.offsetTop + elem.offsetHeight > visibleRange[1]) {
- activeSuggestionRef.current.scrollIntoView(/* alignToTop = */ false);
- }
- }
- }
- }, [activeSuggestion]);
-
- const suggestionsList =
- filteredSuggestions.length === 0 || ref.current == null ? null : (
- <ul
- className="autocomplete-list"
- style={{
- maxWidth: ref.current.offsetWidth,
- width: ref.current.offsetWidth,
- }}
- >
- {filteredSuggestions.map((suggestion, index) => {
- const isFile = suggestion.endsWith(".py");
- const icon = isFile ? "📄" : "📁 ";
- const isActive = activeSuggestion === index;
- return (
- <li
- key={suggestion}
- className={cn({
- file: isFile,
- directory: !isFile,
- "active-suggestion": isActive,
- })}
- onMouseDown={(e) => handleSuggestionMouseDown(index, e)}
- ref={isActive ? activeSuggestionRef : null}
- >
- {icon} {suggestion}
- </li>
- );
- })}
- </ul>
- );
-
- let size: number | undefined;
- if (flexibleWidth) {
- size = Math.min(
- 60,
- Math.max(placeholderText.length, value === null ? 0 : value.length),
- );
- }
-
- const displayValue =
- !focused && placeholderText !== ""
- ? placeholderText
- : value === null
- ? ""
- : value;
- return (
- <div className="DirCompletionInput">
- <Input
- data-testid="dir-completion-input"
- type="text"
- spellCheck="false"
- value={displayValue}
- style={{ width: "unset" }}
- autoComplete="off"
- ref={ref}
- size={size}
- onFocus={onFocus}
- onChange={handleChange}
- onBlur={onBlur}
- onKeyDown={onKeyDown}
- {...rest}
- />
- {suggestionsList}
- </div>
- );
-};
diff --git a/frontend/src/components/editor/FilenameForm.tsx b/frontend/src/components/editor/FilenameForm.tsx
deleted file mode 100644
index 3573e5e6ae..0000000000
--- a/frontend/src/components/editor/FilenameForm.tsx
+++ /dev/null
@@ -1,159 +0,0 @@
-/* Copyright 2024 Marimo. All rights reserved. */
-import { useRef, useState } from "react";
-import { CheckIcon, XIcon } from "lucide-react";
-
-import { Button } from "@/components/editor/inputs/Inputs";
-import {
- DirCompletionInput,
- DirCompletionInputHandle,
-} from "@/components/editor/DirCompletionInput";
-import { useImperativeModal } from "@/components/modal/ImperativeModal";
-import {
- AlertDialogDescription,
- AlertDialogHeader,
- AlertDialogTitle,
-} from "@/components/ui/alert-dialog";
-
-export const FilenameForm = ({
- filename,
- setFilename,
-}: {
- filename: string | null;
- setFilename: (filename: string | null) => Promise<string | null>;
-}): JSX.Element => {
- const { openAlert } = useImperativeModal();
- const placeholderText = filename === null ? "untitled marimo app" : filename;
- const [showButtons, setShowButtons] = useState(false);
- const [validName, setValidName] = useState(false);
- const handle = useRef<DirCompletionInputHandle | null>(null);
-
- function validateAndSubmitFilenameChange() {
- const inputEl = document.getElementById(
- "filename-input",
- ) as HTMLInputElement | null;
- if (inputEl === null) {
- throw new Error("Could not find filename form");
- }
- const value = inputEl.value;
- if (value.length === 0 || value === ".py") {
- openAlert(
- <AlertDialogHeader>
- <AlertDialogTitle className="text-destructive">
- Oops!
- </AlertDialogTitle>
- <AlertDialogDescription>
- The filename can't be empty. Make sure to enter a non-empty name.
- </AlertDialogDescription>
- </AlertDialogHeader>,
- );
- inputEl.blur();
- } else if (value.endsWith(".py")) {
- setFilename(value).then(() => {
- inputEl.blur();
- });
- } else {
- setFilename(`${value}.py`).then(() => {
- // wait for setter to resolve before blurring, because blurring
- // resets the underlying value
- inputEl.blur();
- });
- }
- }
-
- function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
- e.preventDefault();
- validateAndSubmitFilenameChange();
- }
-
- // MouseDown is fired before Blur
- function handleMouseDown(e: React.MouseEvent<HTMLButtonElement>) {
- e.preventDefault();
- validateAndSubmitFilenameChange();
- }
-
- function onFocus() {
- setShowButtons(true);
- }
-
- function onBlur() {
- // TODO(akshayka): if tabbed to button, buttons (and input value)
- // should remain visible
- setShowButtons(false);
- }
-
- function onChange(value: string) {
- const completionHandle = handle.current;
- if (completionHandle === null) {
- return;
- }
-
- const candidate = value.endsWith(".py") ? value : `${value}.py`;
- if (
- // name should not be ".py"
- candidate.length > 3 &&
- // file should not already exist
- !completionHandle.suggestions.includes(candidate)
- ) {
- setValidName(true);
- } else {
- setValidName(false);
- }
- }
-
- const buttonVis = showButtons ? "visible" : "hidden";
- return (
- <div id="Filename">
- <form id="filename-form" onSubmit={handleSubmit}>
- <div /> {/* empty element as grid spacer */}
- <div style={{ position: "relative" }}>
- <DirCompletionInput
- placeholderText={placeholderText}
- initialValue={filename}
- onChangeCallback={onChange}
- onFocusCallback={onFocus}
- onBlurCallback={onBlur}
- resetOnBlur={true}
- flexibleWidth={true}
- handle={handle}
- id="filename-input"
- className={filename === null ? "missing-filename" : "filename"}
- />
- <Button
- type="submit"
- data-testid="filename-form-submit-button"
- color={validName ? "green" : "gray"}
- onMouseDown={handleMouseDown}
- style={{
- marginRight: "0px",
- padding: "0px",
- position: "absolute",
- top: "0.25rem",
- right: "-44px",
- width: "30px",
- height: "30px",
- visibility: buttonVis,
- }}
- >
- <CheckIcon size={16} strokeWidth={1.5} />
- </Button>
- <Button
- color="gray"
- data-testid="filename-form-cancel-button"
- style={{
- marginRight: "0px",
- padding: "0px",
- position: "absolute",
- top: "0.25rem",
- right: "-86px",
- width: "30px",
- height: "30px",
- visibility: buttonVis,
- }}
- >
- <XIcon size={16} strokeWidth={1.5} />
- </Button>
- </div>
- </form>
- </div>
- );
-};
diff --git a/frontend/src/components/editor/header/filename-form.tsx b/frontend/src/components/editor/header/filename-form.tsx
new file mode 100644
index 0000000000..9134f87e5f
--- /dev/null
+++ b/frontend/src/components/editor/header/filename-form.tsx
@@ -0,0 +1,25 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { FilenameInput } from "@/components/editor/header/filename-input";
+import { Paths } from "@/utils/paths";
+
+export const FilenameForm = ({
+ filename,
+ setFilename,
+}: {
+ filename: string | null;
+ setFilename: (filename: string) => void;
+}): JSX.Element => {
+ return (
+ <FilenameInput
+ placeholderText={
+ filename ? Paths.basename(filename) : "untitled marimo app"
+ }
+ initialValue={filename}
+ onNameChange={setFilename}
+ flexibleWidth={true}
+ resetOnBlur={true}
+ data-testid="filename-input"
+ className={filename === null ? "missing-filename" : "filename"}
+ />
+ );
+};
diff --git a/frontend/src/components/editor/header/filename-input.css b/frontend/src/components/editor/header/filename-input.css
new file mode 100644
index 0000000000..5387cc1834
--- /dev/null
+++ b/frontend/src/components/editor/header/filename-input.css
@@ -0,0 +1,27 @@
+.missing-filename {
+ text-align: center;
+ box-shadow: var(--light-shadow-stale);
+}
+
+.missing-filename:hover,
+.missing-filename:focus {
+ box-shadow: var(--medium-shadow-stale);
+}
+
+.missing-filename:focus {
+ border-radius: 4px 4px 0 0;
+}
+
+.filename {
+ text-align: center;
+ box-shadow: none;
+}
+
+.filename:hover,
+.filename:focus {
+ box-shadow: var(--medium-shadow);
+}
+
+.filename:focus {
+ border-radius: 4px 4px 0 0;
+}
diff --git a/frontend/src/components/editor/header/filename-input.tsx b/frontend/src/components/editor/header/filename-input.tsx
new file mode 100644
index 0000000000..cfe6c4404c
--- /dev/null
+++ b/frontend/src/components/editor/header/filename-input.tsx
@@ -0,0 +1,233 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { useEffect, useRef, useState } from "react";
+
+import { cn } from "../../../utils/cn";
+import { sendListFiles } from "@/core/network/requests";
+import { Paths } from "@/utils/paths";
+import { useAsyncData } from "@/hooks/useAsyncData";
+import {
+ Command,
+ CommandEmpty,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from "../../ui/command";
+import { FilePenIcon } from "lucide-react";
+import { FILE_TYPE_ICONS, guessFileType } from "../file-tree/types";
+import { Popover, PopoverContent } from "../../ui/popover";
+import { PopoverAnchor } from "@radix-ui/react-popover";
+import { FileInfo } from "@/core/network/types";
+
+import "./filename-input.css";
+
+interface FilenameInputProps {
+ resetOnBlur?: boolean;
+ placeholderText?: string;
+ initialValue?: string | null;
+ className?: string;
+ flexibleWidth?: boolean;
+ onNameChange: (value: string) => void;
+}
+
+export const FilenameInput = ({
+ resetOnBlur = false,
+ placeholderText,
+ initialValue = null,
+ flexibleWidth = false,
+ onNameChange,
+ className,
+}: FilenameInputProps): JSX.Element => {
+ const [searchValue, setSearchValue] = useState(initialValue);
+ const [suggestions, setSuggestions] = useState<FileInfo[]>([]);
+ const [focused, setFocused] = useState<boolean>(false);
+ const inputRef = useRef<HTMLInputElement>(null);
+ const skipReset = useRef<boolean>(false);
+
+ useEffect(() => {
+ setSearchValue(initialValue);
+ }, [initialValue]);
+
+ const onFocus = () => {
+ setFocused(true);
+ };
+
+ const onBlur = (evt: React.FocusEvent<HTMLInputElement>) => {
+ // If we are coming from a click event from inside the popover, don't blur
+ if (evt.relatedTarget?.closest(".filename-input")) {
+ return;
+ }
+
+ setFocused(false);
+ if (resetOnBlur) {
+ setSearchValue(initialValue);
+ }
+ };
+
+ const dirname = Paths.dirname(searchValue || "");
+ const basename = Paths.basename(searchValue || "");
+
+ const filteredSuggestions = suggestions.filter((suggestion) =>
+ Paths.basename(suggestion.path).startsWith(basename),
+ );
+
+ const { loading } = useAsyncData(async () => {
+ if (!focused) {
+ setSuggestions([]);
+ return;
+ }
+
+ const data = await sendListFiles({ path: dirname });
+ setSuggestions(data.files);
+ }, [dirname, focused]);
+
+ const suggestedNamed = getSuggestion(searchValue, suggestions, initialValue);
+
+ const handleNameChange = () => {
+ if (suggestedNamed) {
+ // Don't reset the value
+ skipReset.current = true;
+ onNameChange(suggestedNamed);
+ inputRef.current?.blur();
+ }
+ };
+
+ const shouldShowList = suggestedNamed || filteredSuggestions.length > 0;
+ const suggestionsList = shouldShowList && (
+ <CommandList className="font-mono">
+ {!loading && <CommandEmpty>No files</CommandEmpty>}
+
+ {suggestedNamed && (
+ <CommandItem
+ key="_rename_"
+ variant="success"
+ className="py-2 px-3"
+ onSelect={handleNameChange}
+ >
+ <FilePenIcon className="w-4 h-4 mr-2" />{" "}
+ <span className="text-sm">
+ {initialValue ? "Rename to: " : "Save as: "}
+ <span className="font-medium text-sm">
+ {Paths.basename(suggestedNamed)}
+ </span>
+ </span>
+ </CommandItem>
+ )}
+
+ {filteredSuggestions.map((suggestion) => {
+ const fileType = suggestion.isDirectory
+ ? "directory"
+ : guessFileType(suggestion.path);
+ const Icon = FILE_TYPE_ICONS[fileType];
+
+ const handleCommand = () => {
+ if (suggestion.isDirectory) {
+ setSearchValue(`${suggestion.path}/`);
+ } else {
+ setSearchValue(suggestion.path);
+ }
+ };
+
+ return (
+ <CommandItem
+ key={suggestion.path}
+ variant={suggestion.isDirectory ? "default" : "muted"}
+ className="py-2 px-3"
+ onSelect={handleCommand}
+ >
+ <Icon className="w-4 h-4 mr-2" /> {Paths.basename(suggestion.path)}
+ </CommandItem>
+ );
+ })}
+ </CommandList>
+ );
+
+ const size =
+ Math.max(20, searchValue?.length || placeholderText?.length || 0) * 10;
+
+ return (
+ <Popover open={true} modal={false}>
+ <Command
+ onFocus={onFocus}
+ onBlur={onBlur}
+ shouldFilter={false}
+ className="bg-transparent group filename-input"
+ >
+ <PopoverAnchor>
+ <CommandInput
+ data-testid="dir-completion-input"
+ tabIndex={-1}
+ rootClassName="border-none justify-center px-1"
+ spellCheck="false"
+ value={focused ? searchValue || "" : initialValue || ""}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ e.currentTarget.blur();
+ }
+ }}
+ icon={null}
+ ref={inputRef}
+ onValueChange={setSearchValue}
+ placeholder={placeholderText}
+ autoComplete="off"
+ style={flexibleWidth ? { maxWidth: size } : undefined}
+ className={cn(
+ className,
+ "w-full px-4 py-1 my-1 h-9 font-mono text-foreground/60",
+ )}
+ />
+ </PopoverAnchor>
+
+ <PopoverContent
+ side="bottom"
+ className={cn(
+ "p-0 w-full min-w-80 max-w-80vw hidden",
+ suggestionsList && "group-focus-within:block",
+ )}
+ portal={false}
+ >
+ {suggestionsList}
+ </PopoverContent>
+ </Command>
+ </Popover>
+ );
+};
+
+function getSuggestion(
+ search: string | undefined | null,
+ existing: FileInfo[],
+ currentFilename: string | null,
+): string | undefined {
+ if (!search) {
+ return;
+ }
+ if (search.endsWith("/")) {
+ return;
+ }
+
+ if (search.endsWith(".")) {
+ search = `${search}py`;
+ } else if (search.endsWith(".p")) {
+ search = `${search}y`;
+ } else if (search.endsWith(".py")) {
+ // If ends with .py, leave as is
+ // noop
+ } else {
+ search = `${search}.py`;
+ }
+
+ if (
+ existing.some((s) => s.path === search || Paths.basename(s.path) === search)
+ ) {
+ return;
+ }
+
+ if (
+ currentFilename &&
+ (currentFilename === search || Paths.basename(currentFilename) === search)
+ ) {
+ return;
+ }
+
+ return search;
+}
diff --git a/frontend/src/components/ui/command.tsx b/frontend/src/components/ui/command.tsx
index e429117742..d00de8e260 100644
--- a/frontend/src/components/ui/command.tsx
+++ b/frontend/src/components/ui/command.tsx
@@ -49,14 +49,17 @@ const CommandInput = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Input>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input> & {
rootClassName?: string;
+ icon?: React.ReactNode | null;
}
->(({ className, rootClassName, ...props }, ref) => (
+>(({ className, icon, rootClassName, ...props }, ref) => (
<div
className={cn("flex items-center border-b px-3", rootClassName)}
// eslint-disable-next-line react/no-unknown-property
cmdk-input-wrapper=""
>
- <Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
+ {icon === null ? null : (
+ <Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
+ )}
<CommandPrimitive.Input
ref={ref}
className={cn(
diff --git a/frontend/src/components/ui/menu-items.tsx b/frontend/src/components/ui/menu-items.tsx
index 26dac616fc..c7f6f2a012 100644
--- a/frontend/src/components/ui/menu-items.tsx
+++ b/frontend/src/components/ui/menu-items.tsx
@@ -55,6 +55,10 @@ export const menuItemVariants = cva(
"focus:bg-accent focus:text-accent-foreground aria-selected:bg-accent aria-selected:text-accent-foreground",
danger:
"focus:bg-[var(--red-5)] focus:text-[var(--red-12)] aria-selected:bg-[var(--red-5)] aria-selected:text-[var(--red-12)]",
+ muted:
+ "focus:bg-muted/70 focus:text-muted-foreground aria-selected:bg-muted/70 aria-selected:text-muted-foreground",
+ success:
+ "focus:bg-[var(--grass-3)] focus:text-[var(--grass-11)] aria-selected:bg-[var(--grass-3)] aria-selected:text-[var(--grass-11)]",
},
},
defaultVariants: {
diff --git a/frontend/src/components/ui/popover.tsx b/frontend/src/components/ui/popover.tsx
index f59449d49b..e4fab4f348 100644
--- a/frontend/src/components/ui/popover.tsx
+++ b/frontend/src/components/ui/popover.tsx
@@ -10,21 +10,33 @@ const PopoverTrigger = PopoverPrimitive.Trigger;
const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
- React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
->(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
- <PopoverPrimitive.Portal>
- <PopoverPrimitive.Content
- ref={ref}
- align={align}
- sideOffset={sideOffset}
- className={cn(
- "z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none animate-in data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
- className,
- )}
- {...props}
- />
- </PopoverPrimitive.Portal>
-));
+ React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content> & {
+ portal?: boolean;
+ }
+>(
+ (
+ { className, align = "center", sideOffset = 4, portal = true, ...props },
+ ref,
+ ) => {
+ const content = (
+ <PopoverPrimitive.Content
+ ref={ref}
+ align={align}
+ sideOffset={sideOffset}
+ className={cn(
+ "z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none animate-in data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
+ className,
+ )}
+ {...props}
+ />
+ );
+ if (portal) {
+ return <PopoverPrimitive.Portal>{content}</PopoverPrimitive.Portal>;
+ }
+
+ return content;
+ },
+);
PopoverContent.displayName = PopoverPrimitive.Content.displayName;
export { Popover, PopoverTrigger, PopoverContent };
diff --git a/frontend/src/core/App.tsx b/frontend/src/core/App.tsx
index 4b18aafe0c..58f7c466b4 100644
--- a/frontend/src/core/App.tsx
+++ b/frontend/src/core/App.tsx
@@ -7,8 +7,8 @@ import { useCallback, useEffect, useState } from "react";
import { sendInterrupt, sendRename, sendSave } from "@/core/network/requests";
import { Controls } from "@/components/editor/controls/Controls";
-import { DirCompletionInput } from "@/components/editor/DirCompletionInput";
-import { FilenameForm } from "@/components/editor/FilenameForm";
+import { FilenameInput } from "@/components/editor/header/filename-input";
+import { FilenameForm } from "@/components/editor/header/filename-form";
import { WebSocketState } from "./websocket/types";
import { useMarimoWebSocket } from "./websocket/useMarimoWebSocket";
import {
@@ -99,32 +99,30 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {
sessionId: getSessionId(),
});
- const handleFilenameChange = useEvent(
- (name: string | null): Promise<string | null> => {
- if (connStatus.state !== WebSocketState.OPEN) {
- alertSaveFailed();
- return Promise.resolve(null);
+ const handleFilenameChange = useEvent(async (name: string | null) => {
+ if (connStatus.state !== WebSocketState.OPEN) {
+ alertSaveFailed();
+ return null;
+ }
+
+ updateQueryParams((params) => {
+ if (name === null) {
+ params.delete("file");
+ } else {
+ params.set("file", name);
}
+ });
- updateQueryParams((params) => {
- if (name === null) {
- params.delete("file");
- } else {
- params.set("file", name);
- }
+ return sendRename(name)
+ .then(() => {
+ setFilename(name);
+ return name;
+ })
+ .catch((error) => {
+ openAlert(error.message);
+ return null;
});
-
- return sendRename(name)
- .then(() => {
- setFilename(name);
- return name;
- })
- .catch((error) => {
- openAlert(error.message);
- return null;
- });
- },
- );
+ });
const cells = notebookCells(notebook);
const cellIds = cells.map((cell) => cell.id);
@@ -188,12 +186,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {
// Filename does not exist and we are connected to a kernel
if (filename === null && connStatus.state !== WebSocketState.CLOSED) {
- openModal(
- <SaveDialog
- onClose={closeModal}
- onSubmitSaveDialog={onSubmitSaveDialog}
- />,
- );
+ openModal(<SaveDialog onClose={closeModal} onSave={handleSaveDialog} />);
}
});
@@ -221,18 +214,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {
}
});
- const onSubmitSaveDialog = (e: React.FormEvent<HTMLFormElement>) => {
- const value = new FormData(e.currentTarget).get("SaveDialogInput");
- if (typeof value !== "string") {
- alert("Filename cannot be empty");
- return;
- }
- if (value.length === 0 || value === ".py") {
- alert("Filename cannot be empty");
- return;
- }
-
- const pythonFilename = value.endsWith(".py") ? value : `${value}.py`;
+ const handleSaveDialog = (pythonFilename: string) => {
handleFilenameChange(pythonFilename).then((name) => {
if (name !== null) {
saveNotebook(name, true);
@@ -343,7 +325,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {
)}
>
{isEditing && (
- <div id="Welcome">
+ <div className="flex items-center justify-center container">
<FilenameForm
filename={filename}
setFilename={handleFilenameChange}
@@ -416,59 +398,49 @@ const NoiseBackground = () => (
const SaveDialog = (props: {
onClose: () => void;
- onSubmitSaveDialog: (e: React.FormEvent<HTMLFormElement>) => void;
+ onSave: (filename: string) => void;
}) => {
- const { onClose, onSubmitSaveDialog } = props;
+ const { onClose, onSave } = props;
const cancelButtonLabel = "Cancel";
+ const [filename, setFilename] = useState<string>();
+ const handleFilenameChange = (name: string) => {
+ setFilename(name);
+ if (name.trim()) {
+ onSave(name);
+ onClose();
+ }
+ };
+
return (
- <DialogContent className="w-fit">
- <form
- onSubmit={(e) => {
- e.preventDefault();
- onSubmitSaveDialog(e);
- onClose();
- }}
- onKeyDown={(e) => {
- // We don't submit on Enter because the user may
- // have focused the cancel button ...
- if (e.key === "Escape") {
- onClose();
- } else if (
- e.key === "Enter" &&
- document.activeElement?.ariaLabel !== cancelButtonLabel
- ) {
- onSubmitSaveDialog(e);
- onClose();
- }
- }}
- >
- <DialogTitle className="text-accent mb-6">Save?</DialogTitle>
- <div className="flex items-center gap-5 mb-6 ml-4 mr-16">
- <Label className="text-md text-muted-foreground">Save as</Label>
- <DirCompletionInput
- name="SaveDialogInput"
- className="missing-filename"
- />
- </div>
- <DialogFooter>
- <Button
- data-testid="cancel-save-dialog-button"
- aria-label={cancelButtonLabel}
- variant="secondary"
- onClick={onClose}
- >
- Cancel
- </Button>
- <Button
- data-testid="submit-save-dialog-button"
- aria-label="Save"
- variant="default"
- type="submit"
- >
- Save
- </Button>
- </DialogFooter>
- </form>
+ <DialogContent>
+ <DialogTitle>Save notebook</DialogTitle>
+ <div className="flex flex-col">
+ <Label className="text-md pt-6 px-1">Save as</Label>
+ <FilenameInput
+ onNameChange={handleFilenameChange}
+ placeholderText="filename"
+ className="missing-filename"
+ />
+ </div>
+ <DialogFooter>
+ <Button
+ data-testid="cancel-save-dialog-button"
+ aria-label={cancelButtonLabel}
+ variant="secondary"
+ onClick={onClose}
+ >
+ Cancel
+ </Button>
+ <Button
+ data-testid="submit-save-dialog-button"
+ aria-label="Save"
+ variant="default"
+ disabled={!filename}
+ type="submit"
+ >
+ Save
+ </Button>
+ </DialogFooter>
</DialogContent>
);
};
diff --git a/frontend/src/css/Cell.css b/frontend/src/css/Cell.css
index 77519ea63e..779d6d0294 100644
--- a/frontend/src/css/Cell.css
+++ b/frontend/src/css/Cell.css
@@ -355,7 +355,7 @@
.output-area {
max-width: inherit;
width: 100%;
- padding: 0.25rem 1.85rem;
+ padding: 1rem;
/* Prevent floated elements from extending out of the output areas and into
* the editor. */
diff --git a/frontend/src/css/Header.css b/frontend/src/css/Header.css
index c1e89f8c12..c88cced76a 100644
--- a/frontend/src/css/Header.css
+++ b/frontend/src/css/Header.css
@@ -6,20 +6,6 @@
color: var(--red-11);
}
-#Welcome {
- max-width: var(--content-width);
- margin: auto;
- display: grid;
-
- /* center filename input , with whitespace on either side */
- grid-template-columns: 1fr auto 1fr;
-}
-
-#Welcome > div:first-child {
- position: relative;
- grid-column: 2;
-}
-
@keyframes running-app-animation {
0% {
transform: rotate(0turn);
@@ -66,95 +52,3 @@
.keyboard-shortcut span {
grid-column: 3;
}
-
-#Filename {
- text-align: center;
- margin-bottom: 25px;
- font-family: var(--monospace-font);
-
- @apply text-muted-foreground;
-}
-
-.missing-filename {
- text-align: center;
- box-shadow: var(--light-shadow-stale);
-}
-
-.missing-filename:hover,
-.missing-filename:focus {
- box-shadow: var(--medium-shadow-stale);
-}
-
-.missing-filename:focus {
- border-radius: 4px 4px 0 0;
-}
-
-.filename {
- text-align: center;
- box-shadow: none;
-}
-
-.filename:hover,
-.filename:focus {
- box-shadow: var(--medium-shadow);
-}
-
-.filename:focus {
- border-radius: 4px 4px 0 0;
-}
-
-#filename-form {
- display: contents;
-}
-
-#filename-input:focus {
- min-width: 200px;
-}
-
-.DirCompletionInput {
- position: relative;
-}
-
-.autocomplete-list {
- padding: 0;
- margin-top: 0;
- border-top-width: 0;
- border-radius: 0 0 5px 5px;
- max-height: 200px;
- overflow-y: auto;
- text-align: left;
- list-style: none;
- z-index: 1;
- position: absolute;
- box-shadow: var(--medium-shadow);
-
- @apply bg-card;
-}
-
-.autocomplete-list li {
- padding: 3px;
-}
-
-.autocomplete-list li:not(:last-of-type) {
- border-bottom: 1px dashed var(--gray-9);
-}
-
-.active-suggestion,
-.autocomplete-list li:hover {
- background-color: var(--grass-4);
- cursor: pointer;
-}
-
-.active-suggestion {
- border-left: 2px solid var(--grass-11);
-}
-
-.active-suggestion.file,
-.autocomplete-list li.file:hover {
- border-left: 2px solid var(--gray-11);
- background-color: var(--gray-2);
-}
-
-.file {
- color: var(--gray-10);
-}
diff --git a/frontend/src/css/md.css b/frontend/src/css/md.css
index eea7603ddc..9f24a97d20 100644
--- a/frontend/src/css/md.css
+++ b/frontend/src/css/md.css
@@ -28,7 +28,7 @@
/* provide by the browser, but removed from 'reset' */
display: block;
font-size: 2rem;
- margin-block: 0.67rem 0.67rem;
+ margin-block-end: 0.67rem;
margin-inline: 0 0;
text-align: center;
}
@@ -42,7 +42,7 @@
/* provide by the browser, but removed from 'reset' */
display: block;
font-size: 1.5rem;
- margin-block: 0.83rem 0.83rem;
+ margin-block-end: 0.83rem;
margin-inline: 0 0;
}
@@ -50,7 +50,7 @@
/* provide by the browser, but removed from 'reset' */
display: block;
font-size: 1.17rem;
- margin-block: 1rem 1rem;
+ margin-block-end: 1rem;
margin-inline: 0 0;
}