TagCloudView.swift 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. import Combine
  2. import Foundation
  3. import SwiftUI
  4. import Swinject
  5. struct TagCloudView: View {
  6. var tags: [String]
  7. var shouldParseToMmolL: Bool
  8. @State private var totalHeight = CGFloat.zero // << variant for ScrollView/List
  9. // = CGFloat.infinity // << variant for VStack
  10. var body: some View {
  11. VStack {
  12. GeometryReader { geometry in
  13. self.generateContent(in: geometry)
  14. }
  15. }
  16. .frame(height: totalHeight) // << variant for ScrollView/List
  17. // .frame(maxHeight: totalHeight) // << variant for VStack
  18. }
  19. private func generateContent(in geometry: GeometryProxy) -> some View {
  20. var width = CGFloat.zero
  21. var height = CGFloat.zero
  22. return ZStack(alignment: .topLeading) {
  23. ForEach(self.tags, id: \.self) { tag in
  24. self.drawTag(for: tag, isMmolL: shouldParseToMmolL)
  25. .padding([.horizontal, .vertical], 2)
  26. .alignmentGuide(.leading, computeValue: { dimensions in
  27. if abs(width - dimensions.width) > geometry.size.width {
  28. width = 0
  29. height -= dimensions.height
  30. }
  31. let result = width
  32. if tag == self.tags.last! {
  33. width = 0 // last item
  34. } else {
  35. width -= dimensions.width
  36. }
  37. return result
  38. })
  39. .alignmentGuide(.top, computeValue: { _ in
  40. let result = height
  41. if tag == self.tags.last! {
  42. height = 0 // last item
  43. }
  44. return result
  45. })
  46. }
  47. }.background(viewHeightReader($totalHeight))
  48. }
  49. private func drawTag(for textTag: String, isMmolL: Bool) -> some View {
  50. var colorOfTag: Color {
  51. switch textTag {
  52. case textTag where textTag.contains("SMB Delivery Ratio:"):
  53. return .uam
  54. case textTag where textTag.contains("Bolus"):
  55. return .green
  56. case textTag where textTag.contains("TDD:"),
  57. textTag where textTag.contains("tdd_factor"),
  58. textTag where textTag.contains("Sigmoid function"),
  59. textTag where textTag.contains("Logarithmic formula"),
  60. textTag where textTag.contains("AF:"),
  61. textTag where textTag.contains("Autosens/Dynamic Limit:"),
  62. textTag where textTag.contains("Dynamic ISF/CR"),
  63. textTag where textTag.contains("Basal ratio"),
  64. textTag where textTag.contains("SMB Ratio"):
  65. return .zt
  66. case textTag where textTag.contains("Middleware:"):
  67. return .red
  68. case textTag where textTag.contains("SMB Ratio"):
  69. return .orange
  70. case textTag where textTag.contains("Smoothing: On"):
  71. return .white
  72. default:
  73. return .insulin
  74. }
  75. }
  76. let formattedTextTag = formatGlucoseTags(textTag, isMmolL: isMmolL)
  77. return ZStack {
  78. Text(formattedTextTag)
  79. .padding(.horizontal, 10)
  80. .padding(.vertical, 5)
  81. .font(.subheadline)
  82. .fontWeight(.semibold)
  83. .background(colorOfTag.opacity(0.8))
  84. .foregroundColor(textTag.contains("Smoothing: On") ? Color.black : Color.white)
  85. .clipShape(Capsule())
  86. }
  87. }
  88. /**
  89. Converts glucose-related values in the given `tag` string to mmol/L, including ranges (e.g., `ISF: 54→54`), comparisons (e.g., `maxDelta 37 > 20% of BG 95`), and both positive and negative values (e.g., `Dev: -36`).
  90. - Parameters:
  91. - tag: The string containing glucose-related values to be converted.
  92. - isMmolL: A Boolean flag indicating whether to convert values to mmol/L.
  93. - Returns:
  94. A string with glucose values converted to mmol/L.
  95. - Glucose tags handled: `ISF:`, `Target:`, `minPredBG`, `minGuardBG`, `IOBpredBG`, `COBpredBG`, `UAMpredBG`, `Dev:`, `maxDelta`, `BGI`.
  96. */
  97. // TODO: Consolidate all mmol parsing methods (in TagCloudView, NightscoutManager and HomeRootView) to one central func
  98. private func formatGlucoseTags(_ tag: String, isMmolL: Bool) -> String {
  99. let patterns = [
  100. "ISF:\\s*-?\\d+\\.?\\d*→-?\\d+\\.?\\d*",
  101. "Dev:\\s*-?\\d+\\.?\\d*",
  102. "BGI:\\s*-?\\d+\\.?\\d*",
  103. "Target:\\s*-?\\d+\\.?\\d*",
  104. "(?:minPredBG|minGuardBG|IOBpredBG|COBpredBG|UAMpredBG)\\s*-?\\d+\\.?\\d*"
  105. ]
  106. let pattern = patterns.joined(separator: "|")
  107. let regex = try! NSRegularExpression(pattern: pattern)
  108. // Convert only if isMmolL == true; otherwise return original mg/dL string
  109. func convertToMmolL(_ value: String) -> String {
  110. if let glucoseValue = Double(value.replacingOccurrences(of: "[^\\d.-]", with: "", options: .regularExpression)) {
  111. let mmolValue = Decimal(glucoseValue).asMmolL // your mg/dL → mmol/L routine
  112. return isMmolL ? mmolValue.description : value
  113. }
  114. return value
  115. }
  116. let matches = regex.matches(in: tag, range: NSRange(tag.startIndex..., in: tag))
  117. var updatedTag = tag
  118. // Process each match in reverse order
  119. for match in matches.reversed() {
  120. guard let range = Range(match.range, in: tag) else { continue }
  121. let glucoseValueString = String(tag[range])
  122. if glucoseValueString.contains("→") {
  123. // -- Handle ISF: X→Y
  124. let values = glucoseValueString.components(separatedBy: "→")
  125. // For example "ISF: 162"
  126. let firstNumber = values[0].components(separatedBy: ":")[1].trimmingCharacters(in: .whitespaces)
  127. let secondNumber = values[1].trimmingCharacters(in: .whitespaces)
  128. let firstValue = convertToMmolL(firstNumber)
  129. let secondValue = convertToMmolL(secondNumber)
  130. let formattedString = "ISF: \(firstValue)→\(secondValue)"
  131. updatedTag.replaceSubrange(range, with: formattedString)
  132. } else if glucoseValueString.starts(with: "Dev:") {
  133. // -- Handle Dev
  134. let value = glucoseValueString.components(separatedBy: ":")[1].trimmingCharacters(in: .whitespaces)
  135. let formattedValue = convertToMmolL(value)
  136. let formattedString = "Dev: \(formattedValue)"
  137. updatedTag.replaceSubrange(range, with: formattedString)
  138. } else if glucoseValueString.starts(with: "BGI:") {
  139. // -- Handle BGI
  140. let value = glucoseValueString.components(separatedBy: ":")[1].trimmingCharacters(in: .whitespaces)
  141. let formattedValue = convertToMmolL(value)
  142. let formattedString = "BGI: \(formattedValue)"
  143. updatedTag.replaceSubrange(range, with: formattedString)
  144. } else if glucoseValueString.starts(with: "Target:") {
  145. // -- Handle Target
  146. let value = glucoseValueString.components(separatedBy: ":")[1].trimmingCharacters(in: .whitespaces)
  147. let formattedValue = convertToMmolL(value)
  148. let formattedString = "Target: \(formattedValue)"
  149. updatedTag.replaceSubrange(range, with: formattedString)
  150. } else {
  151. // -- Handle everything else (e.g., "minPredBG 39" etc.)
  152. let parts = glucoseValueString.components(separatedBy: .whitespaces)
  153. if parts.count >= 2 {
  154. let metric = parts[0]
  155. let value = parts[1]
  156. let formattedValue = convertToMmolL(value)
  157. let formattedString = "\(metric): \(formattedValue)"
  158. updatedTag.replaceSubrange(range, with: formattedString)
  159. }
  160. }
  161. }
  162. return updatedTag
  163. }
  164. private func viewHeightReader(_ binding: Binding<CGFloat>) -> some View {
  165. GeometryReader { geometry -> Color in
  166. let rect = geometry.frame(in: .local)
  167. DispatchQueue.main.async {
  168. binding.wrappedValue = rect.size.height
  169. }
  170. return .clear
  171. }
  172. }
  173. }
  174. struct TestTagCloudView: View {
  175. var body: some View {
  176. VStack {
  177. Text("Header").font(.largeTitle)
  178. TagCloudView(
  179. tags: ["Ninetendo", "XBox", "PlayStation", "PlayStation 2", "PlayStation 3", "PlayStation 4"],
  180. shouldParseToMmolL: false
  181. )
  182. Text("Some other text")
  183. Divider()
  184. Text("Some other cloud")
  185. TagCloudView(
  186. tags: ["Apple", "Google", "Amazon", "Microsoft", "Oracle", "Facebook"],
  187. shouldParseToMmolL: false
  188. )
  189. }
  190. }
  191. }