loris/lib/partials/post_text_renderer.dart

60 lines
1.4 KiB
Dart
Raw Normal View History

2022-08-06 16:46:31 +00:00
import 'package:flutter/material.dart';
2022-08-06 20:13:12 +00:00
import 'package:html/dom.dart' as dom;
import 'package:html/parser.dart' as parser;
2022-08-06 16:46:31 +00:00
class PostTextRenderer extends StatelessWidget {
const PostTextRenderer({
2022-08-06 16:56:33 +00:00
required this.htmlInput,
2022-08-06 16:46:31 +00:00
Key? key,
}) : super(key: key);
2022-08-06 16:56:33 +00:00
final String htmlInput;
2022-08-06 16:46:31 +00:00
@override
Widget build(BuildContext context) {
2022-08-06 20:13:12 +00:00
dom.Document document = parser.parse(htmlInput);
2022-08-09 18:58:11 +00:00
final List<InlineSpan> children =
createSpansFromDoc(document.body!.children);
2022-08-12 19:30:58 +00:00
return SelectableText.rich(
TextSpan(
style: Theme.of(context).textTheme.bodyMedium,
text: "",
children: children,
),
);
2022-08-06 16:46:31 +00:00
}
}
2022-08-06 20:13:12 +00:00
2022-08-09 18:58:11 +00:00
List<InlineSpan> createSpansFromDoc(List<dom.Element> elements) {
2022-08-06 20:13:12 +00:00
List<InlineSpan> result = [];
2022-08-09 18:58:11 +00:00
for (int i = 0; i < elements.length; i += 1) {
final e = elements[i];
2022-08-06 20:13:12 +00:00
result.add(
getSpanForElement(
e,
2022-08-09 18:58:11 +00:00
elements.length,
2022-08-06 20:13:12 +00:00
i,
),
);
}
return result;
}
InlineSpan getSpanForElement(dom.Element e, int bodyLength, int pos) {
if (e.toString() == "<html p>") {
return handleParagraph(e, bodyLength, pos);
}
return TextSpan(text: e.text);
}
InlineSpan handleParagraph(dom.Element e, int bodyLength, int pos) {
String text = e.text;
return WidgetSpan(
child: Padding(
padding: const EdgeInsets.fromLTRB(0, 4, 0, 4),
2022-08-09 18:58:11 +00:00
child: SelectableText(
text,
),
2022-08-06 20:13:12 +00:00
),
);
}