forked from mzeryck/Weather-Cal
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweather-cal-code.js
More file actions
2720 lines (2233 loc) · 92.7 KB
/
Copy pathweather-cal-code.js
File metadata and controls
2720 lines (2233 loc) · 92.7 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: deep-purple; icon-glyph: calendar;
/*
~
This is the Weather Cal code script.
Don't delete it or change its name.
To update, run a Weather Cal widget script.
In the popup, tap "Update code".
It will update to the newest version.
~
*/
// Warn the user if this script is added to a widget.
if (config.runsInWidget) {
let infoWidget = new ListWidget()
infoWidget.addText('The "Weather Cal code" script is not intended to be used as a widget. Please use a Weather Cal widget script instead.')
Script.setWidget(infoWidget)
Script.complete()
}
// Set up the widget.
module.exports.runSetup = async (name, iCloudInUse, codeFilename, gitHubUrl) => {
return await setup(name, iCloudInUse, codeFilename, gitHubUrl)
}
// Return the widget.
module.exports.createWidget = async (layout, name, iCloudInUse, custom) => {
return await makeWidget(layout, name, iCloudInUse, custom)
}
/*
* Un-comment the section below to test the widget code.
*/
// const layout = `
//
// row
// column
// date
// space
// events
//
// column(90)
// current
// future
// space
//
// `
//
// let w = await makeWidget(layout, "Weather Cal widget", true)
// w.presentLarge()
async function setup(name, iCloudInUse, codeFilename, gitHubUrl) {
const fm = iCloudInUse ? FileManager.iCloud() : FileManager.local()
const prefName = "weather-cal-preferences-" + name
const prefPath = fm.joinPath(fm.libraryDirectory(), prefName)
const widgetUrl = "https://raw.githubusercontent.com/mzeryck/Weather-Cal/main/weather-cal.js"
// If no setup file exists, this is the initial Weather Cal setup.
const setupPath = fm.joinPath(fm.libraryDirectory(), "weather-cal-setup")
if (!fm.fileExists(setupPath)) { return await initialSetup() }
// If a settings file exists for this widget, we're editing settings.
const widgetpath = fm.joinPath(fm.libraryDirectory(), "weather-cal-" + name)
if (fm.fileExists(widgetpath)) { return await editSettings() }
// Otherwise, we're setting up this particular widget.
await generateAlert("Weather Cal is set up, but you need to choose a background for this widget.",["Continue"])
writePreference(prefName, defaultSettings())
return await setWidgetBackground()
// Run the initial setup.
async function initialSetup() {
// Welcome the user and make sure they like the script name.
let message = "Welcome to Weather Cal. Make sure your script has the name you want before you begin."
let options = ['I like the name "' + name + '"', "Let me go change it"]
let shouldExit = await generateAlert(message,options)
if (shouldExit) return
// Welcome the user and check for permissions.
message = "Next, we need to check if you've given permissions to the Scriptable app. This might take a few seconds."
options = ["Check permissions"]
await generateAlert(message,options)
let errors = []
try { await Location.current() } catch { errors.push("location") }
try { await CalendarEvent.today() } catch { errors.push("calendar") }
try { await Reminder.all() } catch { errors.push("reminders") }
let issues
if (errors.length > 0) { issues = errors[0] }
if (errors.length == 2) { issues += " and " + errors[1] }
if (errors.length == 3) { issues += ", " + errors[1] + ", and " + errors[2] }
if (issues) {
message = "Scriptable does not have permission for " + issues + ". Some features may not work without enabling them in the Settings app."
options = ["Continue setup anyway", "Exit setup"]
} else {
message = "Your permissions are enabled."
options = ["Continue setup"]
}
shouldExit = await generateAlert(message,options)
if (shouldExit) return
// Set up the weather integration.
message = "To display the weather on your widget, you need an OpenWeather API key."
options = ["I already have a key", "I need to get a key", "I don't want to show weather info"]
const weather = await generateAlert(message,options)
// Show a web view to claim the API key.
if (weather == 1) {
message = "On the next screen, sign up for OpenWeather. Find the API key, copy it, and close the web view. You will then be prompted to paste in the key."
options = ["Continue"]
let weather = await generateAlert(message,options)
let webView = new WebView()
webView.loadURL("https://openweathermap.org/home/sign_up")
await webView.present()
}
// We need the API key if we're showing weather.
if (weather < 2) {
const response = await getWeatherKey(true)
if (!response) return
}
// Set up background image.
await setWidgetBackground()
// Write the default settings to disk.
writePreference(prefName, defaultSettings())
// Record setup completion.
writePreference("weather-cal-setup", "true")
message = "Your widget is ready! You'll now see a preview. Re-run this script to edit the default preferences, including localization. When you're ready, add a Scriptable widget to the home screen and select this script."
options = ["Show preview"]
await generateAlert(message,options)
// Return and show the preview.
return previewValue()
}
// Edit the widget settings.
async function editSettings() {
let message = "Widget Setup"
let options = ["Show widget preview", "Change background", "Edit preferences", "Re-enter API key", "Update code", "Reset widget", "Exit settings menu"]
const response = await generateAlert(message,options)
// Return true to show the widget preview.
if (response == 0) {
return previewValue()
}
// Set the background and show a preview.
if (response == 1) {
await setWidgetBackground()
return true
}
// Display the preferences panel.
if (response == 2) {
await editPreferences()
return
}
// Set the API key.
if (response == 3) {
await getWeatherKey()
return
}
if (response == 4) {
// Prompt the user for updates.
message = "Would you like to update the Weather Cal code? Your widgets will not be affected."
options = ["Update", "Exit"]
const updateResponse = await generateAlert(message,options)
// Exit if the user didn't want to update.
if (updateResponse) return
// Try updating the code.
const success = await downloadCode(codeFilename, gitHubUrl)
message = success ? "The update is now complete." : "The update failed. Please try again later."
options = ["OK"]
await generateAlert(message,options)
return
}
// Reset the widget.
if (response == 5) {
const alert = new Alert()
alert.message = "Are you sure you want to completely reset this widget?"
alert.addDestructiveAction("Reset")
alert.addAction("Cancel")
const cancelReset = await alert.present()
if (cancelReset == 0) {
const bgPath = fm.joinPath(fm.libraryDirectory(), "weather-cal-" + name)
if (fm.fileExists(bgPath)) { fm.remove(bgPath) }
if (fm.fileExists(prefPath)) { fm.remove(prefPath) }
const success = await downloadCode(name, widgetUrl)
message = success ? "This script has been reset. Close the script and reopen it for the change to take effect." : "The reset failed."
options = ["OK"]
await generateAlert(message,options)
}
return
}
// If response was Exit, just return.
return
}
// Get the weather key, optionally determining if it's the first run.
async function getWeatherKey(firstRun = false) {
// Prompt for the key.
const returnVal = await promptForText("Paste your API key in the box below.",[""],["82c29fdbgd6aebbb595d402f8a65fabf"])
const apiKey = returnVal.textFieldValue(0)
let message, options
if (!apiKey || apiKey == "" || apiKey == null) {
message = "No API key was entered. Try copying the key again and re-running this script."
options = ["Exit"]
await generateAlert(message,options)
return false
}
// Save the key.
writePreference("weather-cal-api-key", apiKey)
// Test to see if the key works.
const req = new Request("https://api.openweathermap.org/data/2.5/onecall?lat=37.332280&lon=-122.010980&appid=" + apiKey)
let val = {}
try { val = await req.loadJSON() } catch { val.current = false }
// Warn the user if it didn't work.
if (!val.current) {
message = firstRun ? "New OpenWeather API keys may take a few hours to activate. Your widget will start displaying weather information once it's active." : "The key you entered, " + apiKey + ", didn't work. If it's a new key, it may take a few hours to activate."
options = [firstRun ? "Continue" : "OK"]
await generateAlert(message,options)
// Otherwise, confirm that it was saved.
} else if (val.current && !firstRun) {
message = "The new key worked and was saved."
options = ["OK"]
await generateAlert(message,options)
}
// If we made it this far, we did it.
return true
}
// Set the background of the widget.
async function setWidgetBackground() {
// Prompt for the widget background.
let message = "What type of background would you like for your widget?"
let options = ["Solid color", "Automatic gradient", "Custom gradient", "Image from Photos"]
let backgroundType = await generateAlert(message,options)
let background = {}
let returnVal
if (backgroundType == 0) {
background.type = "color"
returnVal = await promptForText("Enter the hex value of the background color you want.",[""],["#007030"])
background.color = returnVal.textFieldValue(0)
} else if (backgroundType == 1) {
background.type = "auto"
} else if (backgroundType == 2) {
background.type = "gradient"
returnVal = await promptForText("Enter the hex value of the first gradient color.",[""],["#007030"])
background.initialColor = returnVal.textFieldValue(0)
returnVal = await promptForText("Enter the hex value of the second gradient color.",[""],["#007030"])
background.finalColor = returnVal.textFieldValue(0)
} else if (backgroundType == 3) {
background.type = "image"
// Create the Weather Cal directory if it doesn't already exist.
const dirPath = fm.joinPath(fm.documentsDirectory(), "Weather Cal")
if (!fm.fileExists(dirPath) || !fm.isDirectory(dirPath)) {
fm.createDirectory(dirPath)
}
// Determine if a dupe already exists.
const dupePath = fm.joinPath(dirPath, name + " 2.jpg")
const dupeAlreadyExists = fm.fileExists(dupePath)
// Get the image and write it to disk.
const img = await Photos.fromLibrary()
const path = fm.joinPath(dirPath, name + ".jpg")
fm.writeImage(path, img)
// If we just created a dupe, alert the user.
if (!dupeAlreadyExists && fm.fileExists(dupePath)) {
message = "Weather Cal detected a duplicate image. Please open the Files app, navigate to Scriptable > Weather Cal, and make sure the file named " + name + ".jpg is correct."
options = ["OK"]
const response = generateAlert(message,options)
}
}
writePreference("weather-cal-" + name, background)
return previewValue()
}
// Return the default widget settings.
function defaultSettings() {
const settings = {
widget: {
name: "Overall settings",
locale: {
val: "",
name: "Locale code",
description: "Leave blank to match the device's locale.",
},
units: {
val: "imperial",
name: "Units",
description: "Use imperial for Fahrenheit or metric for Celsius.",
type: "enum",
options: ["imperial","metric"],
},
preview: {
val: "large",
name: "Widget preview size",
description: "Set the size of the widget preview displayed in the app.",
type: "enum",
options: ["small","medium","large"],
},
padding: {
val: "5",
name: "Padding",
description: "The padding around each item. Default is 5.",
},
tintIcons: {
val: false,
name: "Icons match text color",
description: "Decide if icons should match the color of the text around them.",
type: "bool",
},
},
localization: {
name: "Localization and text customization",
morningGreeting: {
val: "Good morning.",
name: "Morning greeting",
},
afternoonGreeting: {
val: "Good afternoon.",
name: "Afternoon greeting",
},
eveningGreeting: {
val: "Good evening.",
name: "Evening greeting",
},
nightGreeting: {
val: "Good night.",
name: "Night greeting",
},
nextHourLabel: {
val: "Next hour",
name: "Label for next hour of weather",
},
tomorrowLabel: {
val: "Tomorrow",
name: "Label for tomorrow",
},
noEventMessage: {
val: "Enjoy the rest of your day.",
name: "No event message",
description: "The message shown when there are no more events for the day, if that setting is active.",
},
durationMinute: {
val: "m",
name: "Duration label for minutes",
},
durationHour: {
val: "h",
name: "Duration label for hours",
},
covid: {
val: "{cases} cases, {deaths} deaths, {recovered} recoveries",
name: "COVID data text",
description: "Each {token} is replaced with the number from the data. The available tokens are: cases, todayCases, deaths, todayDeaths, recovered, active, critical, casesPerOneMillion, deathsPerOneMillion, totalTests, testsPerOneMillion"
},
week: {
val: "Week",
name: "Label for the week number",
},
},
font: {
name: "Text sizes, colors, and fonts",
defaultText: {
val: { size: "14", color: "ffffff", font: "regular" },
name: "Default font settings",
description: "These settings apply to all text on the widget that doesn't have a customized value.",
type: "multival",
},
smallDate: {
val: { size: "17", color: "", font: "semibold" },
name: "Small date",
type: "multival",
},
largeDate1: {
val: { size: "30", color: "", font: "light" },
name: "Large date, line 1",
type: "multival",
},
largeDate2: {
val: { size: "30", color: "", font: "light" },
name: "Large date, line 2",
type: "multival",
},
greeting: {
val: { size: "30", color: "", font: "semibold" },
name: "Greeting",
type: "multival",
},
eventLabel: {
val: { size: "14", color: "", font: "semibold" },
name: "Event heading (used for the TOMORROW label)",
type: "multival",
},
eventTitle: {
val: { size: "14", color: "", font: "semibold" },
name: "Event title",
type: "multival",
},
eventLocation: {
val: { size: "14", color: "", font: "" },
name: "Event location",
type: "multival",
},
eventTime: {
val: { size: "14", color: "ffffffcc", font: "" },
name: "Event time",
type: "multival",
},
noEvents: {
val: { size: "30", color: "", font: "semibold" },
name: "No events message",
type: "multival",
},
reminderTitle: {
val: { size: "14", color: "", font: "" },
name: "Reminder title",
type: "multival",
},
reminderTime: {
val: { size: "14", color: "ffffffcc", font: "" },
name: "Reminder time",
type: "multival",
},
largeTemp: {
val: { size: "34", color: "", font: "light" },
name: "Large temperature label",
type: "multival",
},
smallTemp: {
val: { size: "14", color: "", font: "" },
name: "Most text used in weather items",
type: "multival",
},
tinyTemp: {
val: { size: "12", color: "", font: "" },
name: "Small text used in weather items",
type: "multival",
},
customText: {
val: { size: "14", color: "", font: "" },
name: "User-defined text items",
type: "multival",
},
battery: {
val: { size: "14", color: "", font: "medium" },
name: "Battery percentage",
type: "multival",
},
sunrise: {
val: { size: "14", color: "", font: "medium" },
name: "Sunrise and sunset",
type: "multival",
},
covid: {
val: { size: "14", color: "", font: "medium" },
name: "COVID data",
type: "multival",
},
week: {
val: { size: "14", color: "", font: "light" },
name: "Week label",
type: "multival",
},
},
date: {
name: "Date",
dynamicDateSize: {
val: true,
name: "Dynamic date size",
description: "If set to true, the date will become smaller when events are displayed.",
type: "bool",
},
staticDateSize: {
val: "small",
name: "Static date size",
description: "Set the date size shown when dynamic date size is not enabled.",
type: "enum",
options: ["small","large"],
},
smallDateFormat: {
val: "EEEE, MMMM d",
name: "Small date format",
},
largeDateLineOne: {
val: "EEEE,",
name: "Large date format, line 1",
},
largeDateLineTwo: {
val: "MMMM d",
name: "Large date format, line 2",
},
},
events: {
name: "Events",
numberOfEvents: {
val: "3",
name: "Maximum number of events shown",
},
minutesAfter: {
val: "5",
name: "Minutes after event",
description: "Number of minutes after an event begins that it should still be shown.",
},
showAllDay: {
val: false,
name: "Show all-day events",
type: "bool",
},
showTomorrow: {
val: "20",
name: "Tomorrow's events shown at hour",
description: "The hour (in 24-hour time) to start showing tomorrow's events. Use 0 for always, 24 for never.",
},
showEventLength: {
val: "duration",
name: "Event length display style",
description: "Choose whether to show the duration, the end time, or no length information.",
type: "enum",
options: ["duration","time","none"],
},
showLocation: {
val: false,
name: "Show event location",
type: "bool",
},
selectCalendars: {
val: "",
name: "Calendars to show",
description: "Write the names of each calendar separated by commas, like this: Home,Work,Personal. Leave blank to show events from all calendars.",
},
showCalendarColor: {
val: "rectangle left",
name: "Display calendar color",
description: "Choose the shape and location of the calendar color.",
type: "enum",
options: ["rectangle left","rectangle right","circle left","circle right","none"],
},
noEventBehavior: {
val: "message",
name: "Show when no events remain",
description: "When no events remain, show a hard-coded message, a time-based greeting, or nothing.",
type: "enum",
options: ["message","greeting","none"],
},
url: {
val: "",
name: "URL to open when tapped",
description: "Optionally provide a URL to open when this item is tapped. Leave blank to open the built-in Calendar app.",
},
},
reminders: {
name: "Reminders",
numberOfReminders: {
val: "3",
name: "Maximum number of reminders shown",
},
useRelativeDueDate: {
val: false,
name: "Use relative dates",
description: "Set to true for a relative due date (in 3 hours) instead of absolute (3:00 PM).",
type: "bool",
},
showWithoutDueDate: {
val: false,
name: "Show reminders without a due date",
type: "bool",
},
showOverdue: {
val: false,
name: "Show overdue reminders",
type: "bool",
},
todayOnly: {
val: false,
name: "Hide reminders due after today",
type: "bool",
},
selectLists: {
val: "",
name: "Lists to show",
description: "Write the names of each list separated by commas, like this: Home,Work,Personal. Leave blank to show reminders from all lists.",
},
showListColor: {
val: "rectangle left",
name: "Display list color",
description: "Choose the shape and location of the list color.",
type: "enum",
options: ["rectangle left","rectangle right","circle left","circle right","none"],
},
url: {
val: "",
name: "URL to open when tapped",
description: "Optionally provide a URL to open when this item is tapped. Leave blank to open the built-in Reminders app.",
},
},
sunrise: {
name: "Sunrise and sunset",
showWithin: {
val: "",
name: "Limit times displayed",
description: "Set how many minutes before/after sunrise or sunset to show this element. Leave blank to always show.",
},
separateElements: {
val: false,
name: "Use separate sunrise and sunset elements",
description: "By default, the sunrise element changes between sunrise and sunset times automatically. Set to true for individual, hard-coded sunrise and sunset elements.",
type: "bool",
},
},
weather: {
name: "Weather",
showLocation: {
val: false,
name: "Show location name",
type: "bool",
},
horizontalCondition: {
val: false,
name: "Display the condition and temperature horizontally",
type: "bool",
},
showCondition: {
val: false,
name: "Show text value of the current condition",
type: "bool",
},
showHighLow: {
val: true,
name: "Show today's high and low temperatures",
type: "bool",
},
showRain: {
val: false,
name: "Show percent chance of rain",
type: "bool",
},
tomorrowShownAtHour: {
val: "20",
name: "When to switch to tomorrow's weather",
description: "Set the hour (in 24-hour time) to switch from the next hour to tomorrow's weather. Use 0 for always, 24 for never.",
},
showDays: {
val: "3",
name: "Number of days shown in the forecast item",
},
showDaysFormat: {
val: "E",
name: "Date format for the forecast item",
},
showToday: {
val: true,
name: "Show today's weather in the forecast item",
type: "bool",
},
urlCurrent: {
val: "",
name: "URL to open when current weather is tapped",
description: "Optionally provide a URL to open when this item is tapped. Leave blank for the default.",
},
urlFuture: {
val: "",
name: "URL to open when future weather is tapped",
description: "Optionally provide a URL to open when this item is tapped. Leave blank for the default.",
},
urlForecast: {
val: "",
name: "URL to open when the forecast item is tapped",
description: "Optionally provide a URL to open when this item is tapped. Leave blank for the default.",
},
},
covid: {
name: "COVID data",
country: {
val: "USA",
name: "Country for COVID information",
},
url: {
val: "https://covid19.who.int",
name: "URL to open when the COVID data is tapped",
},
},
}
return settings
}
// Load or reload a table full of preferences.
async function loadTable(table,category,settingsObject) {
table.removeAllRows()
for (key in category) {
// Don't show the name as a setting.
if (key == "name") continue
// Make the row.
const row = new UITableRow()
row.dismissOnSelect = false
row.height = 55
// Fill it with the setting information.
const setting = category[key]
let valText
if (typeof setting.val == "object") {
for (subItem in setting.val) {
const setupText = subItem + ": " + setting.val[subItem]
if (!valText) {
valText = setupText
continue
}
valText += ", " + setupText
}
} else {
valText = setting.val + ""
}
const cell = row.addText(setting.name,valText)
cell.subtitleColor = Color.gray()
// If there's no type, it's just text.
if (!setting.type) {
row.onSelect = async () => {
const returnVal = await promptForText(setting.name,[setting.val],[],setting.description)
setting.val = returnVal.textFieldValue(0)
loadTable(table,category,settingsObject)
}
} else if (setting.type == "enum") {
row.onSelect = async () => {
const returnVal = await generateAlert(setting.name,setting.options,setting.description)
setting.val = setting.options[returnVal]
await loadTable(table,category,settingsObject)
}
} else if (setting.type == "bool") {
row.onSelect = async () => {
const returnVal = await generateAlert(setting.name,["true","false"],setting.description)
setting.val = !returnVal
await loadTable(table,category,settingsObject)
}
} else if (setting.type == "multival") {
row.onSelect = async () => {
// We need an ordered set.
let keys = []
let values = []
for (const item in setting.val) {
keys.push(item)
values.push(setting.val[item])
}
const returnVal = await promptForText(setting.name,values,keys,setting.description)
for (let i=0; i < keys.length; i++) {
const currentKey = keys[i]
setting.val[currentKey] = returnVal.textFieldValue(i)
}
await loadTable(table,category,settingsObject)
}
}
// Add it to the table.
table.addRow(row)
}
table.reload()
}
async function editPreferences() {
// Get the preferences object.
let settingsObject
if (!fm.fileExists(prefPath)) {
await generateAlert("No preferences file exists. If you're on an older version of Weather Cal, you need to reset your widget in order to use the preferences editor.",["OK"])
return
} else {
const settingsFromFile = JSON.parse(fm.readString(prefPath))
settingsObject = defaultSettings()
// Iterate through the settings object.
if (settingsFromFile.widget.units.val == undefined) {
for (category in settingsObject) {
for (item in settingsObject[category]) {
// If the setting exists, use it. Otherwise, the default is used.
if (settingsFromFile[category][item] != undefined) {
settingsObject[category][item].val = settingsFromFile[category][item]
}
}
}
// Fix for old preference files.
} else {
settingsObject = settingsFromFile
}
}
// Create the settings table.
const table = new UITable()
table.showSeparators = true
// Iterate through each item in the settings object.
for (key in settingsObject) {
// Make the row.
let row = new UITableRow()
row.dismissOnSelect = false
// Fill it with the category information.
const category = settingsObject[key]
row.addText(category.name)
row.onSelect = async () => {
const subTable = new UITable()
subTable.showSeparators = true
await loadTable(subTable,category,settingsObject)
await subTable.present()
}
// Add it to the table.
table.addRow(row)
}
await table.present()
// Upon dismissal, roll up preferences and write to disk.
for (category in settingsObject) {
for (item in settingsObject[category]) {
if (item == "name") continue
settingsObject[category][item] = settingsObject[category][item].val
}
}
writePreference(prefName, settingsObject)
}
// Return the widget preview value.
function previewValue() {
if (fm.fileExists(prefPath)) {
let settingsObject = JSON.parse(fm.readString(prefPath))
return settingsObject.widget.preview || settingsObject.widget.preview.val
} else {
return "large"
}
}
// Download a Scriptable script.
async function downloadCode(filename, url) {
const pathToCode = fm.joinPath(fm.documentsDirectory(), filename + ".js")
const req = new Request(url)
try {
const codeString = await req.loadString()
fm.writeString(pathToCode, codeString)
return true
} catch {
return false
}
}
// Generate an alert with the provided array of options.
async function generateAlert(title,options,message = null) {
const alert = new Alert()
alert.title = title
if (message) alert.message = message
for (const option of options) {
alert.addAction(option)
}
const response = await alert.presentAlert()
return response
}
// Prompt for one or more text field values.
async function promptForText(title,values,keys,message = null) {
const alert = new Alert()
alert.title = title
if (message) alert.message = message
for (let i=0; i < values.length; i++) {
alert.addTextField(keys ? (keys[i] || null) : null,values[i] + "")
}
alert.addAction("OK")
await alert.present()
return alert
}
// Write the value of a preference to disk.
function writePreference(filename, value) {
const path = fm.joinPath(fm.libraryDirectory(), filename)
if (typeof value === "string") {
fm.writeString(path, value)
} else {
fm.writeString(path, JSON.stringify(value))
}
}
}
async function makeWidget(layout, name, iCloudInUse, custom) {
// All widget items must be documented here.
function provideFunction(functionName) {
const functions = {
battery() { return battery },
center() { return center },
column() { return column },
covid() { return covid },
current() { return current },
date() { return date },
events() { return events },
forecast() { return forecast },
future() { return future },
greeting() { return greeting },
left() { return left },
reminders() { return reminders },
right() { return right },
row() { return row },
space() { return space },
sunrise() { return sunrise },
sunset() { return sunset },
text() { return text },
week() { return week },
}
if (functions[functionName]) return functions[functionName]()
if (custom) return custom[functionName]
return null
}
// We always need a file manager.
const files = iCloudInUse ? FileManager.iCloud() : FileManager.local()
// Determine if we're using the old or new setup.
let settings
if (typeof layout == "object") {
settings = layout
} else {
const prefPath = files.joinPath(files.libraryDirectory(), "weather-cal-preferences-" + name)
settings = JSON.parse(files.readString(prefPath))
// Fix old preference files.
if (settings.widget.units.val != undefined) {
for (category in settings) {
for (item in settings[category]) {