mirror of
https://gitlab.com/comunic/comunicmobile
synced 2025-06-19 00:05:16 +00:00
Parse links
This commit is contained in:
72
lib/ui/widgets/text_rich_content_widget.dart
Normal file
72
lib/ui/widgets/text_rich_content_widget.dart
Normal file
@ -0,0 +1,72 @@
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:comunic/utils/input_utils.dart';
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
/// Text rich content widget
|
||||
///
|
||||
/// This widget is used to parse user content (URLs, references,
|
||||
/// layout content...)
|
||||
///
|
||||
/// @author Pierre HUBERT
|
||||
|
||||
class TextRichContentWidget extends StatelessWidget {
|
||||
final TextSpan rootSpan;
|
||||
final TextAlign textAlign;
|
||||
final TextStyle style;
|
||||
|
||||
TextRichContentWidget(
|
||||
String text, {
|
||||
this.textAlign,
|
||||
this.style,
|
||||
}) : assert(text != null),
|
||||
|
||||
/// Parse content now so we won't have to do it later
|
||||
rootSpan = TextSpan(style: style, children: _parse(text, style));
|
||||
|
||||
/// Parse the text and return it as a list of span elements
|
||||
static List<TextSpan> _parse(String text, TextStyle style) {
|
||||
if (style == null) style = TextStyle();
|
||||
|
||||
List<TextSpan> list = List();
|
||||
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),
|
||||
text: s,
|
||||
recognizer: TapGestureRecognizer()
|
||||
..onTap = () {
|
||||
launch(s);
|
||||
}));
|
||||
|
||||
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) {
|
||||
return RichText(textAlign: textAlign, text: rootSpan);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user