lemmur-app-android/lib/widgets/comment.dart

521 lines
18 KiB
Dart
Raw Normal View History

2020-08-31 18:26:57 +02:00
import 'package:cached_network_image/cached_network_image.dart';
2020-09-09 23:21:21 +02:00
import 'package:esys_flutter_share/esys_flutter_share.dart';
2020-09-21 20:19:14 +02:00
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
2020-09-16 20:09:09 +02:00
import 'package:flutter/services.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
2020-09-09 23:21:21 +02:00
import 'package:intl/intl.dart';
2020-09-03 00:01:04 +02:00
import 'package:lemmy_api_client/lemmy_api_client.dart';
import 'package:timeago/timeago.dart' as timeago;
2020-09-09 23:21:21 +02:00
import 'package:url_launcher/url_launcher.dart' as ul;
2020-08-31 20:10:05 +02:00
import '../comment_tree.dart';
2020-09-19 02:04:00 +02:00
import '../hooks/delayed_loading.dart';
import '../hooks/logged_in_action.dart';
import '../util/extensions/api.dart';
2020-09-09 23:21:21 +02:00
import '../util/goto.dart';
2020-09-19 12:28:46 +02:00
import '../util/intl.dart';
import '../util/text_color.dart';
2020-09-09 23:21:21 +02:00
import 'bottom_modal.dart';
2020-08-31 20:10:05 +02:00
import 'markdown_text.dart';
2020-09-21 13:20:25 +02:00
import 'write_comment.dart';
2020-09-30 19:05:00 +02:00
/// A single comment that renders its replies
2020-09-16 20:09:09 +02:00
class Comment extends HookWidget {
final int indent;
2020-08-31 15:29:02 +02:00
final int postCreatorId;
final CommentTree commentTree;
final bool wasVoted;
static const colors = [
Colors.pink,
Colors.green,
Colors.amber,
Colors.cyan,
Colors.indigo,
];
Comment(
this.commentTree, {
this.indent = 0,
2020-08-31 15:29:02 +02:00
@required this.postCreatorId,
}) : wasVoted =
(commentTree.comment.myVote ?? VoteType.none) != VoteType.none;
2020-09-09 23:21:21 +02:00
_showCommentInfo(BuildContext context) {
final com = commentTree.comment;
showDialog(
context: context,
child: SimpleDialog(
contentPadding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 15,
),
children: [
Table(
children: [
TableRow(children: [
Text('upvotes:'),
Text(com.upvotes.toString()),
]),
TableRow(children: [
Text('downvotes:'),
Text(com.downvotes.toString()),
]),
TableRow(children: [
Text('score:'),
Text(com.score.toString()),
]),
TableRow(children: [
Text('% of upvotes:'),
Text(
'''${(100 * (com.upvotes / (com.upvotes + com.downvotes))).toInt()}%'''),
]),
TableRow(children: [
Text('hotrank:'),
Text(com.hotRank.toString()),
]),
TableRow(children: [
Text('hotrank active:'),
Text(com.hotRankActive.toString()),
]),
TableRow(children: [
Text('published:'),
Text('''${DateFormat.yMMMd().format(com.published)}'''
''' ${DateFormat.Hms().format(com.published)}'''),
]),
TableRow(children: [
Text('updated:'),
Text(com.updated != null
? '''${DateFormat.yMMMd().format(com.updated)}'''
''' ${DateFormat.Hms().format(com.updated)}'''
: 'never'),
]),
],
),
]));
}
2020-08-31 15:29:02 +02:00
bool get isOP => commentTree.comment.creatorId == postCreatorId;
2020-10-05 14:37:43 +02:00
bool get isMine =>
commentTree.comment.creatorId == commentTree.comment.userId;
2020-08-31 15:29:02 +02:00
@override
Widget build(BuildContext context) {
2020-09-19 12:28:46 +02:00
final theme = Theme.of(context);
2020-09-16 20:09:09 +02:00
final selectable = useState(false);
final showRaw = useState(false);
2020-09-19 12:01:12 +02:00
final collapsed = useState(false);
2020-09-19 12:28:46 +02:00
final myVote = useState(commentTree.comment.myVote ?? VoteType.none);
2020-10-05 14:37:43 +02:00
final isDeleted = useState(commentTree.comment.deleted);
2020-09-19 12:28:46 +02:00
final delayedVoting = useDelayedLoading();
2020-10-05 14:37:43 +02:00
final delayedDeletion = useDelayedLoading();
2020-09-19 12:28:46 +02:00
final loggedInAction = useLoggedInAction(commentTree.comment.instanceUrl);
2020-09-21 13:20:25 +02:00
final newReplies = useState(const <CommentTree>[]);
2020-08-31 13:39:27 +02:00
2020-09-16 20:09:09 +02:00
final comment = commentTree.comment;
2020-09-03 00:01:04 +02:00
2020-10-05 14:37:43 +02:00
handleDelete(Jwt token) async {
final api = LemmyApi(token.payload.iss).v1;
delayedDeletion.start();
Navigator.of(context).pop();
try {
final res = await api.deleteComment(
editId: comment.id, deleted: !isDeleted.value, auth: token.raw);
isDeleted.value = res.deleted;
// ignore: avoid_catches_without_on_clauses
} catch (e) {
Scaffold.of(context).showSnackBar(
SnackBar(content: Text('Failed to delete/restore comment')));
return;
}
delayedDeletion.cancel();
}
2020-09-16 20:09:09 +02:00
void _openMoreMenu(BuildContext context) {
2020-09-16 21:21:47 +02:00
pop() => Navigator.of(context).pop();
2020-09-16 20:09:09 +02:00
final com = commentTree.comment;
showModalBottomSheet(
backgroundColor: Colors.transparent,
context: context,
builder: (context) => BottomModal(
child: Column(
children: [
ListTile(
leading: Icon(Icons.open_in_browser),
title: Text('Open in browser'),
onTap: () async => await ul.canLaunch(com.apId)
? ul.launch(com.apId)
: Scaffold.of(context).showSnackBar(
SnackBar(content: Text("can't open in browser"))),
),
ListTile(
leading: Icon(Icons.share),
title: Text('Share url'),
onTap: () =>
Share.text('Share comment url', com.apId, 'text/plain'),
),
ListTile(
leading: Icon(Icons.share),
title: Text('Share text'),
onTap: () =>
Share.text('Share comment text', com.content, 'text/plain'),
),
ListTile(
leading: Icon(
selectable.value ? Icons.assignment : Icons.content_cut),
title:
Text('Make text ${selectable.value ? 'un' : ''}selectable'),
onTap: () {
selectable.value = !selectable.value;
pop();
},
),
ListTile(
leading: Icon(showRaw.value ? Icons.brush : Icons.build),
title: Text('Show ${showRaw.value ? 'fancy' : 'raw'} text'),
onTap: () {
showRaw.value = !showRaw.value;
pop();
},
),
2020-10-05 14:37:43 +02:00
if (isMine)
ListTile(
leading: Icon(isDeleted.value ? Icons.restore : Icons.delete),
title: Text(isDeleted.value ? 'Restore' : 'Delete'),
onTap: loggedInAction(handleDelete),
2020-10-05 21:38:19 +02:00
),
ListTile(
leading: Icon(Icons.info_outline),
title: Text('Nerd stuff'),
onTap: () => _showCommentInfo(context),
),
2020-09-16 20:09:09 +02:00
],
),
),
);
}
2020-09-21 13:20:25 +02:00
reply() async {
2020-09-21 20:18:57 +02:00
final newComment = await showCupertinoModalPopup<CommentView>(
2020-09-21 13:20:25 +02:00
context: context,
2020-09-21 20:18:57 +02:00
builder: (_) => WriteComment.toComment(comment),
2020-09-21 13:20:25 +02:00
);
if (newComment != null) {
newReplies.value = [...newReplies.value, CommentTree(newComment)];
}
2020-09-16 20:09:09 +02:00
}
2020-09-19 12:28:46 +02:00
vote(VoteType vote, Jwt token) async {
final api = LemmyApi(token.payload.iss).v1;
delayedVoting.start();
try {
final res = await api.createCommentLike(
commentId: comment.id, score: vote, auth: token.raw);
myVote.value = res.myVote;
// ignore: avoid_catches_without_on_clauses
} catch (e) {
Scaffold.of(context)
.showSnackBar(SnackBar(content: Text('voting failed :(')));
return;
}
delayedVoting.cancel();
2020-09-16 20:09:09 +02:00
}
2020-08-31 13:39:27 +02:00
// decide which username to use
2020-09-01 14:17:56 +02:00
final username = () {
if (comment.creatorPreferredUsername != null &&
comment.creatorPreferredUsername != '') {
return comment.creatorPreferredUsername;
} else {
return '@${comment.creatorName}';
}
}();
final body = () {
2020-10-05 14:37:43 +02:00
if (isDeleted.value) {
2020-09-01 14:17:56 +02:00
return Flexible(
2020-09-19 12:28:46 +02:00
child: Text(
'comment deleted by creator',
style: TextStyle(fontStyle: FontStyle.italic),
),
);
2020-09-01 14:17:56 +02:00
} else if (comment.removed) {
return Flexible(
2020-09-19 12:01:12 +02:00
child: Text(
'comment deleted by moderator',
style: TextStyle(fontStyle: FontStyle.italic),
),
);
} else if (collapsed.value) {
return Flexible(
child: Opacity(
opacity: 0.3,
2020-09-01 14:17:56 +02:00
child: Text(
2020-09-19 12:01:12 +02:00
commentTree.comment.content,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
);
2020-09-01 14:17:56 +02:00
} else {
2020-09-19 14:05:58 +02:00
// TODO: bug, the text is selectable even when disabled after following
// these steps:
// make selectable > show raw > show fancy > make unselectable
return Flexible(
2020-09-16 20:09:09 +02:00
child: showRaw.value
? selectable.value
? SelectableText(commentTree.comment.content)
: Text(commentTree.comment.content)
: MarkdownText(
commentTree.comment.content,
instanceUrl: commentTree.comment.instanceUrl,
selectable: selectable.value,
));
2020-09-01 14:17:56 +02:00
}
}();
2020-09-19 12:01:12 +02:00
final actions = collapsed.value
? SizedBox.shrink()
2020-09-19 12:01:12 +02:00
: Row(children: [
2020-10-05 14:37:43 +02:00
if (selectable.value && !isDeleted.value && !comment.removed)
2020-09-19 12:01:12 +02:00
_CommentAction(
icon: Icons.content_copy,
tooltip: 'copy',
onPressed: () {
Clipboard.setData(
ClipboardData(text: commentTree.comment.content))
.then((_) => Scaffold.of(context).showSnackBar(SnackBar(
content: Text('comment copied to clipboard'))));
}),
Spacer(),
_CommentAction(
icon: Icons.more_horiz,
onPressed: () => _openMoreMenu(context),
2020-10-05 14:37:43 +02:00
loading: delayedDeletion.loading,
2020-09-19 12:01:12 +02:00
tooltip: 'more',
),
_SaveComment(commentTree.comment),
if (!isDeleted.value && !comment.removed)
_CommentAction(
icon: Icons.reply,
onPressed: loggedInAction((_) => reply()),
tooltip: 'reply',
),
2020-09-19 12:01:12 +02:00
_CommentAction(
icon: Icons.arrow_upward,
2020-09-19 12:28:46 +02:00
iconColor: myVote.value == VoteType.up ? theme.accentColor : null,
onPressed: loggedInAction((token) => vote(
myVote.value == VoteType.up ? VoteType.none : VoteType.up,
token,
)),
2020-09-19 12:01:12 +02:00
tooltip: 'upvote',
),
_CommentAction(
icon: Icons.arrow_downward,
2020-09-19 12:28:46 +02:00
iconColor: myVote.value == VoteType.down ? Colors.red : null,
onPressed: loggedInAction(
(token) => vote(
myVote.value == VoteType.down ? VoteType.none : VoteType.down,
token,
),
),
2020-09-19 12:01:12 +02:00
tooltip: 'downvote',
),
]);
2020-09-16 20:09:09 +02:00
2020-09-19 12:01:12 +02:00
return GestureDetector(
onLongPress: () => collapsed.value = !collapsed.value,
child: Column(
children: [
Container(
child: Column(
children: [
Row(children: [
if (comment.creatorAvatar != null)
Padding(
padding: const EdgeInsets.only(right: 5),
child: InkWell(
onTap: () => goToUser.byId(
context, comment.instanceUrl, comment.creatorId),
child: CachedNetworkImage(
imageUrl: comment.creatorAvatar,
height: 20,
width: 20,
imageBuilder: (context, imageProvider) => Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
image: DecorationImage(
fit: BoxFit.cover,
image: imageProvider,
),
2020-08-31 15:29:02 +02:00
),
),
errorWidget: (_, __, ___) => SizedBox.shrink(),
2020-08-31 15:29:02 +02:00
),
),
),
2020-09-19 12:01:12 +02:00
InkWell(
child: Text(username,
style: TextStyle(
color: Theme.of(context).accentColor,
)),
onTap: () => goToUser.byId(
context, comment.instanceUrl, comment.creatorId),
2020-08-31 15:29:02 +02:00
),
2020-09-19 12:01:12 +02:00
if (isOP) _CommentTag('OP', Theme.of(context).accentColor),
if (comment.banned) _CommentTag('BANNED', Colors.red),
if (comment.bannedFromCommunity)
_CommentTag('BANNED FROM COMMUNITY', Colors.red),
Spacer(),
if (collapsed.value && commentTree.children.length > 0) ...[
_CommentTag('+${commentTree.children.length}',
Theme.of(context).accentColor),
SizedBox(width: 7),
],
2020-09-19 12:01:12 +02:00
InkWell(
onTap: () => _showCommentInfo(context),
child: Row(
children: [
2020-09-19 21:51:22 +02:00
if (delayedVoting.loading)
SizedBox.fromSize(
size: Size.square(16),
child: CircularProgressIndicator())
else
Text(compactNumber(comment.score +
(wasVoted ? 0 : myVote.value.value))),
2020-09-19 12:01:12 +02:00
Text(' · '),
Text(timeago.format(comment.published)),
],
),
)
]),
SizedBox(height: 10),
Row(children: [body]),
SizedBox(height: 5),
actions,
],
),
padding: EdgeInsets.all(10),
margin: EdgeInsets.only(left: indent > 1 ? (indent - 1) * 5.0 : 0),
decoration: BoxDecoration(
border: Border(
left: indent > 0
? BorderSide(
color: colors[indent % colors.length], width: 5)
: BorderSide.none,
top: BorderSide(width: 0.2))),
2020-08-31 15:29:02 +02:00
),
2020-09-19 12:01:12 +02:00
if (!collapsed.value)
2020-09-21 13:20:25 +02:00
for (final c in newReplies.value.followedBy(commentTree.children))
2020-09-19 12:01:12 +02:00
Comment(
c,
indent: indent + 1,
postCreatorId: postCreatorId,
),
],
),
);
}
}
2020-08-31 15:29:02 +02:00
2020-09-19 02:04:00 +02:00
class _SaveComment extends HookWidget {
final CommentView comment;
_SaveComment(this.comment);
@override
Widget build(BuildContext context) {
final loggedInAction = useLoggedInAction(comment.instanceUrl);
final isSaved = useState(comment.saved ?? false);
final delayed = useDelayedLoading(const Duration(milliseconds: 500));
handleSave(Jwt token) async {
final api = LemmyApi(comment.instanceUrl).v1;
delayed.start();
try {
final res = await api.saveComment(
commentId: comment.id, save: !isSaved.value, auth: token.raw);
isSaved.value = res.saved;
// ignore: avoid_catches_without_on_clauses
} catch (e) {
Scaffold.of(context)
.showSnackBar(SnackBar(content: Text('saving failed :(')));
}
delayed.cancel();
}
return _CommentAction(
loading: delayed.loading,
icon: isSaved.value ? Icons.bookmark : Icons.bookmark_border,
onPressed: loggedInAction(delayed.pending ? (_) {} : handleSave),
tooltip: '${isSaved.value ? 'unsave' : 'save'} comment',
);
}
}
2020-09-03 00:10:36 +02:00
class _CommentTag extends StatelessWidget {
2020-08-31 15:29:02 +02:00
final String text;
final Color bgColor;
2020-09-03 00:10:36 +02:00
const _CommentTag(this.text, this.bgColor);
2020-08-31 15:29:02 +02:00
@override
Widget build(BuildContext context) => Padding(
padding: const EdgeInsets.only(left: 5),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(5)),
color: bgColor,
),
padding: EdgeInsets.symmetric(horizontal: 3, vertical: 2),
child: Text(text,
style: TextStyle(
color: textColorBasedOnBackground(bgColor),
2020-08-31 15:29:02 +02:00
fontSize: Theme.of(context).textTheme.bodyText1.fontSize - 5,
fontWeight: FontWeight.w800,
)),
),
);
}
2020-09-03 00:01:04 +02:00
class _CommentAction extends StatelessWidget {
final IconData icon;
final void Function() onPressed;
final String tooltip;
2020-09-19 02:04:00 +02:00
final bool loading;
2020-09-19 12:28:46 +02:00
final Color iconColor;
2020-09-03 00:01:04 +02:00
const _CommentAction({
Key key,
2020-09-19 02:04:00 +02:00
this.loading = false,
2020-09-19 12:28:46 +02:00
this.iconColor,
2020-09-03 00:01:04 +02:00
@required this.icon,
@required this.onPressed,
@required this.tooltip,
}) : super(key: key);
@override
Widget build(BuildContext context) => IconButton(
constraints: BoxConstraints.tight(Size(32, 26)),
2020-09-19 02:04:00 +02:00
icon: loading
2020-09-19 21:51:22 +02:00
? SizedBox.fromSize(
size: Size.square(22), child: CircularProgressIndicator())
2020-09-19 02:04:00 +02:00
: Icon(
icon,
2020-09-19 12:28:46 +02:00
color: iconColor ??
Theme.of(context).iconTheme.color.withAlpha(190),
2020-09-19 02:04:00 +02:00
),
2020-09-03 00:01:04 +02:00
splashRadius: 25,
onPressed: onPressed,
iconSize: 22,
tooltip: tooltip,
padding: EdgeInsets.all(0),
);
}