LiveActivityWidgetConfiguration.swift 15 KB

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