LiveActivityWidgetConfiguration.swift 14 KB

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