loopable / web /src /customer-grid /DatePicker.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
0aaeea7 verified
Raw History Blame Contribute Delete
47.5 kB
import { useEffect, useId, useMemo, useState } from "react";
import { API_V1, CREDENTIALS } from "../apiContract";
import type { DateRecurrence, DateRecurrenceRule, Field } from "./types";
import { AnchoredOverlay } from "./OverlaySurface";
import type { AnchorRect } from "./OverlaySurface";
import "../styles/wave46/field-panels.css";
const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const WEEKDAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
const WEEKDAY_INITIALS = ["M", "T", "W", "T", "F", "S", "S"];
const ORDINALS: ReadonlyArray<readonly [DateRecurrenceRule["ordinal"], string]> = [[1, "First"], [2, "Second"], [3, "Third"], [4, "Fourth"], [5, "Fifth"], [-1, "Last"]];
const RULE_KINDS = ["daily", "weekly", "monthly", "monthly_ordinal", "yearly", "holiday"] as const;
// W47-T25 (R1): a rule may now be ANCHORED, meaning "the date is N days on, after or before
// another date field". The other date field is the recurrence's EXISTING `anchorField`, so there
// is no second anchor concept and no per-rule anchor; because that anchor is a column, every
// record computes its own answer from its own value.
// `anchored` remains local because only the server validates its anchor semantics. Its shared
// quantity/unit/relation vocabulary now lives in `types.ts` too, so holiday and anchored editors
// cannot drift into incompatible control shapes again.
type AnchoredUnit = NonNullable<DateRecurrenceRule["unit"]>;
type AnchoredRelation = NonNullable<DateRecurrenceRule["relation"]>;
type DateRule = Omit<DateRecurrenceRule, "kind"> & {
kind: DateRecurrenceRule["kind"] | "anchored";
};
type RuleKind = DateRule["kind"] | "monthly_ordinal";
const OFFSET_UNIT_LABELS: Record<AnchoredUnit, string> = {
day: "day",
business_day: "business day",
weekday: "weekday",
week: "week",
month: "month",
year: "year",
};
// W46-T33: a holiday rule may now name ONE holiday instead of a whole national calendar, so the
// code is any string the server's registry admits and `group` says which heading it belongs under.
type CalendarOption = { code: string; label: string; group?: "calendar" | "holiday" };
// The two entries the server is certain to send, so the first paint before the preview call
// returns is never an empty dropdown. The seventeen single holidays are NOT copied here: the
// list is the server's, and a second copy would go stale the day one is added.
const DEFAULT_CALENDARS: CalendarOption[] = [
{ code: "TENANT", label: "This tenant's holiday calendar", group: "calendar" },
{ code: "US", label: "United States federal holidays", group: "calendar" },
{ code: "CA", label: "Canada federal public holidays", group: "calendar" },
];
const CALENDAR_GROUPS: ReadonlyArray<readonly [CalendarOption["group"], string]> = [
["calendar", "Whole calendars"],
["holiday", "Single holidays"],
];
function parseIso(value: unknown): Date | null {
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return null;
const [year, month, day] = value.split("-").map(Number);
const date = new Date(Date.UTC(year, month - 1, day));
return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day ? date : null;
}
function iso(date: Date): string { return date.toISOString().slice(0, 10); }
function addMonths(date: Date, amount: number): Date { const out = new Date(date); out.setUTCMonth(out.getUTCMonth() + amount); return out; }
function bounded(value: unknown, lower: number, upper: number, fallback: number): number { const number = Math.round(Number(value)); return Number.isFinite(number) ? Math.max(lower, Math.min(upper, number)) : fallback; }
function ruleKind(rule: DateRule): RuleKind { return rule.kind === "monthly" && rule.ordinal !== undefined ? "monthly_ordinal" : rule.kind; }
function holidayRelation(rule: DateRule): AnchoredRelation {
if (rule.relation === "before" || rule.relation === "on" || rule.relation === "after") return rule.relation;
const legacyOffset = Number(rule.offset ?? 0);
return legacyOffset < 0 ? "before" : legacyOffset > 0 ? "after" : "on";
}
function holidayOffset(rule: DateRule): number {
return bounded(Math.abs(Number(rule.offset ?? 1)) || 1, 1, 366, 1);
}
function offsetUnitLabel(unit: AnchoredUnit | undefined): string { return OFFSET_UNIT_LABELS[unit ?? "day"]; }
function newRule(kind: RuleKind, selected: Date): DateRule {
if (kind === "weekly") return { kind, interval: 1, weekdays: [((selected.getUTCDay() + 6) % 7)] };
if (kind === "monthly_ordinal") return { kind: "monthly", interval: 1, ordinal: 1, weekday: 0 };
if (kind === "monthly") return { kind, interval: 1, day: selected.getUTCDate() };
if (kind === "yearly") return { kind, interval: 1, month: selected.getUTCMonth() + 1, day: selected.getUTCDate() };
if (kind === "holiday") return { kind, interval: 1, calendar: "US", offset: 0, unit: "day", relation: "on" };
// ⛔ Never emit `interval: 0`: `clean_date_recurrence` bounds it to 1..366 and SILENTLY DROPS
// the whole rule below that, so an "on" relation still carries 1.
if (kind === "anchored") return { kind, interval: 1, unit: "day", relation: "after" };
return { kind, interval: 1 };
}
// The unit words that finish the "Repeat every N ..." sentence, so the control reads as one
// phrase instead of restating the whole rule inside its own dropdown.
function labelForKind(kind: RuleKind): string { return ({ daily: "day", weekly: "week", monthly: "month", monthly_ordinal: "month on a weekday", yearly: "year", holiday: "holiday", anchored: "another date field" } as Record<RuleKind, string>)[kind]; }
// W47-T24: the chooser names what gets ADDED, so its labels are nouns and not `labelForKind`'s
// sentence-finishing unit words. Same order and same six kinds as `RULE_KINDS`; the chooser is
// deliberately its own list so a seventh entry that is NOT a repeat rule can join it.
const ADD_KINDS: ReadonlyArray<readonly [RuleKind, string]> = [
["daily", "Day"], ["weekly", "Week"], ["monthly", "Month"],
["monthly_ordinal", "Month on a weekday"], ["yearly", "Year"], ["holiday", "Holidays"],
// W47-T25: the seventh entry, and the first that is NOT a repeat rule. It is worded as what it
// counts from, because the anchor is the whole point of it.
["anchored", "Days from another date field"],
];
type RecurrenceCondition = {
colId: string;
op: "eq" | "neq" | "not_empty" | "between";
value: string;
value2?: string;
};
// `anchorField` and `conditions` are persisted by the server and absent from `DateRecurrence`;
// they have ridden this local intersection since wave 43. `ends` joins them the same way.
type RecurrenceEnds = { kind: "never" } | { kind: "on"; date: string } | { kind: "after"; count: number };
type LinkedRecurrence = Omit<DateRecurrence, "rules"> & {
rules: DateRule[];
/** Tenant-owned ISO holiday dates travel with the declarative recurrence. */
tenantHolidays?: string[];
anchorField?: { table: "same" | string; field: string; linkedVia?: string };
conditions?: RecurrenceCondition[];
ends?: RecurrenceEnds;
};
// The plain-language line the closed picker shows, so a person reads the schedule without
// reopening the editor. Commas and full stops only, and never a dash character.
function ruleSentence(rule: DateRule, calendars: CalendarOption[]): string {
const every = bounded(rule.interval ?? 1, 1, 366, 1);
const unit = (word: string) => (every === 1 ? word : `${every} ${word}s`);
const kind = ruleKind(rule);
if (kind === "weekly") {
const days = (rule.weekdays ?? []).map((day) => WEEKDAYS[day]).filter(Boolean).join(", ");
return `every ${unit("week")}${days ? ` on ${days}` : ""}`;
}
if (kind === "monthly_ordinal") {
const ordinal = ORDINALS.find(([value]) => value === rule.ordinal)?.[1] ?? "First";
return `every ${unit("month")} on the ${ordinal.toLowerCase()} ${WEEKDAYS[rule.weekday ?? 0]}`;
}
if (kind === "monthly") return `every ${unit("month")} on day ${rule.day ?? 1}`;
if (kind === "yearly") return `every ${unit("year")} on ${MONTHS[bounded(rule.month ?? 1, 1, 12, 1) - 1]} ${rule.day ?? 1}`;
if (kind === "holiday") {
const option = calendars.find((item) => item.code === (rule.calendar ?? "US"));
// The server converts the retired signed +/-1 form before returning it. This fallback keeps
// a just-opened legacy draft intelligible until that read completes; every fresh save uses
// the quantity/unit/relation form below.
const relation = holidayRelation(rule);
const offset = relation === "on" ? 0 : holidayOffset(rule);
const offsetWord = offsetUnitLabel(rule.unit);
const amount = relation === "on" ? "on" : `${offset} ${offsetWord}${offset === 1 ? "" : "s"} ${relation}`;
// W47-T28: on a holiday rule `interval` counts YEARS, which the card now says out loud, so
// the sentence says it too. At 1 the phrase is left exactly as it was, because every year is
// what a holiday rule already means and repeating it reads as noise.
const cadence = every === 1 ? "" : `, every ${every} years`;
// A single holiday reads as itself. "each holiday in Christmas Day" is what the calendar
// phrasing becomes once a rule can name one day, and it is not a sentence anybody wrote.
if (option?.group === "holiday") return `${amount} ${option.label}${cadence}`;
return `${amount} each holiday in ${option?.label ?? "public holidays"}${cadence}`;
}
if (kind === "anchored") {
// `unit()` above drops the count at 1, which reads right for "every day" and wrong for
// "1 day after", so an anchored rule spells its own phrase out.
const relation = rule.relation ?? "after";
if (relation === "on") return "on the anchor date";
const unitLabel = offsetUnitLabel(rule.unit);
return `${every} ${unitLabel}${every === 1 ? "" : "s"} ${relation} the anchor date`;
}
return `every ${unit("day")}`;
}
function recurrenceSentence(rules: DateRule[], ends: RecurrenceEnds, calendars: CalendarOption[]): string {
if (!rules.length) return "";
const body = rules.map((rule) => ruleSentence(rule, calendars)).join(", and ");
if (ends.kind === "on") return `Repeats ${body}, until ${ends.date}.`;
if (ends.kind === "after") return `Repeats ${body}, ${ends.count} times.`;
return `Repeats ${body}.`;
}
/**
* ⭐⭐ OWNER 2026-08-31 - THE REPEAT RULE BELONGS TO THE RECORD, AND WAVE 47's R1/R2 IS REVERSED.
*
* Owner: *"THE EDIT REPEAT IS STILL NOT PER FIELD."* Shown R1/R2 - *"a date rule anchors on a
* COLUMN, and that is why it is per-record"* - and asked which reading they meant, they chose
* *"Each ROW stores its own repeat rule. Reverse R1/R2."* So this picker no longer writes the
* FIELD at all: it reads and writes `/grid/record-recurrence` for the row it was opened on.
*
* ⛔ `field.recurrence` IS STILL READ, as the default a row INHERITS until it is given a rule of
* its own. Every column saved before today has one, and treating those as "no repeat" would
* silently retire live rules on tables nobody was asked about.
*
* ⭐⭐ AND SAVING NOW WRITES THE CELL, which is the other half of what the owner reported: *"IT
* STILL DOESN'T POPULATE THE CELL AS THE NEXTDATE WHEN I CLICK IT. WHY IS IT ONLY POPULATING ONLY
* WHEN I CLICK THE DATE IN THE CALENDAR ITSELF NOT UNDER REPEAT BUTTON."* It was literal:
* `onChange` - the ONLY path to `patchAndRecord` - was called by a calendar day and by nothing
* else, and the server-side materialiser that did write cells (`routes_grid.py`) declares in its
* own scope note that it runs for `ut_*` user tables only. A per-record rule is one row, so that
* limit is not on this path; `saveEditor` writes the returned next date through the same
* `onChange` a typed date takes, undo stack and permission check included.
*/
export function DatePicker({ anchor, field, fields, pid, scopeKey, value, today, onChange, onClose }: {
anchor: AnchorRect; field: Field; fields: Field[]; pid: number; scopeKey: string; value: unknown; today?: string; onChange: (value: string) => void;
onClose: () => void;
}) {
const selected = parseIso(value) ?? parseIso(today) ?? new Date();
const selectedIso = iso(selected);
const [cursor, setCursor] = useState(() => new Date(Date.UTC(selected.getUTCFullYear(), selected.getUTCMonth(), 1)));
const [rules, setRules] = useState<DateRule[]>(() => field.recurrence?.rules ?? []);
const [previewCount, setPreviewCount] = useState(() => field.recurrence?.previewCount ?? 10);
const [preview, setPreview] = useState<string[]>(() => field.recurrence?.preview ?? []);
const [nextDate, setNextDate] = useState<string | null | undefined>(() => field.recurrence?.nextDate);
const [calendars, setCalendars] = useState<CalendarOption[]>(DEFAULT_CALENDARS);
const [previewError, setPreviewError] = useState("");
// `?? undefined` is load-bearing: `LinkedRecurrence` now widens `rules`, so the assertion is
// only legal in the direction DateRecurrence -> LinkedRecurrence, and a `null` on the source
// side has no counterpart in the target union.
/** The rule this row is currently answering with, and whether it is the row's own. Seeded
* from the FIELD so the picker paints something correct before the record read lands, then
* replaced by that read. */
const [storedRecurrence, setStoredRecurrence] = useState<LinkedRecurrence | undefined>(
() => (field.recurrence ?? undefined) as LinkedRecurrence | undefined
);
const [tenantHolidays, setTenantHolidays] = useState<string[]>(
() => storedRecurrence?.tenantHolidays ?? []
);
const [inherited, setInherited] = useState(true);
const [saving, setSaving] = useState(false);
const [anchorTable, setAnchorTable] = useState(() => storedRecurrence?.anchorField?.table ?? "same");
// W47-T24: the anchor DEFAULTS to this field's own column. `govern_date_recurrence` requires an
// `anchorField` on every recurrence it admits, and the picker used to emit none until somebody
// opened the old disclosure and picked one, so a fresh repeat previewed and saved as a 400.
const [anchorField, setAnchorField] = useState(() => storedRecurrence?.anchorField?.field ?? field.key);
const [linkedVia, setLinkedVia] = useState(() => storedRecurrence?.anchorField?.linkedVia ?? "");
const [conditions, setConditions] = useState<RecurrenceCondition[]>(() => storedRecurrence?.conditions ?? []);
const [ends, setEnds] = useState<RecurrenceEnds>(() => storedRecurrence?.ends ?? { kind: "never" });
// W50-T13: the day the interval counts FROM, and the reason "every 2 weeks on Monday" is not
// ambiguous: which Monday is skipped depends entirely on this date. Empty means "the day this
// picker is showing", which is what every rule saved before this control existed carries, so an
// untouched draft keeps the exact `startDate` it had.
// ⛔ It stays at CONFIG level, never per rule. `recurrence_row_next_date` computes a row's answer
// by replacing this ONE key with that row's anchor cell; a per-rule copy would keep its own phase
// through that substitution and quietly reverse W47-T25 on any multi-rule config.
const [startDate, setStartDate] = useState(() => storedRecurrence?.startDate ?? "");
// Step 1 is a plain date. The repeat editor is a second step in the SAME overlay, so the
// anchor block, the conditions and the rule rows leave the default path entirely.
const [step, setStep] = useState<"date" | "repeat">("date");
// W47-T24 (R1): the old disclosure is gone, wording and all. Its anchor and condition blocks now
// render inline, and the door that reveals them is the SAME "Add another rule" button that
// appends a repeat rule, so one affordance adds every kind of clause. Nothing about what a
// recurrence MEANS changed: this is placement only, and the affordance is built to hold a
// seventh choice.
const [showAnchor, setShowAnchor] = useState(false);
const [showConditions, setShowConditions] = useState(false);
const [chooserOpen, setChooserOpen] = useState(false);
const [restorePoint, setRestorePoint] = useState<null | { rules: DateRule[]; ends: RecurrenceEnds; anchorTable: string; anchorField: string; linkedVia: string; conditions: RecurrenceCondition[]; previewCount: number; showAnchor: boolean; showConditions: boolean; startDate: string }>(null);
const endsName = useId();
const dateFields = useMemo(() => fields.filter((candidate) => candidate.type === "date"), [fields]);
const linkedFields = useMemo(() => fields.filter((candidate) => candidate.type === "link" && candidate.link?.table), [fields]);
const recurrence = useMemo<LinkedRecurrence | null>(() => rules.length ? ({
// An untouched or cleared start falls back to the day on screen, which is the behaviour every
// rule saved before this control had.
startDate: startDate || selectedIso,
rules,
previewCount: bounded(previewCount, 1, 50, 10),
...(anchorField ? { anchorField: {
table: anchorTable,
field: anchorField,
...(anchorTable !== "same" && linkedVia ? { linkedVia } : {}),
} } : {}),
...(conditions.length ? { conditions } : {}),
...(tenantHolidays.length ? { tenantHolidays } : {}),
...(ends.kind !== "never" ? { ends } : {}),
// ⚠ `startDate` is in this list for the same reason every other draft value is: the preview
// effect is keyed on this memo, so a start date missing from the deps renders a control that
// accepts input and changes nothing, with tsc and the production build both green over it.
}) : null, [anchorField, anchorTable, conditions, ends, linkedVia, previewCount, rules, selectedIso, startDate, tenantHolidays]);
/**
* THE RECORD'S OWN RULE, read once per opened cell.
*
* ⚠ IT RESEEDS EVERY DRAFT, not just `rules`. The anchor, the conditions and the Ends clause
* are all parts of ONE stored config, and reseeding a subset would leave the editor showing
* this row's repeat rules under the COLUMN's end date - a mixture that belongs to neither and
* would be saved as if somebody had authored it.
*/
useEffect(() => {
const controller = new AbortController();
void fetch(`${API_V1}/grid/record-recurrence/read`, {
method: "POST", credentials: CREDENTIALS, signal: controller.signal,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ scopeKey, pid, field: field.key, anchorValue: parseIso(value) ? selectedIso : null }),
}).then(async (response) => {
if (!response.ok) return null;
return await response.json().catch(() => null) as
{ recurrence?: LinkedRecurrence | null; inherited?: boolean } | null;
}).then((data) => {
if (!data || controller.signal.aborted) return;
const got = (data.recurrence ?? undefined) as LinkedRecurrence | undefined;
setStoredRecurrence(got);
setInherited(data.inherited !== false);
setRules(got?.rules ?? []);
setTenantHolidays(got?.tenantHolidays ?? []);
setPreviewCount(got?.previewCount ?? 10);
setAnchorTable(got?.anchorField?.table ?? "same");
setAnchorField(got?.anchorField?.field ?? field.key);
setLinkedVia(got?.anchorField?.linkedVia ?? "");
setConditions(got?.conditions ?? []);
setEnds(got?.ends ?? { kind: "never" });
// Part of the SAME stored config as the clauses above, so it reseeds with them. Showing this
// row's rules under a start date belonging to nothing would be the mixture the note warns of.
setStartDate(got?.startDate ?? "");
}).catch(() => { /* The picker still edits a date when the sidecar cannot be read. */ });
return () => controller.abort();
// One read per opened cell. The drafts below are what changes afterwards, and re-running on
// them would overwrite the edit in progress with the stored rule on every keystroke.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [field.key, pid, scopeKey]);
// Server-evaluated preview: the exact payload saved below is sent here, so edited previews
// cannot differ from the default next date after refresh because of timezone/holiday drift.
useEffect(() => {
if (!recurrence) { setPreview([]); setNextDate(undefined); setPreviewError(""); return; }
const controller = new AbortController();
void fetch(`${API_V1}/grid/recurrence-preview`, { method: "POST", credentials: CREDENTIALS, signal: controller.signal,
headers: { "Content-Type": "application/json" }, body: JSON.stringify({ recurrence, scopeKey })
}).then(async (response) => {
const data = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(String(data?.detail?.message ?? "Could not preview recurrence"));
return data as { recurrence?: DateRecurrence; calendars?: CalendarOption[] };
}).then((data) => {
if (controller.signal.aborted) return;
if (data.recurrence) { setPreview(data.recurrence.preview ?? []); setNextDate(data.recurrence.nextDate); }
if (Array.isArray(data.calendars) && data.calendars.length) setCalendars(data.calendars);
setPreviewError("");
}).catch((error: unknown) => { if (!controller.signal.aborted) setPreviewError(error instanceof Error ? error.message : "Could not preview recurrence"); });
return () => controller.abort();
}, [recurrence]);
const updateRule = (index: number, patch: Partial<DateRule>) => setRules((current) => current.map((rule, item) => item === index ? { ...rule, ...patch } : rule));
const replaceKind = (index: number, kind: RuleKind) => setRules((current) => current.map((rule, item) => item === index ? newRule(kind, selected) : rule));
const toggleWeekday = (index: number, weekday: number, checked: boolean) => setRules((current) => current.map((rule, item) => {
if (item !== index) return rule;
const existing = rule.weekdays ?? [];
const weekdays = checked ? [...new Set([...existing, weekday])].sort() : existing.filter((day) => day !== weekday);
return { ...rule, weekdays: weekdays.length ? weekdays : existing };
}));
const openEditor = () => {
setRestorePoint({ rules, ends, anchorTable, anchorField, linkedVia, conditions, previewCount, showAnchor, showConditions, startDate });
if (!rules.length) setRules([newRule("weekly", selected)]);
setChooserOpen(false);
setStep("repeat");
};
const cancelEditor = () => {
if (restorePoint) {
setRules(restorePoint.rules); setEnds(restorePoint.ends); setAnchorTable(restorePoint.anchorTable);
setAnchorField(restorePoint.anchorField); setLinkedVia(restorePoint.linkedVia);
setConditions(restorePoint.conditions); setPreviewCount(restorePoint.previewCount);
setShowAnchor(restorePoint.showAnchor); setShowConditions(restorePoint.showConditions);
setStartDate(restorePoint.startDate);
}
setRestorePoint(null);
setChooserOpen(false);
setStep("date");
};
/**
* Persist the ROW's rule, then write the date it names into the ROW's cell.
*
* ⛔ THE CELL IS WRITTEN FROM THE SERVER'S ANSWER, never from `nextDate` in local state. The
* preview effect and this write would then be two computations of one number, and the one the
* cell keeps has to be the one the store agrees with - which is the same reason the preview
* itself is a server call rather than arithmetic in this file.
* ⚠ A refusal leaves the editor OPEN with its message. Closing on a failed save is how a
* person walks away believing a rule is stored that is not.
*/
const persistRecurrence = (next: LinkedRecurrence | null) => {
setSaving(true);
setPreviewError("");
void fetch(`${API_V1}/grid/record-recurrence`, {
method: "POST", credentials: CREDENTIALS,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ scopeKey, pid, field: field.key, recurrence: next,
anchorValue: parseIso(value) ? selectedIso : null }),
}).then(async (response) => {
const data = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(String(data?.detail?.message ?? data?.error?.message
?? "Could not save this repeat"));
return data as { recurrence?: LinkedRecurrence | null; inherited?: boolean; nextDate?: string | null };
}).then((data) => {
setStoredRecurrence((data.recurrence ?? undefined) as LinkedRecurrence | undefined);
setInherited(data.inherited !== false);
if (data.nextDate) onChange(data.nextDate);
setRestorePoint(null);
setChooserOpen(false);
setStep("date");
}).catch((error: unknown) => {
setPreviewError(error instanceof Error ? error.message : "Could not save this repeat");
}).finally(() => setSaving(false));
};
const saveEditor = () => persistRecurrence(recurrence);
const removeRepeat = () => {
setRules([]); setEnds({ kind: "never" }); setConditions([]); setStartDate("");
setShowAnchor(false); setShowConditions(false);
persistRecurrence(null);
};
const monthStart = new Date(Date.UTC(cursor.getUTCFullYear(), cursor.getUTCMonth(), 1));
const leading = (monthStart.getUTCDay() + 6) % 7;
const days = new Date(Date.UTC(cursor.getUTCFullYear(), cursor.getUTCMonth() + 1, 0)).getUTCDate();
const cells = Array.from({ length: Math.ceil((leading + days) / 7) * 7 }, (_, index) => index - leading + 1);
const summary = recurrenceSentence(rules, ends, calendars);
// Each optional clause is on screen whenever it HOLDS something, or once the chooser opened it.
// The anchor holds something the moment it stops naming this field's own column.
const anchorShown = showAnchor || anchorTable !== "same" || anchorField !== field.key;
const conditionsShown = showConditions || conditions.length > 0;
// W50-T13: at an interval of 1 every candidate day matches and the phase says nothing, so the
// start date earns its row exactly when some rule skips occurrences. A holiday rule counts years
// and an anchored rule counts a distance, but both are still scanned from `startDate`, so the
// control is never a no-op where it appears.
const startShown = rules.some((rule) => bounded(rule.interval ?? 1, 1, 366, 1) > 1);
// This is a body-portal overlay, so `cg-date-picker` alone only supplies its width and padding.
// Keep the shared `cg-pop` contract on the same element: it supplies the opaque surface, border,
// elevation, and readable ink that every anchored editor needs over Glide's canvas.
return <AnchoredOverlay anchor={anchor} className="cg-pop cg-date-picker" placement="bottom-start" onDismiss={onClose} role="dialog" ariaLabel={`Choose a date for ${field.label}`} dataKind="date-picker">
{step === "date" ? <>
<label className="cg-date-boundary">Date<input className="cg-input" type="date" value={selectedIso} aria-label={`Date value for ${field.label}`} onChange={(event) => onChange(event.target.value)} /></label>
<div className="cg-date-picker-head"><button type="button" className="cg-icon-button" aria-label="Previous month" onClick={() => setCursor(addMonths(cursor, -1))}>‹</button><strong>{MONTHS[cursor.getUTCMonth()]} {cursor.getUTCFullYear()}</strong><button type="button" className="cg-icon-button" aria-label="Next month" onClick={() => setCursor(addMonths(cursor, 1))}>›</button></div>
<div className="cg-date-weekdays">{WEEKDAYS.map((day) => <span key={day}>{day}</span>)}</div>
<div className="cg-date-grid">{cells.map((day, index) => {
if (day < 1 || day > days) return <span key={`blank-${index}`} aria-hidden />;
const dateIso = iso(new Date(Date.UTC(cursor.getUTCFullYear(), cursor.getUTCMonth(), day)));
return <button key={dateIso} type="button" className={"cg-date-day" + (dateIso === selectedIso ? " is-selected" : "")} aria-pressed={dateIso === selectedIso} onClick={() => onChange(dateIso)}>{day}</button>;
})}</div>
<div className="w46-date-footer">
{rules.length ? <>
<span className="w46-date-summary">{summary}</span>
<button type="button" className="w46-date-repeat is-set" onClick={openEditor}>Edit repeat</button>
</> : <button type="button" className="w46-date-repeat" onClick={openEditor}>Repeat</button>}
</div>
</> : <div className="w46-recur">
<div className="w46-recur-head">
<button type="button" className="w46-recur-back" aria-label="Back to the calendar" onClick={cancelEditor}>‹</button>
<div className="cg-pop-title">Custom repeat</div>
</div>
{rules.map((rule, index) => <div className="w46-recur-card" key={`${rule.kind}-${index}`}>
{/* W47-T25: an anchored rule gets its OWN first row. `RULE_KINDS` deliberately stays at
six, so feeding "anchored" to the kind select would render a control whose value
matches no option and whose first interaction silently rewrites the rule. */}
{rule.kind === "anchored" ? <>
<div className="w46-recur-row">
<span className="w46-recur-label">Date is</span>
<div className="w46-recur-controls">
{(rule.relation ?? "after") !== "on" && <>
<input className="cg-input w46-recur-count" min="1" max="366" type="number" aria-label={`Distance from the anchor ${index + 1}`} value={rule.interval ?? 1} onChange={(event) => updateRule(index, { interval: bounded(event.target.value, 1, 366, 1) })} />
<select className="cg-select" value={rule.unit ?? "day"} aria-label={`Distance unit ${index + 1}`} onChange={(event) => updateRule(index, { unit: event.target.value as AnchoredUnit })}><option value="day">days</option><option value="business_day">business days</option><option value="weekday">weekdays</option><option value="week">weeks</option><option value="month">months</option><option value="year">years</option></select>
</>}
{/* Switching to "on" carries `interval: 1` with it. The count input goes away, and a
stale 5 left behind it would be saved and then read back as a distance nobody
can see. */}
<select className="cg-select" value={rule.relation ?? "after"} aria-label={`Anchor relation ${index + 1}`} onChange={(event) => {
const relation = event.target.value as AnchoredRelation;
updateRule(index, relation === "on" ? { relation, interval: 1 } : { relation });
}}><option value="on">on the anchor date</option><option value="after">after the anchor date</option><option value="before">before the anchor date</option></select>
</div>
</div>
{anchorField === field.key && <div className="w46-recur-row"><span className="w46-recur-word">Choose the date field this counts from.</span></div>}
{(rule.relation ?? "after") === "before" && <div className="w46-recur-row"><span className="w46-recur-word">A date that has already passed is left empty.</span></div>}
</> : rule.kind === "holiday" ? <>
{/* W48C-T11: Holidays is no longer a disconnected +/-1 control. Calendar, quantity,
unit and before/on/after are one sentence, exactly like the server's canonical
rule. `interval` remains the separate cadence in years below. */}
<div className="w46-recur-row">
<span className="w46-recur-label">Holidays</span>
<div className="w46-recur-controls">
<select className="cg-select" value={rule.calendar ?? "US"} aria-label="Public calendar" onChange={(event) => updateRule(index, { calendar: event.target.value })}>{CALENDAR_GROUPS.map(([group, heading]) => {
const members = calendars.filter((calendar) => (calendar.group ?? "calendar") === group);
return members.length ? <optgroup key={heading} label={heading}>{members.map((calendar) => <option key={calendar.code} value={calendar.code}>{calendar.label}</option>)}</optgroup> : null;
})}</select>
{holidayRelation(rule) !== "on" && <>
<input className="cg-input w46-recur-count" min="1" max="366" type="number" aria-label={`Holiday offset quantity ${index + 1}`} value={holidayOffset(rule)} onChange={(event) => updateRule(index, { offset: bounded(event.target.value, 1, 366, 1) })} />
<select className="cg-select" value={rule.unit ?? "day"} aria-label={`Holiday offset unit ${index + 1}`} onChange={(event) => updateRule(index, { unit: event.target.value as AnchoredUnit })}><option value="day">days</option><option value="business_day">business days</option><option value="weekday">weekdays</option><option value="week">weeks</option><option value="month">months</option><option value="year">years</option></select>
</>}
<select className="cg-select" value={holidayRelation(rule)} aria-label={`Holiday offset relation ${index + 1}`} onChange={(event) => {
const relation = event.target.value as AnchoredRelation;
updateRule(index, relation === "on"
? { relation, offset: 0, unit: "day" }
: { relation, offset: holidayOffset(rule) });
}}><option value="before">before</option><option value="on">on</option><option value="after">after</option></select>
</div>
</div>
<div className="w46-recur-row">
<span className="w46-recur-label">Repeat every</span>
<div className="w46-recur-controls">
<input className="cg-input w46-recur-count" min="1" max="366" type="number" aria-label={`Repeat interval ${index + 1}`} value={rule.interval ?? 1} onChange={(event) => updateRule(index, { interval: bounded(event.target.value, 1, 366, 1) })} />
<span className="w46-recur-word">{bounded(rule.interval ?? 1, 1, 366, 1) === 1 ? "year" : "years"}</span>
</div>
</div>
{(rule.calendar ?? "US") === "TENANT" && <div className="w46-recur-row">
<label className="w46-recur-label" htmlFor={`${endsName}-tenant-holidays`}>Tenant holidays</label>
<div className="w46-recur-controls">
<input id={`${endsName}-tenant-holidays`} className="cg-input" aria-label="Tenant holiday dates" placeholder="2026-01-01, 2026-12-25" value={tenantHolidays.join(", ")} onChange={(event) => {
const dates = [...new Set(event.target.value.split(/[,\s]+/).filter((date) => /^\d{4}-\d{2}-\d{2}$/.test(date)))].sort();
setTenantHolidays(dates);
}} />
<span className="w46-recur-word">ISO dates, owned by this tenant</span>
</div>
</div>}
</> : <div className="w46-recur-row">
<span className="w46-recur-label">Repeat every</span>
<div className="w46-recur-controls">
<input className="cg-input w46-recur-count" min="1" max="366" type="number" aria-label={`Repeat interval ${index + 1}`} value={rule.interval ?? 1} onChange={(event) => updateRule(index, { interval: bounded(event.target.value, 1, 366, 1) })} />
<select className="cg-select" value={ruleKind(rule)} aria-label={`Repeat unit ${index + 1}`} onChange={(event) => replaceKind(index, event.target.value as RuleKind)}>{RULE_KINDS.map((kind) => <option key={kind} value={kind}>{labelForKind(kind)}</option>)}</select>
</div>
</div>}
{rule.kind === "weekly" && <div className="w46-recur-row">
<span className="w46-recur-label" id={`${endsName}-days-${index}`}>Repeat on</span>
<div className="w46-recur-pills" role="group" aria-labelledby={`${endsName}-days-${index}`}>{WEEKDAY_INITIALS.map((initial, weekday) => {
const on = (rule.weekdays ?? []).includes(weekday);
return <button key={WEEKDAYS[weekday]} type="button" className={"w46-recur-pill" + (on ? " is-on" : "")} aria-pressed={on} aria-label={WEEKDAYS[weekday]} onClick={() => toggleWeekday(index, weekday, !on)}>{initial}</button>;
})}</div>
</div>}
{rule.kind === "monthly" && rule.ordinal === undefined && <div className="w46-recur-row">
<span className="w46-recur-label">Repeat on</span>
<div className="w46-recur-controls"><span className="w46-recur-word">day</span><input className="cg-input w46-recur-count" min="1" max="31" type="number" aria-label={`Day of the month ${index + 1}`} value={rule.day ?? 1} onChange={(event) => updateRule(index, { day: bounded(event.target.value, 1, 31, 1) })} /></div>
</div>}
{rule.kind === "monthly" && rule.ordinal !== undefined && <div className="w46-recur-row">
<span className="w46-recur-label">Repeat on</span>
<div className="w46-recur-controls">
<select className="cg-select" value={rule.ordinal} aria-label="Month ordinal" onChange={(event) => updateRule(index, { ordinal: Number(event.target.value) as DateRecurrenceRule["ordinal"] })}>{ORDINALS.map(([value, label]) => <option key={value} value={value}>{label}</option>)}</select>
<select className="cg-select" value={rule.weekday ?? 0} aria-label="Month weekday" onChange={(event) => updateRule(index, { weekday: Number(event.target.value) })}>{WEEKDAYS.map((day, weekday) => <option key={day} value={weekday}>{day}</option>)}</select>
</div>
</div>}
{rule.kind === "yearly" && <div className="w46-recur-row">
<span className="w46-recur-label">Repeat on</span>
<div className="w46-recur-controls">
<select className="cg-select" value={bounded(rule.month ?? 1, 1, 12, 1)} aria-label="Month of the year" onChange={(event) => updateRule(index, { month: bounded(event.target.value, 1, 12, 1) })}>{MONTHS.map((month, offset) => <option key={month} value={offset + 1}>{month}</option>)}</select>
<input className="cg-input w46-recur-count" min="1" max="31" type="number" aria-label="Day of the month" value={rule.day ?? 1} onChange={(event) => updateRule(index, { day: bounded(event.target.value, 1, 31, 1) })} />
</div>
</div>}
{rules.length > 1 && <div className="w46-recur-card-foot"><button type="button" className="w46-recur-quiet" onClick={() => setRules((current) => current.filter((_, item) => item !== index))}>Remove rule</button></div>}
</div>)}
{/* W50-T13: "every 2 weeks on Monday" names no Monday until this row says which one it counts
from, which is why it sits directly under the rules rather than behind the chooser. */}
{startShown && <div className="w46-recur-row">
<label className="w46-recur-label" htmlFor={`${endsName}-start`}>Starting on</label>
<div className="w46-recur-controls">
<input id={`${endsName}-start`} className="cg-input w46-recur-date" type="date" aria-label="The date this repeat counts from" value={startDate || selectedIso} onChange={(event) => setStartDate(event.target.value)} />
<span className="w46-recur-word">The interval counts from this date.</span>
</div>
</div>}
{anchorShown && <div className="cg-date-boundary" aria-label="Recurrence anchor">
<label>Anchor database<select className="cg-select" value={anchorTable} onChange={(event) => {
const table = event.target.value;
setAnchorTable(table);
if (table === "same") setLinkedVia("");
else setLinkedVia(linkedFields.find((candidate) => candidate.link?.table === table)?.key ?? "");
setAnchorField(table === "same" ? field.key : "");
}}><option value="same">This database</option>{linkedFields.map((candidate) => <option value={candidate.link!.table} key={candidate.key}>{candidate.label} · {candidate.link!.table}</option>)}</select></label>
{anchorTable === "same" ? <label>Date field<select className="cg-select" value={anchorField} onChange={(event) => setAnchorField(event.target.value)}><option value={field.key}>This date</option>{dateFields.filter((candidate) => candidate.key !== field.key).map((candidate) => <option value={candidate.key} key={candidate.key}>{candidate.label}</option>)}</select></label>
: <><label>Linked through<select className="cg-select" value={linkedVia} onChange={(event) => setLinkedVia(event.target.value)}>{linkedFields.filter((candidate) => candidate.link?.table === anchorTable).map((candidate) => <option value={candidate.key} key={candidate.key}>{candidate.label}</option>)}</select></label><label>Linked date field key<input className="cg-input" value={anchorField} onChange={(event) => setAnchorField(event.target.value)} placeholder="due_date" /></label></>}
</div>}
{conditionsShown && <div className="cg-date-boundary" aria-label="Recurrence conditions"><div className="cg-pop-title">Only when</div>{conditions.map((condition, index) => <div className="cg-date-holidays" key={`${condition.colId}-${index}`}><select className="cg-select" aria-label={`Condition field ${index + 1}`} value={condition.colId} onChange={(event) => setConditions((current) => current.map((item, itemIndex) => itemIndex === index ? { ...item, colId: event.target.value } : item))}>{fields.map((candidate) => <option key={candidate.key} value={candidate.key}>{candidate.label}</option>)}</select><select className="cg-select" aria-label={`Condition operator ${index + 1}`} value={condition.op} onChange={(event) => setConditions((current) => current.map((item, itemIndex) => itemIndex === index ? { ...item, op: event.target.value as RecurrenceCondition["op"], ...(event.target.value === "between" ? {} : { value2: undefined }) } : item))}><option value="eq">is</option><option value="neq">is not</option><option value="not_empty">is not empty</option><option value="between">is between</option></select>{condition.op !== "not_empty" && <input className="cg-input" aria-label={`Condition value ${index + 1}`} value={condition.value} onChange={(event) => setConditions((current) => current.map((item, itemIndex) => itemIndex === index ? { ...item, value: event.target.value } : item))} />}{condition.op === "between" && <input className="cg-input" aria-label={`Condition second value ${index + 1}`} value={condition.value2 ?? ""} onChange={(event) => setConditions((current) => current.map((item, itemIndex) => itemIndex === index ? { ...item, value2: event.target.value } : item))} />}<button type="button" className="cg-link-btn" onClick={() => setConditions((current) => current.filter((_, itemIndex) => itemIndex !== index))}>Remove</button></div>)}<button type="button" className="cg-link-btn" disabled={!fields.length} onClick={() => setConditions((current) => [...current, { colId: fields[0]?.key ?? "", op: "eq", value: "" }])}>+ Add condition</button></div>}
<button type="button" className="w46-recur-add" aria-expanded={chooserOpen} onClick={() => setChooserOpen((open) => !open)}>Add another rule</button>
{chooserOpen && <div className="w46-recur-card">
<div className="w46-recur-controls" role="group" aria-label="Add another rule">
{/* W47-T25: an anchored rule is meaningless without an anchor that is not this field's
own column, so choosing it puts the anchor block on screen in the same click. */}
{ADD_KINDS.map(([kind, label]) => <button key={kind} type="button" className="cg-link-btn" onClick={() => { setRules((current) => [...current, newRule(kind, selected)]); if (kind === "anchored") setShowAnchor(true); setChooserOpen(false); }}>{label}</button>)}
{!anchorShown && <button type="button" className="cg-link-btn" onClick={() => { setShowAnchor(true); setChooserOpen(false); }}>Anchor to another date field</button>}
<button type="button" className="cg-link-btn" disabled={!fields.length} onClick={() => {
setConditions((current) => [...current, { colId: fields[0]?.key ?? "", op: "eq", value: "" }]);
setShowConditions(true); setChooserOpen(false);
}}>Only when a condition is met</button>
</div>
</div>}
<div className="w46-recur-row">
<span className="w46-recur-label" id={`${endsName}-label`}>Ends</span>
<div className="w46-recur-ends" role="group" aria-labelledby={`${endsName}-label`}>
<label className="w46-recur-radio"><input type="radio" name={endsName} checked={ends.kind === "never"} onChange={() => setEnds({ kind: "never" })} /><span>Never</span></label>
<label className="w46-recur-radio"><input type="radio" name={endsName} checked={ends.kind === "on"} onChange={() => setEnds({ kind: "on", date: selectedIso })} /><span>On</span>
<input className="cg-input w46-recur-date" type="date" aria-label="Repeat until this date" disabled={ends.kind !== "on"} value={ends.kind === "on" ? ends.date : ""} onChange={(event) => setEnds({ kind: "on", date: event.target.value })} /></label>
<label className="w46-recur-radio"><input type="radio" name={endsName} checked={ends.kind === "after"} onChange={() => setEnds({ kind: "after", count: 13 })} /><span>After</span>
<input className="cg-input w46-recur-count" type="number" min="1" max="365" aria-label="Number of occurrences" disabled={ends.kind !== "after"} value={ends.kind === "after" ? ends.count : ""} onChange={(event) => setEnds({ kind: "after", count: bounded(event.target.value, 1, 365, 13) })} /><span className="w46-recur-word">occurrences</span></label>
</div>
</div>
{/* W47-T24: "Show next N dates" is a display control, not a clause of the recurrence, so it
reads beside the preview it sizes rather than behind the door that adds rules. */}
<div className="cg-date-preview" aria-live="polite"><div className="cg-pop-title">Next dates{nextDate ? ` · next ${nextDate}` : ""}<label className="w46-recur-preview-count">Show next <select className="cg-select" value={previewCount} aria-label="Number of preview dates" onChange={(event) => setPreviewCount(bounded(event.target.value, 1, 50, 10))}>{[3, 5, 10, 20, 50].map((count) => <option key={count} value={count}>{count}</option>)}</select> dates</label></div>{preview.map((date) => <span key={date}>{date}</span>)}{rules.length > 0 && !preview.length && !previewError && <span>Calculating the server preview…</span>}{previewError && <span role="status">{previewError}</span>}</div>
<div className="w46-recur-foot">
{/* ⚠ THE SENTENCE THAT STOPS A SURPRISE. A row with no rule of its own is answering with
its COLUMN's, and pressing Save here gives the row a rule of its OWN - after which
the column can change and this row will not follow. Saying so beats letting somebody
discover it a month later. */}
{inherited && storedRecurrence?.rules?.length ? (
<span className="w46-recur-word">Repeating from this column's rule. Save to use this record's own rule.</span>
) : null}
{storedRecurrence?.rules?.length && !inherited ? <button type="button" className="w46-recur-quiet is-danger" disabled={saving} onClick={removeRepeat}>Remove repeat</button> : null}
<button type="button" className="w46-recur-quiet" disabled={saving} onClick={cancelEditor}>Cancel</button>
<button type="button" className="w46-recur-save" disabled={saving} onClick={saveEditor}>Save</button>
</div>
</div>}
</AnchoredOverlay>;
}