wrapTraceText function

List<String> wrapTraceText(
  1. String text,
  2. int maxWidth
)

Implementation

List<String> wrapTraceText(String text, int maxWidth) {
  if (maxWidth <= 0) return [];
  if (text.characters.length <= maxWidth) return [text];

  final words = text.split(' ');
  final lines = <String>[];
  var currentLine = '';
  var currentLen = 0;

  for (final word in words) {
    if (word.isEmpty) continue;
    final wordLen = word.characters.length;

    if (currentLine.isEmpty) {
      currentLine = word;
      currentLen = wordLen;
    } else if (currentLen + 1 + wordLen <= maxWidth) {
      currentLine = '$currentLine $word';
      currentLen += 1 + wordLen;
    } else {
      lines.add(currentLine);
      currentLine = '  $word'; // Indent wrapped lines
      currentLen = 2 + wordLen;
    }
  }
  if (currentLine.isNotEmpty) {
    lines.add(currentLine);
  }
  return lines;
}