LiveActivityBottomRowConfiguration.swift 17 KB

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