1
0
mirror of https://gitlab.com/comunic/comunicmobile synced 2024-10-23 15:03:22 +00:00
comunicmobile/lib/ui/widgets/text_widget.dart

113 lines
2.6 KiB
Dart
Raw Normal View History

2020-04-16 07:53:19 +00:00
import 'package:comunic/utils/bbcode_parser.dart';
2020-04-16 08:53:09 +00:00
import 'package:comunic/utils/input_utils.dart';
2020-04-16 10:06:01 +00:00
import 'package:comunic/utils/navigation_utils.dart';
2020-04-16 07:53:19 +00:00
import 'package:flutter/material.dart';
2020-04-16 08:14:45 +00:00
import 'package:flutter_emoji/flutter_emoji.dart';
2020-04-16 08:53:09 +00:00
import 'package:url_launcher/url_launcher.dart';
2020-04-16 07:53:19 +00:00
/// Text widget
///
/// The content passed to this widget is automatically parsed
///
/// @author Pierre Hubert
class TextWidget extends StatelessWidget {
final String content;
2020-04-16 08:14:45 +00:00
final bool parseBBcode;
final TextStyle style;
2020-04-16 07:53:19 +00:00
2020-04-16 08:14:45 +00:00
const TextWidget({
Key key,
@required this.content,
this.parseBBcode = false,
this.style,
}) : assert(content != null),
assert(parseBBcode != null),
2020-04-16 07:53:19 +00:00
super(key: key);
@override
Widget build(BuildContext context) {
2020-04-16 08:14:45 +00:00
var content = EmojiParser().emojify(this.content);
2020-04-16 08:53:09 +00:00
// Parse BBcode
2020-04-16 08:14:45 +00:00
if (this.parseBBcode)
2020-04-16 08:53:09 +00:00
return BBCodeParsedWidget(
text: content,
2020-04-16 10:06:01 +00:00
parseCallback: (style, text) => _parseLinks(context, text, style),
2020-04-16 08:14:45 +00:00
);
2020-04-16 08:53:09 +00:00
// Just parse link
return RichText(
2020-04-16 10:06:01 +00:00
text: TextSpan(children: _parseLinks(context, content, style)),
2020-04-16 08:53:09 +00:00
);
}
/// Sub parse function
2020-04-16 10:06:01 +00:00
List<InlineSpan> _parseLinks(BuildContext context, String text, TextStyle style) {
2020-04-16 08:53:09 +00:00
var buff = StringBuffer();
final list = new List<InlineSpan>();
// Change word function
final changeWordType = () {
list.add(TextSpan(style: style, text: buff.toString()));
buff.clear();
};
for (final word in text.replaceAll("\n", " \n ").split(" ")) {
// Line break
if (word == "\n") {
buff.write("\n");
continue;
}
// Check if it is an URL
if (validateUrl(word)) {
changeWordType();
list.add(
WidgetSpan(
child: InkWell(
child: Text(
word,
style: style.copyWith(color: Colors.blueAccent),
),
onTap: () => launch(word),
),
),
);
buff.write(" ");
}
2020-04-16 10:06:01 +00:00
// Check if it is a user reference
else if(validateUserReference(word)) {
changeWordType();
list.add(
WidgetSpan(
child: InkWell(
child: Text(
word,
style: style.copyWith(color: Colors.blueAccent),
),
onTap: () => openVirtualDirectory(context, word),
),
),
);
buff.write(" ");
}
2020-04-16 08:53:09 +00:00
// Simple word
else {
buff.write(word);
buff.write(" ");
}
}
if (buff.isNotEmpty) changeWordType();
return list;
2020-04-16 07:53:19 +00:00
}
}