LiveActivity.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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. func rounded(_ value: Decimal, scale: Int, roundingMode: NSDecimalNumber.RoundingMode) -> Decimal {
  17. var result = Decimal()
  18. var toRound = value
  19. NSDecimalRound(&result, &toRound, scale, roundingMode)
  20. return result
  21. }
  22. extension Int {
  23. var asMmolL: Decimal {
  24. rounded(Decimal(self) * GlucoseUnits.exchangeRate, scale: 1, roundingMode: .plain)
  25. }
  26. var formattedAsMmolL: String {
  27. NumberFormatter.glucoseFormatter.string(from: asMmolL as NSDecimalNumber) ?? "\(asMmolL)"
  28. }
  29. }
  30. extension Decimal {
  31. var asMmolL: Decimal {
  32. rounded(self * GlucoseUnits.exchangeRate, scale: 1, roundingMode: .plain)
  33. }
  34. var asMgdL: Decimal {
  35. rounded(self / GlucoseUnits.exchangeRate, scale: 0, roundingMode: .plain)
  36. }
  37. var formattedAsMmolL: String {
  38. NumberFormatter.glucoseFormatter.string(from: asMmolL as NSDecimalNumber) ?? "\(asMmolL)"
  39. }
  40. }
  41. extension NumberFormatter {
  42. static let glucoseFormatter: NumberFormatter = {
  43. let formatter = NumberFormatter()
  44. formatter.locale = Locale.current
  45. formatter.numberStyle = .decimal
  46. formatter.minimumFractionDigits = 1
  47. formatter.maximumFractionDigits = 1
  48. return formatter
  49. }()
  50. }
  51. struct LiveActivity: Widget {
  52. private let dateFormatter: DateFormatter = {
  53. var f = DateFormatter()
  54. f.dateStyle = .none
  55. f.timeStyle = .short
  56. return f
  57. }()
  58. private var bolusFormatter: NumberFormatter {
  59. let formatter = NumberFormatter()
  60. formatter.numberStyle = .decimal
  61. formatter.maximumFractionDigits = 1
  62. formatter.decimalSeparator = "."
  63. return formatter
  64. }
  65. private var carbsFormatter: NumberFormatter {
  66. let formatter = NumberFormatter()
  67. formatter.numberStyle = .decimal
  68. formatter.maximumFractionDigits = 0
  69. return formatter
  70. }
  71. @ViewBuilder private func changeLabel(context: ActivityViewContext<LiveActivityAttributes>) -> some View {
  72. HStack(spacing: -5) {
  73. if !context.state.change.isEmpty {
  74. Text(context.state.change).foregroundStyle(.primary).font(.subheadline)
  75. .strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  76. } else {
  77. Text("--")
  78. }
  79. }
  80. }
  81. @ViewBuilder func cobLabel(
  82. context: ActivityViewContext<LiveActivityAttributes>,
  83. additionalState: LiveActivityAttributes.ContentAdditionalState
  84. ) -> some View {
  85. VStack(spacing: 2) {
  86. HStack {
  87. Text(
  88. carbsFormatter.string(from: additionalState.cob as NSNumber) ?? "--"
  89. ).fontWeight(.bold).font(.title3).strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  90. Text(NSLocalizedString("g", comment: "grams of carbs")).foregroundStyle(.primary).font(.headline)
  91. .fontWeight(.bold)
  92. }
  93. Text("COB").font(.subheadline).foregroundStyle(.primary)
  94. }
  95. }
  96. @ViewBuilder func iobLabel(
  97. context: ActivityViewContext<LiveActivityAttributes>,
  98. additionalState: LiveActivityAttributes.ContentAdditionalState
  99. ) -> some View {
  100. VStack(spacing: 2) {
  101. HStack {
  102. Text(
  103. bolusFormatter.string(from: additionalState.iob as NSNumber) ?? "--"
  104. ).font(.title3).fontWeight(.bold).strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  105. Text(NSLocalizedString("U", comment: "Unit in number of units delivered (keep the space character!)"))
  106. .foregroundStyle(.primary).font(.headline).fontWeight(.bold)
  107. }
  108. Text("IOB").font(.subheadline).foregroundStyle(.primary)
  109. }
  110. }
  111. @ViewBuilder func mealLabel(
  112. context: ActivityViewContext<LiveActivityAttributes>,
  113. additionalState: LiveActivityAttributes.ContentAdditionalState
  114. ) -> some View {
  115. HStack {
  116. VStack(alignment: .leading, spacing: 0, content: {
  117. HStack {
  118. Image(systemName: "fork.knife")
  119. .font(.title3)
  120. .foregroundColor(.yellow)
  121. }
  122. HStack {
  123. Image(systemName: "syringe.fill")
  124. .font(.title3)
  125. .foregroundColor(.blue)
  126. }
  127. })
  128. VStack(alignment: .trailing, spacing: 0, content: {
  129. HStack {
  130. Text(
  131. carbsFormatter.string(from: additionalState.cob as NSNumber) ?? "--"
  132. ).fontWeight(.bold).font(.title3).strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  133. Text(NSLocalizedString(" g", comment: "grams of carbs")).foregroundStyle(.primary).font(.headline)
  134. }
  135. HStack {
  136. Text(
  137. bolusFormatter.string(from: additionalState.iob as NSNumber) ?? "--"
  138. ).font(.title3).fontWeight(.bold).strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  139. Text(NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)"))
  140. .foregroundStyle(.primary).font(.headline)
  141. }
  142. })
  143. VStack(alignment: .trailing, spacing: 1, content: {
  144. if additionalState.isOverrideActive {
  145. Image(systemName: "person.crop.circle.fill.badge.checkmark")
  146. .font(.title3)
  147. }
  148. })
  149. }
  150. }
  151. @ViewBuilder func trend(context: ActivityViewContext<LiveActivityAttributes>) -> some View {
  152. if context.isStale {
  153. Text("--")
  154. } else {
  155. if let trendSystemImage = context.state.direction {
  156. Image(systemName: trendSystemImage)
  157. }
  158. }
  159. }
  160. private func expiredLabel() -> some View {
  161. Text("Live Activity Expired. Open Trio to Refresh")
  162. .minimumScaleFactor(0.01)
  163. }
  164. @ViewBuilder private func updatedLabel(context: ActivityViewContext<LiveActivityAttributes>) -> some View {
  165. VStack {
  166. let dateText = Text("\(dateFormatter.string(from: context.state.date))").font(.title3).foregroundStyle(.primary)
  167. if context.isStale {
  168. if #available(iOSApplicationExtension 17.0, *) {
  169. dateText.bold().foregroundStyle(.red)
  170. } else {
  171. dateText.bold().foregroundColor(.red)
  172. }
  173. } else {
  174. if #available(iOSApplicationExtension 17.0, *) {
  175. dateText.bold().foregroundStyle(.primary)
  176. } else {
  177. dateText.bold().foregroundColor(.primary)
  178. }
  179. }
  180. Text("Updated").font(.subheadline).foregroundStyle(.primary)
  181. }
  182. }
  183. @ViewBuilder private func bgLabel(
  184. context: ActivityViewContext<LiveActivityAttributes>,
  185. additionalState _: LiveActivityAttributes.ContentAdditionalState
  186. ) -> some View {
  187. HStack(alignment: .center) {
  188. Text(context.state.bg)
  189. .fontWeight(.bold)
  190. .font(.title3)
  191. .strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  192. }
  193. }
  194. private func bgAndTrend(context: ActivityViewContext<LiveActivityAttributes>, size: Size) -> (some View, Int) {
  195. var characters = 0
  196. let bgText = context.state.bg
  197. characters += bgText.count
  198. // narrow mode is for the minimal dynamic island view
  199. // there is not enough space to show all three arrow there
  200. // and everything has to be squeezed together to some degree
  201. // only display the first arrow character and make it red in case there were more characters
  202. var directionText: String?
  203. var warnColor: Color?
  204. if let direction = context.state.direction {
  205. if size == .compact {
  206. directionText = String(direction[direction.startIndex ... direction.startIndex])
  207. if direction.count > 1 {
  208. warnColor = Color.red
  209. }
  210. } else {
  211. directionText = direction
  212. }
  213. characters += directionText!.count
  214. }
  215. let spacing: CGFloat
  216. switch size {
  217. case .minimal: spacing = -1
  218. case .compact: spacing = 0
  219. case .expanded: spacing = 3
  220. }
  221. let stack = HStack(spacing: spacing) {
  222. Text(bgText)
  223. .strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  224. if let direction = directionText {
  225. let text = Text(direction)
  226. switch size {
  227. case .minimal:
  228. let scaledText = text.scaleEffect(x: 0.7, y: 0.7, anchor: .leading)
  229. if let warnColor {
  230. scaledText.foregroundStyle(warnColor)
  231. } else {
  232. scaledText
  233. }
  234. case .compact:
  235. text.scaleEffect(x: 0.8, y: 0.8, anchor: .leading).padding(.trailing, -3)
  236. case .expanded:
  237. text.scaleEffect(x: 0.7, y: 0.7, anchor: .leading).padding(.trailing, -5)
  238. }
  239. }
  240. }
  241. .foregroundStyle(context.isStale ? Color.primary.opacity(0.5) : Color.primary)
  242. return (stack, characters)
  243. }
  244. @ViewBuilder func chart(
  245. context: ActivityViewContext<LiveActivityAttributes>,
  246. additionalState: LiveActivityAttributes.ContentAdditionalState
  247. ) -> some View {
  248. if context.isStale {
  249. Text("No data available")
  250. } else {
  251. // Determine scale
  252. let minValue = min(additionalState.chart.min() ?? 45, 40) - 20
  253. let maxValue = max(additionalState.chart.max() ?? 270, 300) + 50
  254. let yAxisRuleMarkMin = additionalState.unit == "mg/dL" ? additionalState.lowGlucose : additionalState.lowGlucose
  255. .asMmolL
  256. let yAxisRuleMarkMax = additionalState.unit == "mg/dL" ? additionalState.highGlucose : additionalState.highGlucose
  257. .asMmolL
  258. let target = additionalState.unit == "mg/dL" ? additionalState.target : additionalState.target.asMmolL
  259. Chart {
  260. RuleMark(y: .value("Low", yAxisRuleMarkMin))
  261. .lineStyle(.init(lineWidth: 0.5, dash: [5]))
  262. RuleMark(y: .value("High", yAxisRuleMarkMax))
  263. .lineStyle(.init(lineWidth: 0.5, dash: [5]))
  264. RuleMark(y: .value("Target", target)).foregroundStyle(.green.gradient).lineStyle(.init(lineWidth: 1))
  265. ForEach(additionalState.chart.indices, id: \.self) { index in
  266. let currentValue = additionalState.chart[index]
  267. let displayValue = additionalState.unit == "mg/dL" ? currentValue : currentValue.asMmolL
  268. let chartDate = additionalState.chartDate[index] ?? Date()
  269. let pointMark = PointMark(
  270. x: .value("Time", chartDate),
  271. y: .value("Value", displayValue)
  272. ).symbolSize(15)
  273. if displayValue > yAxisRuleMarkMax {
  274. pointMark.foregroundStyle(Color.orange.gradient)
  275. } else if displayValue < yAxisRuleMarkMin {
  276. pointMark.foregroundStyle(Color.red.gradient)
  277. } else {
  278. pointMark.foregroundStyle(Color.green.gradient)
  279. }
  280. }
  281. }
  282. .chartYAxis {
  283. AxisMarks(position: .trailing) { _ in
  284. AxisGridLine(stroke: .init(lineWidth: 0.2, dash: [2, 3])).foregroundStyle(Color.white)
  285. AxisValueLabel().foregroundStyle(.primary).font(.footnote)
  286. }
  287. }
  288. .chartYScale(domain: additionalState.unit == "mg/dL" ? minValue ... maxValue : minValue.asMmolL ... maxValue.asMmolL)
  289. .chartYAxis(.hidden)
  290. .chartPlotStyle { plotContent in
  291. plotContent
  292. .background(
  293. RoundedRectangle(cornerRadius: 12)
  294. .fill(Color.cyan.opacity(0.15))
  295. )
  296. .clipShape(RoundedRectangle(cornerRadius: 12))
  297. }
  298. .chartXAxis {
  299. AxisMarks(position: .automatic) { _ in
  300. AxisGridLine(stroke: .init(lineWidth: 0.2, dash: [2, 3])).foregroundStyle(Color.white)
  301. }
  302. }
  303. }
  304. }
  305. @ViewBuilder func content(context: ActivityViewContext<LiveActivityAttributes>) -> some View {
  306. if let detailedViewState = context.state.detailedViewState {
  307. VStack(content: {
  308. chart(context: context, additionalState: detailedViewState)
  309. .frame(maxWidth: UIScreen.main.bounds.width * 0.9)
  310. .frame(height: 80)
  311. HStack {
  312. ForEach(context.state.itemOrder, id: \.self) { item in
  313. switch item {
  314. case "currentGlucose":
  315. if context.state.showCurrentGlucose {
  316. VStack {
  317. bgLabel(context: context, additionalState: detailedViewState)
  318. HStack {
  319. changeLabel(context: context)
  320. if !context.isStale, let direction = context.state.direction {
  321. Text(direction).font(.headline)
  322. }
  323. }
  324. }
  325. }
  326. case "iob":
  327. if context.state.showIOB {
  328. iobLabel(context: context, additionalState: detailedViewState)
  329. }
  330. case "cob":
  331. if context.state.showCOB {
  332. cobLabel(context: context, additionalState: detailedViewState)
  333. }
  334. case "updatedLabel":
  335. if context.state.showUpdatedLabel {
  336. updatedLabel(context: context)
  337. }
  338. default:
  339. EmptyView()
  340. }
  341. Divider().foregroundStyle(.primary).fontWeight(.bold).frame(width: 10)
  342. }
  343. }
  344. })
  345. .privacySensitive()
  346. .padding(.all, 14)
  347. .imageScale(.small)
  348. .foregroundStyle(Color.primary)
  349. .activityBackgroundTint(Color.clear)
  350. } else {
  351. Group {
  352. if context.state.isInitialState {
  353. // add vertical and horizontal spacers around the label to ensure that the live activity view gets filled completely
  354. HStack {
  355. Spacer()
  356. VStack {
  357. Spacer()
  358. expiredLabel()
  359. Spacer()
  360. }
  361. Spacer()
  362. }
  363. } else {
  364. HStack(spacing: 3) {
  365. bgAndTrend(context: context, size: .expanded).0.font(.title)
  366. Spacer()
  367. VStack(alignment: .trailing, spacing: 5) {
  368. changeLabel(context: context).font(.title3)
  369. updatedLabel(context: context).font(.caption).foregroundStyle(.primary.opacity(0.7))
  370. }
  371. }
  372. }
  373. }
  374. .privacySensitive()
  375. .padding(.all, 15)
  376. // Semantic BackgroundStyle and Color values work here. They adapt to the given interface style (light mode, dark mode)
  377. // Semantic UIColors do NOT (as of iOS 17.1.1). Like UIColor.systemBackgroundColor (it does not adapt to changes of the interface style)
  378. // The colorScheme environment varaible that is usually used to detect dark mode does NOT work here (it reports false values)
  379. .foregroundStyle(Color.primary)
  380. .background(BackgroundStyle.background.opacity(0.4))
  381. .activityBackgroundTint(Color.clear)
  382. }
  383. }
  384. func dynamicIsland(context: ActivityViewContext<LiveActivityAttributes>) -> DynamicIsland {
  385. DynamicIsland {
  386. DynamicIslandExpandedRegion(.leading) {
  387. bgAndTrend(context: context, size: .expanded).0.font(.title2).padding(.leading, 5)
  388. }
  389. DynamicIslandExpandedRegion(.trailing) {
  390. changeLabel(context: context).font(.title2).padding(.trailing, 5)
  391. }
  392. DynamicIslandExpandedRegion(.bottom) {
  393. if context.state.isInitialState {
  394. expiredLabel()
  395. } else if let detailedViewState = context.state.detailedViewState {
  396. chart(context: context, additionalState: detailedViewState)
  397. } else {
  398. Group {
  399. updatedLabel(context: context).font(.caption).foregroundStyle(Color.secondary)
  400. }
  401. .frame(
  402. maxHeight: .infinity,
  403. alignment: .bottom
  404. )
  405. }
  406. }
  407. DynamicIslandExpandedRegion(.center) {
  408. if context.state.detailedViewState != nil {
  409. updatedLabel(context: context).font(.caption).foregroundStyle(Color.secondary)
  410. }
  411. }
  412. } compactLeading: {
  413. bgAndTrend(context: context, size: .compact).0.padding(.leading, 4)
  414. } compactTrailing: {
  415. changeLabel(context: context).padding(.trailing, 4)
  416. } minimal: {
  417. let (_label, characterCount) = bgAndTrend(context: context, size: .minimal)
  418. let label = _label.padding(.leading, 7).padding(.trailing, 3)
  419. if characterCount < 4 {
  420. label
  421. } else if characterCount < 5 {
  422. label.fontWidth(.condensed)
  423. } else {
  424. label.fontWidth(.compressed)
  425. }
  426. }
  427. .widgetURL(URL(string: "Trio://"))
  428. .keylineTint(Color.purple)
  429. .contentMargins(.horizontal, 0, for: .minimal)
  430. .contentMargins(.trailing, 0, for: .compactLeading)
  431. .contentMargins(.leading, 0, for: .compactTrailing)
  432. }
  433. var body: some WidgetConfiguration {
  434. ActivityConfiguration(for: LiveActivityAttributes.self, content: self.content, dynamicIsland: self.dynamicIsland)
  435. }
  436. }
  437. private extension LiveActivityAttributes {
  438. static var preview: LiveActivityAttributes {
  439. LiveActivityAttributes(startDate: Date())
  440. }
  441. }
  442. private extension LiveActivityAttributes.ContentState {
  443. // 0 is the widest digit. Use this to get an upper bound on text width.
  444. // 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
  445. static var testWide: LiveActivityAttributes.ContentState {
  446. LiveActivityAttributes.ContentState(
  447. bg: "00.0",
  448. direction: "→",
  449. change: "+0.0",
  450. date: Date(),
  451. detailedViewState: nil,
  452. showCOB: true,
  453. showIOB: true,
  454. showCurrentGlucose: true,
  455. showUpdatedLabel: true,
  456. itemOrder: ["currentGlucose", "iob", "cob", "updatedLabel"],
  457. isInitialState: false
  458. )
  459. }
  460. static var testVeryWide: LiveActivityAttributes.ContentState {
  461. LiveActivityAttributes.ContentState(
  462. bg: "00.0",
  463. direction: "↑↑",
  464. change: "+0.0",
  465. date: Date(),
  466. detailedViewState: nil,
  467. showCOB: true,
  468. showIOB: true,
  469. showCurrentGlucose: true,
  470. showUpdatedLabel: true,
  471. itemOrder: ["currentGlucose", "iob", "cob", "updatedLabel"],
  472. isInitialState: false
  473. )
  474. }
  475. static var testSuperWide: LiveActivityAttributes.ContentState {
  476. LiveActivityAttributes.ContentState(
  477. bg: "00.0",
  478. direction: "↑↑↑",
  479. change: "+0.0",
  480. date: Date(),
  481. detailedViewState: nil,
  482. showCOB: true,
  483. showIOB: true,
  484. showCurrentGlucose: true,
  485. showUpdatedLabel: true,
  486. itemOrder: ["currentGlucose", "iob", "cob", "updatedLabel"],
  487. isInitialState: false
  488. )
  489. }
  490. // 2 characters for BG, 1 character for change is the minimum that will be shown
  491. static var testNarrow: LiveActivityAttributes.ContentState {
  492. LiveActivityAttributes.ContentState(
  493. bg: "00",
  494. direction: "↑",
  495. change: "+0",
  496. date: Date(),
  497. detailedViewState: nil,
  498. showCOB: true,
  499. showIOB: true,
  500. showCurrentGlucose: true,
  501. showUpdatedLabel: true,
  502. itemOrder: ["currentGlucose", "iob", "cob", "updatedLabel"],
  503. isInitialState: false
  504. )
  505. }
  506. static var testMedium: LiveActivityAttributes.ContentState {
  507. LiveActivityAttributes.ContentState(
  508. bg: "000",
  509. direction: "↗︎",
  510. change: "+00",
  511. date: Date(),
  512. detailedViewState: nil,
  513. showCOB: true,
  514. showIOB: true,
  515. showCurrentGlucose: true,
  516. showUpdatedLabel: true,
  517. itemOrder: ["currentGlucose", "iob", "cob", "updatedLabel"],
  518. isInitialState: false
  519. )
  520. }
  521. static var testExpired: LiveActivityAttributes.ContentState {
  522. LiveActivityAttributes.ContentState(
  523. bg: "--",
  524. direction: nil,
  525. change: "--",
  526. date: Date().addingTimeInterval(-60 * 60),
  527. detailedViewState: nil,
  528. showCOB: true,
  529. showIOB: true,
  530. showCurrentGlucose: true,
  531. showUpdatedLabel: true,
  532. itemOrder: ["currentGlucose", "iob", "cob", "updatedLabel"],
  533. isInitialState: true
  534. )
  535. }
  536. }
  537. @available(iOS 17.0, iOSApplicationExtension 17.0, *)
  538. #Preview("Notification", as: .content, using: LiveActivityAttributes.preview) {
  539. LiveActivity()
  540. } contentStates: {
  541. LiveActivityAttributes.ContentState.testSuperWide
  542. LiveActivityAttributes.ContentState.testVeryWide
  543. LiveActivityAttributes.ContentState.testWide
  544. LiveActivityAttributes.ContentState.testMedium
  545. LiveActivityAttributes.ContentState.testNarrow
  546. LiveActivityAttributes.ContentState.testExpired
  547. }