LiveActivity.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. if context.isStale {
  33. Text(context.state.change).foregroundStyle(.primary.opacity(0.5)).font(.headline)
  34. .strikethrough(pattern: .solid, color: .red.opacity(0.6)).font(.callout)
  35. } else {
  36. HStack {
  37. Text(context.state.change).font(.headline)
  38. }
  39. }
  40. } else {
  41. Text("--")
  42. }
  43. }
  44. @ViewBuilder func mealLabel(context: ActivityViewContext<LiveActivityAttributes>) -> some View {
  45. HStack {
  46. VStack(alignment: .leading, spacing: 1, content: {
  47. HStack {
  48. Image(systemName: "fork.knife")
  49. .font(.title3)
  50. .foregroundColor(.yellow)
  51. }
  52. HStack {
  53. Image(systemName: "syringe.fill")
  54. .font(.title3)
  55. .foregroundColor(.blue)
  56. }
  57. })
  58. VStack(alignment: .trailing, spacing: 1, content: {
  59. HStack {
  60. if context.isStale {
  61. Text(
  62. carbsFormatter.string(from: context.state.cob as NSNumber) ?? "--"
  63. ).fontWeight(.bold).font(.headline).strikethrough(pattern: .solid, color: .red.opacity(0.6))
  64. .font(.callout)
  65. Text(NSLocalizedString(" g", comment: "grams of carbs")).foregroundStyle(.secondary).font(.footnote)
  66. } else {
  67. Text(
  68. carbsFormatter.string(from: context.state.cob as NSNumber) ?? "--"
  69. ).fontWeight(.bold).font(.headline)
  70. Text(NSLocalizedString(" g", comment: "grams of carbs")).foregroundStyle(.secondary).font(.footnote)
  71. }
  72. }
  73. HStack {
  74. if context.isStale {
  75. Text(
  76. bolusFormatter.string(from: context.state.iob as NSNumber) ?? "--"
  77. ).font(.headline).fontWeight(.bold).strikethrough(pattern: .solid, color: .red.opacity(0.6))
  78. .font(.callout)
  79. Text(NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)"))
  80. .foregroundStyle(.secondary).font(.footnote)
  81. } else {
  82. Text(
  83. bolusFormatter.string(from: context.state.iob as NSNumber) ?? "--"
  84. ).font(.headline).fontWeight(.bold)
  85. Text(NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)"))
  86. .foregroundStyle(.secondary).font(.footnote)
  87. }
  88. }
  89. })
  90. }
  91. }
  92. @ViewBuilder func trend(context: ActivityViewContext<LiveActivityAttributes>) -> some View {
  93. if context.isStale {
  94. Text("--")
  95. } else {
  96. if let trendSystemImage = context.state.direction {
  97. Image(systemName: trendSystemImage)
  98. }
  99. }
  100. }
  101. private func updatedLabel(context: ActivityViewContext<LiveActivityAttributes>) -> Text {
  102. let text = Text("Updated: \(dateFormatter.string(from: context.state.date))")
  103. .font(.caption2)
  104. if context.isStale {
  105. // foregroundStyle is not available in <iOS 17 hence the check here
  106. if #available(iOSApplicationExtension 17.0, *) {
  107. return text.bold().foregroundStyle(.red)
  108. } else {
  109. return text.bold().foregroundColor(.red)
  110. }
  111. } else {
  112. if #available(iOSApplicationExtension 17.0, *) {
  113. return text.bold().foregroundStyle(.secondary)
  114. } else {
  115. return text.bold().foregroundColor(.red)
  116. }
  117. }
  118. }
  119. @ViewBuilder private func bgLabel(context: ActivityViewContext<LiveActivityAttributes>) -> some View {
  120. HStack(alignment: .center) {
  121. Text(context.state.bg)
  122. .fontWeight(.bold)
  123. .font(.largeTitle)
  124. .strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  125. Text(context.state.unit).foregroundStyle(.secondary).font(.subheadline).offset(x: -5, y: 5)
  126. }
  127. }
  128. private func bgAndTrend(context: ActivityViewContext<LiveActivityAttributes>, size: Size) -> (some View, Int) {
  129. var characters = 0
  130. let bgText = context.state.bg
  131. characters += bgText.count
  132. // narrow mode is for the minimal dynamic island view
  133. // there is not enough space to show all three arrow there
  134. // and everything has to be squeezed together to some degree
  135. // only display the first arrow character and make it red in case there were more characters
  136. var directionText: String?
  137. var warnColor: Color?
  138. if let direction = context.state.direction {
  139. if size == .compact {
  140. directionText = String(direction[direction.startIndex ... direction.startIndex])
  141. if direction.count > 1 {
  142. warnColor = Color.red
  143. }
  144. } else {
  145. directionText = direction
  146. }
  147. characters += directionText!.count
  148. }
  149. let spacing: CGFloat
  150. switch size {
  151. case .minimal: spacing = -1
  152. case .compact: spacing = 0
  153. case .expanded: spacing = 3
  154. }
  155. let stack = HStack(spacing: spacing) {
  156. Text(bgText)
  157. .strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  158. if let direction = directionText {
  159. let text = Text(direction)
  160. switch size {
  161. case .minimal:
  162. let scaledText = text.scaleEffect(x: 0.7, y: 0.7, anchor: .leading)
  163. if let warnColor {
  164. scaledText.foregroundStyle(warnColor)
  165. } else {
  166. scaledText
  167. }
  168. case .compact:
  169. text.scaleEffect(x: 0.8, y: 0.8, anchor: .leading).padding(.trailing, -3)
  170. case .expanded:
  171. text.scaleEffect(x: 0.7, y: 0.7, anchor: .leading).padding(.trailing, -5)
  172. }
  173. }
  174. }
  175. .foregroundStyle(context.isStale ? Color.primary.opacity(0.5) : Color.primary)
  176. return (stack, characters)
  177. }
  178. @ViewBuilder func bobble(context: ActivityViewContext<LiveActivityAttributes>) -> some View {
  179. let gradient = LinearGradient(colors: [
  180. Color(red: 0.6235294118, green: 0.4235294118, blue: 0.9803921569),
  181. Color(red: 0.4862745098, green: 0.5450980392, blue: 0.9529411765),
  182. Color(red: 0.3411764706, green: 0.6666666667, blue: 0.9254901961),
  183. Color(red: 0.262745098, green: 0.7333333333, blue: 0.9137254902)
  184. ], startPoint: .leading, endPoint: .trailing)
  185. if !context.isStale {
  186. Image(systemName: "arrow.right")
  187. .font(.title)
  188. .rotationEffect(.degrees(context.state.rotationDegrees))
  189. .foregroundStyle(gradient)
  190. }
  191. }
  192. @ViewBuilder func chart(context: ActivityViewContext<LiveActivityAttributes>) -> some View {
  193. if context.isStale {
  194. Text("No data available")
  195. } else {
  196. // determine scale
  197. let min = (context.state.chart.min() ?? 40 * (context.state.unit == " mmol/L" ? 0.0555 : 1)) - 20 *
  198. (context.state.unit == " mmol/L" ? 0.0555 : 1)
  199. let max = (context.state.chart.max() ?? 270 * (context.state.unit == " mmol/L" ? 0.0555 : 1)) + 50 *
  200. (context.state.unit == " mmol/L" ? 0.0555 : 1)
  201. Chart {
  202. RuleMark(y: .value("high", context.state.highGlucose))
  203. .lineStyle(.init(lineWidth: 0.5, dash: [5]))
  204. RuleMark(y: .value("low", context.state.lowGlucose))
  205. .lineStyle(.init(lineWidth: 0.5, dash: [5]))
  206. ForEach(context.state.chart.indices, id: \.self) { index in
  207. let currentValue = context.state.chart[index]
  208. if currentValue > context.state.highGlucose {
  209. PointMark(
  210. x: .value("Time", context.state.chartDate[index] ?? Date()),
  211. y: .value("Value", currentValue)
  212. ).foregroundStyle(Color.orange.gradient).symbolSize(15)
  213. } else if currentValue < context.state.lowGlucose {
  214. PointMark(
  215. x: .value("Time", context.state.chartDate[index] ?? Date()),
  216. y: .value("Value", currentValue)
  217. ).foregroundStyle(Color.red.gradient).symbolSize(15)
  218. } else {
  219. PointMark(
  220. x: .value("Time", context.state.chartDate[index] ?? Date()),
  221. y: .value("Value", currentValue)
  222. ).foregroundStyle(Color.green.gradient).symbolSize(15)
  223. }
  224. }
  225. }
  226. .chartYAxis {
  227. AxisMarks(position: .trailing) { _ in
  228. AxisGridLine(stroke: .init(lineWidth: 0.2, dash: [2, 3])).foregroundStyle(Color.white)
  229. AxisValueLabel().foregroundStyle(.secondary).font(.footnote)
  230. }
  231. }
  232. .chartYScale(domain: min ... max)
  233. .chartXAxis {
  234. AxisMarks(position: .automatic) { _ in
  235. AxisGridLine(stroke: .init(lineWidth: 0.2, dash: [2, 3])).foregroundStyle(Color.white)
  236. }
  237. }
  238. }
  239. }
  240. var body: some WidgetConfiguration {
  241. ActivityConfiguration(for: LiveActivityAttributes.self) { context in
  242. // Lock screen/banner UI goes here
  243. if context.state.lockScreenView == "Simple" {
  244. HStack(spacing: 3) {
  245. bgAndTrend(context: context, size: .expanded).0.font(.title)
  246. Spacer()
  247. VStack(alignment: .trailing, spacing: 5) {
  248. changeLabel(context: context).font(.title3)
  249. updatedLabel(context: context).font(.caption).foregroundStyle(.primary.opacity(0.7))
  250. }
  251. }
  252. .privacySensitive()
  253. .padding(.all, 15)
  254. // Semantic BackgroundStyle and Color values work here. They adapt to the given interface style (light mode, dark mode)
  255. // Semantic UIColors do NOT (as of iOS 17.1.1). Like UIColor.systemBackgroundColor (it does not adapt to changes of the interface style)
  256. // The colorScheme environment varaible that is usually used to detect dark mode does NOT work here (it reports false values)
  257. .foregroundStyle(Color.primary)
  258. .background(BackgroundStyle.background.opacity(0.4))
  259. .activityBackgroundTint(Color.clear)
  260. } else {
  261. HStack(spacing: 12) {
  262. chart(context: context).frame(width: UIScreen.main.bounds.width / 1.8)
  263. VStack(alignment: .leading) {
  264. Spacer()
  265. bgLabel(context: context)
  266. HStack {
  267. changeLabel(context: context)
  268. bobble(context: context)
  269. }
  270. mealLabel(context: context).padding(.bottom, 8)
  271. updatedLabel(context: context).padding(.bottom, 10)
  272. }
  273. }
  274. .privacySensitive()
  275. .padding(.all, 14)
  276. .imageScale(.small)
  277. .foregroundColor(Color.white)
  278. .activityBackgroundTint(Color.black)
  279. }
  280. } dynamicIsland: { context in
  281. DynamicIsland {
  282. // Expanded UI goes here. Compose the expanded UI through
  283. // various regions, like leading/trailing/center/bottom
  284. DynamicIslandExpandedRegion(.leading) {
  285. bgAndTrend(context: context, size: .expanded).0.font(.title2).padding(.leading, 5)
  286. }
  287. DynamicIslandExpandedRegion(.trailing) {
  288. changeLabel(context: context).font(.title2).padding(.trailing, 5)
  289. }
  290. DynamicIslandExpandedRegion(.bottom) {
  291. if context.state.lockScreenView == "Simple" {
  292. Group {
  293. updatedLabel(context: context).font(.caption).foregroundStyle(Color.secondary)
  294. }
  295. .frame(
  296. maxHeight: .infinity,
  297. alignment: .bottom
  298. )
  299. } else {
  300. chart(context: context)
  301. }
  302. }
  303. DynamicIslandExpandedRegion(.center) {
  304. if context.state.lockScreenView == "Detailed" {
  305. updatedLabel(context: context).font(.caption).foregroundStyle(Color.secondary)
  306. }
  307. }
  308. } compactLeading: {
  309. bgAndTrend(context: context, size: .compact).0.padding(.leading, 4)
  310. } compactTrailing: {
  311. changeLabel(context: context).padding(.trailing, 4)
  312. } minimal: {
  313. let (_label, characterCount) = bgAndTrend(context: context, size: .minimal)
  314. let label = _label.padding(.leading, 7).padding(.trailing, 3)
  315. if characterCount < 4 {
  316. label
  317. } else if characterCount < 5 {
  318. label.fontWidth(.condensed)
  319. } else {
  320. label.fontWidth(.compressed)
  321. }
  322. }
  323. .widgetURL(URL(string: "freeaps-x://"))
  324. .keylineTint(Color.purple)
  325. .contentMargins(.horizontal, 0, for: .minimal)
  326. .contentMargins(.trailing, 0, for: .compactLeading)
  327. .contentMargins(.leading, 0, for: .compactTrailing)
  328. }
  329. }
  330. }