Skip to content

Commit

Permalink
refactor: Improve linebreak logic for html messages
Browse files Browse the repository at this point in the history
  • Loading branch information
krille-chan committed Feb 10, 2025
1 parent 41a9fbc commit 2d3bfa6
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
14 changes: 13 additions & 1 deletion lib/src/utils/markdown.dart
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ String markdown(
bool convertLinebreaks = true,
}) {
var ret = markdownToHtml(
text,
text.replaceNewlines(),
extensionSet: ExtensionSet.commonMark,
blockSyntaxes: [
BlockLatexSyntax(),
Expand Down Expand Up @@ -270,6 +270,18 @@ String markdown(
}

extension on String {
String replaceNewlines() {
// RegEx for at least 3 following \n
final regExp = RegExp(r'(\n{3,})');

return replaceAllMapped(regExp, (match) {
final newLineGroup = match.group(0)!;
return newLineGroup
.replaceAll('\n', '<br/>')
.replaceFirst('<br/><br/>', '\n\n');
});
}

String convertLinebreaksToBr(
String tagName, {
bool exclude = false,
Expand Down
25 changes: 20 additions & 5 deletions test/markdown_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -70,14 +70,29 @@ void main() {
'Snape killed <span data-mx-spoiler="">Dumbledoor <strong>bold</strong></span>',
);
});
test('multiple paragraphs', () {
test('linebreaks', () {
expect(markdown('Heya!\nBeep'), 'Heya!<br/>Beep');
expect(markdown('Heya!\n\nBeep'), '<p>Heya!</p><p>Beep</p>');
expect(markdown('Heya!\n\n\nBeep'), '<p>Heya!</p><p><br/>Beep</p>');
expect(
markdown('Heya!\n\n\n\nBeep'),
'<p>Heya!</p><p><br/><br/>Beep</p>',
);
expect(
markdown('Heya!\n\n\n\nBeep\n\n'),
'<p>Heya!</p><p><br/><br/>Beep</p>',
);
expect(
markdown('\n\nHeya!\n\n\n\nBeep'),
'<p>Heya!</p><p><br/><br/>Beep</p>',
);
expect(
markdown('\n\nHeya!\n\n\n\nBeep\n '),
'<p>Heya!</p><p><br/><br/>Beep</p>',
);
});
test('Other block elements', () {
expect(markdown('# blah\n\nblubb'), '<h1>blah</h1><p>blubb</p>');
});
test('linebreaks', () {
expect(markdown('foxies\ncute'), 'foxies<br/>cute');
expect(markdown('# blah\n\nblubb'), '<h1>blah</h1><p><br/>blubb</p>');
});
test('lists', () {
expect(
Expand Down

0 comments on commit 2d3bfa6

Please sign in to comment.