Guest User

minimal date weather events

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

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×