forked from yaylinda/scriptable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCalendarEventsWidget.js
435 lines (343 loc) · 13.2 KB
/
CalendarEventsWidget.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: orange; icon-glyph: magic;
/*=============================================================================
* CONSTANTS
============================================================================*/
Date.prototype.addHours = function (numHours) {
const date = new Date(this.valueOf());
date.setHours(date.getHours() + numHours);
return date;
};
Date.prototype.addMinutes = function (numMinutes) {
const date = new Date(this.valueOf());
date.setMinutes(date.getMinutes() + numMinutes);
return date;
};
/*=============================================================================
* WIDGET CONFIGURATIONS *** CONFIGURE ME!!! ***
============================================================================*/
// Example: 12 PM
const HOUR_FORMAT = new Intl.DateTimeFormat('en-US', {
hour: 'numeric',
});
// Example: Saturday
const DAY_OF_WEEK_FORMAT = new Intl.DateTimeFormat('en-US', {
weekday: 'long',
});
// Example: 12
const DAY_OF_MONTH_FORMAT = new Intl.DateTimeFormat('en-US', {
day: 'numeric',
});
/**
* Widget confugurations. Edit these to customize the widget.
*/
const WIDGET_CONFIGURATIONS = {
// Number of hours to show in the agenda
numHours: 6,
// Calendars to show events from. Empty array means all calendars.
// Calendar names can be found in the "Calendar" App. The name must be an exact string match.
calendars: [],
// Calendar callback app
// When clicking on the widget, which calendar app should open?
// Must be one of the supported apps:
// - calshow - Default iOS Calendar
// - googlecalendar - Google Calendar
// - x-fantastical3 - Fantastical
callbackCalendarApp: 'calshow',
// Whether or not to use a background image for the widget
useBackgroundImage: true,
// If no background, default grayish background color gradient
backgroundColor: [new Color("#29323c"), new Color("#1c1c1c")],
// Font to use in Widget
font: 'Menlo',
// Bold Font to use in Widget
fontBold: 'Menlo-Bold',
// Default text size in Widget
defaultTextSize: 10,
// Larger text size in Widget
largeTextSize: 20,
// Default text color in Widget
defaultTextColor: Color.white(),
// Default spacing between elements
defaultSpacer: 10,
// Smaller spacing between elements
smallSpacer: 5,
// Height of Widget's Draw Context
widgetHeight: 400,
// Width of Widget's Draw Context
widgetWidth: 400,
// Default padding in Draw Context
padding: 10,
// Left padding of events in Draw Context
eventsLeftPadding: 80,
// Corner radius of events in Draw Context
eventsRounding: 10,
// Text color of event titles
eventsTextColor: Color.black(),
// Thickness of hour/now line
lineHeight: 4,
// Color of hour/half-hour line
lineColor: new Color('#ffffff', 0.3),
};
/*=============================================================================
* WIDGET SET UP / PRESENTATION
============================================================================*/
const widget = new ListWidget();
await setBackground(widget, WIDGET_CONFIGURATIONS);
const events = await getEvents(WIDGET_CONFIGURATIONS);
console.log(JSON.stringify(events));
drawWidget(widget, events, WIDGET_CONFIGURATIONS);
console.log(`args.widgetParameter: ${JSON.stringify(args.widgetParameter)}`);
if (config.runsInWidget) {
Script.setWidget(widget);
Script.complete();
} else if (args.widgetParameter === 'callback') {
const timestamp = (new Date().getTime() - new Date('2001/01/01').getTime()) / 1000;
const callback = new CallbackURL(`${WIDGET_CONFIGURATIONS.callbackCalendarApp}:${timestamp}`);
callback.open();
Script.complete();
} else {
Script.setWidget(widget);
widget.presentMedium();
Script.complete();
}
/*=============================================================================
* DRAW WIDGET
============================================================================*/
function drawWidget(widget, events, WIDGET_CONFIGURATIONS) {
const mainStack = widget.addStack();
mainStack.layoutHorizontally();
mainStack.spacing = 30;
// Left stack contains date, and all day events
const leftStack = mainStack.addStack();
leftStack.layoutVertically();
// Right stack contains calendar events
const rightStack = mainStack.addStack();
rightStack.layoutVertically();
drawLeftStack(leftStack, events, WIDGET_CONFIGURATIONS);
drawRightStack(rightStack, events, WIDGET_CONFIGURATIONS);
}
function drawLeftStack(stack, events, {
font,
fontBold,
defaultTextSize,
largeTextSize,
defaultTextColor,
defaultSpacer,
smallSpacer,
}) {
const currentDate = new Date();
const dateStack = stack.addStack();
dateStack.layoutHorizontally();
const dowText = dateStack.addText(DAY_OF_WEEK_FORMAT.format(currentDate).toUpperCase());
dowText.textColor = defaultTextColor;
dowText.font = new Font(font, largeTextSize);
dateStack.addSpacer(smallSpacer);
const domText = dateStack.addText(DAY_OF_MONTH_FORMAT.format(currentDate));
domText.textColor = defaultTextColor;
domText.font = new Font(fontBold, largeTextSize);
stack.addSpacer(defaultSpacer);
const allDayEvents = events['all-day'];
if (allDayEvents) {
const allDayEventsText = stack.addText('All-day events');
allDayEventsText.textColor = defaultTextColor;
allDayEventsText.font = new Font(fontBold, defaultTextSize);
stack.addSpacer(smallSpacer);
for (let event of allDayEvents) {
const eventStack = stack.addStack();
eventStack.layoutHorizontally();
const calendarIconText = eventStack.addText("\u2759");
calendarIconText.textColor = new Color(event.color);
calendarIconText.font = new Font(font, defaultTextSize);
eventStack.addSpacer(smallSpacer);
const calendarEventText = eventStack.addText(event.title);
calendarEventText.textColor = defaultTextColor;
calendarEventText.font = new Font(font, defaultTextSize);
stack.addSpacer(smallSpacer);
}
} else {
const noAllDayEventsText = stack.addText('No all-day events');
noAllDayEventsText.textColor = defaultTextColor;
noAllDayEventsText.font = new Font(fontBold, defaultTextSize);
}
}
function drawRightStack(stack, events, {
defaultTextColor,
font,
largeTextSize,
eventsTextColor,
numHours,
widgetHeight,
widgetWidth,
padding,
eventsLeftPadding,
eventsRounding,
lineHeight,
lineColor,
}) {
const halfHourEventHeight = widgetHeight / (numHours * 2);
const draw = new DrawContext();
draw.opaque = false;
draw.respectScreenScale = true;
draw.size = new Size(widgetWidth, widgetHeight);
const currentDate = new Date();
// Loop through all the hours and draw the lines
for (let i = 0; i < numHours; i++) {
const currentHourDate = currentDate.addHours(i);
const currentHourText = HOUR_FORMAT.format(currentHourDate);
const topPointY = halfHourEventHeight * 2 * i;
const midPointY = topPointY + halfHourEventHeight;
// Draw line at the hour
const topPath = new Path();
topPath.addRect(new Rect(eventsLeftPadding - padding, topPointY, widgetWidth, lineHeight));
draw.addPath(topPath);
draw.setFillColor(lineColor);
draw.fillPath();
// Draw line at the half hour
const middlePath = new Path();
middlePath.addRect(new Rect(eventsLeftPadding - padding, midPointY, widgetWidth, lineHeight / 2));
draw.addPath(middlePath);
draw.setFillColor(lineColor);
draw.fillPath();
// Draw hour text
draw.setTextColor(defaultTextColor);
draw.setFont(new Font(font, largeTextSize));
draw.drawText(`${currentHourText}`, new Point(0, topPointY));
}
// Loop through all the hours and draw the events (on top of the lines)
for (let i = 0; i < numHours; i++) {
const currentHourDate = currentDate.addHours(i);
const currentHourText = HOUR_FORMAT.format(currentHourDate);
const topPointY = halfHourEventHeight * 2 * i;
const midPointY = topPointY + halfHourEventHeight;
// Draw events for this hour (if any)
const hourEvents = events[currentHourText];
if (hourEvents) {
for (let j = 0; j < hourEvents.length; j++) {
// TODO - determine width of events based on num events in hour
const { startMinute, title, color, duration } = hourEvents[j];
// Determine top Y of event
const eventRectY = topPointY + Math.floor((startMinute * halfHourEventHeight) / 30);
// Determine height of events
const eventHeight = Math.floor((duration * halfHourEventHeight) / 30);
const eventRect = new Rect(
eventsLeftPadding + padding,
eventRectY,
widgetWidth - (eventsLeftPadding + padding * 3),
eventHeight
);
const eventPath = new Path();
eventPath.addRoundedRect(eventRect, eventsRounding, eventsRounding);
draw.addPath(eventPath);
draw.setFillColor(new Color(color));
draw.fillPath();
// Draw event name text
draw.setTextColor(eventsTextColor);
draw.setFont(new Font(font, largeTextSize));
draw.drawText(`${title}`, new Point(eventsLeftPadding + padding + padding, eventRectY + padding / 2));
}
}
}
// Draw line at the current time
const currentMinute = new Date().getMinutes();
let currentMinuteY = (currentMinute * halfHourEventHeight) / 30;
const currentMinutePath = new Path();
currentMinutePath.addRect(new Rect(eventsLeftPadding, currentMinuteY, widgetWidth, lineHeight));
draw.addPath(currentMinutePath);
draw.setFillColor(Color.red());
draw.fillPath();
// Put the content on the widget stack
const drawn = draw.getImage();
stack.addImage(drawn);
}
/*=============================================================================
* FUNCTIONS
============================================================================*/
async function setBackground(widget, { useBackgroundImage, backgroundColor }) {
if (useBackgroundImage) {
// Determine if our image exists and when it was saved.
const files = FileManager.local();
const path = files.joinPath(files.documentsDirectory(), 'calendar-events-widget-background');
const exists = files.fileExists(path);
// If it exists and we're running in the widget, use photo from cache
// Or we're invoking the script to run FROM the widget with a widgetParameter
if (exists && config.runsInWidget || args.widgetParameter === 'callback') {
widget.backgroundImage = files.readImage(path);
// If it's missing when running in the widget, fallback to backgroundColor
} else if (!exists && config.runsInWidget) {
const bgColor = new LinearGradient();
bgColor.colors = backgroundColor;
bgColor.locations = [0.0, 1.0];
widget.backgroundGradient = bgColor;
// But if we're running in app, prompt the user for the image.
} else if (config.runsInApp) {
const img = await Photos.fromLibrary();
widget.backgroundImage = img;
files.writeImage(path, img);
}
} else {
const bgColor = new LinearGradient();
bgColor.colors = backgroundColor;
bgColor.locations = [0.0, 1.0];
widget.backgroundGradient = bgColor;
}
}
async function getEvents({ numHours, calendars }) {
const todayEvents = await CalendarEvent.today([]);
const tomorrowEvents = await CalendarEvent.tomorrow([]);
const combinedEvents = todayEvents.concat(tomorrowEvents);
let now = new Date();
now = now.addMinutes(now.getMinutes() * -1);
const inNumHours = now.addHours(numHours);
const eventsByHour = {};
combinedEvents.forEach((event) => {
const start = new Date(event.startDate);
const end = new Date(event.endDate);
// Filter for events that:
// - start between now and numHours from now
// - are in the specified array of calendars (if any)
if (start <= inNumHours && end > now && (calendars.length === 0 || calendars.includes(event.calendar.title))) {
if (event.isAllDay) { // All-day events
if (!eventsByHour['all-day']) {
eventsByHour['all-day'] = [];
}
eventsByHour['all-day'].push({
title: event.title,
color: `#${event.calendar.color.hex}`,
});
} else if (start < now && end > now) { // Events that started before the current hour, but have not yet ended
const hourKey = HOUR_FORMAT.format(now);
if (!eventsByHour[hourKey]) {
eventsByHour[hourKey] = [];
}
let eventDuration = Math.floor(((end - start) / 1000) / 60) - (Math.floor(((now - start) / 1000) / 60));
const eventObj = {
start,
end,
startMinute: start.getMinutes(),
title: event.title,
color: `#${event.calendar.color.hex}`,
duration: eventDuration,
};
eventsByHour[hourKey].push(eventObj);
} else { // Events that start between now and inNumHours
const hourKey = HOUR_FORMAT.format(start);
if (!eventsByHour[hourKey]) {
eventsByHour[hourKey] = [];
}
let eventDuration = Math.floor(((end - start) / 1000) / 60);
const eventObj = {
start,
end,
startMinute: start.getMinutes(),
title: event.title,
color: `#${event.calendar.color.hex}`,
duration: eventDuration,
};
eventsByHour[hourKey].push(eventObj);
}
}
});
return eventsByHour;
}