TagCloudView.swift 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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. private func formatGlucoseTags(_ tag: String, isMmolL: Bool) -> String {
  95. let patterns = [
  96. "ISF:\\s*-?\\d+\\.?\\d*→-?\\d+\\.?\\d*",
  97. "Dev:\\s*-?\\d+\\.?\\d*",
  98. "BGI:\\s*-?\\d+\\.?\\d*",
  99. "Target:\\s*-?\\d+\\.?\\d*",
  100. "(?:minPredBG|minGuardBG|IOBpredBG|COBpredBG|UAMpredBG)\\s*-?\\d+\\.?\\d*"
  101. ]
  102. let pattern = patterns.joined(separator: "|")
  103. let regex = try! NSRegularExpression(pattern: pattern)
  104. // Convert only if isMmolL == true; otherwise return original mg/dL string
  105. func convertToMmolL(_ value: String) -> String {
  106. if let glucoseValue = Double(value.replacingOccurrences(of: "[^\\d.-]", with: "", options: .regularExpression)) {
  107. let mmolValue = Decimal(glucoseValue).asMmolL // your mg/dL → mmol/L routine
  108. return isMmolL ? mmolValue.description : value
  109. }
  110. return value
  111. }
  112. let matches = regex.matches(in: tag, range: NSRange(tag.startIndex..., in: tag))
  113. var updatedTag = tag
  114. // Process each match in reverse order
  115. for match in matches.reversed() {
  116. guard let range = Range(match.range, in: tag) else { continue }
  117. let glucoseValueString = String(tag[range])
  118. if glucoseValueString.contains("→") {
  119. // -- Handle ISF: X→Y
  120. let values = glucoseValueString.components(separatedBy: "→")
  121. // For example "ISF: 162"
  122. let firstNumber = values[0].components(separatedBy: ":")[1].trimmingCharacters(in: .whitespaces)
  123. let secondNumber = values[1].trimmingCharacters(in: .whitespaces)
  124. let firstValue = convertToMmolL(firstNumber)
  125. let secondValue = convertToMmolL(secondNumber)
  126. let formattedString = "ISF: \(firstValue)→\(secondValue)"
  127. updatedTag.replaceSubrange(range, with: formattedString)
  128. } else if glucoseValueString.starts(with: "Dev:") {
  129. // -- Handle Dev
  130. let value = glucoseValueString.components(separatedBy: ":")[1].trimmingCharacters(in: .whitespaces)
  131. let formattedValue = convertToMmolL(value)
  132. let formattedString = "Dev: \(formattedValue)"
  133. updatedTag.replaceSubrange(range, with: formattedString)
  134. } else if glucoseValueString.starts(with: "BGI:") {
  135. // -- Handle BGI
  136. let value = glucoseValueString.components(separatedBy: ":")[1].trimmingCharacters(in: .whitespaces)
  137. let formattedValue = convertToMmolL(value)
  138. let formattedString = "BGI: \(formattedValue)"
  139. updatedTag.replaceSubrange(range, with: formattedString)
  140. } else if glucoseValueString.starts(with: "Target:") {
  141. // -- Handle Target
  142. let value = glucoseValueString.components(separatedBy: ":")[1].trimmingCharacters(in: .whitespaces)
  143. let formattedValue = convertToMmolL(value)
  144. let formattedString = "Target: \(formattedValue)"
  145. updatedTag.replaceSubrange(range, with: formattedString)
  146. } else {
  147. // -- Handle everything else (e.g., "minPredBG 39" etc.)
  148. let parts = glucoseValueString.components(separatedBy: .whitespaces)
  149. if parts.count >= 2 {
  150. let metric = parts[0]
  151. let value = parts[1]
  152. let formattedValue = convertToMmolL(value)
  153. let formattedString = "\(metric): \(formattedValue)"
  154. updatedTag.replaceSubrange(range, with: formattedString)
  155. }
  156. }
  157. }
  158. return updatedTag
  159. }
  160. private func viewHeightReader(_ binding: Binding<CGFloat>) -> some View {
  161. GeometryReader { geometry -> Color in
  162. let rect = geometry.frame(in: .local)
  163. DispatchQueue.main.async {
  164. binding.wrappedValue = rect.size.height
  165. }
  166. return .clear
  167. }
  168. }
  169. }
  170. struct TestTagCloudView: View {
  171. var body: some View {
  172. VStack {
  173. Text("Header").font(.largeTitle)
  174. TagCloudView(
  175. tags: ["Ninetendo", "XBox", "PlayStation", "PlayStation 2", "PlayStation 3", "PlayStation 4"],
  176. shouldParseToMmolL: false
  177. )
  178. Text("Some other text")
  179. Divider()
  180. Text("Some other cloud")
  181. TagCloudView(
  182. tags: ["Apple", "Google", "Amazon", "Microsoft", "Oracle", "Facebook"],
  183. shouldParseToMmolL: false
  184. )
  185. }
  186. }
  187. }