🚀 A self-hostable personal dashboard built for you. Includes status-checking, widgets, themes, icon packs, a UI editor and tons more!
Vue awesomedashboarddockerhomelabhomepagemitnodejsorganizationproductivitypwaself-hostedstartpagevue
✨ Adds location and description support for calendar widget
Alicia Sykes6f72d6cdce65
diff --git a/docs/widgets.md b/docs/widgets.mdindex 35cd2b9c..fb912dfe 100644--- a/docs/widgets.md+++ b/docs/widgets.md@@ -271,6 +271,7 @@ Shows upcoming events from any calendar that publishes an iCalendar (`.ics`) feeNote that this needs to be proxied through Dashy, since calendar providers don't send CORS headers.`webcal://` links are accepted, same as `https://`.Recurring events, exceptions and moved occurrences are all expanded, and times are converted to your browser's timezone.+Events already underway stay listed until they end, and calendars with no `name` set use the name their feed publishes.#### Options@@ -280,6 +281,8 @@ Recurring events, exceptions and moved occurrences are all expanded, and times a**`days`** | `number` | _Optional_ | How many days ahead to show. Min: `1`, max: `365`. Defaults to `7`**`limit`** | `number` | _Optional_ | Maximum number of events to show. Defaults to `10`**`hideAllDay`** | `boolean` | _Optional_ | If `true`, all-day events are omitted+**`showLocation`** | `boolean` | _Optional_ | If `true`, shows each event's location under its title+**`showDescription`** | `boolean` | _Optional_ | If `true`, shows each event's description under its title**`startDate`** | `string` | _Optional_ | Show events from this date instead of today, e.g. `2026-09-03`#### Examplediff --git a/src/components/Widgets/Calendar.vue b/src/components/Widgets/Calendar.vueindex ea438bb2..ff9e0ec2 100644--- a/src/components/Widgets/Calendar.vue+++ b/src/components/Widgets/Calendar.vue@@ -14,9 +14,12 @@v-tooltip="eventTooltip(event)"><span class="event-time" :class="{ 'all-day': event.allDay }">{{ event.time }}</span>- <span class="event-title">- <span class="calendar-dot" v-if="event.color" :style="{ background: event.color }"></span>- {{ event.summary }}+ <span class="event-body">+ <span class="event-title">+ <span class="calendar-dot" v-if="event.color" :style="{ background: event.color }"></span>+ {{ event.summary }}+ </span>+ <span class="event-meta" v-if="event.meta">{{ event.meta }}</span></span></component></div>@@ -26,7 +29,7 @@<script>import WidgetMixin from '@/mixins/WidgetMixin';import { parseIcs } from '@/utils/IcsParser';-import { sanitize } from '@/utils/MiscHelpers';+import { sanitize, truncateStr } from '@/utils/MiscHelpers';import { sanitizeText, sanitizeUrl } from '@/utils/Sanitizer';export default {@@ -46,7 +49,7 @@ export default {const list = Array.isArray(input) ? input : [input];return list.map((entry) => (typeof entry === 'string' ? { url: entry } : entry))- .filter((entry) => entry && entry.url)+ .filter((entry) => entry && typeof entry.url === 'string').map((entry) => ({...entry,url: this.parseAsEnvVar(entry.url).replace(/^webcal:\/\//i, 'https://'),@@ -64,14 +67,14 @@ export default {hideAllDay() {return !!this.options.hideAllDay;},- /* The window to fetch events for, starting now unless told otherwise */+ },+ methods: {+ /* The window to show events for. A method, so refreshes move it along with the clock */range() {const requested = this.options.startDate ? new Date(this.options.startDate).getTime() : NaN;const start = Number.isNaN(requested) ? Date.now() : requested;return { start, end: start + this.daysAhead * 86400000 };},- },- methods: {fetchData() {if (!this.calendars.length) {this.error('Missing calendarUrl, see the docs for supported formats');@@ -83,11 +86,12 @@ export default {}const requests = this.calendars.map((calendar) => this.makeRequest(calendar.url));Promise.allSettled(requests).then((outcomes) => {+ const range = this.range();const events = [];let readable = 0;outcomes.forEach((outcome, index) => {if (outcome.status !== 'fulfilled') return;- if (this.readFeed(outcome.value, this.calendars[index], events)) readable += 1;+ if (this.readFeed(outcome.value, this.calendars[index], events, range)) readable += 1;});// Leave the widget empty if nothing could be read, so only the error showsif (!readable) return;@@ -96,15 +100,15 @@ export default {});},/* Parse a single feed, appending its events to the combined list */- readFeed(data, calendar, events) {- let parsed;+ readFeed(data, calendar, events, range) {+ let feed;try {- parsed = parseIcs(data, this.range);+ feed = parseIcs(data, range);} catch (error) {this.error(`Unable to parse calendar${calendar.name ? ` '${calendar.name}'` : ''}`, error);return false;}- parsed.forEach((event) => {+ feed.events.forEach((event) => {if (this.hideAllDay && event.allDay) return;events.push({...event,@@ -112,7 +116,7 @@ export default {// Feeds often put markup in the description, but never in the other fieldsdescription: sanitizeText(event.description),url: sanitizeUrl(event.url) || '',- source: calendar.name || '',+ source: calendar.name || feed.name,color: calendar.color || '',});});@@ -124,14 +128,25 @@ export default {events.forEach((event) => {const label = this.dayLabel(event);const current = groups[groups.length - 1];- const time = event.allDay- ? this.$t('widgets.calendar.all-day') : this.formatTime(event.start);- const formatted = { ...event, time };- if (current && current.label === label) current.events.push(formatted);- else groups.push({ label, events: [formatted] });+ const row = { ...event, time: this.eventTime(event), meta: this.eventMeta(event) };+ if (current && current.label === label) current.events.push(row);+ else groups.push({ label, events: [row] });});return groups;},+ eventTime(event) {+ if (event.allDay) return this.$t('widgets.calendar.all-day');+ return this.formatTime(event.start);+ },+ /* Location and description, when the user has asked to see them inline */+ eventMeta(event) {+ const meta = [];+ if (this.options.showLocation && event.location) meta.push(event.location);+ if (this.options.showDescription && event.description) {+ meta.push(truncateStr(event.description.replace(/\s+/g, ' '), 100));+ }+ return meta.join(' · ');+ },/* All-day events are anchored to UTC, so must be read back in UTC */eventDate(event) {const date = new Date(event.start);@@ -144,7 +159,8 @@ export default {today.setHours(0, 0, 0, 0);const date = this.eventDate(event);const daysAway = Math.round((date - today) / 86400000);- if (daysAway === 0) return this.$t('widgets.calendar.today');+ // Anything already underway belongs under today, not the day it began+ if (daysAway <= 0) return this.$t('widgets.calendar.today');if (daysAway === 1) return this.$t('widgets.calendar.tomorrow');return date.toLocaleDateString(navigator.language, {weekday: 'short', day: 'numeric', month: 'short',@@ -157,7 +173,8 @@ export default {},eventTooltip(event) {const lines = [];- if (event.source) lines.push(`<b>${sanitize(event.source)}</b>`);+ // Only worth naming the calendar when there is more than one to tell apart+ if (event.source && this.calendars.length > 1) lines.push(`<b>${sanitize(event.source)}</b>`);if (!event.allDay && event.end > event.start) {lines.push(`${event.time} - ${this.formatTime(event.end)}`);}@@ -203,10 +220,18 @@ export default {opacity: var(--dimming-factor);&.all-day { font-size: 0.75rem; }}- .event-title {- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;+ .event-body {+ min-width: 0;+ .event-title, .event-meta {+ display: block;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .event-meta {+ font-size: 0.75rem;+ opacity: var(--dimming-factor);+ }}.calendar-dot {display: inline-block;diff --git a/src/utils/IcsParser.js b/src/utils/IcsParser.jsindex 95b09e9b..75dfa934 100644--- a/src/utils/IcsParser.js+++ b/src/utils/IcsParser.js@@ -7,8 +7,9 @@const DAYS = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'];const FREQS = ['DAILY', 'WEEKLY', 'MONTHLY', 'YEARLY'];const DAY_MS = 86400000;+// Longest each period can be, so skipping ahead always lands early, never past an occurrenceconst PERIOD_MS = {- DAILY: DAY_MS, WEEKLY: 7 * DAY_MS, MONTHLY: 28 * DAY_MS, YEARLY: 365 * DAY_MS,+ DAILY: DAY_MS, WEEKLY: 7 * DAY_MS, MONTHLY: 31 * DAY_MS, YEARLY: 366 * DAY_MS,};const MAX_PERIODS = 5000;const LOCAL_ZONE = Intl.DateTimeFormat().resolvedOptions().timeZone;@@ -115,6 +116,8 @@ const parseRule = (value) => {return rule;};+const numbers = (value) => (value ? value.split(',').map(Number) : null);+const startOfPeriod = (ms, freq, weekStart) => {const date = new Date(ms);date.setUTCHours(0, 0, 0, 0);@@ -145,8 +148,9 @@ const daysMatchingByDay = (byDay, monthStart, monthLength) => {if (new Date(ms).getUTCDay() === weekday) matches.push(ms);}if (!nth) found.push(...matches);- else if (matches[nth > 0 ? nth - 1 : matches.length + nth]) {- found.push(matches[nth > 0 ? nth - 1 : matches.length + nth]);+ else {+ const nthMatch = matches[nth > 0 ? nth - 1 : matches.length + nth];+ if (nthMatch) found.push(nthMatch);}});return found;@@ -197,14 +201,13 @@ const expandRule = (rule, start, range) => {const interval = parseInt(rule.INTERVAL, 10) || 1;const count = parseInt(rule.COUNT, 10) || 0;const until = rule.UNTIL ? toEpoch(parseDate(rule.UNTIL)) : null;- const byMonth = rule.BYMONTH ? rule.BYMONTH.split(',').map(Number) : null;const parsed = {byDay: rule.BYDAY ? rule.BYDAY.split(',') : null,- byMonthDay: rule.BYMONTHDAY ? rule.BYMONTHDAY.split(',').map(Number) : null,- byMonth,+ byMonthDay: numbers(rule.BYMONTHDAY),+ byMonth: numbers(rule.BYMONTH),};- const bySetPos = rule.BYSETPOS ? rule.BYSETPOS.split(',').map(Number) : null;- const weekStart = Math.max(DAYS.indexOf(rule.WKST), 0);+ const bySetPos = numbers(rule.BYSETPOS);+ const weekStart = DAYS.includes(rule.WKST) ? DAYS.indexOf(rule.WKST) : 1;const timeOfDay = ((start.wall % DAY_MS) + DAY_MS) % DAY_MS;let cursor = startOfPeriod(start.wall, freq, weekStart);@@ -217,8 +220,8 @@ const expandRule = (rule, start, range) => {const found = [];for (let period = 0; period < MAX_PERIODS && cursor <= range.end; period += 1) {let days = daysInPeriod(cursor, freq, parsed, start.wall);- if (byMonth && freq !== 'YEARLY') {- days = days.filter((ms) => byMonth.includes(new Date(ms).getUTCMonth() + 1));+ if (parsed.byMonth && freq !== 'YEARLY') {+ days = days.filter((ms) => parsed.byMonth.includes(new Date(ms).getUTCMonth() + 1));}let candidates = days.map((ms) => ms + timeOfDay).sort((a, b) => a - b);if (bySetPos) {@@ -226,8 +229,7 @@ const expandRule = (rule, start, range) => {.map((pos) => candidates[pos > 0 ? pos - 1 : candidates.length + pos]).filter((ms) => ms !== undefined);}- for (let i = 0; i < candidates.length; i += 1) {- const wall = candidates[i];+ for (const wall of candidates) {if (wall >= start.wall) {if (until !== null && toEpoch({ ...start, wall }) > until) return found;found.push(wall);@@ -239,9 +241,10 @@ const expandRule = (rule, start, range) => {return found;};-/* Read every VEVENT, skipping nested components such as VALARM */-const collectEvents = (text) => {+/* Read the calendar's name and every VEVENT, skipping nested parts such as VALARM */+const readCalendar = (text) => {const events = [];+ let calendarName = '';let event = null;let nested = 0;unfold(text).forEach((raw) => {@@ -258,7 +261,11 @@ const collectEvents = (text) => {else if (value === 'VEVENT' && event) { events.push(event); event = null; }return;}- if (!event || nested) return;+ if (!event) {+ if (name === 'X-WR-CALNAME') calendarName = unescapeText(value);+ return;+ }+ if (nested) return;if (TEXT_FIELDS[name]) event[TEXT_FIELDS[name]] = unescapeText(value);else if (name === 'DTSTART') event.start = parseDate(value, params);else if (name === 'DTEND') event.end = parseDate(value, params);@@ -273,7 +280,7 @@ const collectEvents = (text) => {});}});- return events;+ return { name: calendarName, events };};/* Turn one occurrence into the flat shape the widget renders */@@ -297,16 +304,16 @@ const buildOccurrence = (event, wall) => {const isCancelled = (event) => event.status === 'CANCELLED';/**- * Parse an ICS document into occurrences starting within `range`.+ * Parse an ICS document into the occurrences falling within `range`.* @param {string} text - Raw iCalendar document* @param {{ start: number, end: number }} range - Window, as epoch milliseconds- * @returns {Array} Occurrences, ordered by start time+ * @returns {{ name: string, events: Array }} Feed name, and occurrences ordered by start time*/export const parseIcs = (text, range) => {if (!text || typeof text !== 'string' || !text.includes('BEGIN:VCALENDAR')) {throw new Error('Not a valid iCalendar feed');}- const events = collectEvents(text);+ const { name, events } = readCalendar(text);const overrides = new Map();events.forEach((event) => {if (event.recurrenceId && event.uid) {@@ -314,7 +321,9 @@ export const parseIcs = (text, range) => {}});- const inRange = (occurrence) => occurrence.start >= range.start && occurrence.start <= range.end;+ /* Anything overlapping the window, so events stay listed while they are still running */+ const inRange = ({ start, end }) => start <= range.end+ && (start >= range.start || end > range.start);const occurrences = [];events.forEach((event) => {@@ -335,7 +344,5 @@ export const parseIcs = (text, range) => {if (inRange(occurrence)) occurrences.push(occurrence);});- return occurrences.sort((a, b) => a.start - b.start);+ return { name, events: occurrences.sort((a, b) => a.start - b.start) };};--export default parseIcs;diff --git a/tests/components/widgets/calendar.test.js b/tests/components/widgets/calendar.test.jsindex 9be6836a..3518b7d5 100644--- a/tests/components/widgets/calendar.test.js+++ b/tests/components/widgets/calendar.test.js@@ -8,27 +8,31 @@ import Calendar from '@/components/Widgets/Calendar.vue';vi.mock('@/utils/request', () => ({ default: vi.fn() }));vi.mock('@/utils/logging/ErrorHandler', () => ({ default: vi.fn() }));-/* Events are written relative to a frozen clock, so the day labels stay stable */-const NOW = Date.parse('2026-09-03T08:00:00Z');-const at = (offsetDays, time) => {- const date = new Date(NOW + offsetDays * 86400000);- return `${date.toISOString().slice(0, 10).replace(/-/g, '')}T${time}Z`;+/* Events sit at a local wall-clock time on a frozen local day, so that day+ * labels and ordering come out the same whatever timezone the tests run in */+const NOW = new Date('2026-09-03T08:00:00');+const at = (addDays, hour) => {+ const date = new Date(NOW);+ date.setDate(date.getDate() + addDays);+ date.setHours(hour, 0, 0, 0);+ return date.toISOString().replace(/[-:]|\.\d{3}/g, '');};const feed = (...events) => ['BEGIN:VCALENDAR','VERSION:2.0',- ...events.map((event) => `BEGIN:VEVENT\r\n${event}\r\nEND:VEVENT`),+ ...events.map((lines) => ['BEGIN:VEVENT', ...lines, 'END:VEVENT'].join('\r\n')),'END:VCALENDAR',].join('\r\n');const defaultFeed = feed(- ['UID:1', `DTSTART:${at(0, '140000')}`, `DTEND:${at(0, '150000')}`, 'SUMMARY:Team sync',- 'LOCATION:Room 2'].join('\r\n'),+ ['UID:1', `DTSTART:${at(0, 10)}`, `DTEND:${at(0, 11)}`,+ 'SUMMARY:Standup, where nobody stands', 'LOCATION:The broom cupboard',+ 'DESCRIPTION:Bring your own excuses'],['UID:2', 'DTSTART;VALUE=DATE:20260904', 'DTEND;VALUE=DATE:20260905',- 'SUMMARY:Company offsite'].join('\r\n'),- ['UID:3', `DTSTART:${at(2, '090000')}`, 'SUMMARY:Dentist',- 'URL:https://example.com/appointment'].join('\r\n'),+ 'SUMMARY:Offsite trust falls'],+ ['UID:3', `DTSTART:${at(2, 9)}`, 'SUMMARY:Dentist, reluctantly',+ 'URL:https://example.com/appointment'],);const tooltips = [];@@ -44,6 +48,7 @@ async function mount(options = {}) {}const textOf = (wrapper, selector) => wrapper.findAll(selector).map((node) => node.text());+const titles = (wrapper) => textOf(wrapper, '.event-title');describe('Calendar widget', () => {beforeEach(() => {@@ -59,14 +64,14 @@ describe('Calendar widget', () => {it('groups events under a heading for each day', async () => {const wrapper = await mount();const labels = textOf(wrapper, '.day-label');+ expect(labels).toHaveLength(3);expect(labels.slice(0, 2)).toEqual(['widgets.calendar.today', 'widgets.calendar.tomorrow']);- expect(labels[2]).toMatch(/Sat.*5|5.*Sep/);- expect(textOf(wrapper, '.event-title')).toEqual(['Team sync', 'Company offsite', 'Dentist']);+ expect(titles(wrapper))+ .toEqual(['Standup, where nobody stands', 'Offsite trust falls', 'Dentist, reluctantly']);});it('labels all-day events, and shows a start time for the rest', async () => {- const wrapper = await mount();- const times = textOf(wrapper, '.event-time');+ const times = textOf(await mount(), '.event-time');expect(times[1]).toBe('widgets.calendar.all-day');expect(times[0]).toMatch(/\d{2}:\d{2}/);});@@ -82,8 +87,8 @@ describe('Calendar widget', () => {it('merges several calendars, ordered by start time', async () => {request.mockImplementation((config) => Promise.resolve({data: config.headers['Target-URL'].includes('work')- ? feed(['UID:w', `DTSTART:${at(0, '110000')}`, 'SUMMARY:Standup'].join('\r\n'))- : feed(['UID:h', `DTSTART:${at(0, '093000')}`, 'SUMMARY:Gym'].join('\r\n')),+ ? feed(['UID:w', `DTSTART:${at(0, 11)}`, 'SUMMARY:Explain the outage'])+ : feed(['UID:h', `DTSTART:${at(0, 9)}`, 'SUMMARY:Gym (aspirational)']),}));const wrapper = await mount({calendarUrl: [@@ -91,7 +96,7 @@ describe('Calendar widget', () => {{ url: 'https://example.com/home.ics', name: 'Home' },],});- expect(textOf(wrapper, '.event-title')).toEqual(['Gym', 'Standup']);+ expect(titles(wrapper)).toEqual(['Gym (aspirational)', 'Explain the outage']);expect(wrapper.findAll('.calendar-dot')).toHaveLength(1);});@@ -102,41 +107,78 @@ describe('Calendar widget', () => {const wrapper = await mount({calendarUrl: ['https://example.com/broken.ics', 'https://example.com/cal.ics'],});- expect(textOf(wrapper, '.event-title')).toEqual(['Team sync', 'Company offsite', 'Dentist']);+ expect(titles(wrapper)).toHaveLength(3);});it('respects limit, hideAllDay and days', async () => {- const limited = await mount({ limit: 2 });- expect(textOf(limited, '.event-title')).toHaveLength(2);+ expect(titles(await mount({ limit: 2 }))).toHaveLength(2);- const timedOnly = await mount({ hideAllDay: true });- expect(textOf(timedOnly, '.event-title')).toEqual(['Team sync', 'Dentist']);+ expect(titles(await mount({ hideAllDay: true })))+ .toEqual(['Standup, where nobody stands', 'Dentist, reluctantly']);- const today = await mount({ days: 1 });- expect(textOf(today, '.event-title')).toEqual(['Team sync', 'Company offsite']);+ const today = titles(await mount({ days: 1 }));+ expect(today).toContain('Standup, where nobody stands');+ expect(today).not.toContain('Dentist, reluctantly');});it('links events that have a URL, and leaves the others as plain rows', async () => {- const wrapper = await mount();- const links = wrapper.findAll('a.event-row');+ const links = (await mount()).findAll('a.event-row');expect(links).toHaveLength(1);expect(links[0].attributes('href')).toBe('https://example.com/appointment');});it('drops unsafe event URLs', async () => {request.mockResolvedValue({- data: feed(['UID:1', `DTSTART:${at(0, '140000')}`, 'SUMMARY:Dodgy',+ data: feed(['UID:1', `DTSTART:${at(0, 10)}`, 'SUMMARY:Totally legitimate prize',// eslint-disable-next-line no-script-url- 'URL:javascript:alert(1)'].join('\r\n')),+ 'URL:javascript:alert(1)']),});- const wrapper = await mount();- expect(wrapper.findAll('a.event-row')).toHaveLength(0);+ expect((await mount()).findAll('a.event-row')).toHaveLength(0);});- it('shows the location and calendar name in the tooltip', async () => {- await mount({ calendarUrl: [{ url: 'https://example.com/cal.ics', name: 'Work' }] });+ it('shows the location in the tooltip, and names the calendar only when there are several', async () => {+ await mount();+ expect(tooltips[0]).toContain('The broom cupboard');+ expect(tooltips[0]).not.toContain('Work');++ tooltips.length = 0;+ await mount({+ calendarUrl: [+ { url: 'https://example.com/work.ics', name: 'Work' },+ { url: 'https://example.com/home.ics' },+ ],+ });expect(tooltips[0]).toContain('Work');- expect(tooltips[0]).toContain('Room 2');+ });++ it('falls back to the feed\'s own name when the calendar has not been named', async () => {+ request.mockResolvedValue({+ data: ['BEGIN:VCALENDAR', 'X-WR-CALNAME:Bin collections',+ `BEGIN:VEVENT\r\nUID:1\r\nDTSTART:${at(0, 10)}\r\nSUMMARY:Green bin\r\nEND:VEVENT`,+ 'END:VCALENDAR'].join('\r\n'),+ });+ await mount({ calendarUrl: ['https://example.com/a.ics', 'https://example.com/b.ics'] });+ expect(tooltips[0]).toContain('Bin collections');+ });++ it('shows location and description inline, only when asked', async () => {+ expect(textOf(await mount(), '.event-meta')).toEqual([]);++ expect(textOf(await mount({ showLocation: true }), '.event-meta')[0])+ .toBe('The broom cupboard');+ expect(textOf(await mount({ showDescription: true }), '.event-meta')[0])+ .toBe('Bring your own excuses');+ expect(textOf(await mount({ showLocation: true, showDescription: true }), '.event-meta')[0])+ .toBe('The broom cupboard · Bring your own excuses');+ });++ it('keeps showing an event that is underway, under today', async () => {+ request.mockResolvedValue({+ data: feed(['UID:1', `DTSTART:${at(0, 7)}`, `DTEND:${at(0, 18)}`, 'SUMMARY:All-day hackathon']),+ });+ const wrapper = await mount();+ expect(titles(wrapper)).toEqual(['All-day hackathon']);+ expect(textOf(wrapper, '.day-label')).toEqual(['widgets.calendar.today']);});it('reports a helpful message when no calendar is configured', async () => {@@ -146,7 +188,7 @@ describe('Calendar widget', () => {});it('reports a message when the feed is not a calendar, without saying it is empty', async () => {- request.mockResolvedValue({ data: '<html>Login page</html>' });+ request.mockResolvedValue({ data: '<html>Please log in</html>' });const wrapper = await mount();expect(wrapper.emitted().error[0][0]).toContain('Unable to parse calendar');expect(wrapper.find('.no-events').exists()).toBe(false);@@ -154,7 +196,6 @@ describe('Calendar widget', () => {it('says so when there is nothing coming up', async () => {request.mockResolvedValue({ data: feed() });- const wrapper = await mount();- expect(wrapper.find('.no-events').text()).toBe('widgets.calendar.no-events');+ expect((await mount()).find('.no-events').text()).toBe('widgets.calendar.no-events');});});diff --git a/tests/unit/ics-parser.test.js b/tests/unit/ics-parser.test.jsindex 68f6ef82..94118a7a 100644--- a/tests/unit/ics-parser.test.js+++ b/tests/unit/ics-parser.test.js@@ -1,11 +1,11 @@import { describe, it, expect } from 'vitest';import { parseIcs } from '@/utils/IcsParser';-/* Wrap VEVENT bodies in a minimal calendar */+/* Wrap one or more VEVENTs, each given as a list of lines, in a minimal calendar */const calendar = (...events) => ['BEGIN:VCALENDAR','VERSION:2.0',- ...events.map((event) => `BEGIN:VEVENT\r\n${event}\r\nEND:VEVENT`),+ ...events.map((lines) => ['BEGIN:VEVENT', ...lines, 'END:VEVENT'].join('\r\n')),'END:VCALENDAR',].join('\r\n');@@ -14,28 +14,33 @@ const between = (from, to) => ({end: Date.parse(`${to}T00:00:00Z`),});+/* parseIcs returns the feed name alongside its events; most tests only want the events */+const parse = (ics, range) => parseIcs(ics, range).events;+const starts = (events) => events.map((event) => new Date(event.start).toISOString());const days = (events) => events.map((event) => new Date(event.start).toISOString().slice(0, 10));+const titles = (events) => events.map((event) => event.summary);describe('IcsParser', () => {- it('rejects anything that is not a calendar', () => {- expect(() => parseIcs('<html>nope</html>', between('2026-01-01', '2026-12-31'))).toThrow();- expect(() => parseIcs('', between('2026-01-01', '2026-12-31'))).toThrow();+ it('throws on a page that is not a calendar, rather than reporting it as empty', () => {+ expect(() => parseIcs('<html>Please log in</html>', between('2026-01-01', '2026-12-31')))+ .toThrow();});it('unfolds wrapped lines and unescapes text', () => {const ics = calendar(['UID:1','DTSTART:20260904T090000Z',- 'SUMMARY:Quarterly planning\\, budget review',- 'DESCRIPTION:First line\\nSecond line',- 'LOCATION:Room A\\; upstairs\\, near the very long corridor that keeps',- ' going',- ].join('\r\n'));- const [event] = parseIcs(ics, between('2026-09-01', '2026-09-30'));- expect(event.summary).toBe('Quarterly planning, budget review');- expect(event.description).toBe('First line\nSecond line');- expect(event.location).toBe('Room A; upstairs, near the very long corridor that keeps going');+ 'SUMMARY:Tabs vs spaces\\, the reckoning',+ 'DESCRIPTION:Bring snacks\\nAnd a helmet',+ 'LOCATION:The broom cupboard\\; second floor\\, past the humming server that',+ ' nobody will admit to owning',+ ]);+ const [event] = parse(ics, between('2026-09-01', '2026-09-30'));+ expect(event.summary).toBe('Tabs vs spaces, the reckoning');+ expect(event.description).toBe('Bring snacks\nAnd a helmet');+ expect(event.location)+ .toBe('The broom cupboard; second floor, past the humming server that nobody will admit to owning');});it('anchors all-day events to UTC, so the date never drifts', () => {@@ -44,20 +49,20 @@ describe('IcsParser', () => {'DTSTART;VALUE=DATE:20261225','DTEND;VALUE=DATE:20261226','SUMMARY:Christmas Day',- ].join('\r\n'));- const [event] = parseIcs(ics, between('2026-12-01', '2026-12-31'));+ ]);+ const [event] = parse(ics, between('2026-12-01', '2026-12-31'));expect(event.allDay).toBe(true);- expect(new Date(event.start).toISOString()).toBe('2026-12-25T00:00:00.000Z');+ expect(starts([event])).toEqual(['2026-12-25T00:00:00.000Z']);});- it('reads UTC times, and end times from either DTEND or DURATION', () => {+ it('reads end times from either DTEND or DURATION', () => {const ics = calendar(- ['UID:1', 'DTSTART:20260904T090000Z', 'DTEND:20260904T103000Z', 'SUMMARY:With end'].join('\r\n'),- ['UID:2', 'DTSTART:20260904T140000Z', 'DURATION:PT45M', 'SUMMARY:With duration'].join('\r\n'),+ ['UID:1', 'DTSTART:20260904T090000Z', 'DTEND:20260904T103000Z', 'SUMMARY:Long lunch'],+ ['UID:2', 'DTSTART:20260904T140000Z', 'DURATION:PT45M', 'SUMMARY:Quick chat'],);- const events = parseIcs(ics, between('2026-09-01', '2026-09-30'));- expect(events[0].end - events[0].start).toBe(90 * 60 * 1000);- expect(events[1].end - events[1].start).toBe(45 * 60 * 1000);+ const [lunch, chat] = parse(ics, between('2026-09-01', '2026-09-30'));+ expect(lunch.end - lunch.start).toBe(90 * 60 * 1000);+ expect(chat.end - chat.start).toBe(45 * 60 * 1000);});it('holds a recurring meeting at the same local time across a DST change', () => {@@ -66,11 +71,11 @@ describe('IcsParser', () => {'DTSTART;TZID=America/New_York:20261028T090000','DTEND;TZID=America/New_York:20261028T100000','RRULE:FREQ=WEEKLY;BYDAY=WE',- 'SUMMARY:Weekly sync',- ].join('\r\n'));- const events = parseIcs(ics, between('2026-10-27', '2026-11-05'));+ 'SUMMARY:Weekly blameless post-mortem (mostly blame)',+ ]);// New York is UTC-4 on 28 Oct, but UTC-5 on 4 Nov- expect(starts(events)).toEqual(['2026-10-28T13:00:00.000Z', '2026-11-04T14:00:00.000Z']);+ expect(starts(parse(ics, between('2026-10-27', '2026-11-05'))))+ .toEqual(['2026-10-28T13:00:00.000Z', '2026-11-04T14:00:00.000Z']);});it('expands a fortnightly rule, honouring INTERVAL', () => {@@ -78,9 +83,9 @@ describe('IcsParser', () => {'UID:1','DTSTART:20260907T100000Z','RRULE:FREQ=WEEKLY;INTERVAL=2;BYDAY=MO',- 'SUMMARY:Fortnightly',- ].join('\r\n'));- expect(days(parseIcs(ics, between('2026-09-01', '2026-10-20'))))+ 'SUMMARY:Bin day (the good bin)',+ ]);+ expect(days(parse(ics, between('2026-09-01', '2026-10-20')))).toEqual(['2026-09-07', '2026-09-21', '2026-10-05', '2026-10-19']);});@@ -89,9 +94,9 @@ describe('IcsParser', () => {'UID:1','DTSTART:20260120T110000Z','RRULE:FREQ=MONTHLY;BYDAY=3TU',- 'SUMMARY:Third Tuesday',- ].join('\r\n'));- expect(days(parseIcs(ics, between('2026-01-01', '2026-04-01'))))+ 'SUMMARY:Board game night, someone always flips the table',+ ]);+ expect(days(parse(ics, between('2026-01-01', '2026-04-01')))).toEqual(['2026-01-20', '2026-02-17', '2026-03-17']);});@@ -100,32 +105,46 @@ describe('IcsParser', () => {'UID:1','DTSTART:20260131T080000Z','RRULE:FREQ=MONTHLY;BYMONTHDAY=-1',- 'SUMMARY:Month end',- ].join('\r\n'));- expect(days(parseIcs(ics, between('2026-01-01', '2026-04-01'))))+ 'SUMMARY:Remember what the invoices were for',+ ]);+ expect(days(parse(ics, between('2026-01-01', '2026-04-01')))).toEqual(['2026-01-31', '2026-02-28', '2026-03-31']);});+ it('still finds occurrences of a rule that started years ago', () => {+ const ics = calendar([+ 'UID:1',+ 'DTSTART:20160805T170000Z',+ 'RRULE:FREQ=MONTHLY;BYDAY=1WE',+ 'SUMMARY:All-hands, unchanged since 2016',+ ]);+ expect(days(parse(ics, between('2026-09-03', '2026-12-03'))))+ .toEqual(['2026-10-07', '2026-11-04', '2026-12-02']);+ });+it('applies BYSETPOS, such as the last weekday of the month', () => {const ics = calendar(['UID:1','DTSTART:20260130T170000Z','RRULE:FREQ=MONTHLY;BYDAY=MO,TU,WE,TH,FR;BYSETPOS=-1',- 'SUMMARY:Last weekday',- ].join('\r\n'));- expect(days(parseIcs(ics, between('2026-01-01', '2026-03-01'))))+ 'SUMMARY:Friday deploy, against all advice',+ ]);+ expect(days(parse(ics, between('2026-01-01', '2026-03-01')))).toEqual(['2026-01-30', '2026-02-27']);});it('stops a rule at COUNT or UNTIL', () => {- const counted = calendar(['UID:1', 'DTSTART:20260907T090000Z',- 'RRULE:FREQ=DAILY;COUNT=3', 'SUMMARY:Counted'].join('\r\n'));- expect(days(parseIcs(counted, between('2026-09-01', '2026-10-01'))))+ const counted = calendar([+ 'UID:1', 'DTSTART:20260907T090000Z', 'RRULE:FREQ=DAILY;COUNT=3', 'SUMMARY:Three day juice cleanse',+ ]);+ expect(days(parse(counted, between('2026-09-01', '2026-10-01')))).toEqual(['2026-09-07', '2026-09-08', '2026-09-09']);- const dated = calendar(['UID:1', 'DTSTART:20260907T090000Z',- 'RRULE:FREQ=DAILY;UNTIL=20260909T090000Z', 'SUMMARY:Until'].join('\r\n'));- expect(days(parseIcs(dated, between('2026-09-01', '2026-10-01'))))+ const dated = calendar([+ 'UID:1', 'DTSTART:20260907T090000Z', 'RRULE:FREQ=DAILY;UNTIL=20260909T090000Z',+ 'SUMMARY:Feed the neighbour\'s cat',+ ]);+ expect(days(parse(dated, between('2026-09-01', '2026-10-01')))).toEqual(['2026-09-07', '2026-09-08', '2026-09-09']);});@@ -136,53 +155,69 @@ describe('IcsParser', () => {'RRULE:FREQ=DAILY;COUNT=3','EXDATE:20260908T090000Z','RDATE:20260912T090000Z',- 'SUMMARY:Standup',- ].join('\r\n'));- expect(days(parseIcs(ics, between('2026-09-01', '2026-10-01'))))+ 'SUMMARY:Standup, where nobody stands',+ ]);+ expect(days(parse(ics, between('2026-09-01', '2026-10-01')))).toEqual(['2026-09-07', '2026-09-09', '2026-09-12']);});it('replaces a single occurrence with its RECURRENCE-ID override', () => {const ics = calendar(- ['UID:1', 'DTSTART:20260907T090000Z', 'RRULE:FREQ=DAILY;COUNT=3',- 'SUMMARY:Standup'].join('\r\n'),+ ['UID:1', 'DTSTART:20260907T090000Z', 'RRULE:FREQ=DAILY;COUNT=3', 'SUMMARY:Standup'],['UID:1', 'RECURRENCE-ID:20260908T090000Z', 'DTSTART:20260908T160000Z',- 'SUMMARY:Standup (moved)'].join('\r\n'),+ 'SUMMARY:Standup, moved so Dave can go to the dentist'],);- const events = parseIcs(ics, between('2026-09-01', '2026-10-01'));+ const events = parse(ics, between('2026-09-01', '2026-10-01'));expect(starts(events)).toEqual(['2026-09-07T09:00:00.000Z', '2026-09-08T16:00:00.000Z', '2026-09-09T09:00:00.000Z',]);- expect(events[1].summary).toBe('Standup (moved)');+ expect(events[1].summary).toContain('moved');});it('ignores cancelled events and nested components', () => {const ics = calendar(- ['UID:1', 'DTSTART:20260904T090000Z', 'SUMMARY:Cancelled', 'STATUS:CANCELLED'].join('\r\n'),- ['UID:2', 'DTSTART:20260904T100000Z', 'SUMMARY:Real', 'BEGIN:VALARM',- 'TRIGGER:-PT10M', 'SUMMARY:Reminder', 'END:VALARM'].join('\r\n'),+ ['UID:1', 'DTSTART:20260904T090000Z', 'SUMMARY:Mandatory fun', 'STATUS:CANCELLED'],+ ['UID:2', 'DTSTART:20260904T100000Z', 'SUMMARY:Actually happening',+ 'BEGIN:VALARM', 'TRIGGER:-PT10M', 'SUMMARY:Nag', 'END:VALARM'],);- const events = parseIcs(ics, between('2026-09-01', '2026-09-30'));- expect(events.map((event) => event.summary)).toEqual(['Real']);+ expect(titles(parse(ics, between('2026-09-01', '2026-09-30'))))+ .toEqual(['Actually happening']);});- it('only returns events that start within the window', () => {+ it('only returns events overlapping the window', () => {const ics = calendar(- ['UID:1', 'DTSTART:20260801T090000Z', 'SUMMARY:Before'].join('\r\n'),- ['UID:2', 'DTSTART:20260915T090000Z', 'SUMMARY:During'].join('\r\n'),- ['UID:3', 'DTSTART:20261101T090000Z', 'SUMMARY:After'].join('\r\n'),+ ['UID:1', 'DTSTART:20260801T090000Z', 'SUMMARY:Last month\'s regrets'],+ ['UID:2', 'DTSTART:20260915T090000Z', 'SUMMARY:This week\'s chaos'],+ ['UID:3', 'DTSTART:20261101T090000Z', 'SUMMARY:Next quarter\'s problem'],);- const events = parseIcs(ics, between('2026-09-01', '2026-10-01'));- expect(events.map((event) => event.summary)).toEqual(['During']);+ expect(titles(parse(ics, between('2026-09-01', '2026-10-01'))))+ .toEqual(['This week\'s chaos']);+ });++ it('keeps an event that began before the window but has not finished', () => {+ const ics = calendar(+ ['UID:1', 'DTSTART:20260831T090000Z', 'DTEND:20260901T170000Z', 'SUMMARY:Hackathon, hour 30'],+ ['UID:2', 'DTSTART:20260831T090000Z', 'DTEND:20260831T170000Z', 'SUMMARY:Yesterday, finished'],+ ['UID:3', 'DTSTART:20260830T090000Z', 'SUMMARY:No end time, so long gone'],+ );+ expect(titles(parse(ics, between('2026-09-01', '2026-10-01'))))+ .toEqual(['Hackathon, hour 30']);+ });++ it('reads the feed name, for labelling a calendar the user has not named', () => {+ const named = `BEGIN:VCALENDAR\r\nX-WR-CALNAME:Bins\\, and when to move them\r\nEND:VCALENDAR`;+ expect(parseIcs(named, between('2026-09-01', '2026-10-01')).name)+ .toBe('Bins, and when to move them');+ expect(parseIcs(calendar(), between('2026-09-01', '2026-10-01')).name).toBe('');});it('falls back to local time for timezones it cannot resolve', () => {const ics = calendar(['UID:1','DTSTART;TZID=GMT Standard Time:20260904T090000',- 'SUMMARY:Outlook style',- ].join('\r\n'));- const [event] = parseIcs(ics, between('2026-09-01', '2026-09-30'));+ 'SUMMARY:Meeting booked by someone using Outlook',+ ]);+ const [event] = parse(ics, between('2026-09-01', '2026-09-30'));expect(new Date(event.start).getHours()).toBe(9);});});