Skip to content

Instantly share code, notes, and snippets.

@jsloat
Created September 17, 2020 22:35
Show Gist options
  • Save jsloat/3f30185daaa6efd7fdd42d26d67b500c to your computer and use it in GitHub Desktop.
Save jsloat/3f30185daaa6efd7fdd42d26d67b500c to your computer and use it in GitHub Desktop.
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: teal; icon-glyph: magic;
//
// Settings
//
const LOOK_BEHIND_HOURS = 1;
const LOOK_AHEAD_HOURS = 2;
const MAX_EVENTS_IN_WIDGET = 5;
const CALENDAR_TITLES = ["Titles of your calendars to include", "go here"];
const BG_COLOR = Color.black();
const FONT_COLOR = Color.white();
const TITLE_FONT = Font.systemFont(20);
const GET_BODY_FONT = fontSize => Font.thinMonospacedSystemFont(fontSize);
//
// Date utils
//
const HHMM = (date = new Date()) =>
[
String(date.getHours()).padStart(2, "0"),
":",
String(date.getMinutes()).padStart(2, "0"),
].join("");
const addHoursToDate = (date, hours) =>
new Date(new Date(date).setHours(date.getHours() + hours));
//
// Calendar utils
//
const getAllEventCals = async () =>
await Promise.all(CALENDAR_TITLES.map(Calendar.forEventsByTitle));
const getEligibleEvents = async () => {
const NOW = new Date();
const eventsInWindow = await CalendarEvent.between(
addHoursToDate(NOW, -1 * LOOK_BEHIND_HOURS),
addHoursToDate(NOW, LOOK_AHEAD_HOURS),
await getAllEventCals()
);
return eventsInWindow
.map(event => ({
event,
isCompleted: event.endDate < NOW,
isOngoing: event.startDate <= NOW && event.endDate >= NOW,
isFuture: event.startDate > NOW,
}))
.filter(
({ isCompleted, isOngoing, isFuture }) =>
isCompleted || isOngoing || isFuture
);
};
//
// Widget generation
//
const getWidget = async () => {
const eligibleEvents = await getEligibleEvents();
const widget = new ListWidget();
widget.backgroundColor = BG_COLOR;
const title = widget.addText("Events");
title.color = FONT_COLOR;
title.font = TITLE_FONT;
widget.addSpacer(5);
if (eligibleEvents.length) {
eligibleEvents
.slice(0, MAX_EVENTS_IN_WIDGET)
.map(({ event: { startDate, title }, isOngoing }) => {
const event = widget.addText(`${HHMM(startDate)}: ${title}`);
event.color = FONT_COLOR;
event.font = GET_BODY_FONT(isOngoing ? 18 : 16);
event.lineLimit = 1;
event.textOpacity = isOngoing ? 1 : 0.7;
});
} else {
const noEvents = widget.addText(
"None upcoming. Tap to create timestamped note."
);
noEvents.color = FONT_COLOR;
noEvents.font = GET_BODY_FONT(16);
}
widget.addSpacer(7);
const addNoteButton = widget.addText("⊕ Note");
addNoteButton.color = new Color("#61b0a5");
addNoteButton.font = Font.systemFont(14);
addNoteButton.rightAlignText();
return widget;
};
//
(async () => {
const widget = await getWidget();
if (config.runsInWidget) {
Script.setWidget(widget);
Script.complete();
} else await widget.presentMedium();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment