feat: allow removing markdown formating

This commit is contained in:
h.carnot 2022-03-18 11:40:10 +01:00
parent 08e0284cef
commit 77347a44ff
2 changed files with 43 additions and 7 deletions

View File

@ -19,11 +19,13 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:html/parser.dart';
import 'package:http/http.dart' as http;
import '../matrix.dart';
import 'utils/event_localizations.dart';
import 'utils/html_to_text.dart';
import 'utils/markdown.dart';
abstract class RelationshipTypes {
static const String reply = 'm.in_reply_to';
@ -581,13 +583,12 @@ class Event extends MatrixEvent {
/// room list you may find [withSenderNamePrefix] useful. Set [hideReply] to
/// crop all lines starting with '>'. With [plaintextBody] it'll use the
/// plaintextBody instead of the normal body.
String getLocalizedBody(
MatrixLocalizations i18n, {
bool withSenderNamePrefix = false,
bool hideReply = false,
bool hideEdit = false,
bool plaintextBody = false,
}) {
String getLocalizedBody(MatrixLocalizations i18n,
{bool withSenderNamePrefix = false,
bool hideReply = false,
bool hideEdit = false,
bool plaintextBody = false,
bool removeMarkdown = false}) {
if (redacted) {
return i18n.removedBy(redactedBecause?.sender.calcDisplayname() ?? '');
}
@ -621,6 +622,16 @@ class Event extends MatrixEvent {
body = body.replaceFirst(
RegExp(r'^>( \*)? <[^>]+>[^\n\r]+\r?\n(> [^\n]*\r?\n)*\r?\n'), '');
}
// return the html tags free body
if (removeMarkdown == true) {
final html = markdown(body);
final document = parse(
html,
);
body = document.documentElement?.text ?? body;
}
final callback = EventLocalizations.localizationsMap[type];
var localizedBody = i18n.unknownEvent(type);
if (callback != null) {

View File

@ -1034,6 +1034,31 @@ void main() {
event.getLocalizedBody(MatrixDefaultLocalizations(),
hideReply: true, plaintextBody: true),
'hmm, *fox*');
event = Event.fromJson({
'content': {
'body':
'# Title\nsome text and [link](https://example.com)\nokay and this is **important**',
'format': 'org.matrix.custom.html',
'formatted_body':
'<h1>Title</h1>\n<p>some text and <a href=\"https://example.com\">link</a><br>okay and this is <strong>important</strong></p>\n',
'msgtype': 'm.text'
},
'event_id': '\$143273582443PhrSn:example.org',
'origin_server_ts': 1432735824653,
'room_id': '!jEsUZKDJdhlrceRyVU:example.org',
'sender': '@example:example.org',
'type': 'm.room.message',
'unsigned': {'age': 1234}
}, room);
expect(
event.getLocalizedBody(MatrixDefaultLocalizations(),
removeMarkdown: true),
'Title\nsome text and link\nokay and this is important');
expect(
event.getLocalizedBody(MatrixDefaultLocalizations(),
removeMarkdown: true, plaintextBody: true),
'Title\nsome text and 🔗link\nokay and this is important');
});
test('aggregations', () {