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
Refresh plugin (#20)
Myles Scolnick46600a7c891c
diff --git a/docs/api/inputs/index.md b/docs/api/inputs/index.mdindex 1584a4003b..b5f276eeee 100644--- a/docs/api/inputs/index.md+++ b/docs/api/inputs/index.md@@ -17,11 +17,12 @@multiselectnumberradio+ refreshsliderswitchtable- text_areatext+ text_area```marimo comes packaged with interactive UI elements that you can use to build@@ -43,11 +44,12 @@ powerful notebooks and apps. These elements are available in `marimo.ui`.marimo.ui.multiselectmarimo.ui.numbermarimo.ui.radio+ marimo.ui.refreshmarimo.ui.slidermarimo.ui.switchmarimo.ui.table- marimo.ui.text_areamarimo.ui.text+ marimo.ui.text_area```To use a UI element, assign it to a global variable and output it in a cell.diff --git a/docs/api/inputs/refresh.md b/docs/api/inputs/refresh.mdnew file mode 100644index 0000000000..16cdc681aa--- /dev/null+++ b/docs/api/inputs/refresh.md@@ -0,0 +1,12 @@+# Refresh++<!-- TODO: add interactive mo.ui.refresh doc.+At the moment, our components app uses released versions of marimo, so these changes will lag behind. -->+<!-- <iframe class="demo" src="https://components.marimo.io/?component=refresh" frameborder="no"></iframe> -->++```{eval-rst}+.. autoclass:: marimo.ui.refresh+ :members:++ .. autoclasstoc:: marimo._plugins.ui._impl.refresh.refresh+```diff --git a/frontend/package.json b/frontend/package.jsonindex 649062208b..1dc71a6220 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -71,6 +71,7 @@"react-use-event-hook": "^0.9.6","tailwind-merge": "^1.14.0","tailwindcss-animate": "^1.0.6",+ "timestring": "^7.0.0","web-vitals": "^3.4.0","zod": "^3.22.2"},@@ -118,6 +119,7 @@"@types/katex": "^0.16.2","@types/react": "^18.2.20","@types/react-dom": "^18.2.7",+ "@types/timestring": "^6.0.2","@typescript-eslint/eslint-plugin": "^5.62.0","@typescript-eslint/parser": "^5.62.0","@vitejs/plugin-react-swc": "^3.3.2",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex 7b9ba1a254..ff32d2f477 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -185,6 +185,9 @@ dependencies:tailwindcss-animate:specifier: ^1.0.6version: 1.0.6([email protected])+ timestring:+ specifier: ^7.0.0+ version: 7.0.0web-vitals:specifier: ^3.4.0version: 3.4.0@@ -238,6 +241,9 @@ devDependencies:'@types/react-dom':specifier: ^18.2.7version: 18.2.7+ '@types/timestring':+ specifier: ^6.0.2+ version: 6.0.2'@typescript-eslint/eslint-plugin':specifier: ^5.62.0@@ -5828,6 +5834,10 @@ packages:'@types/jest': 27.4.0dev: true+ /@types/[email protected]:+ resolution: {integrity: sha512-JPDV0pPv2UtUrYyWpn/iBA7aDp1vOPYZrUL/9R4Dxrp1XIUrFnqkhN2EroLU0DLsMyN3iWg1vI1pqBNZ+8zxIg==}+ dev: true+/@types/[email protected]:resolution: {integrity: sha512-PBjIUxZHOuj0R15/xuwJYjFi+KZdNFrehocChv4g5hu6aFroHue8m0lBP0POdK2nKzbw0cgV1mws8+V/JAcEkQ==}dev: true@@ -12903,6 +12913,11 @@ packages:resolution: {integrity: sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==}dev: true+ resolution: {integrity: sha512-U7ttxEdKWqHYJ96OGoJJR5gU8Nwkl3tlY0n7Jr4vcpLD2RkVZLE1Ph9k8ZRrZ7LYX9QCtd3M9OUaR9P8Z37QNg==}+ engines: {node: '>=12'}+ dev: false+resolution: {integrity: sha512-AD5ih2NlSssTCwsMznbvwMZpJ1cbhkGd2uueNxzv2jDlEeZdU04JQfRnggJQ8DrcVBGjAsCKwFBbDlVNtEMlzw==}diff --git a/frontend/src/components/ui/native-select.tsx b/frontend/src/components/ui/native-select.tsxindex 796db51778..a60e1bc852 100644--- a/frontend/src/components/ui/native-select.tsx+++ b/frontend/src/components/ui/native-select.tsx@@ -10,7 +10,7 @@ const NativeSelect = React.forwardRef<<selectref={ref}className={cn(- "flex h-6 w-fit mb-1 shadow-xsSolid items-center justify-between rounded-sm border border-input bg-transparent px-2 text-sm font-prose ring-offset-background placeholder:text-muted-foreground hover:shadow-smSolid focus:outline-none focus:ring-1 focus:ring-ring focus:border-accent focus:shadow-mdSolid disabled:cursor-not-allowed disabled:opacity-50",+ "flex h-6 w-fit mb-1 shadow-xsSolid items-center justify-between rounded-sm border border-input bg-transparent px-2 text-sm font-prose ring-offset-background placeholder:text-muted-foreground hover:shadow-smSolid focus:outline-none focus:ring-1 focus:ring-ring focus:border-accent focus:shadow-mdSolid disabled:cursor-not-allowed disabled:opacity-50 cursor-pointer",className)}{...props}diff --git a/frontend/src/plugins/impl/RefreshPlugin.tsx b/frontend/src/plugins/impl/RefreshPlugin.tsxnew file mode 100644index 0000000000..30098fe12e--- /dev/null+++ b/frontend/src/plugins/impl/RefreshPlugin.tsx@@ -0,0 +1,157 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { useEffect, useState } from "react";+import { z } from "zod";++import { IPlugin, IPluginProps } from "@/plugins/types";+import { RefreshCwIcon } from "lucide-react";+import timestring from "timestring";+import { NativeSelect } from "@/components/ui/native-select";+import { Button } from "@/components/ui/button";+import * as labelStyles from "./Label.styles";+import { useEvent } from "../../hooks/useEvent";+import { cn } from "@/lib/utils";+import { Label } from "@/components/ui/label";+import { HtmlOutput } from "@/editor/output/HtmlOutput";++type Value = string | number | undefined;++interface Data {+ /**+ * The refresh interval in seconds.+ *+ * It may also be a human-readable string like "1m" or "1h" or "3h 30m".+ * These will be converted to seconds.+ */+ options: Array<string | number>;+ /**+ * The initial value.+ */+ defaultInterval?: string | number;++ label?: string | null;+}++const zodTimestring = z.string().superRefine((s, ctx) => {+ try {+ const seconds = timestring(s);+ if (seconds < 1) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Must be greater than 1 second.",+ });+ }+ return;+ } catch {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Must be a valid timestring. e.g. 1m, 30m, 1h.",+ });+ return;+ }+});++export class RefreshPlugin implements IPlugin<Value, Data> {+ tagName = "marimo-refresh";++ validator = z.object({+ options: z.array(z.union([zodTimestring, z.number().min(1)])).default([]),+ defaultInterval: z.union([zodTimestring, z.number().min(1)]).optional(),+ label: z.string().nullable(),+ });++ render(props: IPluginProps<Value, Data>): JSX.Element {+ return <RefreshComponent {...props} />;+ }+}++const OFF = "off";++let count = 0;++const RefreshComponent = ({ setValue, data }: IPluginProps<Value, Data>) => {+ // internal selection+ const [selected, setSelected] = useState<string | number>(+ data.defaultInterval ?? OFF+ );++ // reset selection when defaultInterval changes+ useEffect(() => {+ setSelected(data.defaultInterval ?? OFF);+ }, [data.defaultInterval]);++ const [spin, setSpin] = useState(false);++ const refresh = useEvent(() => {+ setSpin(true);+ setValue(() => `${selected} (${count++})`);+ setTimeout(() => setSpin(false), 500); // spin for 500ms+ });++ useEffect(() => {+ if (selected === OFF) {+ return;+ }++ let asSeconds =+ typeof selected === "number"+ ? selected+ : /[a-z]/.test(selected) // check if has units+ ? timestring(selected)+ : timestring(`${selected}s`); // default to seconds if no units++ // Smallest interval is 1 second+ asSeconds = Math.max(asSeconds, 1);++ const id = setInterval(refresh, asSeconds * 1000);+ return () => clearInterval(id);+ }, [selected, refresh]);++ const noShadow =+ "shadow-none! hover:shadow-none! focus:shadow-none! active:shadow-none!";++ const hasOptions = data.options.length > 0;++ return (+ <div className={labelStyles.labelContainer}>+ {data.label && (+ <Label className={labelStyles.label}>+ <HtmlOutput html={data.label} inline={true} />+ </Label>+ )}+ <span className="inline-flex items-center text-secondary-foreground rounded shadow-smSolid">+ <Button+ variant="secondary"+ size="icon"+ className={cn(+ noShadow,+ "border mb-0 rounded",+ hasOptions && "border-r-0 rounded-tr-none rounded-br-none"+ )}+ onClick={refresh}+ >+ <RefreshCwIcon+ className={cn("w-3.5 h-3.5", spin && "animate-spin")}+ />+ </Button>+ <NativeSelect+ onChange={(e) => {+ setSelected(e.target.value);+ }}+ value={selected}+ className={cn(+ noShadow,+ "border mb-0 bg-secondary rounded rounded-tl-none rounded-bl-none hover:bg-secondary/60",+ !hasOptions && "hidden"+ )}+ >+ <option value={OFF}>off</option>+ {data.options.map((option) => (+ <option value={option} key={option}>+ {typeof option === "number" ? `${option}s` : option}+ </option>+ ))}+ </NativeSelect>+ </span>+ </div>+ );+};diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.tsindex 7e9abbc9d2..1c48780f0f 100644--- a/frontend/src/plugins/plugins.ts+++ b/frontend/src/plugins/plugins.ts@@ -24,11 +24,13 @@ import { CalloutPlugin } from "./layout/CalloutPlugin";import { JsonOutputPlugin } from "./layout/JsonOutputPlugin";import { TabsPlugin } from "./layout/TabsPlugin";import { TexPlugin } from "./layout/TexPlugin";+import { RefreshPlugin } from "./impl/RefreshPlugin";// List of UI pluginsconst UI_PLUGINS: Array<IPlugin<any, unknown>> = [new ButtonPlugin(),new CheckboxPlugin(),+ new DataTablePlugin(),new DatePickerPlugin(),new DictPlugin(),new DropdownPlugin(),@@ -37,11 +39,11 @@ const UI_PLUGINS: Array<IPlugin<any, unknown>> = [new MultiselectPlugin(),new NumberPlugin(),new RadioPlugin(),- new DataTablePlugin(),+ new RefreshPlugin(),new SliderPlugin(),new SwitchPlugin(),- new TextInputPlugin(),new TextAreaPlugin(),+ new TextInputPlugin(),];// List of output / layout pluginsdiff --git a/marimo/_plugins/ui/__init__.py b/marimo/_plugins/ui/__init__.pyindex 3403799985..f51b95d4b0 100644--- a/marimo/_plugins/ui/__init__.py+++ b/marimo/_plugins/ui/__init__.py@@ -17,6 +17,7 @@ __all__ = ["multiselect","number","radio",+ "refresh","slider","switch","table",@@ -43,4 +44,5 @@ from marimo._plugins.ui._impl.input import (text,text_area,)+from marimo._plugins.ui._impl.refresh import refreshfrom marimo._plugins.ui._impl.switch import switchdiff --git a/marimo/_plugins/ui/_impl/refresh.py b/marimo/_plugins/ui/_impl/refresh.pynew file mode 100644index 0000000000..9971d05e48--- /dev/null+++ b/marimo/_plugins/ui/_impl/refresh.py@@ -0,0 +1,97 @@+# Copyright 2023 Marimo. All rights reserved.+from __future__ import annotations++from typing import Final, Optional, Union++from marimo._output.rich_help import mddoc+from marimo._plugins.ui._core.ui_element import UIElement+++@mddoc+class refresh(UIElement[int, int]):+ """+ A refresh button that will auto-refresh its descendants for a+ given interval.++ Each option value can either be a number (int or float) in seconds or a+ human-readable string (e.g. "1s", "10s", "1m").++ You can also combine multiple time units (e.g. "1m 30s").++ **Example.**++ ```python+ refresh_button = mo.ui.refresh_button(+ options=["1m", "5m 30s", "10m"],+ default_interval="10m",+ )+ ```++ **Attributes.**++ - `value`: The time in seconds since the refresh has been activated.++ **Initialization Args.**++ - `options`: The options for the refresh interval, as a list of+ human-readable strings or numbers (int or float) in seconds.+ If no options are provided and default_interval is provided,+ the options will be generated automatically.+ If no options are provided and default_interval is not provided,+ the refresh button will not be displayed with a dropdown for auto-refresh.+ - `default_interval`: The default value of the refresh interval.+ - `label`: optional text label for the element+ """++ name: Final[str] = "marimo-refresh"++ def __init__(+ self,+ options: Optional[list[Union[int, float, str]]] = None,+ default_interval: Optional[Union[int, float, str]] = None,+ label: str = "",+ ) -> None:+ if default_interval and not isinstance(+ default_interval, (int, float, str)+ ):+ raise ValueError(+ "Invalid type: `default_interval` must be "+ + "an int, float or str, not %s" % type(default_interval)+ )++ # If no options are provided and default_interval is provided,+ if options is None:+ resolved_options = [default_interval] if default_interval else []+ else:+ resolved_options = options++ if not isinstance(resolved_options, list):+ raise ValueError(+ "Invalid type: `options` must be a list, not %s"+ % type(resolved_options)+ )++ # If has options and default_interval is provided,+ # check that default_interval is in options.+ if (+ default_interval+ and len(resolved_options) > 0+ and (default_interval not in resolved_options)+ ):+ raise ValueError(+ "Invalid value: `default_interval` must be "+ + "one of the options, not %s" % default_interval+ )++ super().__init__(+ component_name=refresh.name,+ initial_value=0,+ label=label,+ args={+ "options": resolved_options,+ "default-interval": default_interval,+ },+ )++ def _convert_value(self, value: int) -> int:+ return valuediff --git a/marimo/_smoke_tests/refresh.py b/marimo/_smoke_tests/refresh.pynew file mode 100644index 0000000000..b1d95c10de--- /dev/null+++ b/marimo/_smoke_tests/refresh.py@@ -0,0 +1,53 @@+# Copyright 2023 Marimo. All rights reserved.+import marimo++__generated_with = "0.1.1"+app = marimo.App()+++def __():+ import marimo as mo+ import random+ return mo, random+++def __(mo):+ reset_button = mo.ui.button(label="Reset")+ reset_button+ return reset_button,+++def __(mo, random, reset_button):+ reset_button+ my_pick = random.randint(0, 10)+ mo.accordion({"My pick": my_pick})+ return my_pick,+++def __(mo):+ refresh = mo.ui.refresh(options=["1s", "10s", "1m"])+ mo.md(f"Choose an interval to guess {refresh}")+ return refresh,+++def __(mo, my_pick, random, refresh):+ refresh+ guess = random.randint(0, 10)+ mo.stop(+ guess == my_pick,+ mo.md(f"That is correct: {my_pick}").callout(kind="success"),+ )++ mo.md(f"Not correct, your guess was {random.randint(0, 10)}").callout(+ kind="warn"+ )+ return guess,+++if __name__ == "__main__":+ app.run()