LiveActivityWidgetConfiguration.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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("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 .currentGlucose:
  182. return AnyView(currentGlucosePreview)
  183. case .cob:
  184. return AnyView(cobPreview)
  185. case .iob:
  186. return AnyView(iobPreview)
  187. case .updatedLabel:
  188. return AnyView(updatedLabelPreview)
  189. }
  190. }
  191. @ViewBuilder private func dummyChart(_ glucoseData: [DummyGlucoseData]) -> some View {
  192. Chart {
  193. ForEach(glucoseData) { data in
  194. let pointMarkColor = FreeAPS.getDynamicGlucoseColor(
  195. glucoseValue: Decimal(data.glucoseLevel),
  196. highGlucoseColorValue: !(state.settingsManager.settings.glucoseColorScheme == .dynamicColor) ? state
  197. .settingsManager.settings.highGlucose : Decimal(220),
  198. lowGlucoseColorValue: !(state.settingsManager.settings.glucoseColorScheme == .dynamicColor) ? state
  199. .settingsManager.settings.lowGlucose : Decimal(55),
  200. targetGlucose: Decimal(100),
  201. glucoseColorScheme: state.settingsManager.settings.glucoseColorScheme
  202. )
  203. PointMark(
  204. x: .value("Time", data.time),
  205. y: .value("Glucose Level", data.glucoseLevel)
  206. ).foregroundStyle(pointMarkColor).symbolSize(15)
  207. }
  208. }
  209. .chartYAxis {
  210. AxisMarks(position: .trailing) { _ in
  211. AxisGridLine(stroke: .init(lineWidth: 0.2, dash: [2, 3])).foregroundStyle(Color.white)
  212. AxisValueLabel().foregroundStyle(.primary).font(.footnote)
  213. }
  214. }
  215. .chartYScale(domain: 39 ... 200)
  216. .chartYAxis(.hidden)
  217. .chartPlotStyle { plotContent in
  218. plotContent
  219. .background(
  220. RoundedRectangle(cornerRadius: 12)
  221. .fill(Color.cyan.opacity(0.15))
  222. )
  223. .clipShape(RoundedRectangle(cornerRadius: 12))
  224. }
  225. .chartXAxis {
  226. AxisMarks(position: .automatic) { _ in
  227. AxisGridLine(stroke: .init(lineWidth: 0.2, dash: [2, 3])).foregroundStyle(Color.primary)
  228. }
  229. }
  230. .frame(height: 100)
  231. }
  232. private var currentGlucosePreview: some View {
  233. VStack {
  234. HStack(alignment: .center) {
  235. Text("123")
  236. .fontWeight(.bold)
  237. .font(.caption)
  238. }
  239. HStack(spacing: -5) {
  240. HStack {
  241. Text("\u{2192}")
  242. Text("+6")
  243. }.foregroundStyle(.primary).font(.caption2)
  244. }
  245. }
  246. }
  247. private var cobPreview: some View {
  248. VStack(spacing: 2) {
  249. Text("25 g").fontWeight(.bold).font(.caption)
  250. Text("COB").font(.caption2).foregroundStyle(.primary)
  251. }
  252. }
  253. private var iobPreview: some View {
  254. VStack(spacing: 2) {
  255. Text("2 U").fontWeight(.bold).font(.caption)
  256. Text("IOB").font(.caption2).foregroundStyle(.primary)
  257. }
  258. }
  259. private var updatedLabelPreview: some View {
  260. VStack {
  261. Text("19:05")
  262. .fontWeight(.bold)
  263. .font(.caption)
  264. .foregroundStyle(.primary)
  265. Text("Updated").font(.caption2).foregroundStyle(.primary)
  266. }
  267. }
  268. private func loadOrder() {
  269. if let savedItems = UserDefaults.standard.loadLiveActivityOrder() {
  270. selectedItems = savedItems.count == 4 ? savedItems : savedItems + Array(repeating: nil, count: 4 - savedItems.count)
  271. } else {
  272. selectedItems = LiveActivityItem.defaultItems
  273. saveOrder()
  274. }
  275. }
  276. private func saveOrder() {
  277. UserDefaults.standard.saveLiveActivityOrder(selectedItems)
  278. Foundation.NotificationCenter.default.post(name: .liveActivityOrderDidChange, object: nil)
  279. }
  280. private func addItem(_ item: LiveActivityItem, at index: Int) {
  281. selectedItems[index] = item
  282. saveOrder()
  283. }
  284. private func removeItem(_ item: LiveActivityItem) {
  285. if let index = selectedItems.firstIndex(of: item) {
  286. selectedItems[index] = nil
  287. saveOrder()
  288. }
  289. }
  290. }
  291. // Extension for UserDefaults to save and load the order
  292. extension UserDefaults {
  293. private enum Keys {
  294. static let liveActivityOrder = "liveActivityOrder"
  295. }
  296. func saveLiveActivityOrder(_ items: [LiveActivityItem?]) {
  297. let itemStrings = items.map { $0?.rawValue ?? "" }
  298. set(itemStrings, forKey: Keys.liveActivityOrder)
  299. }
  300. func loadLiveActivityOrder() -> [LiveActivityItem?]? {
  301. if let itemStrings = array(forKey: Keys.liveActivityOrder) as? [String] {
  302. return itemStrings.map { $0.isEmpty ? nil : LiveActivityItem(rawValue: $0) }
  303. }
  304. return nil
  305. }
  306. }
  307. // Enum to represent each live activity item
  308. enum LiveActivityItem: String, CaseIterable, Identifiable {
  309. case currentGlucose
  310. case iob
  311. case cob
  312. case updatedLabel
  313. var id: String { rawValue }
  314. static var defaultItems: [LiveActivityItem] {
  315. [.currentGlucose, .iob, .cob, .updatedLabel]
  316. }
  317. var displayName: String {
  318. switch self {
  319. case .currentGlucose:
  320. return "Current Glucose"
  321. case .iob:
  322. return "IOB"
  323. case .cob:
  324. return "COB"
  325. case .updatedLabel:
  326. return "Last Updated"
  327. }
  328. }
  329. }
  330. struct DummyGlucoseData: Identifiable {
  331. let id = UUID()
  332. let time: Double // Time in hours
  333. let glucoseLevel: Int // Glucose level in mg/dL
  334. }
  335. struct DummyChartGroupBoxStyle: GroupBoxStyle {
  336. func makeBody(configuration: Configuration) -> some View {
  337. VStack {
  338. configuration.content
  339. }
  340. .padding()
  341. .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
  342. .background(Color.chart, in: RoundedRectangle(cornerRadius: 12))
  343. .frame(width: UIScreen.main.bounds.width * 0.9)
  344. }
  345. }
  346. extension GroupBoxStyle where Self == DummyChartGroupBoxStyle {
  347. static var dummyChart: DummyChartGroupBoxStyle { .init() }
  348. }