feat(admin-portal): port babyboo's date picker and calendar

Adds react-day-picker 10.0.1 (it brings date-fns). The portal bans native date
inputs, and the events and leads forms need a date field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-11-27 00:23:56 +08:00
1 parent 1fa7c60fee
commit c908fbe9fc
13 files changed
+443 -9

No files matched your search

+1 -1
View File
@@ -67,7 +67,7 @@ Alternative: one `services-counter` endpoint that creates both in a transaction.
### 9. Date picker
Port babyboo's `app/components/ui/calendar.tsx` and `date-picker.tsx` (with their tests), adding `react-day-picker` 10.0.1 and `date-fns` ^4.4.0, the versions babyboo uses. Required by the native-date-input ban; change 4 reuses the picker on phones.
Port babyboo's `app/components/ui/calendar.tsx` and `date-picker.tsx` (with their tests), adding `react-day-picker` 10.0.1, the version babyboo uses (it depends on `date-fns` itself, so no direct `date-fns` dependency). Required by the native-date-input ban; change 4 reuses the picker on phones.
### 10. Module
@@ -7,12 +7,13 @@ Lead capture (change 4) records every lead against an event, so staff need to cr
## What Changes
- **Admin portal Events screens**: a paged list (search by name, filter by enabled), a create page and an edit page. Desktop-first, like Users and Roles.
- **`mobile-api` gains `/api/admin/events`**: list, get, create and update, guarded by a new `BO_EVENTS` module. They call the existing `services-counter` event endpoints (`findByPropertyAndPageable`, `findByUuid`, `save`); `services-counter` and its schema do not change.
- **`mobile-api` gains `/api/admin/events`**: list, get, create and update, guarded by a new `BO_EVENTS` module. They call the existing `services-counter` event endpoints (`findByPropertyAndPageable`, `findByUuid`, `save`); the `event` table does not change.
- **Event fields kept** from Tastefully: name, location, start date, end date, enabled. Tastefully's backoffice rules carry over: name and location required, both dates required, end date not before start date, dates are whole days, new events start enabled.
- **Event team**: each event has a team of salespeople (active admin users), chosen on create and edit and stored in a new `services-counter` table `event_salesperson`. Change 4 limits a lead's salesperson to the event's team.
- **Not kept**: the four Tastefully upload fields (floor plan, stage activities, lucky draw, taste rewards). Their columns stay in the table and are left untouched on update.
- **No delete**, as in Tastefully. Leads will reference events, so an event is disabled instead.
- **Back-office module** `BO_EVENTS` (`/events`) added to `service-system`.`module`; SQL in this change folder, mirrored in `local/seed/`.
- **Date picker**: the portal forbids native date inputs (an existing test), so babyboo's `DatePicker` and `Calendar` components are ported, adding `react-day-picker` and `date-fns`. Change 4 reuses them for the follow-up date.
- **Date picker**: the portal forbids native date inputs (an existing test), so babyboo's `DatePicker` and `Calendar` components are ported, adding `react-day-picker`. Change 4 reuses them for the follow-up date.
Not in this change: event booths, products, receipts, lucky draw and the other Tastefully event sub-screens; event company scoping (the design keeps `user` as the only existing table that gains `company_id`).
@@ -26,8 +27,9 @@ None.
## Impact
- `solvway-admin-portal`: new `app/events/**` pages, `app/api/events/**` route handlers, an events service, the ported date picker and calendar, `/events` in the route-module map. New dependencies `react-day-picker` and `date-fns`.
- `solvway-admin-portal`: new `app/events/**` pages, `app/api/events/**` route handlers, an events service, the ported date picker and calendar, `/events` in the route-module map. New dependency `react-day-picker`.
- `solvway-mobile-api`: new `AdminEventController`, `AdminEventService`, DTOs and counter endpoint constants.
- Database `service-system`: one new `module` row. Additive only.
- `local/seed/03-colite.sql`: mirrors the module row.
- No change to `services-counter`, the gateway, or the `event` table.
- `solvway-services-counter`: `EventSalesperson` entity and team endpoints.
- Database: new table `service-counter`.`event_salesperson` and one new `service-system`.`module` row. Additive only.
- `local/seed/03-colite.sql`: mirrors both.
- No change to the gateway or the `event` table.
+2 -2
View File
@@ -19,8 +19,8 @@ Babyboo source: `~/Projects/babyboo` (read only). Tastefully backoffice rules: `
## 4. Admin portal
- [ ] 4.1 Port babyboo's `calendar.tsx` and `date-picker.tsx` (and their tests) into `app/components/ui/`, adding `react-day-picker` 10.0.1 and `date-fns` ^4.4.0 to `package.json` (`npm install`, commit the lockfile). Verify: `npm run lint && npx tsc --noEmit && npx vitest run` exit 0.
- Scope: `solvway-admin-portal/app/components/ui/**`, `solvway-admin-portal/package.json`, `solvway-admin-portal/package-lock.json`
- [x] 4.1 Port babyboo's `calendar.tsx` and `date-picker.tsx` (and their tests) into `app/components/ui/`, with their helpers `app/lib/date-input.ts` (and test), `test/pickDate.ts` and the four `Ui*` i18n keys, adding `react-day-picker` 10.0.1 to `package.json` (`npm install`, commit the lockfile; it brings `date-fns` itself). Verify: `npm run lint && npx tsc --noEmit && npx vitest run` exit 0.
- Scope: `solvway-admin-portal/app/components/ui/**`, `solvway-admin-portal/app/lib/date-input*`, `solvway-admin-portal/test/pickDate.ts`, `solvway-admin-portal/app/lib/i18n/defaultMessages.ts`, `solvway-admin-portal/package.json`, `solvway-admin-portal/package-lock.json`
- [ ] 4.2 Add the Events screens on the Users pattern: `app/events/page.tsx` (list: search, enabled filter, sortable name/start/end, columns name, location, start, end, enabled; row Edit), `app/events/new/page.tsx`, `app/events/[uuid]/page.tsx`, an `EventForm` (name, location, start and end `DatePicker`, enabled on edit only, team multi-select from salesperson-options with inactive members shown marked), route handlers `app/api/events/**`, `app/lib/services/adminEvents.ts`, types, i18n defaults, and `/events` → `BO_EVENTS` in `routeModules`. Form checks required fields and end not before start before submitting; API errors show on the field. `TEAM_NOT_SAVED` lands on the edit page with its message. Tests first (vitest) for each portal-visible scenario. Verify: `npm run lint && npx tsc --noEmit && npx vitest run && npm run build` exit 0.
- Scope: `solvway-admin-portal/app/**`
@@ -0,0 +1,23 @@
import { describe, expect, it } from "vitest";
import { render } from "@testing-library/react";
import { Calendar } from "./calendar";
describe("Calendar", () => {
it("marks today, and only today, with rdp-today", () => {
const { container } = render(
<Calendar mode="single" today={new Date(2026, 9, 9)} defaultMonth={new Date(2026, 9, 1)} />,
);
const marked = Array.from(container.querySelectorAll(".rdp-today"));
expect(marked).toHaveLength(1);
expect(marked[0]).toBe(container.querySelector('[data-day="2026-10-09"]'));
});
it("keeps the today marker on a day in the middle of a selected range", () => {
const { container } = render(
<Calendar mode="range" today={new Date(2026, 9, 9)} defaultMonth={new Date(2026, 9, 1)}
selected={{ from: new Date(2026, 9, 7), to: new Date(2026, 9, 11) }} />,
);
const cell = container.querySelector('[data-day="2026-10-09"]')!;
expect(cell).toHaveClass("rdp-today", "rdp-selected", "rdp-range_middle");
});
});
@@ -0,0 +1,21 @@
"use client"
import * as React from "react"
import { DayPicker } from "react-day-picker"
import "react-day-picker/style.css"
import { cn } from "@/app/lib/utils"
/** shadcn-style Calendar on react-day-picker v10, themed by `.admin-calendar` in globals.css. */
function Calendar({ className, captionLayout = "dropdown", ...props }: React.ComponentProps<typeof DayPicker>) {
return (
<DayPicker
data-slot="calendar"
captionLayout={captionLayout}
className={cn("admin-calendar text-sm", className)}
{...props}
/>
)
}
export { Calendar }
@@ -0,0 +1,122 @@
import { useState } from "react";
import { describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { DatePicker } from "./date-picker";
import { pickDate } from "@/test/pickDate";
function Harness(props: { initial?: string; onChange?: (v: string) => void; min?: string; max?: string; disabled?: boolean }) {
const [value, setValue] = useState(props.initial ?? "");
return (
<>
<DatePicker aria-label="Expiry date" value={value} min={props.min} max={props.max} disabled={props.disabled}
onChange={(v) => { setValue(v); props.onChange?.(v); }} />
<button type="button" onClick={() => setValue("")}>reset</button>
</>
);
}
describe("DatePicker", () => {
it("opens the calendar from the keyboard", () => {
render(<Harness />);
fireEvent.keyDown(screen.getByLabelText("Expiry date"), { key: "Enter" });
expect(screen.getByRole("dialog")).toBeInTheDocument();
});
it("stays open when the box is clicked again", async () => {
const user = userEvent.setup();
render(<Harness />);
await user.click(screen.getByLabelText("Expiry date"));
await user.click(screen.getByLabelText("Expiry date"));
expect(screen.getByRole("dialog")).toBeInTheDocument();
});
it("the pickDate helper refuses a disabled day instead of silently doing nothing", () => {
render(<Harness initial="2026-09-15" min="2026-09-10" />);
expect(() => pickDate("Expiry date", "2026-09-01")).toThrow(/not an enabled day/);
});
it("opens the calendar when the box is clicked", () => {
render(<Harness />);
fireEvent.click(screen.getByLabelText("Expiry date"));
expect(screen.getByRole("dialog")).toBeInTheDocument();
});
it("ignores typing", () => {
const onChange = vi.fn();
render(<Harness onChange={onChange} />);
expect(screen.getByLabelText("Expiry date")).toHaveAttribute("readonly");
fireEvent.change(screen.getByLabelText("Expiry date"), { target: { value: "01/09/2026" } });
expect(onChange).not.toHaveBeenCalled();
expect(screen.getByLabelText("Expiry date")).toHaveValue("");
});
it("picks a date through the helper", () => {
const onChange = vi.fn();
render(<Harness onChange={onChange} />);
pickDate("Expiry date", "2026-09-01");
expect(onChange).toHaveBeenLastCalledWith("2026-09-01");
expect(screen.getByLabelText("Expiry date")).toHaveValue("01/09/2026");
});
it("Clear empties an optional field; a required one has no Clear", () => {
const onChange = vi.fn();
const { unmount } = render(<Harness initial="2026-09-01" onChange={onChange} />);
fireEvent.click(screen.getByLabelText("Expiry date"));
fireEvent.click(screen.getByRole("button", { name: "Clear" }));
expect(onChange).toHaveBeenLastCalledWith("");
unmount();
render(<DatePicker aria-label="Due" required value="2026-09-01" onChange={() => {}} />);
fireEvent.click(screen.getByLabelText("Due"));
expect(screen.queryByRole("button", { name: "Clear" })).not.toBeInTheDocument();
});
it("fills the field from a picked day", async () => {
const onChange = vi.fn();
render(<Harness initial="2026-09-15" onChange={onChange} />);
await userEvent.click(screen.getByRole("button", { name: "Open calendar for Expiry date" }));
await userEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: /September 1st, 2026/ }));
expect(onChange).toHaveBeenLastCalledWith("2026-09-01");
expect(screen.getByLabelText("Expiry date")).toHaveValue("01/09/2026");
});
it("does not wipe the value when the selected day is clicked again", async () => {
const onChange = vi.fn();
render(<Harness initial="2026-09-15" onChange={onChange} />);
await userEvent.click(screen.getByRole("button", { name: "Open calendar for Expiry date" }));
await userEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: /September 15th, 2026/ }));
expect(onChange).not.toHaveBeenCalledWith("");
});
it("disables days outside min and max", async () => {
render(<Harness initial="2026-09-15" min="2026-09-10" max="2026-09-20" />);
await userEvent.click(screen.getByRole("button", { name: "Open calendar for Expiry date" }));
const dialog = screen.getByRole("dialog");
expect(within(dialog).getByRole("button", { name: /September 9th, 2026/ })).toBeDisabled();
expect(within(dialog).getByRole("button", { name: /September 21st, 2026/ })).toBeDisabled();
expect(within(dialog).getByRole("button", { name: /September 10th, 2026/ })).toBeEnabled();
});
it("disables the calendar button when the field is disabled", () => {
render(<Harness disabled />);
expect(screen.getByLabelText("Expiry date")).toBeDisabled();
expect(screen.getByRole("button", { name: "Open calendar for Expiry date" })).toBeDisabled();
});
it("passes id and required to the text box so <Label htmlFor> and native validation keep working", () => {
render(<><label htmlFor="exp">Expiry</label><DatePicker id="exp" required value="" onChange={() => {}} /></>);
expect(screen.getByLabelText("Expiry")).toBeRequired();
});
});
// sales-order-no-contains-search: Input is text-base below md, which cut "DD/MM/YYYY" to "DD/MM/YYY"
// in the 120px range fields at 375px. The box is read-only, so text-sm cannot trigger iOS focus zoom.
describe("DatePicker text size", () => {
it("uses text-sm at every width so the placeholder fits", () => {
render(<Harness />);
const box = screen.getByLabelText("Expiry date");
expect(box).toHaveClass("text-sm");
expect(box).not.toHaveClass("text-base");
});
});
@@ -0,0 +1,138 @@
"use client"
import * as React from "react"
import { CalendarIcon } from "lucide-react"
import type { Matcher } from "react-day-picker"
import { Button } from "@/app/components/ui/button"
import { Calendar } from "@/app/components/ui/calendar"
import { Input } from "@/app/components/ui/input"
import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from "@/app/components/ui/popover"
import { dateToIso, formatDmy, isoToDate } from "@/app/lib/date-input"
import { cn } from "@/app/lib/utils"
import { useT } from "@/app/lib/i18n/MessagesProvider"
type DmyInputProps = Omit<React.ComponentProps<"input">, "value" | "onChange" | "type" | "readOnly"> & {
value: string
onOpen: () => void
}
const OPEN_KEYS = new Set(["Enter", " ", "ArrowDown"])
/** Read-only box showing DD/MM/YYYY; the calendar is the only way to change the value. */
function DmyInput({ value, onOpen, placeholder, className, ...props }: DmyInputProps) {
const t = useT()
// text-sm at every width: Input's mobile text-base cut "DD/MM/YYYY" in the 120px range boxes; read-only, so no iOS zoom.
return (
<Input
{...props}
type="text"
readOnly
inputMode="none"
aria-haspopup="dialog"
placeholder={placeholder ?? t("UiDatePlaceholder")}
value={formatDmy(value)}
className={cn("cursor-pointer text-sm", className)}
onClick={props.disabled ? undefined : onOpen}
onKeyDown={(e) => {
if (!props.disabled && OPEN_KEYS.has(e.key)) {
e.preventDefault()
onOpen()
}
}}
/>
)
}
/** Year-dropdown range and disabled days for a min/max pair ("yyyy-MM-dd"). */
function calendarBounds(min?: string, max?: string) {
const minDate = min ? isoToDate(min) : undefined
const maxDate = max ? isoToDate(max) : undefined
const disabled: Matcher[] = []
if (minDate) disabled.push({ before: minDate })
if (maxDate) disabled.push({ after: maxDate })
return {
startMonth: minDate ?? new Date(1920, 0),
endMonth: maxDate ?? new Date(new Date().getFullYear() + 10, 11),
disabled,
}
}
interface DatePickerProps {
value: string
onChange: (iso: string) => void
id?: string
"aria-label"?: string
"aria-labelledby"?: string
"aria-invalid"?: boolean
"aria-describedby"?: string
required?: boolean
disabled?: boolean
min?: string
max?: string
placeholder?: string
className?: string
}
function DatePicker({ value, onChange, required, min, max, className, ...inputProps }: DatePickerProps) {
const t = useT()
const [open, setOpen] = React.useState(false)
const anchorRef = React.useRef<HTMLDivElement>(null)
const selected = isoToDate(value)
const bounds = calendarBounds(min, max)
const label = inputProps["aria-label"]
const labelledby = inputProps["aria-labelledby"]
const buttonId = React.useId()
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverAnchor asChild>
<div ref={anchorRef} data-slot="date-picker" className={cn("relative h-9", className)}>
<DmyInput {...inputProps} required={required} value={value} onOpen={() => setOpen(true)} className="h-full pr-12" />
<PopoverTrigger asChild>
<Button
type="button"
variant="ghost"
size="icon"
disabled={inputProps.disabled}
id={buttonId}
aria-label={label ? t("UiOpenCalendarFor", { label }) : t("UiOpenCalendar")}
aria-labelledby={!label && labelledby ? `${buttonId} ${labelledby}` : undefined}
className="absolute top-0 right-0 h-full w-9"
>
<CalendarIcon />
</Button>
</PopoverTrigger>
</div>
</PopoverAnchor>
<PopoverContent className="w-auto p-3" align="start" onInteractOutside={(e) => {
// The boxes sit in PopoverAnchor, outside the content, so radix treats a click on them
// as outside and closes; keep it open (the box re-opens, the icon still toggles).
if (anchorRef.current?.contains(e.target as Node)) e.preventDefault()
}}>
<Calendar
mode="single"
selected={selected}
defaultMonth={selected ?? (bounds.endMonth < new Date() ? bounds.endMonth : undefined)}
startMonth={bounds.startMonth}
endMonth={bounds.endMonth}
disabled={bounds.disabled}
onSelect={(d) => {
if (!d) return // clicking the selected day again deselects; keep the value
onChange(dateToIso(d))
setOpen(false)
}}
/>
{!required ? (
<div className="flex justify-end border-t pt-2">
<Button type="button" variant="ghost" size="sm" onClick={() => { onChange(""); setOpen(false) }}>
{t("UiClear")}
</Button>
</div>
) : null}
</PopoverContent>
</Popover>
)
}
export { DatePicker, DmyInput, calendarBounds }
export type { DatePickerProps }
@@ -0,0 +1,24 @@
import { describe, expect, it } from "vitest";
import { dateToIso, formatDmy, isoToDate } from "./date-input";
describe("formatDmy", () => {
it("formats ISO as DD/MM/YYYY", () => {
expect(formatDmy("1990-03-14")).toBe("14/03/1990");
});
it("returns empty for non-ISO input", () => {
expect(formatDmy("")).toBe("");
expect(formatDmy("14/03/1990")).toBe("");
});
});
describe("isoToDate / dateToIso", () => {
it("uses local date parts, not UTC", () => {
const d = isoToDate("1990-03-14")!;
expect([d.getFullYear(), d.getMonth(), d.getDate()]).toEqual([1990, 2, 14]);
expect(dateToIso(new Date(1990, 2, 14, 0, 30))).toBe("1990-03-14");
});
it("isoToDate returns undefined for empty or invalid", () => {
expect(isoToDate("")).toBeUndefined();
expect(isoToDate("1990-02-31")).toBeUndefined();
});
});
@@ -0,0 +1,24 @@
const pad = (n: number) => String(n).padStart(2, "0");
/** Local-midnight Date for y/m/d, or undefined when the parts are not a real calendar day. */
function realDate(y: number, m: number, d: number): Date | undefined {
const dt = new Date(y, m - 1, d);
return dt.getFullYear() === y && dt.getMonth() === m - 1 && dt.getDate() === d ? dt : undefined;
}
/** "yyyy-MM-dd" → "DD/MM/YYYY"; "" for anything else. */
export function formatDmy(iso: string): string {
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso);
return m ? `${m[3]}/${m[2]}/${m[1]}` : "";
}
/** "yyyy-MM-dd" → local-midnight Date; undefined for "" or an impossible date. */
export function isoToDate(iso: string): Date | undefined {
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso);
return m ? realDate(Number(m[1]), Number(m[2]), Number(m[3])) : undefined;
}
/** Date → "yyyy-MM-dd" from LOCAL parts (toISOString would shift the day in UTC+8). */
export function dateToIso(d: Date): string {
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
}
@@ -129,6 +129,10 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
UsrCreatedNoEmail: "User created, but the temporary password email could not be sent. Open the user from the users list and use Send password reset to try again.",
UsrBackToUsers: "Back to users",
AdminPasswordHint: "At least 8 characters, with at least one capital letter and one small letter.",
UiDatePlaceholder: "DD/MM/YYYY",
UiOpenCalendarFor: "Open calendar for {label}",
UiOpenCalendar: "Open calendar",
UiClear: "Clear",
UsrLoadFailed: "Failed to load user",
UsrSaved: "User saved.",
UsrResetSent: "Password reset email sent to {email}.",
+43
View File
@@ -15,6 +15,7 @@
"next": "^16.4.5",
"radix-ui": "^1.6.7",
"react": "^19.2.8",
"react-day-picker": "10.0.1",
"react-dom": "^19.2.8",
"tailwind-merge": "^3.6.0"
},
@@ -513,6 +514,12 @@
"node": ">=20.19.0"
}
},
"node_modules/@date-fns/tz": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@date-fns/tz/-/tz-1.5.0.tgz",
"integrity": "sha512-lwYN/vDPeNRULcepoE/LO2Pgx+7/RV+S9ARfbc9lr2DtGkOD7pAiruHvbR1RX3Qyf6ja47EWJDMsNK5vK08DJg==",
"license": "MIT"
},
"node_modules/@emnapi/core": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",
@@ -5304,6 +5311,16 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/date-fns": {
"version": "4.4.0",
"resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.4.0.tgz",
"integrity": "sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/kossnocorp"
}
},
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
@@ -8670,6 +8687,32 @@
"node": ">=0.10.0"
}
},
"node_modules/react-day-picker": {
"version": "10.0.1",
"resolved": "https://registry.npmjs.org/react-day-picker/-/react-day-picker-10.0.1.tgz",
"integrity": "sha512-eNh6BlwcYInWaJtRv18mXQ06Ys/H6rdTZAnTaSdOYJuTpwP1JMCHNd1FDRadA+gbeinq+psdULN5Xnowy9mV8w==",
"license": "MIT",
"dependencies": {
"@date-fns/tz": "^1.4.1",
"date-fns": "^4.1.0"
},
"engines": {
"node": ">=18"
},
"funding": {
"type": "individual",
"url": "https://github.com/sponsors/gpbl"
},
"peerDependencies": {
"@types/react": ">=16.8.0",
"react": ">=16.8.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/react-dom": {
"version": "19.2.8",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.8.tgz",
+1
View File
@@ -21,6 +21,7 @@
"next": "^16.4.5",
"radix-ui": "^1.6.7",
"react": "^19.2.8",
"react-day-picker": "10.0.1",
"react-dom": "^19.2.8",
"tailwind-merge": "^3.6.0"
},
+32
View File
@@ -0,0 +1,32 @@
import { fireEvent, screen, within } from "@testing-library/react";
function topPopover() {
const dialogs = screen.getAllByRole("dialog");
return dialogs[dialogs.length - 1];
}
/** Shows `iso`'s month in the popover's first calendar month and clicks the day. */
function clickDay(pop: HTMLElement, iso: string) {
const [month, year] = within(pop).getAllByRole("combobox");
const [y, m] = iso.split("-").map(Number);
fireEvent.change(year, { target: { value: String(y) } });
fireEvent.change(month, { target: { value: String(m - 1) } });
const day = pop.querySelector<HTMLButtonElement>(`[data-day="${iso}"] button`);
// A disabled day ignores the click, so fail loudly instead of letting the test pass vacuously.
if (!day || day.disabled) throw new Error(`pickDate: ${iso} is not an enabled day in the calendar`);
fireEvent.click(day);
}
/** Picks `iso` (yyyy-MM-dd) in the calendar of the date box labelled `label`. */
export function pickDate(label: string | RegExp | HTMLElement, iso: string) {
fireEvent.click(label instanceof HTMLElement ? label : screen.getByLabelText(label));
clickDay(topPopover(), iso);
}
/** Picks the range `from`–`to` in the calendar of the range box labelled `fromLabel`. */
export function pickRange(fromLabel: string | RegExp, from: string, to: string) {
fireEvent.click(screen.getByLabelText(fromLabel));
const pop = topPopover();
clickDay(pop, from);
clickDay(pop, to);
}