Skip to content

Build your personal knowledge base with Trilium Notes

feat(calendar): edit how an event repeats from its dock

Elian Doran0782fa43062a
diff --git a/apps/client/src/widgets/collections/calendar/DetailDock.tsx b/apps/client/src/widgets/collections/calendar/DetailDock.tsx
index cf70641776..44a417e034 100644
--- a/apps/client/src/widgets/collections/calendar/DetailDock.tsx
+++ b/apps/client/src/widgets/collections/calendar/DetailDock.tsx
@@ -12,12 +12,15 @@ import PromotedAttributes from "../../PromotedAttributes";
import ActionButton from "../../react/ActionButton";
import { useLegacyComponentElement, useNote } from "../../react/hooks";
import { removeFromCalendar } from "./api";
+import { EventFieldList } from "./EventField";
+import RecurrenceEditor from "./RecurrenceEditor";
/**
- * The dates the calendar already draws the event by, so their fields are not repeated in the dock.
+ * The labels the dock already speaks for, so their fields are not repeated in the promoted grid:
+ * the dates the calendar draws the event by, and the recurrence the dock's own field edits.
* Only the stock names for now; a calendar naming its own (`calendar:startDate`) still shows those.
*/
-const EVENT_DATE_LABELS = [ "startDate", "endDate", "startTime", "endTime" ];
+const EVENT_LABELS = [ "startDate", "endDate", "startTime", "endTime", "recurrence" ];
/**
* A pane docked at the trailing edge of the calendar, holding the note of the selected event — the
@@ -132,7 +135,15 @@ function DockContent({ note, parentNote, isEditable, onClose }: {
</>}
</EmbeddedNoteActions>
- <PromotedAttributes omit={EVENT_DATE_LABELS} />
+ {/* How the event repeats — a way of changing it, so it goes where the calendar may
+ be edited: a calendar root's day notes are days, and days do not recur. */}
+ {isEditable && (
+ <EventFieldList>
+ <RecurrenceEditor note={note} />
+ </EventFieldList>
+ )}
+
+ <PromotedAttributes omit={EVENT_LABELS} />
<NoteDetail />
</div>
</div>
diff --git a/apps/client/src/widgets/collections/calendar/EventField.css b/apps/client/src/widgets/collections/calendar/EventField.css
new file mode 100644
index 0000000000..5e0b50fa2d
--- /dev/null
+++ b/apps/client/src/widgets/collections/calendar/EventField.css
@@ -0,0 +1,32 @@
+.calendar-event-fields {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+
+ .calendar-event-field {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ }
+
+ /* Faded as the promoted grid fades its labels (see theme-next/shell.css), so the event's own
+ fields and the note's promoted ones read as one form when they stand in the same dock. */
+ .calendar-event-field-name {
+ font-weight: normal;
+ font-size: 0.85em;
+ opacity: 0.75;
+ margin: 0;
+ }
+
+ .calendar-event-field-controls {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+
+ /* A number in a sentence is a small thing; the box beside it should be too, leaving the
+ line to the words around it. */
+ > .tn-number-unit-pair {
+ flex: 0 1 auto;
+ }
+ }
+}
diff --git a/apps/client/src/widgets/collections/calendar/EventField.tsx b/apps/client/src/widgets/collections/calendar/EventField.tsx
new file mode 100644
index 0000000000..0930f31ba2
--- /dev/null
+++ b/apps/client/src/widgets/collections/calendar/EventField.tsx
@@ -0,0 +1,40 @@
+import "./EventField.css";
+
+import { ComponentChildren } from "preact";
+
+/**
+ * The column of an event's own fields — how the dock will say what the calendar draws the event by
+ * (its recurrence, and in time its start and end dates), those being kept out of the promoted grid
+ * (see EVENT_DATE_LABELS in DetailDock.tsx). One shared shape so every field of the event reads as
+ * a row of the same form.
+ */
+export function EventFieldList({ children }: { children: ComponentChildren }) {
+ return <div className="calendar-event-fields">{children}</div>;
+}
+
+/**
+ * One field of the event: its name over whatever edits it. The name is a `<label>` where there is
+ * one input to speak for ({@link htmlFor}), and reads as a heading where the field is a group —
+ * a row of weekday toggles has no single input to point at.
+ */
+export function EventField({ name, htmlFor, children }: {
+ name: string;
+ /** The id of the field's input, for a field that has exactly one. */
+ htmlFor?: string;
+ children: ComponentChildren;
+}) {
+ return (
+ <div className="calendar-event-field">
+ <label className="calendar-event-field-name" for={htmlFor}>{name}</label>
+ {children}
+ </div>
+ );
+}
+
+/**
+ * Controls standing in one line, for a field said as a sentence — "every [2] weeks", "after [10]
+ * times" — rather than as a single box.
+ */
+export function EventFieldControls({ children }: { children: ComponentChildren }) {
+ return <div className="calendar-event-field-controls">{children}</div>;
+}
diff --git a/apps/client/src/widgets/collections/calendar/RecurrenceEditor.css b/apps/client/src/widgets/collections/calendar/RecurrenceEditor.css
new file mode 100644
index 0000000000..55dc0a2e5b
--- /dev/null
+++ b/apps/client/src/widgets/collections/calendar/RecurrenceEditor.css
@@ -0,0 +1,33 @@
+.calendar-recurrence-weekdays {
+ display: flex;
+ gap: 4px;
+
+ .calendar-recurrence-weekday {
+ /* Seven of a kind sharing the row evenly, whatever their labels measure in a locale. */
+ flex: 1 1 0;
+ min-width: 0;
+ padding: 3px 0;
+ border: 1px solid var(--main-border-color);
+ border-radius: 6px;
+ background: transparent;
+ color: var(--main-text-color);
+ font-size: 0.85em;
+ cursor: pointer;
+
+ &:hover {
+ background: var(--hover-item-background-color);
+ }
+
+ &.active {
+ background: var(--active-item-background-color);
+ border-color: var(--active-item-background-color);
+ color: var(--active-item-text-color);
+ }
+ }
+}
+
+.calendar-recurrence-hint {
+ font-size: 0.85em;
+ opacity: 0.75;
+ margin: 0;
+}
diff --git a/apps/client/src/widgets/collections/calendar/RecurrenceEditor.tsx b/apps/client/src/widgets/collections/calendar/RecurrenceEditor.tsx
new file mode 100644
index 0000000000..476166a5dd
--- /dev/null
+++ b/apps/client/src/widgets/collections/calendar/RecurrenceEditor.tsx
@@ -0,0 +1,300 @@
+import "./RecurrenceEditor.css";
+
+import clsx from "clsx";
+import { useCallback, useEffect, useState } from "preact/hooks";
+
+import FNote from "../../../entities/fnote";
+import { t } from "../../../services/i18n";
+import LabelValueInput from "../../attribute_widgets/label_value_input";
+import FormSelect from "../../react/FormSelect";
+import FormTextBox, { FormTextBoxWithUnit } from "../../react/FormTextBox";
+import { useNoteLabel, useUniqueName } from "../../react/hooks";
+import { EventField, EventFieldControls } from "./EventField";
+import {
+ FREQUENCIES,
+ Frequency,
+ ParsedRecurrence,
+ parseRecurrence,
+ RecurrenceEnd,
+ serializeRecurrence,
+ SimpleRecurrence,
+ WEEKDAY_CODES,
+ WeekdayCode
+} from "./recurrence";
+
+/**
+ * Edits how the event repeats, through the note's `#recurrence` label — structured fields for the
+ * everyday rules, the raw RRULE string for one saying more than they can (see recurrence.ts for
+ * where that line runs). Rendered as {@link EventField} rows, so it stands in the dock's field
+ * column beside the start and end dates when those grow editors of their own.
+ *
+ * Only the stock label name for now, as the dock reads only the stock names (see EVENT_DATE_LABELS
+ * in DetailDock.tsx); a calendar naming its own via `#calendar:recurrence` edits that label by
+ * hand.
+ */
+export default function RecurrenceEditor({ note }: { note: FNote }) {
+ const [ storedValue, setStoredValue ] = useNoteLabel(note, "recurrence");
+ const [ model, setModel ] = useState<ParsedRecurrence>(() => parseRecurrence(storedValue));
+
+ // Follows the label wherever it changes from — another client, the attribute editor, an undo —
+ // but not where the label already says what the fields say: that is the editor's own write
+ // echoing back, and re-parsing it would flatten a state the string spells more loosely than the
+ // fields hold it — an "until" whose date is still being picked is stored as never ending (see
+ // recurrence.ts), and must not snap back to "never" under the user mid-pick.
+ useEffect(() => {
+ setModel((current) =>
+ serializeRecurrence(current) === (storedValue?.trim() || null)
+ ? current
+ : parseRecurrence(storedValue));
+ }, [ storedValue ]);
+
+ const commit = useCallback((next: ParsedRecurrence) => {
+ setModel(next);
+ setStoredValue(serializeRecurrence(next));
+ }, [ setStoredValue ]);
+
+ return (
+ <>
+ <FrequencyField model={model} commit={commit} />
+ {model.kind === "simple" && <SimpleRuleFields rule={model.rule} commit={commit} />}
+ {model.kind === "custom" && <CustomRuleField value={model.value} commit={commit} />}
+ </>
+ );
+}
+
+/** What the frequency dropdown offers beside the frequencies themselves. */
+const NO_REPEAT = "none";
+const CUSTOM = "custom";
+
+/**
+ * The rule's headline: how often, or not at all. A rule beyond the structured fields shows as
+ * "Custom" — an entry that exists only while it is the answer, since there is no such thing as
+ * asking for a custom rule with nothing to say in it.
+ */
+function FrequencyField({ model, commit }: {
+ model: ParsedRecurrence;
+ commit(next: ParsedRecurrence): void;
+}) {
+ const selectId = useUniqueName("recurrence-frequency");
+ const current = model.kind === "simple" ? model.rule.frequency
+ : model.kind === "custom" ? CUSTOM : NO_REPEAT;
+
+ const choices = [
+ { key: NO_REPEAT, title: t("calendar.recurrence.does_not_repeat") },
+ ...FREQUENCIES.map((frequency) => ({ key: frequency, title: FREQUENCY_TITLES[frequency]() })),
+ ...(model.kind === "custom" ? [ { key: CUSTOM, title: t("calendar.recurrence.custom") } ] : [])
+ ];
+
+ const onChange = (key: string) => {
+ if (key === current) return;
+
+ if (key === NO_REPEAT) {
+ commit({ kind: "none" });
+ return;
+ }
+
+ const frequency = FREQUENCIES.find((f) => f === key);
+ if (!frequency) return;
+
+ // What the old rule already said — how often within its period, and when it stops — is
+ // carried over; the days belong to a weekly rule alone.
+ const rule = model.kind === "simple" ? model.rule : undefined;
+ commit({
+ kind: "simple",
+ rule: {
+ frequency,
+ interval: rule?.interval ?? 1,
+ weekdays: frequency === "WEEKLY" ? (rule?.weekdays ?? []) : [],
+ ends: rule?.ends ?? { type: "never" }
+ }
+ });
+ };
+
+ return (
+ <EventField name={t("calendar.recurrence.repeats")} htmlFor={selectId}>
+ <FormSelect
+ id={selectId}
+ values={choices}
+ keyProperty="key"
+ titleProperty="title"
+ currentValue={current}
+ onChange={onChange}
+ />
+ </EventField>
+ );
+}
+
+const FREQUENCY_TITLES: Record<Frequency, () => string> = {
+ DAILY: () => t("calendar.recurrence.daily"),
+ WEEKLY: () => t("calendar.recurrence.weekly"),
+ MONTHLY: () => t("calendar.recurrence.monthly"),
+ YEARLY: () => t("calendar.recurrence.yearly")
+};
+
+/** The fields a structured rule is spelt out in, once a frequency has been picked. */
+function SimpleRuleFields({ rule, commit }: {
+ rule: SimpleRecurrence;
+ commit(next: ParsedRecurrence): void;
+}) {
+ const commitRule = (changes: Partial<SimpleRecurrence>) =>
+ commit({ kind: "simple", rule: { ...rule, ...changes } });
+
+ return (
+ <>
+ <EventField name={t("calendar.recurrence.repeat_every")}>
+ <EventFieldControls>
+ <FormTextBoxWithUnit
+ type="number"
+ min={1}
+ currentValue={String(rule.interval)}
+ onBlur={(value) => commitRule({ interval: parseInt(value, 10) || 1 })}
+ unit={INTERVAL_UNITS[rule.frequency]()}
+ />
+ </EventFieldControls>
+ </EventField>
+
+ {rule.frequency === "WEEKLY" && (
+ <EventField name={t("calendar.recurrence.on_days")}>
+ <WeekdayToggles
+ weekdays={rule.weekdays}
+ onChange={(weekdays) => commitRule({ weekdays })}
+ />
+ </EventField>
+ )}
+
+ <EndsField ends={rule.ends} onChange={(ends) => commitRule({ ends })} />
+ </>
+ );
+}
+
+const INTERVAL_UNITS: Record<Frequency, () => string> = {
+ DAILY: () => t("calendar.recurrence.unit_days"),
+ WEEKLY: () => t("calendar.recurrence.unit_weeks"),
+ MONTHLY: () => t("calendar.recurrence.unit_months"),
+ YEARLY: () => t("calendar.recurrence.unit_years")
+};
+
+/** The days of a weekly rule, a pill per day. None pressed, the start date's own day carries it. */
+function WeekdayToggles({ weekdays, onChange }: {
+ weekdays: WeekdayCode[];
+ onChange(weekdays: WeekdayCode[]): void;
+}) {
+ const toggle = (code: WeekdayCode) => {
+ onChange(weekdays.includes(code)
+ ? weekdays.filter((day) => day !== code)
+ : [ ...weekdays, code ]);
+ };
+
+ return (
+ <div className="calendar-recurrence-weekdays">
+ {WEEKDAY_CODES.map((code) => (
+ <button
+ key={code}
+ type="button"
+ className={clsx("calendar-recurrence-weekday", weekdays.includes(code) && "active")}
+ aria-pressed={weekdays.includes(code)}
+ onClick={() => toggle(code)}
+ >
+ {WEEKDAY_TITLES[code]()}
+ </button>
+ ))}
+ </div>
+ );
+}
+
+const WEEKDAY_TITLES: Record<WeekdayCode, () => string> = {
+ MO: () => t("calendar.mon"),
+ TU: () => t("calendar.tue"),
+ WE: () => t("calendar.wed"),
+ TH: () => t("calendar.thu"),
+ FR: () => t("calendar.fri"),
+ SA: () => t("calendar.sat"),
+ SU: () => t("calendar.sun")
+};
+
+/** A count an "after N times" ending starts from — a foothold to edit, not a recommendation. */
+const DEFAULT_COUNT = 10;
+
+/** When the repetition stops: never, on a day, or after so many times. */
+function EndsField({ ends, onChange }: {
+ ends: RecurrenceEnd;
+ onChange(ends: RecurrenceEnd): void;
+}) {
+ const selectId = useUniqueName("recurrence-ends");
+
+ const choices = [
+ { key: "never", title: t("calendar.recurrence.never") },
+ { key: "until", title: t("calendar.recurrence.until") },
+ { key: "count", title: t("calendar.recurrence.count") }
+ ];
+
+ const onPick = (key: string) => {
+ if (key === ends.type) return;
+
+ if (key === "until") {
+ // The date comes second: the rule stays unbounded until one is picked (see recurrence.ts).
+ onChange({ type: "until", date: "" });
+ } else if (key === "count") {
+ onChange({ type: "count", count: DEFAULT_COUNT });
+ } else {
+ onChange({ type: "never" });
+ }
+ };
+
+ return (
+ <EventField name={t("calendar.recurrence.ends")} htmlFor={selectId}>
+ <EventFieldControls>
+ <FormSelect
+ id={selectId}
+ values={choices}
+ keyProperty="key"
+ titleProperty="title"
+ currentValue={ends.type}
+ onChange={onPick}
+ />
+
+ {ends.type === "until" && (
+ <LabelValueInput
+ labelType="date"
+ value={ends.date}
+ onCommit={(date) => onChange({ type: "until", date })}
+ inputProps={{ className: "form-control" }}
+ />
+ )}
+
+ {ends.type === "count" && (
+ <FormTextBoxWithUnit
+ type="number"
+ min={1}
+ currentValue={String(ends.count)}
+ onBlur={(value) => onChange({ type: "count", count: parseInt(value, 10) || 1 })}
+ unit={t("calendar.recurrence.times")}
+ />
+ )}
+ </EventFieldControls>
+ </EventField>
+ );
+}
+
+/** The raw RRULE string, for a rule the structured fields cannot say (see recurrence.ts). */
+function CustomRuleField({ value, commit }: {
+ value: string;
+ commit(next: ParsedRecurrence): void;
+}) {
+ const inputId = useUniqueName("recurrence-custom");
+
+ return (
+ <EventField name={t("calendar.recurrence.custom_rule")} htmlFor={inputId}>
+ <FormTextBox
+ id={inputId}
+ currentValue={value}
+ spellcheck={false}
+ placeholder="RRULE:FREQ=WEEKLY;BYDAY=MO,FR"
+ // On blur, and parsed afresh rather than kept custom: an edit may well have brought
+ // the rule back within what the structured fields can say, and then they should say it.
+ onBlur={(newValue) => commit(parseRecurrence(newValue))}
+ />
+ <p className="calendar-recurrence-hint">{t("calendar.recurrence.custom_hint")}</p>
+ </EventField>
+ );
+}
diff --git a/apps/client/src/widgets/collections/calendar/recurrence.spec.ts b/apps/client/src/widgets/collections/calendar/recurrence.spec.ts
new file mode 100644
index 0000000000..f700224ab0
--- /dev/null
+++ b/apps/client/src/widgets/collections/calendar/recurrence.spec.ts
@@ -0,0 +1,124 @@
+import * as rruleLib from "rrule";
+import { describe, expect, it } from "vitest";
+
+import { parseRecurrence, serializeRecurrence, SimpleRecurrence } from "./recurrence";
+
+describe("parseRecurrence", () => {
+ it("reads no label as no repetition", () => {
+ expect(parseRecurrence(null)).toEqual({ kind: "none" });
+ expect(parseRecurrence(undefined)).toEqual({ kind: "none" });
+ expect(parseRecurrence("")).toEqual({ kind: "none" });
+ expect(parseRecurrence(" ")).toEqual({ kind: "none" });
+ });
+
+ it("reads the everyday rules into the structured fields", () => {
+ expect(parseRecurrence("RRULE:FREQ=DAILY")).toEqual({
+ kind: "simple",
+ rule: { frequency: "DAILY", interval: 1, weekdays: [], ends: { type: "never" } }
+ });
+
+ expect(parseRecurrence("RRULE:FREQ=WEEKLY;INTERVAL=2;BYDAY=MO,FR")).toEqual({
+ kind: "simple",
+ rule: { frequency: "WEEKLY", interval: 2, weekdays: [ "MO", "FR" ], ends: { type: "never" } }
+ });
+
+ expect(parseRecurrence("RRULE:FREQ=MONTHLY;COUNT=10")).toEqual({
+ kind: "simple",
+ rule: { frequency: "MONTHLY", interval: 1, weekdays: [], ends: { type: "count", count: 10 } }
+ });
+ });
+
+ it("is forgiving about case and surrounding whitespace, and reads UNTIL down to its day", () => {
+ expect(parseRecurrence(" rrule:freq=yearly;until=20260605T235959Z ")).toEqual({
+ kind: "simple",
+ rule: { frequency: "YEARLY", interval: 1, weekdays: [], ends: { type: "until", date: "2026-06-05" } }
+ });
+
+ // A bare date and a local (un-zoned) time are both valid RRULE spellings of UNTIL.
+ expect(parseRecurrence("RRULE:FREQ=DAILY;UNTIL=20260605")).toEqual({
+ kind: "simple",
+ rule: { frequency: "DAILY", interval: 1, weekdays: [], ends: { type: "until", date: "2026-06-05" } }
+ });
+ expect(parseRecurrence("RRULE:FREQ=DAILY;UNTIL=20260605T120000")).toEqual({
+ kind: "simple",
+ rule: { frequency: "DAILY", interval: 1, weekdays: [], ends: { type: "until", date: "2026-06-05" } }
+ });
+ });
+
+ it.each([
+ // Anything the structured fields cannot say in full stays a raw string.
+ [ "an unsupported parameter", "RRULE:FREQ=MONTHLY;BYMONTHDAY=15" ],
+ [ "a week-start override", "RRULE:FREQ=WEEKLY;WKST=SU" ],
+ [ "an nth-weekday BYDAY", "RRULE:FREQ=MONTHLY;BYDAY=2TU" ],
+ [ "BYDAY outside a weekly rule", "RRULE:FREQ=MONTHLY;BYDAY=TU" ],
+ [ "both UNTIL and COUNT", "RRULE:FREQ=DAILY;UNTIL=20260101;COUNT=3" ],
+ [ "a repeated parameter", "RRULE:FREQ=DAILY;INTERVAL=2;INTERVAL=3" ],
+ [ "a rule set of several lines", "RRULE:FREQ=DAILY\nEXDATE:20260101T000000" ],
+ [ "a zero interval", "RRULE:FREQ=DAILY;INTERVAL=0" ],
+ [ "a malformed UNTIL", "RRULE:FREQ=DAILY;UNTIL=2026-06-05" ],
+ [ "an unknown frequency", "RRULE:FREQ=HOURLY" ],
+ [ "something that is not an RRULE at all", "every second thursday" ]
+ ])("steps aside for %s", (_description, value) => {
+ expect(parseRecurrence(value)).toEqual({ kind: "custom", value });
+ });
+});
+
+describe("serializeRecurrence", () => {
+ it("writes nothing for no repetition or an emptied custom rule", () => {
+ expect(serializeRecurrence({ kind: "none" })).toBeNull();
+ expect(serializeRecurrence({ kind: "custom", value: "" })).toBeNull();
+ expect(serializeRecurrence({ kind: "custom", value: " " })).toBeNull();
+ });
+
+ it("hands a custom rule back as written", () => {
+ expect(serializeRecurrence({ kind: "custom", value: "RRULE:FREQ=MONTHLY;BYSETPOS=-1;BYDAY=FR" }))
+ .toBe("RRULE:FREQ=MONTHLY;BYSETPOS=-1;BYDAY=FR");
+ });
+
+ it("spells out only what differs from the defaults", () => {
+ expect(serialize({ frequency: "DAILY" })).toBe("RRULE:FREQ=DAILY");
+ expect(serialize({ frequency: "WEEKLY", interval: 3 })).toBe("RRULE:FREQ=WEEKLY;INTERVAL=3");
+ expect(serialize({ frequency: "YEARLY", ends: { type: "count", count: 5 } }))
+ .toBe("RRULE:FREQ=YEARLY;COUNT=5");
+ });
+
+ it("writes the picked days in the week's own order, and UNTIL as the end of its day", () => {
+ expect(serialize({ frequency: "WEEKLY", weekdays: [ "FR", "MO" ] }))
+ .toBe("RRULE:FREQ=WEEKLY;BYDAY=MO,FR");
+ expect(serialize({ frequency: "DAILY", ends: { type: "until", date: "2026-06-05" } }))
+ .toBe("RRULE:FREQ=DAILY;UNTIL=20260605T235959Z");
+ });
+
+ it("holds an 'until' whose date has not been picked yet as never ending", () => {
+ expect(serialize({ frequency: "DAILY", ends: { type: "until", date: "" } }))
+ .toBe("RRULE:FREQ=DAILY");
+ });
+
+ it("round-trips through the parser, and through the library the event builder validates with", () => {
+ const rules: SimpleRecurrence[] = [
+ simple({ frequency: "DAILY" }),
+ simple({ frequency: "WEEKLY", interval: 2, weekdays: [ "MO", "WE", "FR" ] }),
+ simple({ frequency: "MONTHLY", ends: { type: "count", count: 12 } }),
+ simple({ frequency: "YEARLY", interval: 4, ends: { type: "until", date: "2040-02-29" } })
+ ];
+
+ for (const rule of rules) {
+ const serialized = serializeRecurrence({ kind: "simple", rule });
+ expect(serialized).not.toBeNull();
+ expect(parseRecurrence(serialized)).toEqual({ kind: "simple", rule });
+
+ // As the event builder assembles it (see buildEvent), so what the editor writes is
+ // exactly what FullCalendar will be asked to draw.
+ expect(() => rruleLib.rrulestr(`DTSTART:20260101T090000\n${serialized}`, { forceset: true }))
+ .not.toThrow();
+ }
+ });
+});
+
+function simple(overrides: Partial<SimpleRecurrence> & Pick<SimpleRecurrence, "frequency">): SimpleRecurrence {
+ return { interval: 1, weekdays: [], ends: { type: "never" }, ...overrides };
+}
+
+function serialize(overrides: Partial<SimpleRecurrence> & Pick<SimpleRecurrence, "frequency">) {
+ return serializeRecurrence({ kind: "simple", rule: simple(overrides) });
+}
diff --git a/apps/client/src/widgets/collections/calendar/recurrence.ts b/apps/client/src/widgets/collections/calendar/recurrence.ts
new file mode 100644
index 0000000000..15413b7020
--- /dev/null
+++ b/apps/client/src/widgets/collections/calendar/recurrence.ts
@@ -0,0 +1,197 @@
+/**
+ * The recurrence of an event as the editor understands it, translated to and from the RRULE string
+ * the `#recurrence` label stores (see event_builder.ts, which hands that string to FullCalendar).
+ *
+ * The editor models the everyday rules — "every day", "every 2 weeks on Mon and Fri, 10 times" —
+ * and steps aside for everything else: a rule using any RRULE feature beyond them (BYMONTHDAY,
+ * BYSETPOS, nth-weekday BYDAY, EXDATE lines, …) parses as {@link CustomRecurrence}, shown and
+ * edited as the raw string, so a hand-written rule is never silently rewritten into less than it
+ * said.
+ */
+
+/** Weekday codes as RRULE spells them, Monday first as the calendar draws its weeks. */
+export const WEEKDAY_CODES = [ "MO", "TU", "WE", "TH", "FR", "SA", "SU" ] as const;
+
+export type WeekdayCode = (typeof WEEKDAY_CODES)[number];
+
+export const FREQUENCIES = [ "DAILY", "WEEKLY", "MONTHLY", "YEARLY" ] as const;
+
+export type Frequency = (typeof FREQUENCIES)[number];
+
+/** A rule the structured fields can say in full. */
+export interface SimpleRecurrence {
+ frequency: Frequency;
+ /** Every how many days/weeks/months/years; `1` for every one. */
+ interval: number;
+ /** Weekly only: the days the event falls on. Empty, the day of the start date carries it. */
+ weekdays: WeekdayCode[];
+ ends: RecurrenceEnd;
+}
+
+/**
+ * When the repetition stops. An `until` whose date has not been picked yet is the empty string:
+ * the choice of ending is made before the date naming it, and until the date arrives the rule is
+ * stored as never ending.
+ */
+export type RecurrenceEnd =
+ | { type: "never" }
+ | { type: "until"; date: string }
+ | { type: "count"; count: number };
+
+/** A rule beyond the structured fields, kept as the string the label holds. */
+export interface CustomRecurrence {
+ kind: "custom";
+ value: string;
+}
+
+export type ParsedRecurrence =
+ | { kind: "none" }
+ | { kind: "simple"; rule: SimpleRecurrence }
+ | CustomRecurrence;
+
+/**
+ * Reads the `#recurrence` label into what the editor can edit. Never throws: whatever cannot be
+ * carried by the structured fields — including a string that is not an RRULE at all — comes back
+ * as custom, leaving the raw field to show exactly what the note holds.
+ */
+export function parseRecurrence(value: string | null | undefined): ParsedRecurrence {
+ const trimmed = value?.trim();
+ if (!trimmed) {
+ return { kind: "none" };
+ }
+
+ const rule = parseSimpleRule(trimmed);
+ return rule ? { kind: "simple", rule } : { kind: "custom", value: trimmed };
+}
+
+/**
+ * Writes the editor's state back to what the label should hold: an RRULE string, or `null` for a
+ * value the label should not exist for — no repetition, or a custom field emptied out.
+ */
+export function serializeRecurrence(parsed: ParsedRecurrence): string | null {
+ switch (parsed.kind) {
+ case "none":
+ return null;
+ case "custom":
+ return parsed.value.trim() || null;
+ case "simple":
+ return serializeSimpleRule(parsed.rule);
+ }
+}
+
+/** The one RRULE line of a simple rule, spelling out only what differs from the defaults. */
+function serializeSimpleRule({ frequency, interval, weekdays, ends }: SimpleRecurrence): string {
+ const parts = [ `FREQ=${frequency}` ];
+
+ if (interval > 1) {
+ parts.push(`INTERVAL=${interval}`);
+ }
+
+ if (frequency === "WEEKLY" && weekdays.length > 0) {
+ // In the week's own order, however the days were picked.
+ const ordered = WEEKDAY_CODES.filter((code) => weekdays.includes(code));
+ parts.push(`BYDAY=${ordered.join(",")}`);
+ }
+
+ if (ends.type === "until" && ends.date) {
+ // The end of the picked day rather than its midnight, so "until June 5th" keeps June 5th:
+ // the builder's DTSTART is written floating (see event_builder.ts), which the rrule library
+ // reads as UTC, and a bare date would cut off before the day's own occurrence.
+ parts.push(`UNTIL=${ends.date.replaceAll("-", "")}T235959Z`);
+ } else if (ends.type === "count") {
+ parts.push(`COUNT=${ends.count}`);
+ }
+
+ return `RRULE:${parts.join(";")}`;
+}
+
+/** What of an RRULE line the structured fields can hold, or `null` for anything they cannot. */
+function parseSimpleRule(value: string): SimpleRecurrence | null {
+ // More than one line is a rule set (EXDATE, RDATE, a second RRULE) — custom by definition.
+ if (value.includes("\n") || !/^RRULE:/i.test(value)) {
+ return null;
+ }
+
+ const params = new Map<string, string>();
+ for (const part of value.substring("RRULE:".length).split(";")) {
+ const eq = part.indexOf("=");
+ if (eq <= 0) {
+ return null;
+ }
+
+ const key = part.substring(0, eq).toUpperCase();
+ // A key repeated is a rule saying two things at once; better shown raw than half-read.
+ if (params.has(key)) {
+ return null;
+ }
+ params.set(key, part.substring(eq + 1));
+ }
+
+ const frequency = FREQUENCIES.find((f) => f === params.get("FREQ")?.toUpperCase());
+ if (!frequency) {
+ return null;
+ }
+ params.delete("FREQ");
+
+ const interval = params.has("INTERVAL") ? parsePositiveInt(params.get("INTERVAL")) : 1;
+ if (interval === null) {
+ return null;
+ }
+ params.delete("INTERVAL");
+
+ let weekdays: WeekdayCode[] = [];
+ if (params.has("BYDAY")) {
+ // Plain weekday codes on a weekly rule only: on a monthly or yearly one — or carrying a
+ // position like `2TU` — BYDAY means "the nth such day", which the fields cannot say.
+ if (frequency !== "WEEKLY") {
+ return null;
+ }
+
+ weekdays = [];
+ for (const day of (params.get("BYDAY") ?? "").toUpperCase().split(",")) {
+ const code = WEEKDAY_CODES.find((c) => c === day);
+ if (!code) {
+ return null;
+ }
+ weekdays.push(code);
+ }
+ params.delete("BYDAY");
+ }
+
+ let ends: RecurrenceEnd = { type: "never" };
+ if (params.has("UNTIL") && params.has("COUNT")) {
+ return null;
+ } else if (params.has("UNTIL")) {
+ // Only the day matters to the editor; the time — ours or anyone else's — is let go, and
+ // written back as the end of that day (see serialization above).
+ const match = (params.get("UNTIL") ?? "").match(/^(\d{4})(\d{2})(\d{2})(T\d{6}Z?)?$/);
+ if (!match) {
+ return null;
+ }
+ ends = { type: "until", date: `${match[1]}-${match[2]}-${match[3]}` };
+ params.delete("UNTIL");
+ } else if (params.has("COUNT")) {
+ const count = parsePositiveInt(params.get("COUNT"));
+ if (count === null) {
+ return null;
+ }
+ ends = { type: "count", count };
+ params.delete("COUNT");
+ }
+
+ // Whatever remains — WKST, BYMONTHDAY, BYSETPOS, anything — the fields cannot carry.
+ if (params.size > 0) {
+ return null;
+ }
+
+ return { frequency, interval, weekdays, ends };
+}
+
+function parsePositiveInt(value: string | undefined): number | null {
+ if (!value || !/^\d+$/.test(value)) {
+ return null;
+ }
+
+ const parsed = parseInt(value, 10);
+ return parsed >= 1 ? parsed : null;
+}