Compare commits

...

13 Commits

Author SHA1 Message Date
4e8cf9837f v0.2.13 (#34)
* fixed #32 and #33

* fall back to default browser #31

* fixed story tile.

* fixed version.

* use Listview.builder instead of listview.

* updated link utls.
2022-06-03 00:26:30 -07:00
f73269404a updated README.md 2022-06-01 09:13:35 -07:00
c4c109e4a3 v0.2.12 (#30)
* added metadata to story tile.

* bumped version

* fixed metadata tile

* bumped version.

* fixed pinned stories not being refreshed.
2022-06-01 01:34:21 -07:00
b7720d0584 v0.2.12 (#29)
* added metadata to story tile.

* bumped version

* fixed metadata tile

* bumped version.
2022-06-01 01:13:21 -07:00
7d5788dec3 updated README.md 2022-05-28 00:03:46 -07:00
80a836c6b9 updated README.md 2022-05-28 00:02:03 -07:00
913be9fc5d v0.2.11 (#27)
* fixed pinned story tile.

* bumped version.
2022-05-27 16:18:36 -07:00
7fceebfd56 fixed poll. (#26) 2022-05-27 10:56:19 -07:00
b9909b6a44 v0.2.9 (#25)
* improved link preview.

* fixed offline mode.

* make refresh controller required.

* remove shouldRetry.

* fixed link preview.
2022-05-25 02:25:58 -07:00
9346542328 improved link preview. (#24) 2022-05-24 22:50:04 -07:00
e8c4e2b653 bumped version. 2022-05-23 11:56:57 -07:00
f6a92be68a fixed collapsed comments. 2022-05-23 11:56:30 -07:00
21c486b7cf fixed comment tile. 2022-05-23 11:52:51 -07:00
51 changed files with 892 additions and 709 deletions

View File

@ -3,7 +3,7 @@
A simple noiseless [Hacker News](https://news.ycombinator.com/) client made with Flutter that is just enough. A simple noiseless [Hacker News](https://news.ycombinator.com/) client made with Flutter that is just enough.
[![App Store](https://img.shields.io/itunes/v/1602043763?label=App%20Store)](https://apps.apple.com/us/app/hacki/id1602043763) [![App Store](https://img.shields.io/itunes/v/1602043763?label=App%20Store)](https://apps.apple.com/us/app/hacki/id1602043763?platform=iphone)
[![Play Store](https://img.shields.io/badge/Play%20Store--yellow)](https://play.google.com/store/apps/details?id=com.jiaqifeng.hacki&hl=en_US&gl=US) [![Play Store](https://img.shields.io/badge/Play%20Store--yellow)](https://play.google.com/store/apps/details?id=com.jiaqifeng.hacki&hl=en_US&gl=US)
[![Visits Badge](https://badges.pufler.dev/visits/livinglist/Hacki)](https://badges.pufler.dev) [![Visits Badge](https://badges.pufler.dev/visits/livinglist/Hacki)](https://badges.pufler.dev)
[![GitHub](https://img.shields.io/github/stars/livinglist/Hacki?style=social)](https://img.shields.io/github/stars/livinglist/Hacki?style=social) [![GitHub](https://img.shields.io/github/stars/livinglist/Hacki?style=social)](https://img.shields.io/github/stars/livinglist/Hacki?style=social)
@ -11,7 +11,7 @@ A simple noiseless [Hacker News](https://news.ycombinator.com/) client made with
<noscript><a href="https://liberapay.com/jfeng_for_open_source/donate"><img alt="Donate using Liberapay" src="https://liberapay.com/assets/widgets/donate.svg"></a></noscript> <noscript><a href="https://liberapay.com/jfeng_for_open_source/donate"><img alt="Donate using Liberapay" src="https://liberapay.com/assets/widgets/donate.svg"></a></noscript>
[<img src="assets/images/app_store_badge.png" height="50">](https://apps.apple.com/us/app/hacki/id1602043763) [<img src="assets/images/google_play_badge.png" height="50">](https://play.google.com/store/apps/details?id=com.jiaqifeng.hacki&hl=en_US&gl=US) [<img src="assets/images/f_droid_badge.png" height="50">](https://f-droid.org/en/packages/com.jiaqifeng.hacki/) [<img src="assets/images/app_store_badge.png" height="50">](https://apps.apple.com/us/app/hacki/id1602043763?platform=iphone) [<img src="assets/images/google_play_badge.png" height="50">](https://play.google.com/store/apps/details?id=com.jiaqifeng.hacki&hl=en_US&gl=US) [<img src="assets/images/f_droid_badge.png" height="50">](https://f-droid.org/en/packages/com.jiaqifeng.hacki/)
Features: Features:
@ -34,20 +34,19 @@ Features:
- Launch from system share sheet. - Launch from system share sheet.
- And more... - And more...
<p align="center"> <p align="center">
<img width="200" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/159799288-6e98352a-fe89-4a2e-8a74-c5782463a1e1.png"> <img width="200" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/171450528-02c561ed-0ebb-4c1b-9ee0-a935211db0f2.png">
<img width="200" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/159799297-75b52eac-2066-4df9-bdfc-7c82bf7b81c8.png"> <img width="200" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/171450536-ea61c176-37d7-4744-8674-4668e0e7e774.png">
<img width="200" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/159799302-860c61b8-abba-486a-9592-bc84a6af3232.png"> <img width="200" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/171450541-a9af3417-526f-4dbd-96d7-781c95c886d3.png">
<img width="200" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/159799305-308743d3-1c89-45de-9645-3b6ec789c282.png"> <img width="200" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/171450543-fb631b02-5f46-4455-b8ff-9ef119a486f1.png">
<img width="200" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/159798176-5212e9bf-296d-4d9b-ab48-19b741684c8a.png"> <img width="200" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/171450548-38e98b02-6201-48c9-9674-87bdfc61f456.png">
<img width="200" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/159798179-72edbe49-7444-4e54-a07c-fc1244447a74.png"> <img width="200" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/159798179-72edbe49-7444-4e54-a07c-fc1244447a74.png">
<img width="200" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/159798182-28397805-a7cc-4124-b65b-c02c80afbbec.png"> <img width="200" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/159798182-28397805-a7cc-4124-b65b-c02c80afbbec.png">
<img width="200" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/159798183-c2984270-ee99-4419-841e-65e98890464f.png"> <img width="200" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/159798183-c2984270-ee99-4419-841e-65e98890464f.png">
<img width="200" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/159798184-2fce5d97-710e-44a7-b99a-3296ebcf273b.png"> <img width="200" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/159798184-2fce5d97-710e-44a7-b99a-3296ebcf273b.png">
<img width="200" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/159798185-d7c81348-956e-483c-a1bc-5cd872bdad62.png"> <img width="200" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/159798185-d7c81348-956e-483c-a1bc-5cd872bdad62.png">
<img width="200" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/159798186-1457ae21-f1aa-40a4-9206-0f3a1e24653e.png"> <img width="200" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/159798186-1457ae21-f1aa-40a4-9206-0f3a1e24653e.png">
<img width="200" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/159798187-4404adea-b2bc-472e-8568-2379e6db01a4.png"> <img width="200" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/171450557-ab038e72-78c4-4daf-9b77-3873be1700db.png">
<img width="400" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/160162711-a9146326-9645-4db6-a04e-1f82e6133e40.png"> <img width="400" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/160162711-a9146326-9645-4db6-a04e-1f82e6133e40.png">
<img width="400" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/160162726-ef1d3f2a-5179-417c-8a5f-0cddb52249da.png"> <img width="400" alt="Screen Shot 2020-03-03 at 1 22 57 PM" src="https://user-images.githubusercontent.com/7277662/160162726-ef1d3f2a-5179-417c-8a5f-0cddb52249da.png">

View File

@ -9,6 +9,10 @@
<action android:name="android.intent.action.VIEW" /> <action android:name="android.intent.action.VIEW" />
<data android:scheme="https" /> <data android:scheme="https" />
</intent> </intent>
<intent>
<action android:name="android.intent.action.SEND" />
<data android:mimeType="*/*" />
</intent>
</queries> </queries>
<application <application

View File

@ -0,0 +1,4 @@
- You can now participate in polls.
- Pick up where you left off.
- Swipe left on comment tile to view its parents without scrolling all the way up.
- Huge performance boost.

View File

@ -0,0 +1,4 @@
- You can now participate in polls.
- Pick up where you left off.
- Swipe left on comment tile to view its parents without scrolling all the way up.
- Huge performance boost.

View File

@ -0,0 +1,4 @@
- You can now participate in polls.
- Pick up where you left off.
- Swipe left on comment tile to view its parents without scrolling all the way up.
- Huge performance boost.

View File

@ -0,0 +1,4 @@
- You can now participate in polls.
- Pick up where you left off.
- Swipe left on comment tile to view its parents without scrolling all the way up.
- Huge performance boost.

View File

@ -0,0 +1,4 @@
- You can now participate in polls.
- Pick up where you left off.
- Swipe left on comment tile to view its parents without scrolling all the way up.
- Huge performance boost.

View File

@ -0,0 +1,4 @@
- You can now participate in polls.
- Pick up where you left off.
- Swipe left on comment tile to view its parents without scrolling all the way up.
- Huge performance boost.

View File

@ -0,0 +1,4 @@
- You can now participate in polls.
- Pick up where you left off.
- Swipe left on comment tile to view its parents without scrolling all the way up.
- Huge performance boost.

View File

@ -0,0 +1,5 @@
- You can now participate in polls.
- Pick up where you left off.
- Swipe left on comment tile to view its parents without scrolling all the way up.
- Huge performance boost.
- Bugfixes.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 393 KiB

After

Width:  |  Height:  |  Size: 422 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 696 KiB

After

Width:  |  Height:  |  Size: 712 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 250 KiB

After

Width:  |  Height:  |  Size: 252 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 231 KiB

After

Width:  |  Height:  |  Size: 262 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 903 KiB

After

Width:  |  Height:  |  Size: 672 KiB

View File

@ -568,7 +568,7 @@
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 2; CURRENT_PROJECT_VERSION = 3;
DEVELOPMENT_TEAM = QMWX3X2NF7; DEVELOPMENT_TEAM = QMWX3X2NF7;
ENABLE_BITCODE = NO; ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist; INFOPLIST_FILE = Runner/Info.plist;
@ -577,7 +577,7 @@
"$(inherited)", "$(inherited)",
"@executable_path/Frameworks", "@executable_path/Frameworks",
); );
MARKETING_VERSION = 0.2.8; MARKETING_VERSION = 0.2.13;
PRODUCT_BUNDLE_IDENTIFIER = com.jiaqi.hacki; PRODUCT_BUNDLE_IDENTIFIER = com.jiaqi.hacki;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = ""; PROVISIONING_PROFILE_SPECIFIER = "";
@ -705,7 +705,7 @@
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 2; CURRENT_PROJECT_VERSION = 3;
DEVELOPMENT_TEAM = QMWX3X2NF7; DEVELOPMENT_TEAM = QMWX3X2NF7;
ENABLE_BITCODE = NO; ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist; INFOPLIST_FILE = Runner/Info.plist;
@ -714,7 +714,7 @@
"$(inherited)", "$(inherited)",
"@executable_path/Frameworks", "@executable_path/Frameworks",
); );
MARKETING_VERSION = 0.2.8; MARKETING_VERSION = 0.2.13;
PRODUCT_BUNDLE_IDENTIFIER = com.jiaqi.hacki; PRODUCT_BUNDLE_IDENTIFIER = com.jiaqi.hacki;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = ""; PROVISIONING_PROFILE_SPECIFIER = "";
@ -736,7 +736,7 @@
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 2; CURRENT_PROJECT_VERSION = 3;
DEVELOPMENT_TEAM = QMWX3X2NF7; DEVELOPMENT_TEAM = QMWX3X2NF7;
ENABLE_BITCODE = NO; ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist; INFOPLIST_FILE = Runner/Info.plist;
@ -745,7 +745,7 @@
"$(inherited)", "$(inherited)",
"@executable_path/Frameworks", "@executable_path/Frameworks",
); );
MARKETING_VERSION = 0.2.8; MARKETING_VERSION = 0.2.13;
PRODUCT_BUNDLE_IDENTIFIER = com.jiaqi.hacki; PRODUCT_BUNDLE_IDENTIFIER = com.jiaqi.hacki;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = ""; PROVISIONING_PROFILE_SPECIFIER = "";

View File

@ -39,6 +39,12 @@
</array> </array>
<key>CFBundleVersion</key> <key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string> <string>$(CURRENT_PROJECT_VERSION)</string>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>https</string>
<string>http</string>
<string>mailto</string>
</array>
<key>LSRequiresIPhoneOS</key> <key>LSRequiresIPhoneOS</key>
<true/> <true/>
<key>UIBackgroundModes</key> <key>UIBackgroundModes</key>

View File

@ -55,21 +55,21 @@ class CollapseCubit extends Cubit<CollapseState> {
} }
void hiddenCommentsStreamListener(Map<int, Set<int>> event) { void hiddenCommentsStreamListener(Map<int, Set<int>> event) {
int collapsedCount = 0;
for (final int key in event.keys) { for (final int key in event.keys) {
if (key == _commentId && !isClosed) { if (key == _commentId && !isClosed) {
emit( collapsedCount = event[key]?.length ?? 0;
state.copyWith( break;
collapsedCount: event[key]?.length ?? 0,
),
);
return;
} }
} }
for (final Set<int> val in event.values) { for (final Set<int> val in event.values) {
if (val.contains(_commentId) && !isClosed) { if (val.contains(_commentId) && !isClosed) {
emit( emit(
state.copyWith(hidden: true), state.copyWith(
hidden: true,
collapsedCount: collapsedCount,
),
); );
return; return;
} }
@ -77,7 +77,10 @@ class CollapseCubit extends Cubit<CollapseState> {
if (!isClosed) { if (!isClosed) {
emit( emit(
state.copyWith(hidden: false), state.copyWith(
hidden: false,
collapsedCount: collapsedCount,
),
); );
} }
} }

View File

@ -89,6 +89,8 @@ class CommentsCubit extends Cubit<CommentsState> {
Future<void> refresh() async { Future<void> refresh() async {
final bool offlineReading = await _cacheRepository.hasCachedStories; final bool offlineReading = await _cacheRepository.hasCachedStories;
_cacheService.resetCollapsedComments();
if (offlineReading) { if (offlineReading) {
emit( emit(
state.copyWith( state.copyWith(

View File

@ -52,6 +52,8 @@ class PinCubit extends Cubit<PinState> {
_preferenceRepository.updatePinnedStoriesIds(state.pinnedStoriesIds); _preferenceRepository.updatePinnedStoriesIds(state.pinnedStoriesIds);
} }
void refresh() => init();
void _onStoryFetched(Story story) { void _onStoryFetched(Story story) {
emit(state.copyWith(pinnedStories: <Story>[...state.pinnedStories, story])); emit(state.copyWith(pinnedStories: <Story>[...state.pinnedStories, story]));
} }

View File

@ -23,6 +23,10 @@ class PollCubit extends Cubit<PollState> {
Future<void> init({ Future<void> init({
bool refresh = false, bool refresh = false,
}) async { }) async {
if (refresh) {
emit(PollState.init());
}
emit(state.copyWith(status: PollStatus.loading)); emit(state.copyWith(status: PollStatus.loading));
List<int> pollOptionsIds = _story.parts; List<int> pollOptionsIds = _story.parts;

View File

@ -31,6 +31,8 @@ class PreferenceCubit extends Cubit<PreferenceState> {
.then((bool value) => emit(state.copyWith(useReader: value))); .then((bool value) => emit(state.copyWith(useReader: value)));
_preferenceRepository.markReadStories _preferenceRepository.markReadStories
.then((bool value) => emit(state.copyWith(markReadStories: value))); .then((bool value) => emit(state.copyWith(markReadStories: value)));
_preferenceRepository.shouldShowMetadata
.then((bool value) => emit(state.copyWith(showMetadata: value)));
} }
void toggleNotificationMode() { void toggleNotificationMode() {
@ -67,4 +69,9 @@ class PreferenceCubit extends Cubit<PreferenceState> {
emit(state.copyWith(markReadStories: !state.markReadStories)); emit(state.copyWith(markReadStories: !state.markReadStories));
_preferenceRepository.toggleMarkReadStoriesMode(); _preferenceRepository.toggleMarkReadStoriesMode();
} }
void toggleMetadataMode() {
emit(state.copyWith(showMetadata: !state.showMetadata));
_preferenceRepository.toggleMetadataMode();
}
} }

View File

@ -9,6 +9,7 @@ class PreferenceState extends Equatable {
required this.useTrueDark, required this.useTrueDark,
required this.useReader, required this.useReader,
required this.markReadStories, required this.markReadStories,
required this.showMetadata,
}); });
const PreferenceState.init() const PreferenceState.init()
@ -18,7 +19,8 @@ class PreferenceState extends Equatable {
showEyeCandy = false, showEyeCandy = false,
useTrueDark = false, useTrueDark = false,
useReader = false, useReader = false,
markReadStories = false; markReadStories = false,
showMetadata = false;
final bool showNotification; final bool showNotification;
final bool showComplexStoryTile; final bool showComplexStoryTile;
@ -27,6 +29,7 @@ class PreferenceState extends Equatable {
final bool useTrueDark; final bool useTrueDark;
final bool useReader; final bool useReader;
final bool markReadStories; final bool markReadStories;
final bool showMetadata;
PreferenceState copyWith({ PreferenceState copyWith({
bool? showNotification, bool? showNotification,
@ -36,6 +39,7 @@ class PreferenceState extends Equatable {
bool? useTrueDark, bool? useTrueDark,
bool? useReader, bool? useReader,
bool? markReadStories, bool? markReadStories,
bool? showMetadata,
}) { }) {
return PreferenceState( return PreferenceState(
showNotification: showNotification ?? this.showNotification, showNotification: showNotification ?? this.showNotification,
@ -45,6 +49,7 @@ class PreferenceState extends Equatable {
useTrueDark: useTrueDark ?? this.useTrueDark, useTrueDark: useTrueDark ?? this.useTrueDark,
useReader: useReader ?? this.useReader, useReader: useReader ?? this.useReader,
markReadStories: markReadStories ?? this.markReadStories, markReadStories: markReadStories ?? this.markReadStories,
showMetadata: showMetadata ?? this.showMetadata,
); );
} }
@ -57,5 +62,6 @@ class PreferenceState extends Equatable {
useTrueDark, useTrueDark,
useReader, useReader,
markReadStories, markReadStories,
showMetadata,
]; ];
} }

View File

@ -4,4 +4,11 @@ extension StringExtension on String {
final String match = regex.stringMatch(this) ?? ''; final String match = regex.stringMatch(this) ?? '';
return int.tryParse(match); return int.tryParse(match);
} }
String removeAllEmojis() {
final RegExp regex = RegExp(
r'(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])',
);
return replaceAllMapped(regex, (_) => '');
}
} }

View File

@ -76,6 +76,7 @@ Future<void> main() async {
// runApp( // runApp(
// HackiApp( // HackiApp(
// savedThemeMode: savedThemeMode, // savedThemeMode: savedThemeMode,
// trueDarkMode: trueDarkMode,
// ), // ),
// ); // );
// }, // },

View File

@ -4,11 +4,15 @@ import 'package:hacki/extensions/extensions.dart';
import 'package:hacki/models/item.dart'; import 'package:hacki/models/item.dart';
enum StoryType { enum StoryType {
top, top('topstories'),
latest, latest('newstories'),
ask, ask('askstories'),
show, show('showstories'),
jobs, jobs('jobstories');
const StoryType(this.path);
final String path;
} }
class Story extends Item { class Story extends Item {
@ -66,6 +70,12 @@ class Story extends Item {
parent: 0, parent: 0,
); );
String get metadata =>
'''$score point${score > 1 ? 's' : ''} by $by $postedDate | $descendants comment${descendants > 1 ? 's' : ''}''';
String get simpleMetadata =>
'''$score point${score > 1 ? 's' : ''} $descendants comment${descendants > 1 ? 's' : ''} $postedDate''';
String get postedDate => String get postedDate =>
DateTime.fromMillisecondsSinceEpoch(time * 1000).toReadableString(); DateTime.fromMillisecondsSinceEpoch(time * 1000).toReadableString();

View File

@ -1,25 +1,23 @@
import 'dart:async'; import 'dart:async';
import 'dart:io';
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import 'package:hacki/config/locator.dart'; import 'package:hacki/config/locator.dart';
import 'package:hacki/models/models.dart'; import 'package:hacki/models/models.dart';
import 'package:hacki/repositories/postable_repository.dart';
import 'package:hacki/repositories/repositories.dart'; import 'package:hacki/repositories/repositories.dart';
import 'package:hacki/utils/service_exception.dart';
class AuthRepository { class AuthRepository extends PostableRepository {
AuthRepository({ AuthRepository({
Dio? dio, Dio? dio,
PreferenceRepository? preferenceRepository, PreferenceRepository? preferenceRepository,
}) : _dio = dio ?? Dio(), }) : _preferenceRepository =
_preferenceRepository = preferenceRepository ?? locator.get<PreferenceRepository>(),
preferenceRepository ?? locator.get<PreferenceRepository>(); super(dio: dio);
final PreferenceRepository _preferenceRepository;
static const String _authority = 'news.ycombinator.com'; static const String _authority = 'news.ycombinator.com';
final Dio _dio;
final PreferenceRepository _preferenceRepository;
Future<bool> get loggedIn async => _preferenceRepository.loggedIn; Future<bool> get loggedIn async => _preferenceRepository.loggedIn;
Future<String?> get username async => _preferenceRepository.username; Future<String?> get username async => _preferenceRepository.username;
@ -37,7 +35,7 @@ class AuthRepository {
goto: 'news', goto: 'news',
); );
final bool success = await _performDefaultPost(uri, data); final bool success = await performDefaultPost(uri, data);
if (success) { if (success) {
await _preferenceRepository.setAuth( await _preferenceRepository.setAuth(
@ -69,7 +67,7 @@ class AuthRepository {
un: flag ? null : 't', un: flag ? null : 't',
); );
return _performDefaultPost(uri, data); return performDefaultPost(uri, data);
} }
Future<bool> favorite({ Future<bool> favorite({
@ -86,7 +84,7 @@ class AuthRepository {
un: favorite ? null : 't', un: favorite ? null : 't',
); );
return _performDefaultPost(uri, data); return performDefaultPost(uri, data);
} }
Future<bool> upvote({ Future<bool> upvote({
@ -103,7 +101,7 @@ class AuthRepository {
how: upvote ? 'up' : 'un', how: upvote ? 'up' : 'un',
); );
return _performDefaultPost(uri, data); return performDefaultPost(uri, data);
} }
Future<bool> downvote({ Future<bool> downvote({
@ -120,53 +118,6 @@ class AuthRepository {
how: downvote ? 'down' : 'un', how: downvote ? 'down' : 'un',
); );
return _performDefaultPost(uri, data); return performDefaultPost(uri, data);
}
Future<bool> _performDefaultPost(
Uri uri,
PostDataMixin data, {
String? cookie,
bool Function(String?)? validateLocation,
}) async {
try {
final Response<void> response = await _performPost<void>(
uri,
data,
cookie: cookie,
validateStatus: (int? status) => status == HttpStatus.found,
);
if (validateLocation != null) {
return validateLocation(response.headers.value('location'));
}
return true;
} on ServiceException {
return false;
}
}
Future<Response<T>> _performPost<T>(
Uri uri,
PostDataMixin data, {
String? cookie,
ResponseType? responseType,
bool Function(int?)? validateStatus,
}) async {
try {
return await _dio.postUri<T>(
uri,
data: data.toJson(),
options: Options(
headers: <String, dynamic>{if (cookie != null) 'cookie': cookie},
responseType: responseType,
contentType: 'application/x-www-form-urlencoded',
validateStatus: validateStatus,
),
);
} on DioError catch (e) {
throw ServiceException(e.message);
}
} }
} }

View File

@ -3,20 +3,20 @@ import 'dart:io';
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import 'package:hacki/config/locator.dart'; import 'package:hacki/config/locator.dart';
import 'package:hacki/models/post_data.dart'; import 'package:hacki/models/post_data.dart';
import 'package:hacki/repositories/repositories.dart'; import 'package:hacki/repositories/postable_repository.dart';
import 'package:hacki/repositories/preference_repository.dart';
import 'package:hacki/utils/utils.dart'; import 'package:hacki/utils/utils.dart';
class PostRepository { class PostRepository extends PostableRepository {
PostRepository({Dio? dio, PreferenceRepository? storageRepository}) PostRepository({Dio? dio, PreferenceRepository? storageRepository})
: _dio = dio ?? Dio(), : _preferenceRepository =
_preferenceRepository = storageRepository ?? locator.get<PreferenceRepository>(),
storageRepository ?? locator.get<PreferenceRepository>(); super(dio: dio);
final PreferenceRepository _preferenceRepository;
static const String _authority = 'news.ycombinator.com'; static const String _authority = 'news.ycombinator.com';
final Dio _dio;
final PreferenceRepository _preferenceRepository;
Future<bool> comment({ Future<bool> comment({
required int parentId, required int parentId,
required String text, required String text,
@ -36,7 +36,7 @@ class PostRepository {
text: text, text: text,
); );
return _performDefaultPost( return performDefaultPost(
uri, uri,
data, data,
validateLocation: (String? location) => location == '/', validateLocation: (String? location) => location == '/',
@ -79,7 +79,7 @@ class PostRepository {
text: text, text: text,
); );
return _performDefaultPost( return performDefaultPost(
uri, uri,
data, data,
cookie: cookie, cookie: cookie,
@ -121,7 +121,7 @@ class PostRepository {
text: text, text: text,
); );
return _performDefaultPost( return performDefaultPost(
uri, uri,
data, data,
cookie: cookie, cookie: cookie,
@ -144,58 +144,11 @@ class PostRepository {
pw: password, pw: password,
id: id, id: id,
); );
return _performPost( return performPost(
uri, uri,
data, data,
responseType: ResponseType.bytes, responseType: ResponseType.bytes,
validateStatus: (int? status) => status == HttpStatus.ok, validateStatus: (int? status) => status == HttpStatus.ok,
); );
} }
Future<bool> _performDefaultPost(
Uri uri,
PostDataMixin data, {
String? cookie,
bool Function(String?)? validateLocation,
}) async {
try {
final Response<void> response = await _performPost<void>(
uri,
data,
cookie: cookie,
validateStatus: (int? status) => status == HttpStatus.found,
);
if (validateLocation != null) {
return validateLocation(response.headers.value('location'));
}
return true;
} on ServiceException {
return false;
}
}
Future<Response<T>> _performPost<T>(
Uri uri,
PostDataMixin data, {
String? cookie,
ResponseType? responseType,
bool Function(int?)? validateStatus,
}) async {
try {
return await _dio.postUri<T>(
uri,
data: data.toJson(),
options: Options(
headers: <String, dynamic>{if (cookie != null) 'cookie': cookie},
responseType: responseType,
contentType: 'application/x-www-form-urlencoded',
validateStatus: validateStatus,
),
);
} on DioError catch (e) {
throw ServiceException(e.message);
}
}
} }

View File

@ -0,0 +1,63 @@
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:hacki/models/models.dart';
import 'package:hacki/utils/service_exception.dart';
class PostableRepository {
PostableRepository({
Dio? dio,
}) : _dio = dio ?? Dio();
final Dio _dio;
@protected
Future<bool> performDefaultPost(
Uri uri,
PostDataMixin data, {
String? cookie,
bool Function(String?)? validateLocation,
}) async {
try {
final Response<void> response = await performPost<void>(
uri,
data,
cookie: cookie,
validateStatus: (int? status) => status == HttpStatus.found,
);
if (validateLocation != null) {
return validateLocation(response.headers.value('location'));
}
return true;
} on ServiceException {
return false;
}
}
@protected
Future<Response<T>> performPost<T>(
Uri uri,
PostDataMixin data, {
String? cookie,
ResponseType? responseType,
bool Function(int?)? validateStatus,
}) async {
try {
return await _dio.postUri<T>(
uri,
data: data.toJson(),
options: Options(
headers: <String, dynamic>{if (cookie != null) 'cookie': cookie},
responseType: responseType,
contentType: 'application/x-www-form-urlencoded',
validateStatus: validateStatus,
),
);
} on DioError catch (e) {
throw ServiceException(e.message);
}
}
}

View File

@ -21,6 +21,7 @@ class PreferenceRepository {
static const String _unreadCommentsIdsKey = 'unreadCommentsIds'; static const String _unreadCommentsIdsKey = 'unreadCommentsIds';
static const String _lastReadStoryIdKey = 'lastReadStoryId'; static const String _lastReadStoryIdKey = 'lastReadStoryId';
static const String _isFirstLaunchKey = 'isFirstLaunch'; static const String _isFirstLaunchKey = 'isFirstLaunch';
static const String _metadataModeKey = 'metadataMode';
static const String _notificationModeKey = 'notificationMode'; static const String _notificationModeKey = 'notificationMode';
static const String _readerModeKey = 'readerMode'; static const String _readerModeKey = 'readerMode';
@ -46,6 +47,7 @@ class PreferenceRepository {
static const bool _readerModeDefaultValue = true; static const bool _readerModeDefaultValue = true;
static const bool _markReadStoriesModeDefaultValue = true; static const bool _markReadStoriesModeDefaultValue = true;
static const bool _isFirstLaunchKeyDefaultValue = true; static const bool _isFirstLaunchKeyDefaultValue = true;
static const bool _metadataModeDefaultValue = true;
final SyncedSharedPreferences _syncedPrefs; final SyncedSharedPreferences _syncedPrefs;
final Future<SharedPreferences> _prefs; final Future<SharedPreferences> _prefs;
@ -67,29 +69,6 @@ class PreferenceRepository {
return val; return val;
} }
Future<List<String>> get blocklist async => _prefs.then(
(SharedPreferences prefs) =>
prefs.getStringList(_blocklistKey) ?? <String>[],
);
Future<List<int>> get pinnedStoriesIds async {
if (Platform.isIOS) {
final List<String>? favList = await _syncedPrefs.getStringList(
key: _pinnedStoriesIdsKey,
);
return favList?.map(int.parse).toList() ?? <int>[];
} else {
return _prefs.then(
(SharedPreferences prefs) =>
prefs
.getStringList(_pinnedStoriesIdsKey)
?.map(int.parse)
.toList() ??
<int>[],
);
}
}
Future<bool> get shouldShowNotification async => _prefs.then( Future<bool> get shouldShowNotification async => _prefs.then(
(SharedPreferences prefs) => (SharedPreferences prefs) =>
prefs.getBool(_notificationModeKey) ?? prefs.getBool(_notificationModeKey) ??
@ -111,6 +90,11 @@ class PreferenceRepository {
prefs.getBool(_eyeCandyModeKey) ?? _eyeCandyModeDefaultValue, prefs.getBool(_eyeCandyModeKey) ?? _eyeCandyModeDefaultValue,
); );
Future<bool> get shouldShowMetadata async => _prefs.then(
(SharedPreferences prefs) =>
prefs.getBool(_metadataModeKey) ?? _metadataModeDefaultValue,
);
Future<bool> get trueDarkMode async => _prefs.then( Future<bool> get trueDarkMode async => _prefs.then(
(SharedPreferences prefs) => (SharedPreferences prefs) =>
prefs.getBool(trueDarkModeKey) ?? _trueDarkModeDefaultValue, prefs.getBool(trueDarkModeKey) ?? _trueDarkModeDefaultValue,
@ -127,24 +111,6 @@ class PreferenceRepository {
_markReadStoriesModeDefaultValue, _markReadStoriesModeDefaultValue,
); );
Future<List<int>> get unreadCommentsIds async => _prefs.then(
(SharedPreferences prefs) =>
prefs
.getStringList(_unreadCommentsIdsKey)
?.map(int.parse)
.toList() ??
<int>[],
);
Future<int?> get lastReadStoryId async =>
_prefs.then((SharedPreferences prefs) {
final String? val = prefs.getString(_lastReadStoryIdKey);
if (val == null) return null;
return int.tryParse(val);
});
Future<bool> hasPushed(int commentId) async => Future<bool> hasPushed(int commentId) async =>
_prefs.then((SharedPreferences prefs) { _prefs.then((SharedPreferences prefs) {
final bool? val = prefs.getBool(_getPushNotificationKey(commentId)); final bool? val = prefs.getBool(_getPushNotificationKey(commentId));
@ -170,53 +136,6 @@ class PreferenceRepository {
} }
} }
Future<List<int>> favList({required String of}) async {
final SharedPreferences prefs = await _prefs;
if (Platform.isIOS) {
final List<String> previousList =
((prefs.getStringList(_getFavKey('')) ?? <String>[])
..addAll(prefs.getStringList(_getFavKey(of)) ?? <String>[]))
.toList();
/// Since v0.2.5, fav list will be stored in [NSUbiquitousKeyValueStore]
/// instead of [UserDefaults] on iOS.
if (previousList.isNotEmpty) {
for (final String fav in previousList) {
await addFav(username: of, id: int.parse(fav));
}
await prefs.remove(_getFavKey(''));
await prefs.remove(_getFavKey(of));
}
final List<String>? initialList =
await _syncedPrefs.getStringList(key: _getFavKey(''));
final List<String>? userList =
await _syncedPrefs.getStringList(key: _getFavKey(of));
return <String>{
...?initialList,
...?userList,
}.map(int.parse).toList();
} else {
final List<int> favList =
((prefs.getStringList(_getFavKey('')) ?? <String>[])
..addAll(prefs.getStringList(_getFavKey(of)) ?? <String>[]))
.map(int.parse)
.toSet()
.toList();
return favList;
}
}
Future<bool?> vote({required int submittedTo, required String from}) async {
final SharedPreferences prefs = await _prefs;
final String key = _getVoteKey(from, submittedTo);
final bool? vote = prefs.getBool(key);
return vote;
}
Future<void> setAuth({ Future<void> setAuth({
required String username, required String username,
required String password, required String password,
@ -279,6 +198,55 @@ class PreferenceRepository {
await prefs.setBool(_markReadStoriesModeKey, !currentMode); await prefs.setBool(_markReadStoriesModeKey, !currentMode);
} }
Future<void> toggleMetadataMode() async {
final SharedPreferences prefs = await _prefs;
final bool currentMode =
prefs.getBool(_metadataModeKey) ?? _metadataModeDefaultValue;
await prefs.setBool(_metadataModeKey, !currentMode);
}
//#region fav
Future<List<int>> favList({required String of}) async {
final SharedPreferences prefs = await _prefs;
if (Platform.isIOS) {
final List<String> previousList =
((prefs.getStringList(_getFavKey('')) ?? <String>[])
..addAll(prefs.getStringList(_getFavKey(of)) ?? <String>[]))
.toList();
/// Since v0.2.5, fav list will be stored in [NSUbiquitousKeyValueStore]
/// instead of [UserDefaults] on iOS.
if (previousList.isNotEmpty) {
for (final String fav in previousList) {
await addFav(username: of, id: int.parse(fav));
}
await prefs.remove(_getFavKey(''));
await prefs.remove(_getFavKey(of));
}
final List<String>? initialList =
await _syncedPrefs.getStringList(key: _getFavKey(''));
final List<String>? userList =
await _syncedPrefs.getStringList(key: _getFavKey(of));
return <String>{
...?initialList,
...?userList,
}.map(int.parse).toList();
} else {
final List<int> favList =
((prefs.getStringList(_getFavKey('')) ?? <String>[])
..addAll(prefs.getStringList(_getFavKey(of)) ?? <String>[]))
.map(int.parse)
.toSet()
.toList();
return favList;
}
}
Future<void> addFav({required String username, required int id}) async { Future<void> addFav({required String username, required int id}) async {
final String key = _getFavKey(username); final String key = _getFavKey(username);
@ -331,6 +299,19 @@ class PreferenceRepository {
} }
} }
static String _getFavKey(String username) => 'fav_$username';
//#endregion
//#region vote
Future<bool?> vote({required int submittedTo, required String from}) async {
final SharedPreferences prefs = await _prefs;
final String key = _getVoteKey(from, submittedTo);
final bool? vote = prefs.getBool(key);
return vote;
}
Future<void> addVote({ Future<void> addVote({
required String username, required String username,
required int id, required int id,
@ -350,11 +331,44 @@ class PreferenceRepository {
await prefs.remove(key); await prefs.remove(key);
} }
String _getVoteKey(String username, int id) => 'vote_$username-$id';
//#endregion
//#region blocklist
Future<List<String>> get blocklist async => _prefs.then(
(SharedPreferences prefs) =>
prefs.getStringList(_blocklistKey) ?? <String>[],
);
Future<void> updateBlocklist(List<String> usernames) async { Future<void> updateBlocklist(List<String> usernames) async {
final SharedPreferences prefs = await _prefs; final SharedPreferences prefs = await _prefs;
await prefs.setStringList(_blocklistKey, usernames); await prefs.setStringList(_blocklistKey, usernames);
} }
//#endregion
//#region pins
Future<List<int>> get pinnedStoriesIds async {
if (Platform.isIOS) {
final List<String>? favList = await _syncedPrefs.getStringList(
key: _pinnedStoriesIdsKey,
);
return favList?.map(int.parse).toList() ?? <int>[];
} else {
return _prefs.then(
(SharedPreferences prefs) =>
prefs
.getStringList(_pinnedStoriesIdsKey)
?.map(int.parse)
.toList() ??
<int>[],
);
}
}
Future<void> updatePinnedStoriesIds(List<int> ids) async { Future<void> updatePinnedStoriesIds(List<int> ids) async {
if (Platform.isIOS) { if (Platform.isIOS) {
await _syncedPrefs.setStringList( await _syncedPrefs.setStringList(
@ -370,6 +384,19 @@ class PreferenceRepository {
} }
} }
//#endregion
//#region unread comment ids
Future<List<int>> get unreadCommentsIds async => _prefs.then(
(SharedPreferences prefs) =>
prefs
.getStringList(_unreadCommentsIdsKey)
?.map(int.parse)
.toList() ??
<int>[],
);
Future<void> updateUnreadCommentsIds(List<int> ids) async { Future<void> updateUnreadCommentsIds(List<int> ids) async {
final SharedPreferences prefs = await _prefs; final SharedPreferences prefs = await _prefs;
await prefs.setStringList( await prefs.setStringList(
@ -378,6 +405,19 @@ class PreferenceRepository {
); );
} }
//#endregion
//#region reminder
Future<int?> get lastReadStoryId async =>
_prefs.then((SharedPreferences prefs) {
final String? val = prefs.getString(_lastReadStoryIdKey);
if (val == null) return null;
return int.tryParse(val);
});
Future<void> updateLastReadStoryId(int? id) async { Future<void> updateLastReadStoryId(int? id) async {
final SharedPreferences prefs = await _prefs; final SharedPreferences prefs = await _prefs;
await prefs.setString( await prefs.setString(
@ -386,6 +426,8 @@ class PreferenceRepository {
); );
} }
//#endregion
Future<void> updateHasPushed(int commentId) async { Future<void> updateHasPushed(int commentId) async {
final SharedPreferences prefs = await _prefs; final SharedPreferences prefs = await _prefs;
await prefs.setBool( await prefs.setBool(
@ -422,11 +464,7 @@ class PreferenceRepository {
} }
} }
String _getPushNotificationKey(int commentId) => 'pushed_$commentId'; static String _getPushNotificationKey(int commentId) => 'pushed_$commentId';
String _getFavKey(String username) => 'fav_$username'; static String _getHasReadKey(int storyId) => 'hasRead_$storyId';
String _getVoteKey(String username, int id) => 'vote_$username-$id';
String _getHasReadKey(int storyId) => 'hasRead_$storyId';
} }

View File

@ -28,6 +28,8 @@ class SearchRepository {
final String by = hit['author'] as String? ?? ''; final String by = hit['author'] as String? ?? '';
final String title = hit['title'] as String? ?? ''; final String title = hit['title'] as String? ?? '';
final int createdAt = hit['created_at_i'] as int? ?? 0; final int createdAt = hit['created_at_i'] as int? ?? 0;
final int score = hit['points'] as int? ?? 0;
final int descendants = hit['num_comments'] as int? ?? 0;
// Getting rid of comments, only keeping stories for convenience. // Getting rid of comments, only keeping stories for convenience.
// Don't judge me. // Don't judge me.
@ -46,9 +48,9 @@ class SearchRepository {
final int id = int.parse(hit['objectID'] as String? ?? '0'); final int id = int.parse(hit['objectID'] as String? ?? '0');
final Story story = Story( final Story story = Story(
descendants: 0, descendants: descendants,
id: id, id: id,
score: 0, score: score,
time: createdAt, time: createdAt,
by: by, by: by,
title: title, title: title,

View File

@ -25,22 +25,9 @@ class StoriesRepository {
} }
Future<List<int>> fetchStoryIds({required StoryType of}) async { Future<List<int>> fetchStoryIds({required StoryType of}) async {
final String suffix = () { final List<int> ids = await _firebaseClient
switch (of) { .get('$_baseUrl${of.path}.json')
case StoryType.top: .then((dynamic val) {
return 'topstories.json';
case StoryType.latest:
return 'newstories.json';
case StoryType.ask:
return 'askstories.json';
case StoryType.show:
return 'showstories.json';
case StoryType.jobs:
return 'jobstories.json';
}
}();
final List<int> ids =
await _firebaseClient.get('$_baseUrl$suffix').then((dynamic val) {
final List<int> ids = (val as List<dynamic>).cast<int>(); final List<int> ids = (val as List<dynamic>).cast<int>();
return ids; return ids;
}); });

View File

@ -140,7 +140,8 @@ class _HomeScreenState extends State<HomeScreen>
final BlocBuilder<PreferenceCubit, PreferenceState> homeScreen = final BlocBuilder<PreferenceCubit, PreferenceState> homeScreen =
BlocBuilder<PreferenceCubit, PreferenceState>( BlocBuilder<PreferenceCubit, PreferenceState>(
buildWhen: (PreferenceState previous, PreferenceState current) => buildWhen: (PreferenceState previous, PreferenceState current) =>
previous.showComplexStoryTile != current.showComplexStoryTile, previous.showComplexStoryTile != current.showComplexStoryTile ||
previous.showMetadata != current.showMetadata,
builder: (BuildContext context, PreferenceState preferenceState) { builder: (BuildContext context, PreferenceState preferenceState) {
final BlocBuilder<PinCubit, PinState> pinnedStories = final BlocBuilder<PinCubit, PinState> pinnedStories =
BlocBuilder<PinCubit, PinState>( BlocBuilder<PinCubit, PinState>(
@ -172,8 +173,9 @@ class _HomeScreenState extends State<HomeScreen>
child: StoryTile( child: StoryTile(
key: ObjectKey(story), key: ObjectKey(story),
story: story, story: story,
onTap: () => onStoryTapped(story), onTap: () => onStoryTapped(story, isPin: true),
showWebPreview: preferenceState.showComplexStoryTile, showWebPreview: preferenceState.showComplexStoryTile,
showMetadata: preferenceState.showMetadata,
), ),
), ),
), ),
@ -408,13 +410,13 @@ class _HomeScreenState extends State<HomeScreen>
return Future<bool>.value(false); return Future<bool>.value(false);
} }
void onStoryTapped(Story story) { void onStoryTapped(Story story, {bool isPin = false}) {
final bool showWebFirst = final bool showWebFirst =
context.read<PreferenceCubit>().state.showWebFirst; context.read<PreferenceCubit>().state.showWebFirst;
final bool useReader = context.read<PreferenceCubit>().state.useReader; final bool useReader = context.read<PreferenceCubit>().state.useReader;
final bool offlineReading = final bool offlineReading =
context.read<StoriesBloc>().state.offlineReading; context.read<StoriesBloc>().state.offlineReading;
final bool hasRead = context.read<StoriesBloc>().hasRead(story); final bool hasRead = isPin || context.read<StoriesBloc>().hasRead(story);
final bool splitViewEnabled = context.read<SplitViewCubit>().state.enabled; final bool splitViewEnabled = context.read<SplitViewCubit>().state.enabled;
// If a story is a job story and it has a link to the job posting, // If a story is a job story and it has a link to the job posting,
@ -443,7 +445,7 @@ class _HomeScreenState extends State<HomeScreen>
} }
if (!offlineReading && (isJobWithLink || (showWebFirst && !hasRead))) { if (!offlineReading && (isJobWithLink || (showWebFirst && !hasRead))) {
LinkUtil.launchUrl(story.url, useReader: useReader); LinkUtil.launch(story.url, useReader: useReader);
} }
context.read<StoriesBloc>().add( context.read<StoriesBloc>().add(

View File

@ -119,6 +119,7 @@ class _ProfileScreenState extends State<ProfileScreen>
return ItemsListView<Item>( return ItemsListView<Item>(
showWebPreview: false, showWebPreview: false,
showMetadata: false,
useConsistentFontSize: true, useConsistentFontSize: true,
refreshController: refreshControllerHistory, refreshController: refreshControllerHistory,
items: historyState.submittedItems items: historyState.submittedItems
@ -170,6 +171,7 @@ class _ProfileScreenState extends State<ProfileScreen>
return ItemsListView<Story>( return ItemsListView<Story>(
showWebPreview: showWebPreview:
preferenceState.showComplexStoryTile, preferenceState.showComplexStoryTile,
showMetadata: preferenceState.showMetadata,
refreshController: refreshControllerFav, refreshController: refreshControllerFav,
items: favState.favStories, items: favState.favStories,
onRefresh: () { onRefresh: () {
@ -292,6 +294,21 @@ class _ProfileScreenState extends State<ProfileScreen>
}, },
activeColor: Colors.orange, activeColor: Colors.orange,
), ),
SwitchListTile(
title: const Text('Show Metadata'),
subtitle: const Text(
'show number of comments and post date'
' in story tile.',
),
value: preferenceState.showMetadata,
onChanged: (bool val) {
HapticFeedback.lightImpact();
context
.read<PreferenceCubit>()
.toggleMetadataMode();
},
activeColor: Colors.orange,
),
SwitchListTile( SwitchListTile(
title: const Text('Show Web Page First'), title: const Text('Show Web Page First'),
subtitle: const Text( subtitle: const Text(
@ -390,7 +407,7 @@ class _ProfileScreenState extends State<ProfileScreen>
showAboutDialog( showAboutDialog(
context: context, context: context,
applicationName: 'Hacki', applicationName: 'Hacki',
applicationVersion: 'v0.2.8', applicationVersion: 'v0.2.13',
applicationIcon: ClipRRect( applicationIcon: ClipRRect(
borderRadius: const BorderRadius.all( borderRadius: const BorderRadius.all(
Radius.circular(12), Radius.circular(12),
@ -403,7 +420,7 @@ class _ProfileScreenState extends State<ProfileScreen>
), ),
children: <Widget>[ children: <Widget>[
ElevatedButton( ElevatedButton(
onPressed: () => LinkUtil.launchUrl( onPressed: () => LinkUtil.launch(
Constants.portfolioLink, Constants.portfolioLink,
), ),
child: Row( child: Row(
@ -419,7 +436,7 @@ class _ProfileScreenState extends State<ProfileScreen>
), ),
), ),
ElevatedButton( ElevatedButton(
onPressed: () => LinkUtil.launchUrl( onPressed: () => LinkUtil.launch(
Constants.githubLink, Constants.githubLink,
), ),
child: Row( child: Row(
@ -435,7 +452,7 @@ class _ProfileScreenState extends State<ProfileScreen>
), ),
), ),
ElevatedButton( ElevatedButton(
onPressed: () => LinkUtil.launchUrl( onPressed: () => LinkUtil.launch(
Platform.isIOS Platform.isIOS
? Constants.appStoreLink ? Constants.appStoreLink
: Constants.googlePlayLink, : Constants.googlePlayLink,
@ -806,7 +823,7 @@ class _ProfileScreenState extends State<ProfileScreen>
child: Transform.translate( child: Transform.translate(
offset: const Offset(0, 1), offset: const Offset(0, 1),
child: TapDownWrapper( child: TapDownWrapper(
onTap: () => LinkUtil.launchUrl( onTap: () => LinkUtil.launch(
Constants.endUserAgreementLink, Constants.endUserAgreementLink,
), ),
child: const Text( child: const Text(

View File

@ -48,20 +48,14 @@ class InboxView extends StatelessWidget {
loadStyle: LoadStyle.ShowWhenLoading, loadStyle: LoadStyle.ShowWhenLoading,
builder: (BuildContext context, LoadStatus? mode) { builder: (BuildContext context, LoadStatus? mode) {
Widget body; Widget body;
if (mode == LoadStatus.idle) { if (mode == LoadStatus.loading) {
body = const Text('');
} else if (mode == LoadStatus.loading) {
body = const CustomCircularProgressIndicator(); body = const CustomCircularProgressIndicator();
} else if (mode == LoadStatus.failed) { } else if (mode == LoadStatus.failed) {
body = const Text( body = const Text(
'loading failed.', 'loading failed.',
); );
} else if (mode == LoadStatus.canLoading) {
body = const Text(
'loading more.',
);
} else { } else {
body = const Text(''); body = const SizedBox.shrink();
} }
return SizedBox( return SizedBox(
height: 55, height: 55,
@ -113,7 +107,7 @@ class InboxView extends StatelessWidget {
), ),
maxLines: 4, maxLines: 4,
onOpen: (LinkableElement link) => onOpen: (LinkableElement link) =>
LinkUtil.launchUrl(link.url), LinkUtil.launch(link.url),
), ),
), ),
), ),

View File

@ -73,20 +73,14 @@ class _SearchScreenState extends State<SearchScreen> {
loadStyle: LoadStyle.ShowWhenLoading, loadStyle: LoadStyle.ShowWhenLoading,
builder: (BuildContext context, LoadStatus? mode) { builder: (BuildContext context, LoadStatus? mode) {
Widget body; Widget body;
if (mode == LoadStatus.idle) { if (mode == LoadStatus.loading) {
body = const Text('');
} else if (mode == LoadStatus.loading) {
body = const CustomCircularProgressIndicator(); body = const CustomCircularProgressIndicator();
} else if (mode == LoadStatus.failed) { } else if (mode == LoadStatus.failed) {
body = const Text( body = const Text(
'loading failed.', 'loading failed.',
); );
} else if (mode == LoadStatus.canLoading) {
body = const Text(
'loading more.',
);
} else { } else {
body = const Text(''); body = const SizedBox.shrink();
} }
return SizedBox( return SizedBox(
height: 55, height: 55,
@ -108,6 +102,7 @@ class _SearchScreenState extends State<SearchScreen> {
child: StoryTile( child: StoryTile(
showWebPreview: showWebPreview:
prefState.showComplexStoryTile, prefState.showComplexStoryTile,
showMetadata: prefState.showMetadata,
story: e, story: e,
onTap: () => goToStoryScreen( onTap: () => goToStoryScreen(
args: StoryScreenArgs(story: e), args: StoryScreenArgs(story: e),

View File

@ -140,6 +140,7 @@ class _StoryScreenState extends State<StoryScreen> {
delay: _featureDiscoveryDismissThrottleDelay, delay: _featureDiscoveryDismissThrottleDelay,
); );
static const int _extraItemsCount = 2;
static const Duration _storyLinkTapThrottleDelay = Duration(seconds: 2); static const Duration _storyLinkTapThrottleDelay = Duration(seconds: 2);
static const Duration _featureDiscoveryDismissThrottleDelay = static const Duration _featureDiscoveryDismissThrottleDelay =
Duration(seconds: 1); Duration(seconds: 1);
@ -261,214 +262,237 @@ class _StoryScreenState extends State<StoryScreen> {
HapticFeedback.lightImpact(); HapticFeedback.lightImpact();
locator.get<CacheService>().resetComments(); locator.get<CacheService>().resetComments();
context.read<CommentsCubit>().refresh(); context.read<CommentsCubit>().refresh();
context.read<PollCubit>().refresh();
if (widget.story.isPoll) {
context.read<PollCubit>().refresh();
}
}, },
onLoading: () { onLoading: () {
context.read<CommentsCubit>().loadMore(); context.read<CommentsCubit>().loadMore();
}, },
child: ListView( child: ListView.builder(
primary: false, primary: false,
children: <Widget>[ itemCount: state.comments.length + _extraItemsCount,
SizedBox( itemBuilder: (BuildContext context, int index) {
height: topPadding, if (index == 0) {
), return Column(
if (!widget.splitViewEnabled)
const Padding(
padding: EdgeInsets.only(bottom: 6),
child: OfflineBanner(),
),
Slidable(
startActionPane: ActionPane(
motion: const BehindMotion(),
children: <Widget>[ children: <Widget>[
SlidableAction( SizedBox(
onPressed: (_) { height: topPadding,
HapticFeedback.lightImpact();
if (widget.story !=
context.read<EditCubit>().state.replyingTo) {
commentEditingController.clear();
}
context
.read<EditCubit>()
.onReplyTapped(widget.story);
focusNode.requestFocus();
},
backgroundColor: Colors.orange,
foregroundColor: Colors.white,
icon: Icons.message,
), ),
SlidableAction( if (!widget.splitViewEnabled)
onPressed: (_) => onMorePressed(widget.story), const Padding(
backgroundColor: Colors.orange, padding: EdgeInsets.only(bottom: 6),
foregroundColor: Colors.white, child: OfflineBanner(),
icon: Icons.more_horiz,
),
],
),
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(
left: 6,
right: 6,
), ),
child: Row( Slidable(
startActionPane: ActionPane(
motion: const BehindMotion(),
children: <Widget>[ children: <Widget>[
Text( SlidableAction(
widget.story.by, onPressed: (_) {
style: const TextStyle( HapticFeedback.lightImpact();
color: Colors.orange,
), if (widget.story !=
context
.read<EditCubit>()
.state
.replyingTo) {
commentEditingController.clear();
}
context
.read<EditCubit>()
.onReplyTapped(widget.story);
focusNode.requestFocus();
},
backgroundColor: Colors.orange,
foregroundColor: Colors.white,
icon: Icons.message,
), ),
const Spacer(), SlidableAction(
Text( onPressed: (_) => onMorePressed(widget.story),
widget.story.postedDate, backgroundColor: Colors.orange,
style: const TextStyle( foregroundColor: Colors.white,
color: Colors.grey, icon: Icons.more_horiz,
),
), ),
], ],
), ),
), child: Column(
InkWell( children: <Widget>[
onTap: () => LinkUtil.launchUrl( Padding(
widget.story.url, padding: const EdgeInsets.only(
useReader: context left: 6,
.read<PreferenceCubit>() right: 6,
.state ),
.useReader, child: Row(
), children: <Widget>[
child: Padding( Text(
padding: const EdgeInsets.only( widget.story.by,
left: 6, style: const TextStyle(
right: 6, color: Colors.orange,
bottom: 12, ),
top: 12, ),
), const Spacer(),
child: Text( Text(
widget.story.title, widget.story.postedDate,
textAlign: TextAlign.center, style: const TextStyle(
style: TextStyle( color: Colors.grey,
fontWeight: FontWeight.bold, ),
color: widget.story.url.isNotEmpty ),
? Colors.orange ],
: null, ),
), ),
), InkWell(
onTap: () => LinkUtil.launch(
widget.story.url,
useReader: context
.read<PreferenceCubit>()
.state
.useReader,
),
child: Padding(
padding: const EdgeInsets.only(
left: 6,
right: 6,
bottom: 12,
top: 12,
),
child: Text(
widget.story.title,
textAlign: TextAlign.center,
style: TextStyle(
fontWeight: FontWeight.bold,
color: widget.story.url.isNotEmpty
? Colors.orange
: null,
),
),
),
),
if (widget.story.text.isNotEmpty)
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 10,
),
child: SelectableLinkify(
text: widget.story.text,
style: TextStyle(
fontSize: MediaQuery.of(context)
.textScaleFactor *
15,
),
linkStyle: TextStyle(
fontSize: MediaQuery.of(context)
.textScaleFactor *
15,
color: Colors.orange,
),
onOpen: (LinkableElement link) {
if (link.url.contains(
'news.ycombinator.com/item',
)) {
onStoryLinkTapped(link.url);
} else {
LinkUtil.launch(link.url);
}
},
),
),
if (widget.story.isPoll)
PollView(
onLoginTapped: onLoginTapped,
),
],
), ),
), ),
if (widget.story.text.isNotEmpty) if (widget.story.text.isNotEmpty)
Padding( const SizedBox(
padding: const EdgeInsets.symmetric( height: 8,
horizontal: 10, ),
), const Divider(
child: SelectableLinkify( height: 0,
text: widget.story.text, ),
style: TextStyle( if (state.onlyShowTargetComment) ...<Widget>[
fontSize: TextButton(
MediaQuery.of(context).textScaleFactor * onPressed: () => context
15, .read<CommentsCubit>()
), .loadAll(widget.story),
linkStyle: TextStyle( child: const Text('View all comments'),
fontSize: ),
MediaQuery.of(context).textScaleFactor * const Divider(
15, height: 0,
color: Colors.orange, ),
), ],
onOpen: (LinkableElement link) { if (state.comments.isEmpty &&
if (link.url.contains( state.status ==
'news.ycombinator.com/item', CommentsStatus.allLoaded) ...<Widget>[
)) { const SizedBox(
onStoryLinkTapped(link.url); height: 240,
} else { ),
LinkUtil.launchUrl(link.url); const Center(
} child: Text(
}, 'Nothing yet',
style: TextStyle(color: Colors.grey),
), ),
), ),
if (widget.story.isPoll) ],
PollView(
onLoginTapped: onLoginTapped,
),
], ],
), );
), } else if (index ==
if (widget.story.text.isNotEmpty) state.comments.length + _extraItemsCount - 1) {
const SizedBox( if ((state.status == CommentsStatus.allLoaded &&
height: 8, state.comments.isNotEmpty) ||
), state.onlyShowTargetComment) {
const Divider( return SizedBox(
height: 0, height: 240,
), child: Center(
if (state.onlyShowTargetComment) ...<Widget>[ child: Text(happyFace),
TextButton( ),
onPressed: () => );
context.read<CommentsCubit>().loadAll(widget.story), }
child: const Text('View all comments'),
),
const Divider(
height: 0,
),
],
if (state.comments.isEmpty &&
state.status == CommentsStatus.allLoaded) ...<Widget>[
const SizedBox(
height: 240,
),
const Center(
child: Text(
'Nothing yet',
style: TextStyle(color: Colors.grey),
),
),
],
for (final Comment e in state.comments)
FadeIn(
child: CommentTile(
comment: e,
level: e.level,
myUsername:
authState.isLoggedIn ? authState.username : null,
opUsername: widget.story.by,
onReplyTapped: (Comment cmt) {
HapticFeedback.lightImpact();
if (cmt.deleted || cmt.dead) {
return;
}
if (cmt != return const SizedBox.shrink();
context.read<EditCubit>().state.replyingTo) { }
commentEditingController.clear();
}
context.read<EditCubit>().onReplyTapped(cmt); final Comment comment = state.comments.elementAt(index - 1);
focusNode.requestFocus();
}, return FadeIn(
onEditTapped: (Comment cmt) { key: ValueKey<int>(comment.id),
HapticFeedback.lightImpact(); child: CommentTile(
if (cmt.deleted || cmt.dead) { comment: comment,
return; level: comment.level,
} myUsername:
authState.isLoggedIn ? authState.username : null,
opUsername: widget.story.by,
onReplyTapped: (Comment cmt) {
HapticFeedback.lightImpact();
if (cmt.deleted || cmt.dead) {
return;
}
if (cmt !=
context.read<EditCubit>().state.replyingTo) {
commentEditingController.clear(); commentEditingController.clear();
context.read<EditCubit>().onEditTapped(cmt); }
focusNode.requestFocus();
}, context.read<EditCubit>().onReplyTapped(cmt);
onMoreTapped: onMorePressed, focusNode.requestFocus();
onStoryLinkTapped: onStoryLinkTapped, },
onTimeMachineActivated: onTimeMachineActivated, onEditTapped: (Comment cmt) {
), HapticFeedback.lightImpact();
if (cmt.deleted || cmt.dead) {
return;
}
commentEditingController.clear();
context.read<EditCubit>().onEditTapped(cmt);
focusNode.requestFocus();
},
onMoreTapped: onMorePressed,
onStoryLinkTapped: onStoryLinkTapped,
onTimeMachineActivated: onTimeMachineActivated,
), ),
if ((state.status == CommentsStatus.allLoaded && );
state.comments.isNotEmpty) || },
state.onlyShowTargetComment)
SizedBox(
height: 240,
child: Center(
child: Text(happyFace),
),
),
],
), ),
); );
@ -671,7 +695,7 @@ class _StoryScreenState extends State<StoryScreen> {
}); });
}); });
} else { } else {
LinkUtil.launchUrl(link); LinkUtil.launch(link);
} }
} }
@ -1090,7 +1114,7 @@ class _StoryScreenState extends State<StoryScreen> {
child: Transform.translate( child: Transform.translate(
offset: const Offset(0, 1), offset: const Offset(0, 1),
child: TapDownWrapper( child: TapDownWrapper(
onTap: () => LinkUtil.launchUrl( onTap: () => LinkUtil.launch(
Constants.endUserAgreementLink, Constants.endUserAgreementLink,
), ),
child: const Text( child: const Text(

View File

@ -47,7 +47,7 @@ class LinkIconButton extends StatelessWidget {
), ),
), ),
onPressed: () => onPressed: () =>
LinkUtil.launchUrl('https://news.ycombinator.com/item?id=$storyId'), LinkUtil.launch('https://news.ycombinator.com/item?id=$storyId'),
); );
} }
} }

View File

@ -124,7 +124,7 @@ class PollView extends StatelessWidget {
option.text, option.text,
), ),
Text( Text(
'${option.score} votes', '''${option.score} vote${option.score > 1 ? 's' : ''}''',
style: const TextStyle( style: const TextStyle(
color: Colors.grey, color: Colors.grey,
fontSize: 12, fontSize: 12,

View File

@ -273,7 +273,7 @@ class _ReplyBoxState extends State<ReplyBox> {
color: Colors.orange, color: Colors.orange,
), ),
onOpen: (LinkableElement link) => onOpen: (LinkableElement link) =>
LinkUtil.launchUrl(link.url), LinkUtil.launch(link.url),
text: replyingTo?.text ?? '', text: replyingTo?.text ?? '',
), ),
), ),

View File

@ -109,8 +109,6 @@ class CommentTile extends StatelessWidget {
: null, : null,
child: InkWell( child: InkWell(
onTap: () { onTap: () {
if (comment.deleted || comment.dead) return;
if (actionable) { if (actionable) {
HapticFeedback.lightImpact(); HapticFeedback.lightImpact();
context.read<CollapseCubit>().collapse(); context.read<CollapseCubit>().collapse();
@ -152,7 +150,21 @@ class CommentTile extends StatelessWidget {
], ],
), ),
), ),
if (comment.deleted) if (actionable && state.collapsed)
Center(
child: Padding(
padding:
const EdgeInsets.only(bottom: 12),
child: Text(
'collapsed '
'(${state.collapsedCount + 1})',
style: const TextStyle(
color: Colors.orangeAccent,
),
),
),
)
else if (comment.deleted)
const Center( const Center(
child: Padding( child: Padding(
padding: EdgeInsets.only(bottom: 12), padding: EdgeInsets.only(bottom: 12),
@ -189,20 +201,6 @@ class CommentTile extends StatelessWidget {
), ),
), ),
) )
else if (actionable && state.collapsed)
Center(
child: Padding(
padding:
const EdgeInsets.only(bottom: 12),
child: Text(
'collapsed '
'(${state.collapsedCount + 1})',
style: const TextStyle(
color: Colors.orangeAccent,
),
),
),
)
else else
Padding( Padding(
padding: const EdgeInsets.only( padding: const EdgeInsets.only(
@ -231,7 +229,7 @@ class CommentTile extends StatelessWidget {
)) { )) {
onStoryLinkTapped.call(link.url); onStoryLinkTapped.call(link.url);
} else { } else {
LinkUtil.launchUrl(link.url); LinkUtil.launch(link.url);
} }
}, },
), ),

View File

@ -14,6 +14,7 @@ class ItemsListView<T extends Item> extends StatelessWidget {
const ItemsListView({ const ItemsListView({
super.key, super.key,
required this.showWebPreview, required this.showWebPreview,
required this.showMetadata,
required this.items, required this.items,
required this.onTap, required this.onTap,
required this.refreshController, required this.refreshController,
@ -32,6 +33,7 @@ class ItemsListView<T extends Item> extends StatelessWidget {
); );
final bool showWebPreview; final bool showWebPreview;
final bool showMetadata;
final bool enablePullDown; final bool enablePullDown;
final bool markReadStories; final bool markReadStories;
final bool showOfflineBanner; final bool showOfflineBanner;
@ -44,7 +46,7 @@ class ItemsListView<T extends Item> extends StatelessWidget {
final List<T> items; final List<T> items;
final Widget? header; final Widget? header;
final RefreshController? refreshController; final RefreshController refreshController;
final VoidCallback? onRefresh; final VoidCallback? onRefresh;
final VoidCallback? onLoadMore; final VoidCallback? onLoadMore;
final ValueChanged<Story>? onPinned; final ValueChanged<Story>? onPinned;
@ -89,6 +91,7 @@ class ItemsListView<T extends Item> extends StatelessWidget {
story: e, story: e,
onTap: () => onTap(e), onTap: () => onTap(e),
showWebPreview: showWebPreview, showWebPreview: showWebPreview,
showMetadata: showMetadata,
hasRead: markReadStories && hasRead, hasRead: markReadStories && hasRead,
simpleTileFontSize: useConsistentFontSize ? 14 : 16, simpleTileFontSize: useConsistentFontSize ? 14 : 16,
), ),
@ -138,7 +141,7 @@ class ItemsListView<T extends Item> extends StatelessWidget {
color: Colors.orange, color: Colors.orange,
), ),
onOpen: (LinkableElement link) => onOpen: (LinkableElement link) =>
LinkUtil.launchUrl(link.url), LinkUtil.launch(link.url),
), ),
), ),
), ),
@ -180,10 +183,6 @@ class ItemsListView<T extends Item> extends StatelessWidget {
], ],
); );
if (refreshController == null) {
return child;
}
return SmartRefresher( return SmartRefresher(
enablePullUp: true, enablePullUp: true,
enablePullDown: enablePullDown, enablePullDown: enablePullDown,
@ -194,20 +193,14 @@ class ItemsListView<T extends Item> extends StatelessWidget {
loadStyle: LoadStyle.ShowWhenLoading, loadStyle: LoadStyle.ShowWhenLoading,
builder: (BuildContext context, LoadStatus? mode) { builder: (BuildContext context, LoadStatus? mode) {
Widget body; Widget body;
if (mode == LoadStatus.idle) { if (mode == LoadStatus.loading) {
body = const Text('');
} else if (mode == LoadStatus.loading) {
body = const CustomCircularProgressIndicator(); body = const CustomCircularProgressIndicator();
} else if (mode == LoadStatus.failed) { } else if (mode == LoadStatus.failed) {
body = const Text( body = const Text(
'loading failed.', 'loading failed.',
); );
} else if (mode == LoadStatus.canLoading) {
body = const Text(
'loading more.',
);
} else { } else {
body = const Text(''); body = const SizedBox.shrink();
} }
return SizedBox( return SizedBox(
height: 55, height: 55,
@ -215,7 +208,7 @@ class ItemsListView<T extends Item> extends StatelessWidget {
); );
}, },
), ),
controller: refreshController!, controller: refreshController,
onRefresh: onRefresh, onRefresh: onRefresh,
onLoading: onLoadMore, onLoading: onLoadMore,
child: child, child: child,

View File

@ -1,8 +1,8 @@
import 'dart:async'; import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:hacki/config/constants.dart'; import 'package:hacki/config/constants.dart';
import 'package:hacki/models/models.dart';
import 'package:hacki/screens/widgets/link_preview/link_view.dart'; import 'package:hacki/screens/widgets/link_preview/link_view.dart';
import 'package:hacki/screens/widgets/link_preview/web_analyzer.dart'; import 'package:hacki/screens/widgets/link_preview/web_analyzer.dart';
import 'package:url_launcher/url_launcher.dart'; import 'package:url_launcher/url_launcher.dart';
@ -11,6 +11,8 @@ class LinkPreview extends StatefulWidget {
const LinkPreview({ const LinkPreview({
super.key, super.key,
required this.link, required this.link,
required this.story,
required this.showMetadata,
this.cache = const Duration(days: 30), this.cache = const Duration(days: 30),
this.titleStyle, this.titleStyle,
this.bodyStyle, this.bodyStyle,
@ -28,6 +30,8 @@ class LinkPreview extends StatefulWidget {
this.removeElevation = false, this.removeElevation = false,
}); });
final Story story;
/// Web address (Url that need to be parsed) /// Web address (Url that need to be parsed)
/// For IOS & Web, only HTTP and HTTPS are support /// For IOS & Web, only HTTP and HTTPS are support
/// For Android, all urls are supported /// For Android, all urls are supported
@ -95,18 +99,19 @@ class LinkPreview extends StatefulWidget {
/// `[BoxShadow(blurRadius: 3, color: Colors.grey)]` /// `[BoxShadow(blurRadius: 3, color: Colors.grey)]`
final List<BoxShadow>? boxShadow; final List<BoxShadow>? boxShadow;
final bool showMetadata;
@override @override
_LinkPreviewState createState() => _LinkPreviewState(); _LinkPreviewState createState() => _LinkPreviewState();
} }
class _LinkPreviewState extends State<LinkPreview> { class _LinkPreviewState extends State<LinkPreview> {
InfoBase? _info; InfoBase? _info;
String? _errorImage, _errorTitle, _errorBody, _url; String? _errorTitle, _errorBody, _url;
bool _loading = false; bool _loading = false;
@override @override
void initState() { void initState() {
_errorImage = widget.errorImage ?? Constants.hackerNewsLogoLink;
_errorTitle = widget.errorTitle ?? 'Something went wrong!'; _errorTitle = widget.errorTitle ?? 'Something went wrong!';
_errorBody = widget.errorBody ?? _errorBody = widget.errorBody ??
'Oops! Unable to parse the url. We have ' 'Oops! Unable to parse the url. We have '
@ -114,7 +119,12 @@ class _LinkPreviewState extends State<LinkPreview> {
'we will try to fix this in our next release. Thanks!'; 'we will try to fix this in our next release. Thanks!';
_url = widget.link.trim(); _url = widget.link.trim();
_info = WebAnalyzer.getInfoFromCache(_url); if (_url?.isNotEmpty ?? false) {
_info = WebAnalyzer.getInfoFromCache(_url);
} else {
_info = WebAnalyzer.getInfoFromCache(widget.story.id.toString());
}
if (_info == null) { if (_info == null) {
_loading = true; _loading = true;
_getInfo(); _getInfo();
@ -124,14 +134,23 @@ class _LinkPreviewState extends State<LinkPreview> {
Future<void> _getInfo() async { Future<void> _getInfo() async {
if (_url!.startsWith('http') || _url!.startsWith('https')) { if (_url!.startsWith('http') || _url!.startsWith('https')) {
_info = await WebAnalyzer.getInfo(_url, cache: widget.cache); _info = await WebAnalyzer.getInfo(
if (mounted) { _url,
setState(() { story: widget.story,
_loading = false; cache: widget.cache,
}); );
}
} else { } else {
//print('$_url is not starting with either http or https'); _info = await WebAnalyzer.getInfo(
widget.story.id.toString(),
story: widget.story,
cache: widget.cache,
);
}
if (mounted) {
setState(() {
_loading = false;
});
} }
} }
@ -167,10 +186,12 @@ class _LinkPreviewState extends State<LinkPreview> {
height: _height, height: _height,
child: LinkView( child: LinkView(
key: widget.key ?? Key(widget.link), key: widget.key ?? Key(widget.link),
metadata: widget.story.simpleMetadata,
url: widget.link, url: widget.link,
title: title!, title: title!,
description: desc!, description: desc!,
imageUri: imageUri, imageUri: imageUri,
imagePath: Constants.hackerNewsLogoPath,
onTap: _launchURL, onTap: _launchURL,
titleTextStyle: widget.titleStyle, titleTextStyle: widget.titleStyle,
bodyTextStyle: widget.bodyStyle, bodyTextStyle: widget.bodyStyle,
@ -180,6 +201,7 @@ class _LinkPreviewState extends State<LinkPreview> {
isIcon: isIcon, isIcon: isIcon,
bgColor: widget.backgroundColor, bgColor: widget.backgroundColor,
radius: widget.borderRadius ?? 12, radius: widget.borderRadius ?? 12,
showMetadata: widget.showMetadata,
), ),
); );
} }
@ -187,11 +209,11 @@ class _LinkPreviewState extends State<LinkPreview> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final double screenWidth = MediaQuery.of(context).size.width; final double screenWidth = MediaQuery.of(context).size.width;
final bool showSmallerPreviewPic = final bool showSmallerPreviewPic = screenWidth > 428.0 && screenWidth < 850;
Platform.isIOS && screenWidth > 428.0 && screenWidth < 850;
final double _height = showSmallerPreviewPic final double _height = showSmallerPreviewPic
? 100.0 ? 100.0
: (MediaQuery.of(context).size.height * 0.14).clamp(118.0, 140.0); : (MediaQuery.of(context).size.height * 0.14).clamp(118.0, 140.0);
final Widget loadingWidget = widget.placeholderWidget ?? final Widget loadingWidget = widget.placeholderWidget ??
Container( Container(
height: _height, height: _height,
@ -212,9 +234,8 @@ class _LinkPreviewState extends State<LinkPreview> {
_height, _height,
title: _errorTitle, title: _errorTitle,
desc: _errorBody, desc: _errorBody,
imageUri: widget.showMultimedia imageUri:
? (img.trim() == '' ? _errorImage : img) widget.showMultimedia ? (img.trim() == '' ? null : img) : null,
: null,
); );
} else { } else {
final WebInfo? info = _info as WebInfo?; final WebInfo? info = _info as WebInfo?;
@ -222,7 +243,8 @@ class _LinkPreviewState extends State<LinkPreview> {
? _buildLinkContainer( ? _buildLinkContainer(
_height, _height,
title: _errorTitle, title: _errorTitle,
imageUri: widget.showMultimedia ? _errorImage : null, desc: _errorBody,
imageUri: null,
) )
: _buildLinkContainer( : _buildLinkContainer(
_height, _height,
@ -235,7 +257,7 @@ class _LinkPreviewState extends State<LinkPreview> {
? info.image ? info.image
: WebAnalyzer.isNotEmpty(info.icon) : WebAnalyzer.isNotEmpty(info.icon)
? info.icon ? info.icon
: _errorImage) : null)
: null, : null,
isIcon: !WebAnalyzer.isNotEmpty(info.image), isIcon: !WebAnalyzer.isNotEmpty(info.image),
); );

View File

@ -5,10 +5,12 @@ import 'package:hacki/config/constants.dart';
class LinkView extends StatelessWidget { class LinkView extends StatelessWidget {
const LinkView({ const LinkView({
super.key, super.key,
required this.metadata,
required this.url, required this.url,
required this.title, required this.title,
required this.description, required this.description,
required this.onTap, required this.onTap,
required this.showMetadata,
this.imageUri, this.imageUri,
this.imagePath, this.imagePath,
this.titleTextStyle, this.titleTextStyle,
@ -25,6 +27,7 @@ class LinkView extends StatelessWidget {
'imageUri or imagePath cannot be null when showMultiMedia is true', 'imageUri or imagePath cannot be null when showMultiMedia is true',
); );
final String metadata;
final String url; final String url;
final String title; final String title;
final String description; final String description;
@ -39,6 +42,7 @@ class LinkView extends StatelessWidget {
final bool isIcon; final bool isIcon;
final double radius; final double radius;
final Color? bgColor; final Color? bgColor;
final bool showMetadata;
double computeTitleFontSize(double width) { double computeTitleFontSize(double width) {
double size = width * 0.13; double size = width * 0.13;
@ -97,7 +101,7 @@ class LinkView extends StatelessWidget {
child: (imageUri?.isEmpty ?? true) && imagePath != null child: (imageUri?.isEmpty ?? true) && imagePath != null
? Image.asset( ? Image.asset(
imagePath!, imagePath!,
fit: isIcon ? BoxFit.scaleDown : BoxFit.fitWidth, fit: BoxFit.cover,
) )
: CachedNetworkImage( : CachedNetworkImage(
imageUrl: imageUri!, imageUrl: imageUri!,
@ -166,6 +170,20 @@ class LinkView extends StatelessWidget {
padding: const EdgeInsets.fromLTRB(5, 3, 5, 0), padding: const EdgeInsets.fromLTRB(5, 3, 5, 0),
child: Column( child: Column(
children: <Widget>[ children: <Widget>[
if (showMetadata)
Container(
alignment: Alignment.topLeft,
child: Text(
metadata,
textAlign: TextAlign.left,
style: _bodyTS.copyWith(
fontSize:
_bodyTS.fontSize == null ? 12 : _bodyTS.fontSize! - 2,
),
overflow: bodyTextOverflow ?? TextOverflow.ellipsis,
maxLines: 1,
),
),
Expanded( Expanded(
child: Container( child: Container(
alignment: Alignment.topLeft, alignment: Alignment.topLeft,
@ -174,7 +192,8 @@ class LinkView extends StatelessWidget {
textAlign: TextAlign.left, textAlign: TextAlign.left,
style: _bodyTS, style: _bodyTS,
overflow: bodyTextOverflow ?? TextOverflow.ellipsis, overflow: bodyTextOverflow ?? TextOverflow.ellipsis,
maxLines: bodyMaxLines ?? _maxLines, maxLines:
(bodyMaxLines ?? _maxLines) - (showMetadata ? 1 : 0),
), ),
), ),
), ),

View File

@ -5,7 +5,11 @@ import 'dart:io';
import 'package:collection/collection.dart' show IterableExtension; import 'package:collection/collection.dart' show IterableExtension;
import 'package:fast_gbk/fast_gbk.dart'; import 'package:fast_gbk/fast_gbk.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:html/dom.dart' hide Text; import 'package:hacki/config/locator.dart';
import 'package:hacki/extensions/extensions.dart';
import 'package:hacki/models/models.dart';
import 'package:hacki/repositories/repositories.dart';
import 'package:html/dom.dart' hide Text, Comment;
import 'package:html/parser.dart' as parser; import 'package:html/parser.dart' as parser;
import 'package:http/http.dart'; import 'package:http/http.dart';
import 'package:http/io_client.dart'; import 'package:http/io_client.dart';
@ -63,7 +67,7 @@ class WebVideoInfo extends WebImageInfo {
/// Web analyzer /// Web analyzer
class WebAnalyzer { class WebAnalyzer {
static final Map<String?, InfoBase> _map = <String?, InfoBase>{}; static final Map<String?, InfoBase> cacheMap = <String?, InfoBase>{};
static final RegExp _bodyReg = static final RegExp _bodyReg =
RegExp(r'<body[^>]*>([\s\S]*?)<\/body>', caseSensitive: false); RegExp(r'<body[^>]*>([\s\S]*?)<\/body>', caseSensitive: false);
static final RegExp _htmlReg = RegExp( static final RegExp _htmlReg = RegExp(
@ -80,7 +84,10 @@ class WebAnalyzer {
static final RegExp _lineReg = RegExp(r'[\n\r]|&nbsp;|&gt;'); static final RegExp _lineReg = RegExp(r'[\n\r]|&nbsp;|&gt;');
static final RegExp _spaceReg = RegExp(r'\s+'); static final RegExp _spaceReg = RegExp(r'\s+');
/// Is it an empty string static bool isEmpty(String? str) {
return !isNotEmpty(str);
}
static bool isNotEmpty(String? str) { static bool isNotEmpty(String? str) {
return str != null && str.isNotEmpty && str.trim().isNotEmpty; return str != null && str.isNotEmpty && str.trim().isNotEmpty;
} }
@ -88,10 +95,11 @@ class WebAnalyzer {
/// Get web information /// Get web information
/// return [InfoBase] /// return [InfoBase]
static InfoBase? getInfoFromCache(String? url) { static InfoBase? getInfoFromCache(String? url) {
final InfoBase? info = _map[url]; final InfoBase? info = cacheMap[url];
if (info != null) { if (info != null) {
if (!info._timeout.isAfter(DateTime.now())) { if (!info._timeout.isAfter(DateTime.now())) {
_map.remove(url); cacheMap.remove(url);
} }
} }
return info; return info;
@ -101,25 +109,69 @@ class WebAnalyzer {
/// return [InfoBase] /// return [InfoBase]
static Future<InfoBase?> getInfo( static Future<InfoBase?> getInfo(
String? url, { String? url, {
required Story story,
Duration cache = const Duration(hours: 24), Duration cache = const Duration(hours: 24),
bool multimedia = true, bool multimedia = true,
}) async { }) async {
// final start = DateTime.now();
InfoBase? info = getInfoFromCache(url); InfoBase? info = getInfoFromCache(url);
if (info != null) return info; if (info != null) return info;
if (story.url.isEmpty && story.text.isNotEmpty) {
info = WebInfo(
title: story.title,
description: story.text,
).._timeout = DateTime.now().add(cache);
cacheMap[story.id.toString()] = info;
return info;
}
try { try {
info = await _getInfoByIsolate(url, multimedia); info = await _getInfoByIsolate(url, multimedia);
if (info != null) { if (info != null) {
info._timeout = DateTime.now().add(cache); info._timeout = DateTime.now().add(cache);
_map[url] = info; cacheMap[url] = info;
} }
} catch (e) { } catch (e) {
//print('Get web error:$url, Error:$e'); //locator.get<Logger>().log(Level.error, e);
} }
// print("$url cost ${DateTime.now().difference(start).inMilliseconds}"); if ((info == null ||
info is WebImageInfo ||
(info is WebInfo && (info.description?.isEmpty ?? true))) &&
story.kids.isNotEmpty) {
bool shouldRetry = false;
final Comment? comment = await locator
.get<StoriesRepository>()
.fetchCommentBy(id: story.kids.first)
.catchError((Object err) async {
int index = 0;
Comment? comment;
while (comment == null && index < story.kids.length) {
comment = await locator
.get<CacheRepository>()
.getCachedComment(id: story.kids.elementAt(index));
index++;
}
shouldRetry = true;
return comment;
});
info = WebInfo(
description:
comment != null ? '${comment.by}: ${comment.text}' : 'no comments',
image: info is WebInfo ? info.image : (info as WebImageInfo?)?.image,
icon: info is WebInfo ? info.icon : null,
);
if (!shouldRetry) {
info._timeout = DateTime.now().add(cache);
cacheMap[url] = info;
}
}
return info; return info;
} }
@ -128,6 +180,7 @@ class WebAnalyzer {
final Response? response = await _requestUrl(url); final Response? response = await _requestUrl(url);
if (response == null) return null; if (response == null) return null;
if (multimedia!) { if (multimedia!) {
final String? contentType = response.headers['content-type']; final String? contentType = response.headers['content-type'];
if (contentType != null) { if (contentType != null) {
@ -156,7 +209,8 @@ class WebAnalyzer {
if (res[0] == '0') { if (res[0] == '0') {
info = WebInfo( info = WebInfo(
title: res[1] as String?, title: res[1] as String?,
description: res[2] as String?, description:
res[2] == null ? null : (res[2] as String).removeAllEmojis(),
icon: res[3] as String?, icon: res[3] as String?,
image: res[4] as String?, image: res[4] as String?,
); );
@ -214,17 +268,21 @@ class WebAnalyzer {
..maxRedirects = 3 ..maxRedirects = 3
..persistentConnection = true ..persistentConnection = true
..headers['accept-encoding'] = 'gzip, deflate' ..headers['accept-encoding'] = 'gzip, deflate'
..headers['User-Agent'] = ..headers['User-Agent'] = url.contains('twitter.com')
'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Mobile Safari/537.36' ? 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
: 'Mozilla/5.0'
..headers['cache-control'] = 'no-cache' ..headers['cache-control'] = 'no-cache'
..headers['accept'] = ..headers['accept'] =
'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'; 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9';
// print(request.headers);
final IOStreamedResponse stream = final IOStreamedResponse stream =
await client.send(request).catchError((dynamic err) { await client.send(request).catchError((dynamic err) {
//print('Error in getting the link => ${request.url}'); // locator.get<Logger>().log(
//print('Error => $err'); // Level.error,
// 'Error in getting the link => ${request.url}\n$err',
// );
}); });
if (stream.statusCode == HttpStatus.movedTemporarily || if (stream.statusCode == HttpStatus.movedTemporarily ||
stream.statusCode == HttpStatus.movedPermanently) { stream.statusCode == HttpStatus.movedPermanently) {
if (stream.isRedirect && count < 6) { if (stream.isRedirect && count < 6) {
@ -240,7 +298,6 @@ class WebAnalyzer {
} }
count++; count++;
client.close(); client.close();
// print("Redirect ====> $url");
return _requestUrl(url, count: count, cookie: cookie); return _requestUrl(url, count: count, cookie: cookie);
} }
} else if (stream.statusCode == HttpStatus.ok) { } else if (stream.statusCode == HttpStatus.ok) {
@ -257,7 +314,6 @@ class WebAnalyzer {
} }
} }
client.close(); client.close();
//if (res == null) print('Get web info empty($url)');
return res; return res;
} }
@ -274,28 +330,22 @@ class WebAnalyzer {
String temp = html.replaceAll(r'\', ''); String temp = html.replaceAll(r'\', '');
temp = temp.replaceAll('u003C', '<'); temp = temp.replaceAll('u003C', '<');
temp = temp.replaceAll('u003E', '>'); temp = temp.replaceAll('u003E', '>');
// print(temp);
} else {
// print(html);
} }
} catch (e) { } catch (e) {
try { try {
html = gbk.decode(response.bodyBytes); html = gbk.decode(response.bodyBytes);
} catch (e) { } catch (e) {
//print('Web page resolution failure from:$url Error:$e'); // locator.get<Logger>().log(
// Level.error,
// 'Web page resolution failure from:$url Error:$e',
// );
} }
} }
if (html == null) { if (html == null) return null;
//print('Web page resolution failure from:$url');
return null;
}
// Improved performance
// final start = DateTime.now();
final String headHtml = _getHeadHtml(html); final String headHtml = _getHeadHtml(html);
final Document document = parser.parse(headHtml); final Document document = parser.parse(headHtml);
// print("dom cost ${DateTime.now().difference(start).inMilliseconds}");
final Uri uri = Uri.parse(url); final Uri uri = Uri.parse(url);
// get image or video // get image or video
@ -360,6 +410,7 @@ class WebAnalyzer {
static String _analyzeTitle(Document document, {bool isTwitter = false}) { static String _analyzeTitle(Document document, {bool isTwitter = false}) {
if (isTwitter) return ''; if (isTwitter) return '';
final String? title = _getMetaContent(document, 'property', 'og:title'); final String? title = _getMetaContent(document, 'property', 'og:title');
if (title != null) return title; if (title != null) return title;
final List<Element> list = document.head!.getElementsByTagName('title'); final List<Element> list = document.head!.getElementsByTagName('title');
if (list.isNotEmpty) { if (list.isNotEmpty) {
@ -379,14 +430,12 @@ class WebAnalyzer {
_getMetaContent(document, 'name', 'description') ?? _getMetaContent(document, 'name', 'description') ??
_getMetaContent(document, 'name', 'Description'); _getMetaContent(document, 'name', 'Description');
if (!isNotEmpty(description)) { if (isEmpty(description)) {
// final DateTime start = DateTime.now();
String body = html.replaceAll(_htmlReg, ''); String body = html.replaceAll(_htmlReg, '');
body = body.trim().replaceAll(_lineReg, ' ').replaceAll(_spaceReg, ' '); body = body.trim().replaceAll(_lineReg, ' ').replaceAll(_spaceReg, ' ');
if (body.length > 300) { if (body.length > 300) {
body = body.substring(0, 300); body = body.substring(0, 300);
} }
// print("html cost ${DateTime.now().difference(start).inMilliseconds}");
if (body.contains('JavaScript is disabled in your browser')) return ''; if (body.contains('JavaScript is disabled in your browser')) return '';
return body; return body;
} }

View File

@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hacki/blocs/blocs.dart'; import 'package:hacki/blocs/blocs.dart';
import 'package:hacki/cubits/cubits.dart'; import 'package:hacki/cubits/cubits.dart';
import 'package:hacki/screens/widgets/link_preview/web_analyzer.dart';
class OfflineBanner extends StatelessWidget { class OfflineBanner extends StatelessWidget {
const OfflineBanner({ const OfflineBanner({
@ -57,6 +58,7 @@ class OfflineBanner extends StatelessWidget {
context.read<StoriesBloc>().add(StoriesExitOffline()); context.read<StoriesBloc>().add(StoriesExitOffline());
context.read<AuthBloc>().add(AuthInitialize()); context.read<AuthBloc>().add(AuthInitialize());
context.read<PinCubit>().init(); context.read<PinCubit>().init();
WebAnalyzer.cacheMap.clear();
} }
}); });
}, },

View File

@ -40,7 +40,8 @@ class _StoriesListViewState extends State<StoriesListView> {
return BlocBuilder<PreferenceCubit, PreferenceState>( return BlocBuilder<PreferenceCubit, PreferenceState>(
buildWhen: (PreferenceState previous, PreferenceState current) => buildWhen: (PreferenceState previous, PreferenceState current) =>
previous.showComplexStoryTile != current.showComplexStoryTile, previous.showComplexStoryTile != current.showComplexStoryTile ||
previous.showMetadata != current.showMetadata,
builder: (BuildContext context, PreferenceState preferenceState) { builder: (BuildContext context, PreferenceState preferenceState) {
return BlocConsumer<StoriesBloc, StoriesState>( return BlocConsumer<StoriesBloc, StoriesState>(
listenWhen: (StoriesState previous, StoriesState current) => listenWhen: (StoriesState previous, StoriesState current) =>
@ -66,6 +67,7 @@ class _StoriesListViewState extends State<StoriesListView> {
markReadStories: markReadStories:
context.read<PreferenceCubit>().state.markReadStories, context.read<PreferenceCubit>().state.markReadStories,
showWebPreview: preferenceState.showComplexStoryTile, showWebPreview: preferenceState.showComplexStoryTile,
showMetadata: preferenceState.showMetadata,
refreshController: refreshController, refreshController: refreshController,
items: state.storiesByType[storyType]!, items: state.storiesByType[storyType]!,
onRefresh: () { onRefresh: () {
@ -73,6 +75,7 @@ class _StoriesListViewState extends State<StoriesListView> {
context context
.read<StoriesBloc>() .read<StoriesBloc>()
.add(StoriesRefresh(type: storyType)); .add(StoriesRefresh(type: storyType));
context.read<PinCubit>().refresh();
}, },
onLoadMore: () { onLoadMore: () {
context context

View File

@ -1,12 +1,8 @@
import 'dart:io';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_fadein/flutter_fadein.dart'; import 'package:flutter_fadein/flutter_fadein.dart';
import 'package:hacki/config/constants.dart'; import 'package:hacki/config/constants.dart';
import 'package:hacki/models/models.dart'; import 'package:hacki/models/models.dart';
import 'package:hacki/screens/widgets/link_preview/link_view.dart';
import 'package:hacki/screens/widgets/widgets.dart'; import 'package:hacki/screens/widgets/widgets.dart';
import 'package:html/parser.dart';
import 'package:shimmer/shimmer.dart'; import 'package:shimmer/shimmer.dart';
class StoryTile extends StatelessWidget { class StoryTile extends StatelessWidget {
@ -14,12 +10,14 @@ class StoryTile extends StatelessWidget {
super.key, super.key,
this.hasRead = false, this.hasRead = false,
required this.showWebPreview, required this.showWebPreview,
required this.showMetadata,
required this.story, required this.story,
required this.onTap, required this.onTap,
this.simpleTileFontSize = 16, this.simpleTileFontSize = 16,
}); });
final bool showWebPreview; final bool showWebPreview;
final bool showMetadata;
final bool hasRead; final bool hasRead;
final Story story; final Story story;
final VoidCallback onTap; final VoidCallback onTap;
@ -30,142 +28,112 @@ class StoryTile extends StatelessWidget {
if (showWebPreview) { if (showWebPreview) {
final double screenWidth = MediaQuery.of(context).size.width; final double screenWidth = MediaQuery.of(context).size.width;
final bool showSmallerPreviewPic = final bool showSmallerPreviewPic =
Platform.isIOS && screenWidth > 428.0 && screenWidth < 850; screenWidth > 428.0 && screenWidth < 850;
final double height = showSmallerPreviewPic final double height = showSmallerPreviewPic
? 100.0 ? 100.0
: (MediaQuery.of(context).size.height * 0.14).clamp(118.0, 140.0); : (MediaQuery.of(context).size.height * 0.14).clamp(118.0, 140.0);
if (story.url.isNotEmpty) { return TapDownWrapper(
return TapDownWrapper( onTap: onTap,
onTap: onTap, child: Padding(
child: Padding( padding: const EdgeInsets.symmetric(
padding: const EdgeInsets.symmetric( horizontal: 12,
horizontal: 12, ),
), child: AbsorbPointer(
child: AbsorbPointer( child: LinkPreview(
child: LinkPreview( story: story,
link: story.url.isNotEmpty ? story.url : 's', link: story.url,
placeholderWidget: FadeIn( placeholderWidget: FadeIn(
child: SizedBox( child: SizedBox(
height: height, height: height,
child: Shimmer.fromColors( child: Shimmer.fromColors(
baseColor: Colors.orange, baseColor: Colors.orange,
highlightColor: Colors.orangeAccent, highlightColor: Colors.orangeAccent,
child: Row( child: Row(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[ children: <Widget>[
Padding( Padding(
padding: const EdgeInsets.only( padding: const EdgeInsets.only(
right: 5, right: 5,
bottom: 5, bottom: 5,
top: 5, top: 5,
), ),
child: Container( child: Container(
height: height, height: height,
width: height, width: height,
color: Colors.white, color: Colors.white,
),
),
Expanded(
flex: 4,
child: Padding(
padding: const EdgeInsets.only(left: 4, top: 6),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
width: double.infinity,
height: 14,
color: Colors.white,
),
const Padding(
padding: EdgeInsets.symmetric(vertical: 4),
),
Container(
width: double.infinity,
height: 10,
color: Colors.white,
),
const Padding(
padding: EdgeInsets.symmetric(vertical: 3),
),
Container(
width: double.infinity,
height: 10,
color: Colors.white,
),
const Padding(
padding: EdgeInsets.symmetric(vertical: 3),
),
Container(
width: double.infinity,
height: 10,
color: Colors.white,
),
const Padding(
padding: EdgeInsets.symmetric(vertical: 3),
),
Container(
width: 40,
height: 10,
color: Colors.white,
),
],
), ),
), ),
Expanded( )
flex: 4, ],
child: Padding(
padding: const EdgeInsets.only(left: 4, top: 6),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
width: double.infinity,
height: 14,
color: Colors.white,
),
const Padding(
padding: EdgeInsets.symmetric(vertical: 4),
),
Container(
width: double.infinity,
height: 10,
color: Colors.white,
),
const Padding(
padding: EdgeInsets.symmetric(vertical: 3),
),
Container(
width: double.infinity,
height: 10,
color: Colors.white,
),
const Padding(
padding: EdgeInsets.symmetric(vertical: 3),
),
Container(
width: double.infinity,
height: 10,
color: Colors.white,
),
const Padding(
padding: EdgeInsets.symmetric(vertical: 3),
),
Container(
width: 40,
height: 10,
color: Colors.white,
),
],
),
),
)
],
),
), ),
), ),
), ),
errorImage: Constants.hackerNewsLogoLink,
backgroundColor: Colors.transparent,
borderRadius: 0,
removeElevation: true,
bodyMaxLines: height == 100 ? 3 : 4,
errorTitle: story.title,
titleStyle: TextStyle(
color: hasRead
? Colors.grey[500]
: Theme.of(context).textTheme.subtitle1!.color,
fontWeight: FontWeight.bold,
),
), ),
errorImage: Constants.hackerNewsLogoLink,
backgroundColor: Colors.transparent,
borderRadius: 0,
removeElevation: true,
bodyMaxLines: height == 100 ? 3 : 4,
errorTitle: story.title,
titleStyle: TextStyle(
color: hasRead
? Colors.grey[500]
: Theme.of(context).textTheme.subtitle1!.color,
fontWeight: FontWeight.bold,
),
showMetadata: showMetadata,
), ),
), ),
); ),
} else { );
final String text = parse(story.text).body?.text ?? '';
return TapDownWrapper(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 12,
),
child: AbsorbPointer(
child: SizedBox(
height: height,
child: LinkView(
title: story.title,
description: text,
onTap: (_) {},
url: '',
imagePath: Constants.hackerNewsLogoPath,
bodyMaxLines: height == 100 ? 3 : 4,
titleTextStyle: TextStyle(
color: hasRead
? Colors.grey[500]
: Theme.of(context).textTheme.subtitle1!.color,
fontWeight: FontWeight.bold,
),
),
),
),
),
);
}
} else { } else {
return InkWell( return InkWell(
onTap: onTap, onTap: onTap,
@ -190,6 +158,21 @@ class StoryTile extends StatelessWidget {
), ),
], ],
), ),
if (showMetadata)
Row(
children: <Widget>[
Expanded(
child: Text(
story.metadata,
style: TextStyle(
color: Colors.grey,
fontSize: simpleTileFontSize - 2,
),
maxLines: 1,
),
),
],
),
const SizedBox( const SizedBox(
height: 8, height: 8,
), ),

View File

@ -2,9 +2,7 @@ import 'package:html/dom.dart' as dom;
import 'package:html/parser.dart' as parser; import 'package:html/parser.dart' as parser;
import 'package:html_unescape/html_unescape.dart'; import 'package:html_unescape/html_unescape.dart';
class HtmlUtil { abstract class HtmlUtil {
const HtmlUtil._();
static String? getTitle(dynamic input) => static String? getTitle(dynamic input) =>
parser.parse(input).head?.querySelector('title')?.text; parser.parse(input).head?.querySelector('title')?.text;

View File

@ -2,13 +2,13 @@ import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:url_launcher/url_launcher.dart'; import 'package:url_launcher/url_launcher.dart';
class LinkUtil { abstract class LinkUtil {
static final ChromeSafariBrowser _browser = ChromeSafariBrowser(); static final ChromeSafariBrowser _browser = ChromeSafariBrowser();
static void launchUrl(String link, {bool useReader = false}) { static void launch(String link, {bool useReader = false}) {
Uri rinseLink(String link) { Uri rinseLink(String link) {
if (link.contains(')')) { final RegExp regex = RegExp(r'\)|].*$');
final RegExp regex = RegExp(r'\).*$'); if (!link.contains('en.wikipedia.org') && link.contains(regex)) {
final String match = regex.stringMatch(link) ?? ''; final String match = regex.stringMatch(link) ?? '';
return Uri.parse(link.replaceAll(match, '')); return Uri.parse(link.replaceAll(match, ''));
} }
@ -19,15 +19,21 @@ class LinkUtil {
final Uri uri = rinseLink(link); final Uri uri = rinseLink(link);
canLaunchUrl(uri).then((bool val) { canLaunchUrl(uri).then((bool val) {
if (val) { if (val) {
_browser.open( if (link.contains('http')) {
url: uri, _browser
options: ChromeSafariBrowserClassOptions( .open(
ios: IOSSafariOptions( url: uri,
entersReaderIfAvailable: useReader, options: ChromeSafariBrowserClassOptions(
preferredControlTintColor: Colors.orange, ios: IOSSafariOptions(
), entersReaderIfAvailable: useReader,
), preferredControlTintColor: Colors.orange,
); ),
),
)
.onError((_, __) => launchUrl(uri));
} else {
launchUrl(uri);
}
} }
}); });
} }

View File

@ -1,6 +1,6 @@
name: hacki name: hacki
description: A Hacker News reader. description: A Hacker News reader.
version: 0.2.8+44 version: 0.2.13+52
publish_to: none publish_to: none
environment: environment:
@ -12,7 +12,7 @@ dependencies:
bloc: ^8.0.3 bloc: ^8.0.3
cached_network_image: ^3.2.1 cached_network_image: ^3.2.1
clipboard: ^0.1.3 clipboard: ^0.1.3
collection: collection: ^1.16.0
connectivity_plus: ^2.2.1 connectivity_plus: ^2.2.1
dio: ^4.0.4 dio: ^4.0.4
equatable: 2.0.3 equatable: 2.0.3