LiveActivity.swift 26 KB

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