LiveActivityWidgetConfiguration.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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. }
  246. .disabled(selectedItems.contains(item))
  247. // This causes the type check error
  248. // .disabled(selectedItems.contains { $0.value == item }) // Disable already selected items
  249. }
  250. }
  251. }
  252. @ViewBuilder private func widgetButton(for index: Int) -> some View {
  253. Button(action: {
  254. buttonIndexToUpdate = index
  255. showAddItemDialog.toggle()
  256. }) {
  257. // This causes an index out of range error
  258. // if let selectedItem = LiveActivityItem.allCases.first(where: { $0.id == selectedItems[index].id }) {
  259. // // Show item preview if an item is selected
  260. // getItemPreview(for: selectedItem)
  261. // }
  262. if index < selectedItems.count {
  263. // Zeige Vorschau, wenn ein Item ausgewählt wurde
  264. let selectedItem = selectedItems[index]
  265. getItemPreview(for: selectedItem)
  266. } else {
  267. // Show "+" symbol if no item is selected
  268. VStack {
  269. Image(systemName: "plus")
  270. .font(.title2)
  271. .foregroundColor(.gray)
  272. }
  273. .frame(width: 60, height: 40)
  274. .overlay(
  275. RoundedRectangle(cornerRadius: 12)
  276. .stroke(style: StrokeStyle(lineWidth: 2, dash: [5]))
  277. .foregroundColor(.gray)
  278. )
  279. }
  280. }
  281. }
  282. private func getItemPreview(for item: LiveActivityItem) -> some View {
  283. switch item {
  284. case .currentGlucose:
  285. return AnyView(currentGlucosePreview)
  286. case .cob:
  287. return AnyView(cobPreview)
  288. case .iob:
  289. return AnyView(iobPreview)
  290. case .updatedLabel:
  291. return AnyView(updatedLabelPreview)
  292. }
  293. }
  294. private var dummyChart: some View {
  295. Chart {
  296. ForEach(glucoseData) { data in
  297. PointMark(
  298. x: .value("Time", data.time),
  299. y: .value("Glucose Level", data.glucoseLevel)
  300. ).foregroundStyle(.green.gradient).symbolSize(15)
  301. }
  302. }
  303. .chartPlotStyle { plotContent in
  304. plotContent
  305. .background(
  306. RoundedRectangle(cornerRadius: 12)
  307. .fill(Color.cyan.opacity(0.15))
  308. )
  309. .clipShape(RoundedRectangle(cornerRadius: 12))
  310. }
  311. .chartYAxis {
  312. AxisMarks(position: .trailing) { _ in
  313. AxisGridLine(stroke: .init(lineWidth: 0.2, dash: [2, 3])).foregroundStyle(Color.primary)
  314. }
  315. }
  316. .chartYAxis(.hidden)
  317. .chartYScale(domain: 40 ... 200)
  318. .chartXAxis {
  319. AxisMarks(position: .automatic) { _ in
  320. AxisGridLine(stroke: .init(lineWidth: 0.2, dash: [2, 3])).foregroundStyle(Color.primary)
  321. }
  322. }
  323. .chartXAxis(.hidden)
  324. .frame(height: 100)
  325. }
  326. private var currentGlucosePreview: some View {
  327. VStack {
  328. HStack(alignment: .center) {
  329. Text("123")
  330. .fontWeight(.bold)
  331. .font(.caption)
  332. }
  333. HStack(spacing: -5) {
  334. HStack {
  335. Text("\u{2192}")
  336. Text("+6")
  337. }.foregroundStyle(.primary).font(.caption2)
  338. }
  339. }
  340. }
  341. private var cobPreview: some View {
  342. VStack(spacing: 2) {
  343. Text("25 g").fontWeight(.bold).font(.caption)
  344. Text("COB").font(.caption2).foregroundStyle(.primary)
  345. }
  346. }
  347. private var iobPreview: some View {
  348. VStack(spacing: 2) {
  349. Text("2 U").fontWeight(.bold).font(.caption)
  350. Text("IOB").font(.caption2).foregroundStyle(.primary)
  351. }
  352. }
  353. private var updatedLabelPreview: some View {
  354. VStack {
  355. Text("19:05")
  356. .fontWeight(.bold)
  357. .font(.caption)
  358. .foregroundStyle(.primary)
  359. Text("Updated").font(.caption2).foregroundStyle(.primary)
  360. }
  361. }
  362. private func loadOrder() {
  363. if let savedItems = UserDefaults.standard.loadLiveActivityOrder() {
  364. selectedItems = savedItems
  365. } else {
  366. selectedItems = LiveActivityItem.defaultItems
  367. saveOrder()
  368. }
  369. print("Loaded order: \(selectedItems.map(\.rawValue))")
  370. updateVisibilityForSelectedItems()
  371. }
  372. private func saveOrder() {
  373. print("Saving order: \(selectedItems.map(\.rawValue))")
  374. UserDefaults.standard.saveLiveActivityOrder(selectedItems)
  375. }
  376. private func addItem(_ item: LiveActivityItem) {
  377. setItemVisibility(item: item, isVisible: true)
  378. selectedItems.append(item)
  379. saveOrder()
  380. }
  381. private func removeItem(_ item: LiveActivityItem) {
  382. setItemVisibility(item: item, isVisible: false)
  383. selectedItems.removeAll { $0 == item }
  384. saveOrder()
  385. }
  386. private func setItemVisibility(item: LiveActivityItem, isVisible: Bool) {
  387. switch item {
  388. case .currentGlucose:
  389. state.showCurrentGlucose = isVisible
  390. case .iob:
  391. state.showIOB = isVisible
  392. case .cob:
  393. state.showCOB = isVisible
  394. case .updatedLabel:
  395. state.showUpdatedLabel = isVisible
  396. }
  397. }
  398. private func updateVisibilityForSelectedItems() {
  399. for item in selectedItems {
  400. setItemVisibility(item: item, isVisible: true)
  401. }
  402. let allItems = LiveActivityItem.allCases
  403. let hiddenItems = allItems.filter { !selectedItems.contains($0) }
  404. for item in hiddenItems {
  405. setItemVisibility(item: item, isVisible: false)
  406. }
  407. }
  408. }
  409. struct DropViewDelegate: DropDelegate {
  410. let item: LiveActivityItem
  411. @Binding var items: [LiveActivityItem]
  412. @Binding var draggingItem: LiveActivityItem?
  413. func dropEntered(info _: DropInfo) {
  414. guard let draggingItem = draggingItem else { return }
  415. if draggingItem != item {
  416. let fromIndex = items.firstIndex(of: draggingItem)!
  417. let toIndex = items.firstIndex(of: item)!
  418. withAnimation {
  419. items.move(fromOffsets: IndexSet(integer: fromIndex), toOffset: toIndex > fromIndex ? toIndex + 1 : toIndex)
  420. }
  421. // Save to User Defaults
  422. saveOrder()
  423. // Trigger Live Activity Update
  424. Foundation.NotificationCenter.default.post(name: .liveActivityOrderDidChange, object: nil)
  425. }
  426. }
  427. func performDrop(info _: DropInfo) -> Bool {
  428. draggingItem = nil
  429. return true
  430. }
  431. private func saveOrder() {
  432. UserDefaults.standard.saveLiveActivityOrder(items)
  433. }
  434. }
  435. // Extension for UserDefaults to save and load the order
  436. extension UserDefaults {
  437. private enum Keys {
  438. static let liveActivityOrder = "liveActivityOrder"
  439. }
  440. func saveLiveActivityOrder(_ items: [LiveActivityItem]) {
  441. let itemStrings = items.map(\.rawValue)
  442. set(itemStrings, forKey: Keys.liveActivityOrder)
  443. }
  444. func loadLiveActivityOrder() -> [LiveActivityItem]? {
  445. if let itemStrings = array(forKey: Keys.liveActivityOrder) as? [String] {
  446. return itemStrings.compactMap { LiveActivityItem(rawValue: $0) }
  447. }
  448. return nil
  449. }
  450. }
  451. // Enum to represent each live activity item
  452. enum LiveActivityItem: String, CaseIterable, Identifiable {
  453. case currentGlucose
  454. case iob
  455. case cob
  456. case updatedLabel
  457. var id: String { rawValue }
  458. static var defaultItems: [LiveActivityItem] {
  459. [.currentGlucose, .iob, .cob, .updatedLabel]
  460. }
  461. var displayName: String {
  462. switch self {
  463. case .currentGlucose:
  464. return "Current Glucose"
  465. case .iob:
  466. return "IOB"
  467. case .cob:
  468. return "COB"
  469. case .updatedLabel:
  470. return "Updated Label"
  471. }
  472. }
  473. }
  474. struct DummyChart: Identifiable {
  475. let id = UUID()
  476. let time: Double // Time in hours
  477. let glucoseLevel: Double // Glucose level in mg/dL
  478. }
  479. struct DummyChartGroupBoxStyle: GroupBoxStyle {
  480. func makeBody(configuration: Configuration) -> some View {
  481. VStack {
  482. configuration.content
  483. }
  484. .padding()
  485. .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
  486. .background(Color.chart, in: RoundedRectangle(cornerRadius: 12))
  487. .frame(width: UIScreen.main.bounds.width * 0.9)
  488. }
  489. }
  490. extension GroupBoxStyle where Self == DummyChartGroupBoxStyle {
  491. static var dummyChart: DummyChartGroupBoxStyle { .init() }
  492. }