TherapySettingEditorView.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. import SwiftUI
  2. struct TherapySettingEditorView: View {
  3. @Binding var items: [TherapySettingItem]
  4. var unit: TherapySettingUnit
  5. var timeOptions: [TimeInterval]
  6. var valueOptions: [Decimal]
  7. var validateOnDelete: (() -> Void)?
  8. @State private var selectedItemID: UUID?
  9. var body: some View {
  10. List {
  11. HStack {
  12. Text("Entries").bold()
  13. Spacer()
  14. Button {
  15. // Prepare and add new entry
  16. let lastTime = items.last?.time ?? 0
  17. let newTime = min(lastTime + 1800, 23 * 3600 + 1800)
  18. let newValue = items.last?.value ?? 1.0
  19. items.append(TherapySettingItem(time: newTime, value: newValue))
  20. // Reset selected item to close picker
  21. selectedItemID = nil
  22. // Sort items, in case user has changed time of one item, then taps 'Add'
  23. sortTherapyItems()
  24. } label: {
  25. HStack {
  26. Image(systemName: "plus.circle.fill")
  27. Text("Add")
  28. }.foregroundColor(.accentColor)
  29. }
  30. .disabled(items.count >= 48)
  31. }
  32. .listRowBackground(Color.chart.opacity(0.65))
  33. .padding(.vertical, 5)
  34. ForEach($items) { $item in
  35. VStack(spacing: 0) {
  36. Button {
  37. selectedItemID = selectedItemID == item.id ? nil : item.id
  38. sortTherapyItems()
  39. } label: {
  40. HStack {
  41. HStack {
  42. Text(displayText(for: unit, decimalValue: item.value))
  43. .foregroundStyle(
  44. selectedItemID == item.id ? Color.accentColor : Color
  45. .primary
  46. )
  47. Text(unit.displayName)
  48. .foregroundStyle(Color.secondary)
  49. }
  50. Spacer()
  51. HStack {
  52. Text("starts at").foregroundStyle(Color.secondary)
  53. let timeIndex = timeOptions.firstIndex { abs($0 - item.time) < 1 } ?? 0
  54. let time = timeOptions[timeIndex]
  55. let date = Date(timeIntervalSince1970: time)
  56. let timeString = timeFormatter.string(from: date)
  57. Text(timeString).foregroundStyle(selectedItemID == item.id ? Color.accentColor : Color.primary)
  58. }
  59. }
  60. .contentShape(Rectangle())
  61. }
  62. .buttonStyle(.plain)
  63. if selectedItemID == item.id {
  64. timeValuePickerRow(
  65. item: $item,
  66. timeOptions: timeOptions,
  67. valueOptions: valueOptions,
  68. unit: unit
  69. )
  70. .transition(.slide)
  71. }
  72. }
  73. .swipeActions(edge: .trailing, allowsFullSwipe: true) {
  74. if let index = items.firstIndex(where: { $0.id == item.id }), items.count > 1 {
  75. Button(role: .destructive) {
  76. items.remove(at: index)
  77. selectedItemID = nil
  78. validateTherapySettingItems()
  79. } label: {
  80. Label("Delete", systemImage: "trash")
  81. }
  82. }
  83. }
  84. }
  85. .listRowBackground(Color.chart.opacity(0.65))
  86. Rectangle().fill(Color.chart.opacity(0.65)).frame(height: 10)
  87. .clipShape(
  88. .rect(
  89. topLeadingRadius: 0,
  90. bottomLeadingRadius: 10,
  91. bottomTrailingRadius: 10,
  92. topTrailingRadius: 0
  93. )
  94. )
  95. .listRowBackground(Color.clear)
  96. .listRowInsets(EdgeInsets(top: -22, leading: 0, bottom: 0, trailing: 0))
  97. .listRowSeparator(.hidden)
  98. }
  99. .listStyle(.plain)
  100. .scrollDisabled(true)
  101. .scrollContentBackground(.hidden)
  102. // 55 for header row, item counts x 45 for every entry row + 230 for a visible picker row
  103. .frame(height: 55 + CGFloat(items.count) * 45 + (items.contains(where: { $0.id == selectedItemID }) ? 230 : 0))
  104. .onAppear {
  105. // ensure picker is closed when view appears
  106. selectedItemID = nil
  107. validateTherapySettingItems()
  108. }
  109. .onChange(of: items, { _, _ in
  110. validateTherapySettingItems()
  111. })
  112. }
  113. @ViewBuilder private func timeValuePickerRow(
  114. item: Binding<TherapySettingItem>,
  115. timeOptions: [TimeInterval],
  116. valueOptions: [Decimal],
  117. unit: TherapySettingUnit
  118. ) -> some View {
  119. // Compute unavailable times (already taken by other entries)
  120. let takenTimes = Set(items.filter { $0.id != item.wrappedValue.id }.map(\.time))
  121. // Allow current selection even if it’s in the set of taken times.
  122. let availableTimes = timeOptions.filter { $0 == item.wrappedValue.time || !takenTimes.contains($0) }
  123. // Determine if this is first item in list (which is locked to 00:00)
  124. var isFirstItem: Bool {
  125. items.first == item.wrappedValue
  126. }
  127. VStack(spacing: 8) {
  128. HStack {
  129. Picker("Value", selection: Binding(
  130. get: { Double(item.wrappedValue.value) },
  131. set: {
  132. item.wrappedValue.value = Decimal($0)
  133. }
  134. )) {
  135. ForEach(valueOptions, id: \.self) { value in
  136. Text("\(displayText(for: unit, decimalValue: value)) \(unit.displayName)").tag(Double(value))
  137. }
  138. }
  139. .frame(maxWidth: .infinity)
  140. .clipped()
  141. Picker("Time", selection: Binding(
  142. get: { item.wrappedValue.time },
  143. set: { newTime in
  144. // Only update if new time is either not taken, or it is the current value
  145. if newTime == item.wrappedValue.time || !takenTimes.contains(newTime) {
  146. item.wrappedValue.time = newTime
  147. validateTherapySettingItems()
  148. }
  149. }
  150. )) {
  151. ForEach(availableTimes, id: \.self) { time in
  152. Text(timeFormatter.string(from: Date(timeIntervalSince1970: time)))
  153. .tag(time)
  154. .foregroundStyle(item.wrappedValue.time != 0 ? Color.primary : Color.secondary)
  155. }
  156. }
  157. // Lock time picker if first item and make it slightly opague
  158. .opacity(isFirstItem ? 0.5 : 1)
  159. .disabled(isFirstItem)
  160. .frame(maxWidth: .infinity)
  161. .clipped()
  162. }
  163. .pickerStyle(.wheel)
  164. }
  165. .padding(.vertical, 8)
  166. }
  167. private func sortTherapyItems() {
  168. Task { @MainActor in
  169. withAnimation {
  170. items = items.sorted { $0.time < $1.time }
  171. }
  172. }
  173. }
  174. private func validateTherapySettingItems() {
  175. // validates therapy items (i.e. parsed therapy settings into wrapper class)
  176. var newItems = Array(Set(items)).sorted { $0.time < $1.time }
  177. if !newItems.isEmpty {
  178. var first = newItems[0]
  179. if first.time != 0 {
  180. first.time = 0
  181. }
  182. newItems[0] = first
  183. }
  184. // force ALL items to have new UUIDs (to enforce binding update)
  185. items = newItems.map { TherapySettingItem(copying: $0, newID: true) }
  186. // validates underlying "raw" therapy setting (i.e. item of type basal, target, isf, carb ratio)
  187. validateOnDelete?()
  188. }
  189. private var timeFormatter: DateFormatter {
  190. let formatter = DateFormatter()
  191. formatter.timeZone = TimeZone(secondsFromGMT: 0)
  192. formatter.timeStyle = .short
  193. return formatter
  194. }
  195. private func displayText(for unit: TherapySettingUnit, decimalValue: Decimal) -> String {
  196. switch unit {
  197. case .mmolL,
  198. .mmolLPerUnit:
  199. return decimalValue.formattedAsMmolL
  200. case .gramPerUnit,
  201. .mgdL,
  202. .mgdLPerUnit,
  203. .unitPerHour:
  204. return decimalValue.description
  205. }
  206. }
  207. }
  208. struct TherapySettingItem: Identifiable, Equatable, Hashable {
  209. var id = UUID()
  210. var time: TimeInterval = 0 // seconds since start of day
  211. var value: Decimal = 0
  212. init(time: TimeInterval, value: Decimal) {
  213. self.time = time
  214. self.value = value
  215. }
  216. static func == (lhs: TherapySettingItem, rhs: TherapySettingItem) -> Bool {
  217. lhs.time == rhs.time && lhs.value == rhs.value
  218. }
  219. func hash(into hasher: inout Hasher) {
  220. hasher.combine(time)
  221. hasher.combine(value)
  222. }
  223. }
  224. /// Convenience extension to ease copying of existing `TherapySettingItem`s
  225. extension TherapySettingItem {
  226. init(copying item: TherapySettingItem, newID: Bool = false) {
  227. id = newID ? UUID() : item.id
  228. time = item.time
  229. value = item.value
  230. }
  231. }
  232. enum TherapySettingUnit: String, CaseIterable {
  233. case mmolLPerUnit
  234. case mgdLPerUnit
  235. case unitPerHour
  236. case gramPerUnit
  237. case mmolL
  238. case mgdL
  239. var id: String { rawValue }
  240. var displayName: String {
  241. switch self {
  242. case .mmolLPerUnit:
  243. return String(localized: "mmol/L/U")
  244. case .mgdLPerUnit:
  245. return String(localized: "mg/dL/U")
  246. case .unitPerHour:
  247. return String(localized: "U/hr")
  248. case .gramPerUnit:
  249. return String(localized: "g/U")
  250. case .mmolL:
  251. return "mmol/L"
  252. case .mgdL:
  253. return "mg/dL"
  254. }
  255. }
  256. }
  257. #Preview {
  258. @Previewable @State var previewItems = [
  259. TherapySettingItem(time: 0, value: 1.0),
  260. TherapySettingItem(time: 1800, value: 1.2)
  261. ]
  262. TherapySettingEditorView(
  263. items: $previewItems,
  264. unit: .unitPerHour,
  265. timeOptions: stride(from: 0.0, to: 1.days.timeInterval, by: 30.minutes.timeInterval).map { $0 },
  266. valueOptions: stride(from: 0.0, through: 10.0, by: 0.05).map { Decimal(round(100 * $0) / 100) }
  267. )
  268. }