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.

feat: snippets panel (#1069)

Myles Scolnickecf43e4da221
diff --git a/frontend/src/components/editor/boundary/ErrorBoundary.tsx b/frontend/src/components/editor/boundary/ErrorBoundary.tsx
index dc7dd7a96a..92054e3280 100644
--- a/frontend/src/components/editor/boundary/ErrorBoundary.tsx
+++ b/frontend/src/components/editor/boundary/ErrorBoundary.tsx
@@ -19,7 +19,7 @@ const FallbackComponent: React.FC<FallbackProps> = (props) => {
return (
<div className="flex-1 flex items-center justify-center flex-col space-y-4 max-w-2xl mx-auto">
<h1 className="text-2xl font-bold">Something went wrong</h1>
- <pre className="text-xs bg-muted/40 border rounded-md p-4">
+ <pre className="text-xs bg-muted/40 border rounded-md p-4 max-w-[80%] whitespace-normal">
{props.error?.message}
</pre>
<div>
diff --git a/frontend/src/components/editor/chrome/components/contribute-snippet-button.tsx b/frontend/src/components/editor/chrome/components/contribute-snippet-button.tsx
new file mode 100644
index 0000000000..50fc79f330
--- /dev/null
+++ b/frontend/src/components/editor/chrome/components/contribute-snippet-button.tsx
@@ -0,0 +1,137 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { useImperativeModal } from "@/components/modal/ImperativeModal";
+import {
+ DialogFooter,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogDescription,
+} from "@/components/ui/dialog";
+import { Slot } from "@radix-ui/react-slot";
+import React, { PropsWithChildren } from "react";
+import { Button } from "@/components/ui/button";
+import { Textarea } from "@/components/ui/textarea";
+import { toast } from "@/components/ui/use-toast";
+import { Constants } from "@/core/constants";
+import { Input } from "@/components/ui/input";
+import AnyLanguageCodeMirror from "@/plugins/impl/code/any-language-editor";
+import { EditorView } from "@codemirror/view";
+import { useState } from "react";
+import { useTheme } from "@/theme/useTheme";
+
+export const ContributeSnippetButton: React.FC<PropsWithChildren> = ({
+ children,
+}) => {
+ const { openModal, closeModal } = useImperativeModal();
+
+ return (
+ <Slot
+ onClick={() => openModal(<ContributeSnippetModal onClose={closeModal} />)}
+ >
+ {children}
+ </Slot>
+ );
+};
+
+const ContributeSnippetModal: React.FC<{
+ onClose: () => void;
+}> = ({ onClose }) => {
+ const [code, setCode] = useState("");
+ const { theme } = useTheme();
+
+ return (
+ <DialogContent className="w-fit">
+ <form
+ onSubmit={async (e) => {
+ e.preventDefault();
+
+ const formData = new FormData(e.target as HTMLFormElement);
+ const title = formData.get("title");
+ const description = formData.get("description");
+ const code = formData.get("code");
+
+ // Fire-and-forget we don't care about the response
+ void fetch("https://marimo.io/api/suggest-snippet", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ title,
+ description,
+ code,
+ }),
+ });
+ onClose();
+ toast({
+ title: "Snippet Submitted",
+ description:
+ "Thank you for contributing! We will review your snippet shortly.",
+ });
+ }}
+ >
+ <DialogHeader>
+ <DialogTitle>Contribute a Snippet</DialogTitle>
+ <DialogDescription>
+ Have a useful snippet you want to share with the community? Submit
+ it here or make a pull request{" "}
+ <a
+ href={Constants.githubPage}
+ target="_blank"
+ rel="noreferrer"
+ className="underline"
+ >
+ on GitHub
+ </a>
+ .
+ </DialogDescription>
+ </DialogHeader>
+ <div className="flex flex-col gap-6 py-4">
+ <Input
+ id="title"
+ name="title"
+ autoFocus={true}
+ placeholder="Title"
+ required={true}
+ autoComplete="off"
+ />
+ <Textarea
+ id="description"
+ name="description"
+ autoFocus={true}
+ placeholder="Description"
+ rows={5}
+ required={true}
+ autoComplete="off"
+ />
+ <input type="hidden" name="code" value={code} />
+ <AnyLanguageCodeMirror
+ theme={theme === "dark" ? "dark" : "light"}
+ language="python"
+ className="cm border rounded overflow-hidden"
+ extensions={[EditorView.lineWrapping]}
+ value={code}
+ onChange={(value) => setCode(value)}
+ />
+ </div>
+ <DialogFooter>
+ <Button
+ data-testid="snippet-cancel-button"
+ variant="secondary"
+ onClick={onClose}
+ >
+ Cancel
+ </Button>
+ <Button
+ data-testid="snippet-send-button"
+ aria-label="Save"
+ variant="default"
+ type="submit"
+ >
+ Send
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ );
+};
diff --git a/frontend/src/components/editor/chrome/footer/feedback-button.tsx b/frontend/src/components/editor/chrome/components/feedback-button.tsx
similarity index 100%
rename from frontend/src/components/editor/chrome/footer/feedback-button.tsx
rename to frontend/src/components/editor/chrome/components/feedback-button.tsx
diff --git a/frontend/src/components/editor/chrome/panels/documentation-panel.tsx b/frontend/src/components/editor/chrome/panels/documentation-panel.tsx
index 44a25989a9..0f13620a8f 100644
--- a/frontend/src/components/editor/chrome/panels/documentation-panel.tsx
+++ b/frontend/src/components/editor/chrome/panels/documentation-panel.tsx
@@ -5,18 +5,18 @@ import { useAtomValue } from "jotai";
import React from "react";
import "../../documentation.css";
import { BookMarkedIcon } from "lucide-react";
+import { PanelEmptyState } from "./empty-state";
export const DocumentationPanel: React.FC = () => {
const { documentation } = useAtomValue(documentationAtom);
if (!documentation) {
return (
- <div className="mx-6 my-6 flex flex-row gap-2 items-center rounded-lg">
- <BookMarkedIcon className="text-accent-foreground" />
- <span className="mt-[0.25rem] text-accent-foreground">
- No documentation
- </span>
- </div>
+ <PanelEmptyState
+ title="No documentation"
+ description="Move your cursor over a symbol to see its documentation."
+ icon={<BookMarkedIcon />}
+ />
);
}
diff --git a/frontend/src/components/editor/chrome/panels/empty-state.tsx b/frontend/src/components/editor/chrome/panels/empty-state.tsx
new file mode 100644
index 0000000000..f6376425cb
--- /dev/null
+++ b/frontend/src/components/editor/chrome/panels/empty-state.tsx
@@ -0,0 +1,22 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import React from "react";
+
+interface Props {
+ title: string;
+ description?: React.ReactNode;
+ color?: string;
+ icon?: React.ReactElement;
+}
+
+export const PanelEmptyState = ({ title, description, color, icon }: Props) => {
+ return (
+ <div className="mx-6 my-6 flex flex-col gap-2">
+ <div className="flex flex-row gap-2 items-center">
+ {icon &&
+ React.cloneElement(icon, { className: "text-accent-foreground" })}
+ <span className="mt-1 text-accent-foreground">{title}</span>
+ </div>
+ <span className="text-muted-foreground text-sm">{description}</span>
+ </div>
+ );
+};
diff --git a/frontend/src/components/editor/chrome/panels/error-panel.tsx b/frontend/src/components/editor/chrome/panels/error-panel.tsx
index a21962795d..619769f7f7 100644
--- a/frontend/src/components/editor/chrome/panels/error-panel.tsx
+++ b/frontend/src/components/editor/chrome/panels/error-panel.tsx
@@ -4,20 +4,13 @@ import { useCellErrors } from "../../../../core/cells/cells";
import { MarimoErrorOutput } from "../../output/MarimoErrorOutput";
import { CellLinkError } from "@/components/editor/links/cell-link";
import { PartyPopperIcon } from "lucide-react";
+import { PanelEmptyState } from "./empty-state";
export const ErrorsPanel: React.FC = () => {
const errors = useCellErrors();
if (errors.length === 0) {
- return (
- <div className="mx-6 my-6 flex flex-row gap-2 items-center rounded-lg">
- <PartyPopperIcon className="text-accent-foreground" />
- <span className="mt-[0.25rem] text-accent-foreground">
- {" "}
- No errors!{" "}
- </span>
- </div>
- );
+ return <PanelEmptyState title="No errors!" icon={<PartyPopperIcon />} />;
}
return (
diff --git a/frontend/src/components/editor/chrome/panels/logs-panel.tsx b/frontend/src/components/editor/chrome/panels/logs-panel.tsx
index 7b0193a9d1..1f8dcaa48e 100644
--- a/frontend/src/components/editor/chrome/panels/logs-panel.tsx
+++ b/frontend/src/components/editor/chrome/panels/logs-panel.tsx
@@ -5,6 +5,7 @@ import { cn } from "@/utils/cn";
import React from "react";
import { FileTextIcon } from "lucide-react";
import { CellLink } from "../../links/cell-link";
+import { PanelEmptyState } from "./empty-state";
interface Props {
className?: string;
@@ -17,10 +18,17 @@ export const LogsPanel: React.FC = () => {
if (logs.length === 0) {
return (
- <div className="mx-6 my-6 flex flex-row gap-2 items-center rounded-lg">
- <FileTextIcon className="text-muted-foreground" />
- <span className="mt-[0.25rem] text-muted-foreground">No logs</span>
- </div>
+ <PanelEmptyState
+ title="No logs"
+ description={
+ <span>
+ <code className="border rounded px-1">stdout</code> and{" "}
+ <code className="border rounded px-1">stderr</code> logs will appear
+ here.
+ </span>
+ }
+ icon={<FileTextIcon />}
+ />
);
}
diff --git a/frontend/src/components/editor/chrome/panels/outline-panel.tsx b/frontend/src/components/editor/chrome/panels/outline-panel.tsx
index 26513679f7..cb25377f6d 100644
--- a/frontend/src/components/editor/chrome/panels/outline-panel.tsx
+++ b/frontend/src/components/editor/chrome/panels/outline-panel.tsx
@@ -4,6 +4,7 @@ import { notebookOutline } from "../../../../core/cells/cells";
import { useAtomValue } from "jotai";
import { cn } from "@/utils/cn";
import { ScrollTextIcon } from "lucide-react";
+import { PanelEmptyState } from "./empty-state";
import "./outline-panel.css";
@@ -12,10 +13,11 @@ export const OutlinePanel: React.FC = () => {
if (outline.items.length === 0) {
return (
- <div className="mx-6 my-6 flex flex-row gap-2 items-center rounded-lg">
- <ScrollTextIcon className="text-muted-foreground" />
- <span className="mt-[0.25rem] text-muted-foreground">No outline</span>
- </div>
+ <PanelEmptyState
+ title="No outline"
+ description="Add markdown headings to your notebook to create an outline."
+ icon={<ScrollTextIcon />}
+ />
);
}
diff --git a/frontend/src/components/editor/chrome/panels/snippets-panel.css b/frontend/src/components/editor/chrome/panels/snippets-panel.css
new file mode 100644
index 0000000000..a04d027018
--- /dev/null
+++ b/frontend/src/components/editor/chrome/panels/snippets-panel.css
@@ -0,0 +1,9 @@
+.snippet-viewer {
+ h1 {
+ text-align: left;
+ @apply text-base font-bold;
+ }
+ h2 {
+ @apply text-sm font-bold;
+ }
+}
diff --git a/frontend/src/components/editor/chrome/panels/snippets-panel.tsx b/frontend/src/components/editor/chrome/panels/snippets-panel.tsx
new file mode 100644
index 0000000000..b1ea58a4dc
--- /dev/null
+++ b/frontend/src/components/editor/chrome/panels/snippets-panel.tsx
@@ -0,0 +1,210 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import React from "react";
+import { BetweenHorizontalStartIcon, PlusIcon } from "lucide-react";
+import { PanelEmptyState } from "./empty-state";
+import { useAsyncData } from "@/hooks/useAsyncData";
+import { ErrorBanner } from "@/plugins/impl/common/error-banner";
+import { Snippet } from "@/core/network/types";
+import { renderHTML } from "@/plugins/core/RenderHTML";
+import { readSnippets } from "@/core/network/requests";
+import {
+ Command,
+ CommandEmpty,
+ CommandInput,
+ CommandItem,
+} from "@/components/ui/command";
+import { CommandList } from "cmdk";
+
+import "./snippets-panel.css";
+import { LazyAnyLanguageCodeMirror } from "@/plugins/impl/code/LazyAnyLanguageCodeMirror";
+import { useTheme } from "@/theme/useTheme";
+import { EditorView } from "@codemirror/view";
+import { Suspense } from "react";
+import { Button } from "@/components/ui/button";
+import { Tooltip } from "@/components/ui/tooltip";
+import { useAtomValue } from "jotai";
+import { lastFocusedCellIdAtom } from "@/core/cells/focus";
+import { useCellActions } from "@/core/cells/cells";
+import { cn } from "@/utils/cn";
+import { ContributeSnippetButton } from "../components/contribute-snippet-button";
+import { Spinner } from "@/components/icons/spinner";
+
+export const SnippetsPanel: React.FC = () => {
+ const [selectedSnippet, setSelectedSnippet] = React.useState<Snippet>();
+ const {
+ data: snippets,
+ error,
+ loading,
+ } = useAsyncData(() => {
+ return readSnippets();
+ }, []);
+
+ if (error) {
+ return <ErrorBanner error={error} />;
+ }
+
+ if (loading || !snippets) {
+ return <Spinner size="medium" centered={true} />;
+ }
+
+ return (
+ <div className="flex-1 overflow-hidden">
+ <Command
+ className={cn(
+ "border-b rounded-none",
+ selectedSnippet ? "h-1/3" : "h-full",
+ )}
+ >
+ <div className="flex items-center w-full">
+ <CommandInput
+ placeholder="Search snippets..."
+ className="h-6 m-1"
+ rootClassName="flex-1 border-r"
+ />
+ <ContributeSnippetButton>
+ <button className="float-right border-b px-2 m-0 h-full hover:bg-accent hover:text-accent-foreground">
+ <PlusIcon className="h-4 w-4" />
+ </button>
+ </ContributeSnippetButton>
+ </div>
+
+ <CommandEmpty>No results</CommandEmpty>
+ <SnippetList
+ onSelect={(snippet) => setSelectedSnippet(snippet)}
+ snippets={snippets.snippets}
+ />
+ </Command>
+ <Suspense>
+ <div className="h-2/3 snippet-viewer flex flex-col">
+ {selectedSnippet ? (
+ <SnippetViewer
+ key={selectedSnippet.title}
+ snippet={selectedSnippet}
+ />
+ ) : (
+ <PanelEmptyState
+ title=""
+ description="Click on a snippet to view its content."
+ />
+ )}
+ </div>
+ </Suspense>
+ </div>
+ );
+};
+
+const SnippetViewer: React.FC<{ snippet: Snippet }> = ({ snippet }) => {
+ const { theme } = useTheme();
+ const { createNewCell } = useCellActions();
+ const lastFocusedCellId = useAtomValue(lastFocusedCellIdAtom);
+
+ const handleInsertSnippet = () => {
+ if (!snippet) {
+ return;
+ }
+
+ // Add below last focused cell in reverse order
+ for (const section of [...snippet.sections].reverse()) {
+ if (section.code) {
+ createNewCell({
+ code: section.code,
+ before: false,
+ cellId: lastFocusedCellId ?? "__end__",
+ });
+ }
+ }
+ };
+
+ const handleInsertCode = (code: string) => {
+ createNewCell({
+ code,
+ before: false,
+ cellId: lastFocusedCellId ?? "__end__",
+ });
+ };
+
+ return (
+ <>
+ <div className="text-sm font-semibold bg-muted border-y px-2 py-1">
+ {snippet.title}
+ </div>
+ <div className="px-2 py-2 space-y-4 overflow-auto flex-1">
+ <div className="flex justify-end">
+ <Button
+ className="float-right"
+ size="xs"
+ variant="outline"
+ onClick={handleInsertSnippet}
+ >
+ Insert snippet
+ <BetweenHorizontalStartIcon className="ml-2 h-4 w-4" />
+ </Button>
+ </div>
+ {snippet.sections.map((section) => {
+ const { code, html, id } = section;
+ if (html) {
+ return (
+ <div key={`${snippet.title}-${id}`}>
+ {renderHTML({ html: html })}
+ </div>
+ );
+ }
+
+ if (!code) {
+ return null;
+ }
+
+ return (
+ <div
+ className="relative hover-actions-parent pr-2"
+ key={`${snippet.title}-${id}`}
+ >
+ <Tooltip content="Insert snippet">
+ <Button
+ className="absolute -top-2 -right-1 z-10 hover-action px-2 bg-background"
+ size="sm"
+ variant="outline"
+ onClick={() => {
+ handleInsertCode(code);
+ }}
+ >
+ <BetweenHorizontalStartIcon className="h-5 w-5" />
+ </Button>
+ </Tooltip>
+ <LazyAnyLanguageCodeMirror
+ key={`${snippet.title}-${id}`}
+ theme={theme === "dark" ? "dark" : "light"}
+ language="python"
+ className="cm border rounded overflow-hidden"
+ extensions={[EditorView.lineWrapping]}
+ value={code}
+ readOnly={true}
+ />
+ </div>
+ );
+ })}
+ </div>
+ </>
+ );
+};
+
+const SnippetList: React.FC<{
+ onSelect: (snippet: Snippet) => void;
+ snippets: Snippet[];
+}> = ({ snippets, onSelect }) => {
+ return (
+ <CommandList className="flex flex-col overflow-auto">
+ {snippets.map((snippet) => (
+ <CommandItem
+ className="rounded-none"
+ key={snippet.title}
+ onSelect={() => onSelect(snippet)}
+ >
+ <div className="flex flex-row gap-2 items-center">
+ <span className="mt-1 text-accent-foreground">{snippet.title}</span>
+ </div>
+ </CommandItem>
+ ))}
+ </CommandList>
+ );
+};
diff --git a/frontend/src/components/editor/chrome/panels/variable-panel.tsx b/frontend/src/components/editor/chrome/panels/variable-panel.tsx
index efa91310d1..15ca77e1bd 100644
--- a/frontend/src/components/editor/chrome/panels/variable-panel.tsx
+++ b/frontend/src/components/editor/chrome/panels/variable-panel.tsx
@@ -3,11 +3,23 @@ import { VariableTable } from "@/components/variables/variables-table";
import { useCellIds } from "@/core/cells/cells";
import { useVariables } from "@/core/variables/state";
import React from "react";
+import { PanelEmptyState } from "./empty-state";
+import { FunctionSquareIcon } from "lucide-react";
export const VariablePanel: React.FC = () => {
const variables = useVariables();
const cellIds = useCellIds();
+ if (Object.keys(variables).length === 0) {
+ return (
+ <PanelEmptyState
+ title="No variables"
+ description="Global variables will appear here."
+ icon={<FunctionSquareIcon />}
+ />
+ );
+ }
+
return (
<VariableTable className="flex-1" cellIds={cellIds} variables={variables} />
);
diff --git a/frontend/src/components/editor/chrome/types.ts b/frontend/src/components/editor/chrome/types.ts
index 73c29d8c33..b49c8e7e31 100644
--- a/frontend/src/components/editor/chrome/types.ts
+++ b/frontend/src/components/editor/chrome/types.ts
@@ -9,6 +9,7 @@ import {
BookMarkedIcon,
FileTextIcon,
LucideIcon,
+ SquareDashedBottomCodeIcon,
} from "lucide-react";
export type PanelType =
@@ -18,6 +19,7 @@ export type PanelType =
| "outline"
| "dependencies"
| "documentation"
+ | "snippets"
| "logs";
export const PANEL_ICONS: Record<PanelType, LucideIcon> = {
@@ -28,6 +30,7 @@ export const PANEL_ICONS: Record<PanelType, LucideIcon> = {
outline: ScrollTextIcon,
documentation: BookMarkedIcon,
logs: FileTextIcon,
+ snippets: SquareDashedBottomCodeIcon,
};
export const PANEL_TYPES: PanelType[] = Objects.keys(PANEL_ICONS);
diff --git a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
index a73135d46b..6bb16e27ad 100644
--- a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
@@ -20,6 +20,7 @@ import { VariablePanel } from "../panels/variable-panel";
import { LogsPanel } from "../panels/logs-panel";
import { DocumentationPanel } from "../panels/documentation-panel";
import { FileExplorerPanel } from "../panels/file-explorer-panel";
+import { SnippetsPanel } from "../panels/snippets-panel";
export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
const { isOpen, selectedPanel } = useChromeState();
@@ -97,6 +98,7 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
{selectedPanel === "dependencies" && <DependencyGraphPanel />}
{selectedPanel === "outline" && <OutlinePanel />}
{selectedPanel === "documentation" && <DocumentationPanel />}
+ {selectedPanel === "snippets" && <SnippetsPanel />}
{selectedPanel === "logs" && <LogsPanel />}
</div>
);
diff --git a/frontend/src/components/editor/chrome/wrapper/footer.tsx b/frontend/src/components/editor/chrome/wrapper/footer.tsx
index e51f6c14e5..9a0245a09e 100644
--- a/frontend/src/components/editor/chrome/wrapper/footer.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/footer.tsx
@@ -6,7 +6,7 @@ import { useChromeActions, useChromeState } from "../state";
import { Tooltip } from "@/components/ui/tooltip";
import { useAtomValue } from "jotai";
import { cellErrorCount } from "@/core/cells/cells";
-import { FeedbackButton } from "../footer/feedback-button";
+import { FeedbackButton } from "../components/feedback-button";
import { PANEL_ICONS, PanelType } from "../types";
export const Footer: React.FC = () => {
@@ -71,6 +71,13 @@ export const Footer: React.FC = () => {
>
{renderIcon("logs")}
</FooterItem>
+ <FooterItem
+ tooltip="Snippets"
+ selected={selectedPanel === "snippets"}
+ onClick={() => openApplication("snippets")}
+ >
+ {renderIcon("snippets")}
+ </FooterItem>
<FeedbackButton>
<FooterItem tooltip="Send feedback!" selected={false}>
diff --git a/frontend/src/components/editor/file-tree/file-explorer.tsx b/frontend/src/components/editor/file-tree/file-explorer.tsx
index a9282eaa50..e8027b8604 100644
--- a/frontend/src/components/editor/file-tree/file-explorer.tsx
+++ b/frontend/src/components/editor/file-tree/file-explorer.tsx
@@ -15,7 +15,6 @@ import {
UploadIcon,
ViewIcon,
} from "lucide-react";
-import { useOnMount } from "@/hooks/useLifecycle";
import { openFile } from "@/core/network/requests";
import { FileInfo } from "@/core/network/types";
import {
@@ -46,6 +45,9 @@ import { FileViewer } from "./file-viewer";
import { treeAtom, openStateAtom } from "./state";
import { useFileExplorerUpload } from "./upload";
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";
export const FileExplorer: React.FC<{
height: number;
@@ -55,9 +57,15 @@ export const FileExplorer: React.FC<{
const [openState, setOpenState] = useAtom(openStateAtom);
const [openFile, setOpenFile] = useState<FileInfo | null>(null);
- useOnMount(() => {
- void tree.initialize(setData);
- });
+ const { loading, error } = useAsyncData(() => tree.initialize(setData), []);
+
+ if (loading) {
+ return <Spinner size="medium" centered={true} />;
+ }
+
+ if (error) {
+ return <ErrorBanner error={error} />;
+ }
if (openFile) {
return (
diff --git a/frontend/src/components/icons/spinner.tsx b/frontend/src/components/icons/spinner.tsx
new file mode 100644
index 0000000000..7fe0d137c9
--- /dev/null
+++ b/frontend/src/components/icons/spinner.tsx
@@ -0,0 +1,38 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { cn } from "@/utils/cn";
+import { VariantProps, cva } from "class-variance-authority";
+import { Loader2Icon } from "lucide-react";
+import React from "react";
+
+const spinnerVariants = cva("animate-spin", {
+ variants: {
+ centered: {
+ true: "m-auto",
+ },
+ size: {
+ small: "size-4",
+ medium: "size-12",
+ large: "size-20",
+ xlarge: "size-20",
+ },
+ },
+ defaultVariants: {
+ size: "medium",
+ },
+});
+
+const Spinner = React.forwardRef<
+ SVGSVGElement,
+ React.SVGProps<SVGSVGElement> & VariantProps<typeof spinnerVariants>
+>(({ className, children, centered, size, ...props }, ref) => (
+ <Loader2Icon
+ ref={ref}
+ className={cn(spinnerVariants({ centered, size }), className)}
+ strokeWidth={1.5}
+ {...props}
+ />
+));
+Spinner.displayName = "Spinner";
+
+export { Spinner };
diff --git a/frontend/src/components/ui/command.tsx b/frontend/src/components/ui/command.tsx
index 2dd0b19e04..e429117742 100644
--- a/frontend/src/components/ui/command.tsx
+++ b/frontend/src/components/ui/command.tsx
@@ -131,7 +131,7 @@ const CommandItem = React.forwardRef<
>(({ className, variant, inset, ...props }, ref) => (
<CommandPrimitive.Item
ref={ref}
- className={menuItemVariants({ className, variant, inset })}
+ className={cn(menuItemVariants({ variant, inset }), className)}
{...props}
/>
));
diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.ts
index 88044ea466..41d6abd04f 100644
--- a/frontend/src/core/cells/__tests__/cells.test.ts
+++ b/frontend/src/core/cells/__tests__/cells.test.ts
@@ -65,6 +65,27 @@ describe("cell reducer", () => {
`);
});
+ it("can add a cell to the end with code", () => {
+ actions.createNewCell({
+ cellId: "__end__",
+ code: "import numpy as np",
+ before: false,
+ });
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ key: 0
+ code: ''
+
+ key: 1
+ code: 'import numpy as np'"
+ `);
+
+ // Cell should be added to the end and edited
+ expect(cells[1].code).toBe("import numpy as np");
+ expect(cells[1].edited).toBe(true);
+ expect(cells[1].lastCodeRun).toBe(null);
+ });
+
it("can add a cell before another cell", () => {
actions.createNewCell({
cellId: firstCellId,
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index 8ceca9481d..f83c7ab7cd 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -119,9 +119,15 @@ function initialNotebookState(): NotebookState {
* Actions and reducer for the notebook state.
*/
const { reducer, createActions } = createReducer(initialNotebookState, {
- createNewCell: (state, action: { cellId: CellId; before: boolean }) => {
- const { cellId, before } = action;
- const index = state.cellIds.indexOf(cellId);
+ createNewCell: (
+ state,
+ action: { cellId: CellId | "__end__"; before: boolean; code?: string },
+ ) => {
+ const { cellId, before, code } = action;
+ const index =
+ cellId === "__end__"
+ ? state.cellIds.length - 1
+ : state.cellIds.indexOf(cellId);
const insertionIndex = before ? index : index + 1;
const newCellId = CellId.create();
@@ -130,7 +136,11 @@ const { reducer, createActions } = createReducer(initialNotebookState, {
cellIds: arrayInsert(state.cellIds, insertionIndex, newCellId),
cellData: {
...state.cellData,
- [newCellId]: createCell({ id: newCellId }),
+ [newCellId]: createCell({
+ id: newCellId,
+ code,
+ edited: Boolean(code),
+ }),
},
cellRuntime: {
...state.cellRuntime,
diff --git a/frontend/src/core/constants.ts b/frontend/src/core/constants.ts
index d949a23684..2df7d49d4a 100644
--- a/frontend/src/core/constants.ts
+++ b/frontend/src/core/constants.ts
@@ -1,4 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
export const Constants = {
+ githubPage: "https://github.com/marimo-team/marimo",
issuesPage: "https://github.com/marimo-team/marimo/issues",
};
diff --git a/frontend/src/core/network/api.ts b/frontend/src/core/network/api.ts
index 14db004a8d..80193c6ad2 100644
--- a/frontend/src/core/network/api.ts
+++ b/frontend/src/core/network/api.ts
@@ -49,6 +49,39 @@ export const API = {
throw error;
});
},
+ get<RESP = null>(
+ url: string,
+ opts: {
+ headers?: Record<string, string>;
+ baseUrl?: string;
+ } = {},
+ ): Promise<RESP> {
+ const baseUrl = opts.baseUrl ?? document.baseURI;
+ const fullUrl = `${baseUrl}api${url}`;
+ return fetch(fullUrl, {
+ method: "GET",
+ headers: {
+ ...API.headers(),
+ ...opts.headers,
+ },
+ })
+ .then((response) => {
+ if (!response.ok) {
+ throw new Error(response.statusText);
+ } else if (
+ response.headers.get("Content-Type")?.startsWith("application/json")
+ ) {
+ return response.json() as RESP;
+ } else {
+ return null as RESP;
+ }
+ })
+ .catch((error) => {
+ // Catch and rethrow
+ Logger.error(`Error requesting ${fullUrl}`, error);
+ throw error;
+ });
+ },
headers() {
return {
"Marimo-Session-Id": getSessionId(),
diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.ts
index a3123b15b2..fc8632c089 100644
--- a/frontend/src/core/network/requests-network.ts
+++ b/frontend/src/core/network/requests-network.ts
@@ -27,6 +27,7 @@ import {
FileUpdateRequest,
FileDetailsResponse,
FileMoveRequest,
+ SnippetsResponse,
} from "./types";
import { invariant } from "@/utils/invariant";
@@ -144,6 +145,9 @@ export function createNetworkRequests(): EditRequests & RunRequests {
readCode: () => {
return API.post<{}, { contents: string }>("/kernel/read_code", {});
},
+ readSnippets: () => {
+ return API.get<SnippetsResponse>("/documentation/snippets", {});
+ },
openFile: async (request) => {
await API.post<{ path: string }>("/kernel/open", request);
await sendRestart();
diff --git a/frontend/src/core/network/requests-static.ts b/frontend/src/core/network/requests-static.ts
index 73d57089d9..8140ed030f 100644
--- a/frontend/src/core/network/requests-static.ts
+++ b/frontend/src/core/network/requests-static.ts
@@ -50,6 +50,7 @@ export function createStaticRequests(): EditRequests & RunRequests {
saveCellConfig: throwNotInEditMode,
sendStdin: throwNotInEditMode,
readCode: throwNotInEditMode,
+ readSnippets: throwNotInEditMode,
openFile: throwNotInEditMode,
sendListFiles: throwNotInEditMode,
sendCreateFileOrFolder: throwNotInEditMode,
diff --git a/frontend/src/core/network/requests-toasting.ts b/frontend/src/core/network/requests-toasting.ts
index bb6cde08d6..0290b27df1 100644
--- a/frontend/src/core/network/requests-toasting.ts
+++ b/frontend/src/core/network/requests-toasting.ts
@@ -26,6 +26,7 @@ export function createErrorToastingRequests(
saveCellConfig: "Failed to save cell config",
sendStdin: "Failed to send stdin",
readCode: "Failed to read code",
+ readSnippets: "Failed to fetch snippets",
openFile: "Failed to open file",
sendListFiles: "Failed to list files",
sendCreateFileOrFolder: "Failed to create file or folder",
diff --git a/frontend/src/core/network/requests.ts b/frontend/src/core/network/requests.ts
index ec027fd0ef..cfaa00606a 100644
--- a/frontend/src/core/network/requests.ts
+++ b/frontend/src/core/network/requests.ts
@@ -35,6 +35,7 @@ export const {
sendFunctionRequest,
sendInstallMissingPackages,
readCode,
+ readSnippets,
openFile,
sendListFiles,
sendCreateFileOrFolder,
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index 92e7c5fe21..6a24d2eab7 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -157,6 +157,19 @@ export interface FileDetailsResponse {
contents: string | undefined;
}
+export interface Snippet {
+ title: string;
+ sections: Array<{
+ id: string;
+ html?: string;
+ code?: string;
+ }>;
+}
+
+export interface SnippetsResponse {
+ snippets: Snippet[];
+}
+
/**
* Requests sent to the BE during run/edit mode.
*/
@@ -187,6 +200,7 @@ export interface EditRequests {
request: SendInstallMissingPackages,
) => Promise<null>;
readCode: () => Promise<{ contents: string }>;
+ readSnippets: () => Promise<SnippetsResponse>;
openFile: (request: { path: string }) => Promise<null>;
// File explorer requests
sendListFiles: (request: FileListRequest) => Promise<FileListResponse>;
diff --git a/frontend/src/core/pyodide/bridge.ts b/frontend/src/core/pyodide/bridge.ts
index 9d22ccaeef..326b3a3782 100644
--- a/frontend/src/core/pyodide/bridge.ts
+++ b/frontend/src/core/pyodide/bridge.ts
@@ -24,6 +24,7 @@ import {
SendFunctionRequest,
SendInstallMissingPackages,
SendStdin,
+ SnippetsResponse,
ValueUpdate,
} from "../network/types";
import { IReconnectingWebSocket } from "../websocket/types";
@@ -258,6 +259,14 @@ export class PyodideBridge implements RunRequests, EditRequests {
return response as { contents: string };
};
+ readSnippets = async (): Promise<SnippetsResponse> => {
+ const response = await this.rpc.proxy.request.bridge({
+ functionName: "read_snippets",
+ payload: undefined,
+ });
+ return response as SnippetsResponse;
+ };
+
openFile = async (request: { path: string }): Promise<null> => {
const url = createShareableLink({
code: null,
diff --git a/frontend/src/core/pyodide/worker/types.ts b/frontend/src/core/pyodide/worker/types.ts
index a70410c1e1..b165385bf7 100644
--- a/frontend/src/core/pyodide/worker/types.ts
+++ b/frontend/src/core/pyodide/worker/types.ts
@@ -14,6 +14,7 @@ import type {
FormatResponse,
SaveAppConfigRequest,
SaveKernelRequest,
+ SnippetsResponse,
} from "../../network/types";
export interface WasmController {
@@ -42,6 +43,7 @@ export interface RawBridge {
put_input(input: string): Promise<string>;
code_complete(request: CodeCompletionRequest): Promise<string>;
read_code(): Promise<{ contents: string }>;
+ read_snippets(): Promise<SnippetsResponse>;
format(request: FormatRequest): Promise<FormatResponse>;
save(request: SaveKernelRequest): Promise<string>;
save_app_config(request: SaveAppConfigRequest): Promise<string>;
diff --git a/frontend/src/plugins/impl/common/error-banner.tsx b/frontend/src/plugins/impl/common/error-banner.tsx
index 586826cfc5..9a7221f91f 100644
--- a/frontend/src/plugins/impl/common/error-banner.tsx
+++ b/frontend/src/plugins/impl/common/error-banner.tsx
@@ -30,6 +30,7 @@ export const ErrorBanner = ({
return (
<>
<Banner
+ kind="danger"
className={className}
clickable={true}
onClick={() => setOpen(true)}
diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.py
index d2e1e523f9..fe1d2de292 100644
--- a/marimo/_pyodide/pyodide_session.py
+++ b/marimo/_pyodide/pyodide_session.py
@@ -56,6 +56,7 @@ from marimo._server.models.models import (
SaveAppConfigurationRequest,
SaveRequest,
)
+from marimo._snippets.snippets import read_snippets
from marimo._utils.formatter import BlackFormatter
from marimo._utils.parse_dataclass import parse_raw
@@ -214,6 +215,10 @@ class PyodideBridge:
response = ReadCodeResponse(contents=contents)
return json.dumps(deep_to_camel_case(dataclasses.asdict(response)))
+ async def read_snippets(self) -> str:
+ snippets = await read_snippets()
+ return json.dumps(deep_to_camel_case(dataclasses.asdict(snippets)))
+
def format(self, request: str) -> str:
parsed = parse_raw(json.loads(request), FormatRequest)
formatter = BlackFormatter(line_length=parsed.line_length)
diff --git a/marimo/_server/api/endpoints/assets.py b/marimo/_server/api/endpoints/assets.py
index 5877e6ae93..4d957f9f55 100644
--- a/marimo/_server/api/endpoints/assets.py
+++ b/marimo/_server/api/endpoints/assets.py
@@ -17,7 +17,7 @@ from marimo._server.api.deps import AppState
from marimo._server.api.utils import parse_title
from marimo._server.model import SessionMode
from marimo._server.router import APIRouter
-from marimo._server.utils import import_files
+from marimo._utils.paths import import_files
LOGGER = _loggers.marimo_logger()
diff --git a/marimo/_server/api/endpoints/documentation.py b/marimo/_server/api/endpoints/documentation.py
new file mode 100644
index 0000000000..8b30431dc3
--- /dev/null
+++ b/marimo/_server/api/endpoints/documentation.py
@@ -0,0 +1,29 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from functools import lru_cache
+
+from starlette.requests import Request
+
+from marimo import _loggers
+from marimo._server.router import APIRouter
+from marimo._snippets.snippets import Snippets, read_snippets
+
+LOGGER = _loggers.marimo_logger()
+
+# Router for documentation
+router = APIRouter()
+
+
+# Cache the snippets
+@lru_cache(1)
+async def _read_snippets_once() -> Snippets:
+ return await read_snippets()
+
+
[email protected]("/snippets")
+async def load_snippets(
+ request: Request,
+) -> Snippets:
+ del request
+ return await _read_snippets_once()
diff --git a/marimo/_server/api/router.py b/marimo/_server/api/router.py
index f073dad451..c0f783d455 100644
--- a/marimo/_server/api/router.py
+++ b/marimo/_server/api/router.py
@@ -8,9 +8,14 @@ from starlette.routing import BaseRoute
from marimo._server.api.endpoints.ai import router as ai_router
from marimo._server.api.endpoints.assets import router as assets_router
from marimo._server.api.endpoints.config import router as config_router
+from marimo._server.api.endpoints.documentation import (
+ router as documentation_router,
+)
from marimo._server.api.endpoints.editing import router as editing_router
from marimo._server.api.endpoints.execution import router as execution_router
-from marimo._server.api.endpoints.file_explorer import router as file_explorer
+from marimo._server.api.endpoints.file_explorer import (
+ router as file_explorer_router,
+)
from marimo._server.api.endpoints.files import router as files_router
from marimo._server.api.endpoints.health import router as health_router
from marimo._server.api.endpoints.ws import router as ws_router
@@ -31,7 +36,10 @@ def build_routes(base_url: str = "") -> List[BaseRoute]:
)
app_router.include_router(files_router, prefix="/api/kernel", name="files")
app_router.include_router(
- file_explorer, prefix="/api/files", name="file_explorer"
+ file_explorer_router, prefix="/api/files", name="file_explorer"
+ )
+ app_router.include_router(
+ documentation_router, prefix="/api/documentation", name="documentation"
)
app_router.include_router(ai_router, prefix="/api/ai", name="ai")
app_router.include_router(health_router, name="health")
diff --git a/marimo/_server/router.py b/marimo/_server/router.py
index 6340a3e1d4..aea9728a56 100644
--- a/marimo/_server/router.py
+++ b/marimo/_server/router.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import dataclasses
import json
+from asyncio import iscoroutine
from dataclasses import dataclass
from typing import Any, Callable, Optional, TypeVar
@@ -76,9 +77,27 @@ class APIRouter(Router):
"""Get method."""
def decorator(func: DecoratedCallable) -> DecoratedCallable:
+ async def wrapper_func(request: Request) -> Response:
+ response = func(request=request)
+ if iscoroutine(response):
+ response = await response
+ if isinstance(response, FileResponse):
+ return response
+ if isinstance(response, StreamingResponse):
+ return response
+
+ if dataclasses.is_dataclass(response):
+ return JSONResponse(
+ content=deep_to_camel_case(
+ dataclasses.asdict(response)
+ )
+ )
+
+ return response # type: ignore[no-any-return]
+
self.add_route(
path=self.prefix + path,
- endpoint=func,
+ endpoint=wrapper_func,
methods=["GET"],
include_in_schema=include_in_schema,
)
diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.py
index 947476710a..d9ccaa20f0 100644
--- a/marimo/_server/sessions.py
+++ b/marimo/_server/sessions.py
@@ -50,10 +50,11 @@ from marimo._server.model import (
from marimo._server.models.models import InstantiateRequest
from marimo._server.session.session_view import SessionView
from marimo._server.types import QueueType
-from marimo._server.utils import import_files, print_tabbed
+from marimo._server.utils import print_tabbed
from marimo._utils.disposable import Disposable
from marimo._utils.distributor import Distributor
from marimo._utils.file_watcher import FileWatcher
+from marimo._utils.paths import import_files
from marimo._utils.repr import format_repr
from marimo._utils.typed_connection import TypedConnection
diff --git a/marimo/_server/start.py b/marimo/_server/start.py
index d19db278a4..b8050a2383 100644
--- a/marimo/_server/start.py
+++ b/marimo/_server/start.py
@@ -14,10 +14,10 @@ from marimo._server.sessions import (
)
from marimo._server.utils import (
find_free_port,
- import_files,
initialize_asyncio,
)
from marimo._server.uvicorn_utils import initialize_signals
+from marimo._utils.paths import import_files
DEFAULT_PORT = 2718
diff --git a/marimo/_server/utils.py b/marimo/_server/utils.py
index 8eeb1174a3..07ef85e4ee 100644
--- a/marimo/_server/utils.py
+++ b/marimo/_server/utils.py
@@ -3,7 +3,6 @@ import asyncio
import os
import pathlib
import sys
-from typing import Any
from marimo import _loggers
@@ -44,15 +43,6 @@ def find_free_port(port: int, attempts: int = 100) -> int:
return find_free_port(port + 1, attempts - 1)
-def import_files(filename: str) -> Any:
- if sys.version_info < (3, 9):
- from importlib_resources import files as importlib_files
- else:
- from importlib.resources import files as importlib_files
-
- return importlib_files(filename)
-
-
def initialize_mimetypes() -> None:
import mimetypes
diff --git a/marimo/_snippets/data/altair-0.py b/marimo/_snippets/data/altair-0.py
new file mode 100644
index 0000000000..166d4f88fb
--- /dev/null
+++ b/marimo/_snippets/data/altair-0.py
@@ -0,0 +1,46 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.9"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Visualization: Interactive Scatter Plot in Altair
+
+ Altair lets you easily create an interactive scatter plot from data stored in a Pandas dataframe.
+ """
+ )
+ return
+
+
+def __():
+ # load an example dataset
+ from vega_datasets import data
+
+ cars = data.cars()
+
+ # plot the dataset, referencing dataframe column names
+ import altair as alt
+
+ (
+ alt.Chart(cars)
+ .mark_point()
+ .encode(x="Horsepower", y="Miles_per_Gallon", color="Origin")
+ .interactive()
+ )
+ return alt, cars, data
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/altair-1.py b/marimo/_snippets/data/altair-1.py
new file mode 100644
index 0000000000..394b5ce167
--- /dev/null
+++ b/marimo/_snippets/data/altair-1.py
@@ -0,0 +1,43 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.9"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Visualization: Bar Plot in Altair
+
+ This shows a simple bar plot in Altair, showing the mean miles per gallon as a function of origin for a number of car models:
+ """
+ )
+ return
+
+
+def __():
+ # load an example dataset
+ from vega_datasets import data
+
+ cars = data.cars()
+
+ # plot the dataset, referencing dataframe column names
+ import altair as alt
+
+ alt.Chart(cars).mark_bar().encode(
+ x="mean(Miles_per_Gallon)", y="Origin", color="Origin"
+ )
+ return alt, cars, data
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/altair-2.py b/marimo/_snippets/data/altair-2.py
new file mode 100644
index 0000000000..22ea96d802
--- /dev/null
+++ b/marimo/_snippets/data/altair-2.py
@@ -0,0 +1,45 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.9"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Visualization: Histogram in Altair
+
+ Altair provides a variety of aggregation operations in order to build custom histograms. Here is a simple example
+
+ """
+ )
+ return
+
+
+def __():
+ # load an example dataset
+ from vega_datasets import data
+
+ cars = data.cars()
+
+ # plot the dataset, referencing dataframe column names
+ import altair as alt
+
+ alt.Chart(cars).mark_bar().encode(
+ x=alt.X("Miles_per_Gallon", bin=True),
+ y="count()",
+ )
+ return alt, cars, data
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/altair-3.py b/marimo/_snippets/data/altair-3.py
new file mode 100644
index 0000000000..a38febafdc
--- /dev/null
+++ b/marimo/_snippets/data/altair-3.py
@@ -0,0 +1,44 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.9"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Visualization: Stacked Histogram in Altair
+
+ If you take a standard histogram and encode another field with color, the result will be a stacked histogram:
+
+ """
+ )
+ return
+
+
+def __():
+ # load an example dataset
+ from vega_datasets import data
+
+ cars = data.cars()
+
+ # plot the dataset, referencing dataframe column names
+ import altair as alt
+
+ alt.Chart(cars).mark_bar().encode(
+ x=alt.X("Miles_per_Gallon", bin=True), y="count()", color="Origin"
+ )
+ return alt, cars, data
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/altair-4.py b/marimo/_snippets/data/altair-4.py
new file mode 100644
index 0000000000..3b59461d68
--- /dev/null
+++ b/marimo/_snippets/data/altair-4.py
@@ -0,0 +1,55 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.9"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Visualization: Scatter Plot with Rolling Mean in Altair
+
+ This shows a scatter chart of miles per gallon as a function of year, with lines indicating the mean values for each country within the given year.
+ """
+ )
+ return
+
+
+def __():
+ # load an example dataset
+ from vega_datasets import data
+
+ cars = data.cars()
+
+ import altair as alt
+
+ points = (
+ alt.Chart(cars)
+ .mark_point()
+ .encode(x="Year:T", y="Miles_per_Gallon", color="Origin")
+ .properties(width=800)
+ )
+
+ lines = (
+ alt.Chart(cars)
+ .mark_line()
+ .encode(x="Year:T", y="mean(Miles_per_Gallon)", color="Origin")
+ .properties(width=800)
+ .interactive(bind_y=False)
+ )
+
+ points + lines
+ return alt, cars, data, lines, points
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/altair-5.py b/marimo/_snippets/data/altair-5.py
new file mode 100644
index 0000000000..28c628b2e4
--- /dev/null
+++ b/marimo/_snippets/data/altair-5.py
@@ -0,0 +1,46 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.9"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Visualization: Interactive Brushing in Altair
+
+ With a few extra lines of code on top of a standard scatter plot, you can add selection behavior to your scatter plot. This lets you click and drag to select points.
+ """
+ )
+ return
+
+
+def __():
+ # load an example dataset
+ from vega_datasets import data
+
+ cars = data.cars()
+
+ import altair as alt
+
+ interval = alt.selection_interval()
+
+ alt.Chart(cars).mark_point().encode(
+ x="Horsepower",
+ y="Miles_per_Gallon",
+ color=alt.condition(interval, "Origin", alt.value("lightgray")),
+ ).add_params(interval)
+ return alt, cars, data, interval
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/altair-6.py b/marimo/_snippets/data/altair-6.py
new file mode 100644
index 0000000000..abade33d62
--- /dev/null
+++ b/marimo/_snippets/data/altair-6.py
@@ -0,0 +1,52 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.9"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Visualization: Linked Brushing in Altair
+
+ If you apply the same selection to multiple panels of an Altair chart, the selections will be linked:
+ """
+ )
+ return
+
+
+def __():
+ # load an example dataset
+ from vega_datasets import data
+
+ cars = data.cars()
+
+ import altair as alt
+
+ interval = alt.selection_interval()
+
+ base = (
+ alt.Chart(cars)
+ .mark_point()
+ .encode(
+ y="Miles_per_Gallon",
+ color=alt.condition(interval, "Origin", alt.value("lightgray")),
+ )
+ .add_params(interval)
+ )
+
+ base.encode(x="Acceleration") | base.encode(x="Horsepower")
+ return alt, base, cars, data, interval
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/altair-7.py b/marimo/_snippets/data/altair-7.py
new file mode 100644
index 0000000000..c7c2f1c64e
--- /dev/null
+++ b/marimo/_snippets/data/altair-7.py
@@ -0,0 +1,60 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.9"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Visualization: Linked Scatter-Plot and Histogram in Altair
+
+ Altair selections can be used for a variety of things. This example shows a scatter plot and a histogram with selections over both that allow exploring the relationships between points
+ """
+ )
+ return
+
+
+def __():
+ # load an example dataset
+ from vega_datasets import data
+
+ cars = data.cars()
+
+ import altair as alt
+
+ interval = alt.selection_interval()
+
+ points = (
+ alt.Chart(cars)
+ .mark_point()
+ .encode(
+ x="Horsepower",
+ y="Miles_per_Gallon",
+ color=alt.condition(interval, "Origin", alt.value("lightgray")),
+ )
+ .add_params(interval)
+ )
+
+ histogram = (
+ alt.Chart(cars)
+ .mark_bar()
+ .encode(x="count()", y="Origin", color="Origin")
+ .transform_filter(interval)
+ )
+
+ points & histogram
+ return alt, cars, data, histogram, interval, points
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/altair-8.py b/marimo/_snippets/data/altair-8.py
new file mode 100644
index 0000000000..86e1e3e83c
--- /dev/null
+++ b/marimo/_snippets/data/altair-8.py
@@ -0,0 +1,41 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.9"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Visualization: Time Series Line Plot in Altair
+
+ Altair handles temporal types natively by using the ``:T`` type marker. An example is in this plot of stock prices over time
+ """
+ )
+ return
+
+
+def __():
+ from vega_datasets import data
+
+ stocks = data.stocks()
+
+ import altair as alt
+
+ alt.Chart(stocks).mark_line().encode(
+ x="date:T", y="price", color="symbol"
+ ).interactive(bind_y=False)
+ return alt, data, stocks
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/pandas-0.py b/marimo/_snippets/data/pandas-0.py
new file mode 100644
index 0000000000..0a9d02512b
--- /dev/null
+++ b/marimo/_snippets/data/pandas-0.py
@@ -0,0 +1,42 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.9"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Pandas DataFrame: Create from lists of values
+ """
+ )
+ return
+
+
+def __():
+ import pandas as pd
+
+ last_names = ["Connor", "Connor", "Reese"]
+ first_names = ["Sarah", "John", "Kyle"]
+ df = pd.DataFrame(
+ {
+ "first_name": first_names,
+ "last_name": last_names,
+ }
+ )
+ df
+ return df, first_names, last_names, pd
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/pandas-1.py b/marimo/_snippets/data/pandas-1.py
new file mode 100644
index 0000000000..814bc83c16
--- /dev/null
+++ b/marimo/_snippets/data/pandas-1.py
@@ -0,0 +1,48 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.9"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Pandas DataFrame: Rename multiple Columns
+ """
+ )
+ return
+
+
+def __():
+ import pandas as pd
+
+ df = pd.DataFrame(
+ {
+ "Year": [2016, 2015, 2014, 2013, 2012],
+ "Top Animal": ["Giant panda", "Chicken", "Pig", "Turkey", "Dog"],
+ }
+ )
+
+ df.rename(
+ columns={
+ "Year": "Calendar Year",
+ "Top Animal": "Favorite Animal",
+ },
+ inplace=True,
+ )
+ df
+ return df, pd
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/pandas-10.py b/marimo/_snippets/data/pandas-10.py
new file mode 100644
index 0000000000..44456860af
--- /dev/null
+++ b/marimo/_snippets/data/pandas-10.py
@@ -0,0 +1,58 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.9"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Pandas DataFrame: Explode a column containing dictionary values into multiple columns
+ """
+ )
+ return
+
+
+def __(mo):
+ mo.md(
+ r"""
+ This code transforms or splits the dictionary column into many columns.
+
+ E.g. The output DataFrame of this cell will have columns named [`date, letter, fruit, weather`].
+ """
+ )
+ return
+
+
+def __():
+ import pandas as pd
+
+ df = pd.DataFrame(
+ {
+ "date": ["2022-09-14", "2022-09-15", "2022-09-16"],
+ "letter": ["A", "B", "C"],
+ "dict": [
+ {"fruit": "apple", "weather": "aces"},
+ {"fruit": "banana", "weather": "bad"},
+ {"fruit": "cantaloupe", "weather": "cloudy"},
+ ],
+ }
+ )
+
+ pd.concat([df.drop(["dict"], axis=1), df["dict"].apply(pd.Series)], axis=1)
+ return df, pd
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/pandas-11.py b/marimo/_snippets/data/pandas-11.py
new file mode 100644
index 0000000000..2326ad30ee
--- /dev/null
+++ b/marimo/_snippets/data/pandas-11.py
@@ -0,0 +1,40 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.8"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Pandas DataFrame: Extract values using regexp (regular expression)
+ """
+ )
+ return
+
+
+def __():
+ import pandas as pd
+
+ df = pd.DataFrame(
+ {
+ "request": ["GET /index.html?baz=3", "GET /foo.html?bar=1"],
+ }
+ )
+
+ df["request"].str.extract("GET /([^?]+)\?", expand=True)
+ return df, pd
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/pandas-12.py b/marimo/_snippets/data/pandas-12.py
new file mode 100644
index 0000000000..b59d6a64f7
--- /dev/null
+++ b/marimo/_snippets/data/pandas-12.py
@@ -0,0 +1,44 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.8"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Pandas Timestamp: Convert string to Timestamp, using date only
+ """
+ )
+ return
+
+
+def __(mo):
+ mo.md(
+ r"""
+ I.e. Midnight on the given date.
+ """
+ )
+ return
+
+
+def __():
+ import pandas as pd
+
+ pd.Timestamp("9/27/22").tz_localize("US/Pacific")
+ return (pd,)
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/pandas-13.py b/marimo/_snippets/data/pandas-13.py
new file mode 100644
index 0000000000..9bcb83a7e2
--- /dev/null
+++ b/marimo/_snippets/data/pandas-13.py
@@ -0,0 +1,34 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.8"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Pandas Timestamp: Convert string to Timestamp
+ """
+ )
+ return
+
+
+def __():
+ import pandas as pd
+
+ pd.Timestamp("9/27/22 06:59").tz_localize("US/Pacific")
+ return (pd,)
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/pandas-14.py b/marimo/_snippets/data/pandas-14.py
new file mode 100644
index 0000000000..a00ef2f96c
--- /dev/null
+++ b/marimo/_snippets/data/pandas-14.py
@@ -0,0 +1,46 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.8"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Pandas: Create a TimeDelta using `unit`
+ """
+ )
+ return
+
+
+def __(mo):
+ mo.md(
+ r"""
+ From an integer.
+ `unit` is a string, defaulting to `ns`. Possible values:
+
+ """
+ )
+ return
+
+
+def __():
+ import pandas as pd
+
+ pd.to_timedelta(1, unit="h")
+ return (pd,)
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/pandas-15.py b/marimo/_snippets/data/pandas-15.py
new file mode 100644
index 0000000000..d68e14100c
--- /dev/null
+++ b/marimo/_snippets/data/pandas-15.py
@@ -0,0 +1,44 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.8"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Pandas: Create a TimeDelta using available kwargs
+ """
+ )
+ return
+
+
+def __(mo):
+ mo.md(
+ r"""
+ Example keyworded args: {days, seconds, microseconds, milliseconds, minutes, hours, weeks}
+ """
+ )
+ return
+
+
+def __():
+ import pandas as pd
+
+ pd.Timedelta(days=2)
+ return (pd,)
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/pandas-16.py b/marimo/_snippets/data/pandas-16.py
new file mode 100644
index 0000000000..326db98870
--- /dev/null
+++ b/marimo/_snippets/data/pandas-16.py
@@ -0,0 +1,34 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.8"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Pandas: Create a TimeDelta from a string
+ """
+ )
+ return
+
+
+def __():
+ import pandas as pd
+
+ pd.Timedelta("2 days 2 hours 15 minutes 30 seconds")
+ return (pd,)
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/pandas-17.py b/marimo/_snippets/data/pandas-17.py
new file mode 100644
index 0000000000..43972f2669
--- /dev/null
+++ b/marimo/_snippets/data/pandas-17.py
@@ -0,0 +1,41 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.8"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Pandas: Replace NaN values in a Column
+ """
+ )
+ return
+
+
+def __():
+ import numpy as np
+ import pandas as pd
+
+ df = pd.DataFrame(
+ {
+ "dogs": [5, 10, np.nan, 7],
+ }
+ )
+
+ df["dogs"].replace(np.nan, 0, regex=True)
+ return df, np, pd
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/pandas-18.py b/marimo/_snippets/data/pandas-18.py
new file mode 100644
index 0000000000..916df56f19
--- /dev/null
+++ b/marimo/_snippets/data/pandas-18.py
@@ -0,0 +1,42 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.8"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Pandas DataFrame: Drop duplicate rows
+ """
+ )
+ return
+
+
+def __():
+ import pandas as pd
+
+ df = pd.DataFrame(
+ {
+ "first_name": ["Sarah", "John", "Kyle", "Joe"],
+ "last_name": ["Connor", "Connor", "Reese", "Bonnot"],
+ }
+ )
+ df.set_index("last_name", inplace=True)
+
+ df.loc[~df.index.duplicated(), :]
+ return df, pd
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/pandas-19.py b/marimo/_snippets/data/pandas-19.py
new file mode 100644
index 0000000000..d708739af4
--- /dev/null
+++ b/marimo/_snippets/data/pandas-19.py
@@ -0,0 +1,41 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.8"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Pandas DataFrame: Ignore one Column
+ """
+ )
+ return
+
+
+def __():
+ import pandas as pd
+
+ df = pd.DataFrame(
+ {
+ "first_name": ["Sarah", "John", "Kyle", "Joe"],
+ "last_name": ["Connor", "Connor", "Reese", "Bonnot"],
+ }
+ )
+
+ df.loc[:, df.columns != "last_name"]
+ return df, pd
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/pandas-2.py b/marimo/_snippets/data/pandas-2.py
new file mode 100644
index 0000000000..a5c67d551d
--- /dev/null
+++ b/marimo/_snippets/data/pandas-2.py
@@ -0,0 +1,41 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.9"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Pandas DataFrame: Query by regexp (regular expression)
+ """
+ )
+ return
+
+
+def __():
+ import pandas as pd
+
+ df = pd.DataFrame(
+ {
+ "first_name": ["Sarah", "John", "Kyle", "Joe"],
+ "last_name": ["Connor", "Connor", "Reese", "Bonnot"],
+ }
+ )
+
+ df[df.last_name.str.match(".*onno.*")]
+ return df, pd
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/pandas-20.py b/marimo/_snippets/data/pandas-20.py
new file mode 100644
index 0000000000..6b3bad9f41
--- /dev/null
+++ b/marimo/_snippets/data/pandas-20.py
@@ -0,0 +1,50 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.8"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Pandas DataFrame: Intersect Indexes
+ """
+ )
+ return
+
+
+def __():
+ import pandas as pd
+
+ terminator_df = pd.DataFrame(
+ {
+ "first_name": ["Sarah", "John", "Kyle"],
+ "last_name": ["Connor", "Connor", "Reese"],
+ }
+ )
+ terminator_df.set_index("first_name", inplace=True)
+
+ buckaroo_df = pd.DataFrame(
+ {
+ "first_name": ["John", "John", "Buckaroo"],
+ "last_name": ["Parker", "Whorfin", "Banzai"],
+ }
+ )
+ buckaroo_df.set_index("first_name", inplace=True)
+
+ terminator_df.index.intersection(buckaroo_df.index).shape
+ return buckaroo_df, pd, terminator_df
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/pandas-21.py b/marimo/_snippets/data/pandas-21.py
new file mode 100644
index 0000000000..04b074d57b
--- /dev/null
+++ b/marimo/_snippets/data/pandas-21.py
@@ -0,0 +1,50 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.8"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Pandas DataFrame: Select all rows from A that are not in B, using the index
+ """
+ )
+ return
+
+
+def __():
+ import pandas as pd
+
+ terminator_df = pd.DataFrame(
+ {
+ "first_name": ["Sarah", "John", "Kyle"],
+ "last_name": ["Connor", "Connor", "Reese"],
+ }
+ )
+ terminator_df.set_index("first_name", inplace=True)
+
+ buckaroo_df = pd.DataFrame(
+ {
+ "first_name": ["John", "John", "Buckaroo"],
+ "last_name": ["Parker", "Whorfin", "Banzai"],
+ }
+ )
+ buckaroo_df.set_index("first_name", inplace=True)
+
+ terminator_df[~terminator_df.index.isin(buckaroo_df.index)]
+ return buckaroo_df, pd, terminator_df
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/pandas-22.py b/marimo/_snippets/data/pandas-22.py
new file mode 100644
index 0000000000..e98041db11
--- /dev/null
+++ b/marimo/_snippets/data/pandas-22.py
@@ -0,0 +1,52 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.8"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Pandas DataFrame: Select rows by an attribute of a column value
+ """
+ )
+ return
+
+
+def __(mo):
+ mo.md(
+ r"""
+ Use the Series `map()` method.
+ E.g. To filter by the length of a column values:
+ """
+ )
+ return
+
+
+def __():
+ import pandas as pd
+
+ df = pd.DataFrame(
+ {
+ "first_name": ["Sarah", "John", "Kyle"],
+ "last_name": ["Connor", "Connor", "Reese"],
+ }
+ )
+
+ df[df["last_name"].map(len) == 5]
+ return df, pd
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/pandas-23.py b/marimo/_snippets/data/pandas-23.py
new file mode 100644
index 0000000000..e554f23530
--- /dev/null
+++ b/marimo/_snippets/data/pandas-23.py
@@ -0,0 +1,41 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.8"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Pandas DataFrame: Sort the count of rows grouped on columns
+ """
+ )
+ return
+
+
+def __():
+ import pandas as pd
+
+ df = pd.DataFrame(
+ {
+ "first_name": ["Sarah", "John", "Kyle"],
+ "last_name": ["Connor", "Connor", "Reese"],
+ }
+ )
+
+ df.groupby(["last_name"]).size().sort_values(ascending=False)
+ return df, pd
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/pandas-24.py b/marimo/_snippets/data/pandas-24.py
new file mode 100644
index 0000000000..08d604157e
--- /dev/null
+++ b/marimo/_snippets/data/pandas-24.py
@@ -0,0 +1,61 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.8"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Pandas DataFrame: Reshape to have 1 row per value in a list column
+ """
+ )
+ return
+
+
+def __(mo):
+ mo.md(
+ r"""
+ Creates a new DataFrame that is a transformed version of the input. E.g.
+ * Input: df with a column named `msg_ids` that is a list of values (i.e. many per row, at least in some rows).
+ * Output: new_df which has 1 row per unique value found in any of the original `msg_ids` lists, with that value in a new column named `msg_id`.
+
+ """
+ )
+ return
+
+
+def __():
+ import pandas as pd
+
+ df = pd.DataFrame(
+ {
+ "date": ["9/1/22", "9/2/22", "9/3/22"],
+ "action": ["Add", "Update", "Delete"],
+ "msg_ids": [[1, 2, 3], [], [2, 3]],
+ }
+ )
+ df.set_index("date", inplace=True)
+
+ temp_series = df["msg_ids"].apply(pd.Series, 1).stack()
+ temp_series.index = temp_series.index.droplevel(-1)
+ temp_series.name = "msg_id"
+ new_df = temp_series.to_frame()
+ new_df.set_index("msg_id", inplace=True)
+ new_df.loc[~new_df.index.duplicated(), :] # Drop duplicates.
+ return df, new_df, pd, temp_series
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/pandas-25.py b/marimo/_snippets/data/pandas-25.py
new file mode 100644
index 0000000000..946066fc4f
--- /dev/null
+++ b/marimo/_snippets/data/pandas-25.py
@@ -0,0 +1,61 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.8"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Pandas: DataFrames: Group Timeseries by Frequency
+ """
+ )
+ return
+
+
+def __(mo):
+ mo.md(
+ r"""
+ You can group timestamped data into intervals of arbitrary duration using a Grouper object to specify groupby instructions. The `freq` parameter is a string that may contain an integer followed by an [offset alias](https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases). E.g. To see output for 2 minute long intervals:
+ """
+ )
+ return
+
+
+def __():
+ import pandas as pd
+
+ df = pd.DataFrame(
+ {
+ "time": [
+ "2022-09-01 00:00:01-07:00",
+ "2022-09-01 00:00:02-07:00",
+ "2022-09-01 00:01:00-07:00",
+ "2022-09-01 00:02:00-07:00",
+ "2022-09-01 00:03:00-07:00",
+ "2022-09-01 00:04:00-07:00",
+ "2022-09-01 00:05:00-07:00",
+ "2022-09-01 00:07:00-07:00",
+ ],
+ "requests": [1, 1, 1, 1, 1, 1, 1, 1],
+ }
+ )
+ df["time"] = pd.to_datetime(df.time)
+
+ df.groupby(pd.Grouper(key="time", freq="2min")).sum()
+ return df, pd
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/pandas-3.py b/marimo/_snippets/data/pandas-3.py
new file mode 100644
index 0000000000..247433d8f9
--- /dev/null
+++ b/marimo/_snippets/data/pandas-3.py
@@ -0,0 +1,52 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.9"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Pandas DataFrame: Query by variable value
+ """
+ )
+ return
+
+
+def __(mo):
+ mo.md(
+ r"""
+ Evaluate a variable as the value to find.
+ """
+ )
+ return
+
+
+def __():
+ import pandas as pd
+
+ df = pd.DataFrame(
+ {
+ "first_name": ["Sarah", "John", "Kyle"],
+ "last_name": ["Connor", "Connor", "Reese"],
+ }
+ )
+
+ foo = "Connor"
+ df.query("last_name == @foo")
+ return df, foo, pd
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/pandas-4.py b/marimo/_snippets/data/pandas-4.py
new file mode 100644
index 0000000000..c3faad6611
--- /dev/null
+++ b/marimo/_snippets/data/pandas-4.py
@@ -0,0 +1,54 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.9"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Pandas DataFrame: Query using variable value as a column name
+ """
+ )
+ return
+
+
+def __(mo):
+ mo.md(
+ r"""
+ Evaluate a variable, to use its value as the name of a column in a query.
+
+ E.g. Query for rows where `John` is the value in the column named `first_name`.
+ """
+ )
+ return
+
+
+def __():
+ import pandas as pd
+
+ df = pd.DataFrame(
+ data={
+ "first_name": ["Sarah", "John", "Kyle"],
+ "last_name": ["Connor", "Connor", "Reese"],
+ }
+ )
+
+ column_name = "first_name"
+ df.query(f"`{column_name}` == 'John'")
+ return column_name, df, pd
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/pandas-5.py b/marimo/_snippets/data/pandas-5.py
new file mode 100644
index 0000000000..4d1dbc70c4
--- /dev/null
+++ b/marimo/_snippets/data/pandas-5.py
@@ -0,0 +1,46 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.8"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Pandas DataFrame: Query by Timestamp above a value
+ """
+ )
+ return
+
+
+def __():
+ import pandas as pd
+
+ df = pd.DataFrame(
+ {
+ "time": [
+ "2022-09-14 00:52:00-07:00",
+ "2022-09-14 00:52:30-07:00",
+ "2022-09-14 01:52:30-07:00",
+ ],
+ "letter": ["A", "B", "C"],
+ }
+ )
+ df["time"] = pd.to_datetime(df.time)
+
+ df.query('time >= "2022-09-14 00:52:30-07:00"')
+ return df, pd
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/pandas-6.py b/marimo/_snippets/data/pandas-6.py
new file mode 100644
index 0000000000..057bee6f8c
--- /dev/null
+++ b/marimo/_snippets/data/pandas-6.py
@@ -0,0 +1,49 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.8"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Pandas DataFrame: Query for Timestamp between two values
+ """
+ )
+ return
+
+
+def __():
+ import pandas as pd
+
+ df = pd.DataFrame(
+ {
+ "time": [
+ "2022-09-14 00:52:00-07:00",
+ "2022-09-14 00:52:30-07:00",
+ "2022-09-14 01:52:30-07:00",
+ ],
+ "letter": ["A", "B", "C"],
+ }
+ )
+ df["time"] = pd.to_datetime(df.time)
+
+ begin_ts = "2022-09-14 00:52:00-07:00"
+ end_ts = "2022-09-14 00:54:00-07:00"
+
+ df.query("@begin_ts <= time < @end_ts")
+ return begin_ts, df, end_ts, pd
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/pandas-7.py b/marimo/_snippets/data/pandas-7.py
new file mode 100644
index 0000000000..3ae984efad
--- /dev/null
+++ b/marimo/_snippets/data/pandas-7.py
@@ -0,0 +1,47 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.8"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Pandas DataFrame: Filter by Timestamp in DatetimeIndex using `.loc[]`
+ """
+ )
+ return
+
+
+def __():
+ import pandas as pd
+
+ df = pd.DataFrame(
+ {
+ "time": [
+ "2022-09-14 00:52:00-07:00",
+ "2022-09-14 00:52:30-07:00",
+ "2022-09-14 01:52:30-07:00",
+ ],
+ "letter": ["A", "B", "C"],
+ }
+ )
+ df["time"] = pd.to_datetime(df.time)
+ df.set_index("time", inplace=True)
+
+ df.loc["2022-09-14":"2022-09-14 00:53"]
+ return df, pd
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/pandas-8.py b/marimo/_snippets/data/pandas-8.py
new file mode 100644
index 0000000000..755c17e8d3
--- /dev/null
+++ b/marimo/_snippets/data/pandas-8.py
@@ -0,0 +1,54 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.8"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Pandas DataFrame: Filter by Timestamp using TimeDelta string
+ """
+ )
+ return
+
+
+def __():
+ import pandas as pd
+
+ df = pd.DataFrame(
+ {
+ "time": [
+ "2022-09-14 00:52:00-07:00",
+ "2022-09-14 00:52:30-07:00",
+ "2022-09-14 01:52:30-07:00",
+ ],
+ "letter": ["A", "B", "C"],
+ }
+ )
+ df["time"] = pd.to_datetime(df.time)
+
+ def rows_in_time_range(df, time_column, start_ts_str, timedelta_str):
+ # Return rows from df, where start_ts < time_column <= start_ts + delta.
+ # start_ts_str can be a date '2022-09-01' or a time '2022-09-14 00:52:00-07:00'
+ # timedelta_str examples: '2 minutes' '2 days 2 hours 15 minutes 30 seconds'
+ start_ts = pd.Timestamp(start_ts_str).tz_localize("US/Pacific")
+ end_ts = start_ts + pd.to_timedelta(timedelta_str)
+ return df.query("@start_ts <= {0} < @end_ts".format(time_column))
+
+ rows_in_time_range(df, "time", "2022-09-14 00:00", "52 minutes 31 seconds")
+ return df, pd, rows_in_time_range
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/data/pandas-9.py b/marimo/_snippets/data/pandas-9.py
new file mode 100644
index 0000000000..c6ad91a89f
--- /dev/null
+++ b/marimo/_snippets/data/pandas-9.py
@@ -0,0 +1,46 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.3.8"
+app = marimo.App()
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Pandas: Describe Timestamp values in a column
+ """
+ )
+ return
+
+
+def __():
+ import pandas as pd
+
+ df = pd.DataFrame(
+ {
+ "time": [
+ "2022-09-14 00:52:00-07:00",
+ "2022-09-14 00:52:30-07:00",
+ "2022-09-14 01:52:30-07:00",
+ ],
+ "letter": ["A", "B", "C"],
+ }
+ )
+ df["time"] = pd.to_datetime(df.time)
+
+ df["time"].describe(datetime_is_numeric=True)
+ return df, pd
+
+
+def __():
+ import marimo as mo
+
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_snippets/snippets.py b/marimo/_snippets/snippets.py
new file mode 100644
index 0000000000..1e90a865f3
--- /dev/null
+++ b/marimo/_snippets/snippets.py
@@ -0,0 +1,93 @@
+# Copyright 2024 Marimo. All rights reserved.
+import os
+from dataclasses import dataclass
+from typing import Any, Awaitable, Generator, List, Optional
+
+from marimo._ast.codegen import get_app
+from marimo._utils.paths import import_files
+
+
+@dataclass
+class SnippetSection:
+ id: str
+ html: Optional[str] = None
+ code: Optional[str] = None
+
+
+@dataclass
+class Snippet:
+ title: str
+ sections: List[SnippetSection]
+
+
+@dataclass
+class Snippets:
+ snippets: List[Snippet]
+
+
+async def read_snippets() -> Snippets:
+ snippets: List[Snippet] = []
+
+ for file in snippet_files():
+ app = get_app(file)
+ assert app is not None
+ sections: List[SnippetSection] = []
+ title = ""
+
+ for cell in app._cell_manager.cells():
+ if not cell:
+ continue
+
+ code = cell._cell.code
+ if should_ignore_code(code):
+ continue
+
+ if is_markdown(code):
+ if not title and "# " in code:
+ title = get_title_from_code(code)
+
+ ret = cell.run()
+ if isinstance(ret, Awaitable):
+ output, _defs = await ret
+ else:
+ output, _defs = ret
+ sections.append(
+ SnippetSection(html=output.text, id=cell._cell.cell_id)
+ )
+ else:
+ sections.append(
+ SnippetSection(code=code, id=cell._cell.cell_id)
+ )
+
+ snippets.append(Snippet(title=title, sections=sections))
+
+ return Snippets(snippets=snippets)
+
+
+def should_ignore_code(code: str) -> bool:
+ return code == "import marimo as mo"
+
+
+def get_title_from_code(code: str) -> str:
+ if not code:
+ return ""
+ if "# " in code:
+ # title is the start of # and end of \n
+ start = code.find("#")
+ end = code[start:].find("\n")
+ return code[start : end + start].replace("#", "", 1).strip()
+ return ""
+
+
+def is_markdown(code: str) -> bool:
+ return code.startswith("mo.md")
+
+
+def snippet_files() -> Generator[str, Any, None]:
+ root = os.path.realpath(
+ str(import_files("marimo").joinpath("_snippets").joinpath("data"))
+ )
+ for _root, _dirs, files in os.walk(root):
+ for file in files:
+ if file.endswith(".py"):
+ yield os.path.join(root, file)
diff --git a/marimo/_utils/paths.py b/marimo/_utils/paths.py
new file mode 100644
index 0000000000..d722c416b2
--- /dev/null
+++ b/marimo/_utils/paths.py
@@ -0,0 +1,12 @@
+# Copyright 2024 Marimo. All rights reserved.
+import sys
+from typing import Any
+
+
+def import_files(filename: str) -> Any:
+ if sys.version_info < (3, 9):
+ from importlib_resources import files as importlib_files
+ else:
+ from importlib.resources import files as importlib_files
+
+ return importlib_files(filename)
diff --git a/pyproject.toml b/pyproject.toml
index e91c19b183..8ca5bd40f1 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -136,6 +136,7 @@ include = ["marimo*"]
line-length=79
exclude = [
"marimo/_tutorials",
+ "marimo/_snippets/data",
"marimo/_smoke_tests",
"marimo/_test_utils/codegen_data",
"marimo/_test_utils/_tutorials",
@@ -185,6 +186,7 @@ extend-exclude = """
| ^/tests/_cli/ipynb_data/*
| ^/tests/_runtime/runtime_data/*
| ^/marimo/_tutorials/*
+ | ^/marimo/_snippets/data/*
| ^/marimo/_smoke_tests/*
)
"""
@@ -198,6 +200,7 @@ exclude = [
'tests/_cli/ipynb_data',
'tests/_runtime/runtime_data',
'marimo/_tutorials/',
+ 'marimo/_snippets/data/',
'marimo/_smoke_tests/',
]
warn_unused_ignores=false
diff --git a/tests/_server/api/endpoints/test_documentation.py b/tests/_server/api/endpoints/test_documentation.py
new file mode 100644
index 0000000000..f40c0d1323
--- /dev/null
+++ b/tests/_server/api/endpoints/test_documentation.py
@@ -0,0 +1,10 @@
+# Copyright 2024 Marimo. All rights reserved.
+from starlette.testclient import TestClient
+
+
+def test_snippets(client: TestClient) -> None:
+ response = client.get("/api/documentation/snippets")
+ assert response.status_code == 200, response.text
+ content = response.json()
+ assert content["snippets"] is not None
+ assert len(content["snippets"]) > 0
diff --git a/tests/_snippets/test_snippets.py b/tests/_snippets/test_snippets.py
new file mode 100644
index 0000000000..d651e83ee8
--- /dev/null
+++ b/tests/_snippets/test_snippets.py
@@ -0,0 +1,38 @@
+from marimo._snippets.snippets import get_title_from_code, read_snippets
+
+
+async def test_snippets() -> None:
+ snippets = await read_snippets()
+ assert len(snippets.snippets) > 0
+ # All have titles
+ assert all(s.title for s in snippets.snippets)
+ # All have more than one section
+ assert all(len(s.sections) > 1 for s in snippets.snippets)
+ # All have a code section
+ assert all(
+ any(section.code for section in s.sections) for s in snippets.snippets
+ )
+
+
+def test_get_title_from_code_empty() -> None:
+ assert get_title_from_code("") == ""
+
+
+def test_get_title_from_code_with_title() -> None:
+ code = "# This is a title\nprint('Hello, world!')"
+ assert get_title_from_code(code) == "This is a title"
+
+
+def test_get_title_from_code_without_title() -> None:
+ code = "print('Hello, world!')"
+ assert get_title_from_code(code) == ""
+
+
+def test_get_title_from_code_with_multiple_titles() -> None:
+ code = "# First title\nprint('Hello, world!')\n# Second title"
+ assert get_title_from_code(code) == "First title"
+
+
+def test_get_title_from_code_with_non_title_hashes() -> None:
+ code = "print('# This is not a title')"
+ assert get_title_from_code(code) == ""