wrapInBox method

String wrapInBox(
  1. String text, {
  2. String? title,
  3. int? width,
})

Wraps text in an ASCII box with an optional title.

Implementation

String wrapInBox(String text, {String? title, int? width}) {
  final lines = text.split('\n');
  final contentWidth =
      width ?? lines.fold<int>(0, (m, l) => math.max(m, l.length));
  final boxWidth = math.max(
    contentWidth,
    title != null ? title.length + 2 : 0,
  );

  final buf = StringBuffer();
  // Top border.
  if (title != null) {
    buf.writeln('┌─ $title ${'─' * (boxWidth - title.length - 2)}┐');
  } else {
    buf.writeln('┌${'─' * (boxWidth + 2)}┐');
  }
  // Content lines.
  for (final line in lines) {
    buf.writeln('│ ${line.padRight(boxWidth)} │');
  }
  // Bottom border.
  buf.write('└${'─' * (boxWidth + 2)}┘');
  return buf.toString();
}