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
feat: mo.ui.datetime, mo.ui.date_range (#2174)
Myles Scolnick0db3a6d3e96f
diff --git a/docs/api/inputs/date.md b/docs/api/inputs/date.mddeleted file mode 100644index b0e9fd82e0..0000000000--- a/docs/api/inputs/date.md+++ /dev/null@@ -1,21 +0,0 @@-# Date--```{eval-rst}-.. marimo-embed::- @app.cell- def __():- date = mo.ui.date(label="Start Date")- return-- @app.cell- def __():- mo.hstack([date, mo.md(f"Has value: {date.value}")])- return-```--```{eval-rst}-.. autoclass:: marimo.ui.date- :members:-- .. autoclasstoc:: marimo._plugins.ui._impl.input.date-```diff --git a/docs/api/inputs/dates.md b/docs/api/inputs/dates.mdnew file mode 100644index 0000000000..5bee30742c--- /dev/null+++ b/docs/api/inputs/dates.md@@ -0,0 +1,56 @@+# Dates++## Single date++```{eval-rst}+.. marimo-embed::+ @app.cell+ def __():+ date = mo.ui.date(label="Start Date")+ return++ @app.cell+ def __():+ mo.hstack([date, mo.md(f"Has value: {date.value}")])+ return+```++```{eval-rst}+.. autoclass:: marimo.ui.date+ :members:++ .. autoclasstoc:: marimo._plugins.ui._impl.input.date+```++## Date and time++```{eval-rst}+.. marimo-embed::+ @app.cell+ def __():+ datetime = mo.ui.datetime(label="Start Date")+ return++ @app.cell+ def __():+ mo.hstack([datetime, mo.md(f"Has value: {datetime.value}")])+ return+```++## Date range++````{eval-rst}+++```{eval-rst}+.. marimo-embed::+ @app.cell+ def __():+ date_range = mo.ui.date_range(label="Start Date")+ return++ @app.cell+ def __():+ mo.hstack([date_range, mo.md(f"Has value: {date_range.value}")])+ return+````diff --git a/docs/api/inputs/index.md b/docs/api/inputs/index.mdindex 3dcae25403..2a56eb4959 100644--- a/docs/api/inputs/index.md+++ b/docs/api/inputs/index.md@@ -12,7 +12,7 @@code_editordataframedata_explorer- date+ datesdictionarydropdownfile@@ -49,6 +49,8 @@ powerful notebooks and apps. These elements are available in `marimo.ui`.marimo.ui.dataframemarimo.ui.data_explorermarimo.ui.date+ marimo.ui.datetime+ marimo.ui.date_rangemarimo.ui.dictionarymarimo.ui.dropdownmarimo.ui.filediff --git a/examples/marimo/inputs.py b/examples/marimo/inputs.pyindex bdb201f1cd..68bee2b2bf 100644--- a/examples/marimo/inputs.py+++ b/examples/marimo/inputs.py@@ -1,6 +1,13 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "marimo",+# ]+# ///+import marimo-__generated_with = "0.8.5"+__generated_with = "0.8.7"app = marimo.App(width="medium")@@ -10,7 +17,7 @@ def __(mo):r"""# Inputs- There are many way that a user can input with your notebook, such as text boxes, sliders, dates, and more.+ There are many way that a user can input with your notebook, such as text boxes, sliders, dates, and more.""")return@@ -169,10 +176,20 @@ def __(mo):start=datetime.date(2020, 1, 1),stop=datetime.date(2020, 12, 31),)- mo.hstack([start_date, "➡️", end_date]).left()return datetime, end_date, start_date+def __(end_date, mo, start_date):+ mo.hstack(+ [+ mo.hstack([start_date, "➡️", end_date]).left(),+ mo.md(f"From {start_date.value} to {end_date.value}"),+ ]+ )+ return++@app.celldef __(mo):mo.md("""## Dropdowns""")diff --git a/frontend/package.json b/frontend/package.jsonindex cb1d7184fa..3ad5157275 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -33,6 +33,7 @@"@emotion/cache": "^11.13.1","@emotion/react": "^11.13.0","@hookform/resolvers": "^3.9.0",+ "@internationalized/date": "^3.5.5","@lezer/common": "^1.2.1","@lezer/highlight": "^1.2.1","@lezer/lr": "^1.4.2",@@ -113,7 +114,6 @@"react-arborist": "^3.4.0","react-aria-components": "^1.3.2","react-codemirror-merge": "^4.23.0",- "react-day-picker": "^8.10.1","react-dropzone": "^14.2.3","react-error-boundary": "^4.0.13","react-grid-layout": "^1.4.4",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex 138f91a24d..3f7a0cd4fd 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -65,6 +65,9 @@ dependencies:'@hookform/resolvers':specifier: ^3.9.0version: 3.9.0([email protected])+ '@internationalized/date':+ specifier: ^3.5.5+ version: 3.5.5'@lezer/common':specifier: ^1.2.1version: 1.2.1@@ -305,9 +308,6 @@ dependencies:react-codemirror-merge:specifier: ^4.23.0version: 4.23.0(@babel/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])([email protected])([email protected])([email protected])- react-day-picker:- specifier: ^8.10.1- version: 8.10.1([email protected])([email protected])react-dropzone:specifier: ^14.2.3version: 14.2.3([email protected])@@ -15841,16 +15841,6 @@ packages:react-dom: 18.3.1([email protected])dev: true- resolution: {integrity: sha512-TMx7fNbhLk15eqcMt+7Z7S2KF7mfTId/XJDjKE8f+IUcFn0l08/kI4FiYTL/0yuOLmEcbR4Fwe3GJf/NiiMnPA==}- peerDependencies:- date-fns: ^2.28.0 || ^3.0.0- react: ^16.8.0 || ^17.0.0 || ^18.0.0- dependencies:- date-fns: 3.6.0- react: 18.3.1- dev: false-resolution: {integrity: sha512-6ONeqEC3XKVf4eVmMTe0oPds+c5B9Foyj8p/ZKLb7kL2qh9COYxiBHv3szd6gztqi/efkmriywLUVlPotqoJyw==}dependencies:diff --git a/frontend/src/components/ui/aria-popover.tsx b/frontend/src/components/ui/aria-popover.tsxnew file mode 100644index 0000000000..bd2beb85d1--- /dev/null+++ b/frontend/src/components/ui/aria-popover.tsx@@ -0,0 +1,39 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { cn } from "@/utils/cn";+import {+ Dialog as AriaDialog,+ type DialogProps as AriaDialogProps,+ DialogTrigger as AriaDialogTrigger,+ Popover as AriaPopover,+ type PopoverProps as AriaPopoverProps,+ composeRenderProps,+} from "react-aria-components";++const PopoverTrigger = AriaDialogTrigger;++const Popover = ({ className, offset = 4, ...props }: AriaPopoverProps) => (+ <AriaPopover+ offset={offset}+ className={composeRenderProps(className, (className) =>+ cn(+ "z-50 rounded-md border bg-popover text-popover-foreground shadow-md outline-none",+ /* Entering */+ "data-[entering]:animate-in data-[entering]:fade-in-0 data-[entering]:zoom-in-95",+ /* Exiting */+ "data-[exiting]:animate-out data-[exiting]:fade-out-0 data-[exiting]:zoom-out-95",+ /* Placement */+ "data-[placement=bottom]:slide-in-from-top-2 data-[placement=left]:slide-in-from-right-2 data-[placement=right]:slide-in-from-left-2 data-[placement=top]:slide-in-from-bottom-2",+ className,+ ),+ )}+ {...props}+ />+);++const PopoverDialog = ({ className, ...props }: AriaDialogProps) => {+ return (+ <AriaDialog className={cn("p-4 outline outline-0", className)} {...props} />+ );+};++export { Popover, PopoverTrigger, PopoverDialog };diff --git a/frontend/src/components/ui/calendar.tsx b/frontend/src/components/ui/calendar.tsxindex ec4533a492..4d0f6f8eeb 100644--- a/frontend/src/components/ui/calendar.tsx+++ b/frontend/src/components/ui/calendar.tsx@@ -1,63 +1,231 @@/* Copyright 2024 Marimo. All rights reserved. */+import * as React from "react";+import { getLocalTimeZone, today } from "@internationalized/date";import { ChevronLeft, ChevronRight } from "lucide-react";-import { DayPicker } from "react-day-picker";+import {+ Button as AriaButton,+ Calendar as AriaCalendar,+ CalendarCell as AriaCalendarCell,+ type CalendarCellProps as AriaCalendarCellProps,+ CalendarGrid as AriaCalendarGrid,+ CalendarGridBody as AriaCalendarGridBody,+ type CalendarGridBodyProps as AriaCalendarGridBodyProps,+ CalendarGridHeader as AriaCalendarGridHeader,+ type CalendarGridHeaderProps as AriaCalendarGridHeaderProps,+ type CalendarGridProps as AriaCalendarGridProps,+ CalendarHeaderCell as AriaCalendarHeaderCell,+ type CalendarHeaderCellProps as AriaCalendarHeaderCellProps,+ type CalendarProps as AriaCalendarProps,+ type DateValue as AriaDateValue,+ Heading as AriaHeading,+ RangeCalendar as AriaRangeCalendar,+ type RangeCalendarProps as AriaRangeCalendarProps,+ RangeCalendarStateContext as AriaRangeCalendarStateContext,+ composeRenderProps,+ Text,+ useLocale,+} from "react-aria-components";-import { cn } from "@/utils/cn";import { buttonVariants } from "@/components/ui/button";+import { cn } from "@/utils/cn";-export type CalendarProps = React.ComponentProps<typeof DayPicker>;+const CalendarHeading = (props: React.HTMLAttributes<HTMLElement>) => {+ const { direction } = useLocale();++ return (+ <header className="flex w-full items-center gap-1 px-1 pb-4" {...props}>+ <AriaButton+ slot="previous"+ className={cn(+ buttonVariants({ variant: "outline" }),+ "size-7 bg-transparent p-0 opacity-50",+ /* Hover */+ "data-[hovered]:opacity-100",+ )}+ >+ {direction === "rtl" ? (+ <ChevronRight aria-hidden={true} className="size-4" />+ ) : (+ <ChevronLeft aria-hidden={true} className="size-4" />+ )}+ </AriaButton>+ <AriaHeading className="grow text-center text-sm font-medium" />+ <AriaButton+ slot="next"+ className={cn(+ buttonVariants({ variant: "outline" }),+ "size-7 bg-transparent p-0 opacity-50",+ /* Hover */+ "data-[hovered]:opacity-100",+ )}+ >+ {direction === "rtl" ? (+ <ChevronLeft aria-hidden={true} className="size-4" />+ ) : (+ <ChevronRight aria-hidden={true} className="size-4" />+ )}+ </AriaButton>+ </header>+ );+};-const Calendar = ({+const CalendarGrid = ({ className, ...props }: AriaCalendarGridProps) => (+ <AriaCalendarGrid+ className={cn(+ " border-separate border-spacing-x-0 border-spacing-y-1 ",+ className,+ )}+ {...props}+ />+);++const CalendarGridHeader = ({ ...props }: AriaCalendarGridHeaderProps) => (+ <AriaCalendarGridHeader {...props} />+);++const CalendarHeaderCell = ({+ className,+ ...props+}: AriaCalendarHeaderCellProps) => (+ <AriaCalendarHeaderCell+ className={cn(+ "w-9 rounded-md text-[0.8rem] font-normal text-muted-foreground",+ className,+ )}+ {...props}+ />+);++const CalendarGridBody = ({className,- classNames,- showOutsideDays = true,...props-}: CalendarProps) => {+}: AriaCalendarGridBodyProps) => (+ <AriaCalendarGridBody className={cn("[&>tr>td]:p-0", className)} {...props} />+);++const CalendarCell = ({ className, ...props }: AriaCalendarCellProps) => {+ const isRange = Boolean(React.useContext(AriaRangeCalendarStateContext));return (- <DayPicker- showOutsideDays={showOutsideDays}- className={cn("p-3", className)}- classNames={{- months: "flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",- month: "space-y-4",- caption: "flex justify-center pt-1 relative items-center",- caption_label: "text-sm font-medium",- nav: "space-x-1 flex items-center",- nav_button: cn(- buttonVariants({ variant: "outline" }),- "h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100",- ),- nav_button_previous: "absolute left-1",- nav_button_next: "absolute right-1",- table: "w-full border-collapse space-y-1",- head_row: "flex",- head_cell:- "text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",- row: "flex w-full mt-2",- cell: "text-center text-sm p-0 relative [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",- day: cn(+ <AriaCalendarCell+ className={composeRenderProps(className, (className, renderProps) =>+ cn(buttonVariants({ variant: "ghost" }),- "h-9 w-9 p-0 font-normal aria-selected:opacity-100",+ "relative flex size-9 items-center justify-center p-0 text-sm font-normal",+ /* Disabled */+ renderProps.isDisabled && "text-muted-foreground opacity-50",+ /* Selected */+ renderProps.isSelected &&+ "bg-primary text-primary-foreground data-[focused]:bg-primary data-[focused]:text-primary-foreground",+ /* Hover */+ renderProps.isHovered &&+ renderProps.isSelected &&+ (renderProps.isSelectionStart ||+ renderProps.isSelectionEnd ||+ !isRange) &&+ "data-[hovered]:bg-primary data-[hovered]:text-primary-foreground",+ /* Selection Start/End */+ renderProps.isSelected &&+ isRange &&+ !renderProps.isSelectionStart &&+ !renderProps.isSelectionEnd &&+ "rounded-none bg-accent text-accent-foreground",+ /* Outside Month */+ renderProps.isOutsideMonth &&+ "text-muted-foreground opacity-50 data-[selected]:bg-accent/50 data-[selected]:text-muted-foreground data-[selected]:opacity-30",+ /* Current Date */+ renderProps.date.compare(today(getLocalTimeZone())) === 0 &&+ !renderProps.isSelected &&+ "bg-accent text-accent-foreground",+ /* Unavailable Date */+ renderProps.isUnavailable && "cursor-default text-destructive ",+ renderProps.isInvalid &&+ "bg-destructive text-destructive-foreground data-[focused]:bg-destructive data-[hovered]:bg-destructive data-[focused]:text-destructive-foreground data-[hovered]:text-destructive-foreground",+ className,),- day_selected:- "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",- day_today: "bg-accent text-accent-foreground",- day_outside: "text-muted-foreground opacity-50",- day_disabled: "text-muted-foreground opacity-50",- day_range_middle:- "aria-selected:bg-accent aria-selected:text-accent-foreground",- day_hidden: "invisible",- ...classNames,- }}- components={{- IconLeft: ({ ...props }) => <ChevronLeft className="h-4 w-4" />,- IconRight: ({ ...props }) => <ChevronRight className="h-4 w-4" />,- }}+ )}{...props}/>);};-Calendar.displayName = "Calendar";-export { Calendar };+interface CalendarProps<T extends AriaDateValue> extends AriaCalendarProps<T> {+ errorMessage?: string;+}++const Calendar = <T extends AriaDateValue>({+ errorMessage,+ className,+ ...props+}: CalendarProps<T>) => {+ return (+ <AriaCalendar+ className={composeRenderProps(className, (className) =>+ cn("w-fit", className),+ )}+ {...props}+ >+ <CalendarHeading />+ <CalendarGrid>+ <CalendarGridHeader>+ {(day) => <CalendarHeaderCell>{day}</CalendarHeaderCell>}+ </CalendarGridHeader>+ <CalendarGridBody>+ {(date) => <CalendarCell date={date} />}+ </CalendarGridBody>+ </CalendarGrid>+ {errorMessage && (+ <Text className="text-sm text-destructive" slot="errorMessage">+ {errorMessage}+ </Text>+ )}+ </AriaCalendar>+ );+};++interface RangeCalendarProps<T extends AriaDateValue>+ extends AriaRangeCalendarProps<T> {+ errorMessage?: string;+}++const RangeCalendar = <T extends AriaDateValue>({+ errorMessage,+ className,+ ...props+}: RangeCalendarProps<T>) => {+ return (+ <AriaRangeCalendar+ className={composeRenderProps(className, (className) =>+ cn("w-fit", className),+ )}+ {...props}+ >+ <CalendarHeading />+ <CalendarGrid>+ <CalendarGridHeader>+ {(day) => <CalendarHeaderCell>{day}</CalendarHeaderCell>}+ </CalendarGridHeader>+ <CalendarGridBody>+ {(date) => <CalendarCell date={date} />}+ </CalendarGridBody>+ </CalendarGrid>+ {errorMessage && (+ <Text slot="errorMessage" className="text-sm text-destructive">+ {errorMessage}+ </Text>+ )}+ </AriaRangeCalendar>+ );+};++export {+ Calendar,+ CalendarCell,+ CalendarGrid,+ CalendarGridBody,+ CalendarGridHeader,+ CalendarHeaderCell,+ CalendarHeading,+ RangeCalendar,+};+export type { CalendarProps, RangeCalendarProps };diff --git a/frontend/src/components/ui/date-input.tsx b/frontend/src/components/ui/date-input.tsxnew file mode 100644index 0000000000..4460e8fe86--- /dev/null+++ b/frontend/src/components/ui/date-input.tsx@@ -0,0 +1,128 @@+/* Copyright 2024 Marimo. All rights reserved. */+import type { VariantProps } from "class-variance-authority";+import {+ DateField as AriaDateField,+ type DateFieldProps as AriaDateFieldProps,+ DateInput as AriaDateInput,+ type DateInputProps as AriaDateInputProps,+ DateSegment as AriaDateSegment,+ type DateSegmentProps as AriaDateSegmentProps,+ type DateValue as AriaDateValue,+ TimeField as AriaTimeField,+ type TimeFieldProps as AriaTimeFieldProps,+ type TimeValue as AriaTimeValue,+ type ValidationResult as AriaValidationResult,+ composeRenderProps,+ Text,+} from "react-aria-components";++import { FieldError, fieldGroupVariants, Label } from "./field";+import { cn } from "@/utils/cn";++const DateSegment = ({ className, ...props }: AriaDateSegmentProps) => {+ return (+ <AriaDateSegment+ className={composeRenderProps(className, (className) =>+ cn(+ "type-literal:px-0 inline rounded p-0.5 caret-transparent outline outline-0",+ /* Placeholder */+ "data-[placeholder]:text-muted-foreground",+ /* Disabled */+ "data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",+ /* Focused */+ "data-[focused]:bg-accent data-[focused]:text-accent-foreground focus:bg-accent focus:text-accent-foreground",+ /* Invalid */+ "data-[invalid]:data-[focused]:bg-destructive data-[invalid]:data-[focused]:data-[placeholder]:text-destructive-foreground data-[invalid]:data-[focused]:text-destructive-foreground data-[invalid]:data-[placeholder]:text-destructive data-[invalid]:text-destructive",+ className,+ ),+ )}+ {...props}+ />+ );+};++interface DateInputProps+ extends AriaDateInputProps,+ VariantProps<typeof fieldGroupVariants> {}++const DateInput = ({+ className,+ variant,+ ...props+}: Omit<DateInputProps, "children">) => {+ return (+ <AriaDateInput+ className={composeRenderProps(className, (className) =>+ cn(fieldGroupVariants({ variant }), "text-sm", className),+ )}+ {...props}+ >+ {(segment) => <DateSegment segment={segment} />}+ </AriaDateInput>+ );+};++interface DateFieldProps<T extends AriaDateValue>+ extends AriaDateFieldProps<T> {+ label?: string;+ description?: string;+ errorMessage?: string | ((validation: AriaValidationResult) => string);+}++const DateField = <T extends AriaDateValue>({+ label,+ description,+ className,+ errorMessage,+ ...props+}: DateFieldProps<T>) => {+ return (+ <AriaDateField+ className={composeRenderProps(className, (className) =>+ cn("group flex flex-col gap-2", className),+ )}+ {...props}+ >+ <Label>{label}</Label>+ <DateInput />+ {description && (+ <Text className="text-sm text-muted-foreground" slot="description">+ {description}+ </Text>+ )}+ <FieldError>{errorMessage}</FieldError>+ </AriaDateField>+ );+};++interface TimeFieldProps<T extends AriaTimeValue>+ extends AriaTimeFieldProps<T> {+ label?: string;+ description?: string;+ errorMessage?: string | ((validation: AriaValidationResult) => string);+}++const TimeField = <T extends AriaTimeValue>({+ label,+ description,+ errorMessage,+ className,+ ...props+}: TimeFieldProps<T>) => {+ return (+ <AriaTimeField+ className={composeRenderProps(className, (className) =>+ cn("group flex flex-col gap-2", className),+ )}+ {...props}+ >+ <Label>{label}</Label>+ <DateInput />+ {description && <Text slot="description">{description}</Text>}+ <FieldError>{errorMessage}</FieldError>+ </AriaTimeField>+ );+};++export { DateSegment, DateInput, DateField, TimeField };+export type { DateInputProps, DateFieldProps, TimeFieldProps };diff --git a/frontend/src/components/ui/date-picker.tsx b/frontend/src/components/ui/date-picker.tsxnew file mode 100644index 0000000000..c666f1b4f2--- /dev/null+++ b/frontend/src/components/ui/date-picker.tsx@@ -0,0 +1,172 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { CalendarIcon } from "lucide-react";+import {+ DatePicker as AriaDatePicker,+ type DatePickerProps as AriaDatePickerProps,+ DateRangePicker as AriaDateRangePicker,+ Dialog as AriaDialog,+ Button as AriaButton,+ type DateRangePickerProps as AriaDateRangePickerProps,+ type DateValue as AriaDateValue,+ type DialogProps as AriaDialogProps,+ type PopoverProps as AriaPopoverProps,+ type ValidationResult as AriaValidationResult,+ composeRenderProps,+ Text,+} from "react-aria-components";++import { buttonVariants } from "./button";+import {+ Calendar,+ CalendarCell,+ CalendarGrid,+ CalendarGridBody,+ CalendarGridHeader,+ CalendarHeaderCell,+ CalendarHeading,+ RangeCalendar,+} from "./calendar";+import { cn } from "@/utils/cn";+import { FieldGroup, FieldError, Label } from "./field";+import { DateInput } from "./date-input";+import { Popover } from "./aria-popover";++const DatePickerContent = ({+ className,+ popoverClassName,+ ...props+}: AriaDialogProps & { popoverClassName?: AriaPopoverProps["className"] }) => (+ <Popover+ className={composeRenderProps(popoverClassName, (className) =>+ cn("w-auto p-3", className),+ )}+ >+ <AriaDialog+ className={cn(+ "flex w-full flex-col space-y-4 outline-none sm:flex-row sm:space-x-4 sm:space-y-0",+ className,+ )}+ {...props}+ />+ </Popover>+);++interface DatePickerProps<T extends AriaDateValue>+ extends AriaDatePickerProps<T> {+ label?: string;+ description?: string;+ errorMessage?: string | ((validation: AriaValidationResult) => string);+}++const DatePicker = <T extends AriaDateValue>({+ label,+ description,+ errorMessage,+ className,+ ...props+}: DatePickerProps<T>) => {+ return (+ <AriaDatePicker+ className={composeRenderProps(className, (className) =>+ cn("group flex flex-col gap-2", className),+ )}+ {...props}+ >+ {label && <Label>{label}</Label>}+ <FieldGroup>+ <DateInput aria-label="date input" className="flex-1" variant="ghost" />+ <AriaButton+ className={cn(+ buttonVariants({ variant: "text", size: "icon" }),+ "ml-1 size-6 data-[focus-visible]:ring-offset-0",+ )}+ >+ <CalendarIcon aria-hidden={true} className="size-4" />+ </AriaButton>+ </FieldGroup>+ {description && (+ <Text className="text-sm text-muted-foreground" slot="description">+ {description}+ </Text>+ )}+ <FieldError>{errorMessage}</FieldError>+ <DatePickerContent>+ <Calendar>+ <CalendarHeading />+ <CalendarGrid>+ <CalendarGridHeader>+ {(day) => <CalendarHeaderCell>{day}</CalendarHeaderCell>}+ </CalendarGridHeader>+ <CalendarGridBody>+ {(date) => <CalendarCell date={date} />}+ </CalendarGridBody>+ </CalendarGrid>+ </Calendar>+ </DatePickerContent>+ </AriaDatePicker>+ );+};++interface DateRangePickerProps<T extends AriaDateValue>+ extends AriaDateRangePickerProps<T> {+ label?: string;+ description?: string;+ errorMessage?: string | ((validation: AriaValidationResult) => string);+}++const DateRangePicker = <T extends AriaDateValue>({+ label,+ description,+ errorMessage,+ className,+ ...props+}: DateRangePickerProps<T>) => {+ return (+ <AriaDateRangePicker+ className={composeRenderProps(className, (className) =>+ cn("group flex flex-col gap-2", className),+ )}+ {...props}+ >+ <Label>{label}</Label>+ <FieldGroup>+ <DateInput variant="ghost" slot={"start"} />+ <span aria-hidden={true} className="px-2 text-sm text-muted-foreground">+ -+ </span>+ <DateInput className="flex-1" variant="ghost" slot={"end"} />++ <AriaButton+ className={cn(+ buttonVariants({ variant: "text", size: "icon" }),+ "ml-1 size-6 data-[focus-visible]:ring-offset-0",+ )}+ >+ <CalendarIcon aria-hidden={true} className="size-4" />+ </AriaButton>+ </FieldGroup>+ {description && (+ <Text className="text-sm text-muted-foreground" slot="description">+ {description}+ </Text>+ )}+ <FieldError>{errorMessage}</FieldError>+ <DatePickerContent>+ <RangeCalendar>+ <CalendarHeading />+ <CalendarGrid>+ <CalendarGridHeader>+ {(day) => <CalendarHeaderCell>{day}</CalendarHeaderCell>}+ </CalendarGridHeader>+ <CalendarGridBody>+ {(date) => <CalendarCell date={date} />}+ </CalendarGridBody>+ </CalendarGrid>+ </RangeCalendar>+ </DatePickerContent>+ </AriaDateRangePicker>+ );+};++export { DatePicker, DatePickerContent, DateRangePicker };+export type { DatePickerProps, DateRangePickerProps };diff --git a/frontend/src/components/ui/field.tsx b/frontend/src/components/ui/field.tsxnew file mode 100644index 0000000000..45680c93c5--- /dev/null+++ b/frontend/src/components/ui/field.tsx@@ -0,0 +1,89 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { cn } from "@/utils/cn";+import { cva, type VariantProps } from "class-variance-authority";+import {+ FieldError as AriaFieldError,+ type FieldErrorProps as AriaFieldErrorProps,+ Group as AriaGroup,+ type GroupProps as AriaGroupProps,+ Label as AriaLabel,+ type LabelProps as AriaLabelProps,+ Text as AriaText,+ type TextProps as AriaTextProps,+ composeRenderProps,+} from "react-aria-components";+import { selectStyles } from "./native-select";++const labelVariants = cva([+ "text-sm font-medium leading-none",+ /* Disabled */+ "data-[disabled]:cursor-not-allowed data-[disabled]:opacity-70",+ /* Invalid */+ "group-data-[invalid]:text-destructive",+]);++const Label = ({ className, ...props }: AriaLabelProps) => (+ <AriaLabel className={cn(labelVariants(), className)} {...props} />+);++const FormDescription = ({ className, ...props }: AriaTextProps) => {+ return (+ <AriaText+ className={cn("text-sm text-muted-foreground", className)}+ {...props}+ slot="description"+ />+ );+};++const FieldError = ({ className, ...props }: AriaFieldErrorProps) => {+ return (+ <AriaFieldError+ className={cn("text-sm font-medium text-destructive", className)}+ {...props}+ />+ );+};++const fieldGroupVariants = cva("", {+ variants: {+ variant: {+ default: [+ "relative flex w-full items-center overflow-hidden rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background",+ selectStyles(),+ /* Focus Within */+ "data-[focus-within]:outline-none data-[focus-within]:ring-2 data-[focus-within]:ring-ring data-[focus-within]:ring-offset-2",+ /* Disabled */+ "data-[disabled]:opacity-50",+ ],+ ghost: "",+ },+ },+ defaultVariants: {+ variant: "default",+ },+});++interface GroupProps+ extends AriaGroupProps,+ VariantProps<typeof fieldGroupVariants> {}++const FieldGroup = ({ className, variant, ...props }: GroupProps) => {+ return (+ <AriaGroup+ className={composeRenderProps(className, (className) =>+ cn(fieldGroupVariants({ variant }), className),+ )}+ {...props}+ />+ );+};++export {+ Label,+ labelVariants,+ FieldGroup,+ fieldGroupVariants,+ FieldError,+ FormDescription,+};diff --git a/frontend/src/core/MarimoApp.tsx b/frontend/src/core/MarimoApp.tsxindex 8eb9734a71..31920c2405 100644--- a/frontend/src/core/MarimoApp.tsx+++ b/frontend/src/core/MarimoApp.tsx@@ -9,7 +9,6 @@ import { ErrorBoundary } from "../components/editor/boundary/ErrorBoundary";import { TooltipProvider } from "../components/ui/tooltip";import { Toaster } from "../components/ui/toaster";import { ModalProvider } from "../components/modal/ImperativeModal";-import { DayPickerProvider } from "react-day-picker";import { useAppConfig, useUserConfig } from "@/core/config/config";import { initialMode } from "./mode";import { CssVariables } from "@/theme/ThemeProvider";@@ -85,15 +84,13 @@ const Providers = memo(({ children }: PropsWithChildren) => {<ErrorBoundary><Suspense><TooltipProvider delayDuration={400}>- <DayPickerProvider initialProps={{}}>- <SlotzProvider controller={slotsController}>- <ModalProvider>- {children}- <Toaster />- <TailwindIndicator />- </ModalProvider>- </SlotzProvider>- </DayPickerProvider>+ <SlotzProvider controller={slotsController}>+ <ModalProvider>+ {children}+ <Toaster />+ <TailwindIndicator />+ </ModalProvider>+ </SlotzProvider></TooltipProvider></Suspense></ErrorBoundary>diff --git a/frontend/src/plugins/impl/DatePickerPlugin.tsx b/frontend/src/plugins/impl/DatePickerPlugin.tsxindex 9a65b35202..ebf18f19dd 100644--- a/frontend/src/plugins/impl/DatePickerPlugin.tsx+++ b/frontend/src/plugins/impl/DatePickerPlugin.tsx@@ -1,11 +1,10 @@/* Copyright 2024 Marimo. All rights reserved. */-import { useId, useRef } from "react";import { z } from "zod";import type { IPlugin, IPluginProps, Setter } from "../types";-import { Input } from "../../components/ui/input";+import { DatePicker } from "@/components/ui/date-picker";+import { type CalendarDate, parseDate } from "@internationalized/date";import { Labeled } from "./common/labeled";-import { cn } from "@/utils/cn";type T = string;@@ -18,7 +17,7 @@ interface Data {}export class DatePickerPlugin implements IPlugin<T, Data> {- tagName = "marimo-date-picker";+ tagName = "marimo-date";validator = z.object({initialValue: z.string(),@@ -31,7 +30,7 @@ export class DatePickerPlugin implements IPlugin<T, Data> {render(props: IPluginProps<T, Data>): JSX.Element {return (- <DatePicker+ <DatePickerComponent{...props.data}value={props.value}setValue={props.setValue}@@ -45,41 +44,25 @@ interface DatePickerProps extends Data {setValue: Setter<T>;}-const DatePicker = (props: DatePickerProps): JSX.Element => {- const inputRef = useRef<HTMLInputElement>(null);- const handleInput = () => {- const input = inputRef.current;- if (input?.valueAsDate) {- // basic bounds validation; browser validation is lacking- // when the input's value changes due to keyboard events- let valueAsDate = input.valueAsDate;- const minDate = new Date(props.start);- valueAsDate = valueAsDate < minDate ? minDate : valueAsDate;- const maxDate = new Date(props.stop);- valueAsDate = valueAsDate > maxDate ? maxDate : valueAsDate;- const isoStr = valueAsDate.toISOString();- // isoStr is of the form YYYY-MM-DDTHH...- const newValue = isoStr.slice(0, isoStr.indexOf("T"));- props.setValue(newValue);+const DatePickerComponent = (props: DatePickerProps): JSX.Element => {+ const handleInput = (valueAsDate: CalendarDate) => {+ if (!valueAsDate) {+ return;}- };- const id = useId();+ const isoStr = valueAsDate.toString();+ props.setValue(isoStr);+ };return (- <Labeled label={props.label} id={id} fullWidth={props.fullWidth}>- <Input- data-testid="marimo-plugin-date-picker"- ref={inputRef}- type="date"- className={cn({- "w-full": props.fullWidth,- })}- min={props.start}- max={props.stop}- value={props.value}- onInput={handleInput}- id={id}+ <Labeled label={props.label} fullWidth={props.fullWidth}>+ <DatePicker+ granularity="day"+ value={parseDate(props.value)}+ onChange={handleInput}+ aria-label={props.label ?? "date picker"}+ minValue={parseDate(props.start)}+ maxValue={parseDate(props.stop)}/></Labeled>);diff --git a/frontend/src/plugins/impl/DateRangePlugin.tsx b/frontend/src/plugins/impl/DateRangePlugin.tsxnew file mode 100644index 0000000000..3ca9b454c8--- /dev/null+++ b/frontend/src/plugins/impl/DateRangePlugin.tsx@@ -0,0 +1,76 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { z } from "zod";++import type { IPlugin, IPluginProps, Setter } from "../types";+import { DateRangePicker } from "@/components/ui/date-picker";+import { type CalendarDate, parseDate } from "@internationalized/date";+import { Labeled } from "./common/labeled";++type T = [string, string];++interface Data {+ label: string | null;+ start: string;+ stop: string;+ step?: string;+ fullWidth: boolean;+}++export class DateRangePickerPlugin implements IPlugin<T, Data> {+ tagName = "marimo-date-range";++ validator = z.object({+ initialValue: z.tuple([z.string(), z.string()]),+ label: z.string().nullable(),+ start: z.string(),+ stop: z.string(),+ step: z.string().optional(),+ fullWidth: z.boolean().default(false),+ });++ render(props: IPluginProps<T, Data>): JSX.Element {+ return (+ <DateRangePickerComponent+ {...props.data}+ value={props.value}+ setValue={props.setValue}+ />+ );+ }+}++interface DateRangePickerProps extends Data {+ value: T;+ setValue: Setter<T>;+}++const DateRangePickerComponent = (props: DateRangePickerProps): JSX.Element => {+ const handleInput = (valueAsDateRange: {+ start: CalendarDate;+ end: CalendarDate;+ }) => {+ if (!valueAsDateRange) {+ return;+ }++ const { start, end } = valueAsDateRange;+ const isoStrRange: T = [start.toString(), end.toString()];+ props.setValue(isoStrRange);+ };++ return (+ <Labeled label={props.label} fullWidth={props.fullWidth}>+ <DateRangePicker+ granularity="day"+ value={{+ start: parseDate(props.value[0]),+ end: parseDate(props.value[1]),+ }}+ onChange={handleInput}+ aria-label={props.label ?? "date range picker"}+ minValue={parseDate(props.start)}+ maxValue={parseDate(props.stop)}+ />+ </Labeled>+ );+};diff --git a/frontend/src/plugins/impl/DateTimePickerPlugin.tsx b/frontend/src/plugins/impl/DateTimePickerPlugin.tsxnew file mode 100644index 0000000000..2d607bd279--- /dev/null+++ b/frontend/src/plugins/impl/DateTimePickerPlugin.tsx@@ -0,0 +1,69 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { z } from "zod";++import type { IPlugin, IPluginProps, Setter } from "../types";+import { DatePicker } from "@/components/ui/date-picker";+import { type CalendarDateTime, parseDateTime } from "@internationalized/date";+import { Labeled } from "./common/labeled";++type T = string;++interface Data {+ label: string | null;+ start: string;+ stop: string;+ step?: string;+ fullWidth: boolean;+}++export class DateTimePickerPlugin implements IPlugin<T, Data> {+ tagName = "marimo-datetime";++ validator = z.object({+ initialValue: z.string(),+ label: z.string().nullable(),+ start: z.string(),+ stop: z.string(),+ step: z.string().optional(),+ fullWidth: z.boolean().default(false),+ });++ render(props: IPluginProps<T, Data>): JSX.Element {+ return (+ <DateTimePickerComponent+ {...props.data}+ value={props.value}+ setValue={props.setValue}+ />+ );+ }+}++interface DateTimePickerProps extends Data {+ value: T;+ setValue: Setter<T>;+}++const DateTimePickerComponent = (props: DateTimePickerProps): JSX.Element => {+ const handleInput = (valueAsDateTime: CalendarDateTime) => {+ if (!valueAsDateTime) {+ return;+ }++ const isoStr = valueAsDateTime.toString();+ props.setValue(isoStr);+ };++ return (+ <Labeled label={props.label} fullWidth={props.fullWidth}>+ <DatePicker+ granularity="minute"+ value={parseDateTime(props.value)}+ onChange={handleInput}+ aria-label={props.label ?? "date time picker"}+ minValue={parseDateTime(props.start)}+ maxValue={parseDateTime(props.stop)}+ />+ </Labeled>+ );+};diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.tsindex e135b59f39..0a648f46cb 100644--- a/frontend/src/plugins/plugins.ts+++ b/frontend/src/plugins/plugins.ts@@ -43,6 +43,8 @@ import { LazyPlugin } from "./layout/LazyPlugin";import { NavigationMenuPlugin } from "@/plugins/layout/NavigationMenuPlugin";import { initializeSidebarElement } from "./core/sidebar-element";import { RoutesPlugin } from "./layout/RoutesPlugin";+import { DateTimePickerPlugin } from "./impl/DateTimePickerPlugin";+import { DateRangePickerPlugin } from "./impl/DateRangePlugin";// List of UI pluginsexport const UI_PLUGINS: Array<IPlugin<any, unknown>> = [@@ -50,6 +52,8 @@ export const UI_PLUGINS: Array<IPlugin<any, unknown>> = [new CheckboxPlugin(),DataTablePlugin,new DatePickerPlugin(),+ new DateTimePickerPlugin(),+ new DateRangePickerPlugin(),new DictPlugin(),new CodeEditorPlugin(),new DropdownPlugin(),diff --git a/marimo/_data/series.py b/marimo/_data/series.pyindex 9828cf5ccd..5358f804fd 100644--- a/marimo/_data/series.py+++ b/marimo/_data/series.py@@ -140,3 +140,40 @@ def get_date_series_info(series: Any) -> DateSeriesInfo:)raise ValueError("Unsupported series type. Expected pandas or polars.")+++def get_datetime_series_info(series: Any) -> DateSeriesInfo:+ """+ Get the summary of a datetime series.+ """++ def validate_datetime(value: Any) -> str:+ if isinstance(value, datetime.datetime):+ return value.strftime("%Y-%m-%dT%H:%M:%S")+ if isinstance(value, datetime.date):+ # Convert date to datetime+ value = datetime.datetime(value.year, value.month, value.day)+ return value.strftime("%Y-%m-%d")+ raise ValueError("Expected a datetime. Got: " + str(type(value)))++ if DependencyManager.pandas.has():+ import pandas as pd++ if isinstance(series, pd.Series):+ return DateSeriesInfo(+ min=validate_datetime(series.min()),+ max=validate_datetime(series.max()),+ label=_get_name(series),+ )++ if DependencyManager.polars.has():+ import polars as pl++ if isinstance(series, pl.Series):+ return DateSeriesInfo(+ min=validate_datetime(series.min()),+ max=validate_datetime(series.max()),+ label=_get_name(series),+ )++ raise ValueError("Unsupported series type. Expected pandas or polars.")diff --git a/marimo/_plugins/ui/__init__.py b/marimo/_plugins/ui/__init__.pyindex a0b0ac9c46..fbf8ee5a32 100644--- a/marimo/_plugins/ui/__init__.py+++ b/marimo/_plugins/ui/__init__.py@@ -4,6 +4,8 @@This module contains a library of interactive UI elements."""+from __future__ import annotations+__all__ = ["altair_chart","array",@@ -13,6 +15,8 @@ __all__ = ["code_editor","data_explorer","date",+ "date_range",+ "datetime","dataframe","dictionary","dropdown",@@ -41,13 +45,17 @@ from marimo._plugins.ui._impl.array import arrayfrom marimo._plugins.ui._impl.batch import batchfrom marimo._plugins.ui._impl.data_explorer import data_explorerfrom marimo._plugins.ui._impl.dataframes.dataframe import dataframe+from marimo._plugins.ui._impl.dates import (+ date,+ date_range,+ datetime,+)from marimo._plugins.ui._impl.dictionary import dictionaryfrom marimo._plugins.ui._impl.from_anywidget import anywidgetfrom marimo._plugins.ui._impl.input import (button,checkbox,code_editor,- date,dropdown,file,file_browser,diff --git a/marimo/_plugins/ui/_impl/dates.py b/marimo/_plugins/ui/_impl/dates.pynew file mode 100644index 0000000000..1069376a76--- /dev/null+++ b/marimo/_plugins/ui/_impl/dates.py@@ -0,0 +1,415 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++import datetime as dt+from typing import (+ Any,+ Callable,+ Final,+ Optional,+ Tuple,+ Union,+ cast,+)++from marimo import _loggers+from marimo._data.series import (+ DataFrameSeries,+ get_date_series_info,+ get_datetime_series_info,+)+from marimo._output.rich_help import mddoc+from marimo._plugins.ui._core.ui_element import UIElement++LOGGER = _loggers.marimo_logger()++Numeric = Union[int, float]+++@mddoc+class date(UIElement[str, dt.date]):+ """+ A date picker with an optional start and stop date.++ **Example.**++ ```python+ # initialize the date picker at a given date+ date = mo.ui.date(value="2022-01-01")+ ```++ ```python+ # when value is omitted, date picker initializes with today's date+ date = mo.ui.date()+ ```++ ```python+ # create a date picker with bounds+ date = mo.ui.date(+ value="2022-06-01",+ start="2022-01-01",+ stop="2022-12-31",+ )+ ```++ Or from a dataframe series:++ ```python+ date = mo.ui.date.from_series(df["column_name"])+ ```++ **Attributes.**++ - `value`: a str (YYYY-MM-DD) or `datetime.date` object of the chosen date+ - `start`: the start date+ - `stop`: the stop date++ **Initialization Args.**++ - `start`: minimum date selectable; if None, defaults to 01-01-0001+ - `stop`: maximum date selectable; if None, defaults to 12-31-9999+ - `value`: default date+ - if `None` and `start` and `stop` are `None`, defaults to the+ current day;+ - else if `None` and `start` is not `None`, defaults to `start`;+ - else if `None` and `stop` is not `None`, defaults to `stop`+ - `label`: text label for the element+ - `on_change`: optional callback to run when this element's value changes+ - `full_width`: whether the input should take up the full width of its+ container+ """++ _name: Final[str] = "marimo-date"++ DATE_FORMAT = "%Y-%m-%d"++ def __init__(+ self,+ start: Optional[dt.date | str] = None,+ stop: Optional[dt.date | str] = None,+ value: Optional[dt.date | str] = None,+ *,+ label: str = "",+ on_change: Optional[Callable[[dt.date], None]] = None,+ full_width: bool = False,+ ) -> None:+ if isinstance(start, str):+ start = self._convert_value(start)+ if isinstance(stop, str):+ stop = self._convert_value(stop)+ if isinstance(value, str):+ value = self._convert_value(value)++ if value is None:+ if start is None and stop is None:+ value = dt.date.today()+ elif start is not None:+ value = start+ else:+ value = stop+ value = cast(dt.date, value)++ self._start = dt.date(dt.MINYEAR, 1, 1) if start is None else start+ self._stop = dt.date(dt.MAXYEAR, 12, 31) if stop is None else stop++ if self._stop < self._start:+ raise ValueError(+ f"The stop date ({stop}) must be greater than "+ f"the start date ({start})"+ )+ elif value < self._start or value > self._stop:+ raise ValueError(+ f"The default value ({value}) must be greater than "+ f"the start date ({start}) and less than the stop "+ f"date ({stop})."+ )++ super().__init__(+ component_name=date._name,+ initial_value=value.isoformat(),+ label=label,+ args={+ "start": self._start.isoformat(),+ "stop": self._stop.isoformat(),+ "full-width": full_width,+ },+ on_change=on_change,+ )++ @staticmethod+ def from_series(series: DataFrameSeries, **kwargs: Any) -> "date":+ """Create a date picker from a dataframe series."""+ info = get_date_series_info(series)+ start = kwargs.pop("start", info.min)+ stop = kwargs.pop("stop", info.max)+ label = kwargs.pop("label", info.label)+ return date(start=start, stop=stop, label=label, **kwargs)++ def _convert_value(self, value: str) -> dt.date:+ # Catch different initialization formats+ if isinstance(value, dt.date):+ return value+ if isinstance(value, dt.datetime):+ return value.date()+ return dt.datetime.strptime(value, self.DATE_FORMAT).date()++ @property+ def start(self) -> dt.date:+ return self._start++ @property+ def stop(self) -> dt.date:+ return self._stop+++@mddoc+class datetime(UIElement[Optional[str], Optional[dt.datetime]]):+ """+ A datetime picker over an interval.++ **Example.**++ ```python+ datetime_picker = mo.ui.datetime(+ start=dt.datetime(2023, 1, 1),+ stop=dt.datetime(2023, 12, 31, 23, 59, 59),+ )+ ```++ Or from a dataframe series:++ ```python+ datetime_picker = mo.ui.datetime.from_series(df["datetime_column"])+ ```++ **Attributes.**++ - `value`: the selected datetime, possibly `None`+ - `start`: the minimum selectable datetime+ - `stop`: the maximum selectable datetime++ **Initialization Args.**++ - `start`: the minimum selectable datetime (default: minimum datetime)+ - `stop`: the maximum selectable datetime (default: maximum datetime)+ - `value`: default value+ - `label`: text label for the element+ - `on_change`: optional callback to run when this element's value changes+ - `full_width`: whether the input should take up the full width of+ its container+ """++ _name: Final[str] = "marimo-datetime"+ DATETIME_FORMAT: Final[str] = "%Y-%m-%dT%H:%M:%S"++ def __init__(+ self,+ start: Optional[dt.datetime | str] = None,+ stop: Optional[dt.datetime | str] = None,+ value: Optional[dt.datetime | str] = None,+ *,+ label: Optional[str] = None,+ on_change: Optional[Callable[[Optional[dt.datetime]], None]] = None,+ full_width: bool = False,+ ):+ if isinstance(start, str):+ start = self._convert_value(start)+ if isinstance(stop, str):+ stop = self._convert_value(stop)+ if isinstance(value, str):+ value = self._convert_value(value)++ self._start = dt.datetime.min if start is None else start+ self._stop = dt.datetime.max if stop is None else stop++ if self._stop < self._start:+ raise ValueError(+ f"The stop datetime ({stop}) must be greater than "+ f"the start datetime ({start})"+ )++ if value is None:+ if start is None and stop is None:+ value = dt.datetime.today()+ elif start is not None:+ value = start+ else:+ value = stop+ value = cast(dt.datetime, value)++ if value < self._start or value > self._stop:+ raise ValueError(+ f"The default value ({value}) must be greater than "+ f"the start datetime ({start}) and less than the stop "+ f"datetime ({stop})."+ )++ super().__init__(+ component_name=datetime._name,+ initial_value=value.isoformat(timespec="seconds"),+ label=label,+ args={+ "start": self._start.strftime(self.DATETIME_FORMAT),+ "stop": self._stop.strftime(self.DATETIME_FORMAT),+ "full-width": full_width,+ },+ on_change=on_change,+ )++ @staticmethod+ def from_series(series: DataFrameSeries, **kwargs: Any) -> "datetime":+ """Create a datetime picker from a dataframe series."""+ info = get_datetime_series_info(series)+ start = kwargs.pop("start", info.min)+ stop = kwargs.pop("stop", info.max)+ label = kwargs.pop("label", info.label)+ return datetime(start=start, stop=stop, label=label, **kwargs)++ def _convert_value(self, value: Optional[str]) -> Optional[dt.datetime]:+ if value is None:+ return None+ POSSIBLE_FORMATS = [+ self.DATETIME_FORMAT,+ "%Y-%m-%d",+ "%Y-%m-%dT%H",+ "%Y-%m-%dT%H:%M",+ "%Y-%m-%dT%H:%M:%S",+ "%Y-%m-%dT%H:%M:%S.%f",+ ]+ for fmt in POSSIBLE_FORMATS:+ try:+ return dt.datetime.strptime(value, fmt)+ except ValueError:+ pass+ raise ValueError(f"Invalid datetime format: {value}")++ @property+ def start(self) -> dt.datetime:+ return self._start++ @property+ def stop(self) -> dt.datetime:+ return self._stop+++@mddoc+class date_range(UIElement[Tuple[str, str], Tuple[dt.date, dt.date]]):+ """+ A date range picker over an interval.++ **Example.**++ ```python+ date_range = mo.ui.date_range(+ start=dt.date(2023, 1, 1), stop=dt.date(2023, 12, 31)+ )+ ```++ Or from a dataframe series:++ ```python+ date_range = mo.ui.date_range.from_series(df["date_column"])+ ```++ **Attributes.**++ - `value`: a tuple of two dates representing the selected range+ - `start`: the minimum selectable date+ - `stop`: the maximum selectable date++ **Initialization Args.**++ - `start`: the minimum selectable date (default: minimum date)+ - `stop`: the maximum selectable date (default: maximum date)+ - `value`: default value (tuple of two dates)+ - `label`: text label for the element+ - `on_change`: optional callback to run when this element's value changes+ - `full_width`: whether the input should take up the full width of its+ container+ """++ _name: Final[str] = "marimo-date-range"+ DATEFORMAT: Final[str] = "%Y-%m-%d"++ def __init__(+ self,+ start: Optional[dt.date | str] = None,+ stop: Optional[dt.date | str] = None,+ value: Optional[Tuple[dt.date, dt.date] | Tuple[str, str]] = None,+ *,+ label: Optional[str] = None,+ on_change: Optional[Callable[[Tuple[dt.date, dt.date]], None]] = None,+ full_width: bool = False,+ ):+ if isinstance(start, str):+ start = self._convert_single_value(start)+ if isinstance(stop, str):+ stop = self._convert_single_value(stop)+ if value is not None:+ value = self._convert_value(value)++ self._start = dt.date(dt.MINYEAR, 1, 1) if start is None else start+ self._stop = dt.date(dt.MAXYEAR, 12, 31) if stop is None else stop++ if self._stop < self._start:+ raise ValueError(+ f"The stop date ({stop}) must be greater than "+ f"the start date ({start})"+ )++ if value is None:+ value = (dt.date.today(), dt.date.today())+ elif (+ value[0] < self._start+ or value[1] > self._stop+ or value[0] > value[1]+ ):+ raise ValueError(+ f"The default value ({value}) must be within "+ f"the range [{start}, {stop}] and the first date "+ f"must not be greater than the second date."+ )++ super().__init__(+ component_name=date_range._name,+ initial_value=(value[0].isoformat(), value[1].isoformat()),+ label=label,+ args={+ "start": self._start.isoformat(),+ "stop": self._stop.isoformat(),+ "full-width": full_width,+ },+ on_change=on_change,+ )++ @staticmethod+ def from_series(series: DataFrameSeries, **kwargs: Any) -> "date_range":+ """Create a date range picker from a dataframe series."""+ info = get_date_series_info(series)+ start = kwargs.pop("start", info.min)+ stop = kwargs.pop("stop", info.max)+ label = kwargs.pop("label", info.label)+ return date_range(start=start, stop=stop, label=label, **kwargs)++ def _convert_value(+ self, value: Tuple[str, str] | Tuple[dt.date, dt.date]+ ) -> Tuple[dt.date, dt.date]:+ return (+ self._convert_single_value(value[0]),+ self._convert_single_value(value[1]),+ )++ def _convert_single_value(self, value: str | dt.date) -> dt.date:+ if isinstance(value, dt.date):+ return value+ if isinstance(value, dt.datetime):+ return value.date()+ return dt.datetime.strptime(value, self.DATEFORMAT).date()++ @property+ def start(self) -> dt.date:+ return self._start++ @property+ def stop(self) -> dt.date:+ return self._stopdiff --git a/marimo/_plugins/ui/_impl/input.py b/marimo/_plugins/ui/_impl/input.pyindex fa5e58c8cd..9fa0188403 100644--- a/marimo/_plugins/ui/_impl/input.py+++ b/marimo/_plugins/ui/_impl/input.py@@ -3,7 +3,6 @@ from __future__ import annotationsimport base64import dataclasses-import datetime as dtimport osimport tracebackfrom dataclasses import dataclass@@ -26,7 +25,6 @@ from marimo import _loggersfrom marimo._data.series import (DataFrameSeries,get_category_series_info,- get_date_series_info,get_number_series_info,)from marimo._output.rich_help import mddoc@@ -129,9 +127,10 @@ class number(UIElement[Optional[Numeric], Optional[Numeric]]):def from_series(series: DataFrameSeries, **kwargs: Any) -> "number":"""Create a number picker from a dataframe series."""info = get_number_series_info(series)- return number(- start=info.min, stop=info.max, label=info.label, **kwargs- )+ start = kwargs.pop("start", info.min)+ stop = kwargs.pop("stop", info.max)+ label = kwargs.pop("label", info.label)+ return number(start=start, stop=stop, label=label, **kwargs)def _convert_value(self, value: Optional[Numeric]) -> Optional[Numeric]:"""Value is `None` if user uses keyboard to delete contents of input"""@@ -310,9 +309,10 @@ class slider(UIElement[Numeric, Numeric]):def from_series(series: DataFrameSeries, **kwargs: Any) -> "slider":"""Create a slider from a dataframe series."""info = get_number_series_info(series)- return slider(- start=info.min, stop=info.max, label=info.label, **kwargs- )+ start = kwargs.pop("start", info.min)+ stop = kwargs.pop("stop", info.max)+ label = kwargs.pop("label", info.label)+ return slider(start=start, stop=stop, label=label, **kwargs)def _convert_value(self, value: Numeric) -> Numeric:if self._mapping is not None:@@ -490,9 +490,10 @@ class range_slider(UIElement[List[Numeric], Sequence[Numeric]]):def from_series(series: DataFrameSeries, **kwargs: Any) -> "range_slider":"""Create a range slider from a dataframe series."""info = get_number_series_info(series)- return range_slider(- start=info.min, stop=info.max, label=info.label, **kwargs- )+ start = kwargs.pop("start", info.min)+ stop = kwargs.pop("stop", info.max)+ label = kwargs.pop("label", info.label)+ return range_slider(start=start, stop=stop, label=label, **kwargs)def _convert_value(self, value: List[Numeric]) -> Sequence[Numeric]:if self._mapping is not None:@@ -631,11 +632,9 @@ class radio(UIElement[Optional[str], Any]):def from_series(series: DataFrameSeries, **kwargs: Any) -> "radio":"""Create a radio group from a dataframe series."""info = get_category_series_info(series)- return radio(- options=info.categories,- label=info.label,- **kwargs,- )+ options = kwargs.pop("options", info.categories)+ label = kwargs.pop("label", info.label)+ return radio(options=options, label=label, **kwargs)def _convert_value(self, value: Optional[str]) -> Any:return self.options[value] if value is not None else None@@ -942,11 +941,9 @@ class dropdown(UIElement[List[str], Any]):def from_series(series: DataFrameSeries, **kwargs: Any) -> "dropdown":"""Create a dropdown from a dataframe series."""info = get_category_series_info(series)- return dropdown(- options=info.categories,- label=info.label,- **kwargs,- )+ options = kwargs.pop("options", info.categories)+ label = kwargs.pop("label", info.label)+ return dropdown(options=options, label=label, **kwargs)def _convert_value(self, value: list[str]) -> Any:if value:@@ -1053,11 +1050,9 @@ class multiselect(UIElement[List[str], List[object]]):def from_series(series: DataFrameSeries, **kwargs: Any) -> "multiselect":"""Create a multiselect from a dataframe series."""info = get_category_series_info(series)- return multiselect(- options=info.categories,- label=info.label,- **kwargs,- )+ options = kwargs.pop("options", info.categories)+ label = kwargs.pop("label", info.label)+ return multiselect(options=options, label=label, **kwargs)def _convert_value(self, value: list[str]) -> list[object]:return [self.options[v] for v in value]@@ -1433,139 +1428,6 @@ class file_browser(UIElement[List[Dict[str, Any]], Sequence[FileInfo]]):return self.value[index].path-@mddoc-class date(UIElement[str, dt.date]):- """- A date picker with an optional start and stop date.-- **Example.**-- ```python- # initialize the date picker at a given date- date = mo.ui.date(value="2022-01-01")- ```-- ```python- # when value is omitted, date picker initializes with today's date- date = mo.ui.date()- ```-- ```python- # create a date picker with bounds- date = mo.ui.date(- value="2022-06-01",- start="2022-01-01",- stop="2022-12-31",- )- ```-- Or from a dataframe series:-- ```python- date = mo.ui.date.from_series(df["column_name"])- ```-- **Attributes.**-- - `value`: a str (YYYY-MM-DD) or `datetime.date` object of the chosen date- - `start`: the start date- - `stop`: the stop date-- **Initialization Args.**-- - `start`: minimum date selectable; if None, defaults to 01-01-0001- - `stop`: maximum date selectable; if None, defaults to 12-31-9999- - `value`: default date- - if `None` and `start` and `stop` are `None`, defaults to the- current day;- - else if `None` and `start` is not `None`, defaults to `start`;- - else if `None` and `stop` is not `None`, defaults to `stop`- - `label`: text label for the element- - `on_change`: optional callback to run when this element's value changes- - `full_width`: whether the input should take up the full width of its- container- """-- _name: Final[str] = "marimo-date-picker"-- DATEFORMAT = "%Y-%m-%d"-- def __init__(- self,- start: Optional[dt.date | str] = None,- stop: Optional[dt.date | str] = None,- value: Optional[dt.date | str] = None,- *,- label: str = "",- on_change: Optional[Callable[[dt.date], None]] = None,- full_width: bool = False,- ) -> None:- if isinstance(start, str):- start = self._convert_value(start)- if isinstance(stop, str):- stop = self._convert_value(stop)- if isinstance(value, str):- value = self._convert_value(value)-- if value is None:- if start is None and stop is None:- value = dt.date.today()- elif start is not None:- value = start- else:- value = stop- value = cast(dt.date, value)-- self._start = dt.date(dt.MINYEAR, 1, 1) if start is None else start- self._stop = dt.date(dt.MAXYEAR, 12, 31) if stop is None else stop-- if self._stop < self._start:- raise ValueError(- f"The stop date ({stop}) must be greater than "- f"the start date ({start})"- )- elif value < self._start or value > self._stop:- raise ValueError(- f"The default value ({value}) must be greater than "- f"the start date ({start}) and less than the stop "- f"date ({stop})."- )-- super().__init__(- component_name=date._name,- initial_value=value.isoformat(),- label=label,- args={- "start": self._start.isoformat(),- "stop": self._stop.isoformat(),- "full-width": full_width,- },- on_change=on_change,- )-- @staticmethod- def from_series(series: DataFrameSeries, **kwargs: Any) -> "date":- """Create a date picker from a dataframe series."""- info = get_date_series_info(series)- return date(- start=info.min,- stop=info.max,- label=info.label,- **kwargs,- )-- def _convert_value(self, value: str) -> dt.date:- return dt.datetime.strptime(value, self.DATEFORMAT).date()-- @property- def start(self) -> dt.date:- return self._start-- @property- def stop(self) -> dt.date:- return self._stop--T = TypeVar("T")diff --git a/marimo/_smoke_tests/dates.py b/marimo/_smoke_tests/dates.pynew file mode 100644index 0000000000..caa67ffa6a--- /dev/null+++ b/marimo/_smoke_tests/dates.py@@ -0,0 +1,99 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "marimo",+# ]+# ///++import marimo++__generated_with = "0.8.7"+app = marimo.App(width="medium")+++def __():+ import marimo as mo+ return mo,+++def __(mo):+ import datetime++ start_date = mo.ui.date(+ label="Start date",+ start=datetime.date(2020, 1, 1),+ stop=datetime.date(2020, 12, 31),+ )+ end_date = mo.ui.date(+ label="End date",+ start=datetime.date(2020, 1, 1),+ stop=datetime.date(2020, 12, 31),+ )+ return datetime, end_date, start_date+++def __(end_date, mo, start_date):+ mo.hstack(+ [+ mo.hstack([start_date, "➡️", end_date]).left(),+ mo.md(f"From {start_date.value} to {end_date.value}"),+ ]+ )+ return+++def __(datetime, mo):+ start_datetime = mo.ui.datetime(+ label="Start datetime",+ start=datetime.datetime(2021, 1, 1),+ stop=datetime.datetime(2021, 12, 31),+ )+ end_datetime = mo.ui.datetime(+ label="End datetime",+ start=datetime.datetime(2021, 1, 1),+ stop=datetime.datetime(2021, 12, 31),+ )+ return end_datetime, start_datetime+++def __(end_datetime, mo, start_datetime):+ mo.hstack(+ [+ mo.hstack([start_datetime, "➡️", end_datetime]).left(),+ mo.md(f"From {start_datetime.value} to {end_datetime.value}"),+ ]+ )+ return+++def __(datetime, mo):+ date_range_input = mo.ui.date_range(+ label="Date_range",+ start=datetime.date(2021, 1, 1),+ stop=datetime.date(2021, 12, 31),+ )+ return date_range_input,+++def __(date_range_input, mo):+ mo.hstack([date_range_input, date_range_input.value])+ return+++def __(mo):+ _date = mo.ui.date(label="Input")+ _datetime = mo.ui.datetime(label="Input")+ _date_range = mo.ui.date_range(label="Input")+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_data/test_series.py b/tests/_data/test_series.pyindex 3589cd625a..12d4f7de12 100644--- a/tests/_data/test_series.py+++ b/tests/_data/test_series.py@@ -9,6 +9,7 @@ import pytestfrom marimo._data.series import (get_category_series_info,get_date_series_info,+ get_datetime_series_info,get_number_series_info,)from marimo._dependencies.dependencies import DependencyManager@@ -113,3 +114,44 @@ def test_date_series(df: Any) -> None:response = get_date_series_info(df["B"])with pytest.raises(ValueError):response = get_date_series_info(df["A"])++[email protected](not HAS_DEPS, reason="optional dependencies not installed")+ "df",+ [+ pd.DataFrame(+ {+ "A": [1, 2, 3],+ "B": ["a", "b", "b"],+ "C": [+ datetime(2024, 1, 1, 12, 0),+ datetime(2024, 1, 2, 13, 30),+ datetime(2024, 1, 3, 15, 45),+ ],+ }+ ),+ pl.DataFrame(+ {+ "A": [1, 2, 3],+ "B": ["a", "b", "b"],+ "C": [+ datetime(2024, 1, 1, 12, 0),+ datetime(2024, 1, 2, 13, 30),+ datetime(2024, 1, 3, 15, 45),+ ],+ }+ ),+ ],+)+def test_datetime_series(df: Any) -> None:+ response = get_datetime_series_info(df["C"])++ assert response.min == "2024-01-01T12:00:00"+ assert response.max == "2024-01-03T15:45:00"+ assert response.label == "C"++ with pytest.raises(ValueError):+ response = get_datetime_series_info(df["B"])+ with pytest.raises(ValueError):+ response = get_datetime_series_info(df["A"])diff --git a/tests/_plugins/ui/_impl/test_dates.py b/tests/_plugins/ui/_impl/test_dates.pynew file mode 100644index 0000000000..89495d3840--- /dev/null+++ b/tests/_plugins/ui/_impl/test_dates.py@@ -0,0 +1,146 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++import datetime++import pytest++from marimo._dependencies.dependencies import DependencyManager+from marimo._plugins import ui++HAS_PANDAS = DependencyManager.pandas.has()+++def test_date() -> None:+ date = ui.date()+ today = date.value+ assert today == datetime.date.today()++ date._update("2024-01-01")+ assert date.value == datetime.date(2024, 1, 1)++ date = ui.date(value="2024-01-01")+ assert date.value == datetime.date(2024, 1, 1)++ date = ui.date(value="2024-01-01")+ date._update("2024-01-02")+ assert date.value == datetime.date(2024, 1, 2)+++def test_datetime() -> None:+ # Test default initialization+ dt = ui.datetime()+ now = datetime.datetime.now()+ assert dt.value+ assert dt.value.date() == now.date()+ assert dt.value.hour == now.hour+ assert dt.value.minute == now.minute++ # Test initialization with a specific value+ dt = ui.datetime(value="2024-01-01T12:30")+ assert dt.value == datetime.datetime(2024, 1, 1, 12, 30)+ # Test initialization with a specific value+ dt = ui.datetime(value="2024-01-01T12")+ assert dt.value == datetime.datetime(2024, 1, 1, 12)+ dt = ui.datetime(value="2024-01-01")+ assert dt.value == datetime.datetime(2024, 1, 1)++ # Test updating the value+ dt._update("2024-02-15T08:45")+ assert dt.value == datetime.datetime(2024, 2, 15, 8, 45)++ # Test with start and stop+ dt = ui.datetime(+ value="2024-01-15T10:00",+ start="2024-01-01T00:00",+ stop="2024-12-31T23:59",+ )+ assert dt.value == datetime.datetime(2024, 1, 15, 10, 0)+ assert dt.start == datetime.datetime(2024, 1, 1, 0, 0)+ assert dt.stop == datetime.datetime(2024, 12, 31, 23, 59)+++def test_date_range() -> None:+ # Test default initialization+ dr = ui.date_range()+ today = datetime.date.today()+ assert dr.value == (today, today)++ # Test initialization with specific values+ dr = ui.date_range(value=("2024-01-01", "2024-01-31"))+ assert dr.value == (datetime.date(2024, 1, 1), datetime.date(2024, 1, 31))++ # Test updating the value+ dr._update(("2024-02-01", "2024-02-29"))+ assert dr.value == (datetime.date(2024, 2, 1), datetime.date(2024, 2, 29))++ # Test with start and stop+ dr = ui.date_range(+ value=("2024-03-01", "2024-03-15"),+ start="2024-01-01",+ stop="2024-12-31",+ )+ assert dr.value == (datetime.date(2024, 3, 1), datetime.date(2024, 3, 15))+ assert dr.start == datetime.date(2024, 1, 1)+ assert dr.stop == datetime.date(2024, 12, 31)++ # Test invalid range (start date after end date)+ with pytest.raises(ValueError):+ ui.date_range(value=("2024-02-01", "2024-01-01"))++[email protected](not HAS_PANDAS, reason="pandas not installed")+def test_date_from_dataframe() -> None:+ import pandas as pd++ df = pd.DataFrame(+ {"A": [pd.Timestamp("2024-01-01"), pd.Timestamp("2024-01-02")]}+ )+ date = ui.date.from_series(+ df["A"], value=datetime.date(2024, 1, 2), label="Custom label"+ )+ assert date.value == datetime.date(2024, 1, 2)+ assert date.start == datetime.date(2024, 1, 1)+ assert date.stop == datetime.date(2024, 1, 2)+ assert date._args.label == "Custom label"++[email protected](not HAS_PANDAS, reason="pandas not installed")+def test_datetime_from_dataframe() -> None:+ import pandas as pd++ # Test from_series for datetime+ df_datetime = pd.DataFrame(+ {+ "B": [+ pd.Timestamp("2024-01-01 10:00"),+ pd.Timestamp("2024-01-02 14:30"),+ ]+ }+ )+ datetime_ui = ui.datetime.from_series(+ df_datetime["B"], value=datetime.datetime(2024, 1, 2, 14, 30)+ )+ assert datetime_ui.value == datetime.datetime(2024, 1, 2, 14, 30)+ assert datetime_ui.start == datetime.datetime(2024, 1, 1, 10, 0)+ assert datetime_ui.stop == datetime.datetime(2024, 1, 2, 14, 30)++[email protected](not HAS_PANDAS, reason="pandas not installed")+def test_date_range_from_dataframe() -> None:+ import pandas as pd++ # Test from_series for date_range+ df_date_range = pd.DataFrame(+ {"C": [pd.Timestamp("2024-01-01"), pd.Timestamp("2024-01-31")]}+ )+ date_range_ui = ui.date_range.from_series(+ df_date_range["C"],+ value=(datetime.date(2024, 1, 15), datetime.date(2024, 1, 20)),+ )+ assert date_range_ui.value == (+ datetime.date(2024, 1, 15),+ datetime.date(2024, 1, 20),+ )+ assert date_range_ui.start == datetime.date(2024, 1, 1)+ assert date_range_ui.stop == datetime.date(2024, 1, 31)diff --git a/tests/_plugins/ui/_impl/test_input.py b/tests/_plugins/ui/_impl/test_input.pyindex be2d1da27a..fd74cd60be 100644--- a/tests/_plugins/ui/_impl/test_input.py+++ b/tests/_plugins/ui/_impl/test_input.py@@ -1,7 +1,6 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-import datetimefrom typing import Anyimport pytest@@ -56,11 +55,12 @@ def test_number_from_dataframe() -> None:import pandas as pddf = pd.DataFrame({"A": [1, 2, 3]})- number = ui.number.from_series(df["A"], step=0.1)+ number = ui.number.from_series(df["A"], step=0.1, label="Custom label")assert number.start == 1assert number.stop == 3assert number.value == 1assert number.step == 0.1+ assert number._args.label == "Custom label"def test_slider_init() -> None:@@ -150,11 +150,12 @@ def test_slider_from_dataframe() -> None:import pandas as pddf = pd.DataFrame({"A": [1, 2, 3]})- slider = ui.slider.from_series(df["A"], step=0.1)+ slider = ui.slider.from_series(df["A"], step=0.1, label="Custom label")assert slider.start == 1assert slider.stop == 3assert slider.value == 1assert slider.step == 0.1+ assert slider._args.label == "Custom label"def test_range_slider_init() -> None:@@ -247,11 +248,14 @@ def test_range_slider_from_dataframe() -> None:import pandas as pddf = pd.DataFrame({"A": [1, 2, 3]})- slider = ui.range_slider.from_series(df["A"], step=0.1)+ slider = ui.range_slider.from_series(+ df["A"], step=0.1, label="Custom label"+ )assert slider.start == 1assert slider.stop == 3assert slider.value == [1, 3]assert slider.step == 0.1+ assert slider._args.label == "Custom label"def test_text() -> None:@@ -434,32 +438,3 @@ def test_form_in_dictionary_allowed() -> None:# TODO(akshayka): test file---def test_date() -> None:- date = ui.date()- today = date.value- assert today == datetime.date.today()-- date._update("2024-01-01")- assert date.value == datetime.date(2024, 1, 1)-- date = ui.date(value="2024-01-01")- assert date.value == datetime.date(2024, 1, 1)-- date = ui.date(value="2024-01-01")- date._update("2024-01-02")- assert date.value == datetime.date(2024, 1, 2)--[email protected](not HAS_PANDAS, reason="pandas not installed")-def test_date_from_dataframe() -> None:- import pandas as pd-- df = pd.DataFrame(- {"A": [pd.Timestamp("2024-01-01"), pd.Timestamp("2024-01-02")]}- )- date = ui.date.from_series(df["A"], value=datetime.date(2024, 1, 2))- assert date.value == datetime.date(2024, 1, 2)- assert date.start == datetime.date(2024, 1, 1)- assert date.stop == datetime.date(2024, 1, 2)