LiveActivityWidgetConfiguration.swift 20 KB

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