LiveActivity.swift 18 KB

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