Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: support filtering by value for all column types in context menu (#11182)

Barok Dagim Getachew0d5e3f4c0872
diff --git a/frontend/src/components/data-table/__tests__/context-menu.test.ts b/frontend/src/components/data-table/__tests__/context-menu.test.ts
new file mode 100644
index 0000000000..50e1ed2f7f
--- /dev/null
+++ b/frontend/src/components/data-table/__tests__/context-menu.test.ts
@@ -0,0 +1,176 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { buildCellFilter } from "../context-menu";
+
+describe("buildCellFilter", () => {
+ // Use a non-UTC, non-DST-ambiguous offset so date-only parsing bugs
+ // (UTC vs. local midnight) can't hide behind a host machine that
+ // happens to run in UTC.
+ let originalTimezone: string | undefined;
+ beforeAll(() => {
+ originalTimezone = process.env.TZ;
+ process.env.TZ = "America/New_York";
+ });
+ afterAll(() => {
+ process.env.TZ = originalTimezone;
+ });
+
+ it("builds an equality filter for a normal date value", () => {
+ const filter = buildCellFilter({
+ type: "date",
+ value: "2024-01-15",
+ comparison: "eq",
+ dataType: "date",
+ dtype: "date",
+ });
+ expect(filter).toEqual({
+ type: "date",
+ operator: "==",
+ // Must be local midnight, not `new Date("2024-01-15")` (UTC
+ // midnight), or the filter shifts by a day in UTC- timezones.
+ value: new Date(2024, 0, 15),
+ });
+ });
+
+ it("returns undefined for an empty-string date value in a non-temporal-looking context", () => {
+ const filter = buildCellFilter({
+ type: "date",
+ value: "",
+ comparison: "eq",
+ dataType: "date",
+ dtype: "date",
+ });
+ expect(filter).toBeUndefined();
+ });
+
+ it("returns undefined for an unparsable date value instead of an Invalid Date filter", () => {
+ const filter = buildCellFilter({
+ type: "date",
+ value: "not-a-date",
+ comparison: "eq",
+ dataType: "date",
+ dtype: "date",
+ });
+ expect(filter).toBeUndefined();
+ });
+
+ it("builds an equality filter for a normal datetime value", () => {
+ const filter = buildCellFilter({
+ type: "datetime",
+ value: "2024-01-15 08:30:00",
+ comparison: "eq",
+ dataType: "datetime",
+ dtype: "datetime64[ns]",
+ });
+ expect(filter).toEqual({
+ type: "datetime",
+ operator: "==",
+ value: new Date(2024, 0, 15, 8, 30, 0),
+ });
+ });
+
+ it("returns undefined for an unparsable datetime value", () => {
+ const filter = buildCellFilter({
+ type: "datetime",
+ value: "not-a-datetime",
+ comparison: "eq",
+ dataType: "datetime",
+ dtype: "datetime64[ns]",
+ });
+ expect(filter).toBeUndefined();
+ });
+
+ it("builds an equality filter for a normal time value", () => {
+ const filter = buildCellFilter({
+ type: "time",
+ value: "08:30:00",
+ comparison: "eq",
+ dataType: "time",
+ });
+ expect(filter).toEqual({
+ type: "time",
+ operator: "==",
+ value: new Date(1970, 0, 1, 8, 30, 0),
+ });
+ });
+
+ it("returns undefined instead of an unparsable time value", () => {
+ const filter = buildCellFilter({
+ type: "time",
+ value: "25:00:00",
+ comparison: "eq",
+ dataType: "time",
+ });
+ expect(filter).toBeUndefined();
+ });
+
+ it("maps a NaT date value to is_null instead of an invalid Date filter", () => {
+ const filter = buildCellFilter({
+ type: "date",
+ value: "NaT",
+ comparison: "eq",
+ dataType: "date",
+ dtype: "date",
+ });
+ expect(filter).toEqual({ type: "date", operator: "is_null" });
+ });
+
+ it("maps a NaT datetime value to is_not_null for the neq comparison", () => {
+ const filter = buildCellFilter({
+ type: "datetime",
+ value: "NaT",
+ comparison: "neq",
+ dataType: "datetime",
+ dtype: "datetime64[ns]",
+ });
+ expect(filter).toEqual({ type: "datetime", operator: "is_not_null" });
+ });
+
+ it("does not treat the string 'NaT' in a non-temporal column as a sentinel", () => {
+ const filter = buildCellFilter({
+ type: "text",
+ value: "NaT",
+ comparison: "eq",
+ dataType: "string",
+ });
+ expect(filter).toEqual({ type: "text", operator: "equals", text: "NaT" });
+ });
+
+ it("maps an actual null value to is_null", () => {
+ const filter = buildCellFilter({
+ type: "number",
+ value: null,
+ comparison: "eq",
+ dataType: "number",
+ });
+ expect(filter).toEqual({ type: "number", operator: "is_null" });
+ });
+
+ it("builds a literal (always-false) equality filter for a NaN number value", () => {
+ // NaN is a real float value, not a missing-value marker like null/NaT,
+ // and the backend's is_null() (narwhals/polars semantics) doesn't match
+ // it, so it falls through to a normal (if unsatisfiable) == filter.
+ const filter = buildCellFilter({
+ type: "number",
+ value: Number.NaN,
+ comparison: "eq",
+ dataType: "number",
+ });
+ expect(filter).toEqual({
+ type: "number",
+ operator: "==",
+ value: Number.NaN,
+ });
+ });
+
+ it("builds a literal equality filter for a normal number value", () => {
+ const filter = buildCellFilter({
+ type: "number",
+ value: 42,
+ comparison: "eq",
+ dataType: "number",
+ });
+ expect(filter).toEqual({ type: "number", operator: "==", value: 42 });
+ });
+});
diff --git a/frontend/src/components/data-table/__tests__/date-filter-inputs.test.tsx b/frontend/src/components/data-table/__tests__/date-filter-inputs.test.tsx
index 33f27ce540..2b3b048134 100644
--- a/frontend/src/components/data-table/__tests__/date-filter-inputs.test.tsx
+++ b/frontend/src/components/data-table/__tests__/date-filter-inputs.test.tsx
@@ -1,7 +1,30 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { describe, expect, it } from "vitest";
import { dateToLocalISODate } from "@/utils/dates";
-import { parsePastedRange } from "../date-filter-inputs";
+import { parsePastedDate, parsePastedRange } from "../date-filter-inputs";
+
+describe("parsePastedDate", () => {
+ it("parses a time-only string for the time filter type", () => {
+ const result = parsePastedDate("time", "2:30 PM");
+ expect(result).toEqual(new Date(1970, 0, 1, 14, 30));
+ });
+
+ it("parses a local ISO datetime for the datetime filter type", () => {
+ const result = parsePastedDate("datetime", "2026-02-01T08:30:00");
+ expect(result).toEqual(new Date(2026, 1, 1, 8, 30, 0));
+ });
+
+ it("falls back to the Date constructor for other formats", () => {
+ const result = parsePastedDate("datetime", "Feb 1, 2026 08:30:00");
+ expect(result).toBeDefined();
+ expect(result?.getFullYear()).toBe(2026);
+ });
+
+ it("returns undefined for an empty or unparsable string", () => {
+ expect(parsePastedDate("date", "")).toBeUndefined();
+ expect(parsePastedDate("time", "not-a-time")).toBeUndefined();
+ });
+});
describe("parsePastedRange", () => {
it.each([
diff --git a/frontend/src/components/data-table/context-menu.tsx b/frontend/src/components/data-table/context-menu.tsx
index f2aaf9b7dc..70ab4c709d 100644
--- a/frontend/src/components/data-table/context-menu.tsx
+++ b/frontend/src/components/data-table/context-menu.tsx
@@ -1,12 +1,19 @@
/* Copyright 2026 Marimo. All rights reserved. */
+import type { DataType } from "@/core/kernel/messages";
+import { assertNever } from "@/utils/assertNever";
+import { copyToClipboard } from "@/utils/copy";
+import {
+ parseLocalISODate,
+ parseLocalISODateTime,
+ parseTimeToDate,
+} from "@/utils/dates";
+import { Logger } from "@/utils/Logger";
import type { Cell } from "@tanstack/react-table";
import { useAtomValue } from "jotai";
import { CopyIcon, FilterIcon, SquareStack } from "lucide-react";
import type { RefObject } from "react";
import useEvent from "react-use-event-hook";
-import { copyToClipboard } from "@/utils/copy";
-import { Logger } from "@/utils/Logger";
import {
ContextMenu,
ContextMenuContent,
@@ -16,13 +23,94 @@ import {
ContextMenuTrigger,
} from "../ui/context-menu";
import { DATA_CELL_ID } from "./cell-utils";
-import {
- Filter,
- isMembershipFilterType,
- type MembershipFilterType,
-} from "./filters";
+import { type FilterType, Filter } from "./filters";
import { selectedCellsAtom } from "./range-focus/atoms";
-import { getClipboardContent, getRawValue } from "./utils";
+import { getClipboardContent, getRawValue, isNullishSentinel } from "./utils";
+
+type Comparison = "eq" | "neq";
+
+const symbolOp = {
+ eq: "==",
+ neq: "!=",
+} as const;
+
+const textOp = {
+ eq: "equals",
+ neq: "does_not_equal",
+} as const;
+
+export function buildCellFilter({
+ type,
+ value,
+ comparison = "eq",
+ dataType,
+ dtype,
+}: {
+ type: FilterType;
+ value: unknown;
+ comparison?: Comparison;
+ dataType?: DataType;
+ dtype?: string;
+}) {
+ if (isNullishSentinel(value, dataType, dtype)) {
+ return { type, operator: comparison === "eq" ? "is_null" : "is_not_null" };
+ }
+
+ switch (type) {
+ case "number":
+ if (typeof value !== "number") {
+ return undefined;
+ }
+
+ return Filter.number({
+ operator: symbolOp[comparison],
+ value,
+ });
+ case "text":
+ return Filter.text({
+ operator: textOp[comparison],
+ text: value as string,
+ });
+ case "date": {
+ const date = parseLocalISODate(value as string);
+ if (!date) {
+ return undefined;
+ }
+ return Filter.date({
+ operator: symbolOp[comparison],
+ value: date,
+ });
+ }
+ case "datetime": {
+ const date = parseLocalISODateTime(value as string);
+ if (!date) {
+ return undefined;
+ }
+ return Filter.datetime({
+ operator: symbolOp[comparison],
+ value: date,
+ });
+ }
+ case "time": {
+ const time = parseTimeToDate(value as string);
+ if (!time) {
+ return undefined;
+ }
+ return Filter.time({
+ operator: symbolOp[comparison],
+ value: time,
+ });
+ }
+ case "boolean": {
+ const target = comparison === "eq" ? value : !(value as boolean);
+ return Filter.boolean({
+ operator: target ? "is_true" : "is_false",
+ });
+ }
+ default:
+ assertNever(type);
+ }
+}
export const DataTableContextMenu = <TData,>({
contextMenuRef,
@@ -102,19 +190,34 @@ export const CellContextMenu = <TData,>({
const column = cell.column;
const filterType = column.columnDef.meta?.filterType;
- const membershipFilterType: MembershipFilterType | undefined =
- column.getCanFilter() && filterType && isMembershipFilterType(filterType)
- ? filterType
+ const dataType = column.columnDef.meta?.dataType;
+ const dtype = column.columnDef.meta?.dtype;
+
+ const canFilter = Boolean(filterType && column.getCanFilter());
+ const buildFilter = (comparison: Comparison) =>
+ canFilter
+ ? buildCellFilter({
+ type: filterType as FilterType,
+ value: rawValue,
+ comparison,
+ dataType,
+ dtype,
+ })
: undefined;
+ const eqFilter = buildFilter("eq");
+ const canFilterByValue = eqFilter !== undefined;
+
+ const handleFilterCellByValue = (comparison: Comparison) => {
+ if (!filterType) {
+ return;
+ }
+
+ const filter = comparison === "eq" ? eqFilter : buildFilter("neq");
+
+ if (!filter) {
+ return;
+ }
- const handleFilterCell = (
- type: MembershipFilterType,
- operator: "in" | "not_in",
- ) => {
- const filter =
- type === "number"
- ? Filter.number({ operator, values: [rawValue] })
- : Filter.text({ operator, values: [rawValue] });
column.setFilterValue(filter);
};
@@ -130,18 +233,14 @@ export const CellContextMenu = <TData,>({
Copy selected cells
</ContextMenuItem>
)}
- {membershipFilterType && (
+ {canFilterByValue && (
<>
<ContextMenuSeparator />
- <ContextMenuItem
- onClick={() => handleFilterCell(membershipFilterType, "in")}
- >
+ <ContextMenuItem onClick={() => handleFilterCellByValue("eq")}>
<FilterIcon className="mo-dropdown-icon h-3 w-3" />
Filter by this value
</ContextMenuItem>
- <ContextMenuItem
- onClick={() => handleFilterCell(membershipFilterType, "not_in")}
- >
+ <ContextMenuItem onClick={() => handleFilterCellByValue("neq")}>
<FilterIcon className="mo-dropdown-icon h-3 w-3" />
Remove rows with this value
</ContextMenuItem>
diff --git a/frontend/src/components/data-table/date-filter-inputs.tsx b/frontend/src/components/data-table/date-filter-inputs.tsx
index ba7fa1010c..0b63504499 100644
--- a/frontend/src/components/data-table/date-filter-inputs.tsx
+++ b/frontend/src/components/data-table/date-filter-inputs.tsx
@@ -14,6 +14,9 @@ import {
dateToLocalISODate,
dateToLocalISODateTime,
dateToLocalISOTime,
+ parseLocalISODate,
+ parseLocalISODateTime,
+ parseTimeToDate,
} from "@/utils/dates";
import type { FilterType } from "./filters";
@@ -72,53 +75,23 @@ export function parsePastedDate(
return undefined;
}
- const timeMatch =
- filterType === "time"
- ? trimmed.match(/^(\d{1,2}):(\d{2})(?::(\d{2}))?\s*(am|pm)?$/i)
- : null;
- if (timeMatch) {
- const [, hStr, mStr, sStr, ampm] = timeMatch;
- let hour = Number.parseInt(hStr, 10);
- const minute = Number.parseInt(mStr, 10);
- const second = sStr ? Number.parseInt(sStr, 10) : 0;
- if (ampm) {
- const isPm = ampm.toLowerCase() === "pm";
- if (hour === 12) {
- hour = isPm ? 12 : 0;
- } else if (isPm) {
- hour += 12;
- }
+ if (filterType === "time") {
+ const date = parseTimeToDate(trimmed);
+ if (date) {
+ return date;
}
- return new Date(1970, 0, 1, hour, minute, second);
}
- const dateOnlyMatch = trimmed.match(/^(\d{4})-(\d{2})-(\d{2})$/);
- if (dateOnlyMatch) {
- const [, y, m, d] = dateOnlyMatch;
- return new Date(
- Number.parseInt(y, 10),
- Number.parseInt(m, 10) - 1,
- Number.parseInt(d, 10),
- );
+ if (filterType === "date") {
+ const date = parseLocalISODate(trimmed);
+ if (date) {
+ return date;
+ }
}
- // Parse ISO datetimes as wall-clock to stay consistent with the picker's
- // local-time basis. Trailing `Z` or offsets are stripped so that pasting
- // `2024-01-15T08:30:00Z` displays `08:30` instead of being shifted by the
- // viewer's timezone.
- const isoMatch = trimmed.match(
- /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?$/,
- );
- if (isoMatch) {
- const [, y, mo, d, h, mi, s] = isoMatch;
- return new Date(
- Number.parseInt(y, 10),
- Number.parseInt(mo, 10) - 1,
- Number.parseInt(d, 10),
- Number.parseInt(h, 10),
- Number.parseInt(mi, 10),
- s ? Number.parseInt(s, 10) : 0,
- );
+ const isoDateTime = parseLocalISODateTime(trimmed);
+ if (isoDateTime) {
+ return isoDateTime;
}
const parsed = new Date(trimmed);
diff --git a/frontend/src/components/data-table/utils.ts b/frontend/src/components/data-table/utils.ts
index d5e7e3f41a..e233f53e68 100644
--- a/frontend/src/components/data-table/utils.ts
+++ b/frontend/src/components/data-table/utils.ts
@@ -228,6 +228,24 @@ export function detectSentinel(
return null;
}
+type NullishSentinelType = Extract<CellValueSentinel["type"], "null" | "nat">;
+
+const NULLISH_SENTINEL_TYPES: ReadonlySet<CellValueSentinel["type"]> =
+ new Set<NullishSentinelType>(["null", "nat"]);
+
+/**
+ * True when the cell value represents a missing value (null, NaT)
+ * rather than a real value that happens to look special.
+ */
+export function isNullishSentinel(
+ value: unknown,
+ dataType: DataType | undefined,
+ dtype?: string,
+): boolean {
+ const sentinel = detectSentinel(value, dataType, dtype);
+ return sentinel !== null && NULLISH_SENTINEL_TYPES.has(sentinel.type);
+}
+
/**
* Stringify an unknown value. Converts objects to JSON strings.
* @param opts.value - The value to stringify.
diff --git a/frontend/src/utils/__tests__/dates.test.ts b/frontend/src/utils/__tests__/dates.test.ts
index a8bc165e6b..4706581c12 100644
--- a/frontend/src/utils/__tests__/dates.test.ts
+++ b/frontend/src/utils/__tests__/dates.test.ts
@@ -4,6 +4,9 @@ import {
exactDateTime,
getDateFormat,
getShortTimeZone,
+ parseLocalISODate,
+ parseLocalISODateTime,
+ parseTimeToDate,
prettyDate,
timeAgo,
} from "../dates";
@@ -191,6 +194,119 @@ describe("dates", () => {
});
});
+ describe("parseTimeToDate", () => {
+ it("parses 24-hour times", () => {
+ expect(parseTimeToDate("14:30")).toEqual(new Date(1970, 0, 1, 14, 30));
+ expect(parseTimeToDate("14:30:05")).toEqual(
+ new Date(1970, 0, 1, 14, 30, 5),
+ );
+ });
+
+ it("parses times with an am/pm suffix", () => {
+ expect(parseTimeToDate("2:30 PM")).toEqual(new Date(1970, 0, 1, 14, 30));
+ expect(parseTimeToDate("12:00 am")).toEqual(new Date(1970, 0, 1, 0, 0));
+ expect(parseTimeToDate("12:00 pm")).toEqual(new Date(1970, 0, 1, 12, 0));
+ });
+
+ it("rejects an out-of-range hour instead of letting Date normalize it", () => {
+ // new Date(1970, 0, 1, 25, 0) would silently become 01:00 the next day.
+ expect(parseTimeToDate("25:00")).toBeUndefined();
+ });
+
+ it("rejects an out-of-range minute instead of letting Date normalize it", () => {
+ // new Date(1970, 0, 1, 12, 99) would silently become 13:39.
+ expect(parseTimeToDate("12:99")).toBeUndefined();
+ });
+
+ it("rejects an out-of-range second", () => {
+ expect(parseTimeToDate("12:30:99")).toBeUndefined();
+ });
+
+ it("requires an hour from 1 to 12 with an am/pm suffix", () => {
+ expect(parseTimeToDate("0:30 am")).toBeUndefined();
+ expect(parseTimeToDate("13:30 pm")).toBeUndefined();
+ });
+
+ it("parses milliseconds", () => {
+ expect(parseTimeToDate("14:30:05.123")).toEqual(
+ new Date(1970, 0, 1, 14, 30, 5, 123),
+ );
+ });
+
+ it("pads a short millisecond fraction and truncates a long one", () => {
+ expect(parseTimeToDate("14:30:05.5")).toEqual(
+ new Date(1970, 0, 1, 14, 30, 5, 500),
+ );
+ expect(parseTimeToDate("14:30:05.123456")).toEqual(
+ new Date(1970, 0, 1, 14, 30, 5, 123),
+ );
+ });
+ });
+
+ describe("parseLocalISODate", () => {
+ it("parses a date-only string into local midnight", () => {
+ expect(parseLocalISODate("2024-01-15")).toEqual(new Date(2024, 0, 15));
+ });
+
+ it("returns undefined for a non-date-only string", () => {
+ expect(parseLocalISODate("2024-01-15T00:00:00")).toBeUndefined();
+ expect(parseLocalISODate("")).toBeUndefined();
+ expect(parseLocalISODate("not-a-date")).toBeUndefined();
+ });
+
+ it("returns undefined for a calendar date that doesn't exist", () => {
+ expect(parseLocalISODate("2024-02-30")).toBeUndefined();
+ expect(parseLocalISODate("2024-13-01")).toBeUndefined();
+ });
+ });
+
+ describe("parseLocalISODateTime", () => {
+ it("parses a 'T'-separated datetime into local wall-clock time", () => {
+ expect(parseLocalISODateTime("2024-01-15T08:30:00")).toEqual(
+ new Date(2024, 0, 15, 8, 30, 0),
+ );
+ });
+
+ it("parses a space-separated datetime", () => {
+ expect(parseLocalISODateTime("2024-01-15 08:30:00")).toEqual(
+ new Date(2024, 0, 15, 8, 30, 0),
+ );
+ });
+
+ it("defaults seconds to 0 when omitted", () => {
+ expect(parseLocalISODateTime("2024-01-15T08:30")).toEqual(
+ new Date(2024, 0, 15, 8, 30, 0),
+ );
+ });
+
+ it("ignores a trailing Z instead of shifting to UTC", () => {
+ expect(parseLocalISODateTime("2024-01-15T08:30:00Z")).toEqual(
+ new Date(2024, 0, 15, 8, 30, 0),
+ );
+ });
+
+ it("ignores a trailing UTC offset instead of shifting the time", () => {
+ expect(parseLocalISODateTime("2024-01-15T08:30:00+05:00")).toEqual(
+ new Date(2024, 0, 15, 8, 30, 0),
+ );
+ expect(parseLocalISODateTime("2024-01-15T08:30:00-0500")).toEqual(
+ new Date(2024, 0, 15, 8, 30, 0),
+ );
+ });
+
+ it("ignores sub-second precision", () => {
+ expect(parseLocalISODateTime("2024-01-15T08:30:00.123")).toEqual(
+ new Date(2024, 0, 15, 8, 30, 0),
+ );
+ });
+
+ it("returns undefined for a date-only or unparsable string", () => {
+ expect(parseLocalISODateTime("2024-01-15")).toBeUndefined();
+ expect(parseLocalISODateTime("not-a-datetime")).toBeUndefined();
+ expect(parseLocalISODateTime("")).toBeUndefined();
+ });
+ });
+
describe("getDateFormat", () => {
it("returns the correct format for date", () => {
expect(getDateFormat("2023-05-15")).toBe("yyyy-MM-dd");
diff --git a/frontend/src/utils/dates.ts b/frontend/src/utils/dates.ts
index 95d9bb6a5d..a6a8c5610d 100644
--- a/frontend/src/utils/dates.ts
+++ b/frontend/src/utils/dates.ts
@@ -165,6 +165,44 @@ export function dateToLocalISOTime(d: Date): string {
return `${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`;
}
+/**
+ * Parse a time string into a Date anchored at the Unix epoch day. Supports
+ * the backend's wire format (`HH:MM:SS`, as produced by `dateToLocalISOTime`)
+ * as well as looser pasted text: optional seconds, optional milliseconds,
+ * and an optional `am`/`pm` suffix (e.g. `"14:30"`, `"2:30 PM"`,
+ * `"14:30:00.123"`).
+ */
+export function parseTimeToDate(value: string): Date | undefined {
+ const match = /^(\d{1,2}):(\d{2})(?::(\d{2}))?(?:\.(\d+))?\s*(am|pm)?$/i.exec(
+ value.trim(),
+ );
+ if (!match) {
+ return undefined;
+ }
+ const [, hStr, mStr, sStr, msStr, ampm] = match;
+ let hour = Number.parseInt(hStr, 10);
+ const minute = Number.parseInt(mStr, 10);
+ const second = sStr ? Number.parseInt(sStr, 10) : 0;
+ const ms = msStr ? Number.parseInt(msStr.padEnd(3, "0").slice(0, 3), 10) : 0;
+ if (minute > 59 || second > 59) {
+ return undefined;
+ }
+ if (ampm) {
+ if (hour < 1 || hour > 12) {
+ return undefined;
+ }
+ const isPm = ampm.toLowerCase() === "pm";
+ if (hour === 12) {
+ hour = isPm ? 12 : 0;
+ } else if (isPm) {
+ hour += 12;
+ }
+ } else if (hour > 23) {
+ return undefined;
+ }
+ return new Date(1970, 0, 1, hour, minute, second, ms);
+}
+
/**
* Format a Date as `YYYY-MM-DDTHH:MM:SS` (no timezone suffix) using local
* fields. See `dateToLocalISODate` for the rationale on local vs UTC.
@@ -173,6 +211,62 @@ export function dateToLocalISODateTime(d: Date): string {
return `${dateToLocalISODate(d)}T${dateToLocalISOTime(d)}`;
}
+/**
+ * Parse a `YYYY-MM-DD` string into a Date anchored at local midnight.
+ *
+ * Unlike `new Date("YYYY-MM-DD")`, which the spec parses as UTC midnight,
+ * this treats the string as a calendar date in the viewer's own timezone.
+ * Returns undefined if the string doesn't match, or encodes a calendar
+ * date that doesn't exist (e.g. month 13, Feb 30), since `Date` would
+ * otherwise silently roll those over into a different date.
+ */
+export function parseLocalISODate(value: string): Date | undefined {
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value.trim());
+ if (!match) {
+ return undefined;
+ }
+ const [, yStr, mStr, dStr] = match;
+ const year = Number.parseInt(yStr, 10);
+ const month = Number.parseInt(mStr, 10);
+ const day = Number.parseInt(dStr, 10);
+ const date = new Date(year, month - 1, day);
+ if (
+ date.getFullYear() !== year ||
+ date.getMonth() !== month - 1 ||
+ date.getDate() !== day
+ ) {
+ return undefined;
+ }
+ return date;
+}
+
+/**
+ * Parse an ISO-ish `YYYY-MM-DD[T ]HH:MM[:SS[.sss]][Z|+HH:MM]` datetime string
+ * as wall-clock local time, ignoring any trailing `Z` or UTC offset.
+ *
+ * This keeps pasted datetimes consistent with the date/time pickers' local-
+ * time basis: pasting `2024-01-15T08:30:00Z` displays `08:30` instead of
+ * being shifted by the viewer's timezone.
+ */
+export function parseLocalISODateTime(value: string): Date | undefined {
+ const match =
+ /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?$/.exec(
+ value.trim(),
+ );
+ if (!match) {
+ return undefined;
+ }
+ const [, yStr, moStr, dStr, hStr, miStr, sStr] = match;
+ return new Date(
+ Number.parseInt(yStr, 10),
+ Number.parseInt(moStr, 10) - 1,
+ Number.parseInt(dStr, 10),
+ Number.parseInt(hStr, 10),
+ Number.parseInt(miStr, 10),
+ sStr ? Number.parseInt(sStr, 10) : 0,
+ );
+}
+
export const supportedDateFormats = ["yyyy", "yyyy-MM", "yyyy-MM-dd"] as const;
export type DateFormat = (typeof supportedDateFormats)[number];