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 6, 2025
1 parent 41a9fbc commit d255b8b
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
11 changes: 10 additions & 1 deletion lib/src/utils/markdown.dart
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,15 @@ String markdown(
String? Function(String)? getMention,
bool convertLinebreaks = true,
}) {
// Workaround to keep linebreaks. We add a **Zero Width Space** in all
// empty lines to keep the lines as the user added them and workaround the
// markdown rules for multiple empty lines.
text = text
.trim()
.split('\n')
.map((line) => line.isEmpty ? '\u200B' : line)
.join('\n');

var ret = markdownToHtml(
text,
extensionSet: ExtensionSet.commonMark,
Expand All @@ -225,7 +234,7 @@ String markdown(
MentionSyntax(getMention),
InlineLatexSyntax(),
],
);
).replaceAll('\u200B', ''); // Remove all Zero-Width Non-Joiners afterwards!

var stripPTags = '<p>'.allMatches(ret).length <= 1;
if (stripPTags) {
Expand Down
24 changes: 18 additions & 6 deletions test/markdown_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -70,14 +70,26 @@ void main() {
'Snape killed <span data-mx-spoiler="">Dumbledoor <strong>bold</strong></span>',
);
});
test('multiple paragraphs', () {
expect(markdown('Heya!\n\nBeep'), '<p>Heya!</p><p>Beep</p>');
test('linebreaks', () {
expect(markdown('Heya!\nBeep'), 'Heya!<br/>Beep');
expect(markdown('Heya!\n\nBeep'), 'Heya!<br/><br/>Beep');
expect(markdown('Heya!\n\n\nBeep'), 'Heya!<br/><br/><br/>Beep');
expect(markdown('Heya!\n\n\n\nBeep'), 'Heya!<br/><br/><br/><br/>Beep');
expect(
markdown('Heya!\n\n\n\nBeep\n\n'),
'Heya!<br/><br/><br/><br/>Beep',
);
expect(
markdown('\n\nHeya!\n\n\n\nBeep'),
'Heya!<br/><br/><br/><br/>Beep',
);
expect(
markdown('\n\nHeya!\n\n\n\nBeep\n '),
'Heya!<br/><br/><br/><br/>Beep',
);
});
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 d255b8b

Please sign in to comment.