wrapWith function

String? wrapWith(
  1. String? value,
  2. Iterable<AnsiCode> codes, {
  3. bool forScript = false,
})

Returns a String formatted with codes.

If forScript is true, the return value is an unescaped literal. The value of ansiOutputEnabled is also ignored.

Returns value unchanged if

  • value is null or empty.
  • both ansiOutputEnabled and forScript are false.
  • codes is empty.

Throws an ArgumentError if

Implementation

String? wrapWith(String? value, Iterable<AnsiCode> codes,
    {bool forScript = false}) {
  // Eliminate duplicates
  final myCodes = codes.toSet();

  if (_isNoop(myCodes.isEmpty, value, forScript)) {
    return value;
  }

  var foreground = 0, background = 0;
  for (var code in myCodes) {
    switch (code.type) {
      case AnsiCodeType.foreground:
        foreground++;
        if (foreground > 1) {
          throw ArgumentError.value(codes, 'codes',
              'Cannot contain more than one foreground color code.');
        }
      case AnsiCodeType.background:
        background++;
        if (background > 1) {
          throw ArgumentError.value(codes, 'codes',
              'Cannot contain more than one foreground color code.');
        }
      case AnsiCodeType.reset:
        throw ArgumentError.value(
            codes, 'codes', 'Cannot contain reset codes.');
      case AnsiCodeType.style:
        // Ignore.
        break;
    }
  }

  final sortedCodes = myCodes.map((ac) => ac.code).toList()..sort();
  final escapeValue = forScript ? _ansiEscapeForScript : _ansiEscapeLiteral;

  return "$escapeValue[${sortedCodes.join(';')}m$value"
      '${resetAll._escapeValue(forScript: forScript)}';
}