From 47215caa0aa8d47f24a47dc043ea9868a8571a5d Mon Sep 17 00:00:00 2001 From: Michiel de Jong Date: Tue, 29 Sep 2026 14:19:02 +0200 Subject: [PATCH 1/4] Calendar: a Repeat field in the row dialog (#1801) The row dialog opened from a calendar view shows a Repeat field instead of the raw recurrence JSON: none, daily, weekly on chosen days, monthly by date or nth weekday, or yearly, ending never, on a date or after N times, with a summary in words. It writes the payload the view already expands; a payload it cannot show reads as Custom, kept as is, with its JSON one click away. A table without a recurrence property gets one (shortname atomic-calendar-recurrence, as in the Event ontology) when a row first repeats. A row's own series (calendarId "atomic") follows the row's date columns, so moving the row moves the series; imported payloads stay the provider's. Co-Authored-By: Claude Opus 5.5 --- .../TablePage/Calendar/CalendarRowFields.tsx | 171 ++++++++ .../TablePage/Calendar/CalendarView.tsx | 105 +++-- .../chunks/TablePage/Calendar/RepeatField.tsx | 401 ++++++++++++++++++ .../TablePage/Calendar/calendarRows.test.ts | 75 ++++ .../chunks/TablePage/Calendar/calendarRows.ts | 172 ++++++++ .../TablePage/Calendar/repeatSummary.test.ts | 103 +++++ .../TablePage/Calendar/repeatSummary.ts | 168 ++++++++ .../Calendar/useCalendarRecurrenceProp.ts | 54 +++ .../chunks/TablePage/ExpandedRowDialog.tsx | 17 +- .../TablePage/Kanban/createSelectProperty.ts | 5 +- browser/lib/src/calendar-repeat.test.ts | 238 +++++++++++ browser/lib/src/calendar-repeat.ts | 334 +++++++++++++++ browser/lib/src/index.ts | 2 + 13 files changed, 1799 insertions(+), 46 deletions(-) create mode 100644 browser/data-browser/src/chunks/TablePage/Calendar/CalendarRowFields.tsx create mode 100644 browser/data-browser/src/chunks/TablePage/Calendar/RepeatField.tsx create mode 100644 browser/data-browser/src/chunks/TablePage/Calendar/calendarRows.test.ts create mode 100644 browser/data-browser/src/chunks/TablePage/Calendar/calendarRows.ts create mode 100644 browser/data-browser/src/chunks/TablePage/Calendar/repeatSummary.test.ts create mode 100644 browser/data-browser/src/chunks/TablePage/Calendar/repeatSummary.ts create mode 100644 browser/data-browser/src/chunks/TablePage/Calendar/useCalendarRecurrenceProp.ts create mode 100644 browser/lib/src/calendar-repeat.test.ts create mode 100644 browser/lib/src/calendar-repeat.ts diff --git a/browser/data-browser/src/chunks/TablePage/Calendar/CalendarRowFields.tsx b/browser/data-browser/src/chunks/TablePage/Calendar/CalendarRowFields.tsx new file mode 100644 index 0000000000..7e354f67ca --- /dev/null +++ b/browser/data-browser/src/chunks/TablePage/Calendar/CalendarRowFields.tsx @@ -0,0 +1,171 @@ +import { + anchorOf, + buildRecurrence, + nativeCalendarPayload, + parseRecurrence, + type RepeatParse, +} from '@tomic/lib'; +import { JSONValue, Resource, useCanWrite, useResource } from '@tomic/react'; +import { useState, type JSX } from 'react'; +import toast from 'react-hot-toast'; +import { styled } from 'styled-components'; +import { ValueForm } from '@components/forms/ValueForm'; +import { + calendarRowTime, + isNativePayload, + readRecurrencePayload, + rowRecord, + type CalendarColumns, + type RecurrencePayload, +} from './calendarRows'; +import { RepeatField } from './RepeatField'; + +/** What the row dialog needs to show a calendar row's own fields. */ +export interface CalendarRowContext extends CalendarColumns { + ensureRecurrenceProp: () => Promise; +} + +/** The calendar fields of a row in its dialog: for now, how it repeats. */ +export function CalendarRowFields({ + subject, + calendar, +}: { + subject: string; + calendar: CalendarRowContext; +}): JSX.Element | null { + const resource = useResource(subject); + const canWrite = useCanWrite(resource); + const [saving, setSaving] = useState(false); + const { recurrenceProp } = calendar; + + const get = (prop: string) => resource.get(prop); + const { payload, time, anchor, parsed } = readRowRepeat( + subject, + get, + calendar, + ); + + if (!anchor) { + // Without a day there is nothing to repeat from. + return null; + } + + const save = (next: RepeatParse) => { + if (next.kind === 'custom') return; + setSaving(true); + void saveRepeat( + resource, + calendar, + nextPayload(subject, next, payload, time), + ) + .catch(error => + toast.error( + `Could not save the repeat: ${error instanceof Error ? error.message : String(error)}`, + ), + ) + .then(() => setSaving(false)); + }; + + return ( +
+ + ) + } + /> +
+ ); +} + +/** The row's series as the Repeat field shows it. An imported series repeats + * from its own start; a native one from the row's day. */ +function readRowRepeat( + subject: string, + get: (prop: string) => unknown, + calendar: CalendarRowContext, +) { + const { recurrenceProp } = calendar; + const value = recurrenceProp ? get(recurrenceProp.subject) : undefined; + const payload = readRecurrencePayload(value); + const time = calendarRowTime(get, calendar); + + try { + // A native series as the view expands it: moved along with its row. + const event = + payload && time && isNativePayload(payload) + ? rowRecord(subject, payload, time).event + : payload?.event; + const start = + payload && !isNativePayload(payload) ? event?.start : time?.start; + const anchor = start && anchorOf(start); + const parsed: RepeatParse = + event && anchor + ? parseRecurrence(event.recurrence, anchor) + : value !== undefined + ? { kind: 'custom' } + : { kind: 'none' }; + + return { payload, time, anchor, parsed }; + } catch { + return { + payload, + time, + anchor: time && anchorOf(time.start), + parsed: { kind: 'custom' } as RepeatParse, + }; + } +} + +async function saveRepeat( + resource: Resource, + calendar: CalendarRowContext, + value: RecurrencePayload | undefined, +) { + const property = await calendar.ensureRecurrenceProp(); + await resource.set(property, value as JSONValue); + await resource.save(); +} + +/** The value to store for a new Repeat setting. A native series is written + * whole; an imported one keeps its payload and only gets new rule lines. + * "Does not repeat" clears a native series and ends an imported one's rule. */ +function nextPayload( + subject: string, + next: Exclude, + payload: RecurrencePayload | undefined, + time: ReturnType, +): RecurrencePayload | undefined { + if (payload && !isNativePayload(payload)) { + const { recurrence: _, ...event } = payload.event; + + return next.kind === 'none' + ? { ...payload, event } + : { + ...payload, + event: { + ...event, + recurrence: buildRecurrence(next.rule, anchorOf(event.start!)), + }, + }; + } + + if (next.kind === 'none' || !time) return undefined; + + return nativeCalendarPayload(subject, next.rule, time); +} + +const Section = styled.div` + padding: 0.5rem; + margin-bottom: 1rem; + border: 1px solid ${p => p.theme.colors.bg2}; + border-radius: ${p => p.theme.radius}; +`; diff --git a/browser/data-browser/src/chunks/TablePage/Calendar/CalendarView.tsx b/browser/data-browser/src/chunks/TablePage/Calendar/CalendarView.tsx index 966607f4e2..f5c8db4d79 100644 --- a/browser/data-browser/src/chunks/TablePage/Calendar/CalendarView.tsx +++ b/browser/data-browser/src/chunks/TablePage/Calendar/CalendarView.tsx @@ -1,4 +1,4 @@ -import { calendarRecurrenceShortname, type CalendarRecord } from '@tomic/lib'; +import { type CalendarRecord } from '@tomic/lib'; import { calendarOccurrenceBuckets, calendarPropertyMatches, @@ -29,6 +29,17 @@ import { useCalendarDateProp } from './useCalendarDateProp'; import { CalendarDay } from './CalendarDay'; import { CalendarDayList } from './CalendarDayList'; import { withTableRowDefaults } from '../rowDefaults'; +import { useCalendarRecurrenceProp } from './useCalendarRecurrenceProp'; +import { + calendarRowTime, + isNativePayload, + localDayKey as toDayKey, + readRecurrencePayload, + rowRecord, + valueToDayKey, + type CalendarColumns, +} from './calendarRows'; +import type { CalendarRowContext } from './CalendarRowFields'; import { calendarFields, isAllDayOnDate, nextCalendarDate } from '@tomic/lib'; interface CalendarViewProps { @@ -44,32 +55,6 @@ interface CalendarViewProps { readOnly: boolean; } -/** Local YYYY-MM-DD key for a Date (NOT toISOString — that shifts timezones). */ -function toDayKey(d: Date): string { - const month = String(d.getMonth() + 1).padStart(2, '0'); - const day = String(d.getDate()).padStart(2, '0'); - - return `${d.getFullYear()}-${month}-${day}`; -} - -const DATE_PREFIX_REGEX = /^\d{4}-\d{2}-\d{2}/; - -/** Buckets a stored date/timestamp value into its (local) day key. */ -function valueToDayKey( - value: JSONValue | undefined, - datatype: Datatype | undefined, -): string | undefined { - if (datatype === Datatype.TIMESTAMP && typeof value === 'number') { - return toDayKey(new Date(value)); - } - - if (typeof value === 'string' && DATE_PREFIX_REGEX.test(value)) { - return value.slice(0, 10); - } - - return undefined; -} - /** Monday-first weekday headers, localized (2024-01-01 was a Monday). */ const WEEKDAY_LABELS = Array.from({ length: 7 }, (_, i) => new Date(2024, 0, 1 + i).toLocaleDateString(undefined, { weekday: 'short' }), @@ -200,33 +185,45 @@ export function CalendarView({ ), ); - const recurrenceProp = allColumns.find(p => - calendarPropertyMatches(p.shortname, calendarRecurrenceShortname), + const { recurrenceProp, ensureRecurrenceProp } = useCalendarRecurrenceProp( + tableClass, + allColumns, ); + const columns: CalendarColumns | undefined = dateProp && { + dateProp, + allDayProp, + endDayProp, + calendarDate, + recurrenceProp, + }; const recurringRows = new Set(); + const nativeRows = new Set(); const recurrenceRecords: CalendarRecord[] = []; - if (calendarDate && recurrenceProp) { + if (columns && recurrenceProp) { for (const subject of memberSubjects) { - const payload = rows.get(subject)?.get(recurrenceProp.subject); - - if ( - payload && - typeof payload === 'object' && - !Array.isArray(payload) && - 'event' in payload - ) { + const row = rows.get(subject); + const payload = readRecurrencePayload(row?.get(recurrenceProp.subject)); + + if (!payload) continue; + + // A row's own series (the Repeat field) works on any date column; an + // imported one only where the view is placed by the calendar's Day. + if (isNativePayload(payload)) { + const time = calendarRowTime(prop => row?.get(prop), columns); + if (!time) continue; + nativeRows.add(subject); recurringRows.add(subject); - recurrenceRecords.push({ - ...payload, - subject, - } as unknown as CalendarRecord); + recurrenceRecords.push(rowRecord(subject, payload, time)); + } else if (calendarDate) { + recurringRows.add(subject); + recurrenceRecords.push({ ...payload, subject }); } } } const { - buckets: occurrenceBuckets, + buckets: expandedBuckets, invalid: invalidRecurrences, error: recurrenceError, } = expandRecurrences( @@ -234,6 +231,20 @@ export function CalendarView({ gridDays.map(day => day.dayKey), ); + // A row's own series is placed as an all-day range, but only labelled "All + // day" when the row is, like the row itself would be. + const occurrenceBuckets = new Map( + [...expandedBuckets].map(([day, occurrences]) => [ + day, + occurrences.map(occurrence => + nativeRows.has(occurrence.subject) && + !allDaySubjects.has(occurrence.subject) + ? { ...occurrence, allDay: false } + : occurrence, + ), + ]), + ); + // Bucket each row onto its day. Reactive: `useResources` re-snapshots when a // row's date changes, so the grid recomputes. const buckets = (() => { @@ -246,7 +257,7 @@ export function CalendarView({ for (const subject of memberSubjects) { if (recurringRows.has(subject)) continue; const resource = rows.get(subject); - const value = resource?.get(dateProp.subject) as JSONValue | undefined; + const value = resource?.get(dateProp.subject); const key = valueToDayKey(value, dateProp.datatype); const isAllDay = @@ -271,6 +282,11 @@ export function CalendarView({ const todayKey = toDayKey(new Date()); + const rowContext: CalendarRowContext | undefined = columns && { + ...columns, + ensureRecurrenceProp, + }; + const monthLabel = new Date(cursor.year, cursor.month, 1).toLocaleDateString( undefined, { month: 'long', year: 'numeric' }, @@ -419,6 +435,7 @@ export function CalendarView({ subject={expandedSubject ?? unknownSubject} open={showExpanded} bindOpen={setShowExpanded} + calendar={rowContext} /> ); diff --git a/browser/data-browser/src/chunks/TablePage/Calendar/RepeatField.tsx b/browser/data-browser/src/chunks/TablePage/Calendar/RepeatField.tsx new file mode 100644 index 0000000000..74349474f2 --- /dev/null +++ b/browser/data-browser/src/chunks/TablePage/Calendar/RepeatField.tsx @@ -0,0 +1,401 @@ +import { + calendarWeekdays, + defaultRepeatRule, + isCalendarDate, + isLastWeekday, + weekdayOf, + weekdayOrdinal, + type RepeatAnchor, + type RepeatFrequency, + type RepeatParse, + type RepeatRule, +} from '@tomic/lib'; +import { useId, useState, type JSX, type ReactNode } from 'react'; +import { styled } from 'styled-components'; +import { BasicSelect } from '@components/forms/BasicSelect'; +import { InputStyled, InputWrapper } from '@components/forms/InputStyles'; +import { ButtonClean } from '@components/Button'; +import { describeRepeat, weekdayName } from './repeatSummary'; + +interface RepeatFieldProps { + parsed: RepeatParse; + /** Where the series starts; the defaults and the summary follow it. */ + anchor: RepeatAnchor; + disabled?: boolean; + onChange: (next: RepeatParse) => void; + /** The raw payload's editor, behind "Show JSON". */ + json?: ReactNode; +} + +type Choice = 'none' | RepeatFrequency | 'custom'; + +/** The Repeat setting of a calendar row: none, daily, weekly on chosen days, + * monthly by date or weekday, or yearly; ending never, on a date or after N + * times. A rule it cannot show is "Custom", kept as is, with its JSON. */ +export function RepeatField({ + parsed, + anchor, + disabled, + onChange, + json, +}: RepeatFieldProps): JSX.Element { + const id = useId(); + const [showJson, setShowJson] = useState(false); + const rule = parsed.kind === 'rule' ? parsed.rule : undefined; + const choice: Choice = + parsed.kind === 'rule' ? parsed.rule.frequency : parsed.kind; + + const update = (patch: Partial) => { + if (rule) onChange({ kind: 'rule', rule: { ...rule, ...patch } }); + }; + + const choose = (next: Choice) => { + if (next === 'none') onChange({ kind: 'none' }); + else if (next !== 'custom') + onChange({ + kind: 'rule', + // Keep the end when switching between frequencies. + rule: { ...defaultRepeatRule(next, anchor), end: rule?.end ?? NEVER }, + }); + }; + + return ( + + + + choose(e.target.value as Choice)} + > + + + + + + {parsed.kind === 'custom' && } + + + + {rule && ( + <> + + + + + { + const interval = Number(e.target.value); + + if (Number.isSafeInteger(interval) && interval >= 1) { + update({ interval: Math.min(interval, 1000) }); + } + }} + /> + + + + + + {rule.frequency === 'weekly' && ( + + + + {calendarWeekdays.map(day => { + const on = rule.weekdays.includes(day); + + return ( + { + const weekdays = on + ? rule.weekdays.filter(d => d !== day) + : [...rule.weekdays, day]; + // A weekly series needs at least one day. + if (weekdays.length) update({ weekdays }); + }} + > + {weekdayName(day, undefined, 'short')} + + ); + })} + + + )} + + {rule.frequency === 'monthly' && ( + + + { + const [by, ordinal] = e.target.value.split(':'); + update( + by === 'date' + ? { monthlyBy: 'date', ordinal: undefined } + : { + monthlyBy: 'weekday', + ordinal: + Number(ordinal) === weekdayOrdinal(anchor.date) + ? undefined + : Number(ordinal), + }, + ); + }} + > + + {monthlyWeekdayOptions(anchor).map(ordinal => ( + + ))} + + + )} + + + + + + update({ end: defaultEnd(e.target.value, anchor) }) + } + > + + + + + {rule.end.type === 'until' && ( + + { + if (isCalendarDate(e.target.value)) { + update({ + end: { type: 'until', date: e.target.value }, + }); + } + }} + /> + + )} + {rule.end.type === 'count' && ( + <> + + { + const count = Number(e.target.value); + + if (Number.isSafeInteger(count) && count >= 1) { + update({ end: { type: 'count', count } }); + } + }} + /> + + times + + )} + + + + )} + +
+ + {describeRepeat(parsed, anchor)} + + {json && ( + setShowJson(show => !show)} + > + {showJson ? 'Hide JSON' : 'Show JSON'} + + )} +
+ {parsed.kind === 'custom' && ( + + This repeat rule has options the Repeat field cannot show. Edit its + JSON, or pick a repeat above to replace it. + + )} + {json && showJson &&
{json}
} +
+ ); +} + +const NEVER = { type: 'never' } as const; + +function defaultEnd(type: string, anchor: RepeatAnchor): RepeatRule['end'] { + if (type === 'until') return { type: 'until', date: anchor.date }; + if (type === 'count') return { type: 'count', count: 10 }; + + return NEVER; +} + +/** The start's own nth weekday, and "last" too when it is also the last. */ +function monthlyWeekdayOptions(anchor: RepeatAnchor): number[] { + const own = weekdayOrdinal(anchor.date); + + return own !== -1 && isLastWeekday(anchor.date) ? [own, -1] : [own]; +} + +function IntervalUnit({ + frequency, +}: { + frequency: RepeatFrequency; +}): JSX.Element { + switch (frequency) { + case 'daily': + return days; + case 'weekly': + return weeks; + case 'monthly': + return months; + case 'yearly': + return years; + } +} + +// Plain strings: an