From 7492817885e774092a99a477593b5cdd5d940490 Mon Sep 17 00:00:00 2001 From: Jojo Feng Date: Sun, 29 Nov 2026 13:19:04 +0000 Subject: [PATCH] feat: include titles when copying or sharing links --- lib/cubits/preference/preference_state.dart | 3 + lib/extensions/extensions.dart | 1 + lib/extensions/item_action_mixin.dart | 18 +- lib/extensions/item_link_extension.dart | 8 + lib/models/preference.dart | 21 ++ lib/screens/item/widgets/main_view.dart | 10 +- lib/screens/share/share_screen.dart | 15 +- .../preference/preference_cubit_test.dart | 16 ++ test/extensions/item_action_mixin_test.dart | 206 ++++++++++++++++++ 9 files changed, 293 insertions(+), 5 deletions(-) create mode 100644 lib/extensions/item_link_extension.dart create mode 100644 test/extensions/item_action_mixin_test.dart diff --git a/lib/cubits/preference/preference_state.dart b/lib/cubits/preference/preference_state.dart index d106fff2d..72330f3fa 100644 --- a/lib/cubits/preference/preference_state.dart +++ b/lib/cubits/preference/preference_state.dart @@ -107,6 +107,9 @@ class PreferenceState extends Equatable { bool get isWebViewBottomSheetEnabled => _isOn(); + bool get shouldIncludeTitleWhenSharingLinks => + _isOn(); + bool get isManualPaginationEnabled => _isOn(); bool get isTrueDarkModeEnabled => _isOn(); diff --git a/lib/extensions/extensions.dart b/lib/extensions/extensions.dart index 2cde3974b..5691fcbb4 100644 --- a/lib/extensions/extensions.dart +++ b/lib/extensions/extensions.dart @@ -3,6 +3,7 @@ export 'context_extension.dart'; export 'date_time_extension.dart'; export 'int_extension.dart'; export 'item_action_mixin.dart'; +export 'item_link_extension.dart'; export 'list_extension.dart'; export 'loggable.dart'; export 'set_extension.dart'; diff --git a/lib/extensions/item_action_mixin.dart b/lib/extensions/item_action_mixin.dart index f66ec9d40..4a36545e8 100644 --- a/lib/extensions/item_action_mixin.dart +++ b/lib/extensions/item_action_mixin.dart @@ -151,14 +151,28 @@ mixin ItemActionMixin on State { }, ); - if (linkToShare == 'image' && mounted) { + if (!mounted) return; + + if (linkToShare == 'image') { await context.push( Paths.share.landing, extra: ShareScreenArgs(item: item, parent: parent), ); } else if (linkToShare != null) { + final String text = item.linkText( + linkToShare, + includeTitle: context + .read() + .state + .shouldIncludeTitleWhenSharingLinks, + ); await SharePlus.instance.share( - ShareParams(uri: Uri.parse(linkToShare), sharePositionOrigin: rect), + text == linkToShare + ? ShareParams( + uri: Uri.parse(linkToShare), + sharePositionOrigin: rect, + ) + : ShareParams(text: text, sharePositionOrigin: rect), ); } } diff --git a/lib/extensions/item_link_extension.dart b/lib/extensions/item_link_extension.dart new file mode 100644 index 000000000..0cf9dbfd1 --- /dev/null +++ b/lib/extensions/item_link_extension.dart @@ -0,0 +1,8 @@ +import 'package:hacki/models/item/item.dart'; + +extension ItemLinkExtension on Item { + String linkText(String link, {required bool includeTitle}) { + final String title = this.title.trim(); + return includeTitle && title.isNotEmpty ? '$title - $link' : link; + } +} diff --git a/lib/models/preference.dart b/lib/models/preference.dart index 6df4a2dd3..cf3f8febd 100644 --- a/lib/models/preference.dart +++ b/lib/models/preference.dart @@ -87,6 +87,7 @@ abstract final class Preference extends Equatable with SettingsDisplayable { const CollapseModePreference(), const CustomTabPreference(), const WebViewBottomSheetPreference(), + const IncludeTitleWhenSharingLinksPreference(), const DividerPlaceholder(label: 'Thread Navigation'), const SkipButtonsPreference(), const HistoryButtonsPreference(), @@ -193,6 +194,26 @@ final class DevMode extends BooleanPreference { bool get isDisplayable => false; } +final class IncludeTitleWhenSharingLinksPreference extends BooleanPreference { + const IncludeTitleWhenSharingLinksPreference({bool? val}) + : super(val: val ?? false); + + @override + IncludeTitleWhenSharingLinksPreference copyWith({required bool? val}) => + IncludeTitleWhenSharingLinksPreference(val: val); + + @override + String get key => 'includeTitleWhenSharingLinks'; + + @override + String get title => 'Include Title when Copying or Sharing Links'; + + @override + String get subtitle => + 'use "title - URL" for article and HN links, ' + 'including Copy in the share sheet.'; +} + final class SkipButtonsPreference extends BooleanPreference { const SkipButtonsPreference({bool? val}) : super(val: val ?? _skipButtonsPreferenceDefaultValue); diff --git a/lib/screens/item/widgets/main_view.dart b/lib/screens/item/widgets/main_view.dart index 3a3107082..5a6c523df 100644 --- a/lib/screens/item/widgets/main_view.dart +++ b/lib/screens/item/widgets/main_view.dart @@ -644,7 +644,15 @@ class _ParentItemSection extends StatelessWidget { onLongPress: () { if (item.url.isNotEmpty) { Clipboard.setData( - ClipboardData(text: item.url), + ClipboardData( + text: item.linkText( + item.url, + includeTitle: context + .read() + .state + .shouldIncludeTitleWhenSharingLinks, + ), + ), ).whenComplete(() { HapticFeedbackUtils.selection(); if (context.mounted) { diff --git a/lib/screens/share/share_screen.dart b/lib/screens/share/share_screen.dart index bea5f4094..b5c19aa10 100644 --- a/lib/screens/share/share_screen.dart +++ b/lib/screens/share/share_screen.dart @@ -7,6 +7,7 @@ import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:hacki/config/constants.dart'; import 'package:hacki/cubits/cubits.dart'; import 'package:hacki/extensions/context_extension.dart'; +import 'package:hacki/extensions/item_link_extension.dart'; import 'package:hacki/models/models.dart'; import 'package:hacki/screens/widgets/widgets.dart'; import 'package:hacki/styles/styles.dart'; @@ -291,15 +292,25 @@ class _ShareScreenState extends State { '${Constants.hackerNewsItemLinkPrefix}$itemId', ); + if (!mounted) return; + + final String linkText = widget.args.item.linkText( + itemUrl.toString(), + includeTitle: context + .read() + .state + .shouldIncludeTitleWhenSharingLinks, + ); + final ShareParams shareParams = ShareParams( files: [XFile(file.path, mimeType: 'image/png')], - text: itemUrl.toString(), + text: linkText, sharePositionOrigin: rect ?? const Rect.fromLTWH(0, 0, 100, 100), // Tablet support ); if (_shouldCopyHnLink) { - await Clipboard.setData(ClipboardData(text: itemUrl.toString())); + await Clipboard.setData(ClipboardData(text: linkText)); } await SharePlus.instance.share(shareParams); diff --git a/test/cubits/preference/preference_cubit_test.dart b/test/cubits/preference/preference_cubit_test.dart index c5fee85b9..9d1a8f75f 100644 --- a/test/cubits/preference/preference_cubit_test.dart +++ b/test/cubits/preference/preference_cubit_test.dart @@ -29,6 +29,22 @@ void main() { return cubit; } + test('persists and resets the shared link title preference', () async { + final PreferenceCubit original = await loadCubit(); + expect(original.state.shouldIncludeTitleWhenSharingLinks, isFalse); + + original.update(const IncludeTitleWhenSharingLinksPreference(val: true)); + final PreferenceCubit restored = await loadCubit(); + expect(restored.state.shouldIncludeTitleWhenSharingLinks, isTrue); + + restored.restoreDefaultSettings(); + expect(restored.state.shouldIncludeTitleWhenSharingLinks, isFalse); + expect( + (await loadCubit()).state.shouldIncludeTitleWhenSharingLinks, + isFalse, + ); + }); + test('persists order and visibility across preference reloads', () async { final PreferenceCubit original = await loadCubit(); final List order = ItemMenuAction.values.reversed.toList(); diff --git a/test/extensions/item_action_mixin_test.dart b/test/extensions/item_action_mixin_test.dart new file mode 100644 index 000000000..15c089fb1 --- /dev/null +++ b/test/extensions/item_action_mixin_test.dart @@ -0,0 +1,206 @@ +import 'package:bloc_test/bloc_test.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:go_router/go_router.dart'; +import 'package:hacki/config/constants.dart'; +import 'package:hacki/cubits/cubits.dart'; +import 'package:hacki/extensions/item_action_mixin.dart'; +import 'package:hacki/models/models.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:mocktail/mocktail.dart'; + +class _MockPreferenceCubit extends MockCubit + implements PreferenceCubit {} + +class _ShareButton extends StatefulWidget { + const _ShareButton(this.item); + + final Item item; + + @override + State<_ShareButton> createState() => _ShareButtonState(); +} + +class _ShareButtonState extends State<_ShareButton> with ItemActionMixin { + @override + Widget build(BuildContext context) { + return ElevatedButton( + onPressed: () => onShareTapped(widget.item, _shareOrigin), + child: const Text('Share item'), + ); + } +} + +const Rect _shareOrigin = Rect.fromLTWH(10, 20, 30, 40); +const int _storyId = 50508845; +const String _title = "Japan's Hometown Tax (2018)"; +const String _articleUrl = 'https://example.com/hometown-tax'; +const String _hnUrl = '${Constants.hackerNewsItemLinkPrefix}$_storyId'; + +Story _story({String title = _title, String url = _articleUrl}) { + return Story.fromJson({ + 'id': _storyId, + 'title': title, + 'url': url, + }); +} + +void main() { + final TestWidgetsFlutterBinding binding = + TestWidgetsFlutterBinding.ensureInitialized(); + const MethodChannel shareChannel = MethodChannel( + 'dev.fluttercommunity.plus/share', + ); + late _MockPreferenceCubit preferenceCubit; + late List shareCalls; + + setUp(() { + preferenceCubit = _MockPreferenceCubit(); + when(() => preferenceCubit.state).thenReturn(PreferenceState.init()); + shareCalls = []; + binding.defaultBinaryMessenger.setMockMethodCallHandler(shareChannel, ( + MethodCall call, + ) async { + shareCalls.add(call); + return ''; + }); + }); + + tearDown(() { + binding.defaultBinaryMessenger.setMockMethodCallHandler(shareChannel, null); + }); + + Future openShareOptions( + WidgetTester tester, { + required Item item, + bool includeTitle = false, + }) async { + when(() => preferenceCubit.state).thenReturn( + PreferenceState.init().copyWithPreference( + IncludeTitleWhenSharingLinksPreference(val: includeTitle), + ), + ); + final GoRouter router = GoRouter( + routes: [ + GoRoute( + path: '/', + builder: (BuildContext context, GoRouterState state) => + Scaffold(body: _ShareButton(item)), + ), + ], + ); + addTearDown(router.dispose); + await tester.pumpWidget( + BlocProvider.value( + value: preferenceCubit, + child: MaterialApp.router(routerConfig: router), + ), + ); + await tester.tap(find.text('Share item')); + await tester.pumpAndSettle(); + } + + Map sharedArguments() { + expect(shareCalls, hasLength(1)); + expect(shareCalls.single.method, 'share'); + final Map arguments = + shareCalls.single.arguments as Map; + expect(arguments['originX'], _shareOrigin.left); + expect(arguments['originY'], _shareOrigin.top); + expect(arguments['originWidth'], _shareOrigin.width); + expect(arguments['originHeight'], _shareOrigin.height); + return arguments; + } + + for (final MapEntry link in { + 'Link to article': _articleUrl, + 'Link to HN': _hnUrl, + }.entries) { + testWidgets('${link.key} shares only the URL by default', ( + WidgetTester tester, + ) async { + await openShareOptions(tester, item: _story()); + await tester.tap(find.text(link.key)); + await tester.pumpAndSettle(); + + final Map arguments = sharedArguments(); + expect(arguments['uri'], link.value); + expect(arguments, isNot(contains('text'))); + }); + + testWidgets('${link.key} includes the title when enabled', ( + WidgetTester tester, + ) async { + await openShareOptions( + tester, + item: _story(title: ' $_title '), + includeTitle: true, + ); + await tester.tap(find.text(link.key)); + await tester.pumpAndSettle(); + + final Map arguments = sharedArguments(); + expect(arguments['text'], '$_title - ${link.value}'); + expect(arguments, isNot(contains('uri'))); + }); + } + + testWidgets('self-post shares the title with its HN link', ( + WidgetTester tester, + ) async { + await openShareOptions(tester, item: _story(url: ''), includeTitle: true); + expect(find.text('Link to article'), findsNothing); + await tester.tap(find.text('Link to HN')); + await tester.pumpAndSettle(); + + expect(sharedArguments()['text'], '$_title - $_hnUrl'); + }); + + testWidgets('comments still share only their HN link', ( + WidgetTester tester, + ) async { + await openShareOptions( + tester, + item: Comment.fromJson(const { + 'id': _storyId, + 'text': 'A comment with no title', + }), + includeTitle: true, + ); + expect(find.text('Link to article'), findsNothing); + await tester.tap(find.text('Link to HN')); + await tester.pumpAndSettle(); + + final Map arguments = sharedArguments(); + expect(arguments['uri'], _hnUrl); + expect(arguments, isNot(contains('text'))); + }); + + testWidgets('blank titles do not add a separator to the link', ( + WidgetTester tester, + ) async { + await openShareOptions( + tester, + item: _story(title: ' '), + includeTitle: true, + ); + await tester.tap(find.text('Link to article')); + await tester.pumpAndSettle(); + + final Map arguments = sharedArguments(); + expect(arguments['uri'], _articleUrl); + expect(arguments, isNot(contains('text'))); + }); + + testWidgets('dismissing the options does not share anything', ( + WidgetTester tester, + ) async { + await openShareOptions(tester, item: _story(), includeTitle: true); + await tester.tapAt(const Offset(10, 10)); + await tester.pumpAndSettle(); + + expect(find.text('Link to HN'), findsNothing); + expect(shareCalls, isEmpty); + }); +}