Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
Merge branch 'feature/calendar-event-popups' into claude/recurring-event-age-display-aoladf
Elian Doran8b2f475d412e
diff --cc apps/client/src/widgets/collections/calendar/event_builder.spec.tsindex 7894543c8b,d326c880d7..7008b8bebf--- a/apps/client/src/widgets/collections/calendar/event_builder.spec.ts+++ b/apps/client/src/widgets/collections/calendar/event_builder.spec.ts@@@ -1,9 -1,15 +1,15 @@@- import { describe, expect, it, vi } from "vitest";+ import rrulePlugin from "@fullcalendar/rrule";+ import { LOCALES } from "@triliumnext/commons";+ import { Calendar, EventInput } from "fullcalendar";+ import dayGridPlugin from "fullcalendar/daygrid";+ import themePlugin from "fullcalendar/themes/forma";+ import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { buildNote, buildNotes } from "../../../test/easy-froca.js";-import { buildEvent, buildEvents } from "./event_builder.js";+import { buildEvent, buildEvents, buildOccurrenceTitle } from "./event_builder.js";import { LOCALE_MAPPINGS } from "./index.js";+ import { serializeRecurrence } from "./recurrence.js";import { isValidDuration, parseDurationSeconds } from "./utils.js";- import { LOCALES } from "@triliumnext/commons";describe("Building events", () => {it("supports start date", async () => {@@@ -390,71 -463,175 +463,239 @@@ describe("Recurrence", () =>consoleSpy.mockRestore();});+ it("carries the title template and the day the series starts on", async () => {+ const noteIds = buildNotes([+ {+ title: "John Smith",+ "#startDate": "1990-05-12",+ "#startTime": "09:00",+ "#recurrence": "RRULE:FREQ=YEARLY",+ "#calendar:titleTemplate": "${title} (${age})"+ }+ ]);+ const events = await buildEvents(noteIds);++ expect(events[0]).toMatchObject({+ title: "John Smith",+ titleTemplate: "${title} (${age})",+ // The date as the label holds it, the start time not yet worked into it.+ seriesStart: "1990-05-12"+ });+ });+++ describe("in a time zone ahead of UTC", () => {+ useTimeZone("Europe/Bucharest");++ it.each([+ [ "without an end date", "RRULE:FREQ=WEEKLY;BYDAY=SU" ],+ [ "with an end date", "RRULE:FREQ=WEEKLY;BYDAY=SU;UNTIL=20261130T235959Z" ]+ ])("shows each occurrence at the event's local time %s", async (_, recurrence) => {+ const noteIds = buildNotes([+ {+ title: "Weekly",+ "#startDate": "2026-10-04",+ "#startTime": "11:00",+ "#endTime": "13:00",+ "#recurrence": recurrence+ }+ ]);+ const events = await buildEvents(noteIds);++ const occurrences = renderOccurrences(events, "2026-10-01");+ expect(occurrences.map(({ start }) => start)).toEqual([+ "2026-10-04 11:00", "2026-10-11 11:00", "2026-10-18 11:00", "2026-10-25 11:00",+ "2026-11-01 11:00", "2026-11-08 11:00"+ ]);+ expect(occurrences.every(({ end }) => end.endsWith(" 13:00"))).toBe(true);+ });++ it("skips the dates a UTC EXDATE names, keeping the rest at local time", async () => {+ const noteIds = buildNotes([+ {+ title: "Weekly",+ "#startDate": "2026-10-04",+ "#startTime": "11:00",+ "#endTime": "13:00",+ "#recurrence": [+ "RRULE:FREQ=WEEKLY;BYDAY=SU",+ "EXDATE:20261011T110000Z",+ "EXDATE:20261025T110000Z"+ ].join("\n")+ }+ ]);+ const events = await buildEvents(noteIds);++ expect(renderOccurrences(events, "2026-10-01").map(({ start }) => start)).toEqual([+ "2026-10-04 11:00", "2026-10-18 11:00", "2026-11-01 11:00", "2026-11-08 11:00"+ ]);+ });++ it.each([+ [ "the recurrence editor writes", untilRule("2026-11-29") ],+ [ "is stored in UTC", "RRULE:FREQ=WEEKLY;BYDAY=SU;UNTIL=20261129T235959Z" ]+ ])("ends the series on the day an UNTIL that %s names", async (_, recurrence) => {+ const noteIds = buildNotes([+ {+ title: "Weekly",+ "#startDate": "2026-10-04",+ "#startTime": "11:00",+ "#endTime": "13:00",+ "#recurrence": recurrence+ }+ ]);+ const events = await buildEvents(noteIds);++ expect(renderOccurrences(events, "2026-11-15").map(({ start }) => start)).toEqual([+ "2026-11-01 11:00", "2026-11-08 11:00", "2026-11-15 11:00", "2026-11-22 11:00",+ "2026-11-29 11:00"+ ]);+ });+ });++ describe("in a time zone behind UTC", () => {+ useTimeZone("America/New_York");++ it.each([+ [ "without an end date", "RRULE:FREQ=WEEKLY;BYDAY=SU" ],+ [ "with an end date", "RRULE:FREQ=WEEKLY;BYDAY=SU;UNTIL=20261130T235959Z" ]+ ])("shows a whole-day occurrence on its own day %s", async (_, recurrence) => {+ const noteIds = buildNotes([+ { title: "Weekly", "#startDate": "2026-10-04", "#recurrence": recurrence }+ ]);+ const events = await buildEvents(noteIds);++ const occurrences = renderOccurrences(events, "2026-10-01");+ expect(occurrences.map(({ start }) => start)).toEqual([+ "2026-10-04 00:00", "2026-10-11 00:00", "2026-10-18 00:00", "2026-10-25 00:00",+ "2026-11-01 00:00", "2026-11-08 00:00"+ ]);+ });++ it.each([+ [ "the recurrence editor writes", untilRule("2026-11-29") ],+ [ "is stored in UTC", "RRULE:FREQ=WEEKLY;BYDAY=SU;UNTIL=20261129T235959Z" ]+ ])("keeps a late occurrence on the day an UNTIL that %s names", async (_, recurrence) => {+ const noteIds = buildNotes([+ {+ title: "Weekly",+ "#startDate": "2026-10-04",+ "#startTime": "21:00",+ "#endTime": "22:00",+ "#recurrence": recurrence+ }+ ]);+ const events = await buildEvents(noteIds);++ expect(renderOccurrences(events, "2026-11-15").map(({ start }) => start)).toEqual([+ "2026-11-01 21:00", "2026-11-08 21:00", "2026-11-15 21:00", "2026-11-22 21:00",+ "2026-11-29 21:00"+ ]);+ });+ });});+/**+ * The title a chip is drawn under, which a repeating event names once per occurrence: the calendar+ * asks for it as each chip is drawn (see eventContent in index.tsx), the occurrence's own date in+ * hand.+ */+describe("buildOccurrenceTitle", () => {+ /** An event as FullCalendar hands it to a chip, this occurrence falling on the given day. */+ function occurrence(titleTemplate: string | null, start: Date, seriesStart = "1990-05-12") {+ return { title: "John Smith", start, extendedProps: { titleTemplate, seriesStart } };+ }++ it("leaves an event with no template under its plain title", () => {+ expect(buildOccurrenceTitle(occurrence(null, new Date(2026, 4, 12)))).toBe("John Smith");+ });++ it("counts the whole years from the start date to the occurrence", () => {+ expect(buildOccurrenceTitle(occurrence("${title} (${age})", new Date(2026, 4, 12))))+ .toBe("John Smith (36)");+ expect(buildOccurrenceTitle(occurrence("${title} turns ${age}", new Date(2027, 4, 12))))+ .toBe("John Smith turns 37");+ // The day the series itself starts on, which is where the count starts.+ expect(buildOccurrenceTitle(occurrence("${title} (${age})", new Date(1990, 4, 12))))+ .toBe("John Smith (0)");+ });++ it("reads both the occurrence's date and the series'", () => {+ const template =+ "${title}, born ${startDate.format('YYYY')}, turns ${age} in ${date.format('YYYY')}";+ expect(buildOccurrenceTitle(occurrence(template, new Date(2026, 4, 12))))+ .toBe("John Smith, born 1990, turns 36 in 2026");+ });++ it("falls back to the plain title for a template the evaluator rejects, saying so once", () => {+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const broken = occurrence("${nmae} (${age})", new Date(2026, 4, 12));++ expect(buildOccurrenceTitle(broken)).toBe("John Smith");+ expect(buildOccurrenceTitle(broken)).toBe("John Smith");+ expect(consoleSpy).toHaveBeenCalledOnce();+ expect(consoleSpy.mock.calls[0]?.[0]).toContain("#calendar:titleTemplate");+ consoleSpy.mockRestore();+ });+});++ /**+ * Expands `events` through FullCalendar and its rrule plugin, the way the calendar view does, and+ * returns the local start and end of each occurrence in the month view around `date`.+ */+ function renderOccurrences(events: EventInput[], date: string) {+ const element = document.createElement("div");+ document.body.append(element);+ const calendar = new Calendar(element, {+ plugins: [ themePlugin, dayGridPlugin, rrulePlugin ],+ initialView: "dayGridMonth",+ initialDate: date,+ events+ });+ calendar.render();++ const occurrences = calendar.getEvents()+ .map(({ start, end }) => ({ start: formatLocal(start), end: formatLocal(end) }))+ .sort((a, b) => a.start.localeCompare(b.start));+ calendar.destroy();+ element.remove();+ return occurrences;+ }++ /** Runs the specs of the enclosing `describe` with the local time zone set to `timeZone`. */+ function useTimeZone(timeZone: string) {+ const originalTimeZone = process.env.TZ;+ beforeAll(() => {+ process.env.TZ = timeZone;+ });+ afterAll(() => {+ if (originalTimeZone === undefined) {+ delete process.env.TZ;+ } else {+ process.env.TZ = originalTimeZone;+ }+ });+ }++ /** A weekly Sunday rule ending on `date`, as the recurrence editor writes it. */+ function untilRule(date: string) {+ return serializeRecurrence({+ kind: "simple",+ rule: {+ frequency: "WEEKLY",+ interval: 1,+ weekdays: [ "SU" ],+ ends: { type: "until", date }+ }+ }) ?? "";+ }++ function formatLocal(date: Date | null) {+ if (!date) return "";+ const pad = (value: number) => String(value).padStart(2, "0");+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} `+ + `${pad(date.getHours())}:${pad(date.getMinutes())}`;+ }+describe("isValidDuration", () => {it("accepts valid durations", () => {diff --cc apps/client/src/widgets/collections/calendar/event_builder.tsindex 15f0d8e4c9,508bd2bc47..a41d04fce3--- a/apps/client/src/widgets/collections/calendar/event_builder.ts+++ b/apps/client/src/widgets/collections/calendar/event_builder.ts@@@ -8,7 -8,10 +8,12 @@@ import FNote from "../../../entities/fnimport froca from "../../../services/froca";import server from "../../../services/server";import toastService from "../../../services/toast";- import { formatDateToLocalISO, getCustomisableLabel, getMonthsInDateRange } from "./utils";+ import {+ type PromotedAttributeSetting, resolvePromotedAttributes, visiblePromotedAttributeNames+ } from "../promoted_attributes";-import { drawnEventLabels, getCustomisableLabel, getMonthsInDateRange } from "./utils";++import {++ drawnEventLabels, formatDateToLocalISO, getCustomisableLabel, getMonthsInDateRange++} from "./utils";interface Event {startDate: string,@@@ -100,15 -128,11 +130,16 @@@ export async function buildEvent(note:const colorClass = note.getColorClass();const events: EventInput[] = [];+ // The day the series starts on, read before the code below appends the start time and the+ // exclusive end date. buildOccurrenceTitle() counts every occurrence from it.+ const seriesStart = startDate;+ const titleTemplate = note.getLabelValue("calendar:titleTemplate");+- const calendarDisplayedAttributes = note.getLabelValue("calendar:displayedAttributes")?.split(",");+ const shownAttributes =+ note.getLabelValue("calendar:displayedAttributes")?.split(",") ?? displayedAttributes;let displayedAttributesData: Array<[string, string]> | null = null;- if (calendarDisplayedAttributes) {- displayedAttributesData = await buildDisplayedAttributes(note, calendarDisplayedAttributes);+ if (shownAttributes.length) {+ displayedAttributesData = await buildDisplayedAttributes(note, shownAttributes);}// An event with no start time takes the whole day, which is how the editor writes one too (see@@@ -188,69 -211,17 +220,80 @@@return events;}+/**+ * Builds the title one occurrence of an event is drawn with: the note's `#calendar:titleTemplate`+ * filled in for the day the occurrence falls on, or the plain title when the note has no template.+ *+ * Runs as the chip is drawn rather than in {@link buildEvent} because FullCalendar expands a+ * `#recurrence` rule into occurrences itself: a repeating event is one {@link EventInput} with+ * one title, so `${age}` — the whole years from `#startDate` to this occurrence — is only known+ * here.+ *+ * A template {@link evaluateTemplate} rejects leaves the event with its plain title.+ */+export function buildOccurrenceTitle({ title, start, extendedProps }: OccurrenceEvent) {+ const { titleTemplate, seriesStart } = extendedProps;+ if (!titleTemplate || !seriesStart) {+ return title;+ }++ // Both dates as plain days, without the time: a DST shift between them would otherwise take an+ // hour off the span and round `age` down by a year.+ const occurrenceDay = formatDateToLocalISO(start);+ const seriesStartDay = dayjs(seriesStart.split("T")[0]);+ const occurrence = occurrenceDay ? dayjs(occurrenceDay) : seriesStartDay;++ try {+ return evaluateTemplate(titleTemplate, {+ title,+ age: occurrence.diff(seriesStartDay, "year"),+ date: occurrence,+ startDate: seriesStartDay+ });+ } catch (error) {+ reportBrokenTitleTemplate(titleTemplate, error);+ return title;+ }+}++/** The parts of a FullCalendar event {@link buildOccurrenceTitle} reads. */+interface OccurrenceEvent {+ title: string;+ /** Where this occurrence starts; the template is filled in for that day. */+ start: Date | null;+ extendedProps: {+ titleTemplate?: string | null;+ /** The `#startDate` the series is counted from, as {@link buildEvent} wrote it. */+ seriesStart?: string | null;+ };+}++/** Templates already reported. {@link buildOccurrenceTitle} runs for every chip the calendar+ * draws, so a rejected template would otherwise be logged once per chip. */+const brokenTitleTemplates = new Set<string>();++/** Logs a template {@link evaluateTemplate} rejects, once per template. */+function reportBrokenTitleTemplate(template: string, error: unknown) {+ if (brokenTitleTemplates.has(template)) {+ return;+ }++ brokenTitleTemplates.add(template);+ const reason = error instanceof Error ? error.message : error;+ console.error(`Invalid #calendar:titleTemplate "${template}": ${reason}`);+}++ /**+ * Rewrites the UTC dates of `UNTIL` and `EXDATE` (`…T235959Z`) as local time, like the DTSTART+ * that `buildEvent()` writes. FullCalendar's rrule plugin reads the whole rule as UTC when any of+ * them carries a zone, which moves every occurrence by the local UTC offset.+ */+ function toLocalDates(recurrence: string) {+ return recurrence+ .replace(/\b(UNTIL=\d{8}T\d{6})Z\b/gi, "$1")+ .replace(/^EXDATE:.*$/gim, (line) => line.replace(/(\d{8}T\d{6})Z\b/gi, "$1"));+ }+/*** How long one occurrence of a recurring event lasts, as the duration object FullCalendar builds* its own from rather than as an `HH:mm` string. A string of hours and minutes has nowhere to putdiff --cc apps/client/src/widgets/collections/calendar/index.tsxindex f2391226bc,7b474a6482..606cf5c340--- a/apps/client/src/widgets/collections/calendar/index.tsx+++ b/apps/client/src/widgets/collections/calendar/index.tsx@@@ -26,30 -29,19 +29,19 @@@ import ActionButton from "../../react/Aimport Button, { ButtonGroup } from "../../react/Button";import CollapseOnOverflow from "../../react/CollapseOnOverflow";import Dropdown from "../../react/Dropdown";+ import { FLOATING_LAYER_SELECTOR } from "../../react/floating_layers";import { FormListItem } from "../../react/FormList";- import { useNoteLabel, useNoteLabelBoolean, useSpacedUpdate, useTriliumEvent, useTriliumOption, useTriliumOptionInt } from "../../react/hooks";+ import { useEffectiveReadOnly, useNoteContext, useNoteLabel, useNoteLabelBoolean, useNoteTypeOptions, useSpacedUpdate, useTriliumEvent, useTriliumOption, useTriliumOptionInt } from "../../react/hooks";import { ParentComponent } from "../../react/react_utils";+ import { offeredTemplateIds, useTemplateChoice } from "../../react/TemplateDropdown";import { ViewModeProps } from "../interface";- import { changeEvent, newEvent } from "./api";+ import { type CalendarViewData, changeEvent, DEFAULT_EVENT_TEMPLATES, newEvent } from "./api";import Calendar from "./calendar";- import EventPopover from "./EventPopover";- import GhostPopover from "./GhostPopover";import { openCalendarContextMenu } from "./context_menu";import { CalendarSelection, EventDraft } from "./selection";-import { buildEvents, buildEventsForCalendar } from "./event_builder";+import { buildEvents, buildEventsForCalendar, buildOccurrenceTitle } from "./event_builder";import { formatDateToLocalISO, formatTimeToLocalISO, isAttributeChangeAffecting, isBranchChangeAffecting, isValidDuration, parseDurationSeconds, parseStartEndDateFromEvent, parseStartEndTimeFromEvent } from "./utils";- interface CalendarViewData {-- }-- interface CalendarViewData {- type: string;- name: string;- previousText: string;- nextText: string;- }-const CALENDAR_VIEWS = [{type: "timeGridDay",diff --cc docs/User Guide/User Guide/Collections/Calendar.mdindex 740f92f07b,32bd155f3b..e5d8e4c7ce--- a/docs/User Guide/User Guide/Collections/Calendar.md+++ b/docs/User Guide/User Guide/Collections/Calendar.md@@@ -148,11 -180,10 +180,11 @@@ For each note of the calendar, the foll| `#endTime` | Similar to `startTime`, it mentions the time at which the event ends (in relation with `endDate` if present, or `startDate`). || `#recurrence` | This is an optional CalDAV `RRULE` string that if present, determines whether a task should repeat or not. Note that it does not include the `DTSTART` attribute, which is derived from the `#startDate` and `#startTime` directly. For examples of valid `RRULE` strings see [https://icalendar.org/rrule-tool.html](https://icalendar.org/rrule-tool.html) || `#color` | Displays the event with a specified color (named such as `red`, `gray` or hex such as `#FF0000`). This will also change the color of the note in other places such as the note tree. |- | `#calendar:color` | **❌️ Removed since v0.100.0. Use** `#color` **instead.** <br> <br>Similar to `#color`, but applies the color only for the event in the calendar and not for other places such as the note tree. |+ | `#calendar:color` | **❌️ Removed since v0.100.0. Use** `#color` **instead.** <br> <br>Similar to `#color`, but applies the color only for the event in the calendar and not for other places such as the note tree. || `#iconClass` | If present, the icon of the note will be displayed to the left of the event title. || `#calendar:title` | Changes the title of an event to point to an attribute of the note other than the title, can either a label or a relation (without the `#` or `~` symbol). See _Use-cases_ for more information. |+| `#calendar:titleTemplate` | Changes the title an event is displayed with on the calendar, filled in again for every occurrence of a repeating event. See _Use-cases_ for displaying an age on a birthday. |- | `#calendar:displayedAttributes` | Allows displaying the value of one or more attributes in the calendar like this: <br> <br> <br> <br>`#weight="70" #Mood="Good" #calendar:displayedAttributes="weight,Mood"` <br> <br>It can also be used with relations, case in which it will display the title of the target note: <br> <br>`~assignee=@My assignee #calendar:displayedAttributes="assignee"` |+ | `#calendar:displayedAttributes` | Takes precedence over the [Event attributes](#event-attributes) chosen in the calendar's properties. Allows displaying the value of one or more attributes in the calendar, in the order given, like this: <br> <br> <br> <br>`#weight="70" #Mood="Good" #calendar:displayedAttributes="weight,Mood"` <br> <br>It can also be used with relations, case in which it will display the title of the target note: <br> <br>`~assignee=@My assignee #calendar:displayedAttributes="assignee"` || `#calendar:startDate` | Allows using a different label to represent the start date, other than `startDate` (e.g. `expiryDate`). The label name **must not be** prefixed with `#`. If the label is not defined for a note, the default will be used instead. || `#calendar:endDate` | Similar to `#calendar:startDate`, allows changing the attribute which is being used to read the end date. || `#calendar:startTime` | Similar to `#calendar:startDate`, allows changing the attribute which is being used to read the start time. |