LiveActivityBottomRowConfiguration.swift 17 KB

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