LiveActivityWidgetConfiguration.swift 16 KB

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