toText method

String toText()

Markdown-friendly text with explicit pagination and escaped cell values.

Implementation

String toText() {
  final data = toJson();
  final groups = data['kind'] == 'groups';
  final rows = (data[groups ? 'groups' : 'rows']! as List)
      .cast<Map<String, Object?>>();
  final select = groups
      ? ['key', 'count']
      : [
          'bundle',
          'id',
          ...((data['query']! as Map)['select']! as List).cast<String>(),
        ];
  String cell(Object? value) {
    final text = value == null
        ? ''
        : value is String
        ? value
        : jsonEncode(value);
    return text.runes.map((r) {
      if (r < 32 || (r >= 127 && r <= 159)) {
        return '\\u{${r.toRadixString(16)}}';
      }
      return switch (r) {
        38 => '&amp;',
        60 => '&lt;',
        62 => '&gt;',
        124 => '&#124;',
        91 => '&#91;',
        93 => '&#93;',
        96 => '&#96;',
        42 => '&#42;',
        95 => '&#95;',
        92 => '&#92;',
        _ => String.fromCharCode(r),
      };
    }).join();
  }

  return [
    '${data['returned']} of ${groups ? data['group_total'] : data['total']} ${groups ? 'groups' : 'concepts'}; offset ${data['offset']}; more: ${data['has_more']}.',
    if (groups) 'Matching concepts: ${data['total']}.',
    '| ${select.join(' | ')} |',
    '| ${select.map((_) => '---').join(' | ')} |',
    for (final row in rows)
      '| ${select.map((key) => cell(groups || key == 'bundle' || key == 'id' ? row[key] : (row['values']! as Map)[key])).join(' | ')} |',
  ].join('\n');
}