LiveActivityWidgetConfiguration.swift 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  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. //
  70. // GroupBox {
  71. // VStack {
  72. // dummyChart
  73. //
  74. // HStack {
  75. // if selectedItems.isEmpty {
  76. // Spacer()
  77. // Button(action: {
  78. // showAddItemDialog.toggle()
  79. // }) {
  80. // VStack {
  81. // Image(systemName: "plus")
  82. // .font(.title2)
  83. // .foregroundColor(.gray)
  84. // }
  85. // .frame(width: 60, height: 40)
  86. // .overlay(
  87. // RoundedRectangle(cornerRadius: 12)
  88. // .stroke(style: StrokeStyle(lineWidth: 2, dash: [5]))
  89. // .foregroundColor(.gray)
  90. // )
  91. // }
  92. // Spacer()
  93. // } else {
  94. // ForEach(Array(selectedItems.enumerated()), id: \.element) { index, item in
  95. // if index > 0 {
  96. // Divider()
  97. // .frame(height: 50)
  98. // }
  99. //
  100. // ZStack(alignment: .topTrailing) {
  101. // getItemPreview(for: item)
  102. // .frame(width: 50, height: 50)
  103. // .padding(5)
  104. // .background(
  105. // draggingItem == item ? Color.blue.opacity(0.2) : Color.clear
  106. // )
  107. // .cornerRadius(12)
  108. // .overlay(
  109. // RoundedRectangle(cornerRadius: 12)
  110. // .stroke(
  111. // draggingItem == item ? Color.blue : Color.primary,
  112. // lineWidth: draggingItem == item ? 2 : 1
  113. // )
  114. // )
  115. // .opacity(draggingItem == item ? 0.85 : 1.0)
  116. // .onDrag {
  117. // self.draggingItem = item
  118. // return NSItemProvider(object: item.rawValue as NSString)
  119. // }
  120. // .onDrop(
  121. // of: [UTType.text],
  122. // delegate: DropViewDelegate(
  123. // item: item,
  124. // items: $selectedItems,
  125. // draggingItem: $draggingItem
  126. // )
  127. // )
  128. // .disabled(!isEditMode)
  129. // .rotationEffect(.degrees(isEditMode ? 2.5 : 0))
  130. // .rotation3DEffect(.degrees(isEditMode ? 2.5 : 0), axis: (x: 0, y: -5, z: 0))
  131. // .animation(
  132. // isEditMode ? Animation.easeInOut(duration: 0.15)
  133. // .repeatForever(autoreverses: true) : .default,
  134. // value: isEditMode
  135. // )
  136. // if isEditMode {
  137. // Button(action: {
  138. // showDeleteAlert = true
  139. // }) {
  140. // Image(systemName: "minus.circle.fill")
  141. // .foregroundColor(Color(UIColor.systemGray2)) // Opaque foreground color
  142. // .background(Color.white) // Adding a background for contrast
  143. // .clipShape(Circle()) // Make sure the background stays circular
  144. // .font(.system(size: 20))
  145. // }
  146. // .offset(x: -45, y: -10)
  147. // .alert(isPresented: $showDeleteAlert) {
  148. // Alert(
  149. // title: Text("Delete Widget"),
  150. // message: Text("Are you sure you want to delete this widget?"),
  151. // primaryButton: .destructive(Text("Delete")) {
  152. // removeItem(item)
  153. // },
  154. // secondaryButton: .cancel()
  155. // )
  156. // }
  157. // }
  158. // }
  159. // .animation(.easeInOut, value: draggingItem)
  160. // .frame(maxWidth: .infinity)
  161. // }
  162. // }
  163. // }
  164. // .padding()
  165. // .overlay(
  166. // RoundedRectangle(cornerRadius: 12)
  167. // .stroke(style: StrokeStyle(lineWidth: 2, dash: [5]))
  168. // .foregroundColor(.gray)
  169. // )
  170. // .cornerRadius(12)
  171. // }
  172. // }.padding(.vertical).groupBoxStyle(.dummyChart)
  173. //
  174. // if isEditMode {
  175. // HStack {
  176. // Image(systemName: "hand.draw.fill")
  177. // Text("Tap 'Add +' to add a widget. Press, drag and drop a widget to re-order a widget.")
  178. // }.frame(maxWidth: .infinity, alignment: .leading)
  179. // .foregroundColor(.secondary)
  180. // .font(.footnote)
  181. // .padding(.horizontal)
  182. // }
  183. //
  184. // Spacer()
  185. // }
  186. // .padding()
  187. // .scrollContentBackground(.hidden).background(color)
  188. // .navigationTitle("Widget Configuration")
  189. // .navigationBarTitleDisplayMode(.automatic)
  190. // .toolbar {
  191. // ToolbarItem(placement: .topBarTrailing) {
  192. // Button {
  193. // isEditMode.toggle()
  194. // } label: {
  195. // HStack {
  196. // Text("Edit")
  197. // }
  198. // }
  199. // }
  200. // ToolbarItem(placement: .topBarTrailing) {
  201. // Button {
  202. // showAddItemDialog.toggle()
  203. // } label: {
  204. // HStack {
  205. // Text("Add")
  206. // Image(systemName: "plus")
  207. // }
  208. // }
  209. // }
  210. // }
  211. // .confirmationDialog("Add Widget", isPresented: $showAddItemDialog, titleVisibility: .visible) {
  212. // ForEach(LiveActivityItem.allCases, id: \.self) { item in
  213. // Button(item.displayName) {
  214. // addItem(item)
  215. // }.disabled(selectedItems.contains(item))
  216. // }
  217. // }
  218. // .onAppear {
  219. // configureView()
  220. // loadOrder()
  221. // }
  222. // }
  223. var body: some View {
  224. VStack {
  225. Group {
  226. VStack(alignment: .leading, spacing: 0) {
  227. Text("Live Activity Personalization".uppercased())
  228. .frame(maxWidth: .infinity, alignment: .leading)
  229. .foregroundColor(.secondary)
  230. .font(.footnote)
  231. .padding(.leading)
  232. }
  233. VStack {
  234. Text(
  235. "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."
  236. )
  237. .padding()
  238. .font(.footnote)
  239. .foregroundColor(.secondary)
  240. }
  241. .background(
  242. RoundedRectangle(cornerRadius: 10, style: .continuous)
  243. .fill(Color.chart)
  244. )
  245. }
  246. GroupBox {
  247. VStack {
  248. dummyChart
  249. HStack(spacing: 15) {
  250. ForEach(0 ..< 4) { index in
  251. widgetButton(for: index)
  252. }
  253. }
  254. .padding()
  255. .overlay(
  256. RoundedRectangle(cornerRadius: 12)
  257. .stroke(style: StrokeStyle(lineWidth: 2, dash: [5]))
  258. .foregroundColor(.gray)
  259. )
  260. .cornerRadius(12)
  261. }
  262. }.padding(.vertical).groupBoxStyle(.dummyChart)
  263. if isEditMode {
  264. Group {
  265. Button {
  266. saveOrder()
  267. isEditMode = false
  268. } label: {
  269. Text("Save Configuration")
  270. .frame(maxWidth: .infinity, alignment: .center)
  271. .tint(Color.white)
  272. .background(Color(.systemBlue))
  273. }
  274. .padding(.vertical)
  275. .tint(Color(.systemBlue))
  276. .buttonStyle(.borderedProminent)
  277. .cornerRadius(12)
  278. }.padding(.vertical)
  279. }
  280. Spacer()
  281. }
  282. .padding()
  283. .scrollContentBackground(.hidden).background(color)
  284. .navigationTitle("Widget Configuration")
  285. .navigationBarTitleDisplayMode(.automatic)
  286. .toolbar {
  287. ToolbarItem(placement: .topBarTrailing) {
  288. Button {
  289. isEditMode.toggle()
  290. } label: {
  291. Text(isEditMode ? "Cancel" : "Edit")
  292. }
  293. }
  294. }
  295. .onAppear {
  296. loadOrder() // Load the saved order when the view appears
  297. }
  298. .confirmationDialog("Add Widget", isPresented: $showAddItemDialog, titleVisibility: .visible) {
  299. ForEach(LiveActivityItem.allCases.filter { !selectedItems.contains($0) }, id: \.self) { item in
  300. Button(item.displayName) {
  301. if let index = buttonIndexToUpdate {
  302. if index == selectedItems.count {
  303. selectedItems.append(item) // Item will be last element in array, just append
  304. } else {
  305. selectedItems[index] = item // Update button index to selected item
  306. }
  307. saveOrder() // Save the order to UserDefaults
  308. }
  309. }
  310. }
  311. }
  312. }
  313. @ViewBuilder private func widgetButton(for index: Int) -> some View {
  314. if index < selectedItems.count {
  315. let selectedItem = selectedItems[index]
  316. ZStack(alignment: .topTrailing) {
  317. getItemPreview(for: selectedItem)
  318. .frame(width: 50, height: 50)
  319. .padding(5)
  320. .background(Color.clear)
  321. .cornerRadius(12)
  322. .overlay(
  323. RoundedRectangle(cornerRadius: 12)
  324. .stroke(
  325. Color.primary,
  326. lineWidth: 1
  327. )
  328. )
  329. if isEditMode {
  330. Button(action: {
  331. showDeleteAlert = true
  332. itemToDelete = selectedItem
  333. }) {
  334. Image(systemName: "minus.circle.fill")
  335. .foregroundColor(Color(UIColor.systemGray2)) // Opaque foreground color
  336. .background(Color.white) // Adding a background for contrast
  337. .clipShape(Circle()) // Make sure the background stays circular
  338. .font(.system(size: 20))
  339. }
  340. .offset(x: -45, y: -10)
  341. .alert(isPresented: $showDeleteAlert) {
  342. Alert(
  343. title: Text("Delete Widget"),
  344. message: Text("Are you sure you want to delete this widget?"),
  345. primaryButton: .destructive(Text("Delete")) {
  346. if let itemToDelete = itemToDelete {
  347. removeItem(itemToDelete)
  348. }
  349. },
  350. secondaryButton: .cancel()
  351. )
  352. }
  353. }
  354. }
  355. } else {
  356. // Show "+" symbol if no item is selected
  357. Button(action: {
  358. buttonIndexToUpdate = index
  359. showAddItemDialog.toggle()
  360. }) {
  361. VStack {
  362. Image(systemName: "plus")
  363. .font(.title2)
  364. .foregroundColor(.accentColor)
  365. }
  366. .frame(width: 50, height: 50)
  367. .padding(5)
  368. .overlay(
  369. RoundedRectangle(cornerRadius: 12)
  370. .stroke(style: StrokeStyle(lineWidth: 1, dash: [5]))
  371. .foregroundColor(.primary)
  372. )
  373. }.buttonStyle(.plain)
  374. }
  375. }
  376. private func getItemPreview(for item: LiveActivityItem) -> some View {
  377. switch item {
  378. case .currentGlucose:
  379. return AnyView(currentGlucosePreview)
  380. case .cob:
  381. return AnyView(cobPreview)
  382. case .iob:
  383. return AnyView(iobPreview)
  384. case .updatedLabel:
  385. return AnyView(updatedLabelPreview)
  386. }
  387. }
  388. private var dummyChart: some View {
  389. Chart {
  390. ForEach(glucoseData) { data in
  391. PointMark(
  392. x: .value("Time", data.time),
  393. y: .value("Glucose Level", data.glucoseLevel)
  394. ).foregroundStyle(.green.gradient).symbolSize(15)
  395. }
  396. }
  397. .chartPlotStyle { plotContent in
  398. plotContent
  399. .background(
  400. RoundedRectangle(cornerRadius: 12)
  401. .fill(Color.cyan.opacity(0.15))
  402. )
  403. .clipShape(RoundedRectangle(cornerRadius: 12))
  404. }
  405. .chartYAxis {
  406. AxisMarks(position: .trailing) { _ in
  407. AxisGridLine(stroke: .init(lineWidth: 0.2, dash: [2, 3])).foregroundStyle(Color.primary)
  408. }
  409. }
  410. .chartYAxis(.hidden)
  411. .chartYScale(domain: 40 ... 200)
  412. .chartXAxis {
  413. AxisMarks(position: .automatic) { _ in
  414. AxisGridLine(stroke: .init(lineWidth: 0.2, dash: [2, 3])).foregroundStyle(Color.primary)
  415. }
  416. }
  417. .chartXAxis(.hidden)
  418. .frame(height: 100)
  419. }
  420. private var currentGlucosePreview: some View {
  421. VStack {
  422. HStack(alignment: .center) {
  423. Text("123")
  424. .fontWeight(.bold)
  425. .font(.caption)
  426. }
  427. HStack(spacing: -5) {
  428. HStack {
  429. Text("\u{2192}")
  430. Text("+6")
  431. }.foregroundStyle(.primary).font(.caption2)
  432. }
  433. }
  434. }
  435. private var cobPreview: some View {
  436. VStack(spacing: 2) {
  437. Text("25 g").fontWeight(.bold).font(.caption)
  438. Text("COB").font(.caption2).foregroundStyle(.primary)
  439. }
  440. }
  441. private var iobPreview: some View {
  442. VStack(spacing: 2) {
  443. Text("2 U").fontWeight(.bold).font(.caption)
  444. Text("IOB").font(.caption2).foregroundStyle(.primary)
  445. }
  446. }
  447. private var updatedLabelPreview: some View {
  448. VStack {
  449. Text("19:05")
  450. .fontWeight(.bold)
  451. .font(.caption)
  452. .foregroundStyle(.primary)
  453. Text("Updated").font(.caption2).foregroundStyle(.primary)
  454. }
  455. }
  456. private func loadOrder() {
  457. if let savedItems = UserDefaults.standard.loadLiveActivityOrder() {
  458. selectedItems = savedItems
  459. } else {
  460. selectedItems = LiveActivityItem.defaultItems
  461. saveOrder()
  462. }
  463. print("Loaded order: \(selectedItems.map(\.rawValue))")
  464. updateVisibilityForSelectedItems()
  465. }
  466. private func saveOrder() {
  467. print("Saving order: \(selectedItems.map(\.rawValue))")
  468. UserDefaults.standard.saveLiveActivityOrder(selectedItems)
  469. }
  470. private func addItem(_ item: LiveActivityItem) {
  471. setItemVisibility(item: item, isVisible: true)
  472. selectedItems.append(item)
  473. saveOrder()
  474. }
  475. private func removeItem(_ item: LiveActivityItem) {
  476. setItemVisibility(item: item, isVisible: false)
  477. selectedItems.removeAll { $0 == item }
  478. saveOrder()
  479. }
  480. private func setItemVisibility(item: LiveActivityItem, isVisible: Bool) {
  481. switch item {
  482. case .currentGlucose:
  483. state.showCurrentGlucose = isVisible
  484. case .iob:
  485. state.showIOB = isVisible
  486. case .cob:
  487. state.showCOB = isVisible
  488. case .updatedLabel:
  489. state.showUpdatedLabel = isVisible
  490. }
  491. }
  492. private func updateVisibilityForSelectedItems() {
  493. for item in selectedItems {
  494. setItemVisibility(item: item, isVisible: true)
  495. }
  496. let allItems = LiveActivityItem.allCases
  497. let hiddenItems = allItems.filter { !selectedItems.contains($0) }
  498. for item in hiddenItems {
  499. setItemVisibility(item: item, isVisible: false)
  500. }
  501. }
  502. }
  503. struct DropViewDelegate: DropDelegate {
  504. let item: LiveActivityItem
  505. @Binding var items: [LiveActivityItem]
  506. @Binding var draggingItem: LiveActivityItem?
  507. func dropEntered(info _: DropInfo) {
  508. guard let draggingItem = draggingItem else { return }
  509. if draggingItem != item {
  510. let fromIndex = items.firstIndex(of: draggingItem)!
  511. let toIndex = items.firstIndex(of: item)!
  512. withAnimation {
  513. items.move(fromOffsets: IndexSet(integer: fromIndex), toOffset: toIndex > fromIndex ? toIndex + 1 : toIndex)
  514. }
  515. // Save to User Defaults
  516. saveOrder()
  517. // Trigger Live Activity Update
  518. Foundation.NotificationCenter.default.post(name: .liveActivityOrderDidChange, object: nil)
  519. }
  520. }
  521. func performDrop(info _: DropInfo) -> Bool {
  522. draggingItem = nil
  523. return true
  524. }
  525. private func saveOrder() {
  526. UserDefaults.standard.saveLiveActivityOrder(items)
  527. }
  528. }
  529. // Extension for UserDefaults to save and load the order
  530. extension UserDefaults {
  531. private enum Keys {
  532. static let liveActivityOrder = "liveActivityOrder"
  533. }
  534. func saveLiveActivityOrder(_ items: [LiveActivityItem]) {
  535. let itemStrings = items.map(\.rawValue)
  536. set(itemStrings, forKey: Keys.liveActivityOrder)
  537. }
  538. func loadLiveActivityOrder() -> [LiveActivityItem]? {
  539. if let itemStrings = array(forKey: Keys.liveActivityOrder) as? [String] {
  540. return itemStrings.compactMap { LiveActivityItem(rawValue: $0) }
  541. }
  542. return nil
  543. }
  544. }
  545. // Enum to represent each live activity item
  546. enum LiveActivityItem: String, CaseIterable, Identifiable {
  547. case currentGlucose
  548. case iob
  549. case cob
  550. case updatedLabel
  551. var id: String { rawValue }
  552. static var defaultItems: [LiveActivityItem] {
  553. [.currentGlucose, .iob, .cob, .updatedLabel]
  554. }
  555. var displayName: String {
  556. switch self {
  557. case .currentGlucose:
  558. return "Current Glucose"
  559. case .iob:
  560. return "IOB"
  561. case .cob:
  562. return "COB"
  563. case .updatedLabel:
  564. return "Updated Label"
  565. }
  566. }
  567. }
  568. struct DummyChart: Identifiable {
  569. let id = UUID()
  570. let time: Double // Time in hours
  571. let glucoseLevel: Double // Glucose level in mg/dL
  572. }
  573. struct DummyChartGroupBoxStyle: GroupBoxStyle {
  574. func makeBody(configuration: Configuration) -> some View {
  575. VStack {
  576. configuration.content
  577. }
  578. .padding()
  579. .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
  580. .background(Color.chart, in: RoundedRectangle(cornerRadius: 12))
  581. .frame(width: UIScreen.main.bounds.width * 0.9)
  582. }
  583. }
  584. extension GroupBoxStyle where Self == DummyChartGroupBoxStyle {
  585. static var dummyChart: DummyChartGroupBoxStyle { .init() }
  586. }