A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
mo.status.progress_bar(), mo.status.spinner() (#182)
Myles Scolnickac6da9187375
diff --git a/docs/api/index.md b/docs/api/index.mdindex ee3d11bdc8..fe6403cb7b 100644--- a/docs/api/index.md+++ b/docs/api/index.md@@ -10,9 +10,10 @@layouts/indexplottingmedia/index- html+ statusoutputscontrol_flow+ htmlstatedebugging```@@ -32,8 +33,9 @@ Use the marimo library in marimo notebooks (`import marimo as mo`) to| {doc}`layouts/index` | Customize outputs with accordions, tabs, stacks, and more || {doc}`plotting` | Output interactive plots || {doc}`media/index` | Output media like images, audio, PDFs, and plain text |-| {doc}`html` | Manipulate HTML objects |+| {doc}`status` | Display progress indicators || {doc}`outputs` | Modify cell outputs, redirect console output || {doc}`control_flow` | Control how cells execute |+| {doc}`html` | Manipulate HTML objects || {doc}`state` | Make stateful apps with `mo.state` || {doc}`debugging` | Debugging utilities |diff --git a/docs/api/status.md b/docs/api/status.mdnew file mode 100644index 0000000000..6fe9a41960--- /dev/null+++ b/docs/api/status.md@@ -0,0 +1,21 @@+# Status++Use progress bars or spinners to visualize loading status in your notebooks and+apps. Useful when iterating over collections or loading data from files,+databases, or APIs.++## Progress bar++You can display a progress bar while iterating over a collection, similar+to `tqdm`.++```{eval-rst}+.. autofunction:: marimo.status.progress_bar+```++## Spinner++```{eval-rst}+.. autofunction:: marimo.status.spinner+```+diff --git a/frontend/package.json b/frontend/package.jsonindex 9b3f25ebdd..bd73bab738 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -41,6 +41,7 @@"@radix-ui/react-icons": "^1.3.0","@radix-ui/react-label": "^2.0.2","@radix-ui/react-popover": "^1.0.7",+ "@radix-ui/react-progress": "^1.0.3","@radix-ui/react-radio-group": "^1.1.3","@radix-ui/react-select": "^1.2.2","@radix-ui/react-slider": "^1.1.2",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex 364900d43f..21296bf9d5 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -95,6 +95,9 @@ dependencies:'@radix-ui/react-popover':specifier: ^1.0.7version: 1.0.7(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ '@radix-ui/react-progress':+ specifier: ^1.0.3+ version: 1.0.3(@types/[email protected])(@types/[email protected])([email protected])([email protected])'@radix-ui/react-radio-group':specifier: ^1.1.3version: 1.1.3(@types/[email protected])(@types/[email protected])([email protected])([email protected])@@ -3743,6 +3746,28 @@ packages:react: 18.2.0react-dom: 18.2.0([email protected])+ /@radix-ui/[email protected](@types/[email protected])(@types/[email protected])([email protected])([email protected]):+ resolution: {integrity: sha512-5G6Om/tYSxjSeEdrb1VfKkfZfn/1IlPWd731h2RfPuSbIfNUgfqAwbKfJCg/PP6nuUCTrYzalwHSpSinoWoCag==}+ peerDependencies:+ '@types/react': '*'+ '@types/react-dom': '*'+ react: ^16.8 || ^17.0 || ^18.0+ react-dom: ^16.8 || ^17.0 || ^18.0+ peerDependenciesMeta:+ '@types/react':+ optional: true+ '@types/react-dom':+ optional: true+ dependencies:+ '@babel/runtime': 7.22.5+ '@radix-ui/react-context': 1.0.1(@types/[email protected])([email protected])+ '@radix-ui/react-primitive': 1.0.3(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ '@types/react': 18.2.25+ '@types/react-dom': 18.2.11+ react: 18.2.0+ react-dom: 18.2.0([email protected])+ dev: false+/@radix-ui/[email protected](@types/[email protected])(@types/[email protected])([email protected])([email protected]):resolution: {integrity: sha512-x+yELayyefNeKeTx4fjK6j99Fs6c4qKm3aY38G3swQVTN6xMpsrbigC0uHs2L//g8q4qR7qOcww8430jJmi2ag==}peerDependencies:diff --git a/frontend/src/components/ui/progress.tsx b/frontend/src/components/ui/progress.tsxnew file mode 100644index 0000000000..0c10503082--- /dev/null+++ b/frontend/src/components/ui/progress.tsx@@ -0,0 +1,27 @@+/* Copyright 2023 Marimo. All rights reserved. */+import * as React from "react";+import * as ProgressPrimitive from "@radix-ui/react-progress";++import { cn } from "@/lib/utils";++const Progress = React.forwardRef<+ React.ElementRef<typeof ProgressPrimitive.Root>,+ React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root>+>(({ className, value, ...props }, ref) => (+ <ProgressPrimitive.Root+ ref={ref}+ className={cn(+ "relative h-2 w-full overflow-hidden rounded-full bg-primary/20",+ className+ )}+ {...props}+ >+ <ProgressPrimitive.Indicator+ className="h-full w-full flex-1 bg-primary transition-all pulse"+ style={{ transform: `translateX(-${100 - (value || 0)}%)` }}+ />+ </ProgressPrimitive.Root>+));+Progress.displayName = ProgressPrimitive.Root.displayName;++export { Progress };diff --git a/frontend/src/plugins/layout/ProgressPlugin.tsx b/frontend/src/plugins/layout/ProgressPlugin.tsxnew file mode 100644index 0000000000..c4202538a9--- /dev/null+++ b/frontend/src/plugins/layout/ProgressPlugin.tsx@@ -0,0 +1,84 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { PropsWithChildren } from "react";++import { z } from "zod";+import { IStatelessPlugin, IStatelessPluginProps } from "../stateless-plugin";+import { renderHTML } from "../core/RenderHTML";+import { Progress } from "@/components/ui/progress";+import { Loader2Icon } from "lucide-react";++interface Data {+ /**+ * The title of the progress bar.+ */+ title?: string;+ /**+ * The subtitle of the progress bar.+ */+ subtitle?: string;+ /**+ * The progress of the progress bar.+ * Number from 0 to 100, or `true` to indicate indeterminate progress if the count is unknown.+ */+ progress: number | boolean;+ /**+ * The total value of the progress bar.+ */+ total?: number;+}++export class ProgressPlugin implements IStatelessPlugin<Data> {+ tagName = "marimo-progress";++ validator = z.object({+ title: z.string().optional(),+ subtitle: z.string().optional(),+ progress: z.union([z.number(), z.boolean()]),+ total: z.number().optional(),+ });++ render(props: IStatelessPluginProps<Data>): JSX.Element {+ return <ProgressComponent {...props.data} />;+ }+}++export const ProgressComponent = ({+ title,+ subtitle,+ progress,+ total,+}: PropsWithChildren<Data>): JSX.Element => {+ return (+ <div className="flex flex-col items-center max-w-sm p-6 mx-auto space-y-4">+ {title && (+ <div className="text-2xl font-bold text-foreground/60">+ {renderHTML({ html: title })}+ </div>+ )}+ {subtitle && (+ <div className="text-sm text-muted-foreground">+ {renderHTML({ html: subtitle })}+ </div>+ )}+ <div className="mt-2 w-full">+ {typeof progress === "number" && total != null && total > 0 ? (+ <div className="flex gap-3 text-sm text-muted-foreground items-baseline">+ <Progress value={clampProgress((progress / total) * 100)} />+ <span className="flex-shrink-0">+ {progress} / {total}+ </span>+ </div>+ ) : (+ <Loader2Icon className="w-12 h-12 animate-spin text-primary mx-auto" />+ )}+ </div>+ </div>+ );+};++function clamp(value: number, min: number, max: number): number {+ return Math.min(Math.max(value, min), max);+}+function clampProgress(progress: number): number {+ return clamp(progress, 0, 100);+}diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.tsindex d77a6d724b..7233c58f3a 100644--- a/frontend/src/plugins/plugins.ts+++ b/frontend/src/plugins/plugins.ts@@ -27,6 +27,7 @@ import { TexPlugin } from "./layout/TexPlugin";import { RefreshPlugin } from "./impl/RefreshPlugin";import { MicrophonePlugin } from "./impl/MicrophonePlugin";import { DownloadPlugin } from "./layout/DownloadPlugin";+import { ProgressPlugin } from "./layout/ProgressPlugin";import { VegaPlugin } from "./impl/vega/VegaPlugin";import { StatPlugin } from "./layout/StatPlugin";@@ -60,6 +61,7 @@ const LAYOUT_PLUGINS: Array<IStatelessPlugin<unknown>> = [new JsonOutputPlugin(),new StatPlugin(),new TabsPlugin(),+ new ProgressPlugin(),new TexPlugin(),];diff --git a/frontend/src/stories/progress-component.stories.tsx b/frontend/src/stories/progress-component.stories.tsxnew file mode 100644index 0000000000..06a536d0a8--- /dev/null+++ b/frontend/src/stories/progress-component.stories.tsx@@ -0,0 +1,45 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { ProgressComponent } from "@/plugins/layout/ProgressPlugin";+import type { Meta, StoryFn } from "@storybook/react";++const meta: Meta<typeof ProgressComponent> = {+ title: "ProgressComponent",+ component: ProgressComponent,+ args: {},+};++export default meta;++const Template: StoryFn<typeof ProgressComponent> = (args) => (+ <div className="bg-background">+ <ProgressComponent {...args} />+ </div>+);++export const Default = Template.bind({});+Default.args = {+ title: "Parsing documents",+ subtitle: "This may take a few seconds",+ progress: 4,+ total: 10,+};++export const Spinner = Template.bind({});+Spinner.args = {+ title: "Loading model",+ subtitle: "This may take a few seconds",+ progress: true,+};++export const SpinnerNoTitle = Template.bind({});+SpinnerNoTitle.args = {+ subtitle: "This may take a few seconds",+ progress: true,+};++export const ProgressNoTitle = Template.bind({});+ProgressNoTitle.args = {+ subtitle: "This may take a few seconds",+ progress: 8,+ total: 10,+};diff --git a/frontend/src/stories/progress.stories.tsx b/frontend/src/stories/progress.stories.tsxnew file mode 100644index 0000000000..5617658b4e--- /dev/null+++ b/frontend/src/stories/progress.stories.tsx@@ -0,0 +1,32 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { Progress } from "@/components/ui/progress";+import type { Meta, StoryFn } from "@storybook/react";++const meta: Meta<typeof Progress> = {+ title: "Progress",+ component: Progress,+ args: {},+};++export default meta;++const Template: StoryFn<typeof Progress> = (args) => (+ <div className="bg-background">+ <Progress {...args} />+ </div>+);++export const Empty = Template.bind({});+Empty.args = {+ value: 0,+};++export const Half = Template.bind({});+Half.args = {+ value: 50,+};++export const Full = Template.bind({});+Full.args = {+ value: 100,+};diff --git a/marimo/__init__.py b/marimo/__init__.pyindex 062c6fbf47..58688829d8 100644--- a/marimo/__init__.py+++ b/marimo/__init__.py@@ -40,6 +40,7 @@ __all__ = ["right","stat","state",+ "status","stop","tabs","tree",@@ -55,7 +56,7 @@ from marimo._output.hypertext import Htmlfrom marimo._output.justify import center, left, rightfrom marimo._output.md import mdfrom marimo._plugins import ui-from marimo._plugins.stateless import mpl+from marimo._plugins.stateless import mpl, statusfrom marimo._plugins.stateless.accordion import accordionfrom marimo._plugins.stateless.audio import audiofrom marimo._plugins.stateless.callout_output import calloutdiff --git a/marimo/_plugins/stateless/status/__init__.py b/marimo/_plugins/stateless/status/__init__.pynew file mode 100644index 0000000000..70e35f0c51--- /dev/null+++ b/marimo/_plugins/stateless/status/__init__.py@@ -0,0 +1,7 @@+# Copyright 2023 Marimo. All rights reserved.+"""Create loading indicators."""+++__all__ = ["progress_bar", "spinner"]++from marimo._plugins.stateless.status._progress import progress_bar, spinnerdiff --git a/marimo/_plugins/stateless/status/_progress.py b/marimo/_plugins/stateless/status/_progress.pynew file mode 100644index 0000000000..068871cce9--- /dev/null+++ b/marimo/_plugins/stateless/status/_progress.py@@ -0,0 +1,236 @@+# Copyright 2023 Marimo. All rights reserved.+from __future__ import annotations++import contextlib+from collections.abc import Collection+from typing import Iterable, Iterator, Optional, TypeVar++import marimo._runtime.output._output as output+from marimo._output.hypertext import Html+from marimo._output.rich_help import mddoc+from marimo._plugins.core.web_component import build_stateless_plugin++S = TypeVar("S")+T = TypeVar("T")+++def _remove_none_values(d: dict[S, T]) -> dict[S, T]:+ return {k: v for k, v in d.items() if v is not None}+++class _Progress(Html):+ """A mutable class to represent a progress indicator in the UI."""++ def __init__(+ self,+ title: Optional[str],+ subtitle: Optional[str],+ total: Optional[int],+ ) -> None:+ self.title = title+ self.subtitle = subtitle+ self.total = total+ self.current = 0+ self.closed = False+ # We show a loading spinner if total not known+ self.loading_spinner = total is None+ self._text = self._get_text()++ def update_progress(+ self,+ increment: int = 1,+ title: Optional[str] = None,+ subtitle: Optional[str] = None,+ ) -> None:+ """Update the progress indicator.++ **Example.**++ ```python+ # Increment by 1+ progress.update()++ # Increment by 10 and update title and subtitle+ progress.update(10, title="Loading", subtitle="Still going...")++ ```++ **Args.**++ - increment: amount to increment by. Defaults to 1.+ - title: new title. Defaults to None.+ - subtitle: new subtitle. Defaults to None.+ """+ if self.closed:+ raise RuntimeError(+ "Progress indicators cannot be updated after exiting "+ "the context manager that created them. "+ )+ self.current += increment+ if title is not None:+ self.title = title+ if subtitle is not None:+ self.subtitle = subtitle++ self._text = self._get_text()+ output.flush()++ def clear(self) -> None:+ if self.closed:+ raise RuntimeError(+ "Progress indicators cannot be updated after exiting "+ "the context manager that created them. "+ )+ output.remove(self)++ def close(self) -> None:+ self.closed = True++ def _get_text(self) -> str:+ return build_stateless_plugin(+ component_name="marimo-progress",+ args=_remove_none_values(+ {+ "title": self.title,+ "subtitle": self.subtitle,+ "total": self.total,+ # 'progress' is True is we don't know the total,+ # which shows a loading spinner+ "progress": True if self.loading_spinner else self.current,+ }+ ),+ )+++class ProgressBar(_Progress):+ def __init__(+ self, title: str | None, subtitle: str | None, total: int+ ) -> None:+ super().__init__(title=title, subtitle=subtitle, total=total)++ def update(+ self,+ increment: int = 1,+ title: str | None = None,+ subtitle: str | None = None,+ ) -> None:+ super().update_progress(+ increment=increment, title=title, subtitle=subtitle+ )+++# TODO(akshayka): Add a `done()` method that turns the spinner into a checkmark+class Spinner(_Progress):+ """A spinner output representing a loading state"""++ def __init__(self, title: str | None, subtitle: str | None) -> None:+ super().__init__(title=title, subtitle=subtitle, total=None)++ def update(+ self, title: str | None = None, subtitle: str | None = None+ ) -> None:+ """Update the title and subtitle of the spinner++ This method updates a spinner output in-place. Must be used+ in the cell the spinner was created.++ **Example.**++ ```python+ with mo.status.spinner("Hang tight!") as _spinner:+ ...+ _spinner.update(title="Almost done!")+ # Optionally, remove the spinner from the output+ # _spinner.clear()+ ```+ """+ super().update_progress(increment=1, title=title, subtitle=subtitle)+++@mddoc+def spinner(+ title: Optional[str] = None,+ subtitle: Optional[str] = None,+ remove_on_exit: bool = True,+) -> Iterator[Spinner]:+ """Show a loading spinner++ Use `mo.status.spinner()` as a context manager to show a loading spinner.+ You can optionally pass a title and subtitle.++ **Example.**++ ```python+ with mo.status.spinner(subtitle="Loading data ...") as _spinner:+ data = expensive_function()+ _spinner.update(subtitle="Crunching numbers ...")+ ...++ mo.ui.table(data)+ ```++ **Args:**++ - `title`: optional title+ - `subtitle`: optional subtitle+ - `remove_on_exit`: if True, the spinner is removed from output on exit+ """+ spinner = Spinner(title=title, subtitle=subtitle)+ output.append(spinner)+ try:+ yield spinner+ finally:+ if remove_on_exit:+ spinner.clear()+ # TODO(akshayka): else consider transitioning to a done state+ spinner.close()+++def progress_bar(+ collection: Collection[S | int],+ *,+ title: Optional[str] = None,+ subtitle: Optional[str] = None,+ completion_title: Optional[str] = None,+ completion_subtitle: Optional[str] = None,+) -> Iterable[S | int]:+ """Iterate over a collection and show a progress bar++ **Example.**++ ```python+ for i in mo.status.progress_bar(range(10)):+ ...+ ```++ You can optionally provide a title and subtitle to show+ during iteration, and a title/subtitle to show upon completion.++ **Args.**++ - `collection`: a collection to iterate over+ - `title`: optional title+ - `subtitle`: optional subtitle+ - `completion_title`: optional title to show during completion+ - `completion_subtitle`: optional subtitle to show during completion++ **Returns.**++ An iterable object that wraps `collection`+ """+ if isinstance(collection, range):+ total = collection.stop - collection.start+ step = collection.step+ else:+ total = len(collection)+ step = 1+ progress = ProgressBar(title=title, subtitle=subtitle, total=total)+ output.append(progress)+ for item in collection:+ yield item+ progress.update(increment=step)+ progress.update(+ increment=0, title=completion_title, subtitle=completion_subtitle+ )+ progress.close()diff --git a/marimo/_runtime/output/_output.py b/marimo/_runtime/output/_output.pyindex dd3827e9aa..c2d44beb55 100644--- a/marimo/_runtime/output/_output.py+++ b/marimo/_runtime/output/_output.py@@ -36,7 +36,10 @@ def replace(value: object) -> None:ctx = get_context()if ctx.kernel.execution_context is None:return- ctx.kernel.execution_context.output = [value]+ elif value is None:+ ctx.kernel.execution_context.output = None+ else:+ ctx.kernel.execution_context.output = [value]write_internal(cell_id=ctx.kernel.execution_context.cell_id, value=value)@@ -69,3 +72,33 @@ def append(value: object) -> None:def clear() -> None:"""Clear a cell's output."""return replace(None)+++def flush() -> None:+ """Internal function to re-render the cell's output."""+ ctx = get_context()+ if ctx.kernel.execution_context is None:+ return++ if ctx.kernel.execution_context.output is not None:+ write_internal(+ cell_id=ctx.kernel.execution_context.cell_id,+ value=vstack(ctx.kernel.execution_context.output),+ )+++def remove(value: object) -> None:+ """Internal function to remove an object from a cell's output."""+ ctx = get_context()+ if (+ ctx.kernel.execution_context is None+ or ctx.kernel.execution_context.output is None+ ):+ return+ output = [+ item+ for item in ctx.kernel.execution_context.output+ if item is not value+ ]+ ctx.kernel.execution_context.output = output if output else None+ flush()diff --git a/marimo/_smoke_tests/status.py b/marimo/_smoke_tests/status.pynew file mode 100644index 0000000000..1bbaf88553--- /dev/null+++ b/marimo/_smoke_tests/status.py@@ -0,0 +1,44 @@+# Copyright 2023 Marimo. All rights reserved.+import marimo++__generated_with = "0.1.24"+app = marimo.App()+++def __():+ import marimo as mo+ import time+ return mo, time+++def __(mo, time):+ for _ in mo.status.progress_bar(+ range(10), title="Loading", subtitle="Please wait"+ ):+ time.sleep(0.1)+ return+++def __(mo, time):+ with mo.status.spinner(title="Loading...", remove_on_exit=True) as _spinner:+ time.sleep(1)+ _spinner.update("Almost done")+ time.sleep(1)+ return+++def __(mo, time):+ with mo.status.spinner(title="Loading...", remove_on_exit=True) as _spinner:+ time.sleep(1)+ _spinner.update("Almost done")+ time.sleep(1)+ mo.ui.table([1, 2, 3])+ return+++if __name__ == "__main__":+ app.run()