LiveActivityWidgetConfiguration.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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] = []
  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 itemToDelete: LiveActivityItem?
  15. @State private var showDeleteAlert: 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. // Dummy data for glucose levels
  35. private var glucoseData: [DummyChart] {
  36. var data = [DummyChart]()
  37. let totalMinutes = 6 * 60 // 6 hours in minutes
  38. let interval = 5 // 5 minutes interval for each data point
  39. for minute in stride(from: 0, to: totalMinutes, by: interval) {
  40. let time = Double(minute) / 60.0 // Convert minutes to hours
  41. let glucoseLevel = 100 + 20 * sin(time) // Oscillating sine wave pattern
  42. data.append(DummyChart(time: Double(minute), glucoseLevel: glucoseLevel))
  43. }
  44. return data
  45. }
  46. var body: some View {
  47. VStack {
  48. Group {
  49. VStack(alignment: .leading, spacing: 0) {
  50. Text("Live Activity Personalization".uppercased())
  51. .frame(maxWidth: .infinity, alignment: .leading)
  52. .foregroundColor(.secondary)
  53. .font(.footnote)
  54. .padding(.leading)
  55. }
  56. VStack {
  57. Text(
  58. "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."
  59. )
  60. .padding()
  61. .font(.footnote)
  62. .foregroundColor(.secondary)
  63. }
  64. .background(
  65. RoundedRectangle(cornerRadius: 10, style: .continuous)
  66. .fill(Color.chart)
  67. )
  68. }
  69. GroupBox {
  70. VStack {
  71. dummyChart
  72. HStack(spacing: 15) {
  73. ForEach(0 ..< 4) { index in
  74. widgetButton(for: index)
  75. }
  76. }
  77. .padding()
  78. .overlay(
  79. RoundedRectangle(cornerRadius: 12)
  80. .stroke(style: StrokeStyle(lineWidth: 2, dash: [5]))
  81. .foregroundColor(.gray)
  82. )
  83. .cornerRadius(12)
  84. }
  85. }.padding(.vertical).groupBoxStyle(.dummyChart)
  86. Group {
  87. Text(
  88. "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."
  89. )
  90. Text("Note: Once you confirm a deletion, you cannot undo it.")
  91. }.frame(maxWidth: .infinity, alignment: .leading)
  92. .foregroundColor(.secondary)
  93. .font(.footnote)
  94. .padding(.vertical, 8)
  95. .padding(.horizontal)
  96. // Group {
  97. // Button {
  98. // saveOrder()
  99. // isEditMode = false
  100. // } label: {
  101. // Text("Save Configuration")
  102. // .frame(maxWidth: .infinity, alignment: .center)
  103. // .tint(Color.white)
  104. // .background(Color(.systemBlue))
  105. // }
  106. // .padding(.vertical)
  107. // .tint(Color(.systemBlue))
  108. // .buttonStyle(.borderedProminent)
  109. // .cornerRadius(12)
  110. // }.padding(.vertical)
  111. // }
  112. Spacer()
  113. }
  114. .padding()
  115. .scrollContentBackground(.hidden).background(color)
  116. .navigationTitle("Widget Configuration")
  117. .navigationBarTitleDisplayMode(.automatic)
  118. .toolbar {
  119. ToolbarItem(placement: .topBarTrailing) {
  120. Button {
  121. isEditMode.toggle()
  122. } label: {
  123. Text(isEditMode ? "Exit Edit Mode" : "Edit Mode")
  124. }
  125. }
  126. }
  127. .onAppear {
  128. loadOrder() // Load the saved order when the view appears
  129. }
  130. .confirmationDialog("Choose Widget to add", isPresented: $showAddItemDialog, titleVisibility: .visible) {
  131. ForEach(LiveActivityItem.allCases.filter { !selectedItems.contains($0) }, id: \.self) { item in
  132. Button(item.displayName) {
  133. if let index = buttonIndexToUpdate {
  134. if index == selectedItems.count {
  135. selectedItems.append(item) // Item will be last element in array, just append
  136. } else {
  137. selectedItems[index] = item // Update button index to selected item
  138. }
  139. saveOrder() // Save the order to UserDefaults
  140. }
  141. }
  142. }
  143. }
  144. }
  145. @ViewBuilder private func widgetButton(for index: Int) -> some View {
  146. if index < selectedItems.count {
  147. let selectedItem = selectedItems[index]
  148. ZStack(alignment: .topTrailing) {
  149. getItemPreview(for: selectedItem)
  150. .frame(width: 50, height: 50)
  151. .padding(5)
  152. .background(Color.clear)
  153. .cornerRadius(12)
  154. .overlay(
  155. RoundedRectangle(cornerRadius: 12)
  156. .stroke(
  157. Color.primary,
  158. lineWidth: 1
  159. )
  160. )
  161. if isEditMode {
  162. Button(action: {
  163. showDeleteAlert = true
  164. itemToDelete = selectedItem
  165. }) {
  166. Image(systemName: "minus.circle.fill")
  167. .foregroundColor(Color(UIColor.systemGray2)) // Opaque foreground color
  168. .background(Color.white) // Adding a background for contrast
  169. .clipShape(Circle()) // Make sure the background stays circular
  170. .font(.system(size: 20))
  171. }
  172. .offset(x: -45, y: -10)
  173. .confirmationDialog("Delete Widget", isPresented: $showDeleteAlert, titleVisibility: .hidden) {
  174. Button("Delete Widget", role: .destructive) {
  175. if let itemToDelete = itemToDelete {
  176. removeItem(itemToDelete)
  177. }
  178. }
  179. }
  180. }
  181. }
  182. } else {
  183. // Show "+" symbol if no item is selected
  184. Button(action: {
  185. buttonIndexToUpdate = index
  186. showAddItemDialog.toggle()
  187. }) {
  188. VStack {
  189. Image(systemName: "plus")
  190. .font(.title2)
  191. .foregroundColor(.accentColor)
  192. }
  193. .frame(width: 50, height: 50)
  194. .padding(5)
  195. .overlay(
  196. RoundedRectangle(cornerRadius: 12)
  197. .stroke(style: StrokeStyle(lineWidth: 1, dash: [5]))
  198. .foregroundColor(.primary)
  199. )
  200. }
  201. .disabled(!isEditMode)
  202. .buttonStyle(.plain)
  203. }
  204. }
  205. private func getItemPreview(for item: LiveActivityItem) -> some View {
  206. switch item {
  207. case .currentGlucose:
  208. return AnyView(currentGlucosePreview)
  209. case .cob:
  210. return AnyView(cobPreview)
  211. case .iob:
  212. return AnyView(iobPreview)
  213. case .updatedLabel:
  214. return AnyView(updatedLabelPreview)
  215. }
  216. }
  217. private var dummyChart: some View {
  218. Chart {
  219. ForEach(glucoseData) { data in
  220. let pointMarkColor = FreeAPS.getDynamicGlucoseColor(
  221. glucoseValue: Decimal(data.glucoseLevel),
  222. highGlucoseColorValue: state.settingsManager.settings.highGlucose,
  223. lowGlucoseColorValue: state.settingsManager.settings.lowGlucose,
  224. targetGlucose: state.units == .mgdL ? Decimal(100) : 100.asMmolL,
  225. glucoseColorScheme: state.settingsManager.settings.glucoseColorScheme
  226. )
  227. PointMark(
  228. x: .value("Time", data.time),
  229. y: .value("Glucose Level", data.glucoseLevel)
  230. ).foregroundStyle(pointMarkColor).symbolSize(15)
  231. }
  232. }
  233. .chartPlotStyle { plotContent in
  234. plotContent
  235. .background(
  236. RoundedRectangle(cornerRadius: 12)
  237. .fill(Color.cyan.opacity(0.15))
  238. )
  239. .clipShape(RoundedRectangle(cornerRadius: 12))
  240. }
  241. .chartYAxis {
  242. AxisMarks(position: .trailing) { _ in
  243. AxisGridLine(stroke: .init(lineWidth: 0.2, dash: [2, 3])).foregroundStyle(Color.primary)
  244. }
  245. }
  246. .chartYAxis(.hidden)
  247. .chartYScale(domain: 40 ... 200)
  248. .chartXAxis {
  249. AxisMarks(position: .automatic) { _ in
  250. AxisGridLine(stroke: .init(lineWidth: 0.2, dash: [2, 3])).foregroundStyle(Color.primary)
  251. }
  252. }
  253. .chartXAxis(.hidden)
  254. .frame(height: 100)
  255. }
  256. private var currentGlucosePreview: some View {
  257. VStack {
  258. HStack(alignment: .center) {
  259. Text("123")
  260. .fontWeight(.bold)
  261. .font(.caption)
  262. }
  263. HStack(spacing: -5) {
  264. HStack {
  265. Text("\u{2192}")
  266. Text("+6")
  267. }.foregroundStyle(.primary).font(.caption2)
  268. }
  269. }
  270. }
  271. private var cobPreview: some View {
  272. VStack(spacing: 2) {
  273. Text("25 g").fontWeight(.bold).font(.caption)
  274. Text("COB").font(.caption2).foregroundStyle(.primary)
  275. }
  276. }
  277. private var iobPreview: some View {
  278. VStack(spacing: 2) {
  279. Text("2 U").fontWeight(.bold).font(.caption)
  280. Text("IOB").font(.caption2).foregroundStyle(.primary)
  281. }
  282. }
  283. private var updatedLabelPreview: some View {
  284. VStack {
  285. Text("19:05")
  286. .fontWeight(.bold)
  287. .font(.caption)
  288. .foregroundStyle(.primary)
  289. Text("Updated").font(.caption2).foregroundStyle(.primary)
  290. }
  291. }
  292. private func loadOrder() {
  293. if let savedItems = UserDefaults.standard.loadLiveActivityOrder() {
  294. selectedItems = savedItems
  295. } else {
  296. selectedItems = LiveActivityItem.defaultItems
  297. saveOrder()
  298. }
  299. print("Loaded order: \(selectedItems.map(\.rawValue))")
  300. updateVisibilityForSelectedItems()
  301. }
  302. private func saveOrder() {
  303. print("Saving order: \(selectedItems.map(\.rawValue))")
  304. UserDefaults.standard.saveLiveActivityOrder(selectedItems)
  305. }
  306. private func addItem(_ item: LiveActivityItem) {
  307. setItemVisibility(item: item, isVisible: true)
  308. selectedItems.append(item)
  309. saveOrder()
  310. }
  311. private func removeItem(_ item: LiveActivityItem) {
  312. setItemVisibility(item: item, isVisible: false)
  313. selectedItems.removeAll { $0 == item }
  314. saveOrder()
  315. }
  316. private func setItemVisibility(item: LiveActivityItem, isVisible: Bool) {
  317. switch item {
  318. case .currentGlucose:
  319. state.showCurrentGlucose = isVisible
  320. case .iob:
  321. state.showIOB = isVisible
  322. case .cob:
  323. state.showCOB = isVisible
  324. case .updatedLabel:
  325. state.showUpdatedLabel = isVisible
  326. }
  327. }
  328. private func updateVisibilityForSelectedItems() {
  329. for item in selectedItems {
  330. setItemVisibility(item: item, isVisible: true)
  331. }
  332. let allItems = LiveActivityItem.allCases
  333. let hiddenItems = allItems.filter { !selectedItems.contains($0) }
  334. for item in hiddenItems {
  335. setItemVisibility(item: item, isVisible: false)
  336. }
  337. }
  338. }
  339. struct DropViewDelegate: DropDelegate {
  340. let item: LiveActivityItem
  341. @Binding var items: [LiveActivityItem]
  342. @Binding var draggingItem: LiveActivityItem?
  343. func dropEntered(info _: DropInfo) {
  344. guard let draggingItem = draggingItem else { return }
  345. if draggingItem != item {
  346. let fromIndex = items.firstIndex(of: draggingItem)!
  347. let toIndex = items.firstIndex(of: item)!
  348. withAnimation {
  349. items.move(fromOffsets: IndexSet(integer: fromIndex), toOffset: toIndex > fromIndex ? toIndex + 1 : toIndex)
  350. }
  351. // Save to User Defaults
  352. saveOrder()
  353. // Trigger Live Activity Update
  354. Foundation.NotificationCenter.default.post(name: .liveActivityOrderDidChange, object: nil)
  355. }
  356. }
  357. func performDrop(info _: DropInfo) -> Bool {
  358. draggingItem = nil
  359. return true
  360. }
  361. private func saveOrder() {
  362. UserDefaults.standard.saveLiveActivityOrder(items)
  363. }
  364. }
  365. // Extension for UserDefaults to save and load the order
  366. extension UserDefaults {
  367. private enum Keys {
  368. static let liveActivityOrder = "liveActivityOrder"
  369. }
  370. func saveLiveActivityOrder(_ items: [LiveActivityItem]) {
  371. let itemStrings = items.map(\.rawValue)
  372. set(itemStrings, forKey: Keys.liveActivityOrder)
  373. }
  374. func loadLiveActivityOrder() -> [LiveActivityItem]? {
  375. if let itemStrings = array(forKey: Keys.liveActivityOrder) as? [String] {
  376. return itemStrings.compactMap { LiveActivityItem(rawValue: $0) }
  377. }
  378. return nil
  379. }
  380. }
  381. // Enum to represent each live activity item
  382. enum LiveActivityItem: String, CaseIterable, Identifiable {
  383. case currentGlucose
  384. case iob
  385. case cob
  386. case updatedLabel
  387. var id: String { rawValue }
  388. static var defaultItems: [LiveActivityItem] {
  389. [.currentGlucose, .iob, .cob, .updatedLabel]
  390. }
  391. var displayName: String {
  392. switch self {
  393. case .currentGlucose:
  394. return "Current Glucose"
  395. case .iob:
  396. return "IOB"
  397. case .cob:
  398. return "COB"
  399. case .updatedLabel:
  400. return "Updated Label"
  401. }
  402. }
  403. }
  404. struct DummyChart: Identifiable {
  405. let id = UUID()
  406. let time: Double // Time in hours
  407. let glucoseLevel: Double // Glucose level in mg/dL
  408. }
  409. struct DummyChartGroupBoxStyle: GroupBoxStyle {
  410. func makeBody(configuration: Configuration) -> some View {
  411. VStack {
  412. configuration.content
  413. }
  414. .padding()
  415. .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
  416. .background(Color.chart, in: RoundedRectangle(cornerRadius: 12))
  417. .frame(width: UIScreen.main.bounds.width * 0.9)
  418. }
  419. }
  420. extension GroupBoxStyle where Self == DummyChartGroupBoxStyle {
  421. static var dummyChart: DummyChartGroupBoxStyle { .init() }
  422. }