Guest User

WeatherCal dark text custom script

a guest
Nov 30th, 2020
673
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Variables used by Scriptable.
  2. // These must be at the very top of the file. Do not edit.
  3. // icon-color: deep-purple; icon-glyph: calendar;
  4. /*
  5.  * SETUP
  6.  * Use this section to set up the widget.
  7.  * ======================================
  8.  */
  9.  
  10. // To use weather, get a free API key at openweathermap.org/appid and paste it in between the quotation marks.
  11. const apiKey = ""
  12.  
  13. // Set the locale code. Leave blank "" to match the device's locale. You can change the hard-coded text strings in the TEXT section below.
  14. let locale = "en"
  15.  
  16. // Set to true for fixed location, false to update location as you move around
  17. const lockLocation = false
  18.  
  19. // The size of the widget preview in the app.
  20. const widgetPreview = "large"
  21.  
  22. // Set to true for an image background, false for no image.
  23. const imageBackground = true
  24.  
  25. // Set to true to reset the widget's background image.
  26. const forceImageUpdate = true
  27.  
  28. // Set the padding around each item. Default is 5.
  29. const padding = 2
  30.  
  31. // Decide if icons should match the color of the text around them.
  32. const tintIcons = true
  33.  
  34. /*
  35.  * LAYOUT
  36.  * Decide what items to show on the widget.
  37.  * ========================================
  38.  */
  39.  
  40. // You always need to start with "row," and "column," items, but you can now add as many as you want.
  41. // Adding left, right, or center will align everything after that. The default alignment is left.
  42.  
  43. // You can add a flexible vertical space with "space," or a fixed-size space like this: "space(50)"
  44. // Align items to the top or bottom of columns by adding "space," before or after all items in the column.
  45.  
  46. // There are many possible items, including: date, greeting, events, current, future, battery, sunrise, and text("Your text here")
  47. // Make sure to always put a comma after each item.
  48.  
  49. const items = [
  50.  
  51. row,
  52.  
  53. column,
  54. center,
  55. date,
  56.  
  57. row,
  58.  
  59. column,
  60. left,
  61. sunrise,
  62. space,
  63.  
  64. column,
  65. center,
  66. current,
  67.  
  68. column,
  69. right,
  70. future,
  71. space,
  72.  
  73. row,
  74.  
  75. column,
  76. left,
  77. space,
  78. events,
  79.  
  80. ]
  81.  
  82. /*
  83.  * ITEM SETTINGS
  84.  * Choose how each item is displayed.
  85.  * ==================================
  86.  */  
  87.  
  88. // DATE
  89. // ====
  90. const dateSettings = {
  91.  
  92.   // If set to true, date will become smaller when events are displayed.
  93.   dynamicDateSize: false
  94.  
  95.   // If the date is not dynamic, should it be large or small?
  96.   ,staticDateSize: "small"
  97.  
  98.   // Determine the date format for each date type. See docs.scriptable.app/dateformatter
  99.   ,smallDateFormat: "EEEE, MMMM d"
  100.   ,largeDateLineOne: ""
  101.   ,largeDateLineTwo: ""
  102. }
  103.  
  104. // EVENTS
  105. // ======
  106. const eventSettings = {
  107.  
  108.   // How many events to show.
  109.   numberOfEvents: 5
  110.  
  111.   // Show all-day events.
  112.   ,showAllDay: true
  113.  
  114.   // Show tomorrow's events.
  115.   ,showTomorrow: true
  116.  
  117.   // Can be blank "" or set to "duration" or "time" to display how long an event is.
  118.   ,showEventLength: "time"
  119.  
  120.   // Set which calendars for which to show events. Empty [] means all calendars.
  121.   ,selectCalendars: []
  122.  
  123.   // Leave blank "" for no color, or specify shape (circle, rectangle) and/or side (left, right).
  124.   ,showCalendarColor: "rectangle left"
  125.  
  126.   // When no events remain, show a hard-coded "message", a "greeting", or "none".
  127.   ,noEventBehavior: "message"
  128. }
  129.  
  130. // SUNRISE
  131. // =======
  132. const sunriseSettings = {
  133.  
  134.   // How many minutes before/after sunrise or sunset to show this element. 0 for always.
  135.   showWithin: 0
  136. }
  137.  
  138. // WEATHER
  139. // =======
  140. const weatherSettings = {
  141.  
  142.   // Set to imperial for Fahrenheit, or metric for Celsius
  143.   units: "imperial"
  144.  
  145.   // Show the location of the current weather.
  146.   ,showLocation: false
  147.  
  148.   // Show the text description of the current conditions.
  149.   ,showCondition: false
  150.  
  151.   // Show today's high and low temperatures.
  152.   ,showHighLow: true
  153.  
  154.   // Set the hour (in 24-hour time) to switch to tomorrow's weather. Set to 24 to never show it.
  155.   ,tomorrowShownAtHour: 20
  156. }
  157.  
  158. /*
  159.  * TEXT
  160.  * Change the language and formatting of text displayed.
  161.  * =====================================================
  162.  */  
  163.  
  164. // You can change the language or wording of any text in the widget.
  165. const localizedText = {
  166.  
  167.   // The text shown if you add a greeting item to the layout.
  168.   nightGreeting: "good night."
  169.   ,morningGreeting: "good morning."
  170.   ,afternoonGreeting: "good afternoon."
  171.   ,eveningGreeting: "good evening."
  172.  
  173.   // The text shown if you add a future weather item to the layout, or tomorrow's events.
  174.   ,nextHourLabel: "next hour"
  175.   ,tomorrowLabel: "tomorrow"
  176.  
  177.   // Shown when noEventBehavior is set to "message".
  178.   ,noEventMessage: "enjoy the rest of your day!"
  179.  
  180.   // The text shown after the hours and minutes of an event duration.
  181.   ,durationMinute: "m"
  182.   ,durationHour: "h"
  183.      
  184. }
  185.  
  186. // Set the font, size, and color of various text elements. Use iosfonts.com to find fonts to use. If you want to use the default iOS font, set the font name to one of the following: ultralight, light, regular, medium, semibold, bold, heavy, black, or italic.
  187. const textFormat = {
  188.  
  189.   // Set the default font and color.
  190.   defaultText: { size: 14, color: "4A4E69", font: "AvenirNext-Regular" },
  191.  
  192.   // Any blank values will use the default.
  193.   smallDate:   { size: 28, color: "4A4E69", font: "AvenirNext-Medium" },
  194.   largeDate1:  { size: 25, color: "", font: "AvenirNext-Regular" },
  195.   largeDate2:  { size: 18, color: "", font: "AvenirNext-Regular" },
  196.  
  197.   greeting:    { size: 22, color: "", font: "AvenirNext-DemiBold" },
  198.   eventLabel:  { size: 14, color: "9A8C98", font: "AvenirNext-Regular" },
  199.   eventTitle:  { size: 14, color: "4A4E69", font: "AvenirNext-Medium" },
  200.   eventTime:   { size: 12, color: "9A8C98", font: "AvenirNext-Medium" },
  201.   noEvents:    { size: 14, color: "4A4E69", font: "AvenirNext-Regular" },
  202.  
  203.   largeTemp:   { size: 34, color: "4A4E69", font: "AvenirNext-Regular" },
  204.   smallTemp:   { size: 14, color: "4A4E69", font: "AvenirNext-Regular" },
  205.   tinyTemp:    { size: 12, color: "4A4E69", font: "AvenirNext-Regular" },
  206.  
  207.   customText:  { size: 14, color: "", font: "AvenirNext-Regular" },
  208.  
  209.   battery:     { size: 14, color: "4A4E69", font: "AvenirNext-Regular" },
  210.   sunrise:     { size: 14, color: "4A4E69", font: "AvenirNext-Regular" },
  211. }
  212.  
  213. /*
  214.  * WIDGET CODE
  215.  * Be more careful editing this section.
  216.  * =====================================
  217.  */
  218.  
  219. // Make sure we have a locale value.
  220. if (locale == "" || locale == null) { locale = Device.locale() }
  221.  
  222. // Declare the data variables.
  223. var eventData, locationData, sunData, weatherData
  224.  
  225. // Create global constants.
  226. const currentDate = new Date()
  227. const files = FileManager.local()
  228.  
  229. /*
  230.  * CONSTRUCTION
  231.  * ============
  232.  */
  233.  
  234. // Set up the widget with padding.
  235. const widget = new ListWidget()
  236. const horizontalPad = padding < 10 ? 10 - padding : 10
  237. const verticalPad = padding < 15 ? 15 - padding : 15
  238. widget.setPadding(horizontalPad, verticalPad, horizontalPad, verticalPad)
  239. widget.spacing = 0
  240.  
  241. // Set up the global variables.
  242. var currentRow = {}
  243. var currentColumn = {}
  244.  
  245. // Set up the initial alignment.
  246. var currentAlignment = alignLeft
  247.  
  248. // Set up the global ASCII variables.
  249. var currentColumns = []
  250. var rowNeedsSetup = false
  251.  
  252. // It's ASCII time!
  253. if (typeof items[0] == 'string') {
  254.   for (line of items[0].split(/\r?\n/)) { await processLine(line) }
  255. }
  256. // Otherwise, set up normally.
  257. else {
  258.   for (item of items) { await item(currentColumn) }
  259. }
  260.  
  261. /*
  262.  * BACKGROUND DISPLAY
  263.  * ==================
  264.  */
  265.  
  266. // If it's an image background, display it.
  267. if (imageBackground) {
  268.  
  269.   // Determine if our image exists and when it was saved.
  270.   const path = files.joinPath(files.documentsDirectory(), "weather-cal-image")
  271.   const exists = files.fileExists(path)
  272.  
  273.   // If it exists and an update isn't forced, use the cache.
  274.   if (exists && (config.runsInWidget || !forceImageUpdate)) {
  275.     widget.backgroundImage = files.readImage(path)
  276.  
  277.   // If it's missing when running in the widget, use a gray background.
  278.   } else if (!exists && config.runsInWidget) {
  279.       widget.backgroundColor = Color.gray()
  280.    
  281.   // But if we're running in app, prompt the user for the image.
  282.   } else {
  283.       const img = await Photos.fromLibrary()
  284.       widget.backgroundImage = img
  285.       files.writeImage(path, img)
  286.   }
  287.    
  288. // If it's not an image background, show the gradient.
  289. } else {
  290.   let gradient = new LinearGradient()
  291.   let gradientSettings = await setupGradient()
  292.  
  293.   gradient.colors = gradientSettings.color()
  294.   gradient.locations = gradientSettings.position()
  295.  
  296.   widget.backgroundGradient = gradient
  297. }
  298.  
  299. // Finish the widget and show a preview.
  300. Script.setWidget(widget)
  301. if (widgetPreview == "small") { widget.presentSmall() }
  302. else if (widgetPreview == "medium") { widget.presentMedium() }
  303. else if (widgetPreview == "large") { widget.presentLarge() }
  304. Script.complete()
  305.  
  306. /*
  307.  * ASCII FUNCTIONS
  308.  * Now isn't this a lot of fun?
  309.  * ============================
  310.  */
  311.  
  312. // Provide the named function.
  313. function provideFunction(name) {
  314.   const functions = {
  315.     space() { return space },
  316.     left() { return left },
  317.     right() { return right },
  318.     center() { return center },
  319.     date() { return date },
  320.     greeting() { return greeting },
  321.     events() { return events },
  322.     current() { return current },
  323.     future() { return future },
  324.     battery() { return battery },
  325.     sunrise() { return sunrise },
  326.   }
  327.   return functions[name]
  328. }
  329.  
  330. // Processes a single line of ASCII.
  331. async function processLine(lineInput) {
  332.  
  333.   // Because iOS loves adding periods to everything.
  334.   const line = lineInput.replace(/\.+/g,'')
  335.  
  336.   // If it's blank, return.
  337.   if (line.trim() == '') { return }
  338.  
  339.   // If it's a line, enumerate previous columns (if any) and set up the new row.
  340.   if (line[0] == '-' && line[line.length-1] == '-') {
  341.     if (currentColumns.length > 0) { await enumerateColumns() }
  342.     rowNeedsSetup = true
  343.     return
  344.   }
  345.  
  346.   // If it's the first content row, finish the row setup.
  347.   if (rowNeedsSetup) {
  348.     row(currentColumn)
  349.     rowNeedsSetup = false
  350.   }
  351.  
  352.   // If there's a number, this is a setup row.
  353.   const setupRow = line.match(/\d+/)
  354.  
  355.   // Otherwise, it has columns.
  356.   const items = line.split('|')
  357.  
  358.   // Iterate through each item.
  359.   for (var i=1; i < items.length-1; i++) {
  360.    
  361.     // If the current column doesn't exist, make it.
  362.     if (!currentColumns[i]) { currentColumns[i] = { items: [] } }
  363.    
  364.     // Now we have a column to add the items to.
  365.     const column = currentColumns[i].items
  366.    
  367.     // Get the current item and its trimmed version.
  368.     const item = items[i]
  369.     const trim = item.trim()
  370.    
  371.     // If it's not a function, figure out spacing.
  372.     if (!provideFunction(trim)) {
  373.      
  374.       // If it's a setup row, whether or not we find the number, we keep going.
  375.       if (setupRow) {
  376.         const value = parseInt(trim, 10)
  377.         if (value) { currentColumns[i].width = value }
  378.         continue
  379.       }
  380.      
  381.       // If it's blank and we haven't already added a space, add one.
  382.       const prevItem = column[column.length-1]
  383.       if (trim == '' && (!prevItem || (prevItem && !prevItem.startsWith("space")))) {
  384.         column.push("space")
  385.       }
  386.      
  387.       // Either way, we're done.
  388.       continue
  389.    
  390.     }
  391.    
  392.     // Determine the alignment.
  393.     const index = item.indexOf(trim)
  394.     const length = item.slice(index,item.length).length
  395.    
  396.     let align
  397.     if (index > 0 && length > trim.length) { align = "center" }
  398.     else if (index > 0) { align = "right" }
  399.     else { align = "left" }
  400.    
  401.     // Add the items to the column.
  402.     column.push(align)
  403.     column.push(trim)
  404.   }
  405. }
  406.  
  407. // Runs the function names in each column.
  408. async function enumerateColumns() {
  409.   if (currentColumns.length > 0) {
  410.     for (col of currentColumns) {
  411.      
  412.       // If it's null, go to the next one.
  413.       if (!col) { continue }
  414.      
  415.       // If there's a width, use the width function.
  416.       if (col.width) {
  417.         column(col.width)(currentColumn)
  418.        
  419.       // Otherwise, create the column normally.
  420.       } else {
  421.         column(currentColumn)
  422.       }
  423.       for (item of col.items) {
  424.         const func = provideFunction(item)()
  425.         await func(currentColumn)
  426.       }
  427.     }
  428.     currentColumns = []
  429.   }
  430. }
  431.  
  432. /*
  433.  * LAYOUT FUNCTIONS
  434.  * These functions manage spacing and alignment.
  435.  * =============================================
  436.  */
  437.  
  438. // Makes a new row on the widget.
  439. function row(input = null) {
  440.  
  441.   function makeRow() {
  442.     currentRow = widget.addStack()
  443.     currentRow.layoutHorizontally()
  444.     currentRow.setPadding(0, 0, 0, 0)
  445.     currentColumn.spacing = 0
  446.    
  447.     // If input was given, make a column of that size.
  448.     if (input > 0) { currentRow.size = new Size(0,input) }
  449.   }
  450.  
  451.   // If there's no input or it's a number, it's being called in the layout declaration.
  452.   if (!input || typeof input == "number") { return makeRow }
  453.  
  454.   // Otherwise, it's being called in the generator.
  455.   else { makeRow() }
  456. }
  457.  
  458. // Makes a new column on the widget.
  459. function column(input = null) {
  460.  
  461.   function makeColumn() {
  462.     currentColumn = currentRow.addStack()
  463.     currentColumn.layoutVertically()
  464.     currentColumn.setPadding(0, 0, 0, 0)
  465.     currentColumn.spacing = 0
  466.    
  467.     // If input was given, make a column of that size.
  468.     if (input > 0) { currentColumn.size = new Size(input,0) }
  469.   }
  470.  
  471.   // If there's no input or it's a number, it's being called in the layout declaration.
  472.   if (!input || typeof input == "number") { return makeColumn }
  473.  
  474.   // Otherwise, it's being called in the generator.
  475.   else { makeColumn() }
  476. }
  477.  
  478. // Create an aligned stack to add content to.
  479. function align(column) {
  480.  
  481.   // Add the containing stack to the column.
  482.   let alignmentStack = column.addStack()
  483.   alignmentStack.layoutHorizontally()
  484.  
  485.   // Get the correct stack from the alignment function.
  486.   let returnStack = currentAlignment(alignmentStack)
  487.   returnStack.layoutVertically()
  488.   return returnStack
  489. }
  490.  
  491. // Create a right-aligned stack.
  492. function alignRight(alignmentStack) {
  493.   alignmentStack.addSpacer()
  494.   let returnStack = alignmentStack.addStack()
  495.   return returnStack
  496. }
  497.  
  498. // Create a left-aligned stack.
  499. function alignLeft(alignmentStack) {
  500.   let returnStack = alignmentStack.addStack()
  501.   alignmentStack.addSpacer()
  502.   return returnStack
  503. }
  504.  
  505. // Create a center-aligned stack.
  506. function alignCenter(alignmentStack) {
  507.   alignmentStack.addSpacer()
  508.   let returnStack = alignmentStack.addStack()
  509.   alignmentStack.addSpacer()
  510.   return returnStack
  511. }
  512.  
  513. // This function adds a space, with an optional amount.
  514. function space(input = null) {
  515.  
  516.   // This function adds a spacer with the input width.
  517.   function spacer(column) {
  518.  
  519.     // If the input is null or zero, add a flexible spacer.
  520.     if (!input || input == 0) { column.addSpacer() }
  521.    
  522.     // Otherwise, add a space with the specified length.
  523.     else { column.addSpacer(input) }
  524.   }
  525.  
  526.   // If there's no input or it's a number, it's being called in the column declaration.
  527.   if (!input || typeof input == "number") { return spacer }
  528.  
  529.   // Otherwise, it's being called in the column generator.
  530.   else { input.addSpacer() }
  531. }
  532.  
  533. // Change the current alignment to right.
  534. function right(x) { currentAlignment = alignRight }
  535.  
  536. // Change the current alignment to left.
  537. function left(x) { currentAlignment = alignLeft }
  538.  
  539. // Change the current alignment to center.
  540. function center(x) { currentAlignment = alignCenter }
  541.  
  542. /*
  543.  * SETUP FUNCTIONS
  544.  * These functions prepare data needed for items.
  545.  * ==============================================
  546.  */
  547.  
  548. // Set up the eventData object.
  549. async function setupEvents() {
  550.  
  551.   eventData = {}
  552.   const calendars = eventSettings.selectCalendars
  553.   const numberOfEvents = eventSettings.numberOfEvents
  554.  
  555.   // Function to determine if an event should be shown.
  556.   function shouldShowEvent(event) {
  557.  
  558.     // If events are filtered and the calendar isn't in the selected calendars, return false.
  559.     if (calendars.length && !calendars.includes(event.calendar.title)) { return false }
  560.  
  561.     // Hack to remove canceled Office 365 events.
  562.     if (event.title.startsWith("Canceled:")) { return false }
  563.  
  564.     // If it's an all-day event, only show if the setting is active.
  565.     if (event.isAllDay) { return eventSettings.showAllDay }
  566.  
  567.     // Otherwise, return the event if it's in the future.
  568.     return (event.startDate.getTime() > currentDate.getTime())
  569.   }
  570.  
  571.   // Determine which events to show, and how many.
  572.   const todayEvents = await CalendarEvent.today([])
  573.   let shownEvents = 0
  574.   let futureEvents = []
  575.  
  576.   for (const event of todayEvents) {
  577.     if (shownEvents == numberOfEvents) { break }
  578.     if (shouldShowEvent(event)) {
  579.       futureEvents.push(event)
  580.       shownEvents++
  581.     }
  582.   }
  583.  
  584.   // If there's room and we need to, show tomorrow's events.
  585.   let multipleTomorrowEvents = false
  586.   if (eventSettings.showTomorrow && shownEvents < numberOfEvents) {
  587.  
  588.     const tomorrowEvents = await CalendarEvent.tomorrow([])
  589.     for (const event of tomorrowEvents) {
  590.       if (shownEvents == numberOfEvents) { break }
  591.       if (shouldShowEvent(event)) {
  592.      
  593.         // Add the tomorrow label prior to the first tomorrow event.
  594.         if (!multipleTomorrowEvents) {
  595.          
  596.           // The tomorrow label is pretending to be an event.
  597.           futureEvents.push({ title: localizedText.tomorrowLabel.toUpperCase(), isLabel: true })
  598.           multipleTomorrowEvents = true
  599.         }
  600.        
  601.         // Show the tomorrow event and increment the counter.
  602.         futureEvents.push(event)
  603.         shownEvents++
  604.       }
  605.     }
  606.   }
  607.  
  608.   // Store the future events, and whether or not any events are displayed.
  609.   eventData.futureEvents = futureEvents
  610.   eventData.eventsAreVisible = (futureEvents.length > 0) && (eventSettings.numberOfEvents > 0)
  611. }
  612.  
  613. // Set up the gradient for the widget background.
  614. async function setupGradient() {
  615.  
  616.   // Requirements: sunrise
  617.   if (!sunData) { await setupSunrise() }
  618.  
  619.   let gradient = {
  620.     dawn: {
  621.       color() { return [new Color("142C52"), new Color("1B416F"), new Color("62668B")] },
  622.       position() { return [0, 0.5, 1] },
  623.     },
  624.  
  625.     sunrise: {
  626.       color() { return [new Color("274875"), new Color("766f8d"), new Color("f0b35e")] },
  627.       position() { return [0, 0.8, 1.5] },
  628.     },
  629.  
  630.     midday: {
  631.       color() { return [new Color("3a8cc1"), new Color("90c0df")] },
  632.       position() { return [0, 1] },
  633.     },
  634.  
  635.     noon: {
  636.       color() { return [new Color("b2d0e1"), new Color("80B5DB"), new Color("3a8cc1")] },
  637.       position() { return [-0.2, 0.2, 1.5] },
  638.     },
  639.  
  640.     sunset: {
  641.       color() { return [new Color("32327A"), new Color("662E55"), new Color("7C2F43")] },
  642.       position() { return [0.1, 0.9, 1.2] },
  643.     },
  644.  
  645.     twilight: {
  646.       color() { return [new Color("021033"), new Color("16296b"), new Color("414791")] },
  647.       position() { return [0, 0.5, 1] },
  648.     },
  649.  
  650.     night: {
  651.       color() { return [new Color("16296b"), new Color("021033"), new Color("021033"), new Color("113245")] },
  652.       position() { return [-0.5, 0.2, 0.5, 1] },
  653.     },
  654.   }
  655.  
  656.   const sunrise = sunData.sunrise
  657.   const sunset = sunData.sunset
  658.  
  659.   // Use sunrise or sunset if we're within 30min of it.
  660.   if (closeTo(sunrise)<=15) { return gradient.sunrise }
  661.   if (closeTo(sunset)<=15) { return gradient.sunset }
  662.  
  663.   // In the 30min before/after, use dawn/twilight.
  664.   if (closeTo(sunrise)<=45 && currentDate.getTime() < sunrise) { return gradient.dawn }
  665.   if (closeTo(sunset)<=45 && currentDate.getTime() > sunset) { return gradient.twilight }
  666.  
  667.   // Otherwise, if it's night, return night.
  668.   if (isNight(currentDate)) { return gradient.night }
  669.  
  670.   // If it's around noon, the sun is high in the sky.
  671.   if (currentDate.getHours() == 12) { return gradient.noon }
  672.  
  673.   // Otherwise, return the "typical" theme.
  674.   return gradient.midday
  675. }
  676.  
  677. // Set up the locationData object.
  678. async function setupLocation() {
  679.  
  680.   locationData = {}
  681.   const locationPath = files.joinPath(files.documentsDirectory(), "weather-cal-loc")
  682.  
  683.   // If our location is unlocked or cache doesn't exist, ask iOS for location.
  684.   var readLocationFromFile = false
  685.   if (!lockLocation || !files.fileExists(locationPath)) {
  686.     try {
  687.       const location = await Location.current()
  688.       const geocode = await Location.reverseGeocode(location.latitude, location.longitude, locale)
  689.       locationData.latitude = location.latitude
  690.       locationData.longitude = location.longitude
  691.       locationData.locality = geocode[0].locality
  692.       files.writeString(locationPath, location.latitude + "|" + location.longitude + "|" + locationData.locality)
  693.    
  694.     } catch(e) {
  695.       // If we fail in unlocked mode, read it from the cache.
  696.       if (!lockLocation) { readLocationFromFile = true }
  697.      
  698.       // We can't recover if we fail on first run in locked mode.
  699.       else { return }
  700.     }
  701.   }
  702.  
  703.   // If our location is locked or we need to read from file, do it.
  704.   if (lockLocation || readLocationFromFile) {
  705.     const locationStr = files.readString(locationPath).split("|")
  706.     locationData.latitude = locationStr[0]
  707.     locationData.longitude = locationStr[1]
  708.     locationData.locality = locationStr[2]
  709.   }
  710. }
  711.  
  712. // Set up the sunData object.
  713. async function setupSunrise() {
  714.  
  715.   // Requirements: location
  716.   if (!locationData) { await setupLocation() }
  717.  
  718.   async function getSunData(date) {
  719.     const req = "https://api.sunrise-sunset.org/json?lat=" + locationData.latitude + "&lng=" + locationData.longitude + "&formatted=0&date=" + date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate()
  720.     const data = await new Request(req).loadJSON()
  721.     return data
  722.   }
  723.  
  724.   // Set up the sunrise/sunset cache.
  725.   const sunCachePath = files.joinPath(files.documentsDirectory(), "weather-cal-sunrise")
  726.   const sunCacheExists = files.fileExists(sunCachePath)
  727.   const sunCacheDate = sunCacheExists ? files.modificationDate(sunCachePath) : 0
  728.   let sunDataRaw
  729.  
  730.   // If cache exists and was created today, use cached data.
  731.   if (sunCacheExists && sameDay(currentDate, sunCacheDate)) {
  732.     const sunCache = files.readString(sunCachePath)
  733.     sunDataRaw = JSON.parse(sunCache)
  734.   }
  735.  
  736.   // Otherwise, get the data from the server.
  737.   else {
  738.  
  739.     sunDataRaw = await getSunData(currentDate)
  740.  
  741.     // Calculate tomorrow's date and get tomorrow's data.
  742.     let tomorrowDate = new Date()
  743.     tomorrowDate.setDate(currentDate.getDate() + 1)
  744.     const tomorrowData = await getSunData(tomorrowDate)
  745.     sunDataRaw.results.tomorrow = tomorrowData.results.sunrise
  746.    
  747.     // Cache the file.
  748.     files.writeString(sunCachePath, JSON.stringify(sunDataRaw))
  749.   }
  750.  
  751.   // Store the timing values.
  752.   sunData = {}
  753.   sunData.sunrise = new Date(sunDataRaw.results.sunrise).getTime()
  754.   sunData.sunset = new Date(sunDataRaw.results.sunset).getTime()
  755.   sunData.tomorrow = new Date(sunDataRaw.results.tomorrow).getTime()
  756. }
  757.  
  758. // Set up the weatherData object.
  759. async function setupWeather() {
  760.  
  761.   // Requirements: location
  762.   if (!locationData) { await setupLocation() }
  763.  
  764.   // Set up the cache.
  765.   const cachePath = files.joinPath(files.documentsDirectory(), "weather-cal-cache")
  766.   const cacheExists = files.fileExists(cachePath)
  767.   const cacheDate = cacheExists ? files.modificationDate(cachePath) : 0
  768.   var weatherDataRaw
  769.  
  770.   // If cache exists and it's been less than 60 seconds since last request, use cached data.
  771.   if (cacheExists && (currentDate.getTime() - cacheDate.getTime()) < 60000) {
  772.     const cache = files.readString(cachePath)
  773.     weatherDataRaw = JSON.parse(cache)
  774.  
  775.   // Otherwise, use the API to get new weather data.
  776.   } else {
  777.     const weatherReq = "https://api.openweathermap.org/data/2.5/onecall?lat=" + locationData.latitude + "&lon=" + locationData.longitude + "&exclude=minutely,alerts&units=" + weatherSettings.units + "&lang=" + locale + "&appid=" + apiKey
  778.     weatherDataRaw = await new Request(weatherReq).loadJSON()
  779.     files.writeString(cachePath, JSON.stringify(weatherDataRaw))
  780.   }
  781.  
  782.   // Store the weather values.
  783.   weatherData = {}
  784.   weatherData.currentTemp = weatherDataRaw.current.temp
  785.   weatherData.currentCondition = weatherDataRaw.current.weather[0].id
  786.   weatherData.currentDescription = weatherDataRaw.current.weather[0].main
  787.   weatherData.todayHigh = weatherDataRaw.daily[0].temp.max
  788.   weatherData.todayLow = weatherDataRaw.daily[0].temp.min
  789.  
  790.   weatherData.nextHourTemp = weatherDataRaw.hourly[1].temp
  791.   weatherData.nextHourCondition = weatherDataRaw.hourly[1].weather[0].id
  792.  
  793.   weatherData.tomorrowHigh = weatherDataRaw.daily[1].temp.max
  794.   weatherData.tomorrowLow = weatherDataRaw.daily[1].temp.min
  795.   weatherData.tomorrowCondition = weatherDataRaw.daily[1].weather[0].id
  796. }
  797.  
  798. /*
  799.  * WIDGET ITEMS
  800.  * These functions display items on the widget.
  801.  * ============================================
  802.  */
  803.  
  804. // Display the date on the widget.
  805. async function date(column) {
  806.  
  807.   // Requirements: events (if dynamicDateSize is enabled)
  808.   if (!eventData && dateSettings.dynamicDateSize) { await setupEvents() }
  809.  
  810.   // Set up the date formatter and set its locale.
  811.   let df = new DateFormatter()
  812.   df.locale = locale
  813.  
  814.   // Show small if it's hard coded, or if it's dynamic and events are visible.
  815.   if (dateSettings.staticDateSize == "small" || (dateSettings.dynamicDateSize && eventData.eventsAreVisible)) {
  816.     let dateStack = align(column)
  817.     dateStack.setPadding(padding, padding, padding, padding)
  818.  
  819.     df.dateFormat = dateSettings.smallDateFormat
  820.     let dateText = provideText(df.string(currentDate), dateStack, textFormat.smallDate)
  821.    
  822.   // Otherwise, show the large date.
  823.   } else {
  824.     let dateOneStack = align(column)
  825.     df.dateFormat = dateSettings.largeDateLineOne
  826.     let dateOne = provideText(df.string(currentDate), dateOneStack, textFormat.largeDate1)
  827.     dateOneStack.setPadding(padding/2, padding, 0, padding)
  828.    
  829.     let dateTwoStack = align(column)
  830.     df.dateFormat = dateSettings.largeDateLineTwo
  831.     let dateTwo = provideText(df.string(currentDate), dateTwoStack, textFormat.largeDate2)
  832.     dateTwoStack.setPadding(0, padding, padding, padding)
  833.   }
  834. }
  835.  
  836. // Display a time-based greeting on the widget.
  837. async function greeting(column) {
  838.  
  839.   // This function makes a greeting based on the time of day.
  840.   function makeGreeting() {
  841.     const hour = currentDate.getHours()
  842.     if (hour    < 5)  { return localizedText.nightGreeting }
  843.     if (hour    < 12) { return localizedText.morningGreeting }
  844.     if (hour-12 < 5)  { return localizedText.afternoonGreeting }
  845.     if (hour-12 < 10) { return localizedText.eveningGreeting }
  846.     return localizedText.nightGreeting
  847.   }
  848.  
  849.   // Set up the greeting.
  850.   let greetingStack = align(column)
  851.   let greeting = provideText(makeGreeting(), greetingStack, textFormat.greeting)
  852.   greetingStack.setPadding(padding, padding, padding, padding)
  853. }
  854.  
  855. // Display events on the widget.
  856. async function events(column) {
  857.  
  858.   // Requirements: events
  859.   if (!eventData) { await setupEvents() }
  860.  
  861.   // If no events are visible, figure out what to do.
  862.   if (!eventData.eventsAreVisible) {
  863.     const display = eventSettings.noEventBehavior
  864.    
  865.     // If it's a greeting, let the greeting function handle it.
  866.     if (display == "greeting") { return await greeting(column) }
  867.    
  868.     // If it's a message, get the localized text.
  869.     if (display == "message" && localizedText.noEventMessage.length) {
  870.       const messageStack = align(column)
  871.       messageStack.setPadding(padding, padding, padding, padding)
  872.       provideText(localizedText.noEventMessage, messageStack, textFormat.noEvents)
  873.     }
  874.    
  875.     // Whether or not we displayed something, return here.
  876.     return
  877.   }
  878.  
  879.   // Set up the event stack.
  880.   let eventStack = column.addStack()
  881.   eventStack.layoutVertically()
  882.   const todaySeconds = Math.floor(currentDate.getTime() / 1000) - 978307200
  883.   eventStack.url = 'calshow:' + todaySeconds
  884.  
  885.   // If there are no events and we have a message, show it and return.
  886.   if (!eventData.eventsAreVisible && localizedText.noEventMessage.length) {
  887.     let message = provideText(localizedText.noEventMessage, eventStack, textFormat.noEvents)
  888.     eventStack.setPadding(padding, padding, padding, padding)
  889.     return
  890.   }
  891.  
  892.   // If we're not showing the message, don't pad the event stack.
  893.   eventStack.setPadding(0, 0, 0, 0)
  894.  
  895.   // Add each event to the stack.
  896.   var currentStack = eventStack
  897.   const futureEvents = eventData.futureEvents
  898.   for (let i = 0; i < futureEvents.length; i++) {
  899.    
  900.     const event = futureEvents[i]
  901.     const bottomPadding = (padding-10 < 0) ? 0 : padding-10
  902.    
  903.     // If it's the tomorrow label, change to the tomorrow stack.
  904.     if (event.isLabel) {
  905.       let tomorrowStack = column.addStack()
  906.       tomorrowStack.layoutVertically()
  907.       const tomorrowSeconds = Math.floor(currentDate.getTime() / 1000) - 978220800
  908.       tomorrowStack.url = 'calshow:' + tomorrowSeconds
  909.       currentStack = tomorrowStack
  910.      
  911.       // Mimic the formatting of an event title, mostly.
  912.       const eventLabelStack = align(currentStack)
  913.       const eventLabel = provideText(event.title, eventLabelStack, textFormat.eventLabel)
  914.       eventLabelStack.setPadding(padding, padding, padding, padding)
  915.       continue
  916.     }
  917.    
  918.     const titleStack = align(currentStack)
  919.     titleStack.layoutHorizontally()
  920.     const showCalendarColor = eventSettings.showCalendarColor
  921.     const colorShape = showCalendarColor.includes("circle") ? "circle" : "rectangle"
  922.    
  923.     // If we're showing a color, and it's not shown on the right, add it to the left.
  924.     if (showCalendarColor.length && !showCalendarColor.includes("right")) {
  925.       let colorItemText = provideTextSymbol(colorShape) + " "
  926.       let colorItem = provideText(colorItemText, titleStack, textFormat.eventTitle)
  927.       colorItem.textColor = event.calendar.color
  928.     }
  929.  
  930.     const title = provideText(event.title.trim(), titleStack, textFormat.eventTitle)
  931.     titleStack.setPadding(padding, padding, event.isAllDay ? padding : padding/5, padding)
  932.    
  933.     // If we're showing a color on the right, show it.
  934.     if (showCalendarColor.length && showCalendarColor.includes("right")) {
  935.       let colorItemText = " " + provideTextSymbol(colorShape)
  936.       let colorItem = provideText(colorItemText, titleStack, textFormat.eventTitle)
  937.       colorItem.textColor = event.calendar.color
  938.     }
  939.  
  940.     // If there are too many events, limit the line height.
  941.     if (futureEvents.length >= 3) { title.lineLimit = 1 }
  942.  
  943.     // If it's an all-day event, we don't need a time.
  944.     if (event.isAllDay) { continue }
  945.    
  946.     // Format the time information.
  947.     let timeText = formatTime(event.startDate)
  948.    
  949.     // If we show the length as time, add an en dash and the time.
  950.     if (eventSettings.showEventLength == "time") {
  951.       timeText += "–" + formatTime(event.endDate)
  952.      
  953.     // If we should it as a duration, add the minutes.
  954.     } else if (eventSettings.showEventLength == "duration") {
  955.       const duration = (event.endDate.getTime() - event.startDate.getTime()) / (1000*60)
  956.       const hours = Math.floor(duration/60)
  957.       const minutes = Math.floor(duration % 60)
  958.       const hourText = hours>0 ? hours + localizedText.durationHour : ""
  959.       const minuteText = minutes>0 ? minutes + localizedText.durationMinute : ""
  960.       const showSpace = hourText.length && minuteText.length
  961.       timeText += " \u2022 " + hourText + (showSpace ? " " : "") + minuteText
  962.     }
  963.  
  964.     const timeStack = align(currentStack)
  965.     const time = provideText(timeText, timeStack, textFormat.eventTime)
  966.     timeStack.setPadding(0, padding, padding, padding)
  967.   }
  968. }
  969.  
  970. // Display the current weather.
  971. async function current(column) {
  972.  
  973.   // Requirements: weather and sunrise
  974.   if (!weatherData) { await setupWeather() }
  975.   if (!sunData) { await setupSunrise() }
  976.  
  977.   // Set up the current weather stack.
  978.   let currentWeatherStack = column.addStack()
  979.   currentWeatherStack.layoutVertically()
  980.   currentWeatherStack.setPadding(0, 0, 0, 0)
  981.   currentWeatherStack.url = "https://weather.com/weather/today/l/" + locationData.latitude + "," + locationData.longitude
  982.  
  983.   // If we're showing the location, add it.
  984.   if (weatherSettings.showLocation) {
  985.     let locationTextStack = align(currentWeatherStack)
  986.     let locationText = provideText(locationData.locality, locationTextStack, textFormat.smallTemp)
  987.     locationTextStack.setPadding(padding, padding, padding, padding)
  988.   }
  989.  
  990.   // Show the current condition symbol.
  991.   let mainConditionStack = align(currentWeatherStack)
  992.   let mainCondition = mainConditionStack.addImage(provideConditionSymbol(weatherData.currentCondition,isNight(currentDate)))
  993.   mainCondition.imageSize = new Size(22,22)
  994.   tintIcon(mainCondition, textFormat.largeTemp)
  995.   mainConditionStack.setPadding(weatherSettings.showLocation ? 0 : padding, padding, 0, padding)
  996.  
  997.   // If we're showing the description, add it.
  998.   if (weatherSettings.showCondition) {
  999.     let conditionTextStack = align(currentWeatherStack)
  1000.     let conditionText = provideText(weatherData.currentDescription, conditionTextStack, textFormat.smallTemp)
  1001.     conditionTextStack.setPadding(padding, padding, 0, padding)
  1002.   }
  1003.  
  1004.   // Show the current temperature.
  1005.   const tempStack = align(currentWeatherStack)
  1006.   tempStack.setPadding(0, padding, 0, padding)
  1007.   const tempText = Math.round(weatherData.currentTemp) + "°"
  1008.   const temp = provideText(tempText, tempStack, textFormat.largeTemp)
  1009.  
  1010.   // If we're not showing the high and low, end it here.
  1011.   if (!weatherSettings.showHighLow) { return }
  1012.  
  1013.   // Show the temp bar and high/low values.
  1014.   let tempBarStack = align(currentWeatherStack)
  1015.   tempBarStack.layoutVertically()
  1016.   tempBarStack.setPadding(0, padding, padding, padding)
  1017.  
  1018.   let tempBar = drawTempBar()
  1019.   let tempBarImage = tempBarStack.addImage(tempBar)
  1020.   tempBarImage.size = new Size(50,0)
  1021.  
  1022.   tempBarStack.addSpacer(1)
  1023.  
  1024.   let highLowStack = tempBarStack.addStack()
  1025.   highLowStack.layoutHorizontally()
  1026.  
  1027.   const mainLowText = Math.round(weatherData.todayLow).toString()
  1028.   const mainLow = provideText(mainLowText, highLowStack, textFormat.tinyTemp)
  1029.   highLowStack.addSpacer()
  1030.   const mainHighText = Math.round(weatherData.todayHigh).toString()
  1031.   const mainHigh = provideText(mainHighText, highLowStack, textFormat.tinyTemp)
  1032.  
  1033.   tempBarStack.size = new Size(60,30)
  1034. }
  1035.  
  1036. // Display upcoming weather.
  1037. async function future(column) {
  1038.  
  1039.   // Requirements: weather and sunrise
  1040.   if (!weatherData) { await setupWeather() }
  1041.   if (!sunData) { await setupSunrise() }
  1042.  
  1043.   // Set up the future weather stack.
  1044.   let futureWeatherStack = column.addStack()
  1045.   futureWeatherStack.layoutVertically()
  1046.   futureWeatherStack.setPadding(0, 0, 0, 0)
  1047.   futureWeatherStack.url = "https://weather.com/weather/tenday/l/" + locationData.latitude + "," + locationData.longitude
  1048.  
  1049.   // Determine if we should show the next hour.
  1050.   const showNextHour = (currentDate.getHours() < weatherSettings.tomorrowShownAtHour)
  1051.  
  1052.   // Set the label value.
  1053.   const subLabelStack = align(futureWeatherStack)
  1054.   const subLabelText = showNextHour ? localizedText.nextHourLabel : localizedText.tomorrowLabel
  1055.   const subLabel = provideText(subLabelText, subLabelStack, textFormat.smallTemp)
  1056.   subLabelStack.setPadding(0, padding, padding/2, padding)
  1057.  
  1058.   // Set up the sub condition stack.
  1059.   let subConditionStack = align(futureWeatherStack)
  1060.   subConditionStack.layoutHorizontally()
  1061.   subConditionStack.centerAlignContent()
  1062.   subConditionStack.setPadding(0, padding, padding, padding)
  1063.  
  1064.   // Determine if it will be night in the next hour.
  1065.   var nightCondition
  1066.   if (showNextHour) {
  1067.     const addHour = currentDate.getTime() + (60*60*1000)
  1068.     const newDate = new Date(addHour)
  1069.     nightCondition = isNight(newDate)
  1070.   } else {
  1071.     nightCondition = false
  1072.   }
  1073.  
  1074.   let subCondition = subConditionStack.addImage(provideConditionSymbol(showNextHour ? weatherData.nextHourCondition : weatherData.tomorrowCondition,nightCondition))
  1075.   const subConditionSize = showNextHour ? 14 : 18
  1076.   subCondition.imageSize = new Size(subConditionSize, subConditionSize)
  1077.   tintIcon(subCondition, textFormat.smallTemp)
  1078.   subConditionStack.addSpacer(5)
  1079.  
  1080.   // The next part of the display changes significantly for next hour vs tomorrow.
  1081.   if (showNextHour) {
  1082.     const subTempText = Math.round(weatherData.nextHourTemp) + "°"
  1083.     const subTemp = provideText(subTempText, subConditionStack, textFormat.smallTemp)
  1084.    
  1085.   } else {
  1086.     let tomorrowLine = subConditionStack.addImage(drawVerticalLine(new Color(textFormat.tinyTemp.color || textFormat.defaultText.color, 0.5), 20))
  1087.     tomorrowLine.imageSize = new Size(3,28)
  1088.     subConditionStack.addSpacer(5)
  1089.     let tomorrowStack = subConditionStack.addStack()
  1090.     tomorrowStack.layoutVertically()
  1091.    
  1092.     const tomorrowHighText = Math.round(weatherData.tomorrowHigh) + ""
  1093.     const tomorrowHigh = provideText(tomorrowHighText, tomorrowStack, textFormat.tinyTemp)
  1094.     tomorrowStack.addSpacer(4)
  1095.     const tomorrowLowText = Math.round(weatherData.tomorrowLow) + ""
  1096.     const tomorrowLow = provideText(tomorrowLowText, tomorrowStack, textFormat.tinyTemp)
  1097.   }
  1098. }
  1099.  
  1100. // Return a text-creation function.
  1101. function text(input = null) {
  1102.  
  1103.   function displayText(column) {
  1104.  
  1105.     // Don't do anything if the input is blank.
  1106.     if (!input || input == "") { return }
  1107.  
  1108.     // Otherwise, add the text.
  1109.     const textStack = align(column)
  1110.     textStack.setPadding(padding, padding, padding, padding)
  1111.     const textDisplay = provideText(input, textStack, textFormat.customText)
  1112.   }
  1113.   return displayText
  1114. }
  1115.  
  1116. // Add a battery element to the widget; consisting of a battery icon and percentage.
  1117. async function battery(column) {
  1118.  
  1119.   // Get battery level via Scriptable function and format it in a convenient way
  1120.   function getBatteryLevel() {
  1121.  
  1122.     const batteryLevel = Device.batteryLevel()
  1123.     const batteryPercentage = `${Math.round(batteryLevel * 100)}%`
  1124.  
  1125.     return batteryPercentage
  1126.   }
  1127.  
  1128.   const batteryLevel = Device.batteryLevel()
  1129.  
  1130.   // Set up the battery level item
  1131.   let batteryStack = align(column)
  1132.   batteryStack.layoutHorizontally()
  1133.   batteryStack.centerAlignContent()
  1134.  
  1135.   let batteryIcon = batteryStack.addImage(provideBatteryIcon())
  1136.   batteryIcon.imageSize = new Size(30,30)
  1137.  
  1138.   // Change the battery icon to red if battery level is <= 20 to match system behavior
  1139.   if ( Math.round(batteryLevel * 100) > 20 || Device.isCharging() ) {
  1140.  
  1141.     tintIcon(batteryIcon, textFormat.battery)
  1142.  
  1143.   } else {
  1144.  
  1145.     batteryIcon.tintColor = Color.red()
  1146.  
  1147.   }
  1148.  
  1149.   batteryStack.addSpacer(padding * 0.6)
  1150.  
  1151.   // Display the battery status
  1152.   let batteryInfo = provideText(getBatteryLevel(), batteryStack, textFormat.battery)
  1153.  
  1154.   batteryStack.setPadding(padding/2, padding, padding/2, padding)
  1155.  
  1156. }
  1157.  
  1158. // Show the sunrise or sunset time.
  1159. async function sunrise(column) {
  1160.  
  1161.   // Requirements: sunrise
  1162.   if (!sunData) { await setupSunrise() }
  1163.  
  1164.   const sunrise = sunData.sunrise
  1165.   const sunset = sunData.sunset
  1166.   const tomorrow = sunData.tomorrow
  1167.   const current = currentDate.getTime()
  1168.  
  1169.   const showWithin = sunriseSettings.showWithin
  1170.   const closeToSunrise = closeTo(sunrise) <= showWithin
  1171.   const closeToSunset = closeTo(sunset) <= showWithin
  1172.  
  1173.   // If we only show sometimes and we're not close, return.
  1174.   if (showWithin > 0 && !closeToSunrise && !closeToSunset) { return }
  1175.  
  1176.   // Otherwise, determine which time to show.
  1177.   let timeToShow, symbolName
  1178.   const halfHour = 30 * 60 * 1000
  1179.  
  1180.   // If we're between sunrise and sunset, show the sunset.
  1181.   if (current > sunrise + halfHour && current < sunset + halfHour) {
  1182.     symbolName = "sunset.fill"
  1183.     timeToShow = sunset
  1184.   }
  1185.  
  1186.   // Otherwise, show a sunrise.
  1187.   else {
  1188.     symbolName = "sunrise.fill"
  1189.     timeToShow = current > sunset ? tomorrow : sunrise
  1190.   }
  1191.  
  1192.   // Set up the stack.
  1193.   const sunriseStack = align(column)
  1194.   sunriseStack.setPadding(padding/2, padding, padding/2, padding)
  1195.   sunriseStack.layoutHorizontally()
  1196.   sunriseStack.centerAlignContent()
  1197.  
  1198.   sunriseStack.addSpacer(padding * 0.3)
  1199.  
  1200.   // Add the correct symbol.
  1201.   const symbol = sunriseStack.addImage(SFSymbol.named(symbolName).image)
  1202.   symbol.imageSize = new Size(22,22)
  1203.   tintIcon(symbol, textFormat.sunrise)
  1204.  
  1205.   sunriseStack.addSpacer(padding)
  1206.  
  1207.   // Add the time.
  1208.   const timeText = formatTime(new Date(timeToShow))
  1209.   const time = provideText(timeText, sunriseStack, textFormat.sunrise)
  1210. }
  1211.  
  1212. // Allow for either term to be used.
  1213. async function sunset(column) {
  1214.   return await sunrise(column)
  1215. }
  1216.  
  1217. /*
  1218.  * HELPER FUNCTIONS
  1219.  * These functions perform duties for other functions.
  1220.  * ===================================================
  1221.  */
  1222.  
  1223. // Tints icons if needed.
  1224. function tintIcon(icon,format) {
  1225.   if (!tintIcons) { return }
  1226.   icon.tintColor = new Color(format.color || textFormat.defaultText.color)
  1227. }
  1228.  
  1229. // Determines if the provided date is at night.
  1230. function isNight(dateInput) {
  1231.   const timeValue = dateInput.getTime()
  1232.   return (timeValue < sunData.sunrise) || (timeValue > sunData.sunset)
  1233. }
  1234.  
  1235. // Determines if two dates occur on the same day
  1236. function sameDay(d1, d2) {
  1237.   return d1.getFullYear() === d2.getFullYear() &&
  1238.     d1.getMonth() === d2.getMonth() &&
  1239.     d1.getDate() === d2.getDate()
  1240. }
  1241.  
  1242. // Returns the number of minutes between now and the provided date.
  1243. function closeTo(time) {
  1244.   return Math.abs(currentDate.getTime() - time) / 60000
  1245. }
  1246.  
  1247. // Format the time for a Date input.
  1248. function formatTime(date) {
  1249.   let df = new DateFormatter()
  1250.   df.locale = locale
  1251.   df.useNoDateStyle()
  1252.   df.useShortTimeStyle()
  1253.   return df.string(date)
  1254. }
  1255.  
  1256. // Provide a text symbol with the specified shape.
  1257. function provideTextSymbol(shape) {
  1258.  
  1259.   // Rectangle character.
  1260.   if (shape.startsWith("rect")) {
  1261.     return "\u2759"
  1262.   }
  1263.   // Circle character.
  1264.   if (shape == "circle") {
  1265.     return "\u2B24"
  1266.   }
  1267.   // Default to the rectangle.
  1268.   return "\u2759"
  1269. }
  1270.  
  1271. // Provide a battery SFSymbol with accurate level drawn on top of it.
  1272. function provideBatteryIcon() {
  1273.  
  1274.   // If we're charging, show the charging icon.
  1275.   if (Device.isCharging()) { return SFSymbol.named("battery.100.bolt").image }
  1276.  
  1277.   // Set the size of the battery icon.
  1278.   const batteryWidth = 87
  1279.   const batteryHeight = 41
  1280.  
  1281.   // Start our draw context.
  1282.   let draw = new DrawContext()
  1283.   draw.opaque = false
  1284.   draw.respectScreenScale = true
  1285.   draw.size = new Size(batteryWidth, batteryHeight)
  1286.  
  1287.   // Draw the battery.
  1288.   draw.drawImageInRect(SFSymbol.named("battery.0").image, new Rect(0, 0, batteryWidth, batteryHeight))
  1289.  
  1290.   // Match the battery level values to the SFSymbol.
  1291.   const x = batteryWidth*0.1525
  1292.   const y = batteryHeight*0.247
  1293.   const width = batteryWidth*0.602
  1294.   const height = batteryHeight*0.505
  1295.  
  1296.   // Prevent unreadable icons.
  1297.   let level = Device.batteryLevel()
  1298.   if (level < 0.05) { level = 0.05 }
  1299.  
  1300.   // Determine the width and radius of the battery level.
  1301.   const current = width * level
  1302.   let radius = height/6.5
  1303.  
  1304.   // When it gets low, adjust the radius to match.
  1305.   if (current < (radius * 2)) { radius = current / 2 }
  1306.  
  1307.   // Make the path for the battery level.
  1308.   let barPath = new Path()
  1309.   barPath.addRoundedRect(new Rect(x, y, current, height), radius, radius)
  1310.   draw.addPath(barPath)
  1311.   const color = tintIcons ? (textFormat.battery.color || textFormat.defaultText.color) : "000000"
  1312.   draw.setFillColor(new Color(color))
  1313.   draw.fillPath()
  1314.   return draw.getImage()
  1315. }
  1316.  
  1317. // Provide a symbol based on the condition.
  1318. function provideConditionSymbol(cond,night) {
  1319.  
  1320.   // Define our symbol equivalencies.
  1321.   let symbols = {
  1322.  
  1323.     // Thunderstorm
  1324.     "2": function() { return "cloud.bolt.rain.fill" },
  1325.    
  1326.     // Drizzle
  1327.     "3": function() { return "cloud.drizzle.fill" },
  1328.    
  1329.     // Rain
  1330.     "5": function() { return (cond == 511) ? "cloud.sleet.fill" : "cloud.rain.fill" },
  1331.    
  1332.     // Snow
  1333.     "6": function() { return (cond >= 611 && cond <= 613) ? "cloud.snow.fill" : "snow" },
  1334.    
  1335.     // Atmosphere
  1336.     "7": function() {
  1337.       if (cond == 781) { return "tornado" }
  1338.       if (cond == 701 || cond == 741) { return "cloud.fog.fill" }
  1339.       return night ? "cloud.fog.fill" : "sun.haze.fill"
  1340.     },
  1341.    
  1342.     // Clear and clouds
  1343.     "8": function() {
  1344.       if (cond == 800 || cond == 801) { return night ? "moon.stars.fill" : "sun.max.fill" }
  1345.       if (cond == 802 || cond == 803) { return night ? "cloud.moon.fill" : "cloud.sun.fill" }
  1346.       return "cloud.fill"
  1347.     }
  1348.   }
  1349.  
  1350.   // Find out the first digit.
  1351.   let conditionDigit = Math.floor(cond / 100)
  1352.  
  1353.   // Get the symbol.
  1354.   return SFSymbol.named(symbols[conditionDigit]()).image
  1355. }
  1356.  
  1357. // Provide a font based on the input.
  1358. function provideFont(fontName, fontSize) {
  1359.   const fontGenerator = {
  1360.     "ultralight": function() { return Font.ultraLightSystemFont(fontSize) },
  1361.     "light": function() { return Font.lightSystemFont(fontSize) },
  1362.     "regular": function() { return Font.regularSystemFont(fontSize) },
  1363.     "medium": function() { return Font.mediumSystemFont(fontSize) },
  1364.     "semibold": function() { return Font.semiboldSystemFont(fontSize) },
  1365.     "bold": function() { return Font.boldSystemFont(fontSize) },
  1366.     "heavy": function() { return Font.heavySystemFont(fontSize) },
  1367.     "black": function() { return Font.blackSystemFont(fontSize) },
  1368.     "italic": function() { return Font.italicSystemFont(fontSize) }
  1369.   }
  1370.  
  1371.   const systemFont = fontGenerator[fontName]
  1372.   if (systemFont) { return systemFont() }
  1373.   return new Font(fontName, fontSize)
  1374. }
  1375.  
  1376. // Add formatted text to a container.
  1377. function provideText(string, container, format) {
  1378.   const textItem = container.addText(string)
  1379.   const textFont = format.font || textFormat.defaultText.font
  1380.   const textSize = format.size || textFormat.defaultText.size
  1381.   const textColor = format.color || textFormat.defaultText.color
  1382.  
  1383.   textItem.font = provideFont(textFont, textSize)
  1384.   textItem.textColor = new Color(textColor)
  1385.   return textItem
  1386. }
  1387.  
  1388. /*
  1389.  * DRAWING FUNCTIONS
  1390.  * These functions draw onto a canvas.
  1391.  * ===================================
  1392.  */
  1393.  
  1394. // Draw the vertical line in the tomorrow view.
  1395. function drawVerticalLine(color, height) {
  1396.  
  1397.   const width = 2
  1398.  
  1399.   let draw = new DrawContext()
  1400.   draw.opaque = false
  1401.   draw.respectScreenScale = true
  1402.   draw.size = new Size(width,height)
  1403.  
  1404.   let barPath = new Path()
  1405.   const barHeight = height
  1406.   barPath.addRoundedRect(new Rect(0, 0, width, height), width/2, width/2)
  1407.   draw.addPath(barPath)
  1408.   draw.setFillColor(color)
  1409.   draw.fillPath()
  1410.  
  1411.   return draw.getImage()
  1412. }
  1413.  
  1414. // Draw the temp bar.
  1415. function drawTempBar() {
  1416.  
  1417.   // Set the size of the temp bar.
  1418.   const tempBarWidth = 200
  1419.   const tempBarHeight = 20
  1420.  
  1421.   // Calculate the current percentage of the high-low range.
  1422.   let percent = (weatherData.currentTemp - weatherData.todayLow) / (weatherData.todayHigh - weatherData.todayLow)
  1423.  
  1424.   // If we're out of bounds, clip it.
  1425.   if (percent < 0) {
  1426.     percent = 0
  1427.   } else if (percent > 1) {
  1428.     percent = 1
  1429.   }
  1430.  
  1431.   // Determine the scaled x-value for the current temp.
  1432.   const currPosition = (tempBarWidth - tempBarHeight) * percent
  1433.  
  1434.   // Start our draw context.
  1435.   let draw = new DrawContext()
  1436.   draw.opaque = false
  1437.   draw.respectScreenScale = true
  1438.   draw.size = new Size(tempBarWidth, tempBarHeight)
  1439.  
  1440.   // Make the path for the bar.
  1441.   let barPath = new Path()
  1442.   const barHeight = tempBarHeight - 10
  1443.   barPath.addRoundedRect(new Rect(0, 5, tempBarWidth, barHeight), barHeight / 2, barHeight / 2)
  1444.   draw.addPath(barPath)
  1445.  
  1446.   // Determine the color.
  1447.   const barColor = textFormat.battery.color || textFormat.defaultText.color
  1448.   draw.setFillColor(new Color(textFormat.tinyTemp.color || textFormat.defaultText.color, 0.5))
  1449.   draw.fillPath()
  1450.  
  1451.   // Make the path for the current temp indicator.
  1452.   let currPath = new Path()
  1453.   currPath.addEllipse(new Rect(currPosition, 0, tempBarHeight, tempBarHeight))
  1454.   draw.addPath(currPath)
  1455.   draw.setFillColor(new Color(textFormat.tinyTemp.color || textFormat.defaultText.color, 1))
  1456.   draw.fillPath()
  1457.  
  1458.   return draw.getImage()
  1459. }
Advertisement
Add Comment
Please, Sign In to add comment