flarkSourcePreview function

String flarkSourcePreview(
  1. String markdown
)

The opening of markdown that a reader's source fallback shows, about 1,024 code units and an ellipsis when there is more. The fallback is also where text with an unpaired surrogate ends up, which a host's text layout may refuse (Flutter's) or drop (Fleury's), so the cut never splits a surrogate pair and an unpaired one shows as U+FFFD. Copying still takes the source exactly as written.

Implementation

String flarkSourcePreview(String markdown) {
  const limit = 1024;
  final preview = StringBuffer();
  var i = 0;
  while (i < markdown.length && i < limit) {
    final unit = markdown.codeUnitAt(i);
    final next = i + 1 < markdown.length ? markdown.codeUnitAt(i + 1) : 0;
    if (unit >= 0xD800 && unit <= 0xDBFF && next >= 0xDC00 && next <= 0xDFFF) {
      preview.writeCharCode(0x10000 + ((unit - 0xD800) << 10) + next - 0xDC00);
      i += 2;
    } else {
      preview.writeCharCode(unit >= 0xD800 && unit <= 0xDFFF ? 0xFFFD : unit);
      i++;
    }
  }
  if (i < markdown.length) preview.write('…');
  return preview.toString();
}