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 = [[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; type AnchoredRelation = NonNullable; type DateRule = Omit & { kind: DateRecurrenceRule["kind"] | "anchored"; }; type RuleKind = DateRule["kind"] | "monthly_ordinal"; const OFFSET_UNIT_LABELS: Record = { 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 = [ ["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)[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 = [ ["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 & { 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(() => field.recurrence?.rules ?? []); const [previewCount, setPreviewCount] = useState(() => field.recurrence?.previewCount ?? 10); const [preview, setPreview] = useState(() => field.recurrence?.preview ?? []); const [nextDate, setNextDate] = useState(() => field.recurrence?.nextDate); const [calendars, setCalendars] = useState(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( () => (field.recurrence ?? undefined) as LinkedRecurrence | undefined ); const [tenantHolidays, setTenantHolidays] = useState( () => 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(() => storedRecurrence?.conditions ?? []); const [ends, setEnds] = useState(() => 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); 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(() => 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) => 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 {step === "date" ? <>
{MONTHS[cursor.getUTCMonth()]} {cursor.getUTCFullYear()}
{WEEKDAYS.map((day) => {day})}
{cells.map((day, index) => { if (day < 1 || day > days) return ; const dateIso = iso(new Date(Date.UTC(cursor.getUTCFullYear(), cursor.getUTCMonth(), day))); return ; })}
{rules.length ? <> {summary} : }
:
Custom repeat
{rules.map((rule, 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" ? <>
Date is
{(rule.relation ?? "after") !== "on" && <> updateRule(index, { interval: bounded(event.target.value, 1, 366, 1) })} /> } {/* 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. */}
{anchorField === field.key &&
Choose the date field this counts from.
} {(rule.relation ?? "after") === "before" &&
A date that has already passed is left empty.
} : 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. */}
Holidays
{holidayRelation(rule) !== "on" && <> updateRule(index, { offset: bounded(event.target.value, 1, 366, 1) })} /> }
Repeat every
updateRule(index, { interval: bounded(event.target.value, 1, 366, 1) })} /> {bounded(rule.interval ?? 1, 1, 366, 1) === 1 ? "year" : "years"}
{(rule.calendar ?? "US") === "TENANT" &&
{ const dates = [...new Set(event.target.value.split(/[,\s]+/).filter((date) => /^\d{4}-\d{2}-\d{2}$/.test(date)))].sort(); setTenantHolidays(dates); }} /> ISO dates, owned by this tenant
} :
Repeat every
updateRule(index, { interval: bounded(event.target.value, 1, 366, 1) })} />
} {rule.kind === "weekly" &&
Repeat on
{WEEKDAY_INITIALS.map((initial, weekday) => { const on = (rule.weekdays ?? []).includes(weekday); return ; })}
} {rule.kind === "monthly" && rule.ordinal === undefined &&
Repeat on
day updateRule(index, { day: bounded(event.target.value, 1, 31, 1) })} />
} {rule.kind === "monthly" && rule.ordinal !== undefined &&
Repeat on
} {rule.kind === "yearly" &&
Repeat on
updateRule(index, { day: bounded(event.target.value, 1, 31, 1) })} />
} {rules.length > 1 &&
}
)} {/* 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 &&
setStartDate(event.target.value)} /> The interval counts from this date.
} {anchorShown &&
{anchorTable === "same" ? : <>}
} {conditionsShown &&
Only when
{conditions.map((condition, index) =>
{condition.op !== "not_empty" && setConditions((current) => current.map((item, itemIndex) => itemIndex === index ? { ...item, value: event.target.value } : item))} />}{condition.op === "between" && setConditions((current) => current.map((item, itemIndex) => itemIndex === index ? { ...item, value2: event.target.value } : item))} />}
)}
} {chooserOpen &&
{/* 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]) => )} {!anchorShown && }
}
Ends
{/* 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. */}
Next dates{nextDate ? ` · next ${nextDate}` : ""}
{preview.map((date) => {date})}{rules.length > 0 && !preview.length && !previewError && Calculating the server preview…}{previewError && {previewError}}
{/* ⚠ 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 ? ( Repeating from this column's rule. Save to use this record's own rule. ) : null} {storedRecurrence?.rules?.length && !inherited ? : null}
}
; }