Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
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<string>;
}

/** 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 (
<Section>
<RepeatField
parsed={parsed}
anchor={anchor}
disabled={!canWrite || saving}
onChange={save}
json={
recurrenceProp && (
<ValueForm
resource={resource}
propertyURL={recurrenceProp.subject}
/>
)
}
/>
</Section>
);
}

/** 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. Without an `anchor`
* the row has nothing to repeat from, and no Repeat field. */
export 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();

// `set` validates, and undefined is not a JSON value.
if (value === undefined) {
resource.remove(property);
} else {
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<RepeatParse, { kind: 'custom' }>,
payload: RecurrencePayload | undefined,
time: ReturnType<typeof calendarRowTime>,
): 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};
`;
121 changes: 66 additions & 55 deletions browser/data-browser/src/chunks/TablePage/Calendar/CalendarView.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { calendarRecurrenceShortname, type CalendarRecord } from '@tomic/lib';
import { type CalendarRecord } from '@tomic/lib';
import {
calendarOccurrenceBuckets,
calendarPropertyMatches,
type CalendarDayOccurrence,
type InvalidCalendarRecord,
} from './calendarOccurrences';
Expand Down Expand Up @@ -29,7 +28,19 @@ import { useCalendarDateProp } from './useCalendarDateProp';
import { CalendarDay } from './CalendarDay';
import { CalendarDayList } from './CalendarDayList';
import { withTableRowDefaults } from '../rowDefaults';
import { calendarFields, isAllDayOnDate, nextCalendarDate } from '@tomic/lib';
import { useCalendarRecurrenceProp } from './useCalendarRecurrenceProp';
import {
calendarRowTime,
isNativePayload,
localDayKey as toDayKey,
readRecurrencePayload,
rowRecord,
valueToDayKey,
type CalendarColumns,
} from './calendarRows';
import type { CalendarRowContext } from './CalendarRowFields';
import { calendarRangeColumns } from './useTableCalendarRow';
import { isAllDayOnDate, nextCalendarDate } from '@tomic/lib';

interface CalendarViewProps {
/** The Table resource; new items are created as its children. */
Expand All @@ -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' }),
Expand Down Expand Up @@ -181,15 +166,9 @@ export function CalendarView({
}, [cursor]);

// Imported ranges are opt-in: unrelated table date columns stay single-day.
const calendarDate = calendarPropertyMatches(
dateProp?.shortname,
calendarFields.day,
);
const allDayProp = allColumns.find(p =>
calendarPropertyMatches(p.shortname, calendarFields.allDay),
);
const endDayProp = allColumns.find(p =>
calendarPropertyMatches(p.shortname, calendarFields.endDay),
const { calendarDate, allDayProp, endDayProp } = calendarRangeColumns(
allColumns,
dateProp,
);
const allDaySubjects = new Set(
memberSubjects.filter(
Expand All @@ -200,40 +179,66 @@ 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<string>();
const nativeRows = new Set<string>();
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(rowRecord(subject, payload, time));
} else if (calendarDate) {
recurringRows.add(subject);
recurrenceRecords.push({
...payload,
subject,
} as unknown as CalendarRecord);
recurrenceRecords.push({ ...payload, subject });
}
}
}

const {
buckets: occurrenceBuckets,
buckets: expandedBuckets,
invalid: invalidRecurrences,
error: recurrenceError,
} = expandRecurrences(
recurrenceRecords,
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 = (() => {
Expand All @@ -246,7 +251,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 =
Expand All @@ -271,6 +276,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' },
Expand Down Expand Up @@ -419,6 +429,7 @@ export function CalendarView({
subject={expandedSubject ?? unknownSubject}
open={showExpanded}
bindOpen={setShowExpanded}
calendar={rowContext}
/>
</>
);
Expand Down
Loading