LiveActivityWidgetConfiguration.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. import Charts
  2. import Foundation
  3. import SwiftUI
  4. import Swinject
  5. import UniformTypeIdentifiers
  6. struct LiveActivityWidgetConfiguration: BaseView {
  7. let resolver: Resolver
  8. @ObservedObject var state: LiveActivitySettings.StateModel
  9. @State private var selectedItems: [LiveActivityItem?] = Array(repeating: nil, count: 4)
  10. @State private var showAddItemDialog: Bool = false
  11. @State private var buttonIndexToUpdate: Int?
  12. @State private var itemToRemove: LiveActivityItem?
  13. @State private var isRemovalConfirmationPresented: Bool = false
  14. @State private var glucoseData: [DummyGlucoseData] = []
  15. @Environment(\.colorScheme) var colorScheme
  16. @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
  17. @Environment(AppState.self) var appState
  18. private var color: LinearGradient {
  19. colorScheme == .dark ? LinearGradient(
  20. gradient: Gradient(colors: [
  21. Color.bgDarkBlue,
  22. Color.bgDarkerDarkBlue
  23. ]),
  24. startPoint: .top,
  25. endPoint: .bottom
  26. )
  27. :
  28. LinearGradient(
  29. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  30. startPoint: .top,
  31. endPoint: .bottom
  32. )
  33. }
  34. private func generateDummyGlucoseData() -> [DummyGlucoseData] {
  35. var data = [DummyGlucoseData]()
  36. let totalMinutes = 6 * 60
  37. let interval = 5
  38. var glucoseLevel: Double = 90 // Start at a normal fasting glucose level
  39. for minute in stride(from: 0, to: totalMinutes, by: interval) {
  40. let time = Double(minute) / 60.0 // Convert minutes to hours
  41. let trendFactor: Double
  42. let randomFactor = Double.random(in: -5 ... 5) // Add slight randomness to each point
  43. // Simulate different phases during the 6-hour window
  44. if time < 1 { // Stable glucose (pre-meal or fasting period)
  45. trendFactor = 0.5 + randomFactor // Small increase with some variability
  46. } else if time >= 1, time < 2 { // Glucose rising (e.g., post-meal spike)
  47. trendFactor = 3.0 + randomFactor // Rapid increase with slight variation
  48. } else if time >= 2, time < 3.5 { // Peak and plateau
  49. trendFactor = -0.1 + randomFactor // Gradual decrease after the peak with variability
  50. } else if time >= 3.5, time < 4.5 { // Second peak (optional, simulate another meal)
  51. trendFactor = 2.5 + randomFactor // Another spike with some randomness
  52. } else { // Post-meal decrease (insulin effect)
  53. trendFactor = -1.5 + randomFactor // Glucose decreasing gradually with some variability
  54. }
  55. // Calculate the next glucose level with trend factors
  56. glucoseLevel += trendFactor
  57. // Ensure glucose level doesn't go out of realistic bounds:
  58. glucoseLevel = max(70, min(glucoseLevel, 200))
  59. data.append(DummyGlucoseData(time: Double(minute), glucoseLevel: Int(glucoseLevel.rounded())))
  60. }
  61. return data
  62. }
  63. var body: some View {
  64. VStack {
  65. Group {
  66. VStack(alignment: .trailing, spacing: 0) {
  67. Text(String(localized: "Live Activity Personalization").uppercased())
  68. .frame(maxWidth: .infinity, alignment: .leading)
  69. .foregroundColor(.secondary)
  70. .font(.footnote)
  71. .padding(.leading)
  72. }
  73. }.padding(.bottom, -15)
  74. GroupBox {
  75. VStack {
  76. dummyChart(glucoseData)
  77. HStack(spacing: 15) {
  78. ForEach(0 ..< 4, id: \.self) { index in
  79. widgetButton(for: index)
  80. }
  81. }
  82. .padding()
  83. .overlay(
  84. RoundedRectangle(cornerRadius: 12)
  85. .stroke(style: StrokeStyle(lineWidth: 2, dash: [5]))
  86. .foregroundColor(.gray)
  87. )
  88. .cornerRadius(12)
  89. }
  90. }.padding(.vertical).groupBoxStyle(.dummyChart)
  91. Group {
  92. HStack {
  93. Image(systemName: "info.circle")
  94. Text(
  95. "To re-order widgets, remove them and re-add them in the desired order."
  96. )
  97. }
  98. }.frame(maxWidth: .infinity, alignment: .leading)
  99. .foregroundColor(.secondary)
  100. .font(.footnote)
  101. .padding(.horizontal)
  102. Spacer()
  103. }
  104. .padding()
  105. .scrollContentBackground(.hidden)
  106. .background(appState.trioBackgroundColor(for: colorScheme))
  107. .navigationTitle("Widget Configuration")
  108. .navigationBarTitleDisplayMode(.automatic)
  109. .onAppear {
  110. if glucoseData.isEmpty {
  111. glucoseData = generateDummyGlucoseData()
  112. }
  113. loadOrder() // Load the saved order when the view appears
  114. }
  115. .confirmationDialog("Add Widget", isPresented: $showAddItemDialog, titleVisibility: .visible) {
  116. ForEach(LiveActivityItem.allCases.filter { !selectedItems.contains($0) }, id: \.self) { item in
  117. Button(item.displayName) {
  118. if let index = buttonIndexToUpdate {
  119. addItem(item, at: index)
  120. }
  121. }
  122. }
  123. }
  124. }
  125. @ViewBuilder private func widgetButton(for index: Int) -> some View {
  126. if index < selectedItems.count, let selectedItem = selectedItems[index] {
  127. // Display selected item preview
  128. ZStack(alignment: .topTrailing) {
  129. getItemPreview(for: selectedItem)
  130. .frame(width: 50, height: 50)
  131. .padding(5)
  132. .background(Color.clear)
  133. .cornerRadius(12)
  134. .overlay(
  135. RoundedRectangle(cornerRadius: 12)
  136. .stroke(Color.primary, lineWidth: 1)
  137. )
  138. Button(action: {
  139. isRemovalConfirmationPresented = true
  140. itemToRemove = selectedItem
  141. }) {
  142. Image(systemName: "trash.circle.fill")
  143. .foregroundColor(Color(UIColor.systemGray2))
  144. .background(Color.white)
  145. .clipShape(Circle())
  146. .font(.title3)
  147. }
  148. .offset(x: 10, y: -10)
  149. .confirmationDialog("Remove Widget", isPresented: $isRemovalConfirmationPresented, titleVisibility: .hidden) {
  150. Button("Remove Widget", role: .destructive) {
  151. if let itemToRemove = itemToRemove {
  152. removeItem(itemToRemove)
  153. }
  154. }
  155. }
  156. }
  157. } else {
  158. // Show "+" symbol for empty slots
  159. Button(action: {
  160. buttonIndexToUpdate = index
  161. showAddItemDialog.toggle()
  162. }) {
  163. VStack {
  164. Image(systemName: "plus")
  165. .font(.title2)
  166. .foregroundColor(.accentColor)
  167. }
  168. .frame(width: 50, height: 50)
  169. .padding(5)
  170. .overlay(
  171. RoundedRectangle(cornerRadius: 12)
  172. .stroke(style: StrokeStyle(lineWidth: 1, dash: [5]))
  173. .foregroundColor(.primary)
  174. )
  175. }
  176. .buttonStyle(.plain)
  177. }
  178. }
  179. private func getItemPreview(for item: LiveActivityItem) -> some View {
  180. switch item {
  181. case .currentGlucoseLarge:
  182. return AnyView(currentGlucoseLargePreview)
  183. case .currentGlucose:
  184. return AnyView(currentGlucosePreview)
  185. case .cob:
  186. return AnyView(cobPreview)
  187. case .iob:
  188. return AnyView(iobPreview)
  189. case .updatedLabel:
  190. return AnyView(updatedLabelPreview)
  191. case .totalDailyDose:
  192. return AnyView(totalDailyDosePreview)
  193. }
  194. }
  195. @ViewBuilder private func dummyChart(_ glucoseData: [DummyGlucoseData]) -> some View {
  196. Chart {
  197. ForEach(glucoseData) { data in
  198. let pointMarkColor = Trio.getDynamicGlucoseColor(
  199. glucoseValue: Decimal(data.glucoseLevel),
  200. highGlucoseColorValue: !(state.settingsManager.settings.glucoseColorScheme == .dynamicColor) ? state
  201. .settingsManager.settings.highGlucose : Decimal(220),
  202. lowGlucoseColorValue: !(state.settingsManager.settings.glucoseColorScheme == .dynamicColor) ? state
  203. .settingsManager.settings.lowGlucose : Decimal(55),
  204. targetGlucose: Decimal(100),
  205. glucoseColorScheme: state.settingsManager.settings.glucoseColorScheme
  206. )
  207. PointMark(
  208. x: .value("Time", data.time),
  209. y: .value("Glucose Level", data.glucoseLevel)
  210. ).foregroundStyle(pointMarkColor).symbolSize(15)
  211. }
  212. }
  213. .chartYAxis {
  214. AxisMarks(position: .trailing) { _ in
  215. AxisGridLine(stroke: .init(lineWidth: 0.2, dash: [2, 3])).foregroundStyle(Color.white)
  216. AxisValueLabel().foregroundStyle(.primary).font(.footnote)
  217. }
  218. }
  219. .chartYScale(domain: 39 ... 200)
  220. .chartYAxis(.hidden)
  221. .chartPlotStyle { plotContent in
  222. plotContent
  223. .background(
  224. RoundedRectangle(cornerRadius: 12)
  225. .fill(Color.cyan.opacity(0.15))
  226. )
  227. .clipShape(RoundedRectangle(cornerRadius: 12))
  228. }
  229. .chartXAxis {
  230. AxisMarks(position: .automatic) { _ in
  231. AxisGridLine(stroke: .init(lineWidth: 0.2, dash: [2, 3])).foregroundStyle(Color.primary)
  232. }
  233. }
  234. .frame(height: 100)
  235. }
  236. private var currentGlucoseLargePreview: some View {
  237. HStack(alignment: .center) {
  238. Text("123")
  239. + Text("\u{2192}")
  240. }
  241. .foregroundStyle(Color.loopGreen)
  242. .fontWeight(.bold)
  243. .font(.subheadline)
  244. }
  245. private var currentGlucosePreview: some View {
  246. VStack {
  247. HStack(alignment: .center) {
  248. Text("123")
  249. .fontWeight(.bold)
  250. .font(.caption)
  251. }
  252. HStack(spacing: -5) {
  253. HStack {
  254. Text("\u{2192}")
  255. Text("+6")
  256. }.foregroundStyle(.primary).font(.caption2)
  257. }
  258. }
  259. }
  260. private var cobPreview: some View {
  261. VStack(spacing: 2) {
  262. Text("25 g").fontWeight(.bold).font(.caption)
  263. Text("COB").font(.caption2).foregroundStyle(.primary)
  264. }
  265. }
  266. private var iobPreview: some View {
  267. VStack(spacing: 2) {
  268. Text("2 U").fontWeight(.bold).font(.caption)
  269. Text("IOB").font(.caption2).foregroundStyle(.primary)
  270. }
  271. }
  272. private var updatedLabelPreview: some View {
  273. VStack {
  274. Text("19:05")
  275. .fontWeight(.bold)
  276. .font(.caption)
  277. .foregroundStyle(.primary)
  278. Text("Updated").font(.caption2).foregroundStyle(.primary)
  279. }
  280. }
  281. private var totalDailyDosePreview: some View {
  282. VStack {
  283. Text("43.21 U")
  284. .fontWeight(.bold)
  285. .font(.caption)
  286. .foregroundStyle(.primary)
  287. Text("TDD").font(.caption2).foregroundStyle(.primary)
  288. }
  289. }
  290. private func loadOrder() {
  291. if let savedItems = UserDefaults.standard.loadLiveActivityOrder() {
  292. selectedItems = savedItems.count == 4 ? savedItems : savedItems + Array(repeating: nil, count: 4 - savedItems.count)
  293. } else {
  294. selectedItems = LiveActivityItem.defaultItems
  295. saveOrder()
  296. }
  297. }
  298. private func saveOrder() {
  299. UserDefaults.standard.saveLiveActivityOrder(selectedItems)
  300. Foundation.NotificationCenter.default.post(name: .liveActivityOrderDidChange, object: nil)
  301. }
  302. private func addItem(_ item: LiveActivityItem, at index: Int) {
  303. selectedItems[index] = item
  304. saveOrder()
  305. }
  306. private func removeItem(_ item: LiveActivityItem) {
  307. if let index = selectedItems.firstIndex(of: item) {
  308. selectedItems[index] = nil
  309. saveOrder()
  310. }
  311. }
  312. }
  313. // Extension for UserDefaults to save and load the order
  314. extension UserDefaults {
  315. private enum Keys {
  316. static let liveActivityOrder = "liveActivityOrder"
  317. }
  318. func saveLiveActivityOrder(_ items: [LiveActivityItem?]) {
  319. let itemStrings = items.map { $0?.rawValue ?? "" }
  320. set(itemStrings, forKey: Keys.liveActivityOrder)
  321. }
  322. func loadLiveActivityOrder() -> [LiveActivityItem?]? {
  323. if let itemStrings = array(forKey: Keys.liveActivityOrder) as? [String] {
  324. return itemStrings.map { $0.isEmpty ? nil : LiveActivityItem(rawValue: $0) }
  325. }
  326. return nil
  327. }
  328. }
  329. // Enum to represent each live activity item
  330. enum LiveActivityItem: String, CaseIterable, Identifiable {
  331. case currentGlucoseLarge
  332. case currentGlucose
  333. case iob
  334. case cob
  335. case updatedLabel
  336. case totalDailyDose
  337. var id: String { rawValue }
  338. static var defaultItems: [LiveActivityItem] {
  339. [.currentGlucose, .iob, .cob, .updatedLabel]
  340. }
  341. var displayName: String {
  342. switch self {
  343. case .currentGlucoseLarge:
  344. return "Glucose and Trend, no Delta"
  345. case .currentGlucose:
  346. return "Glucose, Trend, Delta"
  347. case .iob:
  348. return "Insulin on Board (IOB)"
  349. case .cob:
  350. return "Carbs on Board (IOB)"
  351. case .updatedLabel:
  352. return "Last Updated"
  353. case .totalDailyDose:
  354. return "Total Daily Dose"
  355. }
  356. }
  357. }
  358. struct DummyGlucoseData: Identifiable {
  359. let id = UUID()
  360. let time: Double // Time in hours
  361. let glucoseLevel: Int // Glucose level in mg/dL
  362. }
  363. struct DummyChartGroupBoxStyle: GroupBoxStyle {
  364. func makeBody(configuration: Configuration) -> some View {
  365. VStack {
  366. configuration.content
  367. }
  368. .padding()
  369. .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
  370. .background(Color.chart, in: RoundedRectangle(cornerRadius: 12))
  371. .frame(width: UIScreen.main.bounds.width * 0.9)
  372. }
  373. }
  374. extension GroupBoxStyle where Self == DummyChartGroupBoxStyle {
  375. static var dummyChart: DummyChartGroupBoxStyle { .init() }
  376. }