diff --git a/LoopFollow/Controllers/Graphs.swift b/LoopFollow/Controllers/Graphs.swift index 1261183a7..d202bb67f 100644 --- a/LoopFollow/Controllers/Graphs.swift +++ b/LoopFollow/Controllers/Graphs.swift @@ -1772,71 +1772,50 @@ extension MainViewController { } func wrapText(_ text: String, maxLineLength: Int) -> String { - return text - var lines: [String] = [] - var currentLine = "" - - let words = text.components(separatedBy: .whitespacesAndNewlines) - for word in words { - if word.count > maxLineLength { - var wordToProcess = word - while !wordToProcess.isEmpty { - let spaceCount = currentLine.isEmpty ? 0 : 1 - let availableSpace = maxLineLength - (currentLine.count + spaceCount) - - if availableSpace <= 0 { - if !currentLine.isEmpty { - lines.append(currentLine) - currentLine = "" - } - continue - } + guard maxLineLength > 0 else { + return text + } - let takeCount = min(wordToProcess.count, availableSpace) - if takeCount <= 0 { - if !currentLine.isEmpty { - lines.append(currentLine) - currentLine = "" - } - continue - } + var result: [String] = [] + let lines = text.components(separatedBy: .newlines) - let index = wordToProcess.index(wordToProcess.startIndex, offsetBy: takeCount) - let substring = wordToProcess[.. maxLineLength { + if !currentLine.isEmpty { + result.append(currentLine) + currentLine = "" } - wordToProcess = String(wordToProcess[index...]) - - if currentLine.count >= maxLineLength { - lines.append(currentLine) - currentLine = "" + var wordToSplit = word + while !wordToSplit.isEmpty { + let splitIndex = wordToSplit.index(wordToSplit.startIndex, offsetBy: min(maxLineLength, wordToSplit.count)) + result.append(String(wordToSplit[.. maxLineLength { - lines.append(currentLine) - currentLine = word } else { + // The word fits on the line. if currentLine.isEmpty { currentLine = word - } else { + } else if currentLine.count + word.count + 1 <= maxLineLength { currentLine += " " + word + } else { + result.append(currentLine) + currentLine = word } } } - } - if !currentLine.isEmpty { - lines.append(currentLine) + if !currentLine.isEmpty { + result.append(currentLine) + } } - return lines.joined(separator: "\r\n") + return result.joined(separator: "\r\n") } func formatPillText(line1: String, time: TimeInterval, line2: String? = nil) -> String {