1
0
mirror of https://gitlab.com/comunic/comunicmobile synced 2024-11-22 12:59:21 +00:00
comunicmobile/lib/ui/widgets/text_rich_content_widget.dart

69 lines
1.7 KiB
Dart
Raw Permalink Normal View History

2019-05-01 08:21:26 +00:00
import 'package:comunic/utils/input_utils.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
2022-06-11 13:04:11 +00:00
import 'package:url_launcher/url_launcher_string.dart';
2019-05-01 08:21:26 +00:00
/// Text rich content widget
///
/// This widget is used to parse user content (URLs, references,
/// layout content...)
///
/// @author Pierre HUBERT
class TextRichContentWidget extends StatelessWidget {
final TextAlign? textAlign;
final TextStyle? style;
2020-05-08 07:14:25 +00:00
final String text;
2019-05-01 08:21:26 +00:00
TextRichContentWidget(
2020-05-08 07:14:25 +00:00
this.text, {
2019-05-01 08:21:26 +00:00
this.textAlign,
this.style,
2022-03-11 16:13:54 +00:00
});
2019-05-01 08:21:26 +00:00
/// Parse the text and return it as a list of span elements
static List<TextSpan> _parse(String text, TextStyle? style) {
2019-05-01 08:21:26 +00:00
if (style == null) style = TextStyle();
2021-03-13 14:14:54 +00:00
List<TextSpan> list = [];
2019-05-01 08:21:26 +00:00
String currString = "";
text.split("\n").forEach((f) {
text.split(" ").forEach((s) {
if (validateUrl(s)) {
if (currString.length > 0)
//"Flush" previous text
list.add(TextSpan(style: style, text: currString + " "));
// Add link
list.add(TextSpan(
style: style!.copyWith(color: Colors.indigo),
2019-05-01 08:21:26 +00:00
text: s,
recognizer: TapGestureRecognizer()
..onTap = () {
2022-06-11 13:04:11 +00:00
launchUrlString(s);
2019-05-01 08:21:26 +00:00
}));
currString = "";
} else
currString += s;
currString += " ";
});
currString += "\n";
});
list.add(TextSpan(
style: style, text: currString.substring(0, currString.length - 2)));
return list;
}
@override
Widget build(BuildContext context) {
2020-05-08 07:14:25 +00:00
return RichText(
textAlign: textAlign!, text: TextSpan(children: _parse(text, style)));
2019-05-01 08:21:26 +00:00
}
}