TherapySettingEditorView.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. }
  110. @ViewBuilder private func timeValuePickerRow(
  111. item: Binding<TherapySettingItem>,
  112. timeOptions: [TimeInterval],
  113. valueOptions: [Decimal],
  114. unit: TherapySettingUnit
  115. ) -> some View {
  116. // Compute unavailable times (already taken by other entries)
  117. let takenTimes = Set(items.filter { $0.id != item.wrappedValue.id }.map(\.time))
  118. // Allow current selection even if it’s in the set of taken times.
  119. let availableTimes = timeOptions.filter { $0 == item.wrappedValue.time || !takenTimes.contains($0) }
  120. // Determine if this is first item in list (which is locked to 00:00)
  121. var isFirstItem: Bool {
  122. items.first == item.wrappedValue
  123. }
  124. VStack(spacing: 8) {
  125. HStack {
  126. Picker("Value", selection: Binding(
  127. get: { Double(item.wrappedValue.value) },
  128. set: {
  129. item.wrappedValue.value = Decimal($0)
  130. }
  131. )) {
  132. ForEach(valueOptions, id: \.self) { value in
  133. Text("\(displayText(for: unit, decimalValue: value)) \(unit.displayName)").tag(Double(value))
  134. }
  135. }
  136. .frame(maxWidth: .infinity)
  137. .clipped()
  138. Picker("Time", selection: Binding(
  139. get: { item.wrappedValue.time },
  140. set: { newTime in
  141. // Only update if new time is either not taken, or it is the current value
  142. if newTime == item.wrappedValue.time || !takenTimes.contains(newTime) {
  143. item.wrappedValue.time = newTime
  144. validateTherapySettingItems()
  145. }
  146. }
  147. )) {
  148. ForEach(availableTimes, id: \.self) { time in
  149. Text(timeFormatter.string(from: Date(timeIntervalSince1970: time)))
  150. .tag(time)
  151. .foregroundStyle(item.wrappedValue.time != 0 ? Color.primary : Color.secondary)
  152. }
  153. }
  154. // Lock time picker if first item and make it slightly opague
  155. .opacity(isFirstItem ? 0.5 : 1)
  156. .disabled(isFirstItem)
  157. .frame(maxWidth: .infinity)
  158. .clipped()
  159. }
  160. .pickerStyle(.wheel)
  161. }
  162. .padding(.vertical, 8)
  163. }
  164. private func sortTherapyItems() {
  165. Task { @MainActor in
  166. withAnimation {
  167. items = items.sorted { $0.time < $1.time }
  168. }
  169. }
  170. }
  171. private func validateTherapySettingItems() {
  172. // validates therapy items (i.e. parsed therapy settings into wrapper class)
  173. let newItems = Array(Set(items)).sorted { $0.time < $1.time }
  174. if var first = newItems.first, first.time != 0 {
  175. first.time = 0
  176. items = newItems
  177. }
  178. // validates underlying "raw" therapy setting (i.e. item of type basal, target, isf, carb ratio)
  179. validateOnDelete?()
  180. }
  181. private var timeFormatter: DateFormatter {
  182. let formatter = DateFormatter()
  183. formatter.timeZone = TimeZone(secondsFromGMT: 0)
  184. formatter.timeStyle = .short
  185. return formatter
  186. }
  187. private func displayText(for unit: TherapySettingUnit, decimalValue: Decimal) -> String {
  188. switch unit {
  189. case .mmolL,
  190. .mmolLPerUnit:
  191. return decimalValue.formattedAsMmolL
  192. case .gramPerUnit,
  193. .mgdL,
  194. .mgdLPerUnit,
  195. .unitPerHour:
  196. return decimalValue.description
  197. }
  198. }
  199. }
  200. struct TherapySettingItem: Identifiable, Equatable, Hashable {
  201. var id = UUID()
  202. var time: TimeInterval = 0 // seconds since start of day
  203. var value: Decimal = 0
  204. init(time: TimeInterval, value: Decimal) {
  205. self.time = time
  206. self.value = value
  207. }
  208. static func == (lhs: TherapySettingItem, rhs: TherapySettingItem) -> Bool {
  209. lhs.time == rhs.time && lhs.value == rhs.value
  210. }
  211. func hash(into hasher: inout Hasher) {
  212. hasher.combine(time)
  213. hasher.combine(value)
  214. }
  215. }
  216. enum TherapySettingUnit: String, CaseIterable {
  217. case mmolLPerUnit
  218. case mgdLPerUnit
  219. case unitPerHour
  220. case gramPerUnit
  221. case mmolL
  222. case mgdL
  223. var id: String { rawValue }
  224. var displayName: String {
  225. switch self {
  226. case .mmolLPerUnit:
  227. return String(localized: "mmol/L/U")
  228. case .mgdLPerUnit:
  229. return String(localized: "mg/dL/U")
  230. case .unitPerHour:
  231. return String(localized: "U/hr")
  232. case .gramPerUnit:
  233. return String(localized: "g/U")
  234. case .mmolL:
  235. return "mmol/L"
  236. case .mgdL:
  237. return "mg/dL"
  238. }
  239. }
  240. }
  241. #Preview {
  242. @Previewable @State var previewItems = [
  243. TherapySettingItem(time: 0, value: 1.0),
  244. TherapySettingItem(time: 1800, value: 1.2)
  245. ]
  246. TherapySettingEditorView(
  247. items: $previewItems,
  248. unit: .unitPerHour,
  249. timeOptions: stride(from: 0.0, to: 1.days.timeInterval, by: 30.minutes.timeInterval).map { $0 },
  250. valueOptions: stride(from: 0.0, through: 10.0, by: 0.05).map { Decimal(round(100 * $0) / 100) }
  251. )
  252. }