Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Accessible date/time pickers + slot generator core (#2775)
Luke Vella451dec8a5ffc
diff --git a/apps/web/biome.json b/apps/web/biome.jsonindex 4be9cee64..32d42898b 100644--- a/apps/web/biome.json+++ b/apps/web/biome.json@@ -456,7 +456,6 @@"src/**/edit-options/page.tsx","src/trpc/routers/polls.ts","src/trpc/routers/index.ts",- "src/app/api/private/utils/time-slots.ts","src/lib/utils/date-time-utils.ts","src/features/poll/components/manage-poll/use-csv-exporter.ts","src/test/setup.ts"diff --git a/apps/web/src/app/api/private/[...route]/route.test.ts b/apps/web/src/app/api/private/[...route]/route.test.tsindex e3be38289..341c25a89 100644--- a/apps/web/src/app/api/private/[...route]/route.test.ts+++ b/apps/web/src/app/api/private/[...route]/route.test.ts@@ -70,6 +70,7 @@ vi.mock("@/lib/posthog", () => ({import { prisma } from "@rallly/database";import { after } from "next/server";import { hashApiKey, verifyApiKey } from "@/features/api-keys/utils";+import { MAX_SLOT_GENERATION_DAYS } from "@/lib/datetime/slot-generator";import {createPollRequestExamples,patchPollRequestExamples,@@ -736,6 +737,117 @@ describe("Private API - /polls", () => {expect(res.status).toBe(200);expect(mockCreatePoll).toHaveBeenCalled();});++ it("should reject a slot generator range longer than the supported limit", async () => {+ // A 516-day range, one Sunday slot each week (~74 slots). Deliberately+ // under MAX_POLL_OPTIONS so TOO_MANY_OPTIONS can't mask it: only the+ // range check rejects this. The old code silently truncated to ~52 slots+ // and returned them as a successful poll.+ const res = await app.request("/api/private/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Way too long",+ slots: {+ duration: 30,+ timezone: "Europe/London",+ times: [+ {+ startDate: "2025-01-01",+ endDate: "2026-06-01",+ days: ["sun"],+ startTime: "09:00",+ endTime: "09:30",+ },+ ],+ },+ }),+ });++ // Rejected up front by validation, not silently truncated into a poll.+ // Assert the error targets endDate + names the limit so an unrelated 400+ // (e.g. TOO_MANY_OPTIONS) can't mask a regression.+ expect(res.status).toBe(400);+ expect(mockCreatePoll).not.toHaveBeenCalled();+ const json = await res.json();+ const issue = json.error.find((e: { path: (string | number)[] }) =>+ e.path.includes("endDate"),+ );+ expect(issue).toBeDefined();+ expect(issue.message).toContain(String(MAX_SLOT_GENERATION_DAYS));+ });++ it("should reject a slot generator range where endDate precedes startDate", async () => {+ const res = await app.request("/api/private/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Reversed range",+ slots: {+ duration: 30,+ timezone: "Europe/London",+ times: [+ {+ startDate: "2025-06-01",+ endDate: "2025-01-01",+ days: ["mon"],+ startTime: "09:00",+ endTime: "10:00",+ },+ ],+ },+ }),+ });++ expect(res.status).toBe(400);+ expect(mockCreatePoll).not.toHaveBeenCalled();+ const json = await res.json();+ const issue = json.error.find((e: { path: (string | number)[] }) =>+ e.path.includes("endDate"),+ );+ expect(issue).toBeDefined();+ });++ it("should reject a range spanning exactly MAX_SLOT_GENERATION_DAYS", async () => {+ // The generator processes days inclusively, so a span equal to the cap is+ // one day too many — the boundary must reject, not truncate.+ const start = new Date(Date.UTC(2025, 0, 1));+ const end = new Date(start);+ end.setUTCDate(end.getUTCDate() + MAX_SLOT_GENERATION_DAYS);+ const toIsoDate = (d: Date) => d.toISOString().slice(0, 10);+ const res = await app.request("/api/private/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Boundary range",+ slots: {+ duration: 30,+ timezone: "Europe/London",+ times: [+ {+ startDate: toIsoDate(start),+ endDate: toIsoDate(end),+ days: ["sun"],+ startTime: "09:00",+ endTime: "09:30",+ },+ ],+ },+ }),+ });++ expect(res.status).toBe(400);+ expect(mockCreatePoll).not.toHaveBeenCalled();+ });});describe("Validation", () => {diff --git a/apps/web/src/app/api/private/[...route]/route.ts b/apps/web/src/app/api/private/[...route]/route.tsindex 38e51a50a..74ee6f6b1 100644--- a/apps/web/src/app/api/private/[...route]/route.ts+++ b/apps/web/src/app/api/private/[...route]/route.ts@@ -11,6 +11,7 @@ import {validator,} from "hono-openapi";import { after } from "next/server";+import { MAX_POLL_OPTIONS } from "@/features/poll/constants";import {getPollParticipants,getPollResults,@@ -18,6 +19,12 @@ import {} from "@/features/poll/data";import { closePoll, createPoll, deletePoll } from "@/features/poll/mutations";import type { AuthorizedSpaceId } from "@/features/space/types";+import type { SlotGeneratorInput } from "@/lib/datetime/slot-generator";+import {+ dedupeTimeSlots,+ generateTimeSlots,+ parseStartTime,+} from "@/lib/datetime/slot-generator";import { isMaintenanceModeEnabled } from "@/lib/maintenance";import { flushPostHog, identifyGroup, track } from "@/lib/posthog";import {@@ -40,12 +47,6 @@ import {import { spaceApiKeyAuth } from "../utils/api-key";import { apiError } from "../utils/poll";import { RATE_LIMIT_PER_MINUTE, rateLimit } from "../utils/rate-limit";-import type { SlotGeneratorInput } from "../utils/time-slots";-import {- dedupeTimeSlots,- generateTimeSlots,- parseStartTime,-} from "../utils/time-slots";import { wideEvent } from "../utils/wide-event";type Env = {@@ -111,8 +112,6 @@ app.use("*", async (c, next) => {await next();});-const MAX_OPTIONS = 100;-const spaceNotProResponse = {description:"The space associated with the API key does not have a Pro subscription",@@ -321,11 +320,11 @@ app.post(// Process dates (all-day options)if (input.dates) {- if (input.dates.length > MAX_OPTIONS) {+ if (input.dates.length > MAX_POLL_OPTIONS) {return c.json(apiError("TOO_MANY_OPTIONS",- `Too many options (${input.dates.length}). Maximum allowed is ${MAX_OPTIONS}.`,+ `Too many options (${input.dates.length}). Maximum allowed is ${MAX_POLL_OPTIONS}.`,),400,);@@ -409,11 +408,11 @@ app.post();}- if (options.length > MAX_OPTIONS) {+ if (options.length > MAX_POLL_OPTIONS) {return c.json(apiError("TOO_MANY_OPTIONS",- `Too many options generated (${options.length}). Maximum allowed is ${MAX_OPTIONS}.`,+ `Too many options generated (${options.length}). Maximum allowed is ${MAX_POLL_OPTIONS}.`,),400,);diff --git a/apps/web/src/app/api/private/schemas.ts b/apps/web/src/app/api/private/schemas.tsindex 2d980e9ad..b7ebf6f55 100644--- a/apps/web/src/app/api/private/schemas.ts+++ b/apps/web/src/app/api/private/schemas.ts@@ -1,4 +1,5 @@import { z } from "@hono/zod-openapi";+import { MAX_SLOT_GENERATION_DAYS } from "@/lib/datetime/slot-generator";import { timezoneSchema } from "@/lib/utils/timezone-schema";export const dateSchema = z.iso.date().openapi({@@ -23,6 +24,20 @@ export const slotGeneratorSchema = zexample: 30,}),})+ // Reject over-long ranges up front rather than silently truncating at the+ // generator's MAX_SLOT_GENERATION_DAYS cap.+ .refine(+ (data) => {+ const start = Date.parse(data.startDate);+ const end = Date.parse(data.endDate);+ const spanDays = (end - start) / (1000 * 60 * 60 * 24);+ return spanDays >= 0 && spanDays < MAX_SLOT_GENERATION_DAYS;+ },+ {+ message: `The date range must span fewer than ${MAX_SLOT_GENERATION_DAYS} days, with endDate on or after startDate.`,+ path: ["endDate"],+ },+ ).openapi("SlotGenerator");const slotsInputSchema = zdiff --git a/apps/web/src/features/poll/constants.ts b/apps/web/src/features/poll/constants.tsnew file mode 100644index 000000000..de297c96b--- /dev/null+++ b/apps/web/src/features/poll/constants.ts@@ -0,0 +1 @@+export const MAX_POLL_OPTIONS = 100;diff --git a/apps/web/src/i18n/client.tsx b/apps/web/src/i18n/client.tsxindex c72e373a2..8ccb732b5 100644--- a/apps/web/src/i18n/client.tsx+++ b/apps/web/src/i18n/client.tsx@@ -1,5 +1,6 @@"use client";+import { LocaleProvider } from "@rallly/ui/locale-provider";import type { Resource } from "i18next";import { createInstance } from "i18next";import ICU from "i18next-icu";@@ -38,7 +39,9 @@ export function I18nProvider({return (<I18nextProvider i18n={i18n} defaultNS={defaultNS}>- {children}+ {/* Feeds the locale to react-aria date/time components app-wide, so they+ don't each wrap their own provider. */}+ <LocaleProvider locale={locale}>{children}</LocaleProvider></I18nextProvider>);}diff --git a/apps/web/src/lib/datetime/locales.test.ts b/apps/web/src/lib/datetime/locales.test.tsindex 381ba3914..cdc90447a 100644--- a/apps/web/src/lib/datetime/locales.test.ts+++ b/apps/web/src/lib/datetime/locales.test.ts@@ -38,19 +38,24 @@ describe("getLocaleDefaults", () => {describe("getWeekdayNames", () => {it("starts with Sunday for en", () => {expect(getWeekdayNames("en")).toEqual([- { day: 0, label: "Sunday" },- { day: 1, label: "Monday" },- { day: 2, label: "Tuesday" },- { day: 3, label: "Wednesday" },- { day: 4, label: "Thursday" },- { day: 5, label: "Friday" },- { day: 6, label: "Saturday" },+ { day: 0, label: "Sunday", short: "Sun" },+ { day: 1, label: "Monday", short: "Mon" },+ { day: 2, label: "Tuesday", short: "Tue" },+ { day: 3, label: "Wednesday", short: "Wed" },+ { day: 4, label: "Thursday", short: "Thu" },+ { day: 5, label: "Friday", short: "Fri" },+ { day: 6, label: "Saturday", short: "Sat" },]);});it("starts with Monday for de, keeping canonical day numbers", () => {const weekdays = getWeekdayNames("de");- expect(weekdays[0]).toEqual({ day: 1, label: "Montag" });- expect(weekdays[6]).toEqual({ day: 0, label: "Sonntag" });+ expect(weekdays[0]).toEqual({ day: 1, label: "Montag", short: "Mo" });+ expect(weekdays[6]).toEqual({ day: 0, label: "Sonntag", short: "So" });+ });++ it("localizes the abbreviated names", () => {+ expect(getWeekdayNames("fr").map((day) => day.short)).toContain("lun.");+ expect(getWeekdayNames("es").map((day) => day.short)).toContain("lun");});});diff --git a/apps/web/src/lib/datetime/locales.ts b/apps/web/src/lib/datetime/locales.tsindex 5a632d8f8..a02d1e465 100644--- a/apps/web/src/lib/datetime/locales.ts+++ b/apps/web/src/lib/datetime/locales.ts@@ -16,7 +16,7 @@ function getWeekInfo(locale: string): WeekInfo {return l.getWeekInfo?.() ?? l.weekInfo ?? { firstDay: 1 };}-type Weekday = { day: number; label: string };+type Weekday = { day: number; label: string; short: string };const weekdayCache = new Map<string, Weekday[]>();@@ -30,12 +30,20 @@ export function getWeekdayNames(locale: string): Weekday[] {weekday: "long",timeZone: "UTC",});+ // The abbreviated form for compact controls; the long form stays the+ // accessible name so screen readers hear "Monday", not "Mon".+ const shortFormatter = new Intl.DateTimeFormat(locale, {+ weekday: "short",+ timeZone: "UTC",+ });const { weekStart } = getLocaleDefaults(locale);weekdays = Array.from({ length: 7 }, (_, index) => {const day = (weekStart + index) % 7;+ const date = new Date(Date.UTC(2024, 0, 7 + day));return {day,- label: formatter.format(new Date(Date.UTC(2024, 0, 7 + day))),+ label: formatter.format(date),+ short: shortFormatter.format(date),};});weekdayCache.set(locale, weekdays);diff --git a/apps/web/src/app/api/private/utils/time-slots.test.ts b/apps/web/src/lib/datetime/slot-generator.test.tssimilarity index 76%rename from apps/web/src/app/api/private/utils/time-slots.test.tsrename to apps/web/src/lib/datetime/slot-generator.test.tsindex 731a54b5a..ef6549507 100644--- a/apps/web/src/app/api/private/utils/time-slots.test.ts+++ b/apps/web/src/lib/datetime/slot-generator.test.ts@@ -1,9 +1,11 @@import { describe, expect, it } from "vitest";+import type { SlotGeneratorInput } from "./slot-generator";import {dedupeTimeSlots,generateTimeSlots,+ MAX_SLOT_GENERATION_DAYS,parseStartTime,-} from "./time-slots";+} from "./slot-generator";describe("time-slots utilities", () => {describe("parseStartTime", () => {@@ -254,5 +256,63 @@ describe("time-slots utilities", () => {expect(result[1].startTime).toEqual(new Date("2025-01-15T09:30:00Z"));expect(result[0].duration).toBe(30);});++ // The generator is a pure function that never throws — it self-bounds and+ // returns []. Rejecting an oversized range is the API layer's job (see the+ // slotGeneratorSchema refine + route.test.ts); here we lock the primitive's+ // own behaviour so it can't run unbounded or loop on bad input.+ describe("bounds and invalid input", () => {+ it("caps iteration at MAX_SLOT_GENERATION_DAYS instead of running unbounded", () => {+ // Every day allowed, one slot per day, over a multi-year range: without+ // the cap this would produce thousands of slots. It stops at the cap.+ const result = generateTimeSlots(+ {+ startDate: "2025-01-01",+ endDate: "2099-12-31",+ daysOfWeek: ["mon", "tue", "wed", "thu", "fri", "sat", "sun"],+ fromTime: "09:00",+ toTime: "09:30",+ },+ "UTC",+ 30,+ );++ expect(result.length).toBeLessThanOrEqual(MAX_SLOT_GENERATION_DAYS);+ });++ it("returns no slots for non-positive or NaN duration", () => {+ const input: SlotGeneratorInput = {+ startDate: "2025-01-15",+ endDate: "2025-01-15",+ daysOfWeek: ["wed"],+ fromTime: "09:00",+ toTime: "17:00",+ };++ expect(generateTimeSlots(input, "UTC", 0)).toEqual([]);+ expect(generateTimeSlots(input, "UTC", -30)).toEqual([]);+ expect(generateTimeSlots(input, "UTC", Number.NaN)).toEqual([]);+ });++ it("returns no slots for non-positive or NaN interval", () => {+ const base: SlotGeneratorInput = {+ startDate: "2025-01-15",+ endDate: "2025-01-15",+ daysOfWeek: ["wed"],+ fromTime: "09:00",+ toTime: "17:00",+ };++ expect(generateTimeSlots({ ...base, interval: 0 }, "UTC", 30)).toEqual(+ [],+ );+ expect(+ generateTimeSlots({ ...base, interval: -30 }, "UTC", 30),+ ).toEqual([]);+ expect(+ generateTimeSlots({ ...base, interval: Number.NaN }, "UTC", 30),+ ).toEqual([]);+ });+ });});});diff --git a/apps/web/src/app/api/private/utils/time-slots.ts b/apps/web/src/lib/datetime/slot-generator.tssimilarity index 86%rename from apps/web/src/app/api/private/utils/time-slots.tsrename to apps/web/src/lib/datetime/slot-generator.tsindex fd9a9844f..2eb159abb 100644--- a/apps/web/src/app/api/private/utils/time-slots.ts+++ b/apps/web/src/lib/datetime/slot-generator.ts@@ -50,6 +50,10 @@ export const parseStartTime = (duration,});+// Safety bound against unbounded input: the API accepts any two valid dates, so+// without this a range like 1900-9999 would iterate millions of days.+export const MAX_SLOT_GENERATION_DAYS = 366;+export const generateTimeSlots = (generator: SlotGeneratorInput,timeZone: string | undefined,@@ -72,12 +76,17 @@ export const generateTimeSlots = (const endDay = dayjs.utc(generator.endDate).startOf("day");const results: Array<TimeSlot> = [];+ let daysVisited = 0;for (let cursor = startDay;cursor.isSameOrBefore(endDay, "day");cursor = cursor.add(1, "day")) {+ if (daysVisited >= MAX_SLOT_GENERATION_DAYS) {+ break;+ }+ daysVisited++;const date = cursor.format("YYYY-MM-DD");// Get day of week in the target timezoneconst dayInTz = timeZone ? dayjs.tz(date, timeZone).day() : cursor.day();@@ -102,6 +111,11 @@ export const generateTimeSlots = (const interval = generator.interval ?? durationMinutes;const totalMinutes = windowEnd.diff(windowStart, "minute");+ // A non-positive (or NaN) interval would never advance the loop below.+ if (!(duration > 0) || !(interval > 0)) {+ continue;+ }+for (let offset = 0;offset + duration <= totalMinutes;diff --git a/packages/ui/src/date-field-styles.ts b/packages/ui/src/date-field-styles.tsnew file mode 100644index 000000000..177986146--- /dev/null+++ b/packages/ui/src/date-field-styles.ts@@ -0,0 +1,43 @@+import { cn } from "./lib/utils";++/**+ * Shared styling for react-aria segmented date/time fields.+ *+ * Height and radius match the default Button and Input (h-9, rounded-lg) so a+ * date or time field lines up with the rest of the form controls. react-aria+ * exposes focus/invalid/disabled as data attributes on the wrapper rather than+ * through `has-[]` selectors, so the states are re-expressed here.+ */+export const fieldGroupClassName = cn(+ "flex h-9 w-full min-w-0 items-center rounded-lg border border-input bg-background/80 py-1 pr-1 pl-2 text-sm outline-none transition-colors dark:bg-input/30",+ "data-[focus-within]:border-ring data-[focus-within]:ring-3 data-[focus-within]:ring-ring/50",+ "data-[invalid]:border-destructive data-[invalid]:ring-3 data-[invalid]:ring-destructive/20 dark:data-[invalid]:ring-destructive/40",+ "data-[disabled]:opacity-50",+);++/**+ * react-aria wraps the value in Unicode bidi isolates (U+2066/U+2069), emitted+ * as their own `literal` segments. They render invisibly but would still take+ * horizontal padding, pushing the first digit past the field's inset — so they+ * get no padding of their own.+ */+export const isBidiIsolate = (text: string) => /^[-]+$/.test(text);++/** Each segment keeps its own inset, hence the group's tighter pl-2. */+export const segmentClassName = cn(+ "rounded-sm px-0.5 outline-none",+ // Separators are structure, not content — mute them so the values lead.+ "data-[type=literal]:text-muted-foreground",+ // accent is a translucent overlay, so the text stays `foreground` — the+ // near-white primary-foreground would be unreadable on it.+ "focus:bg-accent focus:text-foreground",+ "data-[placeholder]:text-muted-foreground",+ "data-[disabled]:opacity-50",+);++/** Matches the Button `icon-sm` footprint, sized for the h-9 field. */+export const triggerButtonClassName = cn(+ "ml-auto inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground outline-none transition-colors",+ "hover:bg-accent hover:text-foreground",+ "data-[focus-visible]:ring-3 data-[focus-visible]:ring-ring/50",+);diff --git a/packages/ui/src/date-range-picker.tsx b/packages/ui/src/date-range-picker.tsxnew file mode 100644index 000000000..c05f11827--- /dev/null+++ b/packages/ui/src/date-range-picker.tsx@@ -0,0 +1,175 @@+"use client";++import { CalendarIcon, ChevronLeftIcon, ChevronRightIcon } from "lucide-react";+import type {+ DateValue,+ DateRangePickerProps as RADateRangePickerProps,+} from "react-aria-components";+import {+ CalendarCell,+ CalendarGrid,+ CalendarGridBody,+ CalendarGridHeader,+ CalendarHeaderCell,+ DateInput,+ DateRangePicker as DateRangePickerPrimitive,+ DateSegment,+ Dialog,+ Group,+ Heading,+ Popover,+ Button as RAButton,+ RangeCalendar,+} from "react-aria-components";+import {+ fieldGroupClassName,+ isBidiIsolate,+ segmentClassName,+ triggerButtonClassName,+} from "./date-field-styles";+import { cn } from "./lib/utils";++export type DateRangePickerProps = Pick<+ RADateRangePickerProps<DateValue>,+ | "value"+ | "defaultValue"+ | "onChange"+ | "isDisabled"+ | "isInvalid"+ | "minValue"+ | "maxValue"+ | "firstDayOfWeek"+ // Anchors the calendar and empty segments to a month without selecting a value.+ | "placeholderValue"+ | "aria-label"+ | "aria-labelledby"+> & {+ className?: string;+ /** Months shown side by side in the popover. */+ visibleMonths?: number;+};++const cellClassName = cn(+ "flex size-8 cursor-pointer select-none items-center justify-center rounded-md text-sm outline-none",+ "hover:bg-accent",+ "data-[focus-visible]:ring-[3px] data-[focus-visible]:ring-ring/50",+ // Selected span uses the pro-badge treatment: a low-opacity primary fill+ // with primary text. Squared off by default so the days read as one+ // continuous block; only the endpoints round their outer edge.+ "data-[selected]:rounded-none data-[selected]:bg-primary/10 data-[selected]:text-primary",+ "data-[selection-start]:rounded-l-md",+ "data-[selection-end]:rounded-r-md",+ "data-[outside-month]:invisible",+ "data-[disabled]:pointer-events-none data-[disabled]:opacity-50",+ "data-[unavailable]:pointer-events-none data-[unavailable]:line-through data-[unavailable]:opacity-50",+);++const navButtonClassName = cn(+ "inline-flex size-8 cursor-pointer items-center justify-center rounded-md text-muted-foreground outline-none",+ "hover:bg-accent hover:text-foreground",+ "data-[focus-visible]:ring-[3px] data-[focus-visible]:ring-ring/50",+ "data-[disabled]:pointer-events-none data-[disabled]:opacity-50",+);++/**+ * Accessible date range picker with segmented, fully styleable fields — each+ * date part is its own spinbutton (arrow keys, typeahead), so no native date+ * picker UI is involved.+ */+function DateRangePicker({+ className,+ visibleMonths = 1,+ firstDayOfWeek,+ ...props+}: DateRangePickerProps) {+ return (+ <DateRangePickerPrimitive+ {...props}+ firstDayOfWeek={firstDayOfWeek}+ className={cn("flex flex-col gap-2", className)}+ >+ <Group className={fieldGroupClassName}>+ <DateInput slot="start" className="flex items-center">+ {(segment) => (+ <DateSegment+ segment={segment}+ className={cn(+ segmentClassName,+ isBidiIsolate(segment.text) && "px-0",+ )}+ />+ )}+ </DateInput>+ <span aria-hidden className="px-1.5 text-muted-foreground">+ –+ </span>+ <DateInput slot="end" className="flex items-center">+ {(segment) => (+ <DateSegment+ segment={segment}+ className={cn(+ segmentClassName,+ isBidiIsolate(segment.text) && "px-0",+ )}+ />+ )}+ </DateInput>+ <RAButton className={triggerButtonClassName}>+ <CalendarIcon className="size-4" />+ </RAButton>+ </Group>+ <Popover+ className={cn(+ "z-50 rounded-lg border bg-popover p-3 text-popover-foreground shadow-md outline-none",+ "data-[entering]:fade-in-0 data-[entering]:animate-in",+ "data-[exiting]:fade-out-0 data-[exiting]:animate-out",+ )}+ >+ <Dialog className="outline-none">+ {/* firstDayOfWeek isn't forwarded from the picker to its calendar,+ so it has to be passed here too. */}+ <RangeCalendar+ firstDayOfWeek={firstDayOfWeek}+ visibleDuration={{ months: visibleMonths }}+ >+ <header className="relative flex items-center justify-between pb-3">+ <RAButton slot="previous" className={navButtonClassName}>+ <ChevronLeftIcon className="size-4" />+ </RAButton>+ <Heading className="font-medium text-sm" />+ <RAButton slot="next" className={navButtonClassName}>+ <ChevronRightIcon className="size-4" />+ </RAButton>+ </header>+ <div className="flex flex-col gap-4 md:flex-row">+ {Array.from({ length: visibleMonths }, (_, index) => (+ <CalendarGrid+ // biome-ignore lint/suspicious/noArrayIndexKey: month offset is the identity+ key={index}+ offset={index === 0 ? undefined : { months: index }}+ className="border-collapse"+ >+ <CalendarGridHeader>+ {(day) => (+ <CalendarHeaderCell className="size-8 font-normal text-muted-foreground text-xs">+ {day}+ </CalendarHeaderCell>+ )}+ </CalendarGridHeader>+ <CalendarGridBody>+ {(date) => (+ <CalendarCell date={date} className={cellClassName} />+ )}+ </CalendarGridBody>+ </CalendarGrid>+ ))}+ </div>+ </RangeCalendar>+ </Dialog>+ </Popover>+ </DateRangePickerPrimitive>+ );+}++export type { DateValue };+export { DateRangePicker };diff --git a/packages/ui/src/input-group.tsx b/packages/ui/src/input-group.tsxindex b6442ac7b..7c302d2f8 100644--- a/packages/ui/src/input-group.tsx+++ b/packages/ui/src/input-group.tsx@@ -16,7 +16,7 @@ function InputGroup({ className, ...props }: React.ComponentProps<"div">) {data-slot="input-group"role="group"className={cn(- "group/input-group relative flex h-8 w-full min-w-0 items-center rounded-lg border border-input outline-none transition-colors in-data-[slot=combobox-content]:focus-within:border-inherit in-data-[slot=combobox-content]:focus-within:ring-0 has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-start]]:h-auto has-[>textarea]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:flex-col has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot][aria-invalid=true]]:border-destructive has-disabled:bg-input/50 has-disabled:opacity-50 has-[[data-slot=input-group-control]:focus-visible]:ring-3 has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot][aria-invalid=true]]:ring-3 has-[[data-slot][aria-invalid=true]]:ring-destructive/20 dark:bg-input/30 dark:has-disabled:bg-input/80 dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40 has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=inline-end]]:[&>input]:pr-1.5 has-[>[data-align=block-start]]:[&>input]:pb-3 has-[>[data-align=inline-start]]:[&>input]:pl-1.5",+ "group/input-group relative flex h-9 w-full min-w-0 items-center rounded-lg border border-input outline-none transition-colors in-data-[slot=combobox-content]:focus-within:border-inherit in-data-[slot=combobox-content]:focus-within:ring-0 has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-start]]:h-auto has-[>textarea]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:flex-col has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot][aria-invalid=true]]:border-destructive has-disabled:bg-input/50 has-disabled:opacity-50 has-[[data-slot=input-group-control]:focus-visible]:ring-3 has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot][aria-invalid=true]]:ring-3 has-[[data-slot][aria-invalid=true]]:ring-destructive/20 dark:bg-input/30 dark:has-disabled:bg-input/80 dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40 has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=inline-end]]:[&>input]:pr-1.5 has-[>[data-align=block-start]]:[&>input]:pb-3 has-[>[data-align=inline-start]]:[&>input]:pl-1.5",className,)}{...props}diff --git a/packages/ui/src/locale-provider.tsx b/packages/ui/src/locale-provider.tsxnew file mode 100644index 000000000..e727dc0fe--- /dev/null+++ b/packages/ui/src/locale-provider.tsx@@ -0,0 +1,19 @@+"use client";++import type * as React from "react";+import { I18nProvider } from "react-aria-components";++/**+ * Provides the locale to react-aria components (date/time pickers, calendars).+ * They read locale only from context, so one provider near the app root serves+ * every such component below it — no per-component wrapping needed.+ */+export function LocaleProvider({+ locale,+ children,+}: {+ locale: string;+ children: React.ReactNode;+}) {+ return <I18nProvider locale={locale}>{children}</I18nProvider>;+}diff --git a/packages/ui/src/time-field.tsx b/packages/ui/src/time-field.tsxnew file mode 100644index 000000000..fddaee371--- /dev/null+++ b/packages/ui/src/time-field.tsx@@ -0,0 +1,61 @@+"use client";++import type {+ TimeFieldProps as RATimeFieldProps,+ TimeValue,+} from "react-aria-components";+import {+ DateInput,+ DateSegment,+ TimeField as TimeFieldPrimitive,+} from "react-aria-components";+import {+ fieldGroupClassName,+ isBidiIsolate,+ segmentClassName,+} from "./date-field-styles";+import { cn } from "./lib/utils";++export type TimeFieldProps = Pick<+ RATimeFieldProps<TimeValue>,+ | "value"+ | "defaultValue"+ | "onChange"+ | "isDisabled"+ | "isInvalid"+ | "hourCycle"+ | "granularity"+ | "aria-label"+ | "aria-labelledby"+> & {+ className?: string;+};++/**+ * Accessible time input with segmented, fully styleable fields — each part is+ * its own spinbutton (arrow keys, typeahead), so no native time picker UI is+ * involved. Segment order and the AM/PM field follow the locale from context+ * (a LocaleProvider near the app root).+ */+function TimeField({ className, ...props }: TimeFieldProps) {+ return (+ <TimeFieldPrimitive {...props}>+ {/* pr-2 balances the group's pr-1, which is sized for the date picker's+ trailing button; the left inset stays shared so both fields line up. */}+ <DateInput className={cn(fieldGroupClassName, "pr-2", className)}>+ {(segment) => (+ <DateSegment+ segment={segment}+ className={cn(+ segmentClassName,+ isBidiIsolate(segment.text) && "px-0",+ )}+ />+ )}+ </DateInput>+ </TimeFieldPrimitive>+ );+}++export type { TimeValue };+export { TimeField };