refactor(app): split markdown parsing into cohesive files
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
/// HTML entity decoding for the markdown subset.
|
||||
library;
|
||||
|
||||
const Map<String, String> _namedEntities = {
|
||||
'amp': '&',
|
||||
'lt': '<',
|
||||
'gt': '>',
|
||||
'quot': '"',
|
||||
'apos': "'",
|
||||
'nbsp': '\u00A0',
|
||||
'hellip': '\u2026',
|
||||
'mdash': '\u2014',
|
||||
'ndash': '\u2013',
|
||||
'lsquo': '\u2018',
|
||||
'rsquo': '\u2019',
|
||||
'ldquo': '\u201C',
|
||||
'rdquo': '\u201D',
|
||||
};
|
||||
|
||||
final RegExp _entity = RegExp(
|
||||
r'&(#x[0-9A-Fa-f]+|#[0-9]+|[A-Za-z][A-Za-z0-9]*);',
|
||||
);
|
||||
final RegExp _hexReference = RegExp(r'^#x[0-9A-Fa-f]+$');
|
||||
final RegExp _decimalReference = RegExp(r'^#[0-9]+$');
|
||||
|
||||
/// Decodes the HTML entities a message may carry in one left-to-right pass, so
|
||||
/// `&lt;` becomes `<` and is never decoded twice. Unknown or malformed
|
||||
/// references stay exactly as written.
|
||||
String decodeHtmlEntities(String text) {
|
||||
if (!text.contains('&')) return text;
|
||||
return text.replaceAllMapped(_entity, (match) {
|
||||
final body = match.group(1)!;
|
||||
final named = _namedEntities[body];
|
||||
if (named != null) return named;
|
||||
return _numericReference(body) ?? match.group(0)!;
|
||||
});
|
||||
}
|
||||
|
||||
String? _numericReference(String body) {
|
||||
int? codePoint;
|
||||
if (body.startsWith('#x') || body.startsWith('#X')) {
|
||||
if (_hexReference.hasMatch(body)) {
|
||||
// `tryParse` returns null for a value too large for an int; the web
|
||||
// reference parses such a value as an out-of-range number instead, and
|
||||
// both paths keep the literal. Never let an entity throw.
|
||||
codePoint = int.tryParse(body.substring(2), radix: 16);
|
||||
}
|
||||
} else if (body.startsWith('#')) {
|
||||
if (_decimalReference.hasMatch(body)) {
|
||||
codePoint = int.tryParse(body.substring(1));
|
||||
}
|
||||
}
|
||||
if (codePoint == null || codePoint < 1 || codePoint > 0x10FFFF) return null;
|
||||
return String.fromCharCode(codePoint);
|
||||
}
|
||||
Reference in New Issue
Block a user