truncateWithEllipsisPreserveWords method

String truncateWithEllipsisPreserveWords(
  1. int? cutoff
)

Truncates the string to cutoff and appends an ellipsis '…'.

This method will not cut words in half. It will truncate at the last full word that fits within the cutoff.

Returns the original string if it's shorter than cutoff.

Implementation

String truncateWithEllipsisPreserveWords(int? cutoff) {
  // Return original string if it's empty, cutoff is invalid, or it's already short enough.
  if (isEmpty || cutoff == null || cutoff <= 0 || length <= cutoff) {
    return this;
  }

  // Ensure we don't exceed the string's length when finding the last space.
  final int effectiveCutoff = cutoff >= length ? length : cutoff;

  // Find the last space within the allowed length
  final int lastSpaceIndex = substring(
    0,
    effectiveCutoff + 1 > length ? length : effectiveCutoff + 1,
  ).lastIndexOf(' ');

  // If no space is found (e.g., a single long word), we'll just return the ellipsis.
  if (lastSpaceIndex == -1) {
    return '…';
  }

  // Truncate at the last space found and remove any trailing space before adding the ellipsis.
  return '${substring(0, lastSpaceIndex).trimRight()}$ellipsis';
}