styleToSgr function

String styleToSgr(
  1. UvStyle style
)

Returns the SGR sequence for style.

Implementation

String styleToSgr(UvStyle style) {
  if (style.isZero) return UvAnsi.resetStyle;

  final key = style.packedKey;
  final cached = _styleSgrCache[key];
  if (cached != null) return cached;

  final simple = _simpleRgbStyleToSgr(style);
  if (simple != null) {
    _cacheSgr(key, simple);
    return simple;
  }

  final sb = StringBuffer();
  var sep = false;
  void add(String s) {
    if (sep) sb.write(';');
    sb.write(s);
    sep = true;
  }

  final attrs = style.attrs;
  if ((attrs & Attr.bold) != 0) add('1');
  if ((attrs & Attr.faint) != 0) add('2');
  if ((attrs & Attr.italic) != 0) add('3');
  if ((attrs & Attr.blink) != 0) add('5');
  if ((attrs & Attr.rapidBlink) != 0) add('6');
  if ((attrs & Attr.reverse) != 0) add('7');
  if ((attrs & Attr.conceal) != 0) add('8');
  if ((attrs & Attr.strikethrough) != 0) add('9');

  switch (style.underline) {
    case UnderlineStyle.none:
      break;
    case UnderlineStyle.single:
      add('4');
    case UnderlineStyle.double:
      add('4:2');
    case UnderlineStyle.curly:
      add('4:3');
    case UnderlineStyle.dotted:
      add('4:4');
    case UnderlineStyle.dashed:
      add('4:5');
  }

  final fg = _colorCode(style.fg, _ColorTarget.fg);
  if (fg != null) add(fg);
  final bg = _colorCode(style.bg, _ColorTarget.bg);
  if (bg != null) add(bg);
  final ul = _colorCode(style.underlineColor, _ColorTarget.underline);
  if (ul != null) add(ul);

  if (!sep) {
    _cacheSgr(key, UvAnsi.resetStyle);
    return UvAnsi.resetStyle;
  }
  final result = '\x1b[${sb.toString()}m';
  _cacheSgr(key, result);
  return result;
}