LiveActivityWidgetConfiguration.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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 isEditMode: Bool = false
  13. @State private var draggingItem: LiveActivityItem?
  14. @State private var itemToRemove: LiveActivityItem?
  15. @State private var isRemovalConfirmationPresented: Bool = false
  16. @Environment(\.colorScheme) var colorScheme
  17. @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
  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. // Simulate different phases during the 6-hour window
  43. if time < 1 { // Stable glucose (pre-meal or fasting period)
  44. trendFactor = 0.5 // Small increase
  45. } else if time >= 1, time < 2 { // Glucose rising (e.g., post-meal spike)
  46. trendFactor = 3.0 // Rapid increase for glucose spike
  47. } else if time >= 2, time < 3.5 { // Peak and plateau
  48. trendFactor = -0.1 // Gradual decrease after the peak
  49. } else if time >= 3.5, time < 4.5 { // Second peak (optional, simulate another meal)
  50. trendFactor = 2.5 // Another spike (e.g., after a second meal)
  51. } else { // Post-meal decrease (insulin effect)
  52. trendFactor = -1.5 // Glucose decreasing gradually
  53. }
  54. // Calculate the next glucose level with trend factors only
  55. glucoseLevel += trendFactor
  56. // Ensure glucose level doesn't go out of realistic bounds:
  57. // Clamp glucose levels between 70 and 200 mg/dL
  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. let glucoseData: [DummyGlucoseData] = generateDummyGlucoseData()
  65. VStack {
  66. Group {
  67. VStack(alignment: .leading, spacing: 0) {
  68. Text("Live Activity Personalization".uppercased())
  69. .frame(maxWidth: .infinity, alignment: .leading)
  70. .foregroundColor(.secondary)
  71. .font(.footnote)
  72. .padding(.leading)
  73. }
  74. VStack {
  75. Text(
  76. "Trio offers you to customize your Live Activity lock screen widget. The default configuration will display current glucose, IOB, COB and the time of last algorithm run."
  77. )
  78. .padding()
  79. .font(.footnote)
  80. .foregroundColor(.secondary)
  81. }
  82. .background(
  83. RoundedRectangle(cornerRadius: 10, style: .continuous)
  84. .fill(Color.chart)
  85. )
  86. }
  87. GroupBox {
  88. VStack {
  89. dummyChart(glucoseData)
  90. HStack(spacing: 15) {
  91. ForEach(0 ..< 4, id: \.self) { index in
  92. widgetButton(for: index)
  93. }
  94. }
  95. .padding()
  96. .overlay(
  97. RoundedRectangle(cornerRadius: 12)
  98. .stroke(style: StrokeStyle(lineWidth: 2, dash: [5]))
  99. .foregroundColor(.gray)
  100. )
  101. .cornerRadius(12)
  102. }
  103. }.padding(.vertical).groupBoxStyle(.dummyChart)
  104. Group {
  105. Text(
  106. "Tap 'Edit Mode' to add or remove a widget. You can re-order widgets by removing them from their current position and adding them to the desired one."
  107. )
  108. Text("Note: Once you confirm the removal of a widget, you cannot undo it.")
  109. }.frame(maxWidth: .infinity, alignment: .leading)
  110. .foregroundColor(.secondary)
  111. .font(.footnote)
  112. .padding(.vertical, 8)
  113. .padding(.horizontal)
  114. Spacer()
  115. }
  116. .padding()
  117. .scrollContentBackground(.hidden).background(color)
  118. .navigationTitle("Widget Configuration")
  119. .navigationBarTitleDisplayMode(.automatic)
  120. .toolbar {
  121. ToolbarItem(placement: .topBarTrailing) {
  122. Button {
  123. isEditMode.toggle()
  124. } label: {
  125. Text(isEditMode ? "Exit Edit Mode" : "Edit Mode")
  126. }
  127. }
  128. }
  129. .onAppear {
  130. loadOrder() // Load the saved order when the view appears
  131. }
  132. .confirmationDialog("Choose Widget to add", isPresented: $showAddItemDialog, titleVisibility: .visible) {
  133. ForEach(LiveActivityItem.allCases.filter { !selectedItems.contains($0) }, id: \.self) { item in
  134. Button(item.displayName) {
  135. if let index = buttonIndexToUpdate {
  136. addItem(item, at: index)
  137. }
  138. }
  139. }
  140. }
  141. }
  142. @ViewBuilder private func widgetButton(for index: Int) -> some View {
  143. if index < selectedItems.count, let selectedItem = selectedItems[index] {
  144. // Display selected item preview
  145. ZStack(alignment: .topTrailing) {
  146. getItemPreview(for: selectedItem)
  147. .frame(width: 50, height: 50)
  148. .padding(5)
  149. .background(Color.clear)
  150. .cornerRadius(12)
  151. .overlay(
  152. RoundedRectangle(cornerRadius: 12)
  153. .stroke(Color.primary, lineWidth: 1)
  154. )
  155. if isEditMode {
  156. Button(action: {
  157. isRemovalConfirmationPresented = true
  158. itemToRemove = selectedItem
  159. }) {
  160. Image(systemName: "minus.circle.fill")
  161. .foregroundColor(Color(UIColor.systemGray2))
  162. .background(Color.white)
  163. .clipShape(Circle())
  164. .font(.system(size: 20))
  165. }
  166. .offset(x: -45, y: -10)
  167. .confirmationDialog("Remove Widget", isPresented: $isRemovalConfirmationPresented, titleVisibility: .hidden) {
  168. Button("Remove Widget", role: .destructive) {
  169. if let itemToRemove = itemToRemove {
  170. removeItem(itemToRemove)
  171. }
  172. }
  173. }
  174. }
  175. }
  176. } else {
  177. // Show "+" symbol for empty slots
  178. Button(action: {
  179. buttonIndexToUpdate = index
  180. showAddItemDialog.toggle()
  181. }) {
  182. VStack {
  183. Image(systemName: "plus")
  184. .font(.title2)
  185. .foregroundColor(.accentColor)
  186. }
  187. .frame(width: 50, height: 50)
  188. .padding(5)
  189. .overlay(
  190. RoundedRectangle(cornerRadius: 12)
  191. .stroke(style: StrokeStyle(lineWidth: 1, dash: [5]))
  192. .foregroundColor(.primary)
  193. )
  194. }
  195. .disabled(!isEditMode)
  196. .buttonStyle(.plain)
  197. }
  198. }
  199. private func getItemPreview(for item: LiveActivityItem) -> some View {
  200. switch item {
  201. case .currentGlucose:
  202. return AnyView(currentGlucosePreview)
  203. case .cob:
  204. return AnyView(cobPreview)
  205. case .iob:
  206. return AnyView(iobPreview)
  207. case .updatedLabel:
  208. return AnyView(updatedLabelPreview)
  209. }
  210. }
  211. @ViewBuilder private func dummyChart(_ glucoseData: [DummyGlucoseData]) -> some View {
  212. Chart {
  213. ForEach(glucoseData) { data in
  214. let pointMarkColor = FreeAPS.getDynamicGlucoseColor(
  215. glucoseValue: Decimal(data.glucoseLevel),
  216. highGlucoseColorValue: !(state.settingsManager.settings.glucoseColorScheme == .dynamicColor) ? state
  217. .settingsManager.settings.highGlucose : Decimal(220),
  218. lowGlucoseColorValue: !(state.settingsManager.settings.glucoseColorScheme == .dynamicColor) ? state
  219. .settingsManager.settings.lowGlucose : Decimal(55),
  220. targetGlucose: Decimal(100),
  221. glucoseColorScheme: state.settingsManager.settings.glucoseColorScheme
  222. )
  223. PointMark(
  224. x: .value("Time", data.time),
  225. y: .value("Glucose Level", data.glucoseLevel)
  226. ).foregroundStyle(pointMarkColor).symbolSize(15)
  227. }
  228. }
  229. .chartYAxis {
  230. AxisMarks(position: .trailing) { _ in
  231. AxisGridLine(stroke: .init(lineWidth: 0.2, dash: [2, 3])).foregroundStyle(Color.white)
  232. AxisValueLabel().foregroundStyle(.primary).font(.footnote)
  233. }
  234. }
  235. .chartYScale(domain: 39 ... 200)
  236. .chartYAxis(.hidden)
  237. .chartPlotStyle { plotContent in
  238. plotContent
  239. .background(
  240. RoundedRectangle(cornerRadius: 12)
  241. .fill(Color.cyan.opacity(0.15))
  242. )
  243. .clipShape(RoundedRectangle(cornerRadius: 12))
  244. }
  245. .chartXAxis {
  246. AxisMarks(position: .automatic) { _ in
  247. AxisGridLine(stroke: .init(lineWidth: 0.2, dash: [2, 3])).foregroundStyle(Color.primary)
  248. }
  249. }
  250. .frame(height: 100)
  251. }
  252. private var currentGlucosePreview: some View {
  253. VStack {
  254. HStack(alignment: .center) {
  255. Text("123")
  256. .fontWeight(.bold)
  257. .font(.caption)
  258. }
  259. HStack(spacing: -5) {
  260. HStack {
  261. Text("\u{2192}")
  262. Text("+6")
  263. }.foregroundStyle(.primary).font(.caption2)
  264. }
  265. }
  266. }
  267. private var cobPreview: some View {
  268. VStack(spacing: 2) {
  269. Text("25 g").fontWeight(.bold).font(.caption)
  270. Text("COB").font(.caption2).foregroundStyle(.primary)
  271. }
  272. }
  273. private var iobPreview: some View {
  274. VStack(spacing: 2) {
  275. Text("2 U").fontWeight(.bold).font(.caption)
  276. Text("IOB").font(.caption2).foregroundStyle(.primary)
  277. }
  278. }
  279. private var updatedLabelPreview: some View {
  280. VStack {
  281. Text("19:05")
  282. .fontWeight(.bold)
  283. .font(.caption)
  284. .foregroundStyle(.primary)
  285. Text("Updated").font(.caption2).foregroundStyle(.primary)
  286. }
  287. }
  288. private func loadOrder() {
  289. if let savedItems = UserDefaults.standard.loadLiveActivityOrder() {
  290. selectedItems = savedItems.count == 4 ? savedItems : savedItems + Array(repeating: nil, count: 4 - savedItems.count)
  291. } else {
  292. selectedItems = LiveActivityItem.defaultItems
  293. saveOrder()
  294. }
  295. updateVisibilityForSelectedItems()
  296. }
  297. private func saveOrder() {
  298. UserDefaults.standard.saveLiveActivityOrder(selectedItems)
  299. }
  300. private func addItem(_ item: LiveActivityItem, at index: Int) {
  301. setItemVisibility(item: item, isVisible: true)
  302. selectedItems[index] = item
  303. saveOrder()
  304. updateVisibilityForSelectedItems()
  305. }
  306. private func removeItem(_ item: LiveActivityItem) {
  307. if let index = selectedItems.firstIndex(of: item) {
  308. selectedItems[index] = nil
  309. setItemVisibility(item: item, isVisible: false)
  310. saveOrder()
  311. }
  312. }
  313. private func setItemVisibility(item: LiveActivityItem, isVisible: Bool) {
  314. switch item {
  315. case .currentGlucose:
  316. state.showCurrentGlucose = isVisible
  317. case .iob:
  318. state.showIOB = isVisible
  319. case .cob:
  320. state.showCOB = isVisible
  321. case .updatedLabel:
  322. state.showUpdatedLabel = isVisible
  323. }
  324. }
  325. private func updateVisibilityForSelectedItems() {
  326. for item in selectedItems {
  327. if let widget = item {
  328. setItemVisibility(item: widget, isVisible: true)
  329. }
  330. }
  331. let allItems = LiveActivityItem.allCases
  332. let hiddenItems = allItems.filter { !selectedItems.contains($0) }
  333. for item in hiddenItems {
  334. setItemVisibility(item: item, isVisible: false)
  335. }
  336. }
  337. }
  338. // Extension for UserDefaults to save and load the order
  339. extension UserDefaults {
  340. private enum Keys {
  341. static let liveActivityOrder = "liveActivityOrder"
  342. }
  343. func saveLiveActivityOrder(_ items: [LiveActivityItem?]) {
  344. let itemStrings = items.map { $0?.rawValue ?? "" }
  345. set(itemStrings, forKey: Keys.liveActivityOrder)
  346. print("Saved order to UserDefaults: \(itemStrings)")
  347. }
  348. func loadLiveActivityOrder() -> [LiveActivityItem?]? {
  349. if let itemStrings = array(forKey: Keys.liveActivityOrder) as? [String] {
  350. return itemStrings.map { $0.isEmpty ? nil : LiveActivityItem(rawValue: $0) }
  351. }
  352. return nil
  353. }
  354. }
  355. // Enum to represent each live activity item
  356. enum LiveActivityItem: String, CaseIterable, Identifiable {
  357. case currentGlucose
  358. case iob
  359. case cob
  360. case updatedLabel
  361. var id: String { rawValue }
  362. static var defaultItems: [LiveActivityItem] {
  363. [.currentGlucose, .iob, .cob, .updatedLabel]
  364. }
  365. var displayName: String {
  366. switch self {
  367. case .currentGlucose:
  368. return "Current Glucose"
  369. case .iob:
  370. return "IOB"
  371. case .cob:
  372. return "COB"
  373. case .updatedLabel:
  374. return "Updated Label"
  375. }
  376. }
  377. }
  378. struct DummyGlucoseData: Identifiable {
  379. let id = UUID()
  380. let time: Double // Time in hours
  381. let glucoseLevel: Int // Glucose level in mg/dL
  382. }
  383. struct DummyChartGroupBoxStyle: GroupBoxStyle {
  384. func makeBody(configuration: Configuration) -> some View {
  385. VStack {
  386. configuration.content
  387. }
  388. .padding()
  389. .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
  390. .background(Color.chart, in: RoundedRectangle(cornerRadius: 12))
  391. .frame(width: UIScreen.main.bounds.width * 0.9)
  392. }
  393. }
  394. extension GroupBoxStyle where Self == DummyChartGroupBoxStyle {
  395. static var dummyChart: DummyChartGroupBoxStyle { .init() }
  396. }