LiveActivity.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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 = 2
  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. if !context.state.change.isEmpty {
  73. Text(context.state.change).foregroundStyle(.primary.opacity(0.5)).font(.headline)
  74. .strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  75. } else {
  76. Text("--")
  77. }
  78. }
  79. @ViewBuilder func mealLabel(
  80. context: ActivityViewContext<LiveActivityAttributes>,
  81. additionalState: LiveActivityAttributes.ContentAdditionalState
  82. ) -> some View {
  83. HStack {
  84. VStack(alignment: .leading, spacing: 1, content: {
  85. HStack {
  86. Image(systemName: "fork.knife")
  87. .font(.title3)
  88. .foregroundColor(.yellow)
  89. }
  90. HStack {
  91. Image(systemName: "syringe.fill")
  92. .font(.title3)
  93. .foregroundColor(.blue)
  94. }
  95. })
  96. VStack(alignment: .trailing, spacing: 1, content: {
  97. HStack {
  98. Text(
  99. carbsFormatter.string(from: additionalState.cob as NSNumber) ?? "--"
  100. ).fontWeight(.bold).font(.headline).strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  101. Text(NSLocalizedString(" g", comment: "grams of carbs")).foregroundStyle(.secondary).font(.footnote)
  102. }
  103. HStack {
  104. Text(
  105. bolusFormatter.string(from: additionalState.iob as NSNumber) ?? "--"
  106. ).font(.headline).fontWeight(.bold).strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  107. Text(NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)"))
  108. .foregroundStyle(.secondary).font(.footnote)
  109. }
  110. })
  111. VStack(alignment: .trailing, spacing: 1, content: {
  112. if additionalState.isOverrideActive {
  113. Image(systemName: "person.crop.circle.fill.badge.checkmark")
  114. .font(.title3)
  115. }
  116. })
  117. }
  118. }
  119. @ViewBuilder func trend(context: ActivityViewContext<LiveActivityAttributes>) -> some View {
  120. if context.isStale {
  121. Text("--")
  122. } else {
  123. if let trendSystemImage = context.state.direction {
  124. Image(systemName: trendSystemImage)
  125. }
  126. }
  127. }
  128. private func expiredLabel() -> some View {
  129. Text("Live Activity Expired. Open Trio to Refresh")
  130. .minimumScaleFactor(0.01)
  131. }
  132. private func updatedLabel(context: ActivityViewContext<LiveActivityAttributes>) -> Text {
  133. let text = Text("Updated: \(dateFormatter.string(from: context.state.date))")
  134. .font(.caption2)
  135. if context.isStale {
  136. // foregroundStyle is not available in <iOS 17 hence the check here
  137. if #available(iOSApplicationExtension 17.0, *) {
  138. return text.bold().foregroundStyle(.red)
  139. } else {
  140. return text.bold().foregroundColor(.red)
  141. }
  142. } else {
  143. if #available(iOSApplicationExtension 17.0, *) {
  144. return text.bold().foregroundStyle(.secondary)
  145. } else {
  146. return text.bold().foregroundColor(.red)
  147. }
  148. }
  149. }
  150. @ViewBuilder private func bgLabel(
  151. context: ActivityViewContext<LiveActivityAttributes>,
  152. additionalState: LiveActivityAttributes.ContentAdditionalState
  153. ) -> some View {
  154. HStack(alignment: .center) {
  155. Text(context.state.bg)
  156. .fontWeight(.bold)
  157. .font(.largeTitle)
  158. .strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  159. Text(additionalState.unit).foregroundStyle(.secondary).font(.subheadline).offset(x: -5, y: 5)
  160. }
  161. }
  162. private func bgAndTrend(context: ActivityViewContext<LiveActivityAttributes>, size: Size) -> (some View, Int) {
  163. var characters = 0
  164. let bgText = context.state.bg
  165. characters += bgText.count
  166. // narrow mode is for the minimal dynamic island view
  167. // there is not enough space to show all three arrow there
  168. // and everything has to be squeezed together to some degree
  169. // only display the first arrow character and make it red in case there were more characters
  170. var directionText: String?
  171. var warnColor: Color?
  172. if let direction = context.state.direction {
  173. if size == .compact {
  174. directionText = String(direction[direction.startIndex ... direction.startIndex])
  175. if direction.count > 1 {
  176. warnColor = Color.red
  177. }
  178. } else {
  179. directionText = direction
  180. }
  181. characters += directionText!.count
  182. }
  183. let spacing: CGFloat
  184. switch size {
  185. case .minimal: spacing = -1
  186. case .compact: spacing = 0
  187. case .expanded: spacing = 3
  188. }
  189. let stack = HStack(spacing: spacing) {
  190. Text(bgText)
  191. .strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  192. if let direction = directionText {
  193. let text = Text(direction)
  194. switch size {
  195. case .minimal:
  196. let scaledText = text.scaleEffect(x: 0.7, y: 0.7, anchor: .leading)
  197. if let warnColor {
  198. scaledText.foregroundStyle(warnColor)
  199. } else {
  200. scaledText
  201. }
  202. case .compact:
  203. text.scaleEffect(x: 0.8, y: 0.8, anchor: .leading).padding(.trailing, -3)
  204. case .expanded:
  205. text.scaleEffect(x: 0.7, y: 0.7, anchor: .leading).padding(.trailing, -5)
  206. }
  207. }
  208. }
  209. .foregroundStyle(context.isStale ? Color.primary.opacity(0.5) : Color.primary)
  210. return (stack, characters)
  211. }
  212. @ViewBuilder func trendArrow(
  213. context: ActivityViewContext<LiveActivityAttributes>,
  214. additionalState: LiveActivityAttributes.ContentAdditionalState
  215. ) -> some View {
  216. let gradient = LinearGradient(colors: [
  217. Color(red: 0.6235294118, green: 0.4235294118, blue: 0.9803921569),
  218. Color(red: 0.4862745098, green: 0.5450980392, blue: 0.9529411765),
  219. Color(red: 0.3411764706, green: 0.6666666667, blue: 0.9254901961),
  220. Color(red: 0.262745098, green: 0.7333333333, blue: 0.9137254902)
  221. ], startPoint: .leading, endPoint: .trailing)
  222. if !context.isStale {
  223. Image(systemName: "arrow.right")
  224. .font(.title)
  225. .rotationEffect(.degrees(additionalState.rotationDegrees))
  226. .foregroundStyle(gradient)
  227. }
  228. }
  229. @ViewBuilder func chart(
  230. context: ActivityViewContext<LiveActivityAttributes>,
  231. additionalState: LiveActivityAttributes.ContentAdditionalState
  232. ) -> some View {
  233. if context.isStale {
  234. Text("No data available")
  235. } else {
  236. // Determine scale
  237. let min = min(additionalState.chart.min() ?? 45, 40) - 20
  238. let max = max(additionalState.chart.max() ?? 270, 300) + 50
  239. let yAxisRuleMarkMin = additionalState.unit == "mg/dL" ? additionalState.lowGlucose : additionalState.lowGlucose
  240. .asMmolL
  241. let yAxisRuleMarkMax = additionalState.unit == "mg/dL" ? additionalState.highGlucose : additionalState.highGlucose
  242. .asMmolL
  243. Chart {
  244. RuleMark(y: .value("Low", yAxisRuleMarkMin))
  245. .lineStyle(.init(lineWidth: 0.5, dash: [5]))
  246. RuleMark(y: .value("High", yAxisRuleMarkMax))
  247. .lineStyle(.init(lineWidth: 0.5, dash: [5]))
  248. ForEach(additionalState.chart.indices, id: \.self) { index in
  249. let currentValue = additionalState.chart[index]
  250. let displayValue = additionalState.unit == "mg/dL" ? currentValue : currentValue.asMmolL
  251. let chartDate = additionalState.chartDate[index] ?? Date()
  252. let pointMark = PointMark(
  253. x: .value("Time", chartDate),
  254. y: .value("Value", displayValue)
  255. ).symbolSize(15)
  256. if displayValue > yAxisRuleMarkMax {
  257. pointMark.foregroundStyle(Color.orange.gradient)
  258. } else if displayValue < yAxisRuleMarkMin {
  259. pointMark.foregroundStyle(Color.red.gradient)
  260. } else {
  261. pointMark.foregroundStyle(Color.green.gradient)
  262. }
  263. }
  264. }
  265. .chartYAxis {
  266. AxisMarks(position: .trailing) { _ in
  267. AxisGridLine(stroke: .init(lineWidth: 0.2, dash: [2, 3])).foregroundStyle(Color.white)
  268. AxisValueLabel().foregroundStyle(.secondary).font(.footnote)
  269. }
  270. }
  271. .chartYScale(domain: additionalState.unit == "mg/dL" ? min ... max : min.asMmolL ... max.asMmolL)
  272. .chartXAxis {
  273. AxisMarks(position: .automatic) { _ in
  274. AxisGridLine(stroke: .init(lineWidth: 0.2, dash: [2, 3])).foregroundStyle(Color.white)
  275. }
  276. }
  277. }
  278. }
  279. @ViewBuilder func content(context: ActivityViewContext<LiveActivityAttributes>) -> some View {
  280. if let detailedViewState = context.state.detailedViewState {
  281. HStack(spacing: 12) {
  282. chart(context: context, additionalState: detailedViewState).frame(maxWidth: UIScreen.main.bounds.width / 1.8)
  283. VStack(alignment: .leading) {
  284. Spacer()
  285. bgLabel(context: context, additionalState: detailedViewState)
  286. HStack {
  287. changeLabel(context: context)
  288. trendArrow(context: context, additionalState: detailedViewState)
  289. }
  290. mealLabel(context: context, additionalState: detailedViewState).padding(.bottom, 8)
  291. updatedLabel(context: context).padding(.bottom, 10)
  292. }
  293. }
  294. .privacySensitive()
  295. .padding(.all, 14)
  296. .imageScale(.small)
  297. .foregroundColor(Color.white)
  298. .activityBackgroundTint(Color.black.opacity(0.8))
  299. } else {
  300. Group {
  301. if context.state.isInitialState {
  302. // add vertical and horizontal spacers around the label to ensure that the live activity view gets filled completely
  303. HStack {
  304. Spacer()
  305. VStack {
  306. Spacer()
  307. expiredLabel()
  308. Spacer()
  309. }
  310. Spacer()
  311. }
  312. } else {
  313. HStack(spacing: 3) {
  314. bgAndTrend(context: context, size: .expanded).0.font(.title)
  315. Spacer()
  316. VStack(alignment: .trailing, spacing: 5) {
  317. changeLabel(context: context).font(.title3)
  318. updatedLabel(context: context).font(.caption).foregroundStyle(.primary.opacity(0.7))
  319. }
  320. }
  321. }
  322. }
  323. .privacySensitive()
  324. .padding(.all, 15)
  325. // Semantic BackgroundStyle and Color values work here. They adapt to the given interface style (light mode, dark mode)
  326. // Semantic UIColors do NOT (as of iOS 17.1.1). Like UIColor.systemBackgroundColor (it does not adapt to changes of the interface style)
  327. // The colorScheme environment varaible that is usually used to detect dark mode does NOT work here (it reports false values)
  328. .foregroundStyle(Color.primary)
  329. .background(BackgroundStyle.background.opacity(0.4))
  330. .activityBackgroundTint(Color.clear)
  331. }
  332. }
  333. func dynamicIsland(context: ActivityViewContext<LiveActivityAttributes>) -> DynamicIsland {
  334. DynamicIsland {
  335. DynamicIslandExpandedRegion(.leading) {
  336. bgAndTrend(context: context, size: .expanded).0.font(.title2).padding(.leading, 5)
  337. }
  338. DynamicIslandExpandedRegion(.trailing) {
  339. changeLabel(context: context).font(.title2).padding(.trailing, 5)
  340. }
  341. DynamicIslandExpandedRegion(.bottom) {
  342. if context.state.isInitialState {
  343. expiredLabel()
  344. } else if let detailedViewState = context.state.detailedViewState {
  345. chart(context: context, additionalState: detailedViewState)
  346. } else {
  347. Group {
  348. updatedLabel(context: context).font(.caption).foregroundStyle(Color.secondary)
  349. }
  350. .frame(
  351. maxHeight: .infinity,
  352. alignment: .bottom
  353. )
  354. }
  355. }
  356. DynamicIslandExpandedRegion(.center) {
  357. if context.state.detailedViewState != nil {
  358. updatedLabel(context: context).font(.caption).foregroundStyle(Color.secondary)
  359. }
  360. }
  361. } compactLeading: {
  362. bgAndTrend(context: context, size: .compact).0.padding(.leading, 4)
  363. } compactTrailing: {
  364. changeLabel(context: context).padding(.trailing, 4)
  365. } minimal: {
  366. let (_label, characterCount) = bgAndTrend(context: context, size: .minimal)
  367. let label = _label.padding(.leading, 7).padding(.trailing, 3)
  368. if characterCount < 4 {
  369. label
  370. } else if characterCount < 5 {
  371. label.fontWidth(.condensed)
  372. } else {
  373. label.fontWidth(.compressed)
  374. }
  375. }
  376. .widgetURL(URL(string: "Trio://"))
  377. .keylineTint(Color.purple)
  378. .contentMargins(.horizontal, 0, for: .minimal)
  379. .contentMargins(.trailing, 0, for: .compactLeading)
  380. .contentMargins(.leading, 0, for: .compactTrailing)
  381. }
  382. var body: some WidgetConfiguration {
  383. ActivityConfiguration(for: LiveActivityAttributes.self, content: self.content, dynamicIsland: self.dynamicIsland)
  384. }
  385. }
  386. private extension LiveActivityAttributes {
  387. static var preview: LiveActivityAttributes {
  388. LiveActivityAttributes(startDate: Date())
  389. }
  390. }
  391. private extension LiveActivityAttributes.ContentState {
  392. // 0 is the widest digit. Use this to get an upper bound on text width.
  393. // 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
  394. static var testWide: LiveActivityAttributes.ContentState {
  395. LiveActivityAttributes.ContentState(
  396. bg: "00.0",
  397. direction: "→",
  398. change: "+0.0",
  399. date: Date(),
  400. detailedViewState: nil,
  401. isInitialState: false
  402. )
  403. }
  404. static var testVeryWide: LiveActivityAttributes.ContentState {
  405. LiveActivityAttributes.ContentState(
  406. bg: "00.0",
  407. direction: "↑↑",
  408. change: "+0.0",
  409. date: Date(),
  410. detailedViewState: nil,
  411. isInitialState: false
  412. )
  413. }
  414. static var testSuperWide: LiveActivityAttributes.ContentState {
  415. LiveActivityAttributes.ContentState(
  416. bg: "00.0",
  417. direction: "↑↑↑",
  418. change: "+0.0",
  419. date: Date(),
  420. detailedViewState: nil,
  421. isInitialState: false
  422. )
  423. }
  424. // 2 characters for BG, 1 character for change is the minimum that will be shown
  425. static var testNarrow: LiveActivityAttributes.ContentState {
  426. LiveActivityAttributes.ContentState(
  427. bg: "00",
  428. direction: "↑",
  429. change: "+0",
  430. date: Date(),
  431. detailedViewState: nil,
  432. isInitialState: false
  433. )
  434. }
  435. static var testMedium: LiveActivityAttributes.ContentState {
  436. LiveActivityAttributes.ContentState(
  437. bg: "000",
  438. direction: "↗︎",
  439. change: "+00",
  440. date: Date(),
  441. detailedViewState: nil,
  442. isInitialState: false
  443. )
  444. }
  445. static var testExpired: LiveActivityAttributes.ContentState {
  446. LiveActivityAttributes.ContentState(
  447. bg: "--",
  448. direction: nil,
  449. change: "--",
  450. date: Date().addingTimeInterval(-60 * 60),
  451. detailedViewState: nil,
  452. isInitialState: true
  453. )
  454. }
  455. }
  456. @available(iOS 17.0, iOSApplicationExtension 17.0, *)
  457. #Preview("Notification", as: .content, using: LiveActivityAttributes.preview) {
  458. LiveActivity()
  459. } contentStates: {
  460. LiveActivityAttributes.ContentState.testSuperWide
  461. LiveActivityAttributes.ContentState.testVeryWide
  462. LiveActivityAttributes.ContentState.testWide
  463. LiveActivityAttributes.ContentState.testMedium
  464. LiveActivityAttributes.ContentState.testNarrow
  465. LiveActivityAttributes.ContentState.testExpired
  466. }