Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve link handling in posts/comments #869

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions lib/l10n/app_en.arb
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,8 @@
"@editComment": {},
"comment": "Comment",
"@comment": {},
"linkActions": "Link Actions",
"copy": "Copy",
"comments": "Comments",
"@comments": {},
"visitInstance": "Visit Instance",
Expand Down
294 changes: 208 additions & 86 deletions lib/shared/common_markdown_body.dart
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:link_preview_generator/link_preview_generator.dart';

import 'package:markdown/markdown.dart' as md;
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:lemmy_api_client/v3.dart';
import 'package:share_plus/share_plus.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

import 'package:thunder/account/models/account.dart';
import 'package:thunder/core/auth/helpers/fetch_account.dart';
import 'package:thunder/core/enums/font_scale.dart';
Expand All @@ -11,6 +17,7 @@ import 'package:thunder/feed/utils/utils.dart';
import 'package:thunder/feed/view/feed_page.dart';
import 'package:thunder/post/utils/post.dart';
import 'package:thunder/shared/image_preview.dart';
import 'package:thunder/utils/bottom_sheet_list_picker.dart';
import 'package:thunder/utils/links.dart';
import 'package:thunder/thunder/bloc/thunder_bloc.dart';
import 'package:thunder/utils/instance.dart';
Expand All @@ -35,11 +42,12 @@ class CommonMarkdownBody extends StatelessWidget {
final theme = Theme.of(context);
final ThunderState state = context.watch<ThunderBloc>().state;

bool openInExternalBrowser = state.openInExternalBrowser;

return MarkdownBody(
// TODO We need spoiler support here
data: body,
builders: {
'a': LinkElementBuilder(context: context, state: state, isComment: isComment),
},
imageBuilder: (uri, title, alt) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
Expand All @@ -57,91 +65,10 @@ class CommonMarkdownBody extends StatelessWidget {
);
},
selectable: isSelectableText,
onTapLink: (text, url, title) async {
LemmyApiV3 lemmy = LemmyClient.instance.lemmyApiV3;
Account? account = await fetchActiveProfileAccount();

Uri? parsedUri = Uri.tryParse(text);

String parsedUrl = text;

if (parsedUri != null && parsedUri.host.isNotEmpty) {
parsedUrl = parsedUri.toString();
} else {
parsedUrl = url ?? '';
}

// The markdown link processor treats URLs with @ as emails and prepends "mailto:".
// If the URL contains that, but the text doesn't, we can remove it.
if (parsedUrl.startsWith('mailto:') && !text.startsWith('mailto:')) {
parsedUrl = parsedUrl.replaceFirst('mailto:', '');
}

// Try navigating to community
String? communityName = await getLemmyCommunity(parsedUrl);
if (communityName != null) {
try {
await navigateToFeedPage(context, feedType: FeedType.community, communityName: communityName);
return;
} catch (e) {
// Ignore exception, if it's not a valid community we'll perform the next fallback
}
}

// Try navigating to user
String? username = await getLemmyUser(parsedUrl);
if (username != null) {
try {
await navigateToUserPage(context, username: username);
return;
} catch (e) {
// Ignore exception, if it's not a valid user, we'll perform the next fallback
}
}

// Try navigating to post
int? postId = await getLemmyPostId(parsedUrl);
if (postId != null) {
try {
GetPostResponse post = await lemmy.run(GetPost(
id: postId,
auth: account?.jwt,
));

if (context.mounted) {
navigateToPost(context, postViewMedia: (await parsePostViews([post.postView])).first);
return;
}
} catch (e) {
// Ignore exception, if it's not a valid post, we'll perform the next fallback
}
}

// Try navigating to comment
int? commentId = await getLemmyCommentId(parsedUrl);
if (commentId != null) {
try {
CommentResponse fullCommentView = await lemmy.run(GetComment(
id: commentId,
auth: account?.jwt,
));

if (context.mounted) {
navigateToComment(context, fullCommentView.commentView);
return;
}
} catch (e) {
// Ignore exception, if it's not a valid comment, we'll perform the next fallback
}
}

// Fallback: open link in browser
if (url != null) {
openLink(context, url: parsedUrl, openInExternalBrowser: openInExternalBrowser);
}
},
// Since we're now rending links ourselves, we do not want a separate onTapLink handler.
// In fact, when this is here, it triggers on text that doesn't even represent a link.
//onTapLink: (text, url, title) => _handleLinkTap(context, state, text, url),
styleSheet: MarkdownStyleSheet.fromTheme(theme).copyWith(
// If its a comment, use the commentFontSizeScale, otherwise fallback to the contentFontSizeScale (for posts and other widgets using CommonMarkdownBody)
textScaleFactor: MediaQuery.of(context).textScaleFactor * (isComment == true ? state.commentFontSizeScale.textScaleFactor : state.contentFontSizeScale.textScaleFactor),
p: theme.textTheme.bodyMedium,
blockquoteDecoration: const BoxDecoration(
Expand All @@ -152,3 +79,198 @@ class CommonMarkdownBody extends StatelessWidget {
);
}
}

Future<void> _handleLinkTap(BuildContext context, ThunderState state, String text, String? url) async {
LemmyApiV3 lemmy = LemmyClient.instance.lemmyApiV3;
Account? account = await fetchActiveProfileAccount();

Uri? parsedUri = Uri.tryParse(text);

String parsedUrl = text;

if (parsedUri != null && parsedUri.host.isNotEmpty) {
parsedUrl = parsedUri.toString();
} else {
parsedUrl = url ?? '';
}

// The markdown link processor treats URLs with @ as emails and prepends "mailto:".
// If the URL contains that, but the text doesn't, we can remove it.
if (parsedUrl.startsWith('mailto:') && !text.startsWith('mailto:')) {
parsedUrl = parsedUrl.replaceFirst('mailto:', '');
}

// Try navigating to community
String? communityName = await getLemmyCommunity(parsedUrl);
if (communityName != null) {
try {
if (context.mounted) {
await navigateToFeedPage(context, feedType: FeedType.community, communityName: communityName);
return;
}
} catch (e) {
// Ignore exception, if it's not a valid community we'll perform the next fallback
}
}

// Try navigating to user
String? username = await getLemmyUser(parsedUrl);
if (username != null) {
try {
if (context.mounted) {
await navigateToUserPage(context, username: username);
return;
}
} catch (e) {
// Ignore exception, if it's not a valid user, we'll perform the next fallback
}
}

// Try navigating to post
int? postId = await getLemmyPostId(parsedUrl);
if (postId != null) {
try {
GetPostResponse post = await lemmy.run(GetPost(
id: postId,
auth: account?.jwt,
));

if (context.mounted) {
navigateToPost(context, postViewMedia: (await parsePostViews([post.postView])).first);
return;
}
} catch (e) {
// Ignore exception, if it's not a valid post, we'll perform the next fallback
}
}

// Try navigating to comment
int? commentId = await getLemmyCommentId(parsedUrl);
if (commentId != null) {
try {
CommentResponse fullCommentView = await lemmy.run(GetComment(
id: commentId,
auth: account?.jwt,
));

if (context.mounted) {
navigateToComment(context, fullCommentView.commentView);
return;
}
} catch (e) {
// Ignore exception, if it's not a valid comment, we'll perform the next fallback
}
}

// Fallback: open link in browser
if (url != null && context.mounted) {
openLink(context, url: parsedUrl, openInExternalBrowser: state.openInExternalBrowser);
}
}

/// Creates a [MarkdownElementBuilder] that renders links.
class LinkElementBuilder extends MarkdownElementBuilder {
final BuildContext context;
final ThunderState state;
final bool? isComment;

LinkElementBuilder({required this.context, required this.state, required this.isComment});

@override
Widget? visitElementAfterWithContext(BuildContext context, md.Element element, TextStyle? preferredStyle, TextStyle? parentStyle) {
final ThemeData theme = Theme.of(context);
final AppLocalizations l10n = AppLocalizations.of(context)!;

String? href = element.attributes['href'];
if (href == null) {
// Not a link
return super.visitElementAfterWithContext(context, element, preferredStyle, parentStyle);
} else if (href.startsWith('mailto:')) {
href = href.replaceFirst('mailto:', '');
}

return RichText(
text: TextSpan(
children: [
WidgetSpan(
alignment: PlaceholderAlignment.middle,
child: InkWell(
borderRadius: BorderRadius.circular(5),
onTap: () => _handleLinkTap(context, state, element.textContent, href),
onLongPress: () {
showModalBottomSheet(
context: context,
showDragHandle: true,
isScrollControlled: true,
builder: (ctx) => BottomSheetListPicker(
title: l10n.linkActions,
heading: Column(
children: [
if (!element.attributes['href']!.startsWith('mailto:')) ...[
LinkPreviewGenerator(
link: href!,
placeholderWidget: const CircularProgressIndicator(),
linkPreviewStyle: LinkPreviewStyle.large,
cacheDuration: Duration.zero,
onTap: () {},
bodyTextOverflow: TextOverflow.fade,
graphicFit: BoxFit.scaleDown,
removeElevation: true,
backgroundColor: theme.dividerColor.withOpacity(0.25),
borderRadius: 10,
),
const SizedBox(height: 10),
],
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
decoration: BoxDecoration(
color: theme.dividerColor.withOpacity(0.25),
borderRadius: BorderRadius.circular(10),
),
child: Padding(
padding: const EdgeInsets.all(5),
child: Text(href!),
),
),
],
),
],
),
items: [
ListPickerItem(label: l10n.open, payload: 'open', icon: Icons.language),
ListPickerItem(label: l10n.copy, payload: 'copy', icon: Icons.copy_rounded),
ListPickerItem(label: l10n.share, payload: 'share', icon: Icons.share_rounded),
],
onSelect: (value) {
switch (value.payload) {
case 'open':
_handleLinkTap(context, state, element.textContent, href);
break;
case 'copy':
Clipboard.setData(ClipboardData(text: href!));
break;
case 'share':
Share.share(href!);
break;
}
},
),
);
},
child: Text(
element.textContent,
// Note that we don't need to specify a textScaleFactor here because it's already applied by the styleSheet of the parent
style: theme.textTheme.bodyMedium?.copyWith(
// TODO: In the future, we could consider using a theme color (or a blend) here.
color: Colors.blue,
),
),
),
),
],
),
);
}
}
7 changes: 7 additions & 0 deletions lib/utils/bottom_sheet_list_picker.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ class BottomSheetListPicker<T> extends StatefulWidget {
final void Function(ListPickerItem<T>) onSelect;
final T? previouslySelected;
final bool closeOnSelect;
final Widget? heading;

const BottomSheetListPicker({
super.key,
Expand All @@ -17,6 +18,7 @@ class BottomSheetListPicker<T> extends StatefulWidget {
required this.onSelect,
this.previouslySelected,
this.closeOnSelect = true,
this.heading,
});

@override
Expand Down Expand Up @@ -49,6 +51,11 @@ class _BottomSheetListPickerState<T> extends State<BottomSheetListPicker<T>> {
),
),
),
if (widget.heading != null)
Padding(
padding: const EdgeInsets.only(left: 24, right: 24, bottom: 10),
child: widget.heading!,
),
ListView(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
Expand Down
Loading