truncate function

String truncate(
  1. String s,
  2. int width, [
  3. String tail = ''
])

Truncates a string to fit within the given width.

If the string is longer than width, it is truncated and tail is appended (if there's room).

Implementation

String truncate(String s, int width, [String tail = '']) {
  if (width <= 0) return '';

  final fullWidth = stringWidth(s);
  if (fullWidth <= width) return s;

  final tailWidth = stringWidth(tail);
  final targetWidth = (width - tailWidth).clamp(0, width);

  var currentWidth = 0;
  final result = StringBuffer();

  for (final g in uni.graphemes(s)) {
    final w = runeWidth(uni.firstCodePoint(g));
    if (currentWidth + w > targetWidth) break;
    currentWidth += w;
    result.write(g);
  }

  if (tail.isNotEmpty && currentWidth < width) {
    result.write(tail);
  }

  return result.toString();
}