Guest User

Untitled

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