Skip to content

armgit / dashy

Public Imported from GitHub
0

πŸš€ A self-hostable personal dashboard built for you. Includes status-checking, widgets, themes, icon packs, a UI editor and tons more!

✨ New calendar widget for generic ical

Alicia Sykes23b8b514fbae
diff --git a/src/assets/locales/en.json b/src/assets/locales/en.json
index ab6ee3d3..73e72ab5 100644
--- a/src/assets/locales/en.json
+++ b/src/assets/locales/en.json
@@ -448,6 +448,13 @@
"show-less": "Show Less",
"open-link": "Continue Reading"
},
+ "calendar": {
+ "all-day": "All day",
+ "no-events": "Nothing coming up",
+ "today": "Today",
+ "tomorrow": "Tomorrow",
+ "untitled": "Untitled event"
+ },
"github-profile": {
"repos": "Repos",
"followers": "Followers",
diff --git a/src/components/Widgets/Calendar.vue b/src/components/Widgets/Calendar.vue
new file mode 100644
index 00000000..ea438bb2
--- /dev/null
+++ b/src/components/Widgets/Calendar.vue
@@ -0,0 +1,230 @@
+<template>
+<div class="calendar-wrapper">
+ <p class="no-events" v-if="days && !days.length">{{ $t('widgets.calendar.no-events') }}</p>
+ <div class="day-group" v-for="day in days" :key="day.label">
+ <p class="day-label">{{ day.label }}</p>
+ <component
+ :is="event.url ? 'a' : 'div'"
+ class="event-row"
+ v-for="(event, index) in day.events"
+ :key="index"
+ :href="event.url || undefined"
+ target="_blank"
+ rel="noopener noreferrer"
+ 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>
+ </component>
+ </div>
+</div>
+</template>
+
+<script>
+import WidgetMixin from '@/mixins/WidgetMixin';
+import { parseIcs } from '@/utils/IcsParser';
+import { sanitize } from '@/utils/MiscHelpers';
+import { sanitizeText, sanitizeUrl } from '@/utils/Sanitizer';
+
+export default {
+ mixins: [WidgetMixin],
+ components: {},
+ data() {
+ return {
+ days: null,
+ overrideProxyChoice: true,
+ };
+ },
+ computed: {
+ /* User's feed(s), normalised to a list of { url, name, color } */
+ calendars() {
+ const input = this.options.calendarUrl;
+ if (!input) return [];
+ const list = Array.isArray(input) ? input : [input];
+ return list
+ .map((entry) => (typeof entry === 'string' ? { url: entry } : entry))
+ .filter((entry) => entry && entry.url)
+ .map((entry) => ({
+ ...entry,
+ url: this.parseAsEnvVar(entry.url).replace(/^webcal:\/\//i, 'https://'),
+ }));
+ },
+ /* Number of days ahead to show events for */
+ daysAhead() {
+ const usersChoice = this.options.days;
+ if (usersChoice > 0 && usersChoice <= 365) return usersChoice;
+ return 7;
+ },
+ limit() {
+ return this.options.limit || 10;
+ },
+ hideAllDay() {
+ return !!this.options.hideAllDay;
+ },
+ /* The window to fetch events for, starting now unless told otherwise */
+ 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');
+ this.finishLoading();
+ return;
+ }
+ if (this.options.startDate && Number.isNaN(new Date(this.options.startDate).getTime())) {
+ this.error('Invalid startDate, expected a date like 2026-09-03');
+ }
+ const requests = this.calendars.map((calendar) => this.makeRequest(calendar.url));
+ Promise.allSettled(requests).then((outcomes) => {
+ 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;
+ });
+ // Leave the widget empty if nothing could be read, so only the error shows
+ if (!readable) return;
+ events.sort((first, second) => first.start - second.start);
+ this.days = this.groupByDay(events.slice(0, this.limit));
+ });
+ },
+ /* Parse a single feed, appending its events to the combined list */
+ readFeed(data, calendar, events) {
+ let parsed;
+ try {
+ parsed = parseIcs(data, this.range);
+ } catch (error) {
+ this.error(`Unable to parse calendar${calendar.name ? ` '${calendar.name}'` : ''}`, error);
+ return false;
+ }
+ parsed.forEach((event) => {
+ if (this.hideAllDay && event.allDay) return;
+ events.push({
+ ...event,
+ summary: event.summary || this.$t('widgets.calendar.untitled'),
+ // Feeds often put markup in the description, but never in the other fields
+ description: sanitizeText(event.description),
+ url: sanitizeUrl(event.url) || '',
+ source: calendar.name || '',
+ color: calendar.color || '',
+ });
+ });
+ return true;
+ },
+ /* Bucket events under a heading for the day they fall on */
+ groupByDay(events) {
+ const groups = [];
+ 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] });
+ });
+ return groups;
+ },
+ /* All-day events are anchored to UTC, so must be read back in UTC */
+ eventDate(event) {
+ const date = new Date(event.start);
+ return event.allDay
+ ? new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate())
+ : new Date(date.getFullYear(), date.getMonth(), date.getDate());
+ },
+ dayLabel(event) {
+ const today = new Date();
+ 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');
+ if (daysAway === 1) return this.$t('widgets.calendar.tomorrow');
+ return date.toLocaleDateString(navigator.language, {
+ weekday: 'short', day: 'numeric', month: 'short',
+ });
+ },
+ formatTime(timestamp) {
+ return new Date(timestamp).toLocaleTimeString(navigator.language, {
+ hour: '2-digit', minute: '2-digit',
+ });
+ },
+ eventTooltip(event) {
+ const lines = [];
+ if (event.source) lines.push(`<b>${sanitize(event.source)}</b>`);
+ if (!event.allDay && event.end > event.start) {
+ lines.push(`${event.time} - ${this.formatTime(event.end)}`);
+ }
+ if (event.location) lines.push(sanitize(event.location));
+ if (event.description) lines.push(sanitize(event.description.slice(0, 200)));
+ if (!lines.length) return { content: '' };
+ return { content: lines.join('<br>'), html: true, popperClass: 'calendar-event-tt' };
+ },
+ },
+};
+</script>
+
+<style scoped lang="scss">
+.calendar-wrapper {
+ padding: 0.25rem 0;
+ color: var(--widget-text-color);
+ p.no-events {
+ margin: 0.5rem 0;
+ text-align: center;
+ opacity: var(--dimming-factor);
+ }
+ .day-group {
+ &:not(:last-child) { margin-bottom: 0.5rem; }
+ p.day-label {
+ margin: 0 0 0.15rem;
+ font-size: 0.8rem;
+ font-weight: bold;
+ text-transform: uppercase;
+ opacity: var(--dimming-factor);
+ border-bottom: 1px dashed var(--widget-text-color);
+ }
+ }
+ .event-row {
+ display: grid;
+ grid-template-columns: 4.2rem 1fr;
+ gap: 0.4rem;
+ padding: 0.15rem 0;
+ font-size: 0.9rem;
+ text-decoration: none;
+ color: var(--widget-text-color);
+ .event-time {
+ font-variant-numeric: tabular-nums;
+ opacity: var(--dimming-factor);
+ &.all-day { font-size: 0.75rem; }
+ }
+ .event-title {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .calendar-dot {
+ display: inline-block;
+ width: 0.5rem;
+ height: 0.5rem;
+ margin-right: 0.25rem;
+ border-radius: 50%;
+ }
+ &[href]:hover {
+ opacity: 1;
+ text-decoration: underline;
+ }
+ }
+}
+</style>
+
+<style lang="scss">
+.calendar-event-tt {
+ max-width: 20rem;
+}
+</style>
diff --git a/src/components/Widgets/WidgetBase.vue b/src/components/Widgets/WidgetBase.vue
index b3d83213..79cc390d 100644
--- a/src/components/Widgets/WidgetBase.vue
+++ b/src/components/Widgets/WidgetBase.vue
@@ -58,6 +58,7 @@ const COMPAT = {
anonaddy: 'AnonAddy',
apod: 'Apod',
'blacklist-check': 'BlacklistCheck',
+ calendar: 'Calendar',
chucknorris: 'ChuckNorris',
clock: 'Clock',
'code-stats': 'CodeStats',
diff --git a/src/utils/IcsParser.js b/src/utils/IcsParser.js
new file mode 100644
index 00000000..95b09e9b
--- /dev/null
+++ b/src/utils/IcsParser.js
@@ -0,0 +1,341 @@
+/**
+ * Attempt at a minimal iCal parser, following RFC 5545
+ * Returning a time-ordered list of events from requested start date
+ * Used for the calendar widget
+ */
+
+const DAYS = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'];
+const FREQS = ['DAILY', 'WEEKLY', 'MONTHLY', 'YEARLY'];
+const DAY_MS = 86400000;
+const PERIOD_MS = {
+ DAILY: DAY_MS, WEEKLY: 7 * DAY_MS, MONTHLY: 28 * DAY_MS, YEARLY: 365 * DAY_MS,
+};
+const MAX_PERIODS = 5000;
+const LOCAL_ZONE = Intl.DateTimeFormat().resolvedOptions().timeZone;
+
+const TEXT_FIELDS = {
+ UID: 'uid',
+ SUMMARY: 'summary',
+ DESCRIPTION: 'description',
+ LOCATION: 'location',
+ URL: 'url',
+ STATUS: 'status',
+};
+
+/* Undo RFC 5545 line folding, and split into logical lines */
+const unfold = (text) => text
+ .replace(/^\uFEFF/, '')
+ .replace(/\r\n|\r/g, '\n')
+ .replace(/\n[ \t]/g, '')
+ .split('\n');
+
+/* Split `NAME;PARAM=VALUE:value` into its parts, ignoring colons inside quotes */
+const parseLine = (line) => {
+ let quoted = false;
+ for (let i = 0; i < line.length; i += 1) {
+ if (line[i] === '"') quoted = !quoted;
+ else if (line[i] === ':' && !quoted) {
+ const [name, ...rest] = line.slice(0, i).split(';');
+ const params = {};
+ rest.forEach((param) => {
+ const eq = param.indexOf('=');
+ if (eq > 0) params[param.slice(0, eq).toUpperCase()] = param.slice(eq + 1).replace(/"/g, '');
+ });
+ return { name: name.toUpperCase(), params, value: line.slice(i + 1) };
+ }
+ }
+ return null;
+};
+
+const unescapeText = (value) => value.replace(/\\n/gi, '\n').replace(/\\(.)/g, '$1');
+
+/* Named zones we can't resolve (such as Windows TZIDs) fall back to the local zone */
+const zones = new Map();
+const resolveZone = (tz) => {
+ if (!tz) return LOCAL_ZONE;
+ if (!zones.has(tz)) {
+ try {
+ Intl.DateTimeFormat('en-GB', { timeZone: tz });
+ zones.set(tz, tz);
+ } catch {
+ zones.set(tz, LOCAL_ZONE);
+ }
+ }
+ return zones.get(tz);
+};
+
+/* How far the given zone is from UTC, at the given moment */
+const offsetAt = (ms, zone) => {
+ const parts = {};
+ Intl.DateTimeFormat('en-GB', {
+ timeZone: zone,
+ hourCycle: 'h23',
+ year: 'numeric',
+ month: '2-digit',
+ day: '2-digit',
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit',
+ }).formatToParts(ms).forEach(({ type, value }) => { parts[type] = value; });
+ return Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second) - ms;
+};
+
+/* Parse a date or date-time. `wall` holds the clock face, as if it were UTC */
+const parseDate = (value, params = {}) => {
+ const match = /^(\d{4})(\d{2})(\d{2})(?:T(\d{2})(\d{2})(\d{2})(Z)?)?$/.exec(value.trim());
+ if (!match) return null;
+ const [, year, month, day, hour, minute, second, utc] = match;
+ return {
+ wall: Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0),
+ zone: utc ? 'UTC' : params.TZID || null,
+ allDay: !hour || params.VALUE === 'DATE',
+ };
+};
+
+/* Resolve a wall-clock time in its own zone to a real timestamp */
+const toEpoch = ({ wall, zone, allDay }) => {
+ if (allDay || zone === 'UTC') return wall;
+ const resolved = resolveZone(zone);
+ return wall - offsetAt(wall - offsetAt(wall, resolved), resolved);
+};
+
+const parseDuration = (value) => {
+ const [, w, d, h, m, s] = /^P(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/
+ .exec(value.trim()) || [];
+ return ((+w || 0) * 604800 + (+d || 0) * 86400 + (+h || 0) * 3600
+ + (+m || 0) * 60 + (+s || 0)) * 1000;
+};
+
+const parseRule = (value) => {
+ const rule = {};
+ value.split(';').forEach((part) => {
+ const [key, val] = part.split('=');
+ if (val) rule[key.toUpperCase()] = val;
+ });
+ return rule;
+};
+
+const startOfPeriod = (ms, freq, weekStart) => {
+ const date = new Date(ms);
+ date.setUTCHours(0, 0, 0, 0);
+ if (freq === 'WEEKLY') date.setUTCDate(date.getUTCDate() - ((date.getUTCDay() - weekStart + 7) % 7));
+ if (freq === 'MONTHLY') date.setUTCDate(1);
+ if (freq === 'YEARLY') date.setUTCMonth(0, 1);
+ return date.getTime();
+};
+
+const addPeriods = (ms, freq, amount) => {
+ const date = new Date(ms);
+ if (freq === 'DAILY') date.setUTCDate(date.getUTCDate() + amount);
+ if (freq === 'WEEKLY') date.setUTCDate(date.getUTCDate() + amount * 7);
+ if (freq === 'MONTHLY') date.setUTCMonth(date.getUTCMonth() + amount);
+ if (freq === 'YEARLY') date.setUTCFullYear(date.getUTCFullYear() + amount);
+ return date.getTime();
+};
+
+/* Days in a month matching BYDAY tokens, honouring ordinals like `3TU` or `-1SU` */
+const daysMatchingByDay = (byDay, monthStart, monthLength) => {
+ const found = [];
+ byDay.forEach((token) => {
+ const nth = parseInt(token, 10) || 0;
+ const weekday = DAYS.indexOf(token.slice(-2));
+ const matches = [];
+ for (let day = 0; day < monthLength; day += 1) {
+ const ms = monthStart + day * DAY_MS;
+ 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]);
+ }
+ });
+ return found;
+};
+
+/* Candidate days within a single period, before time-of-day is applied */
+const daysInPeriod = (cursor, freq, rule, anchor) => {
+ const { byDay, byMonth, byMonthDay } = rule;
+ if (freq === 'DAILY' || freq === 'WEEKLY') {
+ let weekdays = byDay && byDay.map((token) => DAYS.indexOf(token.slice(-2)));
+ // A weekly rule with no BYDAY repeats on whichever day it started
+ if (!weekdays && freq === 'WEEKLY') weekdays = [new Date(anchor).getUTCDay()];
+ const span = freq === 'DAILY' ? 1 : 7;
+ const days = [];
+ for (let day = 0; day < span; day += 1) {
+ const ms = cursor + day * DAY_MS;
+ if (!weekdays || weekdays.includes(new Date(ms).getUTCDay())) days.push(ms);
+ }
+ return days;
+ }
+ const year = new Date(cursor).getUTCFullYear();
+ const months = freq === 'YEARLY'
+ ? (byMonth || [new Date(anchor).getUTCMonth() + 1])
+ : [new Date(cursor).getUTCMonth() + 1];
+ const days = [];
+ months.forEach((month) => {
+ const monthStart = Date.UTC(year, month - 1, 1);
+ const monthLength = new Date(Date.UTC(year, month, 0)).getUTCDate();
+ if (byDay) {
+ days.push(...daysMatchingByDay(byDay, monthStart, monthLength));
+ } else {
+ const wanted = byMonthDay || [new Date(anchor).getUTCDate()];
+ wanted.forEach((day) => {
+ const resolved = day > 0 ? day : monthLength + day + 1;
+ if (resolved >= 1 && resolved <= monthLength) {
+ days.push(monthStart + (resolved - 1) * DAY_MS);
+ }
+ });
+ }
+ });
+ return days;
+};
+
+/* Walk a recurrence rule, collecting occurrence start times as wall values */
+const expandRule = (rule, start, range) => {
+ const freq = rule.FREQ;
+ if (!FREQS.includes(freq)) return [start.wall];
+ 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,
+ };
+ const bySetPos = rule.BYSETPOS ? rule.BYSETPOS.split(',').map(Number) : null;
+ const weekStart = Math.max(DAYS.indexOf(rule.WKST), 0);
+ const timeOfDay = ((start.wall % DAY_MS) + DAY_MS) % DAY_MS;
+
+ let cursor = startOfPeriod(start.wall, freq, weekStart);
+ // Skip the periods before our window, unless COUNT means they all matter
+ if (!count && cursor < range.start) {
+ const skip = Math.floor((range.start - cursor) / (PERIOD_MS[freq] * interval)) - 1;
+ if (skip > 0) cursor = addPeriods(cursor, freq, skip * interval);
+ }
+
+ 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));
+ }
+ let candidates = days.map((ms) => ms + timeOfDay).sort((a, b) => a - b);
+ if (bySetPos) {
+ candidates = bySetPos
+ .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];
+ if (wall >= start.wall) {
+ if (until !== null && toEpoch({ ...start, wall }) > until) return found;
+ found.push(wall);
+ if (count && found.length >= count) return found;
+ }
+ }
+ cursor = addPeriods(cursor, freq, interval);
+ }
+ return found;
+};
+
+/* Read every VEVENT, skipping nested components such as VALARM */
+const collectEvents = (text) => {
+ const events = [];
+ let event = null;
+ let nested = 0;
+ unfold(text).forEach((raw) => {
+ const line = parseLine(raw);
+ if (!line) return;
+ const { name, params, value } = line;
+ if (name === 'BEGIN') {
+ if (value === 'VEVENT' && !event) event = { exdates: [], rdates: [] };
+ else if (event) nested += 1;
+ return;
+ }
+ if (name === 'END') {
+ if (nested) nested -= 1;
+ else if (value === 'VEVENT' && event) { events.push(event); event = null; }
+ return;
+ }
+ if (!event || 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);
+ else if (name === 'DURATION') event.duration = parseDuration(value);
+ else if (name === 'RRULE') event.rrule = parseRule(value);
+ else if (name === 'RECURRENCE-ID') event.recurrenceId = parseDate(value, params);
+ else if (name === 'EXDATE' || name === 'RDATE') {
+ const target = name === 'EXDATE' ? event.exdates : event.rdates;
+ value.split(',').forEach((part) => {
+ const date = parseDate(part, params);
+ if (date) target.push(date.wall);
+ });
+ }
+ });
+ return events;
+};
+
+/* Turn one occurrence into the flat shape the widget renders */
+const buildOccurrence = (event, wall) => {
+ const start = toEpoch({ ...event.start, wall });
+ let end = start;
+ if (event.end) end = toEpoch({ ...event.end, wall: wall + (event.end.wall - event.start.wall) });
+ else if (event.duration) end = start + event.duration;
+ return {
+ uid: event.uid,
+ summary: event.summary || '',
+ description: event.description || '',
+ location: event.location || '',
+ url: event.url || '',
+ allDay: event.start.allDay,
+ start,
+ end,
+ };
+};
+
+const isCancelled = (event) => event.status === 'CANCELLED';
+
+/**
+ * Parse an ICS document into occurrences starting 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
+ */
+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 overrides = new Map();
+ events.forEach((event) => {
+ if (event.recurrenceId && event.uid) {
+ overrides.set(`${event.uid}|${event.recurrenceId.wall}`, event);
+ }
+ });
+
+ const inRange = (occurrence) => occurrence.start >= range.start && occurrence.start <= range.end;
+ const occurrences = [];
+
+ events.forEach((event) => {
+ if (event.recurrenceId || !event.start || isCancelled(event)) return;
+ const starts = event.rrule ? expandRule(event.rrule, event.start, range) : [event.start.wall];
+ const all = [...new Set([...starts, ...event.rdates])];
+ all.forEach((wall) => {
+ if (event.exdates.includes(wall)) return;
+ if (overrides.has(`${event.uid}|${wall}`)) return;
+ const occurrence = buildOccurrence(event, wall);
+ if (inRange(occurrence)) occurrences.push(occurrence);
+ });
+ });
+
+ overrides.forEach((event) => {
+ if (!event.start || isCancelled(event)) return;
+ const occurrence = buildOccurrence(event, event.start.wall);
+ if (inRange(occurrence)) occurrences.push(occurrence);
+ });
+
+ return occurrences.sort((a, b) => a.start - b.start);
+};
+
+export default parseIcs;