[json] Weather Widget

Viewer

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

Editor

You can edit this paste and save as new: