-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathNotionCountdowns.js
More file actions
1987 lines (1742 loc) · 80 KB
/
Copy pathNotionCountdowns.js
File metadata and controls
1987 lines (1742 loc) · 80 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
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: teal; icon-glyph: clock;
// === WIDGET PARAM QUICK GUIDE ===
// Comma-separated, case-insensitive. Examples below.
//
// Modes:
// - since | mode=since | mode since
// - countdown | mode=countdown
//
// Lock Screen display override (for accessory widgets):
// - .topbar | .circular | .rect | .rectangular
//
// Since-unit override (for since mode):
// - .days | .weeks | .months | .years | .hours | .minutes
// (also: wk/wks, mo, yr/yrs, hr/hrs, min/mins)
//
// Event selection:
// - number = 1-based index (e.g., 3 selects 3rd event)
// - text = name/alias match (case-insensitive)
//
// Other:
// - age = age display (small widget)
// - pg1/pg2/... = page for grid view
// - col = grid view (medium/large)
//
// Examples:
// - since,work anniversary
// - mode=since.circular.gym
// - since.weeks.habit
// - countdown,3
// - col,pg2
// - mode=since.rectangular.birthday
//
// Lock Screen examples (accessory widgets):
// - since.{wks/yrs/hrs/min/mo}.{circular/topbar/rect}.event_name
// - topbar,5 (inline/top bar, 5th event)
// - since.rect.streak (rectangular lock screen since + name match)
// === CONFIG ===
// === FILEMANAGER INIT (needed globally) ===
const fm = FileManager.iCloud();
// === NOTION CONFIG ===
const NOTION_TOKEN = "YOUR_NOTION_INTEGRATION_TOKEN"; // <-- Replace with your Notion integration token
const NOTION_DATABASE_ID = "YOUR_NOTION_DATABASE_ID"; // <-- Replace with your Notion database ID
const NOTION_PROPERTY_MAP = {
name: "Title",
date: "Event Date",
eventType: "Event Type",
icon: "Widget Emoji",
color: "Widget Clr",
widgetTextColor: "Widget TxtClr",
aliases: "Aliases"
};
// Helper: Get data_source_id from database_id
async function getDataSourceId(databaseId, notionToken) {
const url = `https://api.notion.com/v1/databases/${databaseId}`;
const req = new Request(url);
req.method = "GET";
req.headers = {
"Authorization": `Bearer ${notionToken}`,
"Notion-Version": "2025-09-03"
};
const res = await req.loadJSON();
return res.data_sources && res.data_sources.length ? res.data_sources[0].id : null;
}
// Fetch events from Notion data source (API v2025-09-03)
async function fetchNotionEvents() {
const dataSourceId = await getDataSourceId(NOTION_DATABASE_ID, NOTION_TOKEN);
if (!dataSourceId) {
console.error("No data_source_id found for database!");
return [];
}
const url = `https://api.notion.com/v1/data_sources/${dataSourceId}/query`;
const req = new Request(url);
req.method = "POST";
req.headers = {
"Authorization": `Bearer ${NOTION_TOKEN}`,
"Notion-Version": "2025-09-03",
"Content-Type": "application/json"
};
req.body = JSON.stringify({});
const res = await req.loadJSON();
if (!res.results) return [];
return res.results.map(page => mapNotionPageToEvent(page));
}
// Map a Notion page to the event row format
function mapNotionPageToEvent(page) {
const props = page.properties || {};
function getProp(key) {
const notionKey = NOTION_PROPERTY_MAP[key];
return props[notionKey];
}
// Title: always use the Notion page's title property (type: title, which is the page name)
let name = "";
// Find the first property of type 'title' in the page's properties
let foundTitle = null;
for (const key in page.properties) {
const prop = page.properties[key];
if (prop && prop.type === "title" && Array.isArray(prop.title) && prop.title.length > 0) {
foundTitle = prop.title.map(t => t.plain_text).join("");
break;
}
}
if (foundTitle && foundTitle.trim().length > 0) {
name = foundTitle;
} else {
// fallback to mapped property if present
const titleProp = getProp("name");
if (titleProp && titleProp.title && titleProp.title.length > 0) {
name = titleProp.title.map(t => t.plain_text).join("");
} else if (titleProp && titleProp.rich_text && titleProp.rich_text.length > 0) {
name = titleProp.rich_text.map(t => t.plain_text).join("");
}
}
// Fallback: use Notion page id if name is still empty
if (!name || name.trim().length === 0) {
name = page.id ? `Untitled (${page.id.slice(-6)})` : "Untitled";
}
// Date
let date = "";
const dateProp = getProp("date");
if (dateProp && dateProp.date && dateProp.date.start) {
date = dateProp.date.start;
}
// Icon
let icon = "";
const iconProp = getProp("icon");
if (iconProp && iconProp.rich_text && iconProp.rich_text.length > 0) {
icon = iconProp.rich_text.map(t => t.plain_text).join("");
} else if (iconProp && iconProp.select && iconProp.select.name) {
icon = iconProp.select.name;
}
// Color (support select, formula, or rich_text)
let color = "";
const colorProp = getProp("color");
if (colorProp && colorProp.rich_text && colorProp.rich_text.length > 0) {
color = colorProp.rich_text.map(t => t.plain_text).join("");
} else if (colorProp && colorProp.select && colorProp.select.name) {
color = colorProp.select.name;
} else if (colorProp && colorProp.formula && colorProp.formula.string) {
color = colorProp.formula.string;
}
// Widget Text Color (support select, formula, or rich_text)
let widgetTextColor = "";
const widgetTextColorProp = getProp("widgetTextColor");
if (widgetTextColorProp && widgetTextColorProp.rich_text && widgetTextColorProp.rich_text.length > 0) {
widgetTextColor = widgetTextColorProp.rich_text.map(t => t.plain_text).join("");
} else if (widgetTextColorProp && widgetTextColorProp.select && widgetTextColorProp.select.name) {
widgetTextColor = widgetTextColorProp.select.name;
} else if (widgetTextColorProp && widgetTextColorProp.formula && widgetTextColorProp.formula.string) {
widgetTextColor = widgetTextColorProp.formula.string;
}
// Aliases
let aliases = "";
const aliasesProp = getProp("aliases");
if (aliasesProp && aliasesProp.rich_text && aliasesProp.rich_text.length > 0) {
aliases = aliasesProp.rich_text.map(t => t.plain_text).join("");
}
// Event Type
let eventType = "";
const eventTypeProp = getProp("eventType");
if (eventTypeProp && eventTypeProp.select && eventTypeProp.select.name) {
eventType = eventTypeProp.select.name;
}
// Mode (derived from eventType or explicit property)
let mode = null;
if (eventType && eventType.toLowerCase().includes("since")) mode = "since";
if (eventType && eventType.toLowerCase().includes("countdown")) mode = "countdown";
// Compose normalized event row
return {
name,
date,
icon,
color,
widgetTextColor,
aliases,
eventType,
mode
};
}
const colorPalette = ["#CB2443", "#8e44ad", "#2980b9", "#F79F39", "#CEA834", "#7b9a50"];
const HARDCODED_FORCE_REFRESH = true;
// Notification/testing settings
// Hour (0-23) to schedule real notifications (week/day before). Default 9 AM local.
const HARDCODED_NOTIFY_HOUR = 9;
// TEST mode: set to true only for manual testing. Keep false for normal operation.
const HARDCODED_TEST_MODE = false;
// Prefer pulling data from the Apps Script web app (matches the URL you verified).
const USE_APPS_SCRIPT_WEBAPP = true;
// Set false to ignore args.widgetParameter and always use the hard-coded sheet.
const ALLOW_WIDGET_PARAM_OVERRIDES = false;
function renderTemplate(template, row) {
if (!template) return '';
const mapping = {
icon: row.icon || '',
name: row.name || '',
date: row.date || '',
formattedDate: (row.date ? formatDate(row.date) : ''),
// suffix uses the same mapping as titles in the widget (falls back to empty)
suffix: (typeof titleSuffixes !== 'undefined' && titleSuffixes[row.icon]) ? titleSuffixes[row.icon] : ''
};
return String(template).replace(/\{(\w+)\}/g, (_, key) => mapping.hasOwnProperty(key) ? mapping[key] : '');
}
function buildUrlWithParams(base, params = {}) {
const query = Object.entries(params)
.filter(([, value]) => value !== undefined && value !== null && value !== '')
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&');
if (!query) return base;
return base + (base.includes('?') ? '&' : '?') + query;
}
function normalizeModeValue(raw) {
if (!raw && raw !== 0) return null;
const v = String(raw).trim().toLowerCase();
if (!v) return null;
if (v.includes("since") || v.includes("ended") || v.includes("past")) return "since";
if (v.includes("count") || v.includes("upcoming")) return "countdown";
return null;
}
function normalizeActiveValue(raw) {
if (raw === undefined || raw === null) return null;
if (typeof raw === "boolean") return raw;
const v = String(raw).trim().toLowerCase();
if (v === "true" || v === "yes" || v === "1" || v === "active") return true;
if (v === "false" || v === "no" || v === "0" || v === "inactive") return false;
return null;
}
function normalizeEventRow(row) {
if (!row || typeof row !== 'object') return null;
const pick = (...keys) => {
for (const key of keys) {
if (row[key] !== undefined && row[key] !== null && String(row[key]).trim() !== '') {
return row[key];
}
}
return null;
};
const name = pick('name', 'Name', 'Event Name');
const date = pick('date', 'Date', 'Event Date');
if (!name || !date) return null;
const icon = pick('icon', 'Icon', 'Widget Emoji', 'Emoji') || '📅';
const colorRaw = pick('color', 'Color', 'Widget Clr', 'Widget Color');
const eventType = pick('event type', 'Event Type', 'Type');
const modeRaw = pick('mode', 'Mode', 'Countdown Mode', 'Event Mode', 'Since Mode');
const activeRaw = pick('active?', 'Active?', 'Active', 'active');
const aliasesRaw = pick('aliases', 'Aliases', 'Alias');
const textColorRaw = pick('widget txtclr', 'Widget TxtClr', 'Widget Text Color', 'Text Color', 'TxtClr');
const normalizedMode = normalizeModeValue(modeRaw || eventType);
const normalizedActive = normalizeActiveValue(activeRaw);
const color = colorRaw ? String(colorRaw).trim() : null;
const normalized = {
name: String(name).trim(),
date: String(date).trim(),
icon: String(icon).trim() || '📅',
color: color && color.length ? color : null
};
if (eventType) normalized.eventType = String(eventType).trim();
if (normalizedMode) normalized.mode = normalizedMode;
if (normalizedActive !== null) normalized.active = normalizedActive;
if (aliasesRaw) normalized.aliases = String(aliasesRaw).trim();
if (textColorRaw) normalized.widgetTextColor = String(textColorRaw).trim();
const passthroughKeys = ['notes', 'Notes', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
for (const key of passthroughKeys) {
if (row[key] !== undefined) {
const targetKey = key.length === 1 ? key : key.toLowerCase();
normalized[targetKey] = row[key];
}
}
return normalized;
}
// === Notion-Only Data Source ===
const events = await fetchNotionEvents();
// Debug: log event data to help diagnose missing title
if (config && config.runsInApp) {
console.log("Loaded events:", JSON.stringify(events, null, 2));
}
// const events = await req.loadJSON();
const titleSuffixes = {
"🎂": "'s Birthday",
"🥂": "'s Anniversary",
"🗓": "", // relationships
"🔱": "",
"✈️": "",
"default": ""
};
const ageSuffixMap = {
"🎂": ["turning ", ""],
"🥂": ["", " yrs together"],
"🔱": ["", " yrs observed"],
"🗓": ["", " yrs together"],
"default": [" ", " "]
};
const todaySuffixes = {
"🎂": ["You are ", " 🥳"],
"🥂": ["", " together 🥳"],
"🗓": ["", " together 🥳"],
"🔱": ["", " observed"],
"default": ["", ""]
};
// === Load local files ===
// const fm = FileManager.iCloud();
// === Google Drive assets manifest (OPTIONAL) ===
// Provide direct-download URLs for files you upload to Google Drive. If you leave
// these empty, the script will try to use any locally-cached files in iCloud.
// Replace the example URLs with your own direct-download links (see instructions below).
const DRIVE_ASSETS = {
"Roboto-Regular.ttf": "https://drive.google.com/uc?export=download&id=1yTBh2E9U1zaT1I3hARU8Fsje8NyvVfZT",
// Updated public links provided by user:
"repeat_icon.png": "https://drive.google.com/uc?export=download&id=13CmUtpS7uTsswn9DsVQ7v_zR42b8yg3C",
"since_icon.png": "https://drive.google.com/uc?export=download&id=1RsHDs-bz7OFKzJE4FdrtGMScArxeaTE8",
"since_icon_home.png": "https://drive.google.com/uc?export=download&id=178DbyFt0LyX4x1Abf2bn3EbrhO6INjue",
};
// Helper: ensure a file exists locally by downloading from Drive manifest if provided.
async function ensureLocalFile(subdir, fileName) {
const dir = fm.joinPath(fm.documentsDirectory(), subdir);
if (!fm.fileExists(dir)) fm.createDirectory(dir);
const path = fm.joinPath(dir, fileName);
if (fm.fileExists(path)) {
return path;
}
const driveUrl = DRIVE_ASSETS[fileName];
if (!driveUrl) {
// No remote URL provided and file not in iCloud — caller should handle fallback.
return null;
}
try {
const req = new Request(driveUrl);
// Try to load raw data and write to file (works for images/fonts/binaries)
const data = await req.load();
fm.write(path, data);
return path;
} catch (e) {
// Download failed — return null so caller can fallback.
return null;
}
}
// === Load Custom Roboto Font (from Drive or iCloud fallback) ===
const fontFileName = "Roboto-Regular.ttf";
const localFontPath = await ensureLocalFile(".fonts", fontFileName) || fm.joinPath(fm.joinPath(fm.documentsDirectory(), ".fonts"), fontFileName);
// If we still don't have the font file locally, don't block — fallback to system fonts.
let roboto = null;
if (fm.fileExists(localFontPath)) {
try {
await fm.downloadFileFromiCloud(localFontPath);
} catch (e) {
// ignore download errors
}
roboto = (size) => new Font(localFontPath, size);
} else {
// Fallback factory using system font
roboto = (size) => Font.systemFont(size);
}
// === Load Repeat Icon (from Drive or iCloud fallback) ===
const repeatFileName = "repeat_icon.png";
const localRepeatPath = await ensureLocalFile(".source", repeatFileName) || fm.joinPath(fm.joinPath(fm.documentsDirectory(), ".source"), repeatFileName);
let repeatIcon = null;
if (fm.fileExists(localRepeatPath)) {
try {
await fm.downloadFileFromiCloud(localRepeatPath);
} catch (e) {
// ignore
}
try {
repeatIcon = fm.readImage(localRepeatPath);
} catch (e) {
repeatIcon = null;
}
} else {
repeatIcon = null; // gracefully handle missing icon later
}
// === Load Lock Screen Repeat Icon (from iCloud .source) ===
const repeatLockscreenFileName = "repeat_lockscreen.png";
const localRepeatLockscreenPath = await ensureLocalFile(".source", repeatLockscreenFileName) || fm.joinPath(fm.joinPath(fm.documentsDirectory(), ".source"), repeatLockscreenFileName);
let repeatLockscreenIcon = null;
// repeatLockscreenIcon = fm.readImage(localRepeatLockscreenPath);
if (fm.fileExists(localRepeatLockscreenPath)) {
try {
await fm.downloadFileFromiCloud(localRepeatLockscreenPath);
} catch (e) {
// ignore
}
try {
repeatLockscreenIcon = fm.readImage(localRepeatLockscreenPath);
} catch (e) {
repeatLockscreenIcon = null;
}
}
// === Load Since Icon (from Drive or iCloud fallback) ===
const sinceFileName = "since_icon.png";
// const sinceFileName = "since_icon_48.png";
const localSincePath = await ensureLocalFile(".source", sinceFileName) || fm.joinPath(fm.joinPath(fm.documentsDirectory(), ".source"), sinceFileName);
let sinceIcon = null;
sinceIcon = fm.readImage(localSincePath);
// if (fm.fileExists(localSincePath)) {
// try {
// await fm.downloadFileFromiCloud(localSincePath);
// } catch (e) {
// // ignore
// }
// try {
// sinceIcon = fm.readImage(localSincePath);
// } catch (e) {
// sinceIcon = null;
// }
// } else {
// sinceIcon = null; // gracefully handle missing icon later
// }
// if (!sinceIcon && DRIVE_ASSETS[sinceFileName]) {
// try {
// const req = new Request(DRIVE_ASSETS[sinceFileName]);
// sinceIcon = await req.loadImage();
// } catch (e) {
// // ignore
// }
// }
// === Load Home Screen Since Icon (from Drive or iCloud fallback) ===
const sinceHomeFileName = "since_icon_home.png";
const localSinceHomePath = await ensureLocalFile(".source", sinceHomeFileName) || fm.joinPath(fm.joinPath(fm.documentsDirectory(), ".source"), sinceHomeFileName);
let sinceHomeIcon = null;
if (fm.fileExists(localSinceHomePath)) {
try {
await fm.downloadFileFromiCloud(localSinceHomePath);
} catch (e) {
// ignore
}
try {
sinceHomeIcon = fm.readImage(localSinceHomePath);
} catch (e) {
sinceHomeIcon = null;
}
}
function getSinceHomeIconImage() {
if (sinceHomeIcon) return sinceHomeIcon;
if (sinceIcon) return sinceIcon;
try {
return SFSymbol.named("calendar").image;
} catch (e) {
return null;
}
}
function normalizeHexColorLocal(value) {
if (!value && value !== 0) return null;
let s = String(value).trim();
if (!s) return null;
if (!s.startsWith("#") && /^[0-9a-fA-F]{6}$/.test(s)) s = `#${s}`;
return s;
}
function lightenHexColor(hex, amount) {
const normalized = normalizeHexColorLocal(hex);
if (!normalized) return null;
const r = parseInt(normalized.slice(1, 3), 16);
const g = parseInt(normalized.slice(3, 5), 16);
const b = parseInt(normalized.slice(5, 7), 16);
const nr = Math.round(r + (255 - r) * amount);
const ng = Math.round(g + (255 - g) * amount);
const nb = Math.round(b + (255 - b) * amount);
return `#${nr.toString(16).padStart(2, "0")}${ng.toString(16).padStart(2, "0")}${nb.toString(16).padStart(2, "0")}`;
}
function buildCircularBgImage(valueText, unitText, bgColor, textColor, size) {
const width = size;
const height = size;
const context = new DrawContext();
context.size = new Size(width, height);
context.respectScreenScale = true;
context.opaque = false;
const rect = new Rect(0, 0, width, height);
context.setFillColor(bgColor);
context.fillEllipse(rect);
context.setTextColor(textColor);
context.setTextAlignedCenter();
const measureTextWidth = (text) => {
if (typeof context.measureText === "function") return context.measureText(text).width;
if (typeof context.getTextSize === "function") return context.getTextSize(text).width;
return text.length * 0.55;
};
const fitFontSize = (text, maxWidth, maxFont, minFont, fontBuilder) => {
let size = maxFont;
const safeText = String(text);
while (size > minFont) {
context.setFont(fontBuilder(size));
const measured = measureTextWidth(safeText);
if (measured <= maxWidth) break;
size -= 1;
}
return size;
};
const rawValueLines = String(valueText).split("\n");
const valueLines = rawValueLines.length > 2
? [rawValueLines[0], rawValueLines.slice(1).join(" ")]
: rawValueLines;
const hasUnit = String(unitText).trim().length > 0;
const maxTextWidth = Math.round(width * 0.9);
const baseValueFont = Math.max(12, Math.round(size * (valueLines.length > 1 ? 0.28 : 0.32)));
const baseUnitFont = Math.max(8, Math.round(size * 0.16));
const lineGap = Math.max(2, Math.round(size * 0.03));
const valueFonts = valueLines.map((line, index) => {
const target = Math.round(baseValueFont * (index === 0 ? 1 : 0.75));
return fitFontSize(line, maxTextWidth, target, 9, Font.semiboldSystemFont);
});
const unitFont = hasUnit ? fitFontSize(unitText, maxTextWidth, baseUnitFont, 7, Font.systemFont) : 0;
const valueBlockHeight = valueFonts.reduce((sum, font) => sum + font, 0) + Math.max(0, valueLines.length - 1) * lineGap;
const unitBlockHeight = hasUnit ? unitFont : 0;
const totalTextHeight = hasUnit ? valueBlockHeight + lineGap + unitBlockHeight : valueBlockHeight;
let currentTop = Math.round((size - totalTextHeight) / 2);
valueLines.forEach((line, index) => {
const fontSize = valueFonts[index];
context.setFont(Font.semiboldSystemFont(fontSize));
context.drawTextInRect(String(line), new Rect(0, currentTop, width, Math.round(fontSize * 1.2)));
currentTop += fontSize + lineGap;
});
if (hasUnit) {
context.setFont(Font.systemFont(unitFont));
context.drawTextInRect(String(unitText), new Rect(0, currentTop, width, Math.round(unitFont * 1.2)));
}
return context.getImage();
}
function buildRectBgImage(titleText, valueText, unitText, bgColor, textColor, size) {
const width = size.width;
const height = size.height;
const context = new DrawContext();
context.size = new Size(width, height);
context.respectScreenScale = true;
context.opaque = false;
const rect = new Rect(0, 0, width, height);
context.setFillColor(bgColor);
const rounded = new Path();
rounded.addRoundedRect(rect, 12, 12);
context.addPath(rounded);
context.fillPath();
context.setTextColor(textColor);
context.setTextAlignedLeft();
const measureTextWidth = (text) => {
if (typeof context.measureText === "function") return context.measureText(text).width;
if (typeof context.getTextSize === "function") return context.getTextSize(text).width;
return String(text).length * 0.55;
};
const fitFontSize = (text, maxWidth, maxFont, minFont, fontBuilder) => {
let size = maxFont;
const safeText = String(text);
while (size > minFont) {
context.setFont(fontBuilder(size));
const measured = measureTextWidth(safeText);
if (measured <= maxWidth) break;
size -= 1;
}
return size;
};
const horizontalPadding = Math.max(8, Math.round(width * 0.08));
const maxTextWidth = Math.max(20, width - horizontalPadding * 2);
const baseTitleFont = Math.max(11, Math.round(height * 0.26));
const baseValueFont = Math.max(10, Math.round(height * 0.22));
const titleFont = fitFontSize(titleText, maxTextWidth, baseTitleFont, 9, Font.semiboldSystemFont);
const valueFont = fitFontSize(`${valueText} ${unitText}`.trim(), maxTextWidth, baseValueFont, 8, Font.systemFont);
const lineGap = Math.max(2, Math.round(height * 0.05));
const totalTextHeight = titleFont + valueFont + lineGap;
const titleTop = Math.round((height - totalTextHeight) / 2);
const valueTop = titleTop + titleFont + lineGap;
context.setFont(Font.semiboldSystemFont(titleFont));
context.drawTextInRect(String(titleText), new Rect(horizontalPadding, titleTop, width - horizontalPadding * 2, Math.round(height * 0.34)));
context.setFont(Font.systemFont(valueFont));
context.drawTextInRect(`${valueText} ${unitText}`, new Rect(horizontalPadding, valueTop, width - horizontalPadding * 2, Math.round(height * 0.3)));
return context.getImage();
}
// === Load Circular Background Image (from iCloud .source) ===
const circularBgFileName = "small-seasons-background.png";
const localCircularBgPath = await ensureLocalFile(".source", circularBgFileName) || fm.joinPath(fm.joinPath(fm.documentsDirectory(), ".source"), circularBgFileName);
let circularBgImage = null;
if (fm.fileExists(localCircularBgPath)) {
try {
await fm.downloadFileFromiCloud(localCircularBgPath);
} catch (e) {
// ignore
}
try {
circularBgImage = fm.readImage(localCircularBgPath);
} catch (e) {
circularBgImage = null;
}
}
function getCircularBgImage() {
return circularBgImage;
}
// function getSinceIconImage() {
// if (sinceIcon) return sinceIcon;
// try {
// return SFSymbol.named("calendar").image;
// } catch (e) {
// return null;
// }
// }
// === Parameter Handling for Small Widget ===
const param = args.widgetParameter ? args.widgetParameter.trim().toLowerCase() : null;
// Find the most recent upcoming event (soonest event)
let selectedEvent = events.reduce((closest, event) => {
const daysToEvent = daysUntil(event.date);
const daysToClosest = daysUntil(closest.date);
return daysToEvent < daysToClosest ? event : closest;
}, events[0]);
let showAgeMode = false; // default off
let page = 1; // default page
let sinceMode = false;
let selectionSpecified = false;
let sinceUnitOverride = null;
let lockDisplayType = null;
let modeExplicit = false;
function isSinceEvent(event) {
// Ensure both 'since' and 'ended' events are included in since mode
if (!event) return false;
// Check both possible fields for robustness
const type = event.eventType || event.type || "";
return event.mode === "since" || type.toLowerCase() === "ended";
}
function daysSince(dateStr) {
const today = new Date();
today.setHours(0, 0, 0, 0);
const eventDate = parseLocalDate(dateStr);
if (!eventDate || isNaN(eventDate.getTime())) return -99999;
eventDate.setHours(0, 0, 0, 0);
return Math.round((today - eventDate) / (1000 * 60 * 60 * 24));
}
function formatDurationFromDays(days) {
const absDays = Math.abs(days);
if (absDays >= 1000) {
let months = absDays / 30.44;
let unit = "month";
let value = months;
if (months >= 12) {
value = months / 12;
unit = "year";
}
return { valueText: value.toFixed(2), unit };
}
return { valueText: String(absDays), unit: "day" };
}
function buildDurationLabel(days, mode) {
const { valueText, unit } = formatDurationFromDays(days);
const isSingular = Number(valueText) === 1;
const unitLabel = isSingular ? unit : `${unit}s`;
const suffix = mode === "since" ? "since" : "left";
return { valueText, unitLabel, suffix, isSingular };
}
function buildSinceLabel(days, unitOverride) {
const absDays = Math.abs(days);
let unit = unitOverride;
let value = absDays;
if (unit) {
if (unit === "minutes" || unit === "mins" || unit === "min") value = absDays * 24 * 60;
else if (unit === "hours" || unit === "hrs" || unit === "hr") value = absDays * 24;
else if (unit === "weeks" || unit === "wk" || unit === "wks") value = absDays / 7;
else if (unit === "months" || unit === "mo" || unit === "m") value = absDays / 30.44;
else if (unit === "years" || unit === "yrs" || unit === "yr" || unit === "y") value = absDays / 365.25;
} else {
const fallback = formatDurationFromDays(absDays);
unit = fallback.unit;
value = Number(fallback.valueText);
}
const valueText = unit === "days" ? String(Math.round(value)) : value.toFixed(2);
const normalizedUnit =
unit === "mins" || unit === "min" ? "minutes" :
unit === "hrs" || unit === "hr" ? "hours" :
unit === "yrs" || unit === "yr" ? "years" :
unit === "mo" || unit === "m" ? "months" :
unit === "wk" || unit === "wks" ? "weeks" :
unit;
const decimalUnits = ["weeks", "months", "years"];
let normalizedValueText = valueText;
if (!decimalUnits.includes(normalizedUnit)) {
normalizedValueText = String(Math.round(value));
} else if (normalizedValueText.endsWith(".00")) {
normalizedValueText = normalizedValueText.slice(0, -3);
}
const isSingular = Number(normalizedValueText) === 1;
const singularUnit = normalizedUnit.replace(/s$/, "");
const pluralUnit = normalizedUnit.endsWith("s") ? normalizedUnit : `${normalizedUnit}s`;
const unitLabel = isSingular ? singularUnit : pluralUnit;
return { valueText: normalizedValueText, unitLabel };
}
function getEventDisplayMode(event) {
// Force ended events to always use since mode layout
if (!event) return "countdown";
const type = event.eventType || event.type || "";
if (event.mode === "since" || type.toLowerCase() === "ended") return "since";
return "countdown";
}
function getEventDisplayDays(event) {
const displayMode = getEventDisplayMode(event);
return displayMode === "since" ? daysSince(event.date) : daysUntil(event.date);
}
function getEventDisplayName(event, inSinceMode) {
if (!inSinceMode && event && event.mode === "since" && event.aliases) return event.aliases;
return event.name;
}
function matchesEventName(event, token) {
if (!event || !token) return false;
const t = token.toLowerCase();
if (event.name && event.name.toLowerCase().includes(t)) return true;
if (event.aliases && event.aliases.toLowerCase().includes(t)) return true;
return false;
}
function parseModeAndDisplayToken(token) {
const t = token.toLowerCase();
let mode = null;
let display = null;
let unit = null;
let name = null;
if (t.startsWith("mode since")) mode = "since";
if (t.startsWith("mode=since")) mode = "since";
if (t.startsWith("since")) mode = "since";
if (t.startsWith("mode countdown")) mode = "countdown";
if (t.startsWith("mode=countdown")) mode = "countdown";
if (t.startsWith("countdown")) mode = "countdown";
const parts = t.split(".");
if (parts.length > 1) {
const nameParts = [];
for (const part of parts.slice(1)) {
if (part === "topbar" || part === "circular" || part === "rect" || part === "rectangular") display = part === "rect" ? "rectangular" : part;
if (part === "days" || part === "weeks" || part === "wk" || part === "wks" || part === "months" || part === "mo" || part === "years" || part === "yr" || part === "yrs" || part === "hours" || part === "hrs" || part === "hr" || part === "minutes" || part === "min") unit = part;
if (part !== "topbar" && part !== "circular" && part !== "rect" && part !== "rectangular" && part !== "days" && part !== "weeks" && part !== "wk" && part !== "wks" && part !== "months" && part !== "mo" && part !== "years" && part !== "yr" && part !== "yrs" && part !== "hours" && part !== "hrs" && part !== "hr" && part !== "minutes" && part !== "min") {
nameParts.push(part);
}
}
if (nameParts.length) name = nameParts.join(" ");
}
return { mode, display, unit, name };
}
let currentTextColor = Color.white();
function normalizeHexColor(value) {
if (!value && value !== 0) return null;
let s = String(value).trim();
if (!s) return null;
if (!s.startsWith("#") && /^[0-9a-fA-F]{6}$/.test(s)) s = `#${s}`;
return s;
}
function getEventTextColor(event) {
if (event && event.widgetTextColor) {
const hex = normalizeHexColor(event.widgetTextColor);
if (hex) {
try { return new Color(hex); } catch (e) { /* ignore */ }
}
}
return Color.white();
}
function setCurrentTextColor(color) {
currentTextColor = color || Color.white();
}
if (param) {
const parts = param.split(',').map(p => p.trim().toLowerCase());
sinceMode = parts.some(p => {
if (p === "since" || p === "mode=since" || p === "mode since") return true;
if (p.startsWith("mode since.") || p.startsWith("mode=since.") || p.startsWith("since.")) return true;
const parsed = parseModeAndDisplayToken(p);
return parsed.mode === "since";
});
parts.forEach(p => {
if (p.startsWith("pg")) {
// Handle pagination (pg1, pg2, etc.)
page = parseInt(p.slice(2)) || 1;
return;
}
if (p === "age") {
// Activate age display mode
showAgeMode = true;
return;
}
if (p === "since" || p === "mode=since" || p === "mode since") {
modeExplicit = true;
return;
}
const parsed = parseModeAndDisplayToken(p);
if (parsed.mode) {
sinceMode = parsed.mode === "since";
modeExplicit = true;
if (parsed.display) lockDisplayType = parsed.display;
if (parsed.unit) sinceUnitOverride = parsed.unit;
if (parsed.name) {
selectionSpecified = true;
if (sinceMode) {
const sinceEvents = events.filter(isSinceEvent).filter(e => daysSince(e.date) >= 0);
const match = sinceEvents.find(e => matchesEventName(e, parsed.name));
if (match) selectedEvent = match;
} else {
const match = events.find(e => matchesEventName(e, parsed.name));
if (match) selectedEvent = match;
}
}
return;
}
if (!parsed.mode && parsed.display) {
lockDisplayType = parsed.display;
if (parsed.name) {
selectionSpecified = true;
const match = events.find(e => matchesEventName(e, parsed.name));
if (match) selectedEvent = match;
}
return;
}
if (p.startsWith("mode since.") || p.startsWith("mode=since.") || p.startsWith("since.")) {
const unit = p.split(".").pop();
if (unit) sinceUnitOverride = unit;
modeExplicit = true;
return;
}
if (!isNaN(p)) {
// Select event by numeric index
const index = parseInt(p) - 1;
selectionSpecified = true;
if (sinceMode) {
const sinceEvents = events.filter(isSinceEvent).filter(e => daysSince(e.date) >= 0);
if (index >= 0 && index < sinceEvents.length) selectedEvent = sinceEvents[index];
} else if (index >= 0 && index < events.length) {
selectedEvent = events[index];
}
return;
}
// Select event by matching name (case-insensitive)
selectionSpecified = true;
if (sinceMode) {
const sinceEvents = events.filter(isSinceEvent).filter(e => daysSince(e.date) >= 0);
const match = sinceEvents.find(e => matchesEventName(e, p));
if (match) selectedEvent = match;
} else {
const match = events.find(e => matchesEventName(e, p));
if (match) selectedEvent = match;
}
});
}
if (lockDisplayType && !modeExplicit) {
sinceMode = false;
}
if (sinceMode && selectionSpecified) {
// Include 'ended' events in since mode selection
const sinceFallback = events.filter(e => isSinceEvent(e)).filter(e => getEventDisplayDays(e) >= 0);
if (!selectedEvent || !isSinceEvent(selectedEvent)) {
if (sinceFallback.length) selectedEvent = sinceFallback[0];
}
}
// if (param && param !== "col") {
// const parts = param.split(',').map(p => p.trim());
// if (parts.includes("age")) showAgeMode = true;
// const otherParam = parts.find(p => p !== "age");
// if (otherParam) {
// if (!isNaN(otherParam)) {
// const index = parseInt(otherParam) - 1;
// if (index >= 0 && index < events.length) {
// selectedEvent = events[index];
// }
// } else {
// const match = events.find(e => e.name.toLowerCase().includes(otherParam));
// if (match) selectedEvent = match;
// }
// }
// }
// === Countdown Utils ===
function upcomingDateInCurrentYear(dateStr) {
const today = new Date();
// Use parseLocalDate to avoid UTC parsing issues ("YYYY-MM-DD" parses as UTC)
const d = parseLocalDate(dateStr);
if (!d || isNaN(d.getTime())) return null;
let upcoming = new Date(today.getFullYear(), d.getMonth(), d.getDate());
if (upcoming < today) {
upcoming.setFullYear(today.getFullYear() + 1);
}
return upcoming;
}
// Sort events by days until occurrence so today's events appear first in lists/grids
events.sort((a, b) => daysUntil(a.date) - daysUntil(b.date));
function parseLocalDate(dateStr) {
if (!dateStr && dateStr !== 0) return null;
if (dateStr instanceof Date) {
const dd = new Date(dateStr);
return new Date(dd.getFullYear(), dd.getMonth(), dd.getDate());
}
const s = String(dateStr).trim();
// YYYY-MM-DD (ISO) -> treat as local date (avoid UTC shift)
const mIso = s.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/);
if (mIso) {
const y = Number(mIso[1]);
const mo = Number(mIso[2]) - 1;
const day = Number(mIso[3]);
return new Date(y, mo, day);
}
// MM/DD/YYYY or M/D/YYYY
const mUS = s.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
if (mUS) {
const mo = Number(mUS[1]) - 1;
const day = Number(mUS[2]);
const y = Number(mUS[3]);
return new Date(y, mo, day);
}
// Fallback: parse with Date, then normalize to local Y/M/D
const d = new Date(s);
if (isNaN(d)) return null;
return new Date(d.getFullYear(), d.getMonth(), d.getDate());
}
function daysUntil(dateStr) {
const today = new Date();
today.setHours(0, 0, 0, 0);
let eventDate = parseLocalDate(dateStr);