-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathZenDigest.js
More file actions
341 lines (283 loc) · 10.2 KB
/
Copy pathZenDigest.js
File metadata and controls
341 lines (283 loc) · 10.2 KB
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
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: deep-gray; icon-glyph: bell;
/**
* ZenDigest.js - Your Daily Briefing
*
* A warm, human-written summary of your day.
* Like a thoughtful friend catching you up.
*/
const Fs = importModule("lib/fs")
const Theme = importModule("lib/theme")
const Widget = importModule("lib/widget")
const DateTime = importModule("lib/datetime")
// ============================================
// CONFIGURATION
// ============================================
const CONFIG_PATH = Fs.fm.joinPath(Fs.baseDir, "zendigest_config.json")
const DEFAULTS = { widgetUrl: "calshow://", showWeather: true }
function loadConfig() {
return { ...DEFAULTS, ...Fs.loadJSON(CONFIG_PATH, {}) }
}
function saveConfig(config) {
Fs.saveJSON(CONFIG_PATH, config)
}
const themeConfig = Theme.loadTheme()
let userConfig = loadConfig()
// ============================================
// WEATHER
// ============================================
const WEATHER_CODES = {
0: "clear skies",
1: "mostly clear",
2: "some clouds",
3: "overcast",
45: "foggy",
48: "icy fog",
51: "light drizzle",
53: "drizzle",
55: "heavy drizzle",
61: "light rain",
63: "rain",
65: "heavy rain",
71: "light snow",
73: "snow",
75: "heavy snow",
80: "light showers",
81: "showers",
82: "heavy showers",
95: "thunderstorms",
96: "thunderstorms with hail",
99: "severe storms"
}
function timeout(ms) {
return new Promise((_, reject) =>
Timer.schedule(ms / 1000, false, () => reject(new Error("Timeout")))
)
}
function describeCondition(code) {
return WEATHER_CODES[code] || "mixed conditions"
}
async function getWeather() {
if (!userConfig.showWeather) return null
try {
const location = await Promise.race([
Location.current(),
timeout(10000)
])
const url = `https://api.open-meteo.com/v1/forecast?latitude=${location.latitude}&longitude=${location.longitude}¤t=temperature_2m,weather_code&daily=temperature_2m_max,temperature_2m_min,uv_index_max,weather_code&temperature_unit=celsius&timezone=auto`
const req = new Request(url)
req.timeoutInterval = 10
const data = await req.loadJSON()
if (!data.current) return null
return {
current: {
temp: Math.round(data.current.temperature_2m),
condition: describeCondition(data.current.weather_code)
},
today: {
high: Math.round(data.daily.temperature_2m_max[0]),
low: Math.round(data.daily.temperature_2m_min[0]),
condition: describeCondition(data.daily.weather_code[0]),
uv: Math.round(data.daily.uv_index_max[0])
},
tomorrow: data.daily.temperature_2m_max.length > 1 ? {
high: Math.round(data.daily.temperature_2m_max[1]),
low: Math.round(data.daily.temperature_2m_min[1]),
condition: describeCondition(data.daily.weather_code[1])
} : null
}
} catch (e) {
return null
}
}
// ============================================
// DATA FETCHING
// ============================================
const ZenCalendar = importModule("lib/calendar")
// ============================================
// MODE PICKER
// ============================================
// Mode is driven by today's calendar shape, not raw clock time:
// morning — now is before the earliest timed event of the day
// afternoon — at least one timed event has started but the day's
// last timed event has not yet ended
// evening — the day's last timed event has ended (or empty calendar
// and past 21:00)
// All-day events are ignored for mode selection (they don't define a
// "start" or "end" to the timed day) but still appear in the digest.
function pickMode(now, todayEvents) {
let earliestStart = Infinity
let latestEnd = -Infinity
for (const e of todayEvents) {
if (e.isAllDay) continue
const start = e.startDate.getTime()
const end = e.endDate.getTime()
if (start < earliestStart) earliestStart = start
if (end > latestEnd) latestEnd = end
}
if (!isFinite(earliestStart)) {
const hour = now.getHours()
if (hour < 12) return 'morning'
if (hour < 21) return 'afternoon'
return 'evening'
}
const t = now.getTime()
if (t < earliestStart) return 'morning'
if (t < latestEnd) return 'afternoon'
return 'evening'
}
// ============================================
// MODES
// ============================================
const CAP_ITEMS = 4
const MODES = {
morning: {
selectEvents: ({ todayEvents }) => todayEvents,
selectReminders: ({ todayReminders }) => todayReminders,
formatWeather: ({ current, today }) => {
let line = `${current.temp}° ${current.condition} · ↑${today.high} ↓${today.low}`
if (today.uv > 2) line += ` · UV ${today.uv}`
return line
},
formatReminders: (n) => `${n} ${n === 1 ? 'reminder' : 'reminders'} today.`,
emptyDigest: "Your day is wide open.",
digestPrefix: ""
},
afternoon: {
selectEvents: ({ todayEvents, now }) =>
todayEvents.filter(e => e.isAllDay || e.endDate > now),
selectReminders: ({ todayReminders, now }) =>
todayReminders.filter(r => !r.dueDate || r.dueDate > now),
formatWeather: ({ current }) => `${current.temp}° ${current.condition}`,
formatReminders: (n) => `${n} ${n === 1 ? 'reminder' : 'reminders'} pending.`,
emptyDigest: "The rest of the day is yours.",
digestPrefix: ""
},
evening: {
selectEvents: ({ tomorrowEvents }) => tomorrowEvents,
selectReminders: () => [],
formatWeather: ({ tomorrow }) =>
tomorrow ? `Tomorrow: ${tomorrow.condition} · ↑${tomorrow.high} ↓${tomorrow.low}` : null,
formatReminders: () => null,
emptyDigest: "Nothing scheduled tomorrow.",
digestPrefix: "Tomorrow: "
}
}
// ============================================
// FORMATTING
// ============================================
const timeFormatter = new DateFormatter()
timeFormatter.useShortTimeStyle()
// Locale-aware time. Strip a trailing ":00" so hour-only times read as
// "9" / "9 AM" rather than "9:00" / "9:00 AM". The lookahead ensures we
// only target the minutes slot (after the hour colon), not other digits.
function formatTime(date) {
return timeFormatter.string(date).replace(/:00(?=\D|$)/, '')
}
function formatEventDigest(events, modeConfig) {
if (events.length === 0) return modeConfig.emptyDigest
const allDay = []
const timed = []
for (const e of events) {
(e.isAllDay ? allDay : timed).push(e)
}
timed.sort((a, b) => a.startDate - b.startDate)
const parts = []
if (allDay.length > 0) {
parts.push(`All day: ${allDay.map(e => e.title).join(", ")}.`)
}
if (timed.length > 0) {
const shown = timed.slice(0, CAP_ITEMS)
const overflow = timed.length - shown.length
let clause = shown.map(e => `${e.title} at ${formatTime(e.startDate)}`).join(", ")
clause += overflow > 0 ? `, and ${overflow} more.` : "."
parts.push(clause)
}
return modeConfig.digestPrefix + parts.join(" ")
}
// ============================================
// WIDGET CREATION
// ============================================
function addLine(stack, text, font, url) {
const row = stack.addStack()
if (url) row.url = url
const el = row.addText(text)
el.textColor = Theme.getTextColor(themeConfig)
el.font = font
el.minimumScaleFactor = 0.7
row.addSpacer()
}
async function createWidget() {
const widget = Widget.createWidget({
refreshMinutes: 15,
padding: [12, 16, 12, 16],
theme: themeConfig
})
const now = new Date()
// Today's events drive mode selection, and weather is independent —
// fetch both up front. Tomorrow's events and today's reminders are
// mode-gated to avoid two-thirds-of-the-day waste.
const [todayEvents, weather] = await Promise.all([
ZenCalendar.getTodayEvents(),
getWeather()
])
const mode = pickMode(now, todayEvents)
const modeConfig = MODES[mode]
const [todayReminders, tomorrowEvents] = mode === 'evening'
? [[], await ZenCalendar.getTomorrowEvents()]
: [await ZenCalendar.getTodayReminders(), []]
const inputs = { now, todayEvents, todayReminders, tomorrowEvents }
const eventsForDigest = modeConfig.selectEvents(inputs)
const remindersForLine = modeConfig.selectReminders(inputs)
const digestLine = formatEventDigest(eventsForDigest, modeConfig)
const weatherLine = weather ? modeConfig.formatWeather(weather) : null
const remindersLine = remindersForLine.length > 0
? modeConfig.formatReminders(remindersForLine.length)
: null
const mainStack = widget.addStack()
mainStack.layoutVertically()
addLine(mainStack, DateTime.getGreeting(), Theme.getBoldFont(themeConfig.maxFontSize - 2, themeConfig), "calshow://")
mainStack.addSpacer(6)
if (weatherLine) {
addLine(mainStack, weatherLine, Theme.getMediumFont(themeConfig.minFontSize + 4, themeConfig), "weather://")
mainStack.addSpacer(4)
}
addLine(mainStack, digestLine, Theme.getRegularFont(themeConfig.minFontSize + 2, themeConfig), "calshow://")
if (remindersLine) {
mainStack.addSpacer(2)
addLine(mainStack, remindersLine, Theme.getRegularFont(themeConfig.minFontSize, themeConfig))
}
return widget
}
// ============================================
// CONFIGURATION UI
// ============================================
async function presentConfigAlert() {
const alert = new Alert()
alert.title = "Configure ZenDigest"
alert.message = "Your daily briefing settings"
alert.addTextField("Widget URL", userConfig.widgetUrl)
alert.addTextField("Show weather (true/false)", userConfig.showWeather.toString())
alert.addAction("Save")
alert.addCancelAction("Cancel")
const response = await alert.present()
if (response === -1) return null
userConfig.widgetUrl = alert.textFieldValue(0).trim() || "calshow://"
userConfig.showWeather = alert.textFieldValue(1).toLowerCase() === 'true'
saveConfig(userConfig)
return userConfig
}
// ============================================
// MAIN
// ============================================
async function run() {
if (Widget.isApp()) {
await presentConfigAlert()
} else if (Widget.isWidget()) {
const widget = await createWidget()
Script.setWidget(widget)
}
}
await run()
Script.complete()