TagCloudView.swift 8.8 KB

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