LiveActivity.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. import ActivityKit
  2. import Charts
  3. import Foundation
  4. import SwiftUI
  5. import WidgetKit
  6. private enum Size {
  7. case minimal
  8. case compact
  9. case expanded
  10. }
  11. enum GlucoseUnits: String, Equatable {
  12. case mgdL = "mg/dL"
  13. case mmolL = "mmol/L"
  14. static let exchangeRate: Decimal = 0.0555
  15. }
  16. enum GlucoseColorScheme: String, Equatable {
  17. case staticColor
  18. case dynamicColor
  19. }
  20. func rounded(_ value: Decimal, scale: Int, roundingMode: NSDecimalNumber.RoundingMode) -> Decimal {
  21. var result = Decimal()
  22. var toRound = value
  23. NSDecimalRound(&result, &toRound, scale, roundingMode)
  24. return result
  25. }
  26. extension Int {
  27. var asMmolL: Decimal {
  28. rounded(Decimal(self) * GlucoseUnits.exchangeRate, scale: 1, roundingMode: .plain)
  29. }
  30. var formattedAsMmolL: String {
  31. NumberFormatter.glucoseFormatter.string(from: asMmolL as NSDecimalNumber) ?? "\(asMmolL)"
  32. }
  33. }
  34. extension Decimal {
  35. var asMmolL: Decimal {
  36. rounded(self * GlucoseUnits.exchangeRate, scale: 1, roundingMode: .plain)
  37. }
  38. var asMgdL: Decimal {
  39. rounded(self / GlucoseUnits.exchangeRate, scale: 0, roundingMode: .plain)
  40. }
  41. var formattedAsMmolL: String {
  42. NumberFormatter.glucoseFormatter.string(from: asMmolL as NSDecimalNumber) ?? "\(asMmolL)"
  43. }
  44. }
  45. extension NumberFormatter {
  46. static let glucoseFormatter: NumberFormatter = {
  47. let formatter = NumberFormatter()
  48. formatter.locale = Locale.current
  49. formatter.numberStyle = .decimal
  50. formatter.minimumFractionDigits = 1
  51. formatter.maximumFractionDigits = 1
  52. return formatter
  53. }()
  54. }
  55. struct LiveActivity: Widget {
  56. // Helper function to decide how to pick the glucose color
  57. func getDynamicGlucoseColor(
  58. glucoseValue: Decimal,
  59. highGlucoseColorValue: Decimal,
  60. lowGlucoseColorValue: Decimal,
  61. targetGlucose: Decimal,
  62. glucoseColorScheme: String,
  63. offset: Decimal
  64. ) -> Color {
  65. // Convert Decimal to Int for high and low glucose values
  66. let lowGlucose = lowGlucoseColorValue - offset
  67. let highGlucose = highGlucoseColorValue + (offset * 1.75)
  68. let targetGlucose = targetGlucose
  69. print("glucoseValue: \(glucoseValue)")
  70. print("lowGlucose: \(lowGlucose)")
  71. print("highGlucose: \(highGlucose)")
  72. print("targetGlucose: \(targetGlucose)")
  73. print("glucoseColorScheme: \(glucoseColorScheme)")
  74. print("offset: \(offset)")
  75. // Only use calculateHueBasedGlucoseColor if the setting is enabled in preferences
  76. if glucoseColorScheme == "dynamicColor" {
  77. return calculateHueBasedGlucoseColor(
  78. glucoseValue: glucoseValue,
  79. highGlucose: highGlucose,
  80. lowGlucose: lowGlucose,
  81. targetGlucose: targetGlucose
  82. )
  83. }
  84. // Otheriwse, use static (orange = high, red = low, green = range)
  85. else {
  86. if glucoseValue > highGlucose {
  87. return Color.orange
  88. } else if glucoseValue < lowGlucose {
  89. return Color.red
  90. } else {
  91. return Color.green
  92. }
  93. }
  94. }
  95. // Dynamic color - Define the hue values for the key points
  96. // We'll shift color gradually one glucose point at a time
  97. // We'll shift through the rainbow colors of ROY-G-BIV from low to high
  98. // Start at red for lowGlucose, green for targetGlucose, and violet for highGlucose
  99. func calculateHueBasedGlucoseColor(
  100. glucoseValue: Decimal,
  101. highGlucose: Decimal,
  102. lowGlucose: Decimal,
  103. targetGlucose: Decimal
  104. ) -> Color {
  105. let redHue: CGFloat = 0.0 / 360.0 // 0 degrees
  106. let greenHue: CGFloat = 120.0 / 360.0 // 120 degrees
  107. let purpleHue: CGFloat = 270.0 / 360.0 // 270 degrees
  108. // Calculate the hue based on the bgLevel
  109. var hue: CGFloat
  110. if glucoseValue <= lowGlucose {
  111. hue = redHue
  112. } else if glucoseValue >= highGlucose {
  113. hue = purpleHue
  114. } else if glucoseValue <= targetGlucose {
  115. // Interpolate between red and green
  116. let ratio = CGFloat(truncating: (glucoseValue - lowGlucose) / (targetGlucose - lowGlucose) as NSNumber)
  117. hue = redHue + ratio * (greenHue - redHue)
  118. } else {
  119. // Interpolate between green and purple
  120. let ratio = CGFloat(truncating: (glucoseValue - targetGlucose) / (highGlucose - targetGlucose) as NSNumber)
  121. hue = greenHue + ratio * (purpleHue - greenHue)
  122. }
  123. // Return the color with full saturation and brightness
  124. let color = Color(hue: hue, saturation: 0.6, brightness: 0.9)
  125. return color
  126. }
  127. private let dateFormatter: DateFormatter = {
  128. var f = DateFormatter()
  129. f.dateStyle = .none
  130. f.timeStyle = .short
  131. return f
  132. }()
  133. private var bolusFormatter: NumberFormatter {
  134. let formatter = NumberFormatter()
  135. formatter.numberStyle = .decimal
  136. formatter.maximumFractionDigits = 2
  137. formatter.decimalSeparator = "."
  138. return formatter
  139. }
  140. private var carbsFormatter: NumberFormatter {
  141. let formatter = NumberFormatter()
  142. formatter.numberStyle = .decimal
  143. formatter.maximumFractionDigits = 0
  144. return formatter
  145. }
  146. @ViewBuilder private func changeLabel(context: ActivityViewContext<LiveActivityAttributes>) -> some View {
  147. if !context.state.change.isEmpty {
  148. Text(context.state.change).foregroundStyle(.primary.opacity(0.5)).font(.headline)
  149. .strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  150. } else {
  151. Text("--")
  152. }
  153. }
  154. @ViewBuilder func mealLabel(
  155. context: ActivityViewContext<LiveActivityAttributes>,
  156. additionalState: LiveActivityAttributes.ContentAdditionalState
  157. ) -> some View {
  158. HStack {
  159. VStack(alignment: .leading, spacing: 1, content: {
  160. HStack {
  161. Image(systemName: "fork.knife")
  162. .font(.title3)
  163. .foregroundColor(.yellow)
  164. }
  165. HStack {
  166. Image(systemName: "syringe.fill")
  167. .font(.title3)
  168. .foregroundColor(.blue)
  169. }
  170. })
  171. VStack(alignment: .trailing, spacing: 1, content: {
  172. HStack {
  173. Text(
  174. carbsFormatter.string(from: additionalState.cob as NSNumber) ?? "--"
  175. ).fontWeight(.bold).font(.headline).strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  176. Text(NSLocalizedString(" g", comment: "grams of carbs")).foregroundStyle(.secondary).font(.footnote)
  177. }
  178. HStack {
  179. Text(
  180. bolusFormatter.string(from: additionalState.iob as NSNumber) ?? "--"
  181. ).font(.headline).fontWeight(.bold).strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  182. Text(NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)"))
  183. .foregroundStyle(.secondary).font(.footnote)
  184. }
  185. })
  186. VStack(alignment: .trailing, spacing: 1, content: {
  187. if additionalState.isOverrideActive {
  188. Image(systemName: "person.crop.circle.fill.badge.checkmark")
  189. .font(.title3)
  190. }
  191. })
  192. }
  193. }
  194. @ViewBuilder func trend(context: ActivityViewContext<LiveActivityAttributes>) -> some View {
  195. if context.isStale {
  196. Text("--")
  197. } else {
  198. if let trendSystemImage = context.state.direction {
  199. Image(systemName: trendSystemImage)
  200. }
  201. }
  202. }
  203. private func expiredLabel() -> some View {
  204. Text("Live Activity Expired. Open Trio to Refresh")
  205. .minimumScaleFactor(0.01)
  206. }
  207. private func updatedLabel(context: ActivityViewContext<LiveActivityAttributes>) -> Text {
  208. let text = Text("Updated: \(dateFormatter.string(from: context.state.date))")
  209. .font(.caption2)
  210. if context.isStale {
  211. // foregroundStyle is not available in <iOS 17 hence the check here
  212. if #available(iOSApplicationExtension 17.0, *) {
  213. return text.bold().foregroundStyle(.red)
  214. } else {
  215. return text.bold().foregroundColor(.red)
  216. }
  217. } else {
  218. if #available(iOSApplicationExtension 17.0, *) {
  219. return text.bold().foregroundStyle(.secondary)
  220. } else {
  221. return text.bold().foregroundColor(.red)
  222. }
  223. }
  224. }
  225. @ViewBuilder private func bgLabel(
  226. context: ActivityViewContext<LiveActivityAttributes>,
  227. additionalState: LiveActivityAttributes.ContentAdditionalState
  228. ) -> some View {
  229. HStack(alignment: .center) {
  230. Text(context.state.bg)
  231. .fontWeight(.bold)
  232. .font(.largeTitle)
  233. .strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  234. Text(additionalState.unit).foregroundStyle(.secondary).font(.subheadline).offset(x: -5, y: 5)
  235. }
  236. }
  237. private func bgAndTrend(
  238. context: ActivityViewContext<LiveActivityAttributes>,
  239. size: Size,
  240. hasStaticColorScheme: Bool,
  241. glucoseColor: Color
  242. ) -> (some View, Int) {
  243. var characters = 0
  244. let bgText = context.state.bg
  245. characters += bgText.count
  246. // narrow mode is for the minimal dynamic island view
  247. // there is not enough space to show all three arrow there
  248. // and everything has to be squeezed together to some degree
  249. // only display the first arrow character
  250. var directionText: String?
  251. if let direction = context.state.direction {
  252. if size == .compact {
  253. directionText = String(direction[direction.startIndex ... direction.startIndex])
  254. } else {
  255. directionText = direction
  256. }
  257. characters += directionText!.count
  258. }
  259. let spacing: CGFloat
  260. switch size {
  261. case .minimal: spacing = -1
  262. case .compact: spacing = 0
  263. case .expanded: spacing = 3
  264. }
  265. let stack = HStack(spacing: spacing) {
  266. Text(bgText)
  267. .foregroundColor(hasStaticColorScheme ? .primary : glucoseColor)
  268. .strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  269. if let direction = directionText {
  270. let text = Text(direction)
  271. switch size {
  272. case .minimal:
  273. let scaledText = text.scaleEffect(x: 0.7, y: 0.7, anchor: .leading)
  274. scaledText.foregroundStyle(hasStaticColorScheme ? .primary : glucoseColor)
  275. case .compact:
  276. text.scaleEffect(x: 0.8, y: 0.8, anchor: .leading).padding(.trailing, -3)
  277. case .expanded:
  278. text.scaleEffect(x: 0.7, y: 0.7, anchor: .leading).padding(.trailing, -5)
  279. }
  280. }
  281. }
  282. .foregroundColor(context.isStale ? Color.primary.opacity(0.5) : (hasStaticColorScheme ? .primary : glucoseColor))
  283. return (stack, characters)
  284. }
  285. @ViewBuilder func trendArrow(
  286. context: ActivityViewContext<LiveActivityAttributes>,
  287. additionalState: LiveActivityAttributes.ContentAdditionalState
  288. ) -> some View {
  289. let gradient = LinearGradient(colors: [
  290. Color(red: 0.6235294118, green: 0.4235294118, blue: 0.9803921569),
  291. Color(red: 0.4862745098, green: 0.5450980392, blue: 0.9529411765),
  292. Color(red: 0.3411764706, green: 0.6666666667, blue: 0.9254901961),
  293. Color(red: 0.262745098, green: 0.7333333333, blue: 0.9137254902)
  294. ], startPoint: .leading, endPoint: .trailing)
  295. if !context.isStale {
  296. Image(systemName: "arrow.right")
  297. .font(.title)
  298. .rotationEffect(.degrees(additionalState.rotationDegrees))
  299. .foregroundStyle(gradient)
  300. }
  301. }
  302. @ViewBuilder func chart(
  303. context: ActivityViewContext<LiveActivityAttributes>,
  304. additionalState: LiveActivityAttributes.ContentAdditionalState
  305. ) -> some View {
  306. if context.isStale {
  307. Text("No data available")
  308. } else {
  309. // Determine scale
  310. let min = min(additionalState.chart.min() ?? 45, 40) - 20
  311. let max = max(additionalState.chart.max() ?? 270, 300) + 50
  312. let yAxisRuleMarkMin = additionalState.unit == "mg/dL" ? context.state.lowGlucose : context.state.lowGlucose
  313. .asMmolL
  314. let yAxisRuleMarkMax = additionalState.unit == "mg/dL" ? context.state.highGlucose : context.state.highGlucose
  315. .asMmolL
  316. // TODO: grab target from proper targets, do not hard code.
  317. let highColor = getDynamicGlucoseColor(
  318. glucoseValue: yAxisRuleMarkMax,
  319. highGlucoseColorValue: yAxisRuleMarkMax,
  320. lowGlucoseColorValue: yAxisRuleMarkMin,
  321. targetGlucose: additionalState.unit == "mg/dL" ? Decimal(90) : Decimal(90).asMmolL,
  322. glucoseColorScheme: context.state.glucoseColorScheme,
  323. offset: additionalState.unit == "mg/dL" ? Decimal(20) : Decimal(20).asMmolL
  324. )
  325. // TODO: grab target from proper targets, do not hard code.
  326. let lowColor = getDynamicGlucoseColor(
  327. glucoseValue: yAxisRuleMarkMin,
  328. highGlucoseColorValue: yAxisRuleMarkMax,
  329. lowGlucoseColorValue: yAxisRuleMarkMin,
  330. targetGlucose: additionalState.unit == "mg/dL" ? Decimal(90) : Decimal(90).asMmolL,
  331. glucoseColorScheme: context.state.glucoseColorScheme,
  332. offset: additionalState.unit == "mg/dL" ? Decimal(20) : Decimal(20).asMmolL
  333. )
  334. Chart {
  335. RuleMark(y: .value("High", yAxisRuleMarkMax))
  336. .foregroundStyle(highColor)
  337. .lineStyle(.init(lineWidth: 0.5, dash: [5]))
  338. RuleMark(y: .value("Low", yAxisRuleMarkMin))
  339. .foregroundStyle(lowColor)
  340. .lineStyle(.init(lineWidth: 0.5, dash: [5]))
  341. ForEach(additionalState.chart.indices, id: \.self) { index in
  342. let currentValue = additionalState.chart[index]
  343. let displayValue = additionalState.unit == "mg/dL" ? currentValue : currentValue.asMmolL
  344. // TODO: grab target from proper targets, do not hard code.
  345. let pointMarkColor = self.getDynamicGlucoseColor(
  346. glucoseValue: currentValue,
  347. highGlucoseColorValue: context.state.highGlucose,
  348. lowGlucoseColorValue: context.state.lowGlucose,
  349. targetGlucose: 90,
  350. glucoseColorScheme: context.state.glucoseColorScheme,
  351. offset: 20
  352. )
  353. let chartDate = additionalState.chartDate[index] ?? Date()
  354. let pointMark = PointMark(
  355. x: .value("Time", chartDate),
  356. y: .value("Value", displayValue)
  357. ).symbolSize(15)
  358. pointMark.foregroundStyle(pointMarkColor)
  359. }
  360. }
  361. .chartYAxis {
  362. AxisMarks(position: .trailing) { _ in
  363. AxisGridLine(stroke: .init(lineWidth: 0.2, dash: [2, 3])).foregroundStyle(Color.white)
  364. AxisValueLabel().foregroundStyle(.secondary).font(.footnote)
  365. }
  366. }
  367. .chartYScale(domain: additionalState.unit == "mg/dL" ? min ... max : min.asMmolL ... max.asMmolL)
  368. .chartXAxis {
  369. AxisMarks(position: .automatic) { _ in
  370. AxisGridLine(stroke: .init(lineWidth: 0.2, dash: [2, 3])).foregroundStyle(Color.white)
  371. }
  372. }
  373. }
  374. }
  375. @ViewBuilder func content(context: ActivityViewContext<LiveActivityAttributes>) -> some View {
  376. let hasStaticColorScheme = context.state.glucoseColorScheme == "staticColor"
  377. // TODO: grab target from proper targets, do not hard code.
  378. let glucoseColor = getDynamicGlucoseColor(
  379. glucoseValue: Decimal(string: context.state.bg) ?? 100,
  380. highGlucoseColorValue: context.state.highGlucose,
  381. lowGlucoseColorValue: context.state.lowGlucose,
  382. targetGlucose: 90,
  383. glucoseColorScheme: context.state.glucoseColorScheme,
  384. offset: 20
  385. )
  386. if let detailedViewState = context.state.detailedViewState {
  387. HStack(spacing: 12) {
  388. chart(context: context, additionalState: detailedViewState)
  389. .frame(maxWidth: UIScreen.main.bounds.width / 1.8)
  390. VStack(alignment: .leading) {
  391. Spacer()
  392. bgLabel(context: context, additionalState: detailedViewState)
  393. HStack {
  394. changeLabel(context: context)
  395. trendArrow(context: context, additionalState: detailedViewState)
  396. }
  397. mealLabel(context: context, additionalState: detailedViewState).padding(.bottom, 8)
  398. updatedLabel(context: context).padding(.bottom, 10)
  399. }
  400. }
  401. .privacySensitive()
  402. .padding(.all, 14)
  403. .imageScale(.small)
  404. .foregroundColor(Color.white)
  405. .activityBackgroundTint(Color.black.opacity(0.8))
  406. } else {
  407. Group {
  408. if context.state.isInitialState {
  409. // add vertical and horizontal spacers around the label to ensure that the live activity view gets filled completely
  410. HStack {
  411. Spacer()
  412. VStack {
  413. Spacer()
  414. expiredLabel()
  415. Spacer()
  416. }
  417. Spacer()
  418. }
  419. } else {
  420. HStack(spacing: 3) {
  421. bgAndTrend(
  422. context: context,
  423. size: .expanded,
  424. hasStaticColorScheme: hasStaticColorScheme,
  425. glucoseColor: glucoseColor
  426. ).0.font(.title)
  427. Spacer()
  428. VStack(alignment: .trailing, spacing: 5) {
  429. changeLabel(context: context).font(.title3)
  430. .foregroundStyle(hasStaticColorScheme ? .primary : glucoseColor)
  431. updatedLabel(context: context).font(.caption)
  432. .foregroundStyle(
  433. hasStaticColorScheme ? .primary
  434. .opacity(0.7) : glucoseColor
  435. )
  436. }
  437. }
  438. }
  439. }
  440. .privacySensitive()
  441. .padding(.all, 15)
  442. // Semantic BackgroundStyle and Color values work here. They adapt to the given interface style (light mode, dark mode)
  443. // Semantic UIColors do NOT (as of iOS 17.1.1). Like UIColor.systemBackgroundColor (it does not adapt to changes of the interface style)
  444. // The colorScheme environment varaible that is usually used to detect dark mode does NOT work here (it reports false values)
  445. .foregroundStyle(Color.primary)
  446. .background(BackgroundStyle.background.opacity(0.4))
  447. .activityBackgroundTint(Color.clear)
  448. }
  449. }
  450. func dynamicIsland(context: ActivityViewContext<LiveActivityAttributes>) -> DynamicIsland {
  451. let glucoseValueForColor = context.state.bg
  452. let highGlucose = context.state.highGlucose
  453. let lowGlucose = context.state.lowGlucose
  454. let hasStaticColorScheme = context.state.glucoseColorScheme == "staticColor"
  455. // TODO: grab target from proper targets, do not hard code.
  456. let glucoseColor = getDynamicGlucoseColor(
  457. glucoseValue: Decimal(string: glucoseValueForColor) ?? 100,
  458. highGlucoseColorValue: highGlucose,
  459. lowGlucoseColorValue: lowGlucose,
  460. targetGlucose: 90,
  461. glucoseColorScheme: context.state.glucoseColorScheme,
  462. offset: 20
  463. )
  464. print("Glucose color: \(glucoseColor)")
  465. return DynamicIsland {
  466. DynamicIslandExpandedRegion(.leading) {
  467. bgAndTrend(
  468. context: context,
  469. size: .expanded,
  470. hasStaticColorScheme: hasStaticColorScheme,
  471. glucoseColor: glucoseColor
  472. ).0.font(.title2).padding(.leading, 5)
  473. }
  474. DynamicIslandExpandedRegion(.trailing) {
  475. changeLabel(context: context).font(.title2).padding(.trailing, 5)
  476. .foregroundStyle(hasStaticColorScheme ? .primary : glucoseColor)
  477. }
  478. DynamicIslandExpandedRegion(.bottom) {
  479. if context.state.isInitialState {
  480. expiredLabel()
  481. } else if let detailedViewState = context.state.detailedViewState {
  482. chart(context: context, additionalState: detailedViewState)
  483. } else {
  484. Group {
  485. updatedLabel(context: context).font(.caption).foregroundStyle(Color.secondary)
  486. }
  487. .frame(
  488. maxHeight: .infinity,
  489. alignment: .bottom
  490. )
  491. }
  492. }
  493. DynamicIslandExpandedRegion(.center) {
  494. if context.state.detailedViewState != nil {
  495. updatedLabel(context: context).font(.caption).foregroundStyle(Color.secondary)
  496. }
  497. }
  498. } compactLeading: {
  499. bgAndTrend(context: context, size: .compact, hasStaticColorScheme: hasStaticColorScheme, glucoseColor: glucoseColor).0
  500. .padding(.leading, 4)
  501. } compactTrailing: {
  502. changeLabel(context: context).padding(.trailing, 4).foregroundStyle(hasStaticColorScheme ? .primary : glucoseColor)
  503. } minimal: {
  504. let (_label, characterCount) = bgAndTrend(
  505. context: context,
  506. size: .minimal,
  507. hasStaticColorScheme: hasStaticColorScheme,
  508. glucoseColor: glucoseColor
  509. )
  510. let label = _label.padding(.leading, 7).padding(.trailing, 3)
  511. if characterCount < 4 {
  512. label
  513. } else if characterCount < 5 {
  514. label.fontWidth(.condensed)
  515. } else {
  516. label.fontWidth(.compressed)
  517. }
  518. }
  519. .widgetURL(URL(string: "Trio://"))
  520. .keylineTint(hasStaticColorScheme ? Color.purple : glucoseColor)
  521. .contentMargins(.horizontal, 0, for: .minimal)
  522. .contentMargins(.trailing, 0, for: .compactLeading)
  523. .contentMargins(.leading, 0, for: .compactTrailing)
  524. }
  525. var body: some WidgetConfiguration {
  526. ActivityConfiguration(for: LiveActivityAttributes.self, content: self.content, dynamicIsland: self.dynamicIsland)
  527. }
  528. }
  529. private extension LiveActivityAttributes {
  530. static var preview: LiveActivityAttributes {
  531. LiveActivityAttributes(startDate: Date())
  532. }
  533. }
  534. private extension LiveActivityAttributes.ContentState {
  535. // 0 is the widest digit. Use this to get an upper bound on text width.
  536. // Use mmol/l notation with decimal point as well for the same reason, it uses up to 4 characters, while mg/dl uses up to 3
  537. static var testWide: LiveActivityAttributes.ContentState {
  538. LiveActivityAttributes.ContentState(
  539. bg: 00.0.description,
  540. direction: "→",
  541. change: "+0.0",
  542. date: Date(),
  543. highGlucose: 180,
  544. lowGlucose: 70,
  545. glucoseColorScheme: "staticColor",
  546. detailedViewState: nil,
  547. isInitialState: false
  548. )
  549. }
  550. static var testVeryWide: LiveActivityAttributes.ContentState {
  551. LiveActivityAttributes.ContentState(
  552. bg: "00.0",
  553. direction: "↑↑",
  554. change: "+0.0",
  555. date: Date(),
  556. highGlucose: 180,
  557. lowGlucose: 70,
  558. glucoseColorScheme: "staticColor",
  559. detailedViewState: nil,
  560. isInitialState: false
  561. )
  562. }
  563. static var testSuperWide: LiveActivityAttributes.ContentState {
  564. LiveActivityAttributes.ContentState(
  565. bg: "00.0",
  566. direction: "↑↑↑",
  567. change: "+0.0",
  568. date: Date(),
  569. highGlucose: 180,
  570. lowGlucose: 70,
  571. glucoseColorScheme: "staticColor",
  572. detailedViewState: nil,
  573. isInitialState: false
  574. )
  575. }
  576. // 2 characters for BG, 1 character for change is the minimum that will be shown
  577. static var testNarrow: LiveActivityAttributes.ContentState {
  578. LiveActivityAttributes.ContentState(
  579. bg: "00",
  580. direction: "↑",
  581. change: "+0",
  582. date: Date(),
  583. highGlucose: 180,
  584. lowGlucose: 70,
  585. glucoseColorScheme: "staticColor",
  586. detailedViewState: nil,
  587. isInitialState: false
  588. )
  589. }
  590. static var testMedium: LiveActivityAttributes.ContentState {
  591. LiveActivityAttributes.ContentState(
  592. bg: "000",
  593. direction: "↗︎",
  594. change: "+00",
  595. date: Date(),
  596. highGlucose: 180,
  597. lowGlucose: 70,
  598. glucoseColorScheme: "staticColor",
  599. detailedViewState: nil,
  600. isInitialState: false
  601. )
  602. }
  603. static var testExpired: LiveActivityAttributes.ContentState {
  604. LiveActivityAttributes.ContentState(
  605. bg: "--",
  606. direction: nil,
  607. change: "--",
  608. date: Date().addingTimeInterval(-60 * 60),
  609. highGlucose: 180,
  610. lowGlucose: 70,
  611. glucoseColorScheme: "staticColor",
  612. detailedViewState: nil,
  613. isInitialState: true
  614. )
  615. }
  616. }
  617. @available(iOS 17.0, iOSApplicationExtension 17.0, *)
  618. #Preview("Notification", as: .content, using: LiveActivityAttributes.preview) {
  619. LiveActivity()
  620. } contentStates: {
  621. LiveActivityAttributes.ContentState.testSuperWide
  622. LiveActivityAttributes.ContentState.testVeryWide
  623. LiveActivityAttributes.ContentState.testWide
  624. LiveActivityAttributes.ContentState.testMedium
  625. LiveActivityAttributes.ContentState.testNarrow
  626. LiveActivityAttributes.ContentState.testExpired
  627. }