Compare commits

...

71 Commits

Author SHA1 Message Date
f572f5b462 🚀 Launch 3.5.0+164 2026-01-17 23:36:09 +08:00
a02f2fe3c6 🐛 Fix iOS 2026-01-17 23:36:03 +08:00
bc4fddc164 💄 Optimize post detail 2026-01-17 22:33:27 +08:00
3d7e7951a2 💄 Localizable file list 2026-01-17 22:31:51 +08:00
41df5f3907 🐛 Fix bugs in file list 2026-01-17 22:04:20 +08:00
6487a1ff65 💄 Lift file list search to appbar 2026-01-17 21:58:27 +08:00
2e90d243de 💄 Optimize file list UI 2026-01-17 21:38:35 +08:00
LittleSheep
1eca95fa78 🔀 Merge pull request #237 from BluewhaleYF/v3
改进文言界面翻译
2026-01-17 21:05:48 +08:00
Flint Scophire
96b87f75f9 Add files via upload
改进文言界面翻译
2026-01-17 18:02:25 +08:00
e832f3fd93 🐛 Fix dashboard customize issue 2026-01-17 16:04:18 +08:00
aeea90226a 🐛 Fix some bugs in dashboard 2026-01-17 16:02:56 +08:00
c36a5eaa73 💄 Optimize compose toolbar styling 2026-01-17 15:51:45 +08:00
6840054a41 💄 Better dashboard customization 2026-01-17 15:51:34 +08:00
6a0f351114 💄 Customizable dashboard 2026-01-17 15:32:08 +08:00
c5d667ecf3 💄 Optimize the article editor 2026-01-17 14:50:16 +08:00
09767e113f 💄 Better article editor 2026-01-17 14:42:45 +08:00
9ca5c63afd :drunk: Messing around werid stuff 2026-01-17 02:05:24 +08:00
fd3c08e054 🍱 Localized app intents 2026-01-16 21:30:59 +08:00
72f23a504e ⬆️ Upgrade dependecies
 Remove some unused deps
2026-01-16 21:21:51 +08:00
4898825124 ♻️ Use fully native implmentation of app intents on iOS 2026-01-16 21:17:44 +08:00
387d19d85c 🚀 Launch 3.5.0+163 (SNAPSHOT) 2026-01-16 01:50:27 +08:00
f7b991663f Render post article thumbnail 2026-01-16 01:44:41 +08:00
3a57f4265b Editing article thumbnail 2026-01-16 01:30:46 +08:00
d1ee2e5160 💄 Optimize the notification overlay styling 2026-01-16 00:56:57 +08:00
bcd6753ed2 💄 Updating compose toolbar styling 2026-01-16 00:47:32 +08:00
321ea4458b 💄 Optimize the notification overlays 2026-01-16 00:21:07 +08:00
8ad31dad58 Notification stacks on the mobile 2026-01-16 00:08:56 +08:00
269c17d068 💄 The sfx can be played multiple times 2026-01-15 23:05:39 +08:00
a9abd777e1 💫 Better notification overlay animation 2026-01-15 23:02:21 +08:00
e24b1fc135 💫 Optimize the notification animation 2026-01-15 19:34:03 +08:00
d5feea52fa 💄 Optimize notification item 2026-01-15 19:31:11 +08:00
491252bba9 💫 Optimize the overlay animation of notifications 2026-01-15 01:39:48 +08:00
4f569fbefd ♻️ New notification overlay basis 2026-01-15 01:31:09 +08:00
476da28b5e ♻️ Improved new notifcation style 2026-01-15 01:04:15 +08:00
d639df7623 ♻️ Optimize the sfx playing 2026-01-15 00:44:38 +08:00
e1fc5311d2 🐛 Fix some bugs 2026-01-15 00:09:41 +08:00
d0e4fde6c2 🐛 Added some platform checks 2026-01-14 22:50:06 +08:00
9437339b0f 💄 Give name for pasted image 2026-01-14 22:40:10 +08:00
dd7696132c 👽 Authorized audio, video access 2026-01-14 22:34:17 +08:00
95daa3c28d 💄 Use unlimited variant of the fortune card, close #234 2026-01-14 01:53:24 +08:00
ac5193e1f6 🐛 Fix webfeed issues, close #235 2026-01-14 01:49:27 +08:00
0328a7736a Optimize retry logic 2026-01-14 01:06:34 +08:00
03b332f677 🐛 Adjust analytics service initialization 2026-01-14 00:56:28 +08:00
91b2797fb9 👽 Authorized image load request
💄 Optimize image styling
2026-01-13 23:15:36 +08:00
b66640c6df 🚀 Launch 3.5.0+162 2026-01-12 01:13:55 +08:00
4ac10706ae iOS push notification custom sound 2026-01-12 01:08:52 +08:00
bf2844162d 💄 Optimize post detail layout 2026-01-12 01:04:03 +08:00
23c11a2fbd 🗑️ Remove the file references 2026-01-12 00:25:19 +08:00
2b99f54bc5 🐛 Fix upload task 2026-01-12 00:22:28 +08:00
ab2fc1013b 💄 Scrollable alert 2026-01-12 00:08:51 +08:00
LittleSheep
9a41ff26ef 🔀 Merge pull request #228 from Texas0295/v3
[FIX] linux: defer AnalyticsService init to avoid Firebase crash
2026-01-11 23:49:05 +08:00
63a55658ab Sound effects on notifications 2026-01-11 23:32:00 +08:00
Texas0295
3122ae4cc2 [FIX] linux: defer AnalyticsService init to avoid Firebase crash
Defer FirebaseAnalytics initialization to constructor to avoid crashes on
unsupported platforms (notably Linux). Replace class-level initialization
with nullable field and guarded calls.

Changes:
- remove class-level initialization of _analytics
- add private _init() invoked in constructor
- make _analytics nullable
- add null checks in logEvent() and setUserId()
- emit warning instead of throwing
- Linux builds no longer crash on startup

Signed-off-by: Texas0295 <kimura@texas0295.top>
2026-01-11 20:31:27 +08:00
00e063e99f 🐛 Dozens of bug fixes 2026-01-11 18:41:05 +08:00
532bb30c6a Sfx on notification 2026-01-11 18:32:23 +08:00
d8c33b576f Attachment video preview 2026-01-11 16:56:41 +08:00
a984cba2fa 💫 Animated attachment preview progress bar 2026-01-11 13:42:55 +08:00
b7d5aa5dfb Better attachment preview progress 2026-01-11 13:40:35 +08:00
826238a374 💄 Optimize task overlay 2026-01-11 13:22:13 +08:00
88c4d648d5 ♻️ Better task overlay progress 2026-01-11 13:11:15 +08:00
bf59108569 🐛 Add well defined mounted check in messages notifier 2026-01-11 12:53:57 +08:00
eec181da55 💄 Optimize task overlay styles 2026-01-11 02:48:44 +08:00
c93b543da9 💄 Animated image gates 2026-01-10 23:20:16 +08:00
2fd93246c7 💄 Improve the image don't animated the opacity if cached 2026-01-10 23:02:31 +08:00
1b2620e957 💫 Optimize the chat message animation and performance 2026-01-10 22:56:08 +08:00
d443343052 🐛 Fix serval issues in past commits 2026-01-10 22:23:42 +08:00
9957905212 ⬆️ Upgrade dependecies 2026-01-10 21:21:31 +08:00
e36d694397 💫 Optimize the chat room animation 2026-01-10 16:10:55 +08:00
3847581f1f ♻️ Decouple the room.dart 2026-01-10 14:18:59 +08:00
64903bf1f3 📈 Tracking data's analytics service 2026-01-10 13:43:31 +08:00
a449fbb58a More app intents available on iOS 2026-01-10 13:06:09 +08:00
108 changed files with 9632 additions and 5531 deletions

BIN
assets/audio/messages.mp3 Normal file

Binary file not shown.

Binary file not shown.

View File

@@ -1360,6 +1360,32 @@
"orCreateWith": "Or\ncreate with", "orCreateWith": "Or\ncreate with",
"unindexedFiles": "Unindexed files", "unindexedFiles": "Unindexed files",
"folder": "Folder", "folder": "Folder",
"rootDirectory": "Root Directory",
"pathSeparator": " / ",
"selectAll": "Select All",
"deselectAll": "Deselect All",
"createDirectory": "Create Directory",
"thisDirectoryIsEmpty": "This directory is empty",
"emptyDirectoryHint": "Upload files or create subdirectories to populate this path.\nDirectories are created implicitly when you upload files to them.",
"noUnindexedFiles": "No unindexed files",
"noUnindexedFilesHint": "All files have been assigned to paths.\nFiles without paths will appear here.",
"clearAllRecycledFiles": "Clear All Recycled Files",
"clearRecycledFilesDescription": "Permanently delete all marked recycled files to free up space.",
"allFiles": "All files",
"confirmDeleteSelectedFiles": "Are you sure you want to delete the selected files?",
"deleteSelectedFiles": "Delete Selected Files",
"confirmClearRecycledFiles": "Are you sure you want to clear all recycled files?",
"clearRecycledFiles": "Clear Recycled Files",
"failedToUploadFile": "Failed to upload file: {}",
"deletedFilesCount": "Deleted {} files.",
"failedToDeleteSelectedFiles": "Failed to delete selected files.",
"clearedRecycledFilesCount": "Cleared {} recycled files.",
"failedToClearRecycledFiles": "Failed to clear recycled files.",
"root": "Root",
"searchFiles": "Search files...",
"selectedCount": "{} selected",
"filesSelected": "{} files selected",
"fileSelected": "{} file selected",
"clearCompleted": "Clear Completed", "clearCompleted": "Clear Completed",
"uploadSuccess": "Upload successful!", "uploadSuccess": "Upload successful!",
"wouldYouLikeToViewFile": "Would you like to view the file?", "wouldYouLikeToViewFile": "Would you like to view the file?",
@@ -1587,5 +1613,44 @@
"fediversePostDescribe": "Post from the Fediverse Network", "fediversePostDescribe": "Post from the Fediverse Network",
"settingsShowFediverseContent": "Show Fediverse Content", "settingsShowFediverseContent": "Show Fediverse Content",
"universalSearch": "Universal Search", "universalSearch": "Universal Search",
"universalSearchDescription": "Search content across the Solar Network and the fediverse network." "universalSearchDescription": "Search content across the Solar Network and the fediverse network.",
"tasks": "Tasks",
"tasksCount": {
"one": "{} task",
"other": "{} tasks"
},
"setAsThumbnail": "Set as thumbnail",
"unsetAsThumbnail": "Unset as thumbnail",
"sidebar": "Sidebar",
"dropFilesHere": "Drop your files here",
"dragAndDropToAttach": "Drag your files here to attach it",
"customize": "Customize",
"dashboardCustomizeTitle": "Customize Dashboard",
"dashboardTabVertical": "Vertical",
"dashboardTabHorizontal": "Horizontal",
"dashboardLayoutVertical": "Vertical Layout",
"dashboardLayoutHorizontal": "Horizontal Layout",
"dashboardAvailableCards": "Available Cards",
"dashboardDisplaySettings": "Display Settings",
"dashboardShowSearchBar": "Show Search Bar",
"dashboardShowClockAndCountdown": "Show Clock and Countdown",
"dashboardResetToDefaults": "Reset to Defaults",
"dashboardResetToDefaultsSubtitle": "Restore default dashboard layout and settings",
"dashboardResetConfirmMessage": "This will restore the dashboard to its default layout and settings. This action cannot be undone.",
"dashboardResetConfirmTitle": "Reset Dashboard",
"dashboardCardCheckIn": "Check In",
"dashboardCardFortuneGraph": "Fortune Graph",
"dashboardCardFortune": "Fortune",
"dashboardCardFeaturedPosts": "Featured Posts",
"dashboardCardFriends": "Friends",
"dashboardCardNotifications": "Notifications",
"dashboardCardChats": "Chats",
"dashboardCardActivityColumn": "Activity Column",
"dashboardCardPostsColumn": "Posts Column",
"dashboardCardSocialColumn": "Social Column",
"dashboardCardChatsColumn": "Chats Column",
"dashboardCardActivityColumnDescription": "Check In, Fortune Graph & Fortune",
"dashboardCardPostsColumnDescription": "Featured Posts",
"dashboardCardSocialColumnDescription": "Friends & Notifications",
"dashboardCardChatsColumnDescription": "Recent Chats"
} }

File diff suppressed because it is too large Load Diff

Binary file not shown.

View File

@@ -1,5 +1,7 @@
PODS: PODS:
- Alamofire (5.11.0) - Alamofire (5.11.0)
- audio_session (0.0.1):
- Flutter
- connectivity_plus (0.0.1): - connectivity_plus (0.0.1):
- Flutter - Flutter
- croppy (0.0.1): - croppy (0.0.1):
@@ -125,8 +127,6 @@ PODS:
- nanopb (~> 3.30910.0) - nanopb (~> 3.30910.0)
- PromisesSwift (~> 2.1) - PromisesSwift (~> 2.1)
- Flutter (1.0.0) - Flutter (1.0.0)
- flutter_app_intents (0.1.0):
- Flutter
- flutter_app_update (0.0.1): - flutter_app_update (0.0.1):
- Flutter - Flutter
- flutter_inappwebview_ios (0.0.1): - flutter_inappwebview_ios (0.0.1):
@@ -219,6 +219,9 @@ PODS:
- Flutter - Flutter
- irondash_engine_context (0.0.1): - irondash_engine_context (0.0.1):
- Flutter - Flutter
- just_audio (0.0.1):
- Flutter
- FlutterMacOS
- KeychainAccess (4.2.2) - KeychainAccess (4.2.2)
- Kingfisher (8.6.2) - Kingfisher (8.6.2)
- KingfisherWebP (1.7.2): - KingfisherWebP (1.7.2):
@@ -259,9 +262,6 @@ PODS:
- Flutter - Flutter
- pasteboard (0.0.1): - pasteboard (0.0.1):
- Flutter - Flutter
- path_provider_foundation (0.0.1):
- Flutter
- FlutterMacOS
- permission_handler_apple (9.3.0): - permission_handler_apple (9.3.0):
- Flutter - Flutter
- pointer_interceptor_ios (0.0.1): - pointer_interceptor_ios (0.0.1):
@@ -324,12 +324,16 @@ PODS:
- Flutter - Flutter
- url_launcher_ios (0.0.1): - url_launcher_ios (0.0.1):
- Flutter - Flutter
- video_thumbnail (0.0.1):
- Flutter
- libwebp
- wakelock_plus (0.0.1): - wakelock_plus (0.0.1):
- Flutter - Flutter
- WebRTC-SDK (137.7151.04) - WebRTC-SDK (137.7151.04)
DEPENDENCIES: DEPENDENCIES:
- Alamofire - Alamofire
- audio_session (from `.symlinks/plugins/audio_session/ios`)
- connectivity_plus (from `.symlinks/plugins/connectivity_plus/ios`) - connectivity_plus (from `.symlinks/plugins/connectivity_plus/ios`)
- croppy (from `.symlinks/plugins/croppy/ios`) - croppy (from `.symlinks/plugins/croppy/ios`)
- device_info_plus (from `.symlinks/plugins/device_info_plus/ios`) - device_info_plus (from `.symlinks/plugins/device_info_plus/ios`)
@@ -340,7 +344,6 @@ DEPENDENCIES:
- firebase_crashlytics (from `.symlinks/plugins/firebase_crashlytics/ios`) - firebase_crashlytics (from `.symlinks/plugins/firebase_crashlytics/ios`)
- firebase_messaging (from `.symlinks/plugins/firebase_messaging/ios`) - firebase_messaging (from `.symlinks/plugins/firebase_messaging/ios`)
- Flutter (from `Flutter`) - Flutter (from `Flutter`)
- flutter_app_intents (from `.symlinks/plugins/flutter_app_intents/ios`)
- flutter_app_update (from `.symlinks/plugins/flutter_app_update/ios`) - flutter_app_update (from `.symlinks/plugins/flutter_app_update/ios`)
- flutter_inappwebview_ios (from `.symlinks/plugins/flutter_inappwebview_ios/ios`) - flutter_inappwebview_ios (from `.symlinks/plugins/flutter_inappwebview_ios/ios`)
- flutter_keyboard_visibility (from `.symlinks/plugins/flutter_keyboard_visibility/ios`) - flutter_keyboard_visibility (from `.symlinks/plugins/flutter_keyboard_visibility/ios`)
@@ -354,6 +357,7 @@ DEPENDENCIES:
- image_picker_ios (from `.symlinks/plugins/image_picker_ios/ios`) - image_picker_ios (from `.symlinks/plugins/image_picker_ios/ios`)
- in_app_review (from `.symlinks/plugins/in_app_review/ios`) - in_app_review (from `.symlinks/plugins/in_app_review/ios`)
- irondash_engine_context (from `.symlinks/plugins/irondash_engine_context/ios`) - irondash_engine_context (from `.symlinks/plugins/irondash_engine_context/ios`)
- just_audio (from `.symlinks/plugins/just_audio/darwin`)
- Kingfisher (~> 8.0) - Kingfisher (~> 8.0)
- KingfisherWebP - KingfisherWebP
- livekit_client (from `.symlinks/plugins/livekit_client/ios`) - livekit_client (from `.symlinks/plugins/livekit_client/ios`)
@@ -363,7 +367,6 @@ DEPENDENCIES:
- native_exif (from `.symlinks/plugins/native_exif/ios`) - native_exif (from `.symlinks/plugins/native_exif/ios`)
- package_info_plus (from `.symlinks/plugins/package_info_plus/ios`) - package_info_plus (from `.symlinks/plugins/package_info_plus/ios`)
- pasteboard (from `.symlinks/plugins/pasteboard/ios`) - pasteboard (from `.symlinks/plugins/pasteboard/ios`)
- path_provider_foundation (from `.symlinks/plugins/path_provider_foundation/darwin`)
- permission_handler_apple (from `.symlinks/plugins/permission_handler_apple/ios`) - permission_handler_apple (from `.symlinks/plugins/permission_handler_apple/ios`)
- pointer_interceptor_ios (from `.symlinks/plugins/pointer_interceptor_ios/ios`) - pointer_interceptor_ios (from `.symlinks/plugins/pointer_interceptor_ios/ios`)
- protocol_handler_ios (from `.symlinks/plugins/protocol_handler_ios/ios`) - protocol_handler_ios (from `.symlinks/plugins/protocol_handler_ios/ios`)
@@ -379,6 +382,7 @@ DEPENDENCIES:
- super_native_extensions (from `.symlinks/plugins/super_native_extensions/ios`) - super_native_extensions (from `.symlinks/plugins/super_native_extensions/ios`)
- syncfusion_flutter_pdfviewer (from `.symlinks/plugins/syncfusion_flutter_pdfviewer/ios`) - syncfusion_flutter_pdfviewer (from `.symlinks/plugins/syncfusion_flutter_pdfviewer/ios`)
- url_launcher_ios (from `.symlinks/plugins/url_launcher_ios/ios`) - url_launcher_ios (from `.symlinks/plugins/url_launcher_ios/ios`)
- video_thumbnail (from `.symlinks/plugins/video_thumbnail/ios`)
- wakelock_plus (from `.symlinks/plugins/wakelock_plus/ios`) - wakelock_plus (from `.symlinks/plugins/wakelock_plus/ios`)
SPEC REPOS: SPEC REPOS:
@@ -414,6 +418,8 @@ SPEC REPOS:
- WebRTC-SDK - WebRTC-SDK
EXTERNAL SOURCES: EXTERNAL SOURCES:
audio_session:
:path: ".symlinks/plugins/audio_session/ios"
connectivity_plus: connectivity_plus:
:path: ".symlinks/plugins/connectivity_plus/ios" :path: ".symlinks/plugins/connectivity_plus/ios"
croppy: croppy:
@@ -434,8 +440,6 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/firebase_messaging/ios" :path: ".symlinks/plugins/firebase_messaging/ios"
Flutter: Flutter:
:path: Flutter :path: Flutter
flutter_app_intents:
:path: ".symlinks/plugins/flutter_app_intents/ios"
flutter_app_update: flutter_app_update:
:path: ".symlinks/plugins/flutter_app_update/ios" :path: ".symlinks/plugins/flutter_app_update/ios"
flutter_inappwebview_ios: flutter_inappwebview_ios:
@@ -462,6 +466,8 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/in_app_review/ios" :path: ".symlinks/plugins/in_app_review/ios"
irondash_engine_context: irondash_engine_context:
:path: ".symlinks/plugins/irondash_engine_context/ios" :path: ".symlinks/plugins/irondash_engine_context/ios"
just_audio:
:path: ".symlinks/plugins/just_audio/darwin"
livekit_client: livekit_client:
:path: ".symlinks/plugins/livekit_client/ios" :path: ".symlinks/plugins/livekit_client/ios"
local_auth_darwin: local_auth_darwin:
@@ -476,8 +482,6 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/package_info_plus/ios" :path: ".symlinks/plugins/package_info_plus/ios"
pasteboard: pasteboard:
:path: ".symlinks/plugins/pasteboard/ios" :path: ".symlinks/plugins/pasteboard/ios"
path_provider_foundation:
:path: ".symlinks/plugins/path_provider_foundation/darwin"
permission_handler_apple: permission_handler_apple:
:path: ".symlinks/plugins/permission_handler_apple/ios" :path: ".symlinks/plugins/permission_handler_apple/ios"
pointer_interceptor_ios: pointer_interceptor_ios:
@@ -508,11 +512,14 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/syncfusion_flutter_pdfviewer/ios" :path: ".symlinks/plugins/syncfusion_flutter_pdfviewer/ios"
url_launcher_ios: url_launcher_ios:
:path: ".symlinks/plugins/url_launcher_ios/ios" :path: ".symlinks/plugins/url_launcher_ios/ios"
video_thumbnail:
:path: ".symlinks/plugins/video_thumbnail/ios"
wakelock_plus: wakelock_plus:
:path: ".symlinks/plugins/wakelock_plus/ios" :path: ".symlinks/plugins/wakelock_plus/ios"
SPEC CHECKSUMS: SPEC CHECKSUMS:
Alamofire: bd5e7b23a1a750975288482c1831d71e74415f86 Alamofire: bd5e7b23a1a750975288482c1831d71e74415f86
audio_session: 9bb7f6c970f21241b19f5a3658097ae459681ba0
connectivity_plus: cb623214f4e1f6ef8fe7403d580fdad517d2f7dd connectivity_plus: cb623214f4e1f6ef8fe7403d580fdad517d2f7dd
croppy: 979e8ddc254f4642bffe7d52dc7193354b27ba30 croppy: 979e8ddc254f4642bffe7d52dc7193354b27ba30
device_info_plus: 21fcca2080fbcd348be798aa36c3e5ed849eefbe device_info_plus: 21fcca2080fbcd348be798aa36c3e5ed849eefbe
@@ -535,7 +542,6 @@ SPEC CHECKSUMS:
FirebaseRemoteConfigInterop: 3443b8cb8fffd76bb3e03b2a84bfd3db952fcda4 FirebaseRemoteConfigInterop: 3443b8cb8fffd76bb3e03b2a84bfd3db952fcda4
FirebaseSessions: 2e8f808347e665dff3e5843f275715f07045297d FirebaseSessions: 2e8f808347e665dff3e5843f275715f07045297d
Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467 Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467
flutter_app_intents: e77f999f398c841ab584a1925dbce33ee0168fb5
flutter_app_update: 816fdb2e30e4832a7c45e3f108d391c42ef040a9 flutter_app_update: 816fdb2e30e4832a7c45e3f108d391c42ef040a9
flutter_inappwebview_ios: b89ba3482b96fb25e00c967aae065701b66e9b99 flutter_inappwebview_ios: b89ba3482b96fb25e00c967aae065701b66e9b99
flutter_keyboard_visibility: 4625131e43015dbbe759d9b20daaf77e0e3f6619 flutter_keyboard_visibility: 4625131e43015dbbe759d9b20daaf77e0e3f6619
@@ -553,6 +559,7 @@ SPEC CHECKSUMS:
image_picker_ios: e0ece4aa2a75771a7de3fa735d26d90817041326 image_picker_ios: e0ece4aa2a75771a7de3fa735d26d90817041326
in_app_review: 7dd1ea365263f834b8464673f9df72c80c17c937 in_app_review: 7dd1ea365263f834b8464673f9df72c80c17c937
irondash_engine_context: 8e58ca8e0212ee9d1c7dc6a42121849986c88486 irondash_engine_context: 8e58ca8e0212ee9d1c7dc6a42121849986c88486
just_audio: 4e391f57b79cad2b0674030a00453ca5ce817eed
KeychainAccess: c0c4f7f38f6fc7bbe58f5702e25f7bd2f65abf51 KeychainAccess: c0c4f7f38f6fc7bbe58f5702e25f7bd2f65abf51
Kingfisher: 23d18f54677d973b713e54ce6a8f5eef6e7056ba Kingfisher: 23d18f54677d973b713e54ce6a8f5eef6e7056ba
KingfisherWebP: 38b9721821947f547afb78f933f75f4f9e0ae402 KingfisherWebP: 38b9721821947f547afb78f933f75f4f9e0ae402
@@ -566,7 +573,6 @@ SPEC CHECKSUMS:
OrderedSet: e539b66b644ff081c73a262d24ad552a69be3a94 OrderedSet: e539b66b644ff081c73a262d24ad552a69be3a94
package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499 package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499
pasteboard: 49088aeb6119d51f976a421db60d8e1ab079b63c pasteboard: 49088aeb6119d51f976a421db60d8e1ab079b63c
path_provider_foundation: bb55f6dbba17d0dccd6737fe6f7f34fbd0376880
permission_handler_apple: 4ed2196e43d0651e8ff7ca3483a069d469701f2d permission_handler_apple: 4ed2196e43d0651e8ff7ca3483a069d469701f2d
pointer_interceptor_ios: da06a662d5bfd329602b45b2ab41bc0fb5fdb0f0 pointer_interceptor_ios: da06a662d5bfd329602b45b2ab41bc0fb5fdb0f0
PromisesObjC: f5707f49cb48b9636751c5b2e7d227e43fba9f47 PromisesObjC: f5707f49cb48b9636751c5b2e7d227e43fba9f47
@@ -587,6 +593,7 @@ SPEC CHECKSUMS:
SwiftyGif: 706c60cf65fa2bc5ee0313beece843c8eb8194d4 SwiftyGif: 706c60cf65fa2bc5ee0313beece843c8eb8194d4
syncfusion_flutter_pdfviewer: 90dc48305d2e33d4aa20681d1e98ddeda891bc14 syncfusion_flutter_pdfviewer: 90dc48305d2e33d4aa20681d1e98ddeda891bc14
url_launcher_ios: 7a95fa5b60cc718a708b8f2966718e93db0cef1b url_launcher_ios: 7a95fa5b60cc718a708b8f2966718e93db0cef1b
video_thumbnail: b637e0ad5f588ca9945f6e2c927f73a69a661140
wakelock_plus: e29112ab3ef0b318e58cfa5c32326458be66b556 wakelock_plus: e29112ab3ef0b318e58cfa5c32326458be66b556
WebRTC-SDK: 40d4f5ba05cadff14e4db5614aec402a633f007e WebRTC-SDK: 40d4f5ba05cadff14e4db5614aec402a633f007e

View File

@@ -15,6 +15,10 @@
7301DB052F08D99C008390F3 /* SwiftUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7301DB042F08D99C008390F3 /* SwiftUI.framework */; }; 7301DB052F08D99C008390F3 /* SwiftUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7301DB042F08D99C008390F3 /* SwiftUI.framework */; };
7301DB102F08D99D008390F3 /* SolianWidgetExtensionExtension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 7301DB012F08D99C008390F3 /* SolianWidgetExtensionExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; 7301DB102F08D99D008390F3 /* SolianWidgetExtensionExtension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 7301DB012F08D99C008390F3 /* SolianWidgetExtensionExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
7310A7DF2EB10963002C0FD3 /* Solian Watch App.app in Embed Watch Content */ = {isa = PBXBuildFile; fileRef = 7310A7D42EB10962002C0FD3 /* Solian Watch App.app */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; 7310A7DF2EB10963002C0FD3 /* Solian Watch App.app in Embed Watch Content */ = {isa = PBXBuildFile; fileRef = 7310A7D42EB10962002C0FD3 /* Solian Watch App.app */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
73595B1B2F17FF8000AAD53C /* SfxMessage.caf in Resources */ = {isa = PBXBuildFile; fileRef = 73595B162F17FF8000AAD53C /* SfxMessage.caf */; };
73595B1C2F17FF8000AAD53C /* SfxNotification.caf in Resources */ = {isa = PBXBuildFile; fileRef = 73595B172F17FF8000AAD53C /* SfxNotification.caf */; };
73595B832F1803D300AAD53C /* SfxNotification.caf in Resources */ = {isa = PBXBuildFile; fileRef = 73595B172F17FF8000AAD53C /* SfxNotification.caf */; };
73595B842F1803D300AAD53C /* SfxMessage.caf in Resources */ = {isa = PBXBuildFile; fileRef = 73595B162F17FF8000AAD53C /* SfxMessage.caf */; };
73ACDFAD2E3D0E6100B63535 /* ReplayKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 73ACDFAC2E3D0E6100B63535 /* ReplayKit.framework */; }; 73ACDFAD2E3D0E6100B63535 /* ReplayKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 73ACDFAC2E3D0E6100B63535 /* ReplayKit.framework */; };
73ACDFC32E3D0E6100B63535 /* SolianBroadcastExtension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 73ACDFAB2E3D0E6100B63535 /* SolianBroadcastExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; 73ACDFC32E3D0E6100B63535 /* SolianBroadcastExtension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 73ACDFAB2E3D0E6100B63535 /* SolianBroadcastExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
73C305D82E0BE878009035B9 /* SolianShareExtension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 73C305CE2E0BE878009035B9 /* SolianShareExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; 73C305D82E0BE878009035B9 /* SolianShareExtension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 73C305CE2E0BE878009035B9 /* SolianShareExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
@@ -133,6 +137,8 @@
7301DB042F08D99C008390F3 /* SwiftUI.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SwiftUI.framework; path = System/Library/Frameworks/SwiftUI.framework; sourceTree = SDKROOT; }; 7301DB042F08D99C008390F3 /* SwiftUI.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SwiftUI.framework; path = System/Library/Frameworks/SwiftUI.framework; sourceTree = SDKROOT; };
7301DB162F08D9A5008390F3 /* SolianWidgetExtensionExtension.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = SolianWidgetExtensionExtension.entitlements; sourceTree = "<group>"; }; 7301DB162F08D9A5008390F3 /* SolianWidgetExtensionExtension.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = SolianWidgetExtensionExtension.entitlements; sourceTree = "<group>"; };
7310A7D42EB10962002C0FD3 /* Solian Watch App.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "Solian Watch App.app"; sourceTree = BUILT_PRODUCTS_DIR; }; 7310A7D42EB10962002C0FD3 /* Solian Watch App.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "Solian Watch App.app"; sourceTree = BUILT_PRODUCTS_DIR; };
73595B162F17FF8000AAD53C /* SfxMessage.caf */ = {isa = PBXFileReference; lastKnownFileType = file; path = SfxMessage.caf; sourceTree = "<group>"; };
73595B172F17FF8000AAD53C /* SfxNotification.caf */ = {isa = PBXFileReference; lastKnownFileType = file; path = SfxNotification.caf; sourceTree = "<group>"; };
737E920B2DB6A9FF00BE9CDB /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = "<group>"; }; 737E920B2DB6A9FF00BE9CDB /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = "<group>"; };
73ACDFAB2E3D0E6100B63535 /* SolianBroadcastExtension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = SolianBroadcastExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; }; 73ACDFAB2E3D0E6100B63535 /* SolianBroadcastExtension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = SolianBroadcastExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; };
73ACDFAC2E3D0E6100B63535 /* ReplayKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = ReplayKit.framework; path = System/Library/Frameworks/ReplayKit.framework; sourceTree = SDKROOT; }; 73ACDFAC2E3D0E6100B63535 /* ReplayKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = ReplayKit.framework; path = System/Library/Frameworks/ReplayKit.framework; sourceTree = SDKROOT; };
@@ -396,6 +402,8 @@
91E124CE95BCB4DCD890160D /* Pods */, 91E124CE95BCB4DCD890160D /* Pods */,
498A09270B73B217F0279168 /* Frameworks */, 498A09270B73B217F0279168 /* Frameworks */,
9AE244813FCDFAA941430393 /* GoogleService-Info.plist */, 9AE244813FCDFAA941430393 /* GoogleService-Info.plist */,
73595B162F17FF8000AAD53C /* SfxMessage.caf */,
73595B172F17FF8000AAD53C /* SfxNotification.caf */,
); );
sourceTree = "<group>"; sourceTree = "<group>";
}; };
@@ -695,6 +703,8 @@
isa = PBXResourcesBuildPhase; isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
73595B1B2F17FF8000AAD53C /* SfxMessage.caf in Resources */,
73595B1C2F17FF8000AAD53C /* SfxNotification.caf in Resources */,
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };
@@ -703,6 +713,8 @@
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */,
73595B832F1803D300AAD53C /* SfxNotification.caf in Resources */,
73595B842F1803D300AAD53C /* SfxMessage.caf in Resources */,
3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */,
97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */,
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */,

View File

@@ -3,7 +3,6 @@ import WidgetKit
import UIKit import UIKit
import WatchConnectivity import WatchConnectivity
import AppIntents import AppIntents
import flutter_app_intents
@main @main
@objc class AppDelegate: FlutterAppDelegate { @objc class AppDelegate: FlutterAppDelegate {
@@ -35,10 +34,8 @@ import flutter_app_intents
GeneratedPluginRegistrant.register(with: self) GeneratedPluginRegistrant.register(with: self)
// Setup widget sync method channel
setupWidgetSyncChannel() setupWidgetSyncChannel()
// Always initialize and retain a strong reference
if WCSession.isSupported() { if WCSession.isSupported() {
AppDelegate.sharedWatchConnectivityService = WatchConnectivityService.shared AppDelegate.sharedWatchConnectivityService = WatchConnectivityService.shared
} else { } else {
@@ -84,8 +81,6 @@ final class WatchConnectivityService: NSObject, WCSessionDelegate {
session.activate() session.activate()
} }
// MARK: - WCSessionDelegate
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
if let error = error { if let error = error {
print("[iOS] WCSession activation failed: \(error.localizedDescription)") print("[iOS] WCSession activation failed: \(error.localizedDescription)")
@@ -140,240 +135,3 @@ final class WatchConnectivityService: NSObject, WCSessionDelegate {
} }
} }
} }
// MARK: - App Intents
@available(iOS 16.0, *)
struct OpenChatIntent: AppIntent {
static var title: LocalizedStringResource = "Open Chat"
static var description = IntentDescription("Open a specific chat room")
static var isDiscoverable = true
static var openAppWhenRun = true
@Parameter(title: "Channel ID")
var channelId: String?
func perform() async throws -> some IntentResult & ReturnsValue<String> & OpensIntent {
let plugin = FlutterAppIntentsPlugin.shared
let result = await plugin.handleIntentInvocation(
identifier: "open_chat",
parameters: ["channelId": channelId ?? ""]
)
if let success = result["success"] as? Bool, success {
let value = result["value"] as? String ?? "Chat opened"
return .result(value: value)
} else {
let errorMessage = result["error"] as? String ?? "Failed to open chat"
throw AppIntentError.executionFailed(errorMessage)
}
}
}
@available(iOS 16.0, *)
struct OpenPostIntent: AppIntent {
static var title: LocalizedStringResource = "Open Post"
static var description = IntentDescription("Open a specific post")
static var isDiscoverable = true
static var openAppWhenRun = true
@Parameter(title: "Post ID")
var postId: String?
func perform() async throws -> some IntentResult & ReturnsValue<String> & OpensIntent {
let plugin = FlutterAppIntentsPlugin.shared
let result = await plugin.handleIntentInvocation(
identifier: "open_post",
parameters: ["postId": postId ?? ""]
)
if let success = result["success"] as? Bool, success {
let value = result["value"] as? String ?? "Post opened"
return .result(value: value)
} else {
let errorMessage = result["error"] as? String ?? "Failed to open post"
throw AppIntentError.executionFailed(errorMessage)
}
}
}
@available(iOS 16.0, *)
struct OpenComposeIntent: AppIntent {
static var title: LocalizedStringResource = "Open Compose"
static var description = IntentDescription("Open compose post screen")
static var isDiscoverable = true
static var openAppWhenRun = true
func perform() async throws -> some IntentResult & ReturnsValue<String> & OpensIntent {
let plugin = FlutterAppIntentsPlugin.shared
let result = await plugin.handleIntentInvocation(
identifier: "open_compose",
parameters: [:]
)
if let success = result["success"] as? Bool, success {
let value = result["value"] as? String ?? "Compose screen opened"
return .result(value: value)
} else {
let errorMessage = result["error"] as? String ?? "Failed to open compose"
throw AppIntentError.executionFailed(errorMessage)
}
}
}
@available(iOS 16.0, *)
struct ComposePostIntent: AppIntent {
static var title: LocalizedStringResource = "Compose Post"
static var description = IntentDescription("Create a new post")
static var isDiscoverable = true
static var openAppWhenRun = true
func perform() async throws -> some IntentResult & ReturnsValue<String> & OpensIntent {
let plugin = FlutterAppIntentsPlugin.shared
let result = await plugin.handleIntentInvocation(
identifier: "compose_post",
parameters: [:]
)
if let success = result["success"] as? Bool, success {
let value = result["value"] as? String ?? "Compose screen opened"
return .result(value: value)
} else {
let errorMessage = result["error"] as? String ?? "Failed to compose post"
throw AppIntentError.executionFailed(errorMessage)
}
}
}
@available(iOS 16.0, *)
struct SearchContentIntent: AppIntent {
static var title: LocalizedStringResource = "Search Content"
static var description = IntentDescription("Search for content")
static var isDiscoverable = true
static var openAppWhenRun = true
@Parameter(title: "Search Query")
var query: String?
func perform() async throws -> some IntentResult & ReturnsValue<String> & OpensIntent {
let plugin = FlutterAppIntentsPlugin.shared
let result = await plugin.handleIntentInvocation(
identifier: "search_content",
parameters: ["query": query ?? ""]
)
if let success = result["success"] as? Bool, success {
let value = result["value"] as? String ?? "Search opened"
return .result(value: value)
} else {
let errorMessage = result["error"] as? String ?? "Failed to search"
throw AppIntentError.executionFailed(errorMessage)
}
}
}
@available(iOS 16.0, *)
struct ViewNotificationsIntent: AppIntent {
static var title: LocalizedStringResource = "View Notifications"
static var description = IntentDescription("View notifications")
static var isDiscoverable = true
static var openAppWhenRun = true
func perform() async throws -> some IntentResult & ReturnsValue<String> & OpensIntent {
let plugin = FlutterAppIntentsPlugin.shared
let result = await plugin.handleIntentInvocation(
identifier: "view_notifications",
parameters: [:]
)
if let success = result["success"] as? Bool, success {
let value = result["value"] as? String ?? "Notifications opened"
return .result(value: value)
} else {
let errorMessage = result["error"] as? String ?? "Failed to view notifications"
throw AppIntentError.executionFailed(errorMessage)
}
}
}
@available(iOS 16.0, *)
struct CheckNotificationsIntent: AppIntent {
static var title: LocalizedStringResource = "Check Notifications"
static var description = IntentDescription("Check notification count")
static var isDiscoverable = true
static var openAppWhenRun = false
func perform() async throws -> some IntentResult & ReturnsValue<String> & ProvidesDialog {
let plugin = FlutterAppIntentsPlugin.shared
let result = await plugin.handleIntentInvocation(
identifier: "check_notifications",
parameters: [:]
)
if let success = result["success"] as? Bool, success {
let value = result["value"] as? String ?? "You have new notifications"
return .result(
value: value,
dialog: "Dialog: \(value)"
)
} else {
let errorMessage = result["error"] as? String ?? "Failed to check notifications"
throw AppIntentError.executionFailed(errorMessage)
}
}
}
enum AppIntentError: Error {
case executionFailed(String)
}
@available(iOS 16.0, *)
struct AppShortcuts: AppShortcutsProvider {
static var appShortcuts: [AppShortcut] {
return [
// Open chat
AppShortcut(
intent: OpenChatIntent(),
phrases: [
"Open chat with \(.applicationName)",
"Go to chat using \(.applicationName)",
"Show chat in \(.applicationName)"
]
),
// Open post
AppShortcut(
intent: OpenPostIntent(),
phrases: [
"Open post with \(.applicationName)",
"Show post using \(.applicationName)"
]
),
// Compose
AppShortcut(
intent: OpenComposeIntent(),
phrases: [
"Open compose with \(.applicationName)",
"New post using \(.applicationName)",
"Write post in \(.applicationName)"
]
),
// Search
AppShortcut(
intent: SearchContentIntent(),
phrases: [
"Search in \(.applicationName)",
"Find content using \(.applicationName)"
]
),
// Check notifications
AppShortcut(
intent: CheckNotificationsIntent(),
phrases: [
"Check notifications with \(.applicationName)",
"Get notifications using \(.applicationName)",
"Do I have notifications in \(.applicationName)"
]
)
]
}
}

View File

@@ -0,0 +1,84 @@
//
// AppIntentConfiguration.swift
// Runner
//
// Created by LittleSheep on 2026/1/16.
//
import AppIntents
@available(iOS 16.0, *)
struct AppShortcuts: AppShortcutsProvider {
@AppShortcutsBuilder static var appShortcuts: [AppShortcut] {
AppShortcut(
intent: OpenChatIntent(),
phrases: [
"Open chat with \(.applicationName)",
"Go to chat using \(.applicationName)",
"Show chat in \(.applicationName)"
]
)
AppShortcut(
intent: OpenPostIntent(),
phrases: [
"Open post with \(.applicationName)",
"Show post using \(.applicationName)"
]
)
AppShortcut(
intent: OpenComposeIntent(),
phrases: [
"Open compose with \(.applicationName)",
"New post using \(.applicationName)",
"Write post in \(.applicationName)"
]
)
AppShortcut(
intent: SearchContentIntent(),
phrases: [
"Search in \(.applicationName)",
"Find content using \(.applicationName)"
]
)
AppShortcut(
intent: CheckNotificationsIntent(),
phrases: [
"Check notifications with \(.applicationName)",
"Get notifications using \(.applicationName)",
"Do I have notifications in \(.applicationName)"
]
)
AppShortcut(
intent: SendMessageIntent(),
phrases: [
"Send message with \(.applicationName)",
"Post message using \(.applicationName)",
"Send text using \(.applicationName)"
]
)
AppShortcut(
intent: ReadMessagesIntent(),
phrases: [
"Read messages with \(.applicationName)",
"Get chat using \(.applicationName)",
"Show messages with \(.applicationName)"
]
)
AppShortcut(
intent: CheckUnreadChatsIntent(),
phrases: [
"Check unread chats with \(.applicationName)",
"Do I have messages using \(.applicationName)",
"Get unread messages with \(.applicationName)"
]
)
AppShortcut(
intent: MarkNotificationsReadIntent(),
phrases: [
"Mark notifications read with \(.applicationName)",
"Clear notifications using \(.applicationName)",
"Mark all read with \(.applicationName)"
]
)
}
}

View File

@@ -0,0 +1,296 @@
//
// AppIntentHandlers.swift
// Runner
//
// Created by LittleSheep on 2026/1/16.
//
import AppIntents
import UIKit
@available(iOS 16.0, *)
struct OpenChatIntent: AppIntent {
static var title: LocalizedStringResource = "intent_open_chat_title"
static var description = IntentDescription("intent_open_chat_desc")
static var isDiscoverable = true
static var openAppWhenRun = true
@Parameter(title: "Channel ID")
var channelId: String?
func perform() async throws -> some IntentResult & OpensIntent {
guard let channelId = channelId, !channelId.isEmpty else {
throw AppIntentError.requiredParameter("Channel ID")
}
DeepLinkHandler.shared.handle(url: URL(string: "solian://chat/\(channelId)")!)
return .result(value: "Opening chat \(channelId)")
}
}
@available(iOS 16.0, *)
struct OpenPostIntent: AppIntent {
static var title: LocalizedStringResource = "intent_open_post_title"
static var description = IntentDescription("intent_open_post_desc")
static var isDiscoverable = true
static var openAppWhenRun = true
@Parameter(title: "Post ID")
var postId: String?
func perform() async throws -> some IntentResult & OpensIntent {
guard let postId = postId, !postId.isEmpty else {
throw AppIntentError.requiredParameter("Post ID")
}
DeepLinkHandler.shared.handle(url: URL(string: "solian://posts/\(postId)")!)
return .result(value: "Opening post \(postId)")
}
}
@available(iOS 16.0, *)
struct OpenComposeIntent: AppIntent {
static var title: LocalizedStringResource = "intent_open_compose_title"
static var description = IntentDescription("intent_open_compose_desc")
static var isDiscoverable = true
static var openAppWhenRun = true
func perform() async throws -> some IntentResult & OpensIntent {
DeepLinkHandler.shared.handle(url: URL(string: "solian://compose")!)
return .result(value: "Opening compose screen")
}
}
@available(iOS 16.0, *)
struct ComposePostIntent: AppIntent {
static var title: LocalizedStringResource = "intent_compose_post_title"
static var description = IntentDescription("intent_compose_post_desc")
static var isDiscoverable = true
static var openAppWhenRun = true
func perform() async throws -> some IntentResult & OpensIntent {
DeepLinkHandler.shared.handle(url: URL(string: "solian://compose")!)
return .result(value: "Opening compose screen")
}
}
@available(iOS 16.0, *)
struct SearchContentIntent: AppIntent {
static var title: LocalizedStringResource = "intent_search_title"
static var description = IntentDescription("intent_search_desc")
static var isDiscoverable = true
static var openAppWhenRun = true
@Parameter(title: "Search Query")
var query: String?
func perform() async throws -> some IntentResult & OpensIntent {
guard let query = query, !query.isEmpty else {
throw AppIntentError.requiredParameter("Search Query")
}
let encodedQuery = query.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? query
DeepLinkHandler.shared.handle(url: URL(string: "solian://search?q=\(encodedQuery)")!)
return .result(value: "Searching for \"\(query)\"")
}
}
@available(iOS 16.0, *)
struct ViewNotificationsIntent: AppIntent {
static var title: LocalizedStringResource = "intent_notifications_title"
static var description = IntentDescription("intent_notifications_desc")
static var isDiscoverable = true
static var openAppWhenRun = true
func perform() async throws -> some IntentResult & OpensIntent {
DeepLinkHandler.shared.handle(url: URL(string: "solian://notifications")!)
return .result(value: "Opening notifications")
}
}
@available(iOS 16.0, *)
struct CheckNotificationsIntent: AppIntent {
static var title: LocalizedStringResource = "intent_check_notifications_title"
static var description = IntentDescription("intent_check_notifications_desc")
static var isDiscoverable = true
static var openAppWhenRun = false
func perform() async throws -> some IntentResult & ProvidesDialog {
do {
let count = try await NetworkService.shared.getNotificationCount()
let message: String
if count == 0 {
message = "You have no new notifications"
} else if count == 1 {
message = "You have 1 new notification"
} else {
message = "You have \(count) new notifications"
}
return .result(
value: message,
dialog: "\(message)"
)
} catch {
throw AppIntentError.networkError("Failed to check notifications: \(error.localizedDescription)")
}
}
}
@available(iOS 16.0, *)
struct SendMessageIntent: AppIntent {
static var title: LocalizedStringResource = "intent_send_message_title"
static var description = IntentDescription("intent_send_message_desc")
static var isDiscoverable = true
static var openAppWhenRun = false
@Parameter(title: "Channel ID")
var channelId: String?
@Parameter(title: "Message Content")
var content: String?
func perform() async throws -> some IntentResult & ProvidesDialog {
guard let channelId = channelId, !channelId.isEmpty else {
throw AppIntentError.requiredParameter("Channel ID")
}
guard let content = content, !content.isEmpty else {
throw AppIntentError.requiredParameter("Message Content")
}
do {
try await NetworkService.shared.sendMessage(channelId: channelId, content: content)
return .result(
value: "Message sent to channel \(channelId)",
dialog: "Message sent successfully"
)
} catch {
throw AppIntentError.networkError("Failed to send message: \(error.localizedDescription)")
}
}
}
@available(iOS 16.0, *)
struct ReadMessagesIntent: AppIntent {
static var title: LocalizedStringResource = "intent_read_messages_title"
static var description = IntentDescription("intent_read_messages_desc")
static var isDiscoverable = true
static var openAppWhenRun = false
@Parameter(title: "Channel ID")
var channelId: String?
@Parameter(title: "Number of Messages", default: "5")
var limit: String?
func perform() async throws -> some IntentResult & ProvidesDialog {
guard let channelId = channelId, !channelId.isEmpty else {
throw AppIntentError.requiredParameter("Channel ID")
}
let limitValue = Int(limit ?? "5") ?? 5
let safeLimit = max(1, min(20, limitValue))
do {
let messages = try await NetworkService.shared.getMessages(
channelId: channelId,
offset: 0,
take: safeLimit
)
if messages.isEmpty {
return .result(
value: "No messages found in channel \(channelId)",
dialog: "No messages found"
)
}
let formattedMessages = messages.compactMap { message -> String? in
let senderName = message.sender?.account?.name ?? "Unknown"
let content = message.content ?? ""
return "\(senderName): \(content)"
}.joined(separator: "\n")
return .result(
value: formattedMessages,
dialog: "Found \(messages.count) messages"
)
} catch {
throw AppIntentError.networkError("Failed to read messages: \(error.localizedDescription)")
}
}
}
@available(iOS 16.0, *)
struct CheckUnreadChatsIntent: AppIntent {
static var title: LocalizedStringResource = "intent_unread_chats_title"
static var description = IntentDescription("intent_unread_chats_desc")
static var isDiscoverable = true
static var openAppWhenRun = false
func perform() async throws -> some IntentResult & ProvidesDialog {
do {
let count = try await NetworkService.shared.getUnreadChatsCount()
let message: String
if count == 0 {
message = "You have no unread messages"
} else if count == 1 {
message = "You have 1 unread message"
} else {
message = "You have \(count) unread messages"
}
return .result(
value: message,
dialog: "\(message)"
)
} catch {
throw AppIntentError.networkError("Failed to check unread chats: \(error.localizedDescription)")
}
}
}
@available(iOS 16.0, *)
struct MarkNotificationsReadIntent: AppIntent {
static var title: LocalizedStringResource = "intent_mark_read_title"
static var description = IntentDescription("intent_mark_read_desc")
static var isDiscoverable = true
static var openAppWhenRun = false
func perform() async throws -> some IntentResult & ProvidesDialog {
do {
try await NetworkService.shared.markNotificationsRead()
return .result(
value: "All notifications marked as read",
dialog: "All notifications marked as read"
)
} catch {
throw AppIntentError.networkError("Failed to mark notifications: \(error.localizedDescription)")
}
}
}
enum AppIntentError: Error, CustomLocalizedStringResourceConvertible {
case requiredParameter(String)
case networkError(String)
var localizedStringResource: LocalizedStringResource {
switch self {
case .requiredParameter(let param):
return "\(param) is required"
case .networkError(let message):
return "Network error: \(message)"
}
}
}

View File

@@ -0,0 +1,103 @@
//
// DeepLinkHandler.swift
// Runner
//
// Created by LittleSheep on 2026/1/16.
//
import Foundation
import UIKit
final class DeepLinkHandler {
static let shared = DeepLinkHandler()
private init() {}
func handle(url: URL) -> Bool {
guard url.scheme == SharedConstants.urlScheme else {
return false
}
let host = url.host ?? ""
let path = url.path
let queryItems = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems
switch host {
case "chat":
if let channelId = url.pathComponents.count > 1 ? url.pathComponents[1] : nil {
openUrl("solian://chat/\(channelId)")
return true
}
case "posts":
if let postId = url.pathComponents.count > 1 ? url.pathComponents[1] : nil {
openUrl("solian://posts/\(postId)")
return true
}
case "search":
if let query = queryItems?.first(where: { $0.name == "query" })?.value {
let encodedQuery = query.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? query
openUrl("solian://search?q=\(encodedQuery)")
return true
}
case "notifications":
openUrl("solian://notifications")
return true
case "compose":
openUrl("solian://compose")
return true
default:
if path.hasPrefix("/chat/") {
let channelId = path.replacingOccurrences(of: "/chat/", with: "")
openUrl("solian://chat/\(channelId)")
return true
}
if path.hasPrefix("/posts/") {
let postId = path.replacingOccurrences(of: "/posts/", with: "")
openUrl("solian://posts/\(postId)")
return true
}
if path.hasPrefix("/search") {
let query = queryItems?.first(where: { $0.name == "q" })?.value ?? ""
let encodedQuery = query.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? query
openUrl("solian://search?q=\(encodedQuery)")
return true
}
if path == "/notifications" {
openUrl("solian://notifications")
return true
}
if path.hasPrefix("/compose") || path == "/compose" {
openUrl("solian://compose")
return true
}
if path.hasPrefix("/dashboard") {
openUrl("solian://dashboard")
return true
}
}
return false
}
private func openUrl(_ urlString: String) {
guard let url = URL(string: urlString) else {
print("[DeepLinkHandler] Invalid URL: \(urlString)")
return
}
DispatchQueue.main.async {
UIApplication.shared.open(url) { success in
if success {
print("[DeepLinkHandler] Opened URL: \(urlString)")
} else {
print("[DeepLinkHandler] Failed to open URL: \(urlString)")
}
}
}
}
}

View File

@@ -0,0 +1,177 @@
//
// NetworkService.swift
// Runner
//
// Created by LittleSheep on 2026/1/16.
//
import Foundation
final class NetworkService {
static let shared = NetworkService()
private let session: URLSession
private let decoder: JSONDecoder
private init() {
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 10
config.timeoutIntervalForResource = 30
self.session = URLSession(configuration: config)
self.decoder = JSONDecoder()
self.decoder.keyDecodingStrategy = .convertFromSnakeCase
}
private var baseUrl: String {
UserDefaults.shared.getServerUrl()
}
private var authHeaders: [String: String] {
var headers = [
"Accept": "application/json",
"Content-Type": "application/json"
]
if let token = UserDefaults.shared.getAuthToken() {
headers["Authorization"] = "AtField \(token)"
}
return headers
}
func getNotificationCount() async throws -> Int {
let url = try buildUrl(path: SharedConstants.API.notificationsCount)
let response: NotificationCountResponse = try await get(url: url)
return response.count
}
func markNotificationsRead() async throws {
let url = try buildUrl(path: SharedConstants.API.notificationsMarkRead)
let _: EmptyResponse = try await post(url: url)
}
func getUnreadChatsCount() async throws -> Int {
let url = try buildUrl(path: SharedConstants.API.unreadChats)
let response: UnreadChatsResponse = try await get(url: url)
return response.unreadCount
}
func getMessages(channelId: String, offset: Int = 0, take: Int = 5) async throws -> [MessageResponse] {
let path = String(format: SharedConstants.API.messages, channelId)
let url = try buildUrl(path: path, queryItems: [
URLQueryItem(name: "offset", value: String(offset)),
URLQueryItem(name: "take", value: String(take))
])
let response: MessagesResponse = try await get(url: url)
return response.messages
}
func sendMessage(channelId: String, content: String) async throws {
let path = String(format: SharedConstants.API.sendMessage, channelId)
let url = try buildUrl(path: path)
let body = SendMessageBody(content: content, nonce: generateNonce())
let _: EmptyResponse = try await post(url: url, body: body)
}
private func buildUrl(path: String, queryItems: [URLQueryItem]? = nil) throws -> URL {
var components = URLComponents(string: baseUrl + path)
if let queryItems = queryItems, !queryItems.isEmpty {
components?.queryItems = queryItems
}
guard let url = components?.url else {
throw NetworkError.invalidUrl
}
return url
}
private func get<T: Decodable>(url: URL) async throws -> T {
var request = URLRequest(url: url)
authHeaders.forEach { request.setValue($1, forHTTPHeaderField: $0) }
let (data, response) = try await session.data(for: request)
try validateResponse(response)
return try decoder.decode(T.self, from: data)
}
private func post<T: Decodable>(url: URL) async throws -> T {
var request = URLRequest(url: url)
request.httpMethod = "POST"
authHeaders.forEach { request.setValue($1, forHTTPHeaderField: $0) }
let (data, response) = try await session.data(for: request)
try validateResponse(response)
if T.self == EmptyResponse.self {
return EmptyResponse() as! T
}
return try decoder.decode(T.self, from: data)
}
private func post<T: Decodable, B: Encodable>(url: URL, body: B) async throws -> T {
var request = URLRequest(url: url)
request.httpMethod = "POST"
authHeaders.forEach { request.setValue($1, forHTTPHeaderField: $0) }
request.httpBody = try JSONEncoder().encode(body)
let (data, response) = try await session.data(for: request)
try validateResponse(response)
if T.self == EmptyResponse.self {
return EmptyResponse() as! T
}
return try decoder.decode(T.self, from: data)
}
private func validateResponse(_ response: URLResponse) throws {
guard let httpResponse = response as? HTTPURLResponse else {
throw NetworkError.invalidResponse
}
guard (200...299).contains(httpResponse.statusCode) else {
throw NetworkError.httpError(statusCode: httpResponse.statusCode)
}
}
private func generateNonce() -> String {
"\(Date().timeIntervalSince1970)"
}
}
enum NetworkError: Error {
case invalidUrl
case invalidResponse
case httpError(statusCode: Int)
}
struct NotificationCountResponse: Decodable {
let count: Int
}
struct UnreadChatsResponse: Decodable {
let unreadCount: Int
}
struct MessagesResponse: Decodable {
let messages: [MessageResponse]
}
struct MessageResponse: Decodable {
let content: String?
let sender: SenderResponse?
struct SenderResponse: Decodable {
let account: AccountResponse?
struct AccountResponse: Decodable {
let name: String?
}
}
}
struct SendMessageBody: Encodable {
let content: String
let nonce: String
}
struct EmptyResponse: Decodable {}

View File

@@ -0,0 +1,45 @@
//
// SharedConstants.swift
// Runner
//
// Created by LittleSheep on 2026/1/16.
//
import Foundation
enum SharedConstants {
static let appGroupId = "group.solsynth.solian"
static let urlScheme = "solian"
static let serverUrlKey = "flutter.app_server_url"
static let tokenKey = "flutter.dyn_user_tk"
static let defaultServerUrl = "https://api.solian.app"
enum API {
static let notificationsCount = "/ring/notifications/count"
static let notificationsMarkRead = "/ring/notifications/all/read"
static let unreadChats = "/messager/chat/unread"
static let messages = "/messager/chat/%@/messages"
static let sendMessage = "/messager/chat/%@/messages"
}
}
extension UserDefaults {
static let shared: UserDefaults = {
UserDefaults(suiteName: SharedConstants.appGroupId) ?? UserDefaults.standard
}()
func getServerUrl() -> String {
string(forKey: SharedConstants.serverUrlKey) ?? SharedConstants.defaultServerUrl
}
func getAuthToken() -> String? {
guard let jsonString = string(forKey: SharedConstants.tokenKey),
let data = jsonString.data(using: .utf8),
let jsonObject = try? JSONSerialization.jsonObject(with: data),
let jsonDict = jsonObject as? [String: Any],
let token = jsonDict["token"] as? String else {
return nil
}
return token
}
}

View File

@@ -0,0 +1,33 @@
/* App Intents - Chat */
"intent_open_chat_title" = "Open Chat";
"intent_open_chat_desc" = "Open a specific chat room";
/* App Intents - Post */
"intent_open_post_title" = "Open Post";
"intent_open_post_desc" = "Open a specific post";
/* App Intents - Compose */
"intent_open_compose_title" = "Open Compose";
"intent_open_compose_desc" = "Open compose post screen";
"intent_compose_post_title" = "Compose Post";
"intent_compose_post_desc" = "Create a new post";
/* App Intents - Search */
"intent_search_title" = "Search Content";
"intent_search_desc" = "Search for content";
/* App Intents - Notifications */
"intent_notifications_title" = "View Notifications";
"intent_notifications_desc" = "View notifications";
"intent_check_notifications_title" = "Check Notifications";
"intent_check_notifications_desc" = "Check notification count";
/* App Intents - Messages */
"intent_send_message_title" = "Send Message";
"intent_send_message_desc" = "Send a message to a chat channel";
"intent_read_messages_title" = "Read Messages";
"intent_read_messages_desc" = "Read recent messages from a chat channel";
"intent_unread_chats_title" = "Check Unread Chats";
"intent_unread_chats_desc" = "Check number of unread chat messages";
"intent_mark_read_title" = "Mark Notifications Read";
"intent_mark_read_desc" = "Mark all notifications as read";

View File

@@ -0,0 +1,33 @@
/* App Intents - Chat */
"intent_open_chat_title" = "Abrir chat";
"intent_open_chat_desc" = "Abrir sala de chat específica";
/* App Intents - Post */
"intent_open_post_title" = "Abrir publicación";
"intent_open_post_desc" = "Abrir publicación específica";
/* App Intents - Compose */
"intent_open_compose_title" = "Abrir compose";
"intent_open_compose_desc" = "Abrir pantalla de publicación";
"intent_compose_post_title" = "Redactar publicación";
"intent_compose_post_desc" = "Crear nueva publicación";
/* App Intents - Search */
"intent_search_title" = "Buscar contenido";
"intent_search_desc" = "Buscar contenido";
/* App Intents - Notifications */
"intent_notifications_title" = "Ver notificaciones";
"intent_notifications_desc" = "Ver notificaciones";
"intent_check_notifications_title" = "Ver notificaciones";
"intent_check_notifications_desc" = "Ver número de notificaciones";
/* App Intents - Messages */
"intent_send_message_title" = "Enviar mensaje";
"intent_send_message_desc" = "Enviar mensaje a canal de chat";
"intent_read_messages_title" = "Leer mensajes";
"intent_read_messages_desc" = "Leer mensajes recientes de un canal de chat";
"intent_unread_chats_title" = "Ver chats no leídos";
"intent_unread_chats_desc" = "Ver mensajes no leídos";
"intent_mark_read_title" = "Marcar notificaciones leídas";
"intent_mark_read_desc" = "Marcar todas como leídas";

View File

@@ -0,0 +1,33 @@
/* App Intents - Chat */
"intent_open_chat_title" = "チャットを開く";
"intent_open_chat_desc" = "特定のチャットルームを開く";
/* App Intents - Post */
"intent_open_post_title" = "投稿を開く";
"intent_open_post_desc" = "特定の投稿を開く";
/* App Intents - Compose */
"intent_open_compose_title" = "作成を開く";
"intent_open_compose_desc" = "投稿作成画面を開く";
"intent_compose_post_title" = "投稿を作成する";
"intent_compose_post_desc" = "新規投稿を作成する";
/* App Intents - Search */
"intent_search_title" = "検索";
"intent_search_desc" = "コンテンツを検索";
/* App Intents - Notifications */
"intent_notifications_title" = "通知を見る";
"intent_notifications_desc" = "通知を見る";
"intent_check_notifications_title" = "通知を確認";
"intent_check_notifications_desc" = "通知数を確認";
/* App Intents - Messages */
"intent_send_message_title" = "メッセージを送信";
"intent_send_message_desc" = "チャットチャンネルにメッセージを送信";
"intent_read_messages_title" = "メッセージを読む";
"intent_read_messages_desc" = "チャットチャンネルから最近のメッセージを読む";
"intent_unread_chats_title" = "未読チャットを確認";
"intent_unread_chats_desc" = "未読チャットメッセージ数を確認";
"intent_mark_read_title" = "通知を既読にする";
"intent_mark_read_desc" = "すべての通知を既読にする";

View File

@@ -0,0 +1,33 @@
/* App Intents - Chat */
"intent_open_chat_title" = "채팅 열기";
"intent_open_chat_desc" = "특정 채팅방 열기";
/* App Intents - Post */
"intent_open_post_title" = "게시물 열기";
"intent_open_post_desc" = "특정 게시물 열기";
/* App Intents - Compose */
"intent_open_compose_title" = "글쓰기 열기";
"intent_open_compose_desc" = "글쓰기 화면 열기";
"intent_compose_post_title" = "게시물 작성";
"intent_compose_post_desc" = "새 게시물 작성";
/* App Intents - Search */
"intent_search_title" = "검색";
"intent_search_desc" = "콘텐츠 검색";
/* App Intents - Notifications */
"intent_notifications_title" = "알림 보기";
"intent_notifications_desc" = "알림 보기";
"intent_check_notifications_title" = "알림 확인";
"intent_check_notifications_desc" = "알림 수 확인";
/* App Intents - Messages */
"intent_send_message_title" = "메시지 보내기";
"intent_send_message_desc" = "채팅 채널에 메시지 보내기";
"intent_read_messages_title" = "메시지 읽기";
"intent_read_messages_desc" = "채팅 채널에서 최근 메시지 읽기";
"intent_unread_chats_title" = "읽지 않은 채팅 확인";
"intent_unread_chats_desc" = "읽지 않은 채팅 메시지 수 확인";
"intent_mark_read_title" = "알림 읽음 처리";
"intent_mark_read_desc" = "모든 알림을 읽음으로 처리";

View File

@@ -0,0 +1,33 @@
/* App Intents - Chat */
"intent_open_chat_title" = "打开聊天";
"intent_open_chat_desc" = "打开特定聊天室";
/* App Intents - Post */
"intent_open_post_title" = "打开帖子";
"intent_open_post_desc" = "打开特定帖子";
/* App Intents - Compose */
"intent_open_compose_title" = "打开撰写";
"intent_open_compose_desc" = "打开撰写帖子页面";
"intent_compose_post_title" = "撰写帖子";
"intent_compose_post_desc" = "创建新帖子";
/* App Intents - Search */
"intent_search_title" = "搜索内容";
"intent_search_desc" = "搜索内容";
/* App Intents - Notifications */
"intent_notifications_title" = "查看通知";
"intent_notifications_desc" = "查看通知";
"intent_check_notifications_title" = "检查通知";
"intent_check_notifications_desc" = "检查通知数量";
/* App Intents - Messages */
"intent_send_message_title" = "发送消息";
"intent_send_message_desc" = "发送消息到聊天频道";
"intent_read_messages_title" = "读取消息";
"intent_read_messages_desc" = "从聊天频道读取最近消息";
"intent_unread_chats_title" = "检查未读聊天";
"intent_unread_chats_desc" = "检查未读聊天消息数量";
"intent_mark_read_title" = "标记通知已读";
"intent_mark_read_desc" = "将所有通知标记为已读";

View File

@@ -0,0 +1,33 @@
/* App Intents - Chat */
"intent_open_chat_title" = "開啟聊天";
"intent_open_chat_desc" = "開啟特定聊天室";
/* App Intents - Post */
"intent_open_post_title" = "開啟貼文";
"intent_open_post_desc" = "開啟特定貼文";
/* App Intents - Compose */
"intent_open_compose_title" = "開啟撰寫";
"intent_open_compose_desc" = "開啟撰寫貼文頁面";
"intent_compose_post_title" = "撰寫貼文";
"intent_compose_post_desc" = "建立新貼文";
/* App Intents - Search */
"intent_search_title" = "搜尋內容";
"intent_search_desc" = "搜尋內容";
/* App Intents - Notifications */
"intent_notifications_title" = "查看通知";
"intent_notifications_desc" = "查看通知";
"intent_check_notifications_title" = "檢查通知";
"intent_check_notifications_desc" = "檢查通知數量";
/* App Intents - Messages */
"intent_send_message_title" = "傳送訊息";
"intent_send_message_desc" = "傳送訊息到聊天頻道";
"intent_read_messages_title" = "讀取訊息";
"intent_read_messages_desc" = "從聊天頻道讀取最近訊息";
"intent_unread_chats_title" = "檢查未讀聊天";
"intent_unread_chats_desc" = "檢查未讀聊天訊息數量";
"intent_mark_read_title" = "標記通知已讀";
"intent_mark_read_desc" = "將所有通知標記為已讀";

BIN
ios/SfxMessage.caf Normal file

Binary file not shown.

BIN
ios/SfxNotification.caf Normal file

Binary file not shown.

View File

@@ -53,8 +53,10 @@ class NotificationService: UNNotificationServiceExtension {
private func processNotification(request: UNNotificationRequest, content: UNMutableNotificationContent) throws { private func processNotification(request: UNNotificationRequest, content: UNMutableNotificationContent) throws {
switch content.userInfo["type"] as? String { switch content.userInfo["type"] as? String {
case "messages.new": case "messages.new":
content.sound = UNNotificationSound(named: UNNotificationSoundName("SfxMessage.caf"))
try handleMessagingNotification(request: request, content: content) try handleMessagingNotification(request: request, content: content)
default: default:
content.sound = UNNotificationSound(named: UNNotificationSoundName("SfxNotification.caf"))
try handleDefaultNotification(content: content) try handleDefaultNotification(content: content)
} }
} }

View File

@@ -0,0 +1,135 @@
import 'dart:async';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:image_picker/image_picker.dart';
import 'package:island/models/file.dart';
import 'package:island/widgets/chat/chat_link_attachments.dart';
class RoomFilePicker {
final List<UniversalFile> attachments;
final void Function(List<UniversalFile>) updateAttachments;
final Future<void> Function() pickPhotos;
final Future<void> Function() pickVideos;
final Future<void> Function() pickAudio;
final Future<void> Function() pickFiles;
final Future<void> Function() linkAttachment;
RoomFilePicker({
required this.attachments,
required this.updateAttachments,
required this.pickPhotos,
required this.pickVideos,
required this.pickAudio,
required this.pickFiles,
required this.linkAttachment,
});
}
RoomFilePicker useRoomFilePicker(
BuildContext context,
List<UniversalFile> currentAttachments,
Function(List<UniversalFile>) onAttachmentsChanged,
) {
final attachments = useState<List<UniversalFile>>(currentAttachments);
Future<void> pickPhotos() async {
final picker = ImagePicker();
final results = await picker.pickMultiImage();
if (results.isEmpty) return;
attachments.value = [
...attachments.value,
...results.map(
(xfile) => UniversalFile(data: xfile, type: UniversalFileType.image),
),
];
onAttachmentsChanged(attachments.value);
}
Future<void> pickVideos() async {
final result = await FilePicker.platform.pickFiles(
type: FileType.video,
allowMultiple: true,
allowCompression: false,
);
if (result == null || result.count == 0) return;
attachments.value = [
...attachments.value,
...result.files.map(
(e) => UniversalFile(data: e.xFile, type: UniversalFileType.video),
),
];
onAttachmentsChanged(attachments.value);
}
Future<void> pickAudio() async {
final result = await FilePicker.platform.pickFiles(
type: FileType.audio,
allowMultiple: true,
allowCompression: false,
);
if (result == null || result.count == 0) return;
attachments.value = [
...attachments.value,
...result.files.map(
(e) => UniversalFile(data: e.xFile, type: UniversalFileType.audio),
),
];
onAttachmentsChanged(attachments.value);
}
Future<void> pickFiles() async {
final result = await FilePicker.platform.pickFiles(
allowMultiple: true,
allowCompression: false,
);
if (result == null || result.count == 0) return;
attachments.value = [
...attachments.value,
...result.files.map(
(e) => UniversalFile(data: e.xFile, type: UniversalFileType.file),
),
];
onAttachmentsChanged(attachments.value);
}
Future<void> linkAttachment() async {
final cloudFile = await showModalBottomSheet<SnCloudFile?>(
context: context,
useRootNavigator: true,
isScrollControlled: true,
builder: (context) => const ChatLinkAttachment(),
);
if (cloudFile == null) return;
attachments.value = [
...attachments.value,
UniversalFile(
data: cloudFile,
type: switch (cloudFile.mimeType?.split('/').firstOrNull) {
'image' => UniversalFileType.image,
'video' => UniversalFileType.video,
'audio' => UniversalFileType.audio,
_ => UniversalFileType.file,
},
isLink: true,
),
];
onAttachmentsChanged(attachments.value);
}
void updateAttachments(List<UniversalFile> newAttachments) {
attachments.value = newAttachments;
onAttachmentsChanged(attachments.value);
}
return RoomFilePicker(
attachments: attachments.value,
updateAttachments: updateAttachments,
pickPhotos: pickPhotos,
pickVideos: pickVideos,
pickAudio: pickAudio,
pickFiles: pickFiles,
linkAttachment: linkAttachment,
);
}

View File

@@ -0,0 +1,236 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:image_picker/image_picker.dart';
import 'package:island/models/file.dart';
import 'package:island/models/chat.dart';
import 'package:island/models/poll.dart';
import 'package:island/models/wallet.dart';
import 'package:island/pods/chat/chat_subscribe.dart';
import 'package:island/database/message.dart';
import 'package:island/pods/chat/messages_notifier.dart';
import 'package:island/widgets/chat/message_item.dart';
import 'package:pasteboard/pasteboard.dart';
class RoomInputManager {
final TextEditingController messageController;
final List<UniversalFile> attachments;
final Map<String, Map<int, double?>> attachmentProgress;
final SnChatMessage? messageEditingTo;
final SnChatMessage? messageReplyingTo;
final SnChatMessage? messageForwardingTo;
final SnPoll? selectedPoll;
final SnWalletFund? selectedFund;
final void Function(List<UniversalFile>) updateAttachments;
final void Function(String, double?) updateAttachmentProgress;
final void Function(SnChatMessage?) setEditingTo;
final void Function(SnChatMessage?) setReplyingTo;
final void Function(SnChatMessage?) setForwardingTo;
final void Function(SnPoll?) setPoll;
final void Function(SnWalletFund?) setFund;
final void Function() clear;
final void Function() clearAttachmentsOnly;
final Future<void> Function() handlePaste;
final void Function(WidgetRef ref) sendMessage;
final void Function(String action, LocalChatMessage message) onMessageAction;
RoomInputManager({
required this.messageController,
required this.attachments,
required this.attachmentProgress,
this.messageEditingTo,
this.messageReplyingTo,
this.messageForwardingTo,
this.selectedPoll,
this.selectedFund,
required this.updateAttachments,
required this.updateAttachmentProgress,
required this.setEditingTo,
required this.setReplyingTo,
required this.setForwardingTo,
required this.setPoll,
required this.setFund,
required this.clear,
required this.clearAttachmentsOnly,
required this.handlePaste,
required this.sendMessage,
required this.onMessageAction,
});
}
RoomInputManager useRoomInputManager(WidgetRef ref, String roomId) {
final messageController = useTextEditingController();
final attachments = useState<List<UniversalFile>>([]);
final attachmentProgress = useState<Map<String, Map<int, double?>>>({});
final messageEditingTo = useState<SnChatMessage?>(null);
final messageReplyingTo = useState<SnChatMessage?>(null);
final messageForwardingTo = useState<SnChatMessage?>(null);
final selectedPoll = useState<SnPoll?>(null);
final selectedFund = useState<SnWalletFund?>(null);
final chatSubscribeNotifier = ref.read(
chatSubscribeProvider(roomId).notifier,
);
final messagesNotifier = ref.read(messagesProvider(roomId).notifier);
void updateAttachments(List<UniversalFile> newAttachments) {
attachments.value = newAttachments;
}
void updateAttachmentProgress(String messageId, double? progress) {
attachmentProgress.value = {
...attachmentProgress.value,
messageId: {0: progress},
};
}
void setEditingTo(SnChatMessage? message) {
messageEditingTo.value = message;
if (message != null) {
messageController.text = message.content ?? '';
attachments.value = message.attachments
.map((e) => UniversalFile.fromAttachment(e))
.toList();
}
}
void setReplyingTo(SnChatMessage? message) {
messageReplyingTo.value = message;
}
void setForwardingTo(SnChatMessage? message) {
messageForwardingTo.value = message;
}
void setPoll(SnPoll? poll) {
selectedPoll.value = poll;
}
void setFund(SnWalletFund? fund) {
selectedFund.value = fund;
}
void clear() {
messageController.clear();
messageEditingTo.value = null;
messageReplyingTo.value = null;
messageForwardingTo.value = null;
selectedPoll.value = null;
selectedFund.value = null;
attachments.value = [];
}
void clearAttachmentsOnly() {
messageController.clear();
attachments.value = [];
}
void onTextChange() {
if (messageController.text.isNotEmpty) {
chatSubscribeNotifier.sendTypingStatus();
}
}
useEffect(() {
messageController.addListener(onTextChange);
return () => messageController.removeListener(onTextChange);
}, [messageController]);
Future<void> handlePaste() async {
final image = await Pasteboard.image;
if (image != null) {
final newAttachments = [
...attachments.value,
UniversalFile(
displayName: 'image.jpeg',
data: XFile.fromData(
image,
mimeType: "image/jpeg",
name: 'image.jpeg',
),
type: UniversalFileType.image,
),
];
attachments.value = newAttachments;
}
final textData = await Clipboard.getData(Clipboard.kTextPlain);
if (textData != null && textData.text != null) {
final text = messageController.text;
final selection = messageController.selection;
final start = selection.start >= 0 ? selection.start : text.length;
final end = selection.end >= 0 ? selection.end : text.length;
final newText = text.replaceRange(start, end, textData.text!);
messageController.value = TextEditingValue(
text: newText,
selection: TextSelection.collapsed(
offset: start + textData.text!.length,
),
);
}
}
void onMessageAction(String action, LocalChatMessage message) {
switch (action) {
case MessageItemAction.delete:
messagesNotifier.deleteMessage(message.id);
case MessageItemAction.edit:
setEditingTo(message.toRemoteMessage());
case MessageItemAction.forward:
setForwardingTo(message.toRemoteMessage());
case MessageItemAction.reply:
setReplyingTo(message.toRemoteMessage());
case MessageItemAction.resend:
messagesNotifier.retryMessage(message.id);
}
}
void sendMessage(WidgetRef ref) {
if (messageController.text.trim().isNotEmpty ||
attachments.value.isNotEmpty ||
selectedPoll.value != null ||
selectedFund.value != null) {
messagesNotifier.sendMessage(
ref,
messageController.text.trim(),
attachments.value,
poll: selectedPoll.value,
fund: selectedFund.value,
editingTo: messageEditingTo.value,
forwardingTo: messageForwardingTo.value,
replyingTo: messageReplyingTo.value,
onProgress: (messageId, progress) {
attachmentProgress.value = {
...attachmentProgress.value,
messageId: progress,
};
},
);
clear();
}
}
return RoomInputManager(
messageController: messageController,
attachments: attachments.value,
attachmentProgress: attachmentProgress.value,
messageEditingTo: messageEditingTo.value,
messageReplyingTo: messageReplyingTo.value,
messageForwardingTo: messageForwardingTo.value,
selectedPoll: selectedPoll.value,
selectedFund: selectedFund.value,
updateAttachments: updateAttachments,
updateAttachmentProgress: updateAttachmentProgress,
setEditingTo: setEditingTo,
setReplyingTo: setReplyingTo,
setForwardingTo: setForwardingTo,
setPoll: setPoll,
setFund: setFund,
clear: clear,
clearAttachmentsOnly: clearAttachmentsOnly,
handlePaste: handlePaste,
sendMessage: sendMessage,
onMessageAction: onMessageAction,
);
}

View File

@@ -0,0 +1,127 @@
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/pods/chat/chat_room.dart';
import 'package:island/database/message.dart';
import 'package:island/pods/chat/messages_notifier.dart';
import 'package:super_sliver_list/super_sliver_list.dart';
class RoomScrollManager {
final ScrollController scrollController;
final ListController listController;
final ValueNotifier<double> bottomGradientOpacity;
bool isScrollingToMessage;
final void Function({
required String messageId,
required List<LocalChatMessage> messageList,
})
scrollToMessage;
RoomScrollManager({
required this.scrollController,
required this.listController,
required this.bottomGradientOpacity,
required this.scrollToMessage,
this.isScrollingToMessage = false,
});
}
RoomScrollManager useRoomScrollManager(
WidgetRef ref,
String roomId,
Future<int> Function(String) jumpToMessage,
AsyncValue<List<LocalChatMessage>> messagesAsync,
) {
final scrollController = useScrollController();
final listController = useMemoized(() => ListController(), []);
final bottomGradientOpacity = useState(ValueNotifier<double>(0.0));
var isLoading = false;
var isScrollingToMessage = false;
final messagesNotifier = ref.read(messagesProvider(roomId).notifier);
final flashingMessagesNotifier = ref.read(flashingMessagesProvider.notifier);
void performScrollAnimation({required int index, required String messageId}) {
flashingMessagesNotifier.update((set) => set.union({messageId}));
WidgetsBinding.instance.addPostFrameCallback((_) {
WidgetsBinding.instance.addPostFrameCallback((_) {
try {
listController.animateToItem(
index: index,
scrollController: scrollController,
alignment: 0.5,
duration: (estimatedDistance) => Duration(
milliseconds: (estimatedDistance * 0.5).clamp(200, 800).toInt(),
),
curve: (estimatedDistance) => Curves.easeOutCubic,
);
Future.delayed(const Duration(milliseconds: 800), () {
isScrollingToMessage = false;
});
} catch (e) {
isScrollingToMessage = false;
}
});
});
}
void scrollToMessageWrapper({
required String messageId,
required List<LocalChatMessage> messageList,
}) {
if (isScrollingToMessage) return;
isScrollingToMessage = true;
final messageIndex = messageList.indexWhere((m) => m.id == messageId);
if (messageIndex == -1) {
jumpToMessage(messageId).then((index) {
if (index != -1) {
WidgetsBinding.instance.addPostFrameCallback((_) {
performScrollAnimation(index: index, messageId: messageId);
});
} else {
isScrollingToMessage = false;
}
});
} else {
WidgetsBinding.instance.addPostFrameCallback((_) {
performScrollAnimation(index: messageIndex, messageId: messageId);
});
}
}
useEffect(() {
void onScroll() {
messagesAsync.when(
data: (messageList) {
if (scrollController.position.pixels >=
scrollController.position.maxScrollExtent - 200) {
if (!isLoading) {
isLoading = true;
messagesNotifier.loadMore().then((_) => isLoading = false);
}
}
final pixels = scrollController.position.pixels;
bottomGradientOpacity.value.value = (pixels / 500.0).clamp(0.0, 1.0);
},
loading: () {},
error: (_, _) {},
);
}
scrollController.addListener(onScroll);
return () => scrollController.removeListener(onScroll);
}, [scrollController, messagesAsync]);
return RoomScrollManager(
scrollController: scrollController,
listController: listController,
bottomGradientOpacity: bottomGradientOpacity.value,
scrollToMessage: scrollToMessageWrapper,
isScrollingToMessage: isScrollingToMessage,
);
}

View File

@@ -12,9 +12,11 @@ import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:hotkey_manager/hotkey_manager.dart'; import 'package:hotkey_manager/hotkey_manager.dart';
import 'package:image_picker_android/image_picker_android.dart'; import 'package:image_picker_android/image_picker_android.dart';
import 'package:island/services/analytics_service.dart';
import 'package:island/talker.dart'; import 'package:island/talker.dart';
import 'package:island/firebase_options.dart'; import 'package:island/firebase_options.dart';
import 'package:island/pods/config.dart'; import 'package:island/pods/config.dart';
import 'package:island/pods/audio.dart';
import 'package:island/pods/network.dart'; import 'package:island/pods/network.dart';
import 'package:island/pods/theme.dart'; import 'package:island/pods/theme.dart';
import 'package:island/pods/userinfo.dart'; import 'package:island/pods/userinfo.dart';
@@ -23,7 +25,6 @@ import 'package:island/route.dart';
import 'package:island/services/notify.dart'; import 'package:island/services/notify.dart';
import 'package:island/services/widget_sync_service.dart'; import 'package:island/services/widget_sync_service.dart';
import 'package:island/services/timezone.dart'; import 'package:island/services/timezone.dart';
import 'package:island/services/app_intents.dart';
import 'package:island/services/quick_actions.dart'; import 'package:island/services/quick_actions.dart';
import 'package:island/widgets/alert.dart'; import 'package:island/widgets/alert.dart';
import 'package:island/widgets/app_scaffold.dart'; import 'package:island/widgets/app_scaffold.dart';
@@ -101,17 +102,6 @@ void main() async {
talker.error("[SplashScreen] Failed to load timezone database... $err"); talker.error("[SplashScreen] Failed to load timezone database... $err");
} }
try {
talker.info("[AppIntents] Initializing App Intents service...");
final appIntentsService = AppIntentsService();
await appIntentsService.initialize();
talker.info("[AppIntents] App Intents service is ready!");
} catch (err) {
talker.error(
"[AppIntents] Failed to initialize App Intents service... $err",
);
}
try { try {
talker.info("[QuickActions] Initializing Quick Actions service..."); talker.info("[QuickActions] Initializing Quick Actions service...");
final quickActionsService = QuickActionsService(); final quickActionsService = QuickActionsService();
@@ -123,6 +113,14 @@ void main() async {
); );
} }
try {
talker.info("[Analytics] Initializing Analytics service...");
final analyticsService = AnalyticsService();
analyticsService.initialize();
} catch (err) {
talker.error("[Analytics] Failed to initialize Analytics service... $err");
}
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
if (!kIsWeb && (Platform.isMacOS || Platform.isLinux || Platform.isWindows)) { if (!kIsWeb && (Platform.isMacOS || Platform.isLinux || Platform.isWindows)) {
@@ -196,8 +194,12 @@ void main() async {
runApp( runApp(
ProviderScope( ProviderScope(
retry: (retryCount, error) { retry: (retryCount, error) {
if (error is DioException && error.response?.statusCode == 404) { if (retryCount > 3) return null;
return null; if (error is DioException) {
if (error.response?.statusCode == 401) return null;
if (error.response?.statusCode == 403) return null;
if (error.response?.statusCode == 404) return null;
if (error.response?.statusCode == 500) return null;
} }
return const Duration(milliseconds: 300); return const Duration(milliseconds: 300);
}, },
@@ -326,6 +328,9 @@ class IslandApp extends HookConsumerWidget {
final apiClient = ref.read(apiClientProvider); final apiClient = ref.read(apiClientProvider);
subscribePushNotification(apiClient); subscribePushNotification(apiClient);
initializeLocalNotifications(); initializeLocalNotifications();
ref.read(audioSessionProvider);
ref.read(notificationSfxProvider);
ref.read(messageSfxProvider);
final wsNotifier = ref.read(websocketStateProvider.notifier); final wsNotifier = ref.read(websocketStateProvider.notifier);
wsNotifier.connect(); wsNotifier.connect();
} }

View File

@@ -8,7 +8,7 @@ sealed class SnScrappedLink with _$SnScrappedLink {
const factory SnScrappedLink({ const factory SnScrappedLink({
required String type, required String type,
required String url, required String url,
required String title, required String? title,
required String? description, required String? description,
required String? imageUrl, required String? imageUrl,
required String? faviconUrl, required String? faviconUrl,

View File

@@ -15,7 +15,7 @@ T _$identity<T>(T value) => value;
/// @nodoc /// @nodoc
mixin _$SnScrappedLink { mixin _$SnScrappedLink {
String get type; String get url; String get title; String? get description; String? get imageUrl; String? get faviconUrl; String? get siteName; String? get contentType; String? get author; DateTime? get publishedDate; String get type; String get url; String? get title; String? get description; String? get imageUrl; String? get faviconUrl; String? get siteName; String? get contentType; String? get author; DateTime? get publishedDate;
/// Create a copy of SnScrappedLink /// Create a copy of SnScrappedLink
/// with the given fields replaced by the non-null parameter values. /// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false) @JsonKey(includeFromJson: false, includeToJson: false)
@@ -48,7 +48,7 @@ abstract mixin class $SnScrappedLinkCopyWith<$Res> {
factory $SnScrappedLinkCopyWith(SnScrappedLink value, $Res Function(SnScrappedLink) _then) = _$SnScrappedLinkCopyWithImpl; factory $SnScrappedLinkCopyWith(SnScrappedLink value, $Res Function(SnScrappedLink) _then) = _$SnScrappedLinkCopyWithImpl;
@useResult @useResult
$Res call({ $Res call({
String type, String url, String title, String? description, String? imageUrl, String? faviconUrl, String? siteName, String? contentType, String? author, DateTime? publishedDate String type, String url, String? title, String? description, String? imageUrl, String? faviconUrl, String? siteName, String? contentType, String? author, DateTime? publishedDate
}); });
@@ -65,12 +65,12 @@ class _$SnScrappedLinkCopyWithImpl<$Res>
/// Create a copy of SnScrappedLink /// Create a copy of SnScrappedLink
/// with the given fields replaced by the non-null parameter values. /// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? type = null,Object? url = null,Object? title = null,Object? description = freezed,Object? imageUrl = freezed,Object? faviconUrl = freezed,Object? siteName = freezed,Object? contentType = freezed,Object? author = freezed,Object? publishedDate = freezed,}) { @pragma('vm:prefer-inline') @override $Res call({Object? type = null,Object? url = null,Object? title = freezed,Object? description = freezed,Object? imageUrl = freezed,Object? faviconUrl = freezed,Object? siteName = freezed,Object? contentType = freezed,Object? author = freezed,Object? publishedDate = freezed,}) {
return _then(_self.copyWith( return _then(_self.copyWith(
type: null == type ? _self.type : type // ignore: cast_nullable_to_non_nullable type: null == type ? _self.type : type // ignore: cast_nullable_to_non_nullable
as String,url: null == url ? _self.url : url // ignore: cast_nullable_to_non_nullable as String,url: null == url ? _self.url : url // ignore: cast_nullable_to_non_nullable
as String,title: null == title ? _self.title : title // ignore: cast_nullable_to_non_nullable as String,title: freezed == title ? _self.title : title // ignore: cast_nullable_to_non_nullable
as String,description: freezed == description ? _self.description : description // ignore: cast_nullable_to_non_nullable as String?,description: freezed == description ? _self.description : description // ignore: cast_nullable_to_non_nullable
as String?,imageUrl: freezed == imageUrl ? _self.imageUrl : imageUrl // ignore: cast_nullable_to_non_nullable as String?,imageUrl: freezed == imageUrl ? _self.imageUrl : imageUrl // ignore: cast_nullable_to_non_nullable
as String?,faviconUrl: freezed == faviconUrl ? _self.faviconUrl : faviconUrl // ignore: cast_nullable_to_non_nullable as String?,faviconUrl: freezed == faviconUrl ? _self.faviconUrl : faviconUrl // ignore: cast_nullable_to_non_nullable
as String?,siteName: freezed == siteName ? _self.siteName : siteName // ignore: cast_nullable_to_non_nullable as String?,siteName: freezed == siteName ? _self.siteName : siteName // ignore: cast_nullable_to_non_nullable
@@ -159,7 +159,7 @@ return $default(_that);case _:
/// } /// }
/// ``` /// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( String type, String url, String title, String? description, String? imageUrl, String? faviconUrl, String? siteName, String? contentType, String? author, DateTime? publishedDate)? $default,{required TResult orElse(),}) {final _that = this; @optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( String type, String url, String? title, String? description, String? imageUrl, String? faviconUrl, String? siteName, String? contentType, String? author, DateTime? publishedDate)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) { switch (_that) {
case _SnScrappedLink() when $default != null: case _SnScrappedLink() when $default != null:
return $default(_that.type,_that.url,_that.title,_that.description,_that.imageUrl,_that.faviconUrl,_that.siteName,_that.contentType,_that.author,_that.publishedDate);case _: return $default(_that.type,_that.url,_that.title,_that.description,_that.imageUrl,_that.faviconUrl,_that.siteName,_that.contentType,_that.author,_that.publishedDate);case _:
@@ -180,7 +180,7 @@ return $default(_that.type,_that.url,_that.title,_that.description,_that.imageUr
/// } /// }
/// ``` /// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( String type, String url, String title, String? description, String? imageUrl, String? faviconUrl, String? siteName, String? contentType, String? author, DateTime? publishedDate) $default,) {final _that = this; @optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( String type, String url, String? title, String? description, String? imageUrl, String? faviconUrl, String? siteName, String? contentType, String? author, DateTime? publishedDate) $default,) {final _that = this;
switch (_that) { switch (_that) {
case _SnScrappedLink(): case _SnScrappedLink():
return $default(_that.type,_that.url,_that.title,_that.description,_that.imageUrl,_that.faviconUrl,_that.siteName,_that.contentType,_that.author,_that.publishedDate);} return $default(_that.type,_that.url,_that.title,_that.description,_that.imageUrl,_that.faviconUrl,_that.siteName,_that.contentType,_that.author,_that.publishedDate);}
@@ -197,7 +197,7 @@ return $default(_that.type,_that.url,_that.title,_that.description,_that.imageUr
/// } /// }
/// ``` /// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( String type, String url, String title, String? description, String? imageUrl, String? faviconUrl, String? siteName, String? contentType, String? author, DateTime? publishedDate)? $default,) {final _that = this; @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( String type, String url, String? title, String? description, String? imageUrl, String? faviconUrl, String? siteName, String? contentType, String? author, DateTime? publishedDate)? $default,) {final _that = this;
switch (_that) { switch (_that) {
case _SnScrappedLink() when $default != null: case _SnScrappedLink() when $default != null:
return $default(_that.type,_that.url,_that.title,_that.description,_that.imageUrl,_that.faviconUrl,_that.siteName,_that.contentType,_that.author,_that.publishedDate);case _: return $default(_that.type,_that.url,_that.title,_that.description,_that.imageUrl,_that.faviconUrl,_that.siteName,_that.contentType,_that.author,_that.publishedDate);case _:
@@ -217,7 +217,7 @@ class _SnScrappedLink implements SnScrappedLink {
@override final String type; @override final String type;
@override final String url; @override final String url;
@override final String title; @override final String? title;
@override final String? description; @override final String? description;
@override final String? imageUrl; @override final String? imageUrl;
@override final String? faviconUrl; @override final String? faviconUrl;
@@ -259,7 +259,7 @@ abstract mixin class _$SnScrappedLinkCopyWith<$Res> implements $SnScrappedLinkCo
factory _$SnScrappedLinkCopyWith(_SnScrappedLink value, $Res Function(_SnScrappedLink) _then) = __$SnScrappedLinkCopyWithImpl; factory _$SnScrappedLinkCopyWith(_SnScrappedLink value, $Res Function(_SnScrappedLink) _then) = __$SnScrappedLinkCopyWithImpl;
@override @useResult @override @useResult
$Res call({ $Res call({
String type, String url, String title, String? description, String? imageUrl, String? faviconUrl, String? siteName, String? contentType, String? author, DateTime? publishedDate String type, String url, String? title, String? description, String? imageUrl, String? faviconUrl, String? siteName, String? contentType, String? author, DateTime? publishedDate
}); });
@@ -276,12 +276,12 @@ class __$SnScrappedLinkCopyWithImpl<$Res>
/// Create a copy of SnScrappedLink /// Create a copy of SnScrappedLink
/// with the given fields replaced by the non-null parameter values. /// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? type = null,Object? url = null,Object? title = null,Object? description = freezed,Object? imageUrl = freezed,Object? faviconUrl = freezed,Object? siteName = freezed,Object? contentType = freezed,Object? author = freezed,Object? publishedDate = freezed,}) { @override @pragma('vm:prefer-inline') $Res call({Object? type = null,Object? url = null,Object? title = freezed,Object? description = freezed,Object? imageUrl = freezed,Object? faviconUrl = freezed,Object? siteName = freezed,Object? contentType = freezed,Object? author = freezed,Object? publishedDate = freezed,}) {
return _then(_SnScrappedLink( return _then(_SnScrappedLink(
type: null == type ? _self.type : type // ignore: cast_nullable_to_non_nullable type: null == type ? _self.type : type // ignore: cast_nullable_to_non_nullable
as String,url: null == url ? _self.url : url // ignore: cast_nullable_to_non_nullable as String,url: null == url ? _self.url : url // ignore: cast_nullable_to_non_nullable
as String,title: null == title ? _self.title : title // ignore: cast_nullable_to_non_nullable as String,title: freezed == title ? _self.title : title // ignore: cast_nullable_to_non_nullable
as String,description: freezed == description ? _self.description : description // ignore: cast_nullable_to_non_nullable as String?,description: freezed == description ? _self.description : description // ignore: cast_nullable_to_non_nullable
as String?,imageUrl: freezed == imageUrl ? _self.imageUrl : imageUrl // ignore: cast_nullable_to_non_nullable as String?,imageUrl: freezed == imageUrl ? _self.imageUrl : imageUrl // ignore: cast_nullable_to_non_nullable
as String?,faviconUrl: freezed == faviconUrl ? _self.faviconUrl : faviconUrl // ignore: cast_nullable_to_non_nullable as String?,faviconUrl: freezed == faviconUrl ? _self.faviconUrl : faviconUrl // ignore: cast_nullable_to_non_nullable
as String?,siteName: freezed == siteName ? _self.siteName : siteName // ignore: cast_nullable_to_non_nullable as String?,siteName: freezed == siteName ? _self.siteName : siteName // ignore: cast_nullable_to_non_nullable

View File

@@ -10,7 +10,7 @@ _SnScrappedLink _$SnScrappedLinkFromJson(Map<String, dynamic> json) =>
_SnScrappedLink( _SnScrappedLink(
type: json['type'] as String, type: json['type'] as String,
url: json['url'] as String, url: json['url'] as String,
title: json['title'] as String, title: json['title'] as String?,
description: json['description'] as String?, description: json['description'] as String?,
imageUrl: json['image_url'] as String?, imageUrl: json['image_url'] as String?,
faviconUrl: json['favicon_url'] as String?, faviconUrl: json['favicon_url'] as String?,

View File

@@ -37,6 +37,45 @@ sealed class UniversalFile with _$UniversalFile {
} }
} }
@freezed
sealed class SnFileReplica with _$SnFileReplica {
const factory SnFileReplica({
required String id,
required String objectId,
required String poolId,
required SnFilePool? pool,
required String storageId,
required int status,
required bool isPrimary,
required DateTime createdAt,
required DateTime updatedAt,
required DateTime? deletedAt,
}) = _SnFileReplica;
factory SnFileReplica.fromJson(Map<String, dynamic> json) =>
_$SnFileReplicaFromJson(json);
}
@freezed
sealed class SnCloudFileObject with _$SnCloudFileObject {
const factory SnCloudFileObject({
required String id,
required int size,
required Map<String, dynamic>? meta,
required String? mimeType,
required String? hash,
required bool hasCompression,
required bool hasThumbnail,
required List<SnFileReplica> fileReplicas,
required DateTime createdAt,
required DateTime updatedAt,
required DateTime? deletedAt,
}) = _SnCloudFileObject;
factory SnCloudFileObject.fromJson(Map<String, dynamic> json) =>
_$SnCloudFileObjectFromJson(json);
}
@freezed @freezed
sealed class SnCloudFile with _$SnCloudFile { sealed class SnCloudFile with _$SnCloudFile {
const factory SnCloudFile({ const factory SnCloudFile({
@@ -45,13 +84,11 @@ sealed class SnCloudFile with _$SnCloudFile {
required String? description, required String? description,
required Map<String, dynamic>? fileMeta, required Map<String, dynamic>? fileMeta,
required Map<String, dynamic>? userMeta, required Map<String, dynamic>? userMeta,
required SnFilePool? pool,
@Default([]) List<int> sensitiveMarks, @Default([]) List<int> sensitiveMarks,
required String? mimeType, required String? mimeType,
required String? hash, required String? hash,
required int size, required int size,
required DateTime? uploadedAt, required DateTime? uploadedAt,
required String? uploadedTo,
required DateTime createdAt, required DateTime createdAt,
required DateTime updatedAt, required DateTime updatedAt,
required DateTime? deletedAt, required DateTime? deletedAt,

View File

@@ -279,42 +279,42 @@ as String?,
/// @nodoc /// @nodoc
mixin _$SnCloudFile { mixin _$SnFileReplica {
String get id; String get name; String? get description; Map<String, dynamic>? get fileMeta; Map<String, dynamic>? get userMeta; SnFilePool? get pool; List<int> get sensitiveMarks; String? get mimeType; String? get hash; int get size; DateTime? get uploadedAt; String? get uploadedTo; DateTime get createdAt; DateTime get updatedAt; DateTime? get deletedAt; String? get url; String get id; String get objectId; String get poolId; SnFilePool? get pool; String get storageId; int get status; bool get isPrimary; DateTime get createdAt; DateTime get updatedAt; DateTime? get deletedAt;
/// Create a copy of SnCloudFile /// Create a copy of SnFileReplica
/// with the given fields replaced by the non-null parameter values. /// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false) @JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline') @pragma('vm:prefer-inline')
$SnCloudFileCopyWith<SnCloudFile> get copyWith => _$SnCloudFileCopyWithImpl<SnCloudFile>(this as SnCloudFile, _$identity); $SnFileReplicaCopyWith<SnFileReplica> get copyWith => _$SnFileReplicaCopyWithImpl<SnFileReplica>(this as SnFileReplica, _$identity);
/// Serializes this SnCloudFile to a JSON map. /// Serializes this SnFileReplica to a JSON map.
Map<String, dynamic> toJson(); Map<String, dynamic> toJson();
@override @override
bool operator ==(Object other) { bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is SnCloudFile&&(identical(other.id, id) || other.id == id)&&(identical(other.name, name) || other.name == name)&&(identical(other.description, description) || other.description == description)&&const DeepCollectionEquality().equals(other.fileMeta, fileMeta)&&const DeepCollectionEquality().equals(other.userMeta, userMeta)&&(identical(other.pool, pool) || other.pool == pool)&&const DeepCollectionEquality().equals(other.sensitiveMarks, sensitiveMarks)&&(identical(other.mimeType, mimeType) || other.mimeType == mimeType)&&(identical(other.hash, hash) || other.hash == hash)&&(identical(other.size, size) || other.size == size)&&(identical(other.uploadedAt, uploadedAt) || other.uploadedAt == uploadedAt)&&(identical(other.uploadedTo, uploadedTo) || other.uploadedTo == uploadedTo)&&(identical(other.createdAt, createdAt) || other.createdAt == createdAt)&&(identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)&&(identical(other.deletedAt, deletedAt) || other.deletedAt == deletedAt)&&(identical(other.url, url) || other.url == url)); return identical(this, other) || (other.runtimeType == runtimeType&&other is SnFileReplica&&(identical(other.id, id) || other.id == id)&&(identical(other.objectId, objectId) || other.objectId == objectId)&&(identical(other.poolId, poolId) || other.poolId == poolId)&&(identical(other.pool, pool) || other.pool == pool)&&(identical(other.storageId, storageId) || other.storageId == storageId)&&(identical(other.status, status) || other.status == status)&&(identical(other.isPrimary, isPrimary) || other.isPrimary == isPrimary)&&(identical(other.createdAt, createdAt) || other.createdAt == createdAt)&&(identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)&&(identical(other.deletedAt, deletedAt) || other.deletedAt == deletedAt));
} }
@JsonKey(includeFromJson: false, includeToJson: false) @JsonKey(includeFromJson: false, includeToJson: false)
@override @override
int get hashCode => Object.hash(runtimeType,id,name,description,const DeepCollectionEquality().hash(fileMeta),const DeepCollectionEquality().hash(userMeta),pool,const DeepCollectionEquality().hash(sensitiveMarks),mimeType,hash,size,uploadedAt,uploadedTo,createdAt,updatedAt,deletedAt,url); int get hashCode => Object.hash(runtimeType,id,objectId,poolId,pool,storageId,status,isPrimary,createdAt,updatedAt,deletedAt);
@override @override
String toString() { String toString() {
return 'SnCloudFile(id: $id, name: $name, description: $description, fileMeta: $fileMeta, userMeta: $userMeta, pool: $pool, sensitiveMarks: $sensitiveMarks, mimeType: $mimeType, hash: $hash, size: $size, uploadedAt: $uploadedAt, uploadedTo: $uploadedTo, createdAt: $createdAt, updatedAt: $updatedAt, deletedAt: $deletedAt, url: $url)'; return 'SnFileReplica(id: $id, objectId: $objectId, poolId: $poolId, pool: $pool, storageId: $storageId, status: $status, isPrimary: $isPrimary, createdAt: $createdAt, updatedAt: $updatedAt, deletedAt: $deletedAt)';
} }
} }
/// @nodoc /// @nodoc
abstract mixin class $SnCloudFileCopyWith<$Res> { abstract mixin class $SnFileReplicaCopyWith<$Res> {
factory $SnCloudFileCopyWith(SnCloudFile value, $Res Function(SnCloudFile) _then) = _$SnCloudFileCopyWithImpl; factory $SnFileReplicaCopyWith(SnFileReplica value, $Res Function(SnFileReplica) _then) = _$SnFileReplicaCopyWithImpl;
@useResult @useResult
$Res call({ $Res call({
String id, String name, String? description, Map<String, dynamic>? fileMeta, Map<String, dynamic>? userMeta, SnFilePool? pool, List<int> sensitiveMarks, String? mimeType, String? hash, int size, DateTime? uploadedAt, String? uploadedTo, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt, String? url String id, String objectId, String poolId, SnFilePool? pool, String storageId, int status, bool isPrimary, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt
}); });
@@ -322,37 +322,31 @@ $SnFilePoolCopyWith<$Res>? get pool;
} }
/// @nodoc /// @nodoc
class _$SnCloudFileCopyWithImpl<$Res> class _$SnFileReplicaCopyWithImpl<$Res>
implements $SnCloudFileCopyWith<$Res> { implements $SnFileReplicaCopyWith<$Res> {
_$SnCloudFileCopyWithImpl(this._self, this._then); _$SnFileReplicaCopyWithImpl(this._self, this._then);
final SnCloudFile _self; final SnFileReplica _self;
final $Res Function(SnCloudFile) _then; final $Res Function(SnFileReplica) _then;
/// Create a copy of SnCloudFile /// Create a copy of SnFileReplica
/// with the given fields replaced by the non-null parameter values. /// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? id = null,Object? name = null,Object? description = freezed,Object? fileMeta = freezed,Object? userMeta = freezed,Object? pool = freezed,Object? sensitiveMarks = null,Object? mimeType = freezed,Object? hash = freezed,Object? size = null,Object? uploadedAt = freezed,Object? uploadedTo = freezed,Object? createdAt = null,Object? updatedAt = null,Object? deletedAt = freezed,Object? url = freezed,}) { @pragma('vm:prefer-inline') @override $Res call({Object? id = null,Object? objectId = null,Object? poolId = null,Object? pool = freezed,Object? storageId = null,Object? status = null,Object? isPrimary = null,Object? createdAt = null,Object? updatedAt = null,Object? deletedAt = freezed,}) {
return _then(_self.copyWith( return _then(_self.copyWith(
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
as String,name: null == name ? _self.name : name // ignore: cast_nullable_to_non_nullable as String,objectId: null == objectId ? _self.objectId : objectId // ignore: cast_nullable_to_non_nullable
as String,description: freezed == description ? _self.description : description // ignore: cast_nullable_to_non_nullable as String,poolId: null == poolId ? _self.poolId : poolId // ignore: cast_nullable_to_non_nullable
as String?,fileMeta: freezed == fileMeta ? _self.fileMeta : fileMeta // ignore: cast_nullable_to_non_nullable as String,pool: freezed == pool ? _self.pool : pool // ignore: cast_nullable_to_non_nullable
as Map<String, dynamic>?,userMeta: freezed == userMeta ? _self.userMeta : userMeta // ignore: cast_nullable_to_non_nullable as SnFilePool?,storageId: null == storageId ? _self.storageId : storageId // ignore: cast_nullable_to_non_nullable
as Map<String, dynamic>?,pool: freezed == pool ? _self.pool : pool // ignore: cast_nullable_to_non_nullable as String,status: null == status ? _self.status : status // ignore: cast_nullable_to_non_nullable
as SnFilePool?,sensitiveMarks: null == sensitiveMarks ? _self.sensitiveMarks : sensitiveMarks // ignore: cast_nullable_to_non_nullable as int,isPrimary: null == isPrimary ? _self.isPrimary : isPrimary // ignore: cast_nullable_to_non_nullable
as List<int>,mimeType: freezed == mimeType ? _self.mimeType : mimeType // ignore: cast_nullable_to_non_nullable as bool,createdAt: null == createdAt ? _self.createdAt : createdAt // ignore: cast_nullable_to_non_nullable
as String?,hash: freezed == hash ? _self.hash : hash // ignore: cast_nullable_to_non_nullable
as String?,size: null == size ? _self.size : size // ignore: cast_nullable_to_non_nullable
as int,uploadedAt: freezed == uploadedAt ? _self.uploadedAt : uploadedAt // ignore: cast_nullable_to_non_nullable
as DateTime?,uploadedTo: freezed == uploadedTo ? _self.uploadedTo : uploadedTo // ignore: cast_nullable_to_non_nullable
as String?,createdAt: null == createdAt ? _self.createdAt : createdAt // ignore: cast_nullable_to_non_nullable
as DateTime,updatedAt: null == updatedAt ? _self.updatedAt : updatedAt // ignore: cast_nullable_to_non_nullable as DateTime,updatedAt: null == updatedAt ? _self.updatedAt : updatedAt // ignore: cast_nullable_to_non_nullable
as DateTime,deletedAt: freezed == deletedAt ? _self.deletedAt : deletedAt // ignore: cast_nullable_to_non_nullable as DateTime,deletedAt: freezed == deletedAt ? _self.deletedAt : deletedAt // ignore: cast_nullable_to_non_nullable
as DateTime?,url: freezed == url ? _self.url : url // ignore: cast_nullable_to_non_nullable as DateTime?,
as String?,
)); ));
} }
/// Create a copy of SnCloudFile /// Create a copy of SnFileReplica
/// with the given fields replaced by the non-null parameter values. /// with the given fields replaced by the non-null parameter values.
@override @override
@pragma('vm:prefer-inline') @pragma('vm:prefer-inline')
@@ -368,6 +362,607 @@ $SnFilePoolCopyWith<$Res>? get pool {
} }
/// Adds pattern-matching-related methods to [SnFileReplica].
extension SnFileReplicaPatterns on SnFileReplica {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeMap<TResult extends Object?>(TResult Function( _SnFileReplica value)? $default,{required TResult orElse(),}){
final _that = this;
switch (_that) {
case _SnFileReplica() when $default != null:
return $default(_that);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult map<TResult extends Object?>(TResult Function( _SnFileReplica value) $default,){
final _that = this;
switch (_that) {
case _SnFileReplica():
return $default(_that);}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? mapOrNull<TResult extends Object?>(TResult? Function( _SnFileReplica value)? $default,){
final _that = this;
switch (_that) {
case _SnFileReplica() when $default != null:
return $default(_that);case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( String id, String objectId, String poolId, SnFilePool? pool, String storageId, int status, bool isPrimary, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) {
case _SnFileReplica() when $default != null:
return $default(_that.id,_that.objectId,_that.poolId,_that.pool,_that.storageId,_that.status,_that.isPrimary,_that.createdAt,_that.updatedAt,_that.deletedAt);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( String id, String objectId, String poolId, SnFilePool? pool, String storageId, int status, bool isPrimary, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt) $default,) {final _that = this;
switch (_that) {
case _SnFileReplica():
return $default(_that.id,_that.objectId,_that.poolId,_that.pool,_that.storageId,_that.status,_that.isPrimary,_that.createdAt,_that.updatedAt,_that.deletedAt);}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( String id, String objectId, String poolId, SnFilePool? pool, String storageId, int status, bool isPrimary, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt)? $default,) {final _that = this;
switch (_that) {
case _SnFileReplica() when $default != null:
return $default(_that.id,_that.objectId,_that.poolId,_that.pool,_that.storageId,_that.status,_that.isPrimary,_that.createdAt,_that.updatedAt,_that.deletedAt);case _:
return null;
}
}
}
/// @nodoc
@JsonSerializable()
class _SnFileReplica implements SnFileReplica {
const _SnFileReplica({required this.id, required this.objectId, required this.poolId, required this.pool, required this.storageId, required this.status, required this.isPrimary, required this.createdAt, required this.updatedAt, required this.deletedAt});
factory _SnFileReplica.fromJson(Map<String, dynamic> json) => _$SnFileReplicaFromJson(json);
@override final String id;
@override final String objectId;
@override final String poolId;
@override final SnFilePool? pool;
@override final String storageId;
@override final int status;
@override final bool isPrimary;
@override final DateTime createdAt;
@override final DateTime updatedAt;
@override final DateTime? deletedAt;
/// Create a copy of SnFileReplica
/// with the given fields replaced by the non-null parameter values.
@override @JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$SnFileReplicaCopyWith<_SnFileReplica> get copyWith => __$SnFileReplicaCopyWithImpl<_SnFileReplica>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$SnFileReplicaToJson(this, );
}
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _SnFileReplica&&(identical(other.id, id) || other.id == id)&&(identical(other.objectId, objectId) || other.objectId == objectId)&&(identical(other.poolId, poolId) || other.poolId == poolId)&&(identical(other.pool, pool) || other.pool == pool)&&(identical(other.storageId, storageId) || other.storageId == storageId)&&(identical(other.status, status) || other.status == status)&&(identical(other.isPrimary, isPrimary) || other.isPrimary == isPrimary)&&(identical(other.createdAt, createdAt) || other.createdAt == createdAt)&&(identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)&&(identical(other.deletedAt, deletedAt) || other.deletedAt == deletedAt));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,id,objectId,poolId,pool,storageId,status,isPrimary,createdAt,updatedAt,deletedAt);
@override
String toString() {
return 'SnFileReplica(id: $id, objectId: $objectId, poolId: $poolId, pool: $pool, storageId: $storageId, status: $status, isPrimary: $isPrimary, createdAt: $createdAt, updatedAt: $updatedAt, deletedAt: $deletedAt)';
}
}
/// @nodoc
abstract mixin class _$SnFileReplicaCopyWith<$Res> implements $SnFileReplicaCopyWith<$Res> {
factory _$SnFileReplicaCopyWith(_SnFileReplica value, $Res Function(_SnFileReplica) _then) = __$SnFileReplicaCopyWithImpl;
@override @useResult
$Res call({
String id, String objectId, String poolId, SnFilePool? pool, String storageId, int status, bool isPrimary, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt
});
@override $SnFilePoolCopyWith<$Res>? get pool;
}
/// @nodoc
class __$SnFileReplicaCopyWithImpl<$Res>
implements _$SnFileReplicaCopyWith<$Res> {
__$SnFileReplicaCopyWithImpl(this._self, this._then);
final _SnFileReplica _self;
final $Res Function(_SnFileReplica) _then;
/// Create a copy of SnFileReplica
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? id = null,Object? objectId = null,Object? poolId = null,Object? pool = freezed,Object? storageId = null,Object? status = null,Object? isPrimary = null,Object? createdAt = null,Object? updatedAt = null,Object? deletedAt = freezed,}) {
return _then(_SnFileReplica(
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
as String,objectId: null == objectId ? _self.objectId : objectId // ignore: cast_nullable_to_non_nullable
as String,poolId: null == poolId ? _self.poolId : poolId // ignore: cast_nullable_to_non_nullable
as String,pool: freezed == pool ? _self.pool : pool // ignore: cast_nullable_to_non_nullable
as SnFilePool?,storageId: null == storageId ? _self.storageId : storageId // ignore: cast_nullable_to_non_nullable
as String,status: null == status ? _self.status : status // ignore: cast_nullable_to_non_nullable
as int,isPrimary: null == isPrimary ? _self.isPrimary : isPrimary // ignore: cast_nullable_to_non_nullable
as bool,createdAt: null == createdAt ? _self.createdAt : createdAt // ignore: cast_nullable_to_non_nullable
as DateTime,updatedAt: null == updatedAt ? _self.updatedAt : updatedAt // ignore: cast_nullable_to_non_nullable
as DateTime,deletedAt: freezed == deletedAt ? _self.deletedAt : deletedAt // ignore: cast_nullable_to_non_nullable
as DateTime?,
));
}
/// Create a copy of SnFileReplica
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$SnFilePoolCopyWith<$Res>? get pool {
if (_self.pool == null) {
return null;
}
return $SnFilePoolCopyWith<$Res>(_self.pool!, (value) {
return _then(_self.copyWith(pool: value));
});
}
}
/// @nodoc
mixin _$SnCloudFileObject {
String get id; int get size; Map<String, dynamic>? get meta; String? get mimeType; String? get hash; bool get hasCompression; bool get hasThumbnail; List<SnFileReplica> get fileReplicas; DateTime get createdAt; DateTime get updatedAt; DateTime? get deletedAt;
/// Create a copy of SnCloudFileObject
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$SnCloudFileObjectCopyWith<SnCloudFileObject> get copyWith => _$SnCloudFileObjectCopyWithImpl<SnCloudFileObject>(this as SnCloudFileObject, _$identity);
/// Serializes this SnCloudFileObject to a JSON map.
Map<String, dynamic> toJson();
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is SnCloudFileObject&&(identical(other.id, id) || other.id == id)&&(identical(other.size, size) || other.size == size)&&const DeepCollectionEquality().equals(other.meta, meta)&&(identical(other.mimeType, mimeType) || other.mimeType == mimeType)&&(identical(other.hash, hash) || other.hash == hash)&&(identical(other.hasCompression, hasCompression) || other.hasCompression == hasCompression)&&(identical(other.hasThumbnail, hasThumbnail) || other.hasThumbnail == hasThumbnail)&&const DeepCollectionEquality().equals(other.fileReplicas, fileReplicas)&&(identical(other.createdAt, createdAt) || other.createdAt == createdAt)&&(identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)&&(identical(other.deletedAt, deletedAt) || other.deletedAt == deletedAt));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,id,size,const DeepCollectionEquality().hash(meta),mimeType,hash,hasCompression,hasThumbnail,const DeepCollectionEquality().hash(fileReplicas),createdAt,updatedAt,deletedAt);
@override
String toString() {
return 'SnCloudFileObject(id: $id, size: $size, meta: $meta, mimeType: $mimeType, hash: $hash, hasCompression: $hasCompression, hasThumbnail: $hasThumbnail, fileReplicas: $fileReplicas, createdAt: $createdAt, updatedAt: $updatedAt, deletedAt: $deletedAt)';
}
}
/// @nodoc
abstract mixin class $SnCloudFileObjectCopyWith<$Res> {
factory $SnCloudFileObjectCopyWith(SnCloudFileObject value, $Res Function(SnCloudFileObject) _then) = _$SnCloudFileObjectCopyWithImpl;
@useResult
$Res call({
String id, int size, Map<String, dynamic>? meta, String? mimeType, String? hash, bool hasCompression, bool hasThumbnail, List<SnFileReplica> fileReplicas, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt
});
}
/// @nodoc
class _$SnCloudFileObjectCopyWithImpl<$Res>
implements $SnCloudFileObjectCopyWith<$Res> {
_$SnCloudFileObjectCopyWithImpl(this._self, this._then);
final SnCloudFileObject _self;
final $Res Function(SnCloudFileObject) _then;
/// Create a copy of SnCloudFileObject
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? id = null,Object? size = null,Object? meta = freezed,Object? mimeType = freezed,Object? hash = freezed,Object? hasCompression = null,Object? hasThumbnail = null,Object? fileReplicas = null,Object? createdAt = null,Object? updatedAt = null,Object? deletedAt = freezed,}) {
return _then(_self.copyWith(
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
as String,size: null == size ? _self.size : size // ignore: cast_nullable_to_non_nullable
as int,meta: freezed == meta ? _self.meta : meta // ignore: cast_nullable_to_non_nullable
as Map<String, dynamic>?,mimeType: freezed == mimeType ? _self.mimeType : mimeType // ignore: cast_nullable_to_non_nullable
as String?,hash: freezed == hash ? _self.hash : hash // ignore: cast_nullable_to_non_nullable
as String?,hasCompression: null == hasCompression ? _self.hasCompression : hasCompression // ignore: cast_nullable_to_non_nullable
as bool,hasThumbnail: null == hasThumbnail ? _self.hasThumbnail : hasThumbnail // ignore: cast_nullable_to_non_nullable
as bool,fileReplicas: null == fileReplicas ? _self.fileReplicas : fileReplicas // ignore: cast_nullable_to_non_nullable
as List<SnFileReplica>,createdAt: null == createdAt ? _self.createdAt : createdAt // ignore: cast_nullable_to_non_nullable
as DateTime,updatedAt: null == updatedAt ? _self.updatedAt : updatedAt // ignore: cast_nullable_to_non_nullable
as DateTime,deletedAt: freezed == deletedAt ? _self.deletedAt : deletedAt // ignore: cast_nullable_to_non_nullable
as DateTime?,
));
}
}
/// Adds pattern-matching-related methods to [SnCloudFileObject].
extension SnCloudFileObjectPatterns on SnCloudFileObject {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeMap<TResult extends Object?>(TResult Function( _SnCloudFileObject value)? $default,{required TResult orElse(),}){
final _that = this;
switch (_that) {
case _SnCloudFileObject() when $default != null:
return $default(_that);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult map<TResult extends Object?>(TResult Function( _SnCloudFileObject value) $default,){
final _that = this;
switch (_that) {
case _SnCloudFileObject():
return $default(_that);}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? mapOrNull<TResult extends Object?>(TResult? Function( _SnCloudFileObject value)? $default,){
final _that = this;
switch (_that) {
case _SnCloudFileObject() when $default != null:
return $default(_that);case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( String id, int size, Map<String, dynamic>? meta, String? mimeType, String? hash, bool hasCompression, bool hasThumbnail, List<SnFileReplica> fileReplicas, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) {
case _SnCloudFileObject() when $default != null:
return $default(_that.id,_that.size,_that.meta,_that.mimeType,_that.hash,_that.hasCompression,_that.hasThumbnail,_that.fileReplicas,_that.createdAt,_that.updatedAt,_that.deletedAt);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( String id, int size, Map<String, dynamic>? meta, String? mimeType, String? hash, bool hasCompression, bool hasThumbnail, List<SnFileReplica> fileReplicas, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt) $default,) {final _that = this;
switch (_that) {
case _SnCloudFileObject():
return $default(_that.id,_that.size,_that.meta,_that.mimeType,_that.hash,_that.hasCompression,_that.hasThumbnail,_that.fileReplicas,_that.createdAt,_that.updatedAt,_that.deletedAt);}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( String id, int size, Map<String, dynamic>? meta, String? mimeType, String? hash, bool hasCompression, bool hasThumbnail, List<SnFileReplica> fileReplicas, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt)? $default,) {final _that = this;
switch (_that) {
case _SnCloudFileObject() when $default != null:
return $default(_that.id,_that.size,_that.meta,_that.mimeType,_that.hash,_that.hasCompression,_that.hasThumbnail,_that.fileReplicas,_that.createdAt,_that.updatedAt,_that.deletedAt);case _:
return null;
}
}
}
/// @nodoc
@JsonSerializable()
class _SnCloudFileObject implements SnCloudFileObject {
const _SnCloudFileObject({required this.id, required this.size, required final Map<String, dynamic>? meta, required this.mimeType, required this.hash, required this.hasCompression, required this.hasThumbnail, required final List<SnFileReplica> fileReplicas, required this.createdAt, required this.updatedAt, required this.deletedAt}): _meta = meta,_fileReplicas = fileReplicas;
factory _SnCloudFileObject.fromJson(Map<String, dynamic> json) => _$SnCloudFileObjectFromJson(json);
@override final String id;
@override final int size;
final Map<String, dynamic>? _meta;
@override Map<String, dynamic>? get meta {
final value = _meta;
if (value == null) return null;
if (_meta is EqualUnmodifiableMapView) return _meta;
// ignore: implicit_dynamic_type
return EqualUnmodifiableMapView(value);
}
@override final String? mimeType;
@override final String? hash;
@override final bool hasCompression;
@override final bool hasThumbnail;
final List<SnFileReplica> _fileReplicas;
@override List<SnFileReplica> get fileReplicas {
if (_fileReplicas is EqualUnmodifiableListView) return _fileReplicas;
// ignore: implicit_dynamic_type
return EqualUnmodifiableListView(_fileReplicas);
}
@override final DateTime createdAt;
@override final DateTime updatedAt;
@override final DateTime? deletedAt;
/// Create a copy of SnCloudFileObject
/// with the given fields replaced by the non-null parameter values.
@override @JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$SnCloudFileObjectCopyWith<_SnCloudFileObject> get copyWith => __$SnCloudFileObjectCopyWithImpl<_SnCloudFileObject>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$SnCloudFileObjectToJson(this, );
}
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _SnCloudFileObject&&(identical(other.id, id) || other.id == id)&&(identical(other.size, size) || other.size == size)&&const DeepCollectionEquality().equals(other._meta, _meta)&&(identical(other.mimeType, mimeType) || other.mimeType == mimeType)&&(identical(other.hash, hash) || other.hash == hash)&&(identical(other.hasCompression, hasCompression) || other.hasCompression == hasCompression)&&(identical(other.hasThumbnail, hasThumbnail) || other.hasThumbnail == hasThumbnail)&&const DeepCollectionEquality().equals(other._fileReplicas, _fileReplicas)&&(identical(other.createdAt, createdAt) || other.createdAt == createdAt)&&(identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)&&(identical(other.deletedAt, deletedAt) || other.deletedAt == deletedAt));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,id,size,const DeepCollectionEquality().hash(_meta),mimeType,hash,hasCompression,hasThumbnail,const DeepCollectionEquality().hash(_fileReplicas),createdAt,updatedAt,deletedAt);
@override
String toString() {
return 'SnCloudFileObject(id: $id, size: $size, meta: $meta, mimeType: $mimeType, hash: $hash, hasCompression: $hasCompression, hasThumbnail: $hasThumbnail, fileReplicas: $fileReplicas, createdAt: $createdAt, updatedAt: $updatedAt, deletedAt: $deletedAt)';
}
}
/// @nodoc
abstract mixin class _$SnCloudFileObjectCopyWith<$Res> implements $SnCloudFileObjectCopyWith<$Res> {
factory _$SnCloudFileObjectCopyWith(_SnCloudFileObject value, $Res Function(_SnCloudFileObject) _then) = __$SnCloudFileObjectCopyWithImpl;
@override @useResult
$Res call({
String id, int size, Map<String, dynamic>? meta, String? mimeType, String? hash, bool hasCompression, bool hasThumbnail, List<SnFileReplica> fileReplicas, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt
});
}
/// @nodoc
class __$SnCloudFileObjectCopyWithImpl<$Res>
implements _$SnCloudFileObjectCopyWith<$Res> {
__$SnCloudFileObjectCopyWithImpl(this._self, this._then);
final _SnCloudFileObject _self;
final $Res Function(_SnCloudFileObject) _then;
/// Create a copy of SnCloudFileObject
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? id = null,Object? size = null,Object? meta = freezed,Object? mimeType = freezed,Object? hash = freezed,Object? hasCompression = null,Object? hasThumbnail = null,Object? fileReplicas = null,Object? createdAt = null,Object? updatedAt = null,Object? deletedAt = freezed,}) {
return _then(_SnCloudFileObject(
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
as String,size: null == size ? _self.size : size // ignore: cast_nullable_to_non_nullable
as int,meta: freezed == meta ? _self._meta : meta // ignore: cast_nullable_to_non_nullable
as Map<String, dynamic>?,mimeType: freezed == mimeType ? _self.mimeType : mimeType // ignore: cast_nullable_to_non_nullable
as String?,hash: freezed == hash ? _self.hash : hash // ignore: cast_nullable_to_non_nullable
as String?,hasCompression: null == hasCompression ? _self.hasCompression : hasCompression // ignore: cast_nullable_to_non_nullable
as bool,hasThumbnail: null == hasThumbnail ? _self.hasThumbnail : hasThumbnail // ignore: cast_nullable_to_non_nullable
as bool,fileReplicas: null == fileReplicas ? _self._fileReplicas : fileReplicas // ignore: cast_nullable_to_non_nullable
as List<SnFileReplica>,createdAt: null == createdAt ? _self.createdAt : createdAt // ignore: cast_nullable_to_non_nullable
as DateTime,updatedAt: null == updatedAt ? _self.updatedAt : updatedAt // ignore: cast_nullable_to_non_nullable
as DateTime,deletedAt: freezed == deletedAt ? _self.deletedAt : deletedAt // ignore: cast_nullable_to_non_nullable
as DateTime?,
));
}
}
/// @nodoc
mixin _$SnCloudFile {
String get id; String get name; String? get description; Map<String, dynamic>? get fileMeta; Map<String, dynamic>? get userMeta; List<int> get sensitiveMarks; String? get mimeType; String? get hash; int get size; DateTime? get uploadedAt; DateTime get createdAt; DateTime get updatedAt; DateTime? get deletedAt; String? get url;
/// Create a copy of SnCloudFile
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$SnCloudFileCopyWith<SnCloudFile> get copyWith => _$SnCloudFileCopyWithImpl<SnCloudFile>(this as SnCloudFile, _$identity);
/// Serializes this SnCloudFile to a JSON map.
Map<String, dynamic> toJson();
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is SnCloudFile&&(identical(other.id, id) || other.id == id)&&(identical(other.name, name) || other.name == name)&&(identical(other.description, description) || other.description == description)&&const DeepCollectionEquality().equals(other.fileMeta, fileMeta)&&const DeepCollectionEquality().equals(other.userMeta, userMeta)&&const DeepCollectionEquality().equals(other.sensitiveMarks, sensitiveMarks)&&(identical(other.mimeType, mimeType) || other.mimeType == mimeType)&&(identical(other.hash, hash) || other.hash == hash)&&(identical(other.size, size) || other.size == size)&&(identical(other.uploadedAt, uploadedAt) || other.uploadedAt == uploadedAt)&&(identical(other.createdAt, createdAt) || other.createdAt == createdAt)&&(identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)&&(identical(other.deletedAt, deletedAt) || other.deletedAt == deletedAt)&&(identical(other.url, url) || other.url == url));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,id,name,description,const DeepCollectionEquality().hash(fileMeta),const DeepCollectionEquality().hash(userMeta),const DeepCollectionEquality().hash(sensitiveMarks),mimeType,hash,size,uploadedAt,createdAt,updatedAt,deletedAt,url);
@override
String toString() {
return 'SnCloudFile(id: $id, name: $name, description: $description, fileMeta: $fileMeta, userMeta: $userMeta, sensitiveMarks: $sensitiveMarks, mimeType: $mimeType, hash: $hash, size: $size, uploadedAt: $uploadedAt, createdAt: $createdAt, updatedAt: $updatedAt, deletedAt: $deletedAt, url: $url)';
}
}
/// @nodoc
abstract mixin class $SnCloudFileCopyWith<$Res> {
factory $SnCloudFileCopyWith(SnCloudFile value, $Res Function(SnCloudFile) _then) = _$SnCloudFileCopyWithImpl;
@useResult
$Res call({
String id, String name, String? description, Map<String, dynamic>? fileMeta, Map<String, dynamic>? userMeta, List<int> sensitiveMarks, String? mimeType, String? hash, int size, DateTime? uploadedAt, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt, String? url
});
}
/// @nodoc
class _$SnCloudFileCopyWithImpl<$Res>
implements $SnCloudFileCopyWith<$Res> {
_$SnCloudFileCopyWithImpl(this._self, this._then);
final SnCloudFile _self;
final $Res Function(SnCloudFile) _then;
/// Create a copy of SnCloudFile
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? id = null,Object? name = null,Object? description = freezed,Object? fileMeta = freezed,Object? userMeta = freezed,Object? sensitiveMarks = null,Object? mimeType = freezed,Object? hash = freezed,Object? size = null,Object? uploadedAt = freezed,Object? createdAt = null,Object? updatedAt = null,Object? deletedAt = freezed,Object? url = freezed,}) {
return _then(_self.copyWith(
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
as String,name: null == name ? _self.name : name // ignore: cast_nullable_to_non_nullable
as String,description: freezed == description ? _self.description : description // ignore: cast_nullable_to_non_nullable
as String?,fileMeta: freezed == fileMeta ? _self.fileMeta : fileMeta // ignore: cast_nullable_to_non_nullable
as Map<String, dynamic>?,userMeta: freezed == userMeta ? _self.userMeta : userMeta // ignore: cast_nullable_to_non_nullable
as Map<String, dynamic>?,sensitiveMarks: null == sensitiveMarks ? _self.sensitiveMarks : sensitiveMarks // ignore: cast_nullable_to_non_nullable
as List<int>,mimeType: freezed == mimeType ? _self.mimeType : mimeType // ignore: cast_nullable_to_non_nullable
as String?,hash: freezed == hash ? _self.hash : hash // ignore: cast_nullable_to_non_nullable
as String?,size: null == size ? _self.size : size // ignore: cast_nullable_to_non_nullable
as int,uploadedAt: freezed == uploadedAt ? _self.uploadedAt : uploadedAt // ignore: cast_nullable_to_non_nullable
as DateTime?,createdAt: null == createdAt ? _self.createdAt : createdAt // ignore: cast_nullable_to_non_nullable
as DateTime,updatedAt: null == updatedAt ? _self.updatedAt : updatedAt // ignore: cast_nullable_to_non_nullable
as DateTime,deletedAt: freezed == deletedAt ? _self.deletedAt : deletedAt // ignore: cast_nullable_to_non_nullable
as DateTime?,url: freezed == url ? _self.url : url // ignore: cast_nullable_to_non_nullable
as String?,
));
}
}
/// Adds pattern-matching-related methods to [SnCloudFile]. /// Adds pattern-matching-related methods to [SnCloudFile].
extension SnCloudFilePatterns on SnCloudFile { extension SnCloudFilePatterns on SnCloudFile {
/// A variant of `map` that fallback to returning `orElse`. /// A variant of `map` that fallback to returning `orElse`.
@@ -443,10 +1038,10 @@ return $default(_that);case _:
/// } /// }
/// ``` /// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( String id, String name, String? description, Map<String, dynamic>? fileMeta, Map<String, dynamic>? userMeta, SnFilePool? pool, List<int> sensitiveMarks, String? mimeType, String? hash, int size, DateTime? uploadedAt, String? uploadedTo, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt, String? url)? $default,{required TResult orElse(),}) {final _that = this; @optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( String id, String name, String? description, Map<String, dynamic>? fileMeta, Map<String, dynamic>? userMeta, List<int> sensitiveMarks, String? mimeType, String? hash, int size, DateTime? uploadedAt, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt, String? url)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) { switch (_that) {
case _SnCloudFile() when $default != null: case _SnCloudFile() when $default != null:
return $default(_that.id,_that.name,_that.description,_that.fileMeta,_that.userMeta,_that.pool,_that.sensitiveMarks,_that.mimeType,_that.hash,_that.size,_that.uploadedAt,_that.uploadedTo,_that.createdAt,_that.updatedAt,_that.deletedAt,_that.url);case _: return $default(_that.id,_that.name,_that.description,_that.fileMeta,_that.userMeta,_that.sensitiveMarks,_that.mimeType,_that.hash,_that.size,_that.uploadedAt,_that.createdAt,_that.updatedAt,_that.deletedAt,_that.url);case _:
return orElse(); return orElse();
} }
@@ -464,10 +1059,10 @@ return $default(_that.id,_that.name,_that.description,_that.fileMeta,_that.userM
/// } /// }
/// ``` /// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( String id, String name, String? description, Map<String, dynamic>? fileMeta, Map<String, dynamic>? userMeta, SnFilePool? pool, List<int> sensitiveMarks, String? mimeType, String? hash, int size, DateTime? uploadedAt, String? uploadedTo, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt, String? url) $default,) {final _that = this; @optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( String id, String name, String? description, Map<String, dynamic>? fileMeta, Map<String, dynamic>? userMeta, List<int> sensitiveMarks, String? mimeType, String? hash, int size, DateTime? uploadedAt, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt, String? url) $default,) {final _that = this;
switch (_that) { switch (_that) {
case _SnCloudFile(): case _SnCloudFile():
return $default(_that.id,_that.name,_that.description,_that.fileMeta,_that.userMeta,_that.pool,_that.sensitiveMarks,_that.mimeType,_that.hash,_that.size,_that.uploadedAt,_that.uploadedTo,_that.createdAt,_that.updatedAt,_that.deletedAt,_that.url);} return $default(_that.id,_that.name,_that.description,_that.fileMeta,_that.userMeta,_that.sensitiveMarks,_that.mimeType,_that.hash,_that.size,_that.uploadedAt,_that.createdAt,_that.updatedAt,_that.deletedAt,_that.url);}
} }
/// A variant of `when` that fallback to returning `null` /// A variant of `when` that fallback to returning `null`
/// ///
@@ -481,10 +1076,10 @@ return $default(_that.id,_that.name,_that.description,_that.fileMeta,_that.userM
/// } /// }
/// ``` /// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( String id, String name, String? description, Map<String, dynamic>? fileMeta, Map<String, dynamic>? userMeta, SnFilePool? pool, List<int> sensitiveMarks, String? mimeType, String? hash, int size, DateTime? uploadedAt, String? uploadedTo, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt, String? url)? $default,) {final _that = this; @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( String id, String name, String? description, Map<String, dynamic>? fileMeta, Map<String, dynamic>? userMeta, List<int> sensitiveMarks, String? mimeType, String? hash, int size, DateTime? uploadedAt, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt, String? url)? $default,) {final _that = this;
switch (_that) { switch (_that) {
case _SnCloudFile() when $default != null: case _SnCloudFile() when $default != null:
return $default(_that.id,_that.name,_that.description,_that.fileMeta,_that.userMeta,_that.pool,_that.sensitiveMarks,_that.mimeType,_that.hash,_that.size,_that.uploadedAt,_that.uploadedTo,_that.createdAt,_that.updatedAt,_that.deletedAt,_that.url);case _: return $default(_that.id,_that.name,_that.description,_that.fileMeta,_that.userMeta,_that.sensitiveMarks,_that.mimeType,_that.hash,_that.size,_that.uploadedAt,_that.createdAt,_that.updatedAt,_that.deletedAt,_that.url);case _:
return null; return null;
} }
@@ -496,7 +1091,7 @@ return $default(_that.id,_that.name,_that.description,_that.fileMeta,_that.userM
@JsonSerializable() @JsonSerializable()
class _SnCloudFile implements SnCloudFile { class _SnCloudFile implements SnCloudFile {
const _SnCloudFile({required this.id, required this.name, required this.description, required final Map<String, dynamic>? fileMeta, required final Map<String, dynamic>? userMeta, required this.pool, final List<int> sensitiveMarks = const [], required this.mimeType, required this.hash, required this.size, required this.uploadedAt, required this.uploadedTo, required this.createdAt, required this.updatedAt, required this.deletedAt, this.url}): _fileMeta = fileMeta,_userMeta = userMeta,_sensitiveMarks = sensitiveMarks; const _SnCloudFile({required this.id, required this.name, required this.description, required final Map<String, dynamic>? fileMeta, required final Map<String, dynamic>? userMeta, final List<int> sensitiveMarks = const [], required this.mimeType, required this.hash, required this.size, required this.uploadedAt, required this.createdAt, required this.updatedAt, required this.deletedAt, this.url}): _fileMeta = fileMeta,_userMeta = userMeta,_sensitiveMarks = sensitiveMarks;
factory _SnCloudFile.fromJson(Map<String, dynamic> json) => _$SnCloudFileFromJson(json); factory _SnCloudFile.fromJson(Map<String, dynamic> json) => _$SnCloudFileFromJson(json);
@override final String id; @override final String id;
@@ -520,7 +1115,6 @@ class _SnCloudFile implements SnCloudFile {
return EqualUnmodifiableMapView(value); return EqualUnmodifiableMapView(value);
} }
@override final SnFilePool? pool;
final List<int> _sensitiveMarks; final List<int> _sensitiveMarks;
@override@JsonKey() List<int> get sensitiveMarks { @override@JsonKey() List<int> get sensitiveMarks {
if (_sensitiveMarks is EqualUnmodifiableListView) return _sensitiveMarks; if (_sensitiveMarks is EqualUnmodifiableListView) return _sensitiveMarks;
@@ -532,7 +1126,6 @@ class _SnCloudFile implements SnCloudFile {
@override final String? hash; @override final String? hash;
@override final int size; @override final int size;
@override final DateTime? uploadedAt; @override final DateTime? uploadedAt;
@override final String? uploadedTo;
@override final DateTime createdAt; @override final DateTime createdAt;
@override final DateTime updatedAt; @override final DateTime updatedAt;
@override final DateTime? deletedAt; @override final DateTime? deletedAt;
@@ -551,16 +1144,16 @@ Map<String, dynamic> toJson() {
@override @override
bool operator ==(Object other) { bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _SnCloudFile&&(identical(other.id, id) || other.id == id)&&(identical(other.name, name) || other.name == name)&&(identical(other.description, description) || other.description == description)&&const DeepCollectionEquality().equals(other._fileMeta, _fileMeta)&&const DeepCollectionEquality().equals(other._userMeta, _userMeta)&&(identical(other.pool, pool) || other.pool == pool)&&const DeepCollectionEquality().equals(other._sensitiveMarks, _sensitiveMarks)&&(identical(other.mimeType, mimeType) || other.mimeType == mimeType)&&(identical(other.hash, hash) || other.hash == hash)&&(identical(other.size, size) || other.size == size)&&(identical(other.uploadedAt, uploadedAt) || other.uploadedAt == uploadedAt)&&(identical(other.uploadedTo, uploadedTo) || other.uploadedTo == uploadedTo)&&(identical(other.createdAt, createdAt) || other.createdAt == createdAt)&&(identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)&&(identical(other.deletedAt, deletedAt) || other.deletedAt == deletedAt)&&(identical(other.url, url) || other.url == url)); return identical(this, other) || (other.runtimeType == runtimeType&&other is _SnCloudFile&&(identical(other.id, id) || other.id == id)&&(identical(other.name, name) || other.name == name)&&(identical(other.description, description) || other.description == description)&&const DeepCollectionEquality().equals(other._fileMeta, _fileMeta)&&const DeepCollectionEquality().equals(other._userMeta, _userMeta)&&const DeepCollectionEquality().equals(other._sensitiveMarks, _sensitiveMarks)&&(identical(other.mimeType, mimeType) || other.mimeType == mimeType)&&(identical(other.hash, hash) || other.hash == hash)&&(identical(other.size, size) || other.size == size)&&(identical(other.uploadedAt, uploadedAt) || other.uploadedAt == uploadedAt)&&(identical(other.createdAt, createdAt) || other.createdAt == createdAt)&&(identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)&&(identical(other.deletedAt, deletedAt) || other.deletedAt == deletedAt)&&(identical(other.url, url) || other.url == url));
} }
@JsonKey(includeFromJson: false, includeToJson: false) @JsonKey(includeFromJson: false, includeToJson: false)
@override @override
int get hashCode => Object.hash(runtimeType,id,name,description,const DeepCollectionEquality().hash(_fileMeta),const DeepCollectionEquality().hash(_userMeta),pool,const DeepCollectionEquality().hash(_sensitiveMarks),mimeType,hash,size,uploadedAt,uploadedTo,createdAt,updatedAt,deletedAt,url); int get hashCode => Object.hash(runtimeType,id,name,description,const DeepCollectionEquality().hash(_fileMeta),const DeepCollectionEquality().hash(_userMeta),const DeepCollectionEquality().hash(_sensitiveMarks),mimeType,hash,size,uploadedAt,createdAt,updatedAt,deletedAt,url);
@override @override
String toString() { String toString() {
return 'SnCloudFile(id: $id, name: $name, description: $description, fileMeta: $fileMeta, userMeta: $userMeta, pool: $pool, sensitiveMarks: $sensitiveMarks, mimeType: $mimeType, hash: $hash, size: $size, uploadedAt: $uploadedAt, uploadedTo: $uploadedTo, createdAt: $createdAt, updatedAt: $updatedAt, deletedAt: $deletedAt, url: $url)'; return 'SnCloudFile(id: $id, name: $name, description: $description, fileMeta: $fileMeta, userMeta: $userMeta, sensitiveMarks: $sensitiveMarks, mimeType: $mimeType, hash: $hash, size: $size, uploadedAt: $uploadedAt, createdAt: $createdAt, updatedAt: $updatedAt, deletedAt: $deletedAt, url: $url)';
} }
@@ -571,11 +1164,11 @@ abstract mixin class _$SnCloudFileCopyWith<$Res> implements $SnCloudFileCopyWith
factory _$SnCloudFileCopyWith(_SnCloudFile value, $Res Function(_SnCloudFile) _then) = __$SnCloudFileCopyWithImpl; factory _$SnCloudFileCopyWith(_SnCloudFile value, $Res Function(_SnCloudFile) _then) = __$SnCloudFileCopyWithImpl;
@override @useResult @override @useResult
$Res call({ $Res call({
String id, String name, String? description, Map<String, dynamic>? fileMeta, Map<String, dynamic>? userMeta, SnFilePool? pool, List<int> sensitiveMarks, String? mimeType, String? hash, int size, DateTime? uploadedAt, String? uploadedTo, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt, String? url String id, String name, String? description, Map<String, dynamic>? fileMeta, Map<String, dynamic>? userMeta, List<int> sensitiveMarks, String? mimeType, String? hash, int size, DateTime? uploadedAt, DateTime createdAt, DateTime updatedAt, DateTime? deletedAt, String? url
}); });
@override $SnFilePoolCopyWith<$Res>? get pool;
} }
/// @nodoc /// @nodoc
@@ -588,21 +1181,19 @@ class __$SnCloudFileCopyWithImpl<$Res>
/// Create a copy of SnCloudFile /// Create a copy of SnCloudFile
/// with the given fields replaced by the non-null parameter values. /// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? id = null,Object? name = null,Object? description = freezed,Object? fileMeta = freezed,Object? userMeta = freezed,Object? pool = freezed,Object? sensitiveMarks = null,Object? mimeType = freezed,Object? hash = freezed,Object? size = null,Object? uploadedAt = freezed,Object? uploadedTo = freezed,Object? createdAt = null,Object? updatedAt = null,Object? deletedAt = freezed,Object? url = freezed,}) { @override @pragma('vm:prefer-inline') $Res call({Object? id = null,Object? name = null,Object? description = freezed,Object? fileMeta = freezed,Object? userMeta = freezed,Object? sensitiveMarks = null,Object? mimeType = freezed,Object? hash = freezed,Object? size = null,Object? uploadedAt = freezed,Object? createdAt = null,Object? updatedAt = null,Object? deletedAt = freezed,Object? url = freezed,}) {
return _then(_SnCloudFile( return _then(_SnCloudFile(
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
as String,name: null == name ? _self.name : name // ignore: cast_nullable_to_non_nullable as String,name: null == name ? _self.name : name // ignore: cast_nullable_to_non_nullable
as String,description: freezed == description ? _self.description : description // ignore: cast_nullable_to_non_nullable as String,description: freezed == description ? _self.description : description // ignore: cast_nullable_to_non_nullable
as String?,fileMeta: freezed == fileMeta ? _self._fileMeta : fileMeta // ignore: cast_nullable_to_non_nullable as String?,fileMeta: freezed == fileMeta ? _self._fileMeta : fileMeta // ignore: cast_nullable_to_non_nullable
as Map<String, dynamic>?,userMeta: freezed == userMeta ? _self._userMeta : userMeta // ignore: cast_nullable_to_non_nullable as Map<String, dynamic>?,userMeta: freezed == userMeta ? _self._userMeta : userMeta // ignore: cast_nullable_to_non_nullable
as Map<String, dynamic>?,pool: freezed == pool ? _self.pool : pool // ignore: cast_nullable_to_non_nullable as Map<String, dynamic>?,sensitiveMarks: null == sensitiveMarks ? _self._sensitiveMarks : sensitiveMarks // ignore: cast_nullable_to_non_nullable
as SnFilePool?,sensitiveMarks: null == sensitiveMarks ? _self._sensitiveMarks : sensitiveMarks // ignore: cast_nullable_to_non_nullable
as List<int>,mimeType: freezed == mimeType ? _self.mimeType : mimeType // ignore: cast_nullable_to_non_nullable as List<int>,mimeType: freezed == mimeType ? _self.mimeType : mimeType // ignore: cast_nullable_to_non_nullable
as String?,hash: freezed == hash ? _self.hash : hash // ignore: cast_nullable_to_non_nullable as String?,hash: freezed == hash ? _self.hash : hash // ignore: cast_nullable_to_non_nullable
as String?,size: null == size ? _self.size : size // ignore: cast_nullable_to_non_nullable as String?,size: null == size ? _self.size : size // ignore: cast_nullable_to_non_nullable
as int,uploadedAt: freezed == uploadedAt ? _self.uploadedAt : uploadedAt // ignore: cast_nullable_to_non_nullable as int,uploadedAt: freezed == uploadedAt ? _self.uploadedAt : uploadedAt // ignore: cast_nullable_to_non_nullable
as DateTime?,uploadedTo: freezed == uploadedTo ? _self.uploadedTo : uploadedTo // ignore: cast_nullable_to_non_nullable as DateTime?,createdAt: null == createdAt ? _self.createdAt : createdAt // ignore: cast_nullable_to_non_nullable
as String?,createdAt: null == createdAt ? _self.createdAt : createdAt // ignore: cast_nullable_to_non_nullable
as DateTime,updatedAt: null == updatedAt ? _self.updatedAt : updatedAt // ignore: cast_nullable_to_non_nullable as DateTime,updatedAt: null == updatedAt ? _self.updatedAt : updatedAt // ignore: cast_nullable_to_non_nullable
as DateTime,deletedAt: freezed == deletedAt ? _self.deletedAt : deletedAt // ignore: cast_nullable_to_non_nullable as DateTime,deletedAt: freezed == deletedAt ? _self.deletedAt : deletedAt // ignore: cast_nullable_to_non_nullable
as DateTime?,url: freezed == url ? _self.url : url // ignore: cast_nullable_to_non_nullable as DateTime?,url: freezed == url ? _self.url : url // ignore: cast_nullable_to_non_nullable
@@ -610,19 +1201,7 @@ as String?,
)); ));
} }
/// Create a copy of SnCloudFile
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$SnFilePoolCopyWith<$Res>? get pool {
if (_self.pool == null) {
return null;
}
return $SnFilePoolCopyWith<$Res>(_self.pool!, (value) {
return _then(_self.copyWith(pool: value));
});
}
} }

View File

@@ -29,15 +29,78 @@ const _$UniversalFileTypeEnumMap = {
UniversalFileType.file: 'file', UniversalFileType.file: 'file',
}; };
_SnFileReplica _$SnFileReplicaFromJson(Map<String, dynamic> json) =>
_SnFileReplica(
id: json['id'] as String,
objectId: json['object_id'] as String,
poolId: json['pool_id'] as String,
pool: json['pool'] == null
? null
: SnFilePool.fromJson(json['pool'] as Map<String, dynamic>),
storageId: json['storage_id'] as String,
status: (json['status'] as num).toInt(),
isPrimary: json['is_primary'] as bool,
createdAt: DateTime.parse(json['created_at'] as String),
updatedAt: DateTime.parse(json['updated_at'] as String),
deletedAt: json['deleted_at'] == null
? null
: DateTime.parse(json['deleted_at'] as String),
);
Map<String, dynamic> _$SnFileReplicaToJson(_SnFileReplica instance) =>
<String, dynamic>{
'id': instance.id,
'object_id': instance.objectId,
'pool_id': instance.poolId,
'pool': instance.pool?.toJson(),
'storage_id': instance.storageId,
'status': instance.status,
'is_primary': instance.isPrimary,
'created_at': instance.createdAt.toIso8601String(),
'updated_at': instance.updatedAt.toIso8601String(),
'deleted_at': instance.deletedAt?.toIso8601String(),
};
_SnCloudFileObject _$SnCloudFileObjectFromJson(Map<String, dynamic> json) =>
_SnCloudFileObject(
id: json['id'] as String,
size: (json['size'] as num).toInt(),
meta: json['meta'] as Map<String, dynamic>?,
mimeType: json['mime_type'] as String?,
hash: json['hash'] as String?,
hasCompression: json['has_compression'] as bool,
hasThumbnail: json['has_thumbnail'] as bool,
fileReplicas: (json['file_replicas'] as List<dynamic>)
.map((e) => SnFileReplica.fromJson(e as Map<String, dynamic>))
.toList(),
createdAt: DateTime.parse(json['created_at'] as String),
updatedAt: DateTime.parse(json['updated_at'] as String),
deletedAt: json['deleted_at'] == null
? null
: DateTime.parse(json['deleted_at'] as String),
);
Map<String, dynamic> _$SnCloudFileObjectToJson(_SnCloudFileObject instance) =>
<String, dynamic>{
'id': instance.id,
'size': instance.size,
'meta': instance.meta,
'mime_type': instance.mimeType,
'hash': instance.hash,
'has_compression': instance.hasCompression,
'has_thumbnail': instance.hasThumbnail,
'file_replicas': instance.fileReplicas.map((e) => e.toJson()).toList(),
'created_at': instance.createdAt.toIso8601String(),
'updated_at': instance.updatedAt.toIso8601String(),
'deleted_at': instance.deletedAt?.toIso8601String(),
};
_SnCloudFile _$SnCloudFileFromJson(Map<String, dynamic> json) => _SnCloudFile( _SnCloudFile _$SnCloudFileFromJson(Map<String, dynamic> json) => _SnCloudFile(
id: json['id'] as String, id: json['id'] as String,
name: json['name'] as String, name: json['name'] as String,
description: json['description'] as String?, description: json['description'] as String?,
fileMeta: json['file_meta'] as Map<String, dynamic>?, fileMeta: json['file_meta'] as Map<String, dynamic>?,
userMeta: json['user_meta'] as Map<String, dynamic>?, userMeta: json['user_meta'] as Map<String, dynamic>?,
pool: json['pool'] == null
? null
: SnFilePool.fromJson(json['pool'] as Map<String, dynamic>),
sensitiveMarks: sensitiveMarks:
(json['sensitive_marks'] as List<dynamic>?) (json['sensitive_marks'] as List<dynamic>?)
?.map((e) => (e as num).toInt()) ?.map((e) => (e as num).toInt())
@@ -49,7 +112,6 @@ _SnCloudFile _$SnCloudFileFromJson(Map<String, dynamic> json) => _SnCloudFile(
uploadedAt: json['uploaded_at'] == null uploadedAt: json['uploaded_at'] == null
? null ? null
: DateTime.parse(json['uploaded_at'] as String), : DateTime.parse(json['uploaded_at'] as String),
uploadedTo: json['uploaded_to'] as String?,
createdAt: DateTime.parse(json['created_at'] as String), createdAt: DateTime.parse(json['created_at'] as String),
updatedAt: DateTime.parse(json['updated_at'] as String), updatedAt: DateTime.parse(json['updated_at'] as String),
deletedAt: json['deleted_at'] == null deletedAt: json['deleted_at'] == null
@@ -65,13 +127,11 @@ Map<String, dynamic> _$SnCloudFileToJson(_SnCloudFile instance) =>
'description': instance.description, 'description': instance.description,
'file_meta': instance.fileMeta, 'file_meta': instance.fileMeta,
'user_meta': instance.userMeta, 'user_meta': instance.userMeta,
'pool': instance.pool?.toJson(),
'sensitive_marks': instance.sensitiveMarks, 'sensitive_marks': instance.sensitiveMarks,
'mime_type': instance.mimeType, 'mime_type': instance.mimeType,
'hash': instance.hash, 'hash': instance.hash,
'size': instance.size, 'size': instance.size,
'uploaded_at': instance.uploadedAt?.toIso8601String(), 'uploaded_at': instance.uploadedAt?.toIso8601String(),
'uploaded_to': instance.uploadedTo,
'created_at': instance.createdAt.toIso8601String(), 'created_at': instance.createdAt.toIso8601String(),
'updated_at': instance.updatedAt.toIso8601String(), 'updated_at': instance.updatedAt.toIso8601String(),
'deleted_at': instance.deletedAt?.toIso8601String(), 'deleted_at': instance.deletedAt?.toIso8601String(),

View File

@@ -1,23 +0,0 @@
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:island/models/file.dart';
part 'reference.freezed.dart';
part 'reference.g.dart';
@freezed
sealed class Reference with _$Reference {
const factory Reference({
required String id,
@JsonKey(name: 'file_id') required String fileId,
SnCloudFile? file,
required String usage,
@JsonKey(name: 'resource_id') required String resourceId,
@JsonKey(name: 'expired_at') DateTime? expiredAt,
@JsonKey(name: 'created_at') required DateTime createdAt,
@JsonKey(name: 'updated_at') required DateTime updatedAt,
@JsonKey(name: 'deleted_at') DateTime? deletedAt,
}) = _Reference;
factory Reference.fromJson(Map<String, dynamic> json) =>
_$ReferenceFromJson(json);
}

View File

@@ -1,319 +0,0 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
// coverage:ignore-file
// ignore_for_file: type=lint
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'reference.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// dart format off
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$Reference {
String get id;@JsonKey(name: 'file_id') String get fileId; SnCloudFile? get file; String get usage;@JsonKey(name: 'resource_id') String get resourceId;@JsonKey(name: 'expired_at') DateTime? get expiredAt;@JsonKey(name: 'created_at') DateTime get createdAt;@JsonKey(name: 'updated_at') DateTime get updatedAt;@JsonKey(name: 'deleted_at') DateTime? get deletedAt;
/// Create a copy of Reference
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$ReferenceCopyWith<Reference> get copyWith => _$ReferenceCopyWithImpl<Reference>(this as Reference, _$identity);
/// Serializes this Reference to a JSON map.
Map<String, dynamic> toJson();
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is Reference&&(identical(other.id, id) || other.id == id)&&(identical(other.fileId, fileId) || other.fileId == fileId)&&(identical(other.file, file) || other.file == file)&&(identical(other.usage, usage) || other.usage == usage)&&(identical(other.resourceId, resourceId) || other.resourceId == resourceId)&&(identical(other.expiredAt, expiredAt) || other.expiredAt == expiredAt)&&(identical(other.createdAt, createdAt) || other.createdAt == createdAt)&&(identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)&&(identical(other.deletedAt, deletedAt) || other.deletedAt == deletedAt));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,id,fileId,file,usage,resourceId,expiredAt,createdAt,updatedAt,deletedAt);
@override
String toString() {
return 'Reference(id: $id, fileId: $fileId, file: $file, usage: $usage, resourceId: $resourceId, expiredAt: $expiredAt, createdAt: $createdAt, updatedAt: $updatedAt, deletedAt: $deletedAt)';
}
}
/// @nodoc
abstract mixin class $ReferenceCopyWith<$Res> {
factory $ReferenceCopyWith(Reference value, $Res Function(Reference) _then) = _$ReferenceCopyWithImpl;
@useResult
$Res call({
String id,@JsonKey(name: 'file_id') String fileId, SnCloudFile? file, String usage,@JsonKey(name: 'resource_id') String resourceId,@JsonKey(name: 'expired_at') DateTime? expiredAt,@JsonKey(name: 'created_at') DateTime createdAt,@JsonKey(name: 'updated_at') DateTime updatedAt,@JsonKey(name: 'deleted_at') DateTime? deletedAt
});
$SnCloudFileCopyWith<$Res>? get file;
}
/// @nodoc
class _$ReferenceCopyWithImpl<$Res>
implements $ReferenceCopyWith<$Res> {
_$ReferenceCopyWithImpl(this._self, this._then);
final Reference _self;
final $Res Function(Reference) _then;
/// Create a copy of Reference
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? id = null,Object? fileId = null,Object? file = freezed,Object? usage = null,Object? resourceId = null,Object? expiredAt = freezed,Object? createdAt = null,Object? updatedAt = null,Object? deletedAt = freezed,}) {
return _then(_self.copyWith(
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
as String,fileId: null == fileId ? _self.fileId : fileId // ignore: cast_nullable_to_non_nullable
as String,file: freezed == file ? _self.file : file // ignore: cast_nullable_to_non_nullable
as SnCloudFile?,usage: null == usage ? _self.usage : usage // ignore: cast_nullable_to_non_nullable
as String,resourceId: null == resourceId ? _self.resourceId : resourceId // ignore: cast_nullable_to_non_nullable
as String,expiredAt: freezed == expiredAt ? _self.expiredAt : expiredAt // ignore: cast_nullable_to_non_nullable
as DateTime?,createdAt: null == createdAt ? _self.createdAt : createdAt // ignore: cast_nullable_to_non_nullable
as DateTime,updatedAt: null == updatedAt ? _self.updatedAt : updatedAt // ignore: cast_nullable_to_non_nullable
as DateTime,deletedAt: freezed == deletedAt ? _self.deletedAt : deletedAt // ignore: cast_nullable_to_non_nullable
as DateTime?,
));
}
/// Create a copy of Reference
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$SnCloudFileCopyWith<$Res>? get file {
if (_self.file == null) {
return null;
}
return $SnCloudFileCopyWith<$Res>(_self.file!, (value) {
return _then(_self.copyWith(file: value));
});
}
}
/// Adds pattern-matching-related methods to [Reference].
extension ReferencePatterns on Reference {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeMap<TResult extends Object?>(TResult Function( _Reference value)? $default,{required TResult orElse(),}){
final _that = this;
switch (_that) {
case _Reference() when $default != null:
return $default(_that);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult map<TResult extends Object?>(TResult Function( _Reference value) $default,){
final _that = this;
switch (_that) {
case _Reference():
return $default(_that);}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? mapOrNull<TResult extends Object?>(TResult? Function( _Reference value)? $default,){
final _that = this;
switch (_that) {
case _Reference() when $default != null:
return $default(_that);case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( String id, @JsonKey(name: 'file_id') String fileId, SnCloudFile? file, String usage, @JsonKey(name: 'resource_id') String resourceId, @JsonKey(name: 'expired_at') DateTime? expiredAt, @JsonKey(name: 'created_at') DateTime createdAt, @JsonKey(name: 'updated_at') DateTime updatedAt, @JsonKey(name: 'deleted_at') DateTime? deletedAt)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) {
case _Reference() when $default != null:
return $default(_that.id,_that.fileId,_that.file,_that.usage,_that.resourceId,_that.expiredAt,_that.createdAt,_that.updatedAt,_that.deletedAt);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( String id, @JsonKey(name: 'file_id') String fileId, SnCloudFile? file, String usage, @JsonKey(name: 'resource_id') String resourceId, @JsonKey(name: 'expired_at') DateTime? expiredAt, @JsonKey(name: 'created_at') DateTime createdAt, @JsonKey(name: 'updated_at') DateTime updatedAt, @JsonKey(name: 'deleted_at') DateTime? deletedAt) $default,) {final _that = this;
switch (_that) {
case _Reference():
return $default(_that.id,_that.fileId,_that.file,_that.usage,_that.resourceId,_that.expiredAt,_that.createdAt,_that.updatedAt,_that.deletedAt);}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( String id, @JsonKey(name: 'file_id') String fileId, SnCloudFile? file, String usage, @JsonKey(name: 'resource_id') String resourceId, @JsonKey(name: 'expired_at') DateTime? expiredAt, @JsonKey(name: 'created_at') DateTime createdAt, @JsonKey(name: 'updated_at') DateTime updatedAt, @JsonKey(name: 'deleted_at') DateTime? deletedAt)? $default,) {final _that = this;
switch (_that) {
case _Reference() when $default != null:
return $default(_that.id,_that.fileId,_that.file,_that.usage,_that.resourceId,_that.expiredAt,_that.createdAt,_that.updatedAt,_that.deletedAt);case _:
return null;
}
}
}
/// @nodoc
@JsonSerializable()
class _Reference implements Reference {
const _Reference({required this.id, @JsonKey(name: 'file_id') required this.fileId, this.file, required this.usage, @JsonKey(name: 'resource_id') required this.resourceId, @JsonKey(name: 'expired_at') this.expiredAt, @JsonKey(name: 'created_at') required this.createdAt, @JsonKey(name: 'updated_at') required this.updatedAt, @JsonKey(name: 'deleted_at') this.deletedAt});
factory _Reference.fromJson(Map<String, dynamic> json) => _$ReferenceFromJson(json);
@override final String id;
@override@JsonKey(name: 'file_id') final String fileId;
@override final SnCloudFile? file;
@override final String usage;
@override@JsonKey(name: 'resource_id') final String resourceId;
@override@JsonKey(name: 'expired_at') final DateTime? expiredAt;
@override@JsonKey(name: 'created_at') final DateTime createdAt;
@override@JsonKey(name: 'updated_at') final DateTime updatedAt;
@override@JsonKey(name: 'deleted_at') final DateTime? deletedAt;
/// Create a copy of Reference
/// with the given fields replaced by the non-null parameter values.
@override @JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$ReferenceCopyWith<_Reference> get copyWith => __$ReferenceCopyWithImpl<_Reference>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$ReferenceToJson(this, );
}
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _Reference&&(identical(other.id, id) || other.id == id)&&(identical(other.fileId, fileId) || other.fileId == fileId)&&(identical(other.file, file) || other.file == file)&&(identical(other.usage, usage) || other.usage == usage)&&(identical(other.resourceId, resourceId) || other.resourceId == resourceId)&&(identical(other.expiredAt, expiredAt) || other.expiredAt == expiredAt)&&(identical(other.createdAt, createdAt) || other.createdAt == createdAt)&&(identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)&&(identical(other.deletedAt, deletedAt) || other.deletedAt == deletedAt));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,id,fileId,file,usage,resourceId,expiredAt,createdAt,updatedAt,deletedAt);
@override
String toString() {
return 'Reference(id: $id, fileId: $fileId, file: $file, usage: $usage, resourceId: $resourceId, expiredAt: $expiredAt, createdAt: $createdAt, updatedAt: $updatedAt, deletedAt: $deletedAt)';
}
}
/// @nodoc
abstract mixin class _$ReferenceCopyWith<$Res> implements $ReferenceCopyWith<$Res> {
factory _$ReferenceCopyWith(_Reference value, $Res Function(_Reference) _then) = __$ReferenceCopyWithImpl;
@override @useResult
$Res call({
String id,@JsonKey(name: 'file_id') String fileId, SnCloudFile? file, String usage,@JsonKey(name: 'resource_id') String resourceId,@JsonKey(name: 'expired_at') DateTime? expiredAt,@JsonKey(name: 'created_at') DateTime createdAt,@JsonKey(name: 'updated_at') DateTime updatedAt,@JsonKey(name: 'deleted_at') DateTime? deletedAt
});
@override $SnCloudFileCopyWith<$Res>? get file;
}
/// @nodoc
class __$ReferenceCopyWithImpl<$Res>
implements _$ReferenceCopyWith<$Res> {
__$ReferenceCopyWithImpl(this._self, this._then);
final _Reference _self;
final $Res Function(_Reference) _then;
/// Create a copy of Reference
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? id = null,Object? fileId = null,Object? file = freezed,Object? usage = null,Object? resourceId = null,Object? expiredAt = freezed,Object? createdAt = null,Object? updatedAt = null,Object? deletedAt = freezed,}) {
return _then(_Reference(
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
as String,fileId: null == fileId ? _self.fileId : fileId // ignore: cast_nullable_to_non_nullable
as String,file: freezed == file ? _self.file : file // ignore: cast_nullable_to_non_nullable
as SnCloudFile?,usage: null == usage ? _self.usage : usage // ignore: cast_nullable_to_non_nullable
as String,resourceId: null == resourceId ? _self.resourceId : resourceId // ignore: cast_nullable_to_non_nullable
as String,expiredAt: freezed == expiredAt ? _self.expiredAt : expiredAt // ignore: cast_nullable_to_non_nullable
as DateTime?,createdAt: null == createdAt ? _self.createdAt : createdAt // ignore: cast_nullable_to_non_nullable
as DateTime,updatedAt: null == updatedAt ? _self.updatedAt : updatedAt // ignore: cast_nullable_to_non_nullable
as DateTime,deletedAt: freezed == deletedAt ? _self.deletedAt : deletedAt // ignore: cast_nullable_to_non_nullable
as DateTime?,
));
}
/// Create a copy of Reference
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$SnCloudFileCopyWith<$Res>? get file {
if (_self.file == null) {
return null;
}
return $SnCloudFileCopyWith<$Res>(_self.file!, (value) {
return _then(_self.copyWith(file: value));
});
}
}
// dart format on

View File

@@ -1,38 +0,0 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'reference.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_Reference _$ReferenceFromJson(Map<String, dynamic> json) => _Reference(
id: json['id'] as String,
fileId: json['file_id'] as String,
file: json['file'] == null
? null
: SnCloudFile.fromJson(json['file'] as Map<String, dynamic>),
usage: json['usage'] as String,
resourceId: json['resource_id'] as String,
expiredAt: json['expired_at'] == null
? null
: DateTime.parse(json['expired_at'] as String),
createdAt: DateTime.parse(json['created_at'] as String),
updatedAt: DateTime.parse(json['updated_at'] as String),
deletedAt: json['deleted_at'] == null
? null
: DateTime.parse(json['deleted_at'] as String),
);
Map<String, dynamic> _$ReferenceToJson(_Reference instance) =>
<String, dynamic>{
'id': instance.id,
'file_id': instance.fileId,
'file': instance.file?.toJson(),
'usage': instance.usage,
'resource_id': instance.resourceId,
'expired_at': instance.expiredAt?.toIso8601String(),
'created_at': instance.createdAt.toIso8601String(),
'updated_at': instance.updatedAt.toIso8601String(),
'deleted_at': instance.deletedAt?.toIso8601String(),
};

176
lib/pods/audio.dart Normal file
View File

@@ -0,0 +1,176 @@
import 'dart:math' as math;
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:just_audio/just_audio.dart';
import 'package:island/pods/config.dart';
import 'package:audio_session/audio_session.dart';
import 'package:dart_midi_pro/dart_midi_pro.dart';
final sfxPlayerProvider = Provider<AudioPlayer>((ref) {
final player = AudioPlayer();
ref.onDispose(() {
player.dispose();
});
return player;
});
Future<void> _configureAudioSession() async {
final session = await AudioSession.instance;
await session.configure(
const AudioSessionConfiguration(
avAudioSessionCategory: AVAudioSessionCategory.playback,
avAudioSessionCategoryOptions:
AVAudioSessionCategoryOptions.mixWithOthers,
),
);
await session.setActive(true);
}
final audioSessionProvider = FutureProvider<void>((ref) async {
await _configureAudioSession();
});
final notificationSfxProvider = FutureProvider<void>((ref) async {
final player = ref.watch(sfxPlayerProvider);
await player.setVolume(0.75);
await player.setAudioSource(
AudioSource.asset('assets/audio/notification.mp3'),
preload: true,
);
});
final messageSfxProvider = FutureProvider<void>((ref) async {
final player = ref.watch(sfxPlayerProvider);
await player.setAudioSource(
AudioSource.asset('assets/audio/messages.mp3'),
preload: true,
);
});
Future<void> _playSfx(String assetPath, double volume) async {
final player = AudioPlayer();
await player.setVolume(volume);
await player.setAudioSource(AudioSource.asset(assetPath));
await player.play();
await player.dispose();
}
void playNotificationSfx(WidgetRef ref) {
final settings = ref.read(appSettingsProvider);
if (!settings.soundEffects) return;
_playSfx('assets/audio/notification.mp3', 0.75);
}
void playMessageSfx(WidgetRef ref) {
final settings = ref.read(appSettingsProvider);
if (!settings.soundEffects) return;
_playSfx('assets/audio/messages.mp3', 0.75);
}
class MiniSampleSynth {
final String sampleAsset;
final int baseNote; // MIDI note of the sample (usually 72 = C5 for lower pitch playback)
AudioPlayer? currentPlayer;
MiniSampleSynth({required this.sampleAsset, this.baseNote = 72});
Future<void> playMidiAsset(String midiAsset) async {
final data = await rootBundle.load(midiAsset);
final midi = MidiParser().parseMidiFromBuffer(data.buffer.asUint8List());
for (final track in midi.tracks) {
int currentTick = 0;
for (final event in track) {
currentTick += event.deltaTime;
if (event is NoteOnEvent && event.velocity > 0) {
final note = event.noteNumber;
final durationTicks = _estimateDuration(track, event);
final durationMs = _ticksToMs(durationTicks, midi);
_scheduleNote(
note: note,
startMs: _ticksToMs(currentTick, midi),
durationMs: durationMs,
);
}
}
}
}
void _scheduleNote({
required int note,
required int startMs,
required int durationMs,
}) {
Future.delayed(Duration(milliseconds: startMs), () async {
// Stop any currently playing note
if (currentPlayer != null) {
await currentPlayer!.stop();
await currentPlayer!.dispose();
currentPlayer = null;
}
final player = AudioPlayer();
currentPlayer = player;
await player.setAudioSource(AudioSource.asset(sampleAsset));
final speed = _noteToSpeed(note);
await player.setSpeed(speed);
await player.play();
Future.delayed(Duration(milliseconds: durationMs), () async {
if (currentPlayer == player) {
await player.stop();
await player.dispose();
currentPlayer = null;
}
});
});
}
double _noteToSpeed(int note) {
return math.pow(2, (note - baseNote) / 12).toDouble();
}
int _getTempo(MidiFile midi) {
for (var track in midi.tracks) {
for (var event in track) {
if (event is SetTempoEvent) {
return event.microsecondsPerBeat;
}
}
}
return 500000; // default 120 BPM
}
int _ticksToMs(int ticks, MidiFile midi) {
final tempo = _getTempo(midi);
final ticksPerBeat = midi.header.ticksPerBeat ?? 480;
return ((ticks * tempo) / ticksPerBeat / 1000).round();
}
int _estimateDuration(List<MidiEvent> track, NoteOnEvent on) {
int ticks = 0;
bool started = false;
for (final e in track) {
if (e == on) {
started = true;
continue;
}
if (!started) continue;
ticks += e.deltaTime;
if (e is NoteOffEvent && e.noteNumber == on.noteNumber) {
return ticks;
}
}
return 200; // fallback
}
}

View File

@@ -2,6 +2,8 @@ import "dart:async";
import "dart:convert"; import "dart:convert";
import "package:flutter/material.dart"; import "package:flutter/material.dart";
import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:flutter_riverpod/flutter_riverpod.dart";
import "package:just_audio/just_audio.dart";
import "package:island/pods/config.dart";
import "package:island/models/chat.dart"; import "package:island/models/chat.dart";
import "package:island/pods/chat/chat_room.dart"; import "package:island/pods/chat/chat_room.dart";
import "package:island/pods/lifecycle.dart"; import "package:island/pods/lifecycle.dart";
@@ -198,7 +200,7 @@ class ChatSubscribeNotifier extends _$ChatSubscribeNotifier {
return _typingStatuses; return _typingStatuses;
} }
void onMessage(WebSocketPacket pkt) { Future<void> onMessage(WebSocketPacket pkt) async {
if (!pkt.type.startsWith('messages')) return; if (!pkt.type.startsWith('messages')) return;
if (['messages.read'].contains(pkt.type)) return; if (['messages.read'].contains(pkt.type)) return;
@@ -221,7 +223,7 @@ class ChatSubscribeNotifier extends _$ChatSubscribeNotifier {
// Add new typing status // Add new typing status
_typingStatuses.add(sender); _typingStatuses.add(sender);
} }
state = List.of(_typingStatuses); if (ref.mounted) state = List.of(_typingStatuses);
return; return;
} }
@@ -238,6 +240,20 @@ class ChatSubscribeNotifier extends _$ChatSubscribeNotifier {
_messagesNotifier.receiveMessage(message); _messagesNotifier.receiveMessage(message);
// Send read receipt for new message // Send read receipt for new message
sendReadReceipt(); sendReadReceipt();
// Play sound for new messages when app is unfocused
if (pkt.type == 'messages.new' &&
message.senderId != _chatIdentity.id &&
ref.read(appLifecycleStateProvider).value !=
AppLifecycleState.resumed &&
ref.read(appSettingsProvider).soundEffects) {
final player = AudioPlayer();
await player.setVolume(0.75);
await player.setAudioSource(
AudioSource.asset('assets/audio/messages.mp3'),
);
await player.play();
player.dispose();
}
} }
} }

View File

@@ -59,7 +59,7 @@ final class ChatSubscribeNotifierProvider
} }
String _$chatSubscribeNotifierHash() => String _$chatSubscribeNotifierHash() =>
r'b7624ae45ace2944a88f8b4d14ddce556c236371'; r'f2f5059a975fc44a41850459d6b7d041ff9d41cb';
final class ChatSubscribeNotifierFamily extends $Family final class ChatSubscribeNotifierFamily extends $Family
with with

View File

@@ -128,7 +128,7 @@ class MessagesNotifier extends _$MessagesNotifier {
uniqueMessages.add(message); uniqueMessages.add(message);
} }
} }
state = AsyncValue.data(uniqueMessages); if (ref.mounted) state = AsyncValue.data(uniqueMessages);
} finally { } finally {
_isUpdatingState = false; _isUpdatingState = false;
} }
@@ -350,7 +350,7 @@ class MessagesNotifier extends _$MessagesNotifier {
offset: 0, offset: 0,
take: _pageSize, take: _pageSize,
); );
state = AsyncValue.data(newMessages); if (ref.mounted) state = AsyncValue.data(newMessages);
return; return;
} }
@@ -408,7 +408,9 @@ class MessagesNotifier extends _$MessagesNotifier {
} finally { } finally {
talker.log('Finished message sync'); talker.log('Finished message sync');
// Always reset global syncing state, regardless of disposal // Always reset global syncing state, regardless of disposal
Future.microtask(() => ref.read(chatSyncingProvider.notifier).set(false)); Future.microtask(() {
if (ref.mounted) ref.read(chatSyncingProvider.notifier).set(false);
});
_isSyncing = false; _isSyncing = false;
} }
} }
@@ -498,7 +500,7 @@ class MessagesNotifier extends _$MessagesNotifier {
_hasMore = messages.length == _pageSize; _hasMore = messages.length == _pageSize;
state = AsyncValue.data(messages); if (ref.mounted) state = AsyncValue.data(messages);
} }
Future<void> loadMore() async { Future<void> loadMore() async {
@@ -509,7 +511,7 @@ class MessagesNotifier extends _$MessagesNotifier {
Future.microtask(() => ref.read(chatSyncingProvider.notifier).set(true)); Future.microtask(() => ref.read(chatSyncingProvider.notifier).set(true));
} }
try { try {
final currentMessages = state.value ?? []; final currentMessages = (ref.mounted ? state.value : null) ?? [];
final offset = currentMessages.length; final offset = currentMessages.length;
final newMessages = await listMessages(offset: offset, take: _pageSize); final newMessages = await listMessages(offset: offset, take: _pageSize);
@@ -518,9 +520,11 @@ class MessagesNotifier extends _$MessagesNotifier {
_hasMore = false; _hasMore = false;
} }
if (ref.mounted) {
state = AsyncValue.data( state = AsyncValue.data(
_sortMessages([...currentMessages, ...newMessages]), _sortMessages([...currentMessages, ...newMessages]),
); );
}
} catch (err, stackTrace) { } catch (err, stackTrace) {
talker.log( talker.log(
'Error loading more messages', 'Error loading more messages',
@@ -531,12 +535,14 @@ class MessagesNotifier extends _$MessagesNotifier {
showErrorAlert(err); showErrorAlert(err);
} finally { } finally {
// Always reset global syncing state, regardless of disposal // Always reset global syncing state, regardless of disposal
Future.microtask(() => ref.read(chatSyncingProvider.notifier).set(false)); Future.microtask(() {
if (ref.mounted) ref.read(chatSyncingProvider.notifier).set(false);
});
} }
} }
Future<void> sendMessage( Future<void> sendMessage(
WidgetRef ref, WidgetRef outerRef,
String content, String content,
List<UniversalFile> attachments, { List<UniversalFile> attachments, {
SnPoll? poll, SnPoll? poll,
@@ -569,14 +575,14 @@ class MessagesNotifier extends _$MessagesNotifier {
_fileUploadProgress[localMessage.id] = {}; _fileUploadProgress[localMessage.id] = {};
await _database.saveMessageWithSender(localMessage); await _database.saveMessageWithSender(localMessage);
final currentMessages = state.value ?? []; final currentMessages = (ref.mounted ? state.value : null) ?? [];
state = AsyncValue.data([localMessage, ...currentMessages]); state = AsyncValue.data([localMessage, ...currentMessages]);
try { try {
var cloudAttachments = List.empty(growable: true); var cloudAttachments = List.empty(growable: true);
for (var idx = 0; idx < attachments.length; idx++) { for (var idx = 0; idx < attachments.length; idx++) {
final cloudFile = await FileUploader.createCloudFile( final cloudFile = await FileUploader.createCloudFile(
ref: ref, ref: outerRef,
fileData: attachments[idx], fileData: attachments[idx],
onProgress: (progress, _) { onProgress: (progress, _) {
_fileUploadProgress[localMessage.id]?[idx] = progress ?? 0.0; _fileUploadProgress[localMessage.id]?[idx] = progress ?? 0.0;
@@ -619,6 +625,7 @@ class MessagesNotifier extends _$MessagesNotifier {
await _database.deleteMessage(localMessage.id); await _database.deleteMessage(localMessage.id);
await _database.saveMessageWithSender(updatedMessage); await _database.saveMessageWithSender(updatedMessage);
if (ref.mounted) {
final currentMessages = state.value ?? []; final currentMessages = state.value ?? [];
if (editingTo != null) { if (editingTo != null) {
final newMessages = currentMessages final newMessages = currentMessages
@@ -637,6 +644,8 @@ class MessagesNotifier extends _$MessagesNotifier {
}).toList(); }).toList();
state = AsyncValue.data(newMessages); state = AsyncValue.data(newMessages);
} }
}
talker.log('Message with nonce $nonce sent successfully'); talker.log('Message with nonce $nonce sent successfully');
} catch (e, stackTrace) { } catch (e, stackTrace) {
talker.log( talker.log(
@@ -651,6 +660,7 @@ class MessagesNotifier extends _$MessagesNotifier {
localMessage.id, localMessage.id,
MessageStatus.failed, MessageStatus.failed,
); );
if (ref.mounted) {
final newMessages = (state.value ?? []).map((m) { final newMessages = (state.value ?? []).map((m) {
if (m.id == localMessage.id) { if (m.id == localMessage.id) {
return m..status = MessageStatus.failed; return m..status = MessageStatus.failed;
@@ -658,6 +668,7 @@ class MessagesNotifier extends _$MessagesNotifier {
return m; return m;
}).toList(); }).toList();
state = AsyncValue.data(newMessages); state = AsyncValue.data(newMessages);
}
showErrorAlert(e); showErrorAlert(e);
} }
} }
@@ -698,6 +709,7 @@ class MessagesNotifier extends _$MessagesNotifier {
await _database.deleteMessage(pendingMessageId); await _database.deleteMessage(pendingMessageId);
await _database.saveMessageWithSender(updatedMessage); await _database.saveMessageWithSender(updatedMessage);
if (ref.mounted) {
final newMessages = (state.value ?? []).map((m) { final newMessages = (state.value ?? []).map((m) {
if (m.id == pendingMessageId) { if (m.id == pendingMessageId) {
return updatedMessage; return updatedMessage;
@@ -705,6 +717,7 @@ class MessagesNotifier extends _$MessagesNotifier {
return m; return m;
}).toList(); }).toList();
state = AsyncValue.data(newMessages); state = AsyncValue.data(newMessages);
}
} catch (e, stackTrace) { } catch (e, stackTrace) {
talker.log( talker.log(
'Failed to retry message $pendingMessageId', 'Failed to retry message $pendingMessageId',
@@ -718,6 +731,7 @@ class MessagesNotifier extends _$MessagesNotifier {
pendingMessageId, pendingMessageId,
MessageStatus.failed, MessageStatus.failed,
); );
if (ref.mounted) {
final newMessages = (state.value ?? []).map((m) { final newMessages = (state.value ?? []).map((m) {
if (m.id == pendingMessageId) { if (m.id == pendingMessageId) {
return m..status = MessageStatus.failed; return m..status = MessageStatus.failed;
@@ -725,6 +739,7 @@ class MessagesNotifier extends _$MessagesNotifier {
return m; return m;
}).toList(); }).toList();
state = AsyncValue.data(_sortMessages(newMessages)); state = AsyncValue.data(_sortMessages(newMessages));
}
showErrorAlert(e); showErrorAlert(e);
} }
} }
@@ -756,13 +771,14 @@ class MessagesNotifier extends _$MessagesNotifier {
if (!isSilentMessage) { if (!isSilentMessage) {
await _database.saveMessageWithSender(localMessage); await _database.saveMessageWithSender(localMessage);
final currentMessages = state.value ?? []; final currentMessages = (ref.mounted ? state.value : null) ?? [];
final existingIndex = currentMessages.indexWhere( final existingIndex = currentMessages.indexWhere(
(m) => (m) =>
m.id == localMessage.id || m.id == localMessage.id ||
(localMessage.nonce != null && m.nonce == localMessage.nonce), (localMessage.nonce != null && m.nonce == localMessage.nonce),
); );
if (ref.mounted) {
if (existingIndex >= 0) { if (existingIndex >= 0) {
final newList = [...currentMessages]; final newList = [...currentMessages];
newList[existingIndex] = localMessage; newList[existingIndex] = localMessage;
@@ -773,6 +789,7 @@ class MessagesNotifier extends _$MessagesNotifier {
); );
} }
} }
}
switch (remoteMessage.type) { switch (remoteMessage.type) {
case "messages.delete": case "messages.delete":
@@ -837,15 +854,17 @@ class MessagesNotifier extends _$MessagesNotifier {
await _database.updateMessage(_database.messageToCompanion(updatedMessage)); await _database.updateMessage(_database.messageToCompanion(updatedMessage));
final currentMessages = state.value ?? []; final currentMessages = (ref.mounted ? state.value : null) ?? [];
final index = currentMessages.indexWhere((m) => m.id == updatedMessage.id); final index = currentMessages.indexWhere((m) => m.id == updatedMessage.id);
if (ref.mounted) {
if (index >= 0) { if (index >= 0) {
final newList = [...currentMessages]; final newList = [...currentMessages];
newList[index] = updatedMessage; newList[index] = updatedMessage;
state = AsyncValue.data(_sortMessages(newList)); state = AsyncValue.data(_sortMessages(newList));
} }
} }
}
Future<void> receiveMessageDeletion(String messageId) async { Future<void> receiveMessageDeletion(String messageId) async {
// Block message deletions during jumps to prevent list resets // Block message deletions during jumps to prevent list resets
@@ -857,7 +876,7 @@ class MessagesNotifier extends _$MessagesNotifier {
talker.log('Received message deletion $messageId'); talker.log('Received message deletion $messageId');
_pendingMessages.remove(messageId); _pendingMessages.remove(messageId);
final currentMessages = state.value ?? []; final currentMessages = (ref.mounted ? state.value : null) ?? [];
final messageIndex = currentMessages.indexWhere((m) => m.id == messageId); final messageIndex = currentMessages.indexWhere((m) => m.id == messageId);
LocalChatMessage? messageToUpdate; LocalChatMessage? messageToUpdate;
@@ -883,12 +902,14 @@ class MessagesNotifier extends _$MessagesNotifier {
await _database.saveMessageWithSender(deletedMessage); await _database.saveMessageWithSender(deletedMessage);
if (ref.mounted) {
if (messageIndex != -1) { if (messageIndex != -1) {
final newList = [...currentMessages]; final newList = [...currentMessages];
newList[messageIndex] = deletedMessage; newList[messageIndex] = deletedMessage;
state = AsyncValue.data(newList); state = AsyncValue.data(newList);
} }
} }
}
Future<void> deleteMessage(String messageId) async { Future<void> deleteMessage(String messageId) async {
talker.log('Deleting message $messageId'); talker.log('Deleting message $messageId');
@@ -907,7 +928,7 @@ class MessagesNotifier extends _$MessagesNotifier {
_pendingMessages.remove(messageId); _pendingMessages.remove(messageId);
await _database.deleteMessage(messageId); await _database.deleteMessage(messageId);
final currentMessages = state.value ?? []; final currentMessages = (ref.mounted ? state.value : null) ?? [];
final newMessages = currentMessages final newMessages = currentMessages
.where((m) => m.id != messageId) .where((m) => m.id != messageId)
.toList(); .toList();
@@ -1063,7 +1084,7 @@ class MessagesNotifier extends _$MessagesNotifier {
} }
// Check if message is already in current state to avoid duplicate loading // Check if message is already in current state to avoid duplicate loading
final currentMessages = state.value ?? []; final currentMessages = (ref.mounted ? state.value : null) ?? [];
final existingIndex = currentMessages.indexWhere( final existingIndex = currentMessages.indexWhere(
(m) => m.id == messageId, (m) => m.id == messageId,
); );

View File

@@ -50,7 +50,7 @@ final class MessagesNotifierProvider
} }
} }
String _$messagesNotifierHash() => r'a721a4b92b48ee7c2289cdcd7130bbf1ca9dcb40'; String _$messagesNotifierHash() => r'622fed0908eb04381a971e36540c516743246dff';
final class MessagesNotifierFamily extends $Family final class MessagesNotifierFamily extends $Family
with with

View File

@@ -3,6 +3,7 @@ import 'dart:convert';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:island/services/analytics_service.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import 'package:window_manager/window_manager.dart'; import 'package:window_manager/window_manager.dart';
@@ -41,6 +42,7 @@ const kAppAskedReview = 'app_asked_review';
const kAppDashSearchEngine = 'app_dash_search_engine'; const kAppDashSearchEngine = 'app_dash_search_engine';
const kAppDefaultScreen = 'app_default_screen'; const kAppDefaultScreen = 'app_default_screen';
const kAppShowFediverseContent = 'app_show_fediverse_content'; const kAppShowFediverseContent = 'app_show_fediverse_content';
const kAppDashboardConfig = 'app_dashboard_config';
// Will be overrided by the ProviderScope // Will be overrided by the ProviderScope
final sharedPreferencesProvider = Provider<SharedPreferences>((ref) { final sharedPreferencesProvider = Provider<SharedPreferences>((ref) {
@@ -67,6 +69,19 @@ sealed class ThemeColors with _$ThemeColors {
_$ThemeColorsFromJson(json); _$ThemeColorsFromJson(json);
} }
@freezed
sealed class DashboardConfig with _$DashboardConfig {
factory DashboardConfig({
required List<String> verticalLayouts,
required List<String> horizontalLayouts,
required bool showSearchBar,
required bool showClockAndCountdown,
}) = _DashboardConfig;
factory DashboardConfig.fromJson(Map<String, dynamic> json) =>
_$DashboardConfigFromJson(json);
}
@freezed @freezed
sealed class AppSettings with _$AppSettings { sealed class AppSettings with _$AppSettings {
const factory AppSettings({ const factory AppSettings({
@@ -93,6 +108,7 @@ sealed class AppSettings with _$AppSettings {
required String? dashSearchEngine, required String? dashSearchEngine,
required String? defaultScreen, required String? defaultScreen,
required bool showFediverseContent, required bool showFediverseContent,
required DashboardConfig? dashboardConfig,
}) = _AppSettings; }) = _AppSettings;
} }
@@ -125,6 +141,7 @@ class AppSettingsNotifier extends _$AppSettingsNotifier {
dashSearchEngine: prefs.getString(kAppDashSearchEngine), dashSearchEngine: prefs.getString(kAppDashSearchEngine),
defaultScreen: prefs.getString(kAppDefaultScreen), defaultScreen: prefs.getString(kAppDefaultScreen),
showFediverseContent: prefs.getBool(kAppShowFediverseContent) ?? true, showFediverseContent: prefs.getBool(kAppShowFediverseContent) ?? true,
dashboardConfig: _getDashboardConfigFromPrefs(prefs),
); );
} }
@@ -157,6 +174,18 @@ class AppSettingsNotifier extends _$AppSettingsNotifier {
} }
} }
DashboardConfig? _getDashboardConfigFromPrefs(SharedPreferences prefs) {
final jsonString = prefs.getString(kAppDashboardConfig);
if (jsonString == null) return null;
try {
final json = jsonDecode(jsonString);
return DashboardConfig.fromJson(json);
} catch (e) {
return null;
}
}
void setDefaultPoolId(String? value) { void setDefaultPoolId(String? value) {
final prefs = ref.read(sharedPreferencesProvider); final prefs = ref.read(sharedPreferencesProvider);
if (value != null) { if (value != null) {
@@ -256,8 +285,11 @@ class AppSettingsNotifier extends _$AppSettingsNotifier {
void setThemeMode(String value) { void setThemeMode(String value) {
final prefs = ref.read(sharedPreferencesProvider); final prefs = ref.read(sharedPreferencesProvider);
final oldValue = state.themeMode;
prefs.setString(kAppThemeMode, value); prefs.setString(kAppThemeMode, value);
state = state.copyWith(themeMode: value); state = state.copyWith(themeMode: value);
AnalyticsService().logThemeChanged(oldValue ?? 'system', value);
} }
void setAppTransparentBackground(double value) { void setAppTransparentBackground(double value) {
@@ -320,6 +352,23 @@ class AppSettingsNotifier extends _$AppSettingsNotifier {
prefs.setBool(kAppShowFediverseContent, value); prefs.setBool(kAppShowFediverseContent, value);
state = state.copyWith(showFediverseContent: value); state = state.copyWith(showFediverseContent: value);
} }
void setDashboardConfig(DashboardConfig? value) {
final prefs = ref.read(sharedPreferencesProvider);
if (value != null) {
final json = jsonEncode(value.toJson());
prefs.setString(kAppDashboardConfig, json);
} else {
prefs.remove(kAppDashboardConfig);
}
state = state.copyWith(dashboardConfig: value);
}
void resetDashboardConfig() {
final prefs = ref.read(sharedPreferencesProvider);
prefs.remove(kAppDashboardConfig);
state = state.copyWith(dashboardConfig: null);
}
} }
final updateInfoProvider = final updateInfoProvider =

View File

@@ -281,6 +281,284 @@ as int?,
} }
}
/// @nodoc
mixin _$DashboardConfig {
List<String> get verticalLayouts; List<String> get horizontalLayouts; bool get showSearchBar; bool get showClockAndCountdown;
/// Create a copy of DashboardConfig
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$DashboardConfigCopyWith<DashboardConfig> get copyWith => _$DashboardConfigCopyWithImpl<DashboardConfig>(this as DashboardConfig, _$identity);
/// Serializes this DashboardConfig to a JSON map.
Map<String, dynamic> toJson();
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is DashboardConfig&&const DeepCollectionEquality().equals(other.verticalLayouts, verticalLayouts)&&const DeepCollectionEquality().equals(other.horizontalLayouts, horizontalLayouts)&&(identical(other.showSearchBar, showSearchBar) || other.showSearchBar == showSearchBar)&&(identical(other.showClockAndCountdown, showClockAndCountdown) || other.showClockAndCountdown == showClockAndCountdown));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,const DeepCollectionEquality().hash(verticalLayouts),const DeepCollectionEquality().hash(horizontalLayouts),showSearchBar,showClockAndCountdown);
@override
String toString() {
return 'DashboardConfig(verticalLayouts: $verticalLayouts, horizontalLayouts: $horizontalLayouts, showSearchBar: $showSearchBar, showClockAndCountdown: $showClockAndCountdown)';
}
}
/// @nodoc
abstract mixin class $DashboardConfigCopyWith<$Res> {
factory $DashboardConfigCopyWith(DashboardConfig value, $Res Function(DashboardConfig) _then) = _$DashboardConfigCopyWithImpl;
@useResult
$Res call({
List<String> verticalLayouts, List<String> horizontalLayouts, bool showSearchBar, bool showClockAndCountdown
});
}
/// @nodoc
class _$DashboardConfigCopyWithImpl<$Res>
implements $DashboardConfigCopyWith<$Res> {
_$DashboardConfigCopyWithImpl(this._self, this._then);
final DashboardConfig _self;
final $Res Function(DashboardConfig) _then;
/// Create a copy of DashboardConfig
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? verticalLayouts = null,Object? horizontalLayouts = null,Object? showSearchBar = null,Object? showClockAndCountdown = null,}) {
return _then(_self.copyWith(
verticalLayouts: null == verticalLayouts ? _self.verticalLayouts : verticalLayouts // ignore: cast_nullable_to_non_nullable
as List<String>,horizontalLayouts: null == horizontalLayouts ? _self.horizontalLayouts : horizontalLayouts // ignore: cast_nullable_to_non_nullable
as List<String>,showSearchBar: null == showSearchBar ? _self.showSearchBar : showSearchBar // ignore: cast_nullable_to_non_nullable
as bool,showClockAndCountdown: null == showClockAndCountdown ? _self.showClockAndCountdown : showClockAndCountdown // ignore: cast_nullable_to_non_nullable
as bool,
));
}
}
/// Adds pattern-matching-related methods to [DashboardConfig].
extension DashboardConfigPatterns on DashboardConfig {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeMap<TResult extends Object?>(TResult Function( _DashboardConfig value)? $default,{required TResult orElse(),}){
final _that = this;
switch (_that) {
case _DashboardConfig() when $default != null:
return $default(_that);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult map<TResult extends Object?>(TResult Function( _DashboardConfig value) $default,){
final _that = this;
switch (_that) {
case _DashboardConfig():
return $default(_that);}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? mapOrNull<TResult extends Object?>(TResult? Function( _DashboardConfig value)? $default,){
final _that = this;
switch (_that) {
case _DashboardConfig() when $default != null:
return $default(_that);case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( List<String> verticalLayouts, List<String> horizontalLayouts, bool showSearchBar, bool showClockAndCountdown)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) {
case _DashboardConfig() when $default != null:
return $default(_that.verticalLayouts,_that.horizontalLayouts,_that.showSearchBar,_that.showClockAndCountdown);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( List<String> verticalLayouts, List<String> horizontalLayouts, bool showSearchBar, bool showClockAndCountdown) $default,) {final _that = this;
switch (_that) {
case _DashboardConfig():
return $default(_that.verticalLayouts,_that.horizontalLayouts,_that.showSearchBar,_that.showClockAndCountdown);}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( List<String> verticalLayouts, List<String> horizontalLayouts, bool showSearchBar, bool showClockAndCountdown)? $default,) {final _that = this;
switch (_that) {
case _DashboardConfig() when $default != null:
return $default(_that.verticalLayouts,_that.horizontalLayouts,_that.showSearchBar,_that.showClockAndCountdown);case _:
return null;
}
}
}
/// @nodoc
@JsonSerializable()
class _DashboardConfig implements DashboardConfig {
_DashboardConfig({required final List<String> verticalLayouts, required final List<String> horizontalLayouts, required this.showSearchBar, required this.showClockAndCountdown}): _verticalLayouts = verticalLayouts,_horizontalLayouts = horizontalLayouts;
factory _DashboardConfig.fromJson(Map<String, dynamic> json) => _$DashboardConfigFromJson(json);
final List<String> _verticalLayouts;
@override List<String> get verticalLayouts {
if (_verticalLayouts is EqualUnmodifiableListView) return _verticalLayouts;
// ignore: implicit_dynamic_type
return EqualUnmodifiableListView(_verticalLayouts);
}
final List<String> _horizontalLayouts;
@override List<String> get horizontalLayouts {
if (_horizontalLayouts is EqualUnmodifiableListView) return _horizontalLayouts;
// ignore: implicit_dynamic_type
return EqualUnmodifiableListView(_horizontalLayouts);
}
@override final bool showSearchBar;
@override final bool showClockAndCountdown;
/// Create a copy of DashboardConfig
/// with the given fields replaced by the non-null parameter values.
@override @JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$DashboardConfigCopyWith<_DashboardConfig> get copyWith => __$DashboardConfigCopyWithImpl<_DashboardConfig>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$DashboardConfigToJson(this, );
}
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _DashboardConfig&&const DeepCollectionEquality().equals(other._verticalLayouts, _verticalLayouts)&&const DeepCollectionEquality().equals(other._horizontalLayouts, _horizontalLayouts)&&(identical(other.showSearchBar, showSearchBar) || other.showSearchBar == showSearchBar)&&(identical(other.showClockAndCountdown, showClockAndCountdown) || other.showClockAndCountdown == showClockAndCountdown));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,const DeepCollectionEquality().hash(_verticalLayouts),const DeepCollectionEquality().hash(_horizontalLayouts),showSearchBar,showClockAndCountdown);
@override
String toString() {
return 'DashboardConfig(verticalLayouts: $verticalLayouts, horizontalLayouts: $horizontalLayouts, showSearchBar: $showSearchBar, showClockAndCountdown: $showClockAndCountdown)';
}
}
/// @nodoc
abstract mixin class _$DashboardConfigCopyWith<$Res> implements $DashboardConfigCopyWith<$Res> {
factory _$DashboardConfigCopyWith(_DashboardConfig value, $Res Function(_DashboardConfig) _then) = __$DashboardConfigCopyWithImpl;
@override @useResult
$Res call({
List<String> verticalLayouts, List<String> horizontalLayouts, bool showSearchBar, bool showClockAndCountdown
});
}
/// @nodoc
class __$DashboardConfigCopyWithImpl<$Res>
implements _$DashboardConfigCopyWith<$Res> {
__$DashboardConfigCopyWithImpl(this._self, this._then);
final _DashboardConfig _self;
final $Res Function(_DashboardConfig) _then;
/// Create a copy of DashboardConfig
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? verticalLayouts = null,Object? horizontalLayouts = null,Object? showSearchBar = null,Object? showClockAndCountdown = null,}) {
return _then(_DashboardConfig(
verticalLayouts: null == verticalLayouts ? _self._verticalLayouts : verticalLayouts // ignore: cast_nullable_to_non_nullable
as List<String>,horizontalLayouts: null == horizontalLayouts ? _self._horizontalLayouts : horizontalLayouts // ignore: cast_nullable_to_non_nullable
as List<String>,showSearchBar: null == showSearchBar ? _self.showSearchBar : showSearchBar // ignore: cast_nullable_to_non_nullable
as bool,showClockAndCountdown: null == showClockAndCountdown ? _self.showClockAndCountdown : showClockAndCountdown // ignore: cast_nullable_to_non_nullable
as bool,
));
}
} }
/// @nodoc /// @nodoc
@@ -290,7 +568,7 @@ mixin _$AppSettings {
ThemeColors? get customColors; Size? get windowSize;// The window size for desktop platforms ThemeColors? get customColors; Size? get windowSize;// The window size for desktop platforms
double get windowOpacity;// The window opacity for desktop platforms double get windowOpacity;// The window opacity for desktop platforms
double get cardTransparency;// The card background opacity double get cardTransparency;// The card background opacity
String? get defaultPoolId; String get messageDisplayStyle; String? get themeMode; bool get disableAnimation; bool get groupedChatList; String? get firstLaunchAt; bool get askedReview; String? get dashSearchEngine; String? get defaultScreen; bool get showFediverseContent; String? get defaultPoolId; String get messageDisplayStyle; String? get themeMode; bool get disableAnimation; bool get groupedChatList; String? get firstLaunchAt; bool get askedReview; String? get dashSearchEngine; String? get defaultScreen; bool get showFediverseContent; DashboardConfig? get dashboardConfig;
/// Create a copy of AppSettings /// Create a copy of AppSettings
/// with the given fields replaced by the non-null parameter values. /// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false) @JsonKey(includeFromJson: false, includeToJson: false)
@@ -301,16 +579,16 @@ $AppSettingsCopyWith<AppSettings> get copyWith => _$AppSettingsCopyWithImpl<AppS
@override @override
bool operator ==(Object other) { bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is AppSettings&&(identical(other.dataSavingMode, dataSavingMode) || other.dataSavingMode == dataSavingMode)&&(identical(other.soundEffects, soundEffects) || other.soundEffects == soundEffects)&&(identical(other.festivalFeatures, festivalFeatures) || other.festivalFeatures == festivalFeatures)&&(identical(other.enterToSend, enterToSend) || other.enterToSend == enterToSend)&&(identical(other.appBarTransparent, appBarTransparent) || other.appBarTransparent == appBarTransparent)&&(identical(other.showBackgroundImage, showBackgroundImage) || other.showBackgroundImage == showBackgroundImage)&&(identical(other.notifyWithHaptic, notifyWithHaptic) || other.notifyWithHaptic == notifyWithHaptic)&&(identical(other.customFonts, customFonts) || other.customFonts == customFonts)&&(identical(other.appColorScheme, appColorScheme) || other.appColorScheme == appColorScheme)&&(identical(other.customColors, customColors) || other.customColors == customColors)&&(identical(other.windowSize, windowSize) || other.windowSize == windowSize)&&(identical(other.windowOpacity, windowOpacity) || other.windowOpacity == windowOpacity)&&(identical(other.cardTransparency, cardTransparency) || other.cardTransparency == cardTransparency)&&(identical(other.defaultPoolId, defaultPoolId) || other.defaultPoolId == defaultPoolId)&&(identical(other.messageDisplayStyle, messageDisplayStyle) || other.messageDisplayStyle == messageDisplayStyle)&&(identical(other.themeMode, themeMode) || other.themeMode == themeMode)&&(identical(other.disableAnimation, disableAnimation) || other.disableAnimation == disableAnimation)&&(identical(other.groupedChatList, groupedChatList) || other.groupedChatList == groupedChatList)&&(identical(other.firstLaunchAt, firstLaunchAt) || other.firstLaunchAt == firstLaunchAt)&&(identical(other.askedReview, askedReview) || other.askedReview == askedReview)&&(identical(other.dashSearchEngine, dashSearchEngine) || other.dashSearchEngine == dashSearchEngine)&&(identical(other.defaultScreen, defaultScreen) || other.defaultScreen == defaultScreen)&&(identical(other.showFediverseContent, showFediverseContent) || other.showFediverseContent == showFediverseContent)); return identical(this, other) || (other.runtimeType == runtimeType&&other is AppSettings&&(identical(other.dataSavingMode, dataSavingMode) || other.dataSavingMode == dataSavingMode)&&(identical(other.soundEffects, soundEffects) || other.soundEffects == soundEffects)&&(identical(other.festivalFeatures, festivalFeatures) || other.festivalFeatures == festivalFeatures)&&(identical(other.enterToSend, enterToSend) || other.enterToSend == enterToSend)&&(identical(other.appBarTransparent, appBarTransparent) || other.appBarTransparent == appBarTransparent)&&(identical(other.showBackgroundImage, showBackgroundImage) || other.showBackgroundImage == showBackgroundImage)&&(identical(other.notifyWithHaptic, notifyWithHaptic) || other.notifyWithHaptic == notifyWithHaptic)&&(identical(other.customFonts, customFonts) || other.customFonts == customFonts)&&(identical(other.appColorScheme, appColorScheme) || other.appColorScheme == appColorScheme)&&(identical(other.customColors, customColors) || other.customColors == customColors)&&(identical(other.windowSize, windowSize) || other.windowSize == windowSize)&&(identical(other.windowOpacity, windowOpacity) || other.windowOpacity == windowOpacity)&&(identical(other.cardTransparency, cardTransparency) || other.cardTransparency == cardTransparency)&&(identical(other.defaultPoolId, defaultPoolId) || other.defaultPoolId == defaultPoolId)&&(identical(other.messageDisplayStyle, messageDisplayStyle) || other.messageDisplayStyle == messageDisplayStyle)&&(identical(other.themeMode, themeMode) || other.themeMode == themeMode)&&(identical(other.disableAnimation, disableAnimation) || other.disableAnimation == disableAnimation)&&(identical(other.groupedChatList, groupedChatList) || other.groupedChatList == groupedChatList)&&(identical(other.firstLaunchAt, firstLaunchAt) || other.firstLaunchAt == firstLaunchAt)&&(identical(other.askedReview, askedReview) || other.askedReview == askedReview)&&(identical(other.dashSearchEngine, dashSearchEngine) || other.dashSearchEngine == dashSearchEngine)&&(identical(other.defaultScreen, defaultScreen) || other.defaultScreen == defaultScreen)&&(identical(other.showFediverseContent, showFediverseContent) || other.showFediverseContent == showFediverseContent)&&(identical(other.dashboardConfig, dashboardConfig) || other.dashboardConfig == dashboardConfig));
} }
@override @override
int get hashCode => Object.hashAll([runtimeType,dataSavingMode,soundEffects,festivalFeatures,enterToSend,appBarTransparent,showBackgroundImage,notifyWithHaptic,customFonts,appColorScheme,customColors,windowSize,windowOpacity,cardTransparency,defaultPoolId,messageDisplayStyle,themeMode,disableAnimation,groupedChatList,firstLaunchAt,askedReview,dashSearchEngine,defaultScreen,showFediverseContent]); int get hashCode => Object.hashAll([runtimeType,dataSavingMode,soundEffects,festivalFeatures,enterToSend,appBarTransparent,showBackgroundImage,notifyWithHaptic,customFonts,appColorScheme,customColors,windowSize,windowOpacity,cardTransparency,defaultPoolId,messageDisplayStyle,themeMode,disableAnimation,groupedChatList,firstLaunchAt,askedReview,dashSearchEngine,defaultScreen,showFediverseContent,dashboardConfig]);
@override @override
String toString() { String toString() {
return 'AppSettings(dataSavingMode: $dataSavingMode, soundEffects: $soundEffects, festivalFeatures: $festivalFeatures, enterToSend: $enterToSend, appBarTransparent: $appBarTransparent, showBackgroundImage: $showBackgroundImage, notifyWithHaptic: $notifyWithHaptic, customFonts: $customFonts, appColorScheme: $appColorScheme, customColors: $customColors, windowSize: $windowSize, windowOpacity: $windowOpacity, cardTransparency: $cardTransparency, defaultPoolId: $defaultPoolId, messageDisplayStyle: $messageDisplayStyle, themeMode: $themeMode, disableAnimation: $disableAnimation, groupedChatList: $groupedChatList, firstLaunchAt: $firstLaunchAt, askedReview: $askedReview, dashSearchEngine: $dashSearchEngine, defaultScreen: $defaultScreen, showFediverseContent: $showFediverseContent)'; return 'AppSettings(dataSavingMode: $dataSavingMode, soundEffects: $soundEffects, festivalFeatures: $festivalFeatures, enterToSend: $enterToSend, appBarTransparent: $appBarTransparent, showBackgroundImage: $showBackgroundImage, notifyWithHaptic: $notifyWithHaptic, customFonts: $customFonts, appColorScheme: $appColorScheme, customColors: $customColors, windowSize: $windowSize, windowOpacity: $windowOpacity, cardTransparency: $cardTransparency, defaultPoolId: $defaultPoolId, messageDisplayStyle: $messageDisplayStyle, themeMode: $themeMode, disableAnimation: $disableAnimation, groupedChatList: $groupedChatList, firstLaunchAt: $firstLaunchAt, askedReview: $askedReview, dashSearchEngine: $dashSearchEngine, defaultScreen: $defaultScreen, showFediverseContent: $showFediverseContent, dashboardConfig: $dashboardConfig)';
} }
@@ -321,11 +599,11 @@ abstract mixin class $AppSettingsCopyWith<$Res> {
factory $AppSettingsCopyWith(AppSettings value, $Res Function(AppSettings) _then) = _$AppSettingsCopyWithImpl; factory $AppSettingsCopyWith(AppSettings value, $Res Function(AppSettings) _then) = _$AppSettingsCopyWithImpl;
@useResult @useResult
$Res call({ $Res call({
bool dataSavingMode, bool soundEffects, bool festivalFeatures, bool enterToSend, bool appBarTransparent, bool showBackgroundImage, bool notifyWithHaptic, String? customFonts, int? appColorScheme, ThemeColors? customColors, Size? windowSize, double windowOpacity, double cardTransparency, String? defaultPoolId, String messageDisplayStyle, String? themeMode, bool disableAnimation, bool groupedChatList, String? firstLaunchAt, bool askedReview, String? dashSearchEngine, String? defaultScreen, bool showFediverseContent bool dataSavingMode, bool soundEffects, bool festivalFeatures, bool enterToSend, bool appBarTransparent, bool showBackgroundImage, bool notifyWithHaptic, String? customFonts, int? appColorScheme, ThemeColors? customColors, Size? windowSize, double windowOpacity, double cardTransparency, String? defaultPoolId, String messageDisplayStyle, String? themeMode, bool disableAnimation, bool groupedChatList, String? firstLaunchAt, bool askedReview, String? dashSearchEngine, String? defaultScreen, bool showFediverseContent, DashboardConfig? dashboardConfig
}); });
$ThemeColorsCopyWith<$Res>? get customColors; $ThemeColorsCopyWith<$Res>? get customColors;$DashboardConfigCopyWith<$Res>? get dashboardConfig;
} }
/// @nodoc /// @nodoc
@@ -338,7 +616,7 @@ class _$AppSettingsCopyWithImpl<$Res>
/// Create a copy of AppSettings /// Create a copy of AppSettings
/// with the given fields replaced by the non-null parameter values. /// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? dataSavingMode = null,Object? soundEffects = null,Object? festivalFeatures = null,Object? enterToSend = null,Object? appBarTransparent = null,Object? showBackgroundImage = null,Object? notifyWithHaptic = null,Object? customFonts = freezed,Object? appColorScheme = freezed,Object? customColors = freezed,Object? windowSize = freezed,Object? windowOpacity = null,Object? cardTransparency = null,Object? defaultPoolId = freezed,Object? messageDisplayStyle = null,Object? themeMode = freezed,Object? disableAnimation = null,Object? groupedChatList = null,Object? firstLaunchAt = freezed,Object? askedReview = null,Object? dashSearchEngine = freezed,Object? defaultScreen = freezed,Object? showFediverseContent = null,}) { @pragma('vm:prefer-inline') @override $Res call({Object? dataSavingMode = null,Object? soundEffects = null,Object? festivalFeatures = null,Object? enterToSend = null,Object? appBarTransparent = null,Object? showBackgroundImage = null,Object? notifyWithHaptic = null,Object? customFonts = freezed,Object? appColorScheme = freezed,Object? customColors = freezed,Object? windowSize = freezed,Object? windowOpacity = null,Object? cardTransparency = null,Object? defaultPoolId = freezed,Object? messageDisplayStyle = null,Object? themeMode = freezed,Object? disableAnimation = null,Object? groupedChatList = null,Object? firstLaunchAt = freezed,Object? askedReview = null,Object? dashSearchEngine = freezed,Object? defaultScreen = freezed,Object? showFediverseContent = null,Object? dashboardConfig = freezed,}) {
return _then(_self.copyWith( return _then(_self.copyWith(
dataSavingMode: null == dataSavingMode ? _self.dataSavingMode : dataSavingMode // ignore: cast_nullable_to_non_nullable dataSavingMode: null == dataSavingMode ? _self.dataSavingMode : dataSavingMode // ignore: cast_nullable_to_non_nullable
as bool,soundEffects: null == soundEffects ? _self.soundEffects : soundEffects // ignore: cast_nullable_to_non_nullable as bool,soundEffects: null == soundEffects ? _self.soundEffects : soundEffects // ignore: cast_nullable_to_non_nullable
@@ -363,7 +641,8 @@ as String?,askedReview: null == askedReview ? _self.askedReview : askedReview //
as bool,dashSearchEngine: freezed == dashSearchEngine ? _self.dashSearchEngine : dashSearchEngine // ignore: cast_nullable_to_non_nullable as bool,dashSearchEngine: freezed == dashSearchEngine ? _self.dashSearchEngine : dashSearchEngine // ignore: cast_nullable_to_non_nullable
as String?,defaultScreen: freezed == defaultScreen ? _self.defaultScreen : defaultScreen // ignore: cast_nullable_to_non_nullable as String?,defaultScreen: freezed == defaultScreen ? _self.defaultScreen : defaultScreen // ignore: cast_nullable_to_non_nullable
as String?,showFediverseContent: null == showFediverseContent ? _self.showFediverseContent : showFediverseContent // ignore: cast_nullable_to_non_nullable as String?,showFediverseContent: null == showFediverseContent ? _self.showFediverseContent : showFediverseContent // ignore: cast_nullable_to_non_nullable
as bool, as bool,dashboardConfig: freezed == dashboardConfig ? _self.dashboardConfig : dashboardConfig // ignore: cast_nullable_to_non_nullable
as DashboardConfig?,
)); ));
} }
/// Create a copy of AppSettings /// Create a copy of AppSettings
@@ -378,6 +657,18 @@ $ThemeColorsCopyWith<$Res>? get customColors {
return $ThemeColorsCopyWith<$Res>(_self.customColors!, (value) { return $ThemeColorsCopyWith<$Res>(_self.customColors!, (value) {
return _then(_self.copyWith(customColors: value)); return _then(_self.copyWith(customColors: value));
}); });
}/// Create a copy of AppSettings
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$DashboardConfigCopyWith<$Res>? get dashboardConfig {
if (_self.dashboardConfig == null) {
return null;
}
return $DashboardConfigCopyWith<$Res>(_self.dashboardConfig!, (value) {
return _then(_self.copyWith(dashboardConfig: value));
});
} }
} }
@@ -457,10 +748,10 @@ return $default(_that);case _:
/// } /// }
/// ``` /// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( bool dataSavingMode, bool soundEffects, bool festivalFeatures, bool enterToSend, bool appBarTransparent, bool showBackgroundImage, bool notifyWithHaptic, String? customFonts, int? appColorScheme, ThemeColors? customColors, Size? windowSize, double windowOpacity, double cardTransparency, String? defaultPoolId, String messageDisplayStyle, String? themeMode, bool disableAnimation, bool groupedChatList, String? firstLaunchAt, bool askedReview, String? dashSearchEngine, String? defaultScreen, bool showFediverseContent)? $default,{required TResult orElse(),}) {final _that = this; @optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( bool dataSavingMode, bool soundEffects, bool festivalFeatures, bool enterToSend, bool appBarTransparent, bool showBackgroundImage, bool notifyWithHaptic, String? customFonts, int? appColorScheme, ThemeColors? customColors, Size? windowSize, double windowOpacity, double cardTransparency, String? defaultPoolId, String messageDisplayStyle, String? themeMode, bool disableAnimation, bool groupedChatList, String? firstLaunchAt, bool askedReview, String? dashSearchEngine, String? defaultScreen, bool showFediverseContent, DashboardConfig? dashboardConfig)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) { switch (_that) {
case _AppSettings() when $default != null: case _AppSettings() when $default != null:
return $default(_that.dataSavingMode,_that.soundEffects,_that.festivalFeatures,_that.enterToSend,_that.appBarTransparent,_that.showBackgroundImage,_that.notifyWithHaptic,_that.customFonts,_that.appColorScheme,_that.customColors,_that.windowSize,_that.windowOpacity,_that.cardTransparency,_that.defaultPoolId,_that.messageDisplayStyle,_that.themeMode,_that.disableAnimation,_that.groupedChatList,_that.firstLaunchAt,_that.askedReview,_that.dashSearchEngine,_that.defaultScreen,_that.showFediverseContent);case _: return $default(_that.dataSavingMode,_that.soundEffects,_that.festivalFeatures,_that.enterToSend,_that.appBarTransparent,_that.showBackgroundImage,_that.notifyWithHaptic,_that.customFonts,_that.appColorScheme,_that.customColors,_that.windowSize,_that.windowOpacity,_that.cardTransparency,_that.defaultPoolId,_that.messageDisplayStyle,_that.themeMode,_that.disableAnimation,_that.groupedChatList,_that.firstLaunchAt,_that.askedReview,_that.dashSearchEngine,_that.defaultScreen,_that.showFediverseContent,_that.dashboardConfig);case _:
return orElse(); return orElse();
} }
@@ -478,10 +769,10 @@ return $default(_that.dataSavingMode,_that.soundEffects,_that.festivalFeatures,_
/// } /// }
/// ``` /// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( bool dataSavingMode, bool soundEffects, bool festivalFeatures, bool enterToSend, bool appBarTransparent, bool showBackgroundImage, bool notifyWithHaptic, String? customFonts, int? appColorScheme, ThemeColors? customColors, Size? windowSize, double windowOpacity, double cardTransparency, String? defaultPoolId, String messageDisplayStyle, String? themeMode, bool disableAnimation, bool groupedChatList, String? firstLaunchAt, bool askedReview, String? dashSearchEngine, String? defaultScreen, bool showFediverseContent) $default,) {final _that = this; @optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( bool dataSavingMode, bool soundEffects, bool festivalFeatures, bool enterToSend, bool appBarTransparent, bool showBackgroundImage, bool notifyWithHaptic, String? customFonts, int? appColorScheme, ThemeColors? customColors, Size? windowSize, double windowOpacity, double cardTransparency, String? defaultPoolId, String messageDisplayStyle, String? themeMode, bool disableAnimation, bool groupedChatList, String? firstLaunchAt, bool askedReview, String? dashSearchEngine, String? defaultScreen, bool showFediverseContent, DashboardConfig? dashboardConfig) $default,) {final _that = this;
switch (_that) { switch (_that) {
case _AppSettings(): case _AppSettings():
return $default(_that.dataSavingMode,_that.soundEffects,_that.festivalFeatures,_that.enterToSend,_that.appBarTransparent,_that.showBackgroundImage,_that.notifyWithHaptic,_that.customFonts,_that.appColorScheme,_that.customColors,_that.windowSize,_that.windowOpacity,_that.cardTransparency,_that.defaultPoolId,_that.messageDisplayStyle,_that.themeMode,_that.disableAnimation,_that.groupedChatList,_that.firstLaunchAt,_that.askedReview,_that.dashSearchEngine,_that.defaultScreen,_that.showFediverseContent);} return $default(_that.dataSavingMode,_that.soundEffects,_that.festivalFeatures,_that.enterToSend,_that.appBarTransparent,_that.showBackgroundImage,_that.notifyWithHaptic,_that.customFonts,_that.appColorScheme,_that.customColors,_that.windowSize,_that.windowOpacity,_that.cardTransparency,_that.defaultPoolId,_that.messageDisplayStyle,_that.themeMode,_that.disableAnimation,_that.groupedChatList,_that.firstLaunchAt,_that.askedReview,_that.dashSearchEngine,_that.defaultScreen,_that.showFediverseContent,_that.dashboardConfig);}
} }
/// A variant of `when` that fallback to returning `null` /// A variant of `when` that fallback to returning `null`
/// ///
@@ -495,10 +786,10 @@ return $default(_that.dataSavingMode,_that.soundEffects,_that.festivalFeatures,_
/// } /// }
/// ``` /// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( bool dataSavingMode, bool soundEffects, bool festivalFeatures, bool enterToSend, bool appBarTransparent, bool showBackgroundImage, bool notifyWithHaptic, String? customFonts, int? appColorScheme, ThemeColors? customColors, Size? windowSize, double windowOpacity, double cardTransparency, String? defaultPoolId, String messageDisplayStyle, String? themeMode, bool disableAnimation, bool groupedChatList, String? firstLaunchAt, bool askedReview, String? dashSearchEngine, String? defaultScreen, bool showFediverseContent)? $default,) {final _that = this; @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( bool dataSavingMode, bool soundEffects, bool festivalFeatures, bool enterToSend, bool appBarTransparent, bool showBackgroundImage, bool notifyWithHaptic, String? customFonts, int? appColorScheme, ThemeColors? customColors, Size? windowSize, double windowOpacity, double cardTransparency, String? defaultPoolId, String messageDisplayStyle, String? themeMode, bool disableAnimation, bool groupedChatList, String? firstLaunchAt, bool askedReview, String? dashSearchEngine, String? defaultScreen, bool showFediverseContent, DashboardConfig? dashboardConfig)? $default,) {final _that = this;
switch (_that) { switch (_that) {
case _AppSettings() when $default != null: case _AppSettings() when $default != null:
return $default(_that.dataSavingMode,_that.soundEffects,_that.festivalFeatures,_that.enterToSend,_that.appBarTransparent,_that.showBackgroundImage,_that.notifyWithHaptic,_that.customFonts,_that.appColorScheme,_that.customColors,_that.windowSize,_that.windowOpacity,_that.cardTransparency,_that.defaultPoolId,_that.messageDisplayStyle,_that.themeMode,_that.disableAnimation,_that.groupedChatList,_that.firstLaunchAt,_that.askedReview,_that.dashSearchEngine,_that.defaultScreen,_that.showFediverseContent);case _: return $default(_that.dataSavingMode,_that.soundEffects,_that.festivalFeatures,_that.enterToSend,_that.appBarTransparent,_that.showBackgroundImage,_that.notifyWithHaptic,_that.customFonts,_that.appColorScheme,_that.customColors,_that.windowSize,_that.windowOpacity,_that.cardTransparency,_that.defaultPoolId,_that.messageDisplayStyle,_that.themeMode,_that.disableAnimation,_that.groupedChatList,_that.firstLaunchAt,_that.askedReview,_that.dashSearchEngine,_that.defaultScreen,_that.showFediverseContent,_that.dashboardConfig);case _:
return null; return null;
} }
@@ -510,7 +801,7 @@ return $default(_that.dataSavingMode,_that.soundEffects,_that.festivalFeatures,_
class _AppSettings implements AppSettings { class _AppSettings implements AppSettings {
const _AppSettings({required this.dataSavingMode, required this.soundEffects, required this.festivalFeatures, required this.enterToSend, required this.appBarTransparent, required this.showBackgroundImage, required this.notifyWithHaptic, required this.customFonts, required this.appColorScheme, required this.customColors, required this.windowSize, required this.windowOpacity, required this.cardTransparency, required this.defaultPoolId, required this.messageDisplayStyle, required this.themeMode, required this.disableAnimation, required this.groupedChatList, required this.firstLaunchAt, required this.askedReview, required this.dashSearchEngine, required this.defaultScreen, required this.showFediverseContent}); const _AppSettings({required this.dataSavingMode, required this.soundEffects, required this.festivalFeatures, required this.enterToSend, required this.appBarTransparent, required this.showBackgroundImage, required this.notifyWithHaptic, required this.customFonts, required this.appColorScheme, required this.customColors, required this.windowSize, required this.windowOpacity, required this.cardTransparency, required this.defaultPoolId, required this.messageDisplayStyle, required this.themeMode, required this.disableAnimation, required this.groupedChatList, required this.firstLaunchAt, required this.askedReview, required this.dashSearchEngine, required this.defaultScreen, required this.showFediverseContent, required this.dashboardConfig});
@override final bool dataSavingMode; @override final bool dataSavingMode;
@@ -540,6 +831,7 @@ class _AppSettings implements AppSettings {
@override final String? dashSearchEngine; @override final String? dashSearchEngine;
@override final String? defaultScreen; @override final String? defaultScreen;
@override final bool showFediverseContent; @override final bool showFediverseContent;
@override final DashboardConfig? dashboardConfig;
/// Create a copy of AppSettings /// Create a copy of AppSettings
/// with the given fields replaced by the non-null parameter values. /// with the given fields replaced by the non-null parameter values.
@@ -551,16 +843,16 @@ _$AppSettingsCopyWith<_AppSettings> get copyWith => __$AppSettingsCopyWithImpl<_
@override @override
bool operator ==(Object other) { bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _AppSettings&&(identical(other.dataSavingMode, dataSavingMode) || other.dataSavingMode == dataSavingMode)&&(identical(other.soundEffects, soundEffects) || other.soundEffects == soundEffects)&&(identical(other.festivalFeatures, festivalFeatures) || other.festivalFeatures == festivalFeatures)&&(identical(other.enterToSend, enterToSend) || other.enterToSend == enterToSend)&&(identical(other.appBarTransparent, appBarTransparent) || other.appBarTransparent == appBarTransparent)&&(identical(other.showBackgroundImage, showBackgroundImage) || other.showBackgroundImage == showBackgroundImage)&&(identical(other.notifyWithHaptic, notifyWithHaptic) || other.notifyWithHaptic == notifyWithHaptic)&&(identical(other.customFonts, customFonts) || other.customFonts == customFonts)&&(identical(other.appColorScheme, appColorScheme) || other.appColorScheme == appColorScheme)&&(identical(other.customColors, customColors) || other.customColors == customColors)&&(identical(other.windowSize, windowSize) || other.windowSize == windowSize)&&(identical(other.windowOpacity, windowOpacity) || other.windowOpacity == windowOpacity)&&(identical(other.cardTransparency, cardTransparency) || other.cardTransparency == cardTransparency)&&(identical(other.defaultPoolId, defaultPoolId) || other.defaultPoolId == defaultPoolId)&&(identical(other.messageDisplayStyle, messageDisplayStyle) || other.messageDisplayStyle == messageDisplayStyle)&&(identical(other.themeMode, themeMode) || other.themeMode == themeMode)&&(identical(other.disableAnimation, disableAnimation) || other.disableAnimation == disableAnimation)&&(identical(other.groupedChatList, groupedChatList) || other.groupedChatList == groupedChatList)&&(identical(other.firstLaunchAt, firstLaunchAt) || other.firstLaunchAt == firstLaunchAt)&&(identical(other.askedReview, askedReview) || other.askedReview == askedReview)&&(identical(other.dashSearchEngine, dashSearchEngine) || other.dashSearchEngine == dashSearchEngine)&&(identical(other.defaultScreen, defaultScreen) || other.defaultScreen == defaultScreen)&&(identical(other.showFediverseContent, showFediverseContent) || other.showFediverseContent == showFediverseContent)); return identical(this, other) || (other.runtimeType == runtimeType&&other is _AppSettings&&(identical(other.dataSavingMode, dataSavingMode) || other.dataSavingMode == dataSavingMode)&&(identical(other.soundEffects, soundEffects) || other.soundEffects == soundEffects)&&(identical(other.festivalFeatures, festivalFeatures) || other.festivalFeatures == festivalFeatures)&&(identical(other.enterToSend, enterToSend) || other.enterToSend == enterToSend)&&(identical(other.appBarTransparent, appBarTransparent) || other.appBarTransparent == appBarTransparent)&&(identical(other.showBackgroundImage, showBackgroundImage) || other.showBackgroundImage == showBackgroundImage)&&(identical(other.notifyWithHaptic, notifyWithHaptic) || other.notifyWithHaptic == notifyWithHaptic)&&(identical(other.customFonts, customFonts) || other.customFonts == customFonts)&&(identical(other.appColorScheme, appColorScheme) || other.appColorScheme == appColorScheme)&&(identical(other.customColors, customColors) || other.customColors == customColors)&&(identical(other.windowSize, windowSize) || other.windowSize == windowSize)&&(identical(other.windowOpacity, windowOpacity) || other.windowOpacity == windowOpacity)&&(identical(other.cardTransparency, cardTransparency) || other.cardTransparency == cardTransparency)&&(identical(other.defaultPoolId, defaultPoolId) || other.defaultPoolId == defaultPoolId)&&(identical(other.messageDisplayStyle, messageDisplayStyle) || other.messageDisplayStyle == messageDisplayStyle)&&(identical(other.themeMode, themeMode) || other.themeMode == themeMode)&&(identical(other.disableAnimation, disableAnimation) || other.disableAnimation == disableAnimation)&&(identical(other.groupedChatList, groupedChatList) || other.groupedChatList == groupedChatList)&&(identical(other.firstLaunchAt, firstLaunchAt) || other.firstLaunchAt == firstLaunchAt)&&(identical(other.askedReview, askedReview) || other.askedReview == askedReview)&&(identical(other.dashSearchEngine, dashSearchEngine) || other.dashSearchEngine == dashSearchEngine)&&(identical(other.defaultScreen, defaultScreen) || other.defaultScreen == defaultScreen)&&(identical(other.showFediverseContent, showFediverseContent) || other.showFediverseContent == showFediverseContent)&&(identical(other.dashboardConfig, dashboardConfig) || other.dashboardConfig == dashboardConfig));
} }
@override @override
int get hashCode => Object.hashAll([runtimeType,dataSavingMode,soundEffects,festivalFeatures,enterToSend,appBarTransparent,showBackgroundImage,notifyWithHaptic,customFonts,appColorScheme,customColors,windowSize,windowOpacity,cardTransparency,defaultPoolId,messageDisplayStyle,themeMode,disableAnimation,groupedChatList,firstLaunchAt,askedReview,dashSearchEngine,defaultScreen,showFediverseContent]); int get hashCode => Object.hashAll([runtimeType,dataSavingMode,soundEffects,festivalFeatures,enterToSend,appBarTransparent,showBackgroundImage,notifyWithHaptic,customFonts,appColorScheme,customColors,windowSize,windowOpacity,cardTransparency,defaultPoolId,messageDisplayStyle,themeMode,disableAnimation,groupedChatList,firstLaunchAt,askedReview,dashSearchEngine,defaultScreen,showFediverseContent,dashboardConfig]);
@override @override
String toString() { String toString() {
return 'AppSettings(dataSavingMode: $dataSavingMode, soundEffects: $soundEffects, festivalFeatures: $festivalFeatures, enterToSend: $enterToSend, appBarTransparent: $appBarTransparent, showBackgroundImage: $showBackgroundImage, notifyWithHaptic: $notifyWithHaptic, customFonts: $customFonts, appColorScheme: $appColorScheme, customColors: $customColors, windowSize: $windowSize, windowOpacity: $windowOpacity, cardTransparency: $cardTransparency, defaultPoolId: $defaultPoolId, messageDisplayStyle: $messageDisplayStyle, themeMode: $themeMode, disableAnimation: $disableAnimation, groupedChatList: $groupedChatList, firstLaunchAt: $firstLaunchAt, askedReview: $askedReview, dashSearchEngine: $dashSearchEngine, defaultScreen: $defaultScreen, showFediverseContent: $showFediverseContent)'; return 'AppSettings(dataSavingMode: $dataSavingMode, soundEffects: $soundEffects, festivalFeatures: $festivalFeatures, enterToSend: $enterToSend, appBarTransparent: $appBarTransparent, showBackgroundImage: $showBackgroundImage, notifyWithHaptic: $notifyWithHaptic, customFonts: $customFonts, appColorScheme: $appColorScheme, customColors: $customColors, windowSize: $windowSize, windowOpacity: $windowOpacity, cardTransparency: $cardTransparency, defaultPoolId: $defaultPoolId, messageDisplayStyle: $messageDisplayStyle, themeMode: $themeMode, disableAnimation: $disableAnimation, groupedChatList: $groupedChatList, firstLaunchAt: $firstLaunchAt, askedReview: $askedReview, dashSearchEngine: $dashSearchEngine, defaultScreen: $defaultScreen, showFediverseContent: $showFediverseContent, dashboardConfig: $dashboardConfig)';
} }
@@ -571,11 +863,11 @@ abstract mixin class _$AppSettingsCopyWith<$Res> implements $AppSettingsCopyWith
factory _$AppSettingsCopyWith(_AppSettings value, $Res Function(_AppSettings) _then) = __$AppSettingsCopyWithImpl; factory _$AppSettingsCopyWith(_AppSettings value, $Res Function(_AppSettings) _then) = __$AppSettingsCopyWithImpl;
@override @useResult @override @useResult
$Res call({ $Res call({
bool dataSavingMode, bool soundEffects, bool festivalFeatures, bool enterToSend, bool appBarTransparent, bool showBackgroundImage, bool notifyWithHaptic, String? customFonts, int? appColorScheme, ThemeColors? customColors, Size? windowSize, double windowOpacity, double cardTransparency, String? defaultPoolId, String messageDisplayStyle, String? themeMode, bool disableAnimation, bool groupedChatList, String? firstLaunchAt, bool askedReview, String? dashSearchEngine, String? defaultScreen, bool showFediverseContent bool dataSavingMode, bool soundEffects, bool festivalFeatures, bool enterToSend, bool appBarTransparent, bool showBackgroundImage, bool notifyWithHaptic, String? customFonts, int? appColorScheme, ThemeColors? customColors, Size? windowSize, double windowOpacity, double cardTransparency, String? defaultPoolId, String messageDisplayStyle, String? themeMode, bool disableAnimation, bool groupedChatList, String? firstLaunchAt, bool askedReview, String? dashSearchEngine, String? defaultScreen, bool showFediverseContent, DashboardConfig? dashboardConfig
}); });
@override $ThemeColorsCopyWith<$Res>? get customColors; @override $ThemeColorsCopyWith<$Res>? get customColors;@override $DashboardConfigCopyWith<$Res>? get dashboardConfig;
} }
/// @nodoc /// @nodoc
@@ -588,7 +880,7 @@ class __$AppSettingsCopyWithImpl<$Res>
/// Create a copy of AppSettings /// Create a copy of AppSettings
/// with the given fields replaced by the non-null parameter values. /// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? dataSavingMode = null,Object? soundEffects = null,Object? festivalFeatures = null,Object? enterToSend = null,Object? appBarTransparent = null,Object? showBackgroundImage = null,Object? notifyWithHaptic = null,Object? customFonts = freezed,Object? appColorScheme = freezed,Object? customColors = freezed,Object? windowSize = freezed,Object? windowOpacity = null,Object? cardTransparency = null,Object? defaultPoolId = freezed,Object? messageDisplayStyle = null,Object? themeMode = freezed,Object? disableAnimation = null,Object? groupedChatList = null,Object? firstLaunchAt = freezed,Object? askedReview = null,Object? dashSearchEngine = freezed,Object? defaultScreen = freezed,Object? showFediverseContent = null,}) { @override @pragma('vm:prefer-inline') $Res call({Object? dataSavingMode = null,Object? soundEffects = null,Object? festivalFeatures = null,Object? enterToSend = null,Object? appBarTransparent = null,Object? showBackgroundImage = null,Object? notifyWithHaptic = null,Object? customFonts = freezed,Object? appColorScheme = freezed,Object? customColors = freezed,Object? windowSize = freezed,Object? windowOpacity = null,Object? cardTransparency = null,Object? defaultPoolId = freezed,Object? messageDisplayStyle = null,Object? themeMode = freezed,Object? disableAnimation = null,Object? groupedChatList = null,Object? firstLaunchAt = freezed,Object? askedReview = null,Object? dashSearchEngine = freezed,Object? defaultScreen = freezed,Object? showFediverseContent = null,Object? dashboardConfig = freezed,}) {
return _then(_AppSettings( return _then(_AppSettings(
dataSavingMode: null == dataSavingMode ? _self.dataSavingMode : dataSavingMode // ignore: cast_nullable_to_non_nullable dataSavingMode: null == dataSavingMode ? _self.dataSavingMode : dataSavingMode // ignore: cast_nullable_to_non_nullable
as bool,soundEffects: null == soundEffects ? _self.soundEffects : soundEffects // ignore: cast_nullable_to_non_nullable as bool,soundEffects: null == soundEffects ? _self.soundEffects : soundEffects // ignore: cast_nullable_to_non_nullable
@@ -613,7 +905,8 @@ as String?,askedReview: null == askedReview ? _self.askedReview : askedReview //
as bool,dashSearchEngine: freezed == dashSearchEngine ? _self.dashSearchEngine : dashSearchEngine // ignore: cast_nullable_to_non_nullable as bool,dashSearchEngine: freezed == dashSearchEngine ? _self.dashSearchEngine : dashSearchEngine // ignore: cast_nullable_to_non_nullable
as String?,defaultScreen: freezed == defaultScreen ? _self.defaultScreen : defaultScreen // ignore: cast_nullable_to_non_nullable as String?,defaultScreen: freezed == defaultScreen ? _self.defaultScreen : defaultScreen // ignore: cast_nullable_to_non_nullable
as String?,showFediverseContent: null == showFediverseContent ? _self.showFediverseContent : showFediverseContent // ignore: cast_nullable_to_non_nullable as String?,showFediverseContent: null == showFediverseContent ? _self.showFediverseContent : showFediverseContent // ignore: cast_nullable_to_non_nullable
as bool, as bool,dashboardConfig: freezed == dashboardConfig ? _self.dashboardConfig : dashboardConfig // ignore: cast_nullable_to_non_nullable
as DashboardConfig?,
)); ));
} }
@@ -629,6 +922,18 @@ $ThemeColorsCopyWith<$Res>? get customColors {
return $ThemeColorsCopyWith<$Res>(_self.customColors!, (value) { return $ThemeColorsCopyWith<$Res>(_self.customColors!, (value) {
return _then(_self.copyWith(customColors: value)); return _then(_self.copyWith(customColors: value));
}); });
}/// Create a copy of AppSettings
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$DashboardConfigCopyWith<$Res>? get dashboardConfig {
if (_self.dashboardConfig == null) {
return null;
}
return $DashboardConfigCopyWith<$Res>(_self.dashboardConfig!, (value) {
return _then(_self.copyWith(dashboardConfig: value));
});
} }
} }

View File

@@ -25,6 +25,26 @@ Map<String, dynamic> _$ThemeColorsToJson(_ThemeColors instance) =>
'error': instance.error, 'error': instance.error,
}; };
_DashboardConfig _$DashboardConfigFromJson(Map<String, dynamic> json) =>
_DashboardConfig(
verticalLayouts: (json['vertical_layouts'] as List<dynamic>)
.map((e) => e as String)
.toList(),
horizontalLayouts: (json['horizontal_layouts'] as List<dynamic>)
.map((e) => e as String)
.toList(),
showSearchBar: json['show_search_bar'] as bool,
showClockAndCountdown: json['show_clock_and_countdown'] as bool,
);
Map<String, dynamic> _$DashboardConfigToJson(_DashboardConfig instance) =>
<String, dynamic>{
'vertical_layouts': instance.verticalLayouts,
'horizontal_layouts': instance.horizontalLayouts,
'show_search_bar': instance.showSearchBar,
'show_clock_and_countdown': instance.showClockAndCountdown,
};
// ************************************************************************** // **************************************************************************
// RiverpodGenerator // RiverpodGenerator
// ************************************************************************** // **************************************************************************
@@ -65,7 +85,7 @@ final class AppSettingsNotifierProvider
} }
String _$appSettingsNotifierHash() => String _$appSettingsNotifierHash() =>
r'2437c621dcb1625a120ed1f21ab5c29906ba98be'; r'0a7f75bd95850b0c564b29c57912ec8fcac53f09';
abstract class _$AppSettingsNotifier extends $Notifier<AppSettings> { abstract class _$AppSettingsNotifier extends $Notifier<AppSettings> {
AppSettings build(); AppSettings build();

View File

@@ -1,15 +0,0 @@
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:island/models/reference.dart';
import 'package:island/pods/network.dart';
part 'file_references.g.dart';
@riverpod
Future<List<Reference>> fileReferences(Ref ref, String fileId) async {
final client = ref.read(apiClientProvider);
final response = await client.get('/drive/files/$fileId/references');
final list = response.data as List<dynamic>;
return list
.map((json) => Reference.fromJson(json as Map<String, dynamic>))
.toList();
}

View File

@@ -1,85 +0,0 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'file_references.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(fileReferences)
final fileReferencesProvider = FileReferencesFamily._();
final class FileReferencesProvider
extends
$FunctionalProvider<
AsyncValue<List<Reference>>,
List<Reference>,
FutureOr<List<Reference>>
>
with $FutureModifier<List<Reference>>, $FutureProvider<List<Reference>> {
FileReferencesProvider._({
required FileReferencesFamily super.from,
required String super.argument,
}) : super(
retry: null,
name: r'fileReferencesProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$fileReferencesHash();
@override
String toString() {
return r'fileReferencesProvider'
''
'($argument)';
}
@$internal
@override
$FutureProviderElement<List<Reference>> $createElement(
$ProviderPointer pointer,
) => $FutureProviderElement(pointer);
@override
FutureOr<List<Reference>> create(Ref ref) {
final argument = this.argument as String;
return fileReferences(ref, argument);
}
@override
bool operator ==(Object other) {
return other is FileReferencesProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$fileReferencesHash() => r'd66c678c221f61978bdb242b98e6dbe31d0c204b';
final class FileReferencesFamily extends $Family
with $FunctionalFamilyOverride<FutureOr<List<Reference>>, String> {
FileReferencesFamily._()
: super(
retry: null,
name: r'fileReferencesProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: true,
);
FileReferencesProvider call(String fileId) =>
FileReferencesProvider._(argument: fileId, from: this);
@override
String toString() => r'fileReferencesProvider';
}

View File

@@ -29,30 +29,59 @@ class UploadTasksNotifier extends Notifier<List<DriveTask>> {
} }
void _handleWebSocketPacket(dynamic packet) { void _handleWebSocketPacket(dynamic packet) {
if (packet.type.startsWith('task.')) { if (packet.type.startsWith('task.') || packet.type == 'upload.completed') {
final data = packet.data; final data = packet.data;
if (data == null) return; if (data == null && packet.type != 'upload.completed') return;
// Debug logging // Debug logging
talker.info( talker.info(
'[UploadTasks] Received WebSocket packet: ${packet.type}, data: $data', '[UploadTasks] Received WebSocket packet: ${packet.type}, data: $data',
); );
final taskId = data['task_id'] as String?; final taskId = data != null ? (data['task_id'] as String?) : null;
if (taskId == null) return; if (taskId == null && packet.type != 'upload.completed') return;
switch (packet.type) { switch (packet.type) {
case 'task.created': case 'task.created':
_handleTaskCreated(taskId, data); _handleTaskCreated(taskId!, data);
break; break;
case 'task.progress': case 'task.progress':
_handleProgressUpdate(taskId, data); _handleProgressUpdate(taskId!, data);
break; break;
case 'task.completed': case 'task.completed':
_handleUploadCompleted(taskId, data); _handleUploadCompleted(taskId!, data);
break;
case 'upload.completed':
// For upload.completed, we need to find the taskId differently
// Since data is null, we can't get task_id from data
// We'll need to mark all in-progress uploads as completed
// For now, assume we need to handle it per task, but since no task_id,
// perhaps it's a broadcast or we need to modify the logic
// Actually, looking at the logs, upload.completed has data: null, but maybe in real scenario it has task_id?
// For now, let's assume it needs task_id, and modify accordingly
// But since the original code expects data, perhaps the server sends data with task_id
// Wait, in the logs: "upload.completed null" - the null is data, but perhaps in code it's null
// To be safe, let's modify to handle upload.completed even with null data, but we need task_id
// Perhaps search for in-progress tasks and complete them
// But that's risky. Let's see the log again: the previous task.progress had task_id: YvvfVbaWSxj5vUnFnzJDu
// So probably upload.completed should have the same task_id
// Perhaps the server sends it with data containing task_id
// The log says "upload.completed null" meaning data is null
// But maybe it's a logging issue. To fix, let's assume data has task_id for upload.completed
// If not, we can modify _handleUploadCompleted to accept null data and find the task
if (data != null && data['task_id'] != null) {
_handleUploadCompleted(data['task_id'], data);
} else {
// If no data, perhaps complete the most recent in-progress task
final inProgressTasks = state.where((task) => task.status == DriveTaskStatus.inProgress).toList();
if (inProgressTasks.isNotEmpty) {
final task = inProgressTasks.last; // Assume the last one
_handleUploadCompleted(task.taskId, {});
}
}
break; break;
case 'task.failed': case 'task.failed':
_handleUploadFailed(taskId, data); _handleUploadFailed(taskId!, data);
break; break;
} }
} }
@@ -256,6 +285,21 @@ class UploadTasksNotifier extends Notifier<List<DriveTask>> {
}).toList(); }).toList();
} }
void updateUploadProgress(String taskId, int uploadedBytes, int uploadedChunks) {
state =
state.map((task) {
if (task.taskId == taskId) {
return task.copyWith(
uploadedBytes: uploadedBytes,
uploadedChunks: uploadedChunks,
status: DriveTaskStatus.inProgress,
updatedAt: DateTime.now(),
);
}
return task;
}).toList();
}
void updateDownloadProgress( void updateDownloadProgress(
String taskId, String taskId,
int downloadedBytes, int downloadedBytes,
@@ -470,6 +514,7 @@ class EnhancedFileUploader extends FileUploader {
// Step 2: Upload chunks // Step 2: Upload chunks
int bytesUploaded = 0; int bytesUploaded = 0;
int chunksUploaded = 0;
if (fileData is XFile) { if (fileData is XFile) {
// Use stream for XFile // Use stream for XFile
final subscription = fileData.openRead().listen(null); final subscription = fileData.openRead().listen(null);
@@ -494,6 +539,11 @@ class EnhancedFileUploader extends FileUploader {
}, },
); );
bytesUploaded += chunkData.length; bytesUploaded += chunkData.length;
chunksUploaded += 1;
// Update upload progress in UI
ref
.read(uploadTasksProvider.notifier)
.updateUploadProgress(taskId, bytesUploaded, chunksUploaded);
} }
subscription.cancel(); subscription.cancel();
} else if (fileData is Uint8List) { } else if (fileData is Uint8List) {
@@ -521,6 +571,11 @@ class EnhancedFileUploader extends FileUploader {
}, },
); );
bytesUploaded += chunks[i].length; bytesUploaded += chunks[i].length;
chunksUploaded += 1;
// Update upload progress in UI
ref
.read(uploadTasksProvider.notifier)
.updateUploadProgress(taskId, bytesUploaded, chunksUploaded);
} }
} else { } else {
throw ArgumentError('Invalid fileData type'); throw ArgumentError('Invalid fileData type');

View File

@@ -0,0 +1,99 @@
import 'dart:async';
import 'package:island/models/account.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:uuid/uuid.dart';
part 'notification.g.dart';
const kNotificationBaseDuration = Duration(seconds: 5);
const kNotificationStackedDuration = Duration(seconds: 1);
class NotificationItem {
final String id;
final SnNotification notification;
final DateTime createdAt;
final int index;
final Duration duration;
final bool dismissed;
NotificationItem({
String? id,
required this.notification,
DateTime? createdAt,
required this.index,
Duration? duration,
this.dismissed = false,
}) : id = id ?? const Uuid().v4(),
createdAt = createdAt ?? DateTime.now(),
duration =
duration ?? kNotificationBaseDuration + Duration(seconds: index);
NotificationItem copyWith({
String? id,
SnNotification? notification,
DateTime? createdAt,
int? index,
Duration? duration,
bool? dismissed,
}) {
return NotificationItem(
id: id ?? this.id,
notification: notification ?? this.notification,
createdAt: createdAt ?? this.createdAt,
index: index ?? this.index,
duration: duration ?? this.duration,
dismissed: dismissed ?? this.dismissed,
);
}
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is NotificationItem && other.id == id;
}
@override
int get hashCode => id.hashCode;
}
@riverpod
class NotificationState extends _$NotificationState {
final Map<String, Timer> _timers = {};
@override
List<NotificationItem> build() {
return [];
}
void add(SnNotification notification, {Duration? duration}) {
final newItem = NotificationItem(
notification: notification,
index: state.length,
duration: duration,
);
state = [...state, newItem];
_timers[newItem.id] = Timer(newItem.duration, () => dismiss(newItem.id));
}
void dismiss(String id) {
_timers[id]?.cancel();
_timers.remove(id);
final index = state.indexWhere((item) => item.id == id);
if (index != -1) {
state = List.from(state)..[index] = state[index].copyWith(dismissed: true);
}
}
void remove(String id) {
state = state.where((item) => item.id != id).toList();
}
void clear() {
for (final timer in _timers.values) {
timer.cancel();
}
_timers.clear();
state = [];
}
}

View File

@@ -0,0 +1,63 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'notification.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(NotificationState)
final notificationStateProvider = NotificationStateProvider._();
final class NotificationStateProvider
extends $NotifierProvider<NotificationState, List<NotificationItem>> {
NotificationStateProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'notificationStateProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$notificationStateHash();
@$internal
@override
NotificationState create() => NotificationState();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(List<NotificationItem> value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<List<NotificationItem>>(value),
);
}
}
String _$notificationStateHash() => r'4597cfc7c75dd0fd05dab65f78265a3ae10d23e7';
abstract class _$NotificationState extends $Notifier<List<NotificationItem>> {
List<NotificationItem> build();
@$mustCallSuper
@override
void runBuild() {
final ref =
this.ref as $Ref<List<NotificationItem>, List<NotificationItem>>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<List<NotificationItem>, List<NotificationItem>>,
List<NotificationItem>,
Object?,
Object?
>;
element.handleCreate(ref, build);
}
}

View File

@@ -1,10 +1,6 @@
import 'dart:convert'; import 'dart:convert';
import 'dart:io' show Platform;
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import 'package:easy_localization/easy_localization.dart'; import 'package:easy_localization/easy_localization.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:island/widgets/alert.dart'; import 'package:island/widgets/alert.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
@@ -13,6 +9,7 @@ import 'package:island/models/account.dart';
import 'package:island/pods/config.dart'; import 'package:island/pods/config.dart';
import 'package:island/pods/network.dart'; import 'package:island/pods/network.dart';
import 'package:island/talker.dart'; import 'package:island/talker.dart';
import 'package:island/services/analytics_service.dart';
class UserInfoNotifier extends AsyncNotifier<SnAccount?> { class UserInfoNotifier extends AsyncNotifier<SnAccount?> {
@override @override
@@ -31,9 +28,7 @@ class UserInfoNotifier extends AsyncNotifier<SnAccount?> {
final response = await client.get('/pass/accounts/me'); final response = await client.get('/pass/accounts/me');
final user = SnAccount.fromJson(response.data); final user = SnAccount.fromJson(response.data);
if (kIsWeb || !(Platform.isLinux || Platform.isWindows)) { AnalyticsService().setUserId(user.id);
FirebaseAnalytics.instance.setUserId(id: user.id);
}
return user; return user;
} catch (error, stackTrace) { } catch (error, stackTrace) {
if (error is DioException) { if (error is DioException) {
@@ -91,9 +86,8 @@ class UserInfoNotifier extends AsyncNotifier<SnAccount?> {
final prefs = ref.read(sharedPreferencesProvider); final prefs = ref.read(sharedPreferencesProvider);
await prefs.remove(kTokenPairStoreKey); await prefs.remove(kTokenPairStoreKey);
ref.invalidate(tokenProvider); ref.invalidate(tokenProvider);
if (kIsWeb || !(Platform.isLinux || Platform.isWindows)) { AnalyticsService().setUserId(null);
FirebaseAnalytics.instance.setUserId(id: null); AnalyticsService().logLogout();
}
} }
} }

View File

@@ -35,7 +35,7 @@ class WebFeedNotifier extends AsyncNotifier<SnWebFeed> {
try { try {
final client = ref.read(apiClientProvider); final client = ref.read(apiClientProvider);
final response = await client.get( final response = await client.get(
'/sphere/publishers/${arg.pubName}/feeds/${arg.feedId}', '/insight/publishers/${arg.pubName}/feeds/${arg.feedId}',
); );
return SnWebFeed.fromJson(response.data); return SnWebFeed.fromJson(response.data);
} catch (e) { } catch (e) {
@@ -47,7 +47,7 @@ class WebFeedNotifier extends AsyncNotifier<SnWebFeed> {
state = const AsyncValue.loading(); state = const AsyncValue.loading();
try { try {
final client = ref.read(apiClientProvider); final client = ref.read(apiClientProvider);
final url = '/sphere/publishers/${feed.publisherId}/feeds'; final url = '/insight/publishers/${feed.publisherId}/feeds';
final response = feed.id.isEmpty final response = feed.id.isEmpty
? await client.post(url, data: feed.toJson()) ? await client.post(url, data: feed.toJson())
@@ -67,7 +67,7 @@ class WebFeedNotifier extends AsyncNotifier<SnWebFeed> {
state = const AsyncValue.loading(); state = const AsyncValue.loading();
try { try {
final client = ref.read(apiClientProvider); final client = ref.read(apiClientProvider);
await client.delete('/sphere/publishers/${arg.pubName}/feeds/$feedId'); await client.delete('/insight/publishers/${arg.pubName}/feeds/$feedId');
state = AsyncValue.data( state = AsyncValue.data(
SnWebFeed( SnWebFeed(
id: '', id: '',
@@ -93,7 +93,7 @@ class WebFeedNotifier extends AsyncNotifier<SnWebFeed> {
try { try {
final client = ref.read(apiClientProvider); final client = ref.read(apiClientProvider);
await client.post( await client.post(
'/sphere/publishers/${arg.pubName}/feeds/$feedId/scrap', '/insight/publishers/${arg.pubName}/feeds/$feedId/scrap',
options: Options( options: Options(
sendTimeout: const Duration(seconds: 60), sendTimeout: const Duration(seconds: 60),
receiveTimeout: const Duration(seconds: 180), receiveTimeout: const Duration(seconds: 180),

File diff suppressed because it is too large Load Diff

View File

@@ -1,13 +1,13 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/database/message.dart'; import 'package:island/database/message.dart';
import 'package:island/models/chat.dart'; import 'package:island/models/chat.dart';
import 'package:island/widgets/chat/message_item.dart'; import 'package:island/widgets/chat/message_item.dart';
// Provider to track animated messages to prevent replay // Provider to track animated messages to prevent replay
final animatedMessagesProvider = final animatedMessagesProvider = NotifierProvider.autoDispose(
NotifierProvider<AnimatedMessagesNotifier, Set<String>>(
AnimatedMessagesNotifier.new, AnimatedMessagesNotifier.new,
); );
@@ -22,7 +22,7 @@ class AnimatedMessagesNotifier extends Notifier<Set<String>> {
} }
} }
class MessageItemWrapper extends ConsumerWidget { class MessageItemWrapper extends HookConsumerWidget {
final LocalChatMessage message; final LocalChatMessage message;
final int index; final int index;
final bool isLastInGroup; final bool isLastInGroup;
@@ -54,51 +54,6 @@ class MessageItemWrapper extends ConsumerWidget {
required this.roomOpenTime, required this.roomOpenTime,
}); });
@override
Widget build(BuildContext context, WidgetRef ref) {
// Animation logic
final animatedMessages = ref.watch(animatedMessagesProvider);
final isNewMessage = message.createdAt.isAfter(roomOpenTime);
final hasAnimated = animatedMessages.contains(message.id);
// Only animate if:
// 1. Animation is enabled
// 2. Message is new (created after room open)
// 3. Has not animated yet
final shouldAnimate = !disableAnimation && isNewMessage && !hasAnimated;
final child = chatIdentity.when(
skipError: true,
data: (identity) => _buildContent(context, identity),
loading: () => _buildLoading(),
error: (_, _) => const SizedBox.shrink(),
);
if (!shouldAnimate) {
return child;
}
return TweenAnimationBuilder<double>(
key: ValueKey('anim-${message.id}'), // Ensure unique key for animation
tween: Tween<double>(begin: 0.0, end: 1.0),
duration: Duration(milliseconds: 400 + (index % 5) * 50),
curve: Curves.easeOutCubic,
builder: (context, value, child) {
return Transform.translate(
offset: Offset(0, 20 * (1 - value)),
child: Opacity(opacity: value, child: child),
);
},
onEnd: () {
// Mark as animated
WidgetsBinding.instance.addPostFrameCallback((_) {
ref.read(animatedMessagesProvider.notifier).addMessage(message.id);
});
},
child: child,
);
}
Widget _buildContent(BuildContext context, SnChatMember? identity) { Widget _buildContent(BuildContext context, SnChatMember? identity) {
final isSelected = selectedMessages.contains(message.id); final isSelected = selectedMessages.contains(message.id);
final isCurrentUser = identity?.id == message.senderId; final isCurrentUser = identity?.id == message.senderId;
@@ -116,11 +71,8 @@ class MessageItemWrapper extends ConsumerWidget {
} }
}, },
child: Container( child: Container(
color: color: isSelected
isSelected ? Theme.of(context).colorScheme.primaryContainer.withOpacity(0.3)
? Theme.of(
context,
).colorScheme.primaryContainer.withOpacity(0.3)
: null, : null,
child: Stack( child: Stack(
children: [ children: [
@@ -130,8 +82,7 @@ class MessageItemWrapper extends ConsumerWidget {
key: ValueKey('item-${message.id}'), key: ValueKey('item-${message.id}'),
message: message, message: message,
isCurrentUser: isCurrentUser, isCurrentUser: isCurrentUser,
onAction: onAction: isSelectionMode
isSelectionMode
? null ? null
: (action) => onMessageAction(action, message), : (action) => onMessageAction(action, message),
onJump: onJump, onJump: onJump,
@@ -178,4 +129,88 @@ class MessageItemWrapper extends ConsumerWidget {
onJump: (_) {}, onJump: (_) {},
); );
} }
@override
Widget build(BuildContext context, WidgetRef ref) {
// Animation logic
final animatedMessages = ref.watch(animatedMessagesProvider);
final isNewMessage = message.createdAt.isAfter(roomOpenTime);
final hasAnimated = animatedMessages.contains(message.id);
// Only animate if:
// 1. Animation is enabled
// 2. Message is new (created after room open)
// 3. Has not animated yet
final shouldAnimate = !disableAnimation && isNewMessage && !hasAnimated;
final child = chatIdentity.when(
skipError: true,
data: (identity) => _buildContent(context, identity),
loading: () => _buildLoading(),
error: (_, _) => const SizedBox.shrink(),
);
final controller = useAnimationController(
duration: Duration(milliseconds: 400 + (index % 5) * 50),
);
final hasStarted = useState(false);
useEffect(() {
if (shouldAnimate && !hasStarted.value) {
hasStarted.value = true;
controller.forward().then((_) {
WidgetsBinding.instance.addPostFrameCallback((_) {
ref.read(animatedMessagesProvider.notifier).addMessage(message.id);
});
});
}
return null;
}, [shouldAnimate]);
if (!shouldAnimate) {
return child;
}
final curvedAnimation = useMemoized(
() => CurvedAnimation(parent: controller, curve: Curves.easeOutQuart),
[controller],
);
final sizeAnimation = useMemoized(
() => Tween<double>(begin: 0.0, end: 1.0).animate(curvedAnimation),
[curvedAnimation],
);
final slideAnimation = useMemoized(
() => Tween<Offset>(
begin: const Offset(0, 0.12),
end: Offset.zero,
).animate(curvedAnimation),
[curvedAnimation],
);
final fadeAnimation = useMemoized(
() => Tween<double>(begin: 0.0, end: 1.0).animate(
CurvedAnimation(
parent: controller,
curve: const Interval(0.1, 1.0, curve: Curves.easeOut),
),
),
[controller],
);
return AnimatedBuilder(
animation: controller,
builder: (context, child) => FadeTransition(
opacity: fadeAnimation,
child: SizeTransition(
axis: Axis.vertical,
sizeFactor: sizeAnimation,
child: SlideTransition(position: slideAnimation, child: child),
),
),
child: child,
);
}
} }

View File

@@ -105,11 +105,9 @@ class WebfeedForm extends HookConsumerWidget {
return feedAsync.when( return feedAsync.when(
loading: () => const Center(child: CircularProgressIndicator()), loading: () => const Center(child: CircularProgressIndicator()),
error: error: (error, _) => ResponseErrorWidget(
(error, _) => ResponseErrorWidget(
error: error, error: error,
onRetry: onRetry: () => ref.invalidate(
() => ref.invalidate(
webFeedNotifierProvider((pubName: pubName, feedId: feedId)), webFeedNotifierProvider((pubName: pubName, feedId: feedId)),
), ),
), ),
@@ -140,7 +138,7 @@ class WebfeedForm extends HookConsumerWidget {
} catch (e) { } catch (e) {
showErrorAlert(e); showErrorAlert(e);
} finally { } finally {
isLoading.value = false; if (context.mounted) isLoading.value = false;
} }
}, [pubName, feedId, ref, context, isLoading]); }, [pubName, feedId, ref, context, isLoading]);
@@ -160,8 +158,8 @@ class WebfeedForm extends HookConsumerWidget {
} }
return null; return null;
}, },
onTapOutside: onTapOutside: (_) =>
(_) => FocusManager.instance.primaryFocus?.unfocus(), FocusManager.instance.primaryFocus?.unfocus(),
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
TextFormField( TextFormField(
@@ -184,8 +182,8 @@ class WebfeedForm extends HookConsumerWidget {
} }
return null; return null;
}, },
onTapOutside: onTapOutside: (_) =>
(_) => FocusManager.instance.primaryFocus?.unfocus(), FocusManager.instance.primaryFocus?.unfocus(),
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
TextFormField( TextFormField(
@@ -197,8 +195,8 @@ class WebfeedForm extends HookConsumerWidget {
borderRadius: BorderRadius.all(Radius.circular(12)), borderRadius: BorderRadius.all(Radius.circular(12)),
), ),
), ),
onTapOutside: onTapOutside: (_) =>
(_) => FocusManager.instance.primaryFocus?.unfocus(), FocusManager.instance.primaryFocus?.unfocus(),
maxLines: 3, maxLines: 3,
), ),
const SizedBox(height: 24), const SizedBox(height: 24),
@@ -256,7 +254,12 @@ class WebfeedForm extends HookConsumerWidget {
], ],
).padding(horizontal: 20, vertical: 12); ).padding(horizontal: 20, vertical: 12);
return Column(children: [Expanded(child: formWidget), buttonsRow]); return Column(
children: [
Expanded(child: formWidget),
buttonsRow,
],
);
}, },
); );
} }

View File

@@ -1,5 +1,6 @@
import 'dart:math' as math; import 'dart:math' as math;
import 'package:desktop_drop/desktop_drop.dart';
import 'package:easy_localization/easy_localization.dart'; import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:flutter_hooks/flutter_hooks.dart';
@@ -26,9 +27,13 @@ import 'package:island/models/activity.dart';
import 'package:island/screens/notification.dart'; import 'package:island/screens/notification.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart'; import 'package:material_symbols_icons/material_symbols_icons.dart';
import 'package:slide_countdown/slide_countdown.dart'; import 'package:slide_countdown/slide_countdown.dart';
import 'package:styled_widget/styled_widget.dart'; import 'package:island/widgets/share/share_sheet.dart';
import 'dart:async'; import 'dart:async';
import 'package:styled_widget/styled_widget.dart';
import 'package:island/screens/dashboard/dash_customize.dart';
import 'package:island/pods/config.dart';
class DashboardScreen extends HookConsumerWidget { class DashboardScreen extends HookConsumerWidget {
const DashboardScreen({super.key}); const DashboardScreen({super.key});
@@ -41,6 +46,111 @@ class DashboardScreen extends HookConsumerWidget {
} }
} }
// Helper functions for dynamic dashboard rendering
class DashboardRenderer {
// Map individual card IDs to widgets
static Widget buildCard(String cardId, WidgetRef ref) {
switch (cardId) {
case 'checkIn':
return CheckInWidget(margin: EdgeInsets.zero);
case 'fortuneGraph':
return Card(
margin: EdgeInsets.zero,
child: FortuneGraphWidget(
events: ref.watch(
eventCalendarProvider(
EventCalendarQuery(
uname: 'me',
year: DateTime.now().year,
month: DateTime.now().month,
),
),
),
),
);
case 'fortuneCard':
return FortuneCard(unlimited: true);
case 'postFeatured':
return ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 400),
child: PostFeaturedList(),
);
case 'friendsOverview':
return FriendsOverviewWidget();
case 'notifications':
return NotificationsCard();
case 'chatList':
return ChatListCard();
default:
return const SizedBox.shrink();
}
}
// Map column group IDs to column widgets
static Widget buildColumn(String columnId, WidgetRef ref) {
switch (columnId) {
case 'activityColumn':
return SizedBox(
width: 400,
child: Column(
spacing: 16,
children: [
CheckInWidget(margin: EdgeInsets.zero),
Card(
margin: EdgeInsets.zero,
child: FortuneGraphWidget(
events: ref.watch(
eventCalendarProvider(
EventCalendarQuery(
uname: 'me',
year: DateTime.now().year,
month: DateTime.now().month,
),
),
),
),
),
Expanded(child: FortuneCard()),
],
),
);
case 'postsColumn':
return SizedBox(
width: 400,
child: LayoutBuilder(
builder: (context, constraints) {
return PostFeaturedList(
collapsable: false,
maxHeight: constraints.maxHeight,
);
},
),
);
case 'socialColumn':
return SizedBox(
width: 400,
child: Column(
spacing: 16,
children: [
FriendsOverviewWidget(),
Expanded(child: NotificationsCard()),
],
),
);
case 'chatsColumn':
return SizedBox(
width: 400,
child: Column(
spacing: 16,
children: [Expanded(child: ChatListCard())],
),
);
default:
return const SizedBox.shrink();
}
}
}
class DashboardGrid extends HookConsumerWidget { class DashboardGrid extends HookConsumerWidget {
const DashboardGrid({super.key}); const DashboardGrid({super.key});
@@ -50,8 +160,27 @@ class DashboardGrid extends HookConsumerWidget {
final devicePadding = MediaQuery.paddingOf(context); final devicePadding = MediaQuery.paddingOf(context);
final userInfo = ref.watch(userInfoProvider); final userInfo = ref.watch(userInfoProvider);
final appSettings = ref.watch(appSettingsProvider);
return Container( final dragging = useState(false);
return DropTarget(
onDragDone: (detail) {
dragging.value = false;
if (detail.files.isNotEmpty) {
showModalBottomSheet(
context: context,
isScrollControlled: true,
useRootNavigator: true,
builder: (context) => ShareSheet.files(files: detail.files),
);
}
},
onDragEntered: (_) => dragging.value = true,
onDragExited: (_) => dragging.value = false,
child: Stack(
children: [
Container(
constraints: BoxConstraints( constraints: BoxConstraints(
maxHeight: isWide maxHeight: isWide
? math.min(640, MediaQuery.sizeOf(context).height * 0.65) ? math.min(640, MediaQuery.sizeOf(context).height * 0.65)
@@ -64,15 +193,20 @@ class DashboardGrid extends HookConsumerWidget {
spacing: 16, spacing: 16,
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
// Clock card spans full width // Clock card spans full width (only if enabled in settings)
if (isWide) if (isWide &&
(appSettings.dashboardConfig?.showClockAndCountdown ??
true))
ClockCard().padding(horizontal: 24) ClockCard().padding(horizontal: 24)
else else if (!isWide)
Row( Row(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
const Gap(8), const Gap(8),
if (appSettings.dashboardConfig?.showClockAndCountdown ??
true)
Expanded(child: ClockCard(compact: true)), Expanded(child: ClockCard(compact: true)),
if (appSettings.dashboardConfig?.showSearchBar ?? true)
IconButton( IconButton(
onPressed: () { onPressed: () {
eventBus.fire(CommandPaletteTriggerEvent()); eventBus.fire(CommandPaletteTriggerEvent());
@@ -82,14 +216,17 @@ class DashboardGrid extends HookConsumerWidget {
), ),
], ],
).padding(horizontal: 24), ).padding(horizontal: 24),
// Row with two cards side by side // Row with two cards side by side (only if enabled in settings)
if (isWide) if (isWide &&
(appSettings.dashboardConfig?.showSearchBar ?? true))
Padding( Padding(
padding: EdgeInsets.symmetric(horizontal: isWide ? 24 : 16), padding: EdgeInsets.symmetric(horizontal: isWide ? 24 : 16),
child: SearchBar( child: SearchBar(
hintText: 'searchAnything'.tr(), hintText: 'searchAnything'.tr(),
constraints: const BoxConstraints(minHeight: 56), constraints: const BoxConstraints(minHeight: 56),
leading: const Icon(Symbols.search).padding(horizontal: 24), leading: const Icon(
Symbols.search,
).padding(horizontal: 24),
readOnly: true, readOnly: true,
onTap: () { onTap: () {
eventBus.fire(CommandPaletteTriggerEvent()); eventBus.fire(CommandPaletteTriggerEvent());
@@ -124,6 +261,74 @@ class DashboardGrid extends HookConsumerWidget {
).padding(horizontal: isWide ? 24 : 16), ).padding(horizontal: isWide ? 24 : 16),
], ],
), ),
),
// Customize button
Positioned(
bottom: isWide ? 16 : 16 + devicePadding.bottom,
right: 16,
child: TextButton.icon(
onPressed: () {
showModalBottomSheet(
context: context,
isScrollControlled: true,
useRootNavigator: true,
builder: (context) => const DashboardCustomizationSheet(),
);
},
icon: Icon(
Symbols.tune,
size: 16,
color: Theme.of(context).colorScheme.primary,
),
label: Text(
'customize',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.primary,
),
).tr(),
style: TextButton.styleFrom(
backgroundColor: Theme.of(context).colorScheme.surface,
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 8,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
),
),
),
if (dragging.value)
Positioned.fill(
child: Container(
color: Theme.of(
context,
).colorScheme.primaryContainer.withOpacity(0.9),
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Symbols.upload_file,
size: 64,
color: Theme.of(context).colorScheme.primary,
),
const Gap(16),
Text(
'dropToShare'.tr(),
style: Theme.of(context).textTheme.headlineMedium
?.copyWith(
color: Theme.of(context).colorScheme.primary,
fontWeight: FontWeight.bold,
),
),
],
),
),
),
),
],
),
); );
} }
} }
@@ -134,56 +339,30 @@ class _DashboardGridWide extends HookConsumerWidget {
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
final userInfo = ref.watch(userInfoProvider); final userInfo = ref.watch(userInfoProvider);
final appSettings = ref.watch(appSettingsProvider);
return Row( final List<Widget> children = [];
spacing: 16,
children: [ // Always include account unactivated card if user is not activated
if (userInfo.value != null && userInfo.value?.activatedAt == null) if (userInfo.value != null && userInfo.value?.activatedAt == null) {
SizedBox(width: 400, child: AccountUnactivatedCard()), children.add(SizedBox(width: 400, child: AccountUnactivatedCard()));
SizedBox( }
width: 400,
child: Column( // Add configured columns in the specified order
spacing: 16, final horizontalLayouts =
children: [ appSettings.dashboardConfig?.horizontalLayouts ??
CheckInWidget(margin: EdgeInsets.zero), ['activityColumn', 'postsColumn', 'socialColumn', 'chatsColumn'];
Card(
margin: EdgeInsets.zero, for (final columnId in horizontalLayouts) {
child: FortuneGraphWidget( children.add(DashboardRenderer.buildColumn(columnId, ref));
events: ref.watch( }
eventCalendarProvider(
EventCalendarQuery( // If no children, add a SizedBox.expand to maintain width
uname: 'me', if (children.isEmpty) {
year: DateTime.now().year, children.add(SizedBox(width: MediaQuery.sizeOf(context).width));
month: DateTime.now().month, }
),
), return Row(spacing: 16, children: children);
),
),
),
Expanded(child: FortuneCard()),
],
),
),
SizedBox(width: 400, child: PostFeaturedList(collapsable: false)),
SizedBox(
width: 400,
child: Column(
spacing: 16,
children: [
FriendsOverviewWidget(),
Expanded(child: NotificationsCard()),
],
),
),
SizedBox(
width: 400,
child: Column(
spacing: 16,
children: [Expanded(child: ChatListCard())],
),
),
],
);
} }
} }
@@ -193,37 +372,33 @@ class _DashboardGridNarrow extends HookConsumerWidget {
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
final userInfo = ref.watch(userInfoProvider); final userInfo = ref.watch(userInfoProvider);
final appSettings = ref.watch(appSettingsProvider);
return Column( final List<Widget> children = [];
spacing: 16,
children: [ // Always include account unactivated card if user is not activated
if (userInfo.value != null && userInfo.value?.activatedAt == null) if (userInfo.value != null && userInfo.value?.activatedAt == null) {
AccountUnactivatedCard(), children.add(AccountUnactivatedCard());
CheckInWidget(margin: EdgeInsets.zero), }
FortuneCard(),
ConstrainedBox( // Add configured cards in the specified order
constraints: const BoxConstraints(maxHeight: 400), final verticalLayouts =
child: PostFeaturedList(), appSettings.dashboardConfig?.verticalLayouts ??
), [
FriendsOverviewWidget(), 'checkIn',
NotificationsCard(), 'fortuneCard',
ChatListCard(), 'postFeatured',
Card( 'friendsOverview',
margin: EdgeInsets.zero, 'notifications',
child: FortuneGraphWidget( 'chatList',
events: ref.watch( 'fortuneGraph',
eventCalendarProvider( ];
EventCalendarQuery(
uname: 'me', for (final cardId in verticalLayouts) {
year: DateTime.now().year, children.add(DashboardRenderer.buildCard(cardId, ref));
month: DateTime.now().month, }
),
), return Column(spacing: 16, children: children);
),
),
),
],
);
} }
} }
@@ -304,7 +479,9 @@ class ClockCard extends HookConsumerWidget {
), ),
], ],
), ),
Row( SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
spacing: 5, spacing: 5,
children: [ children: [
notableDay.when( notableDay.when(
@@ -318,6 +495,7 @@ class ClockCard extends HookConsumerWidget {
), ),
], ],
), ),
),
], ],
), ),
), ),
@@ -528,13 +706,14 @@ class ChatListCard extends HookConsumerWidget {
} }
class FortuneCard extends HookConsumerWidget { class FortuneCard extends HookConsumerWidget {
const FortuneCard({super.key}); final bool unlimited;
const FortuneCard({super.key, this.unlimited = false});
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
final fortuneAsync = ref.watch(randomFortuneSayingProvider); final fortuneAsync = ref.watch(randomFortuneSayingProvider);
return Card( final child = Card(
margin: EdgeInsets.zero, margin: EdgeInsets.zero,
shape: const RoundedRectangleBorder( shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(12)), borderRadius: BorderRadius.all(Radius.circular(12)),
@@ -550,16 +729,19 @@ class FortuneCard extends HookConsumerWidget {
Expanded( Expanded(
child: Text( child: Text(
fortune.content, fortune.content,
maxLines: 2, maxLines: unlimited ? null : 2,
overflow: TextOverflow.fade, overflow: TextOverflow.fade,
), ),
), ),
Text('—— ${fortune.source}').bold(), Text('—— ${fortune.source}').bold(),
], ],
).padding(horizontal: 16); ).padding(horizontal: 16, vertical: unlimited ? 12 : 0);
}, },
), ),
).height(48); );
if (unlimited) return child;
return child.height(48);
} }
} }
@@ -582,6 +764,7 @@ class _UnauthorizedCard extends HookConsumerWidget {
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
const Gap(16), const Gap(16),
const SizedBox(width: double.infinity),
Icon( Icon(
Symbols.dashboard_rounded, Symbols.dashboard_rounded,
size: 64, size: 64,

View File

@@ -0,0 +1,398 @@
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart';
import 'package:island/widgets/content/sheet.dart';
import 'package:island/pods/config.dart';
import 'package:island/widgets/alert.dart';
import 'package:styled_widget/styled_widget.dart';
class DashboardCustomizationSheet extends HookConsumerWidget {
const DashboardCustomizationSheet({super.key});
static Map<String, Map<String, dynamic>> _getCardMetadata(
BuildContext context,
) {
return {
// Vertical layout cards
'checkIn': {
'name': 'dashboardCardCheckIn'.tr(),
'icon': Symbols.check_circle,
},
'fortuneGraph': {
'name': 'dashboardCardFortuneGraph'.tr(),
'icon': Symbols.show_chart,
},
'fortuneCard': {
'name': 'dashboardCardFortune'.tr(),
'icon': Symbols.lightbulb,
},
'postFeatured': {
'name': 'dashboardCardFeaturedPosts'.tr(),
'icon': Symbols.article,
},
'friendsOverview': {
'name': 'dashboardCardFriends'.tr(),
'icon': Symbols.group,
},
'notifications': {
'name': 'dashboardCardNotifications'.tr(),
'icon': Symbols.notifications,
},
'chatList': {'name': 'dashboardCardChats'.tr(), 'icon': Symbols.chat},
// Horizontal layout columns
'activityColumn': {
'name': 'dashboardCardActivityColumn'.tr(),
'icon': Symbols.dashboard,
'description': 'dashboardCardActivityColumnDescription'.tr(),
},
'postsColumn': {
'name': 'dashboardCardPostsColumn'.tr(),
'icon': Symbols.article,
'description': 'dashboardCardPostsColumnDescription'.tr(),
},
'socialColumn': {
'name': 'dashboardCardSocialColumn'.tr(),
'icon': Symbols.group,
'description': 'dashboardCardSocialColumnDescription'.tr(),
},
'chatsColumn': {
'name': 'dashboardCardChatsColumn'.tr(),
'icon': Symbols.chat,
'description': 'dashboardCardChatsColumnDescription'.tr(),
},
};
}
@override
Widget build(BuildContext context, WidgetRef ref) {
final tabController = useTabController(initialLength: 2);
final appSettings = ref.watch(appSettingsProvider);
// Local state for editing
final verticalLayouts = useState<List<String>>(
(appSettings.dashboardConfig?.verticalLayouts ??
[
'checkIn',
'fortuneCard',
'postFeatured',
'friendsOverview',
'notifications',
'chatList',
'fortuneGraph',
])
.where((id) => id != 'accountUnactivated')
.toList(),
);
final horizontalLayouts = useState<List<String>>(
_migrateHorizontalLayouts(appSettings.dashboardConfig?.horizontalLayouts),
);
final showSearchBar = useState<bool>(
appSettings.dashboardConfig?.showSearchBar ?? true,
);
final showClockAndCountdown = useState<bool>(
appSettings.dashboardConfig?.showClockAndCountdown ?? true,
);
void saveConfig() {
final config = DashboardConfig(
verticalLayouts: verticalLayouts.value,
horizontalLayouts: horizontalLayouts.value,
showSearchBar: showSearchBar.value,
showClockAndCountdown: showClockAndCountdown.value,
);
ref.read(appSettingsProvider.notifier).setDashboardConfig(config);
Navigator.of(context).pop();
}
return SheetScaffold(
titleText: 'dashboardCustomizeTitle'.tr(),
actions: [IconButton(onPressed: saveConfig, icon: Icon(Symbols.save))],
child: DefaultTabController(
length: 2,
child: Column(
children: [
TabBar(
controller: tabController,
tabs: [
Tab(text: 'dashboardTabVertical'.tr()),
Tab(text: 'dashboardTabHorizontal'.tr()),
],
),
Expanded(
child: CustomScrollView(
slivers: [
SliverFillRemaining(
child: TabBarView(
controller: tabController,
children: [
// Vertical layout
_buildSliverLayoutEditor(
context,
ref,
'dashboardLayoutVertical'.tr(),
verticalLayouts,
false,
showSearchBar,
showClockAndCountdown,
),
// Horizontal layout
_buildSliverLayoutEditor(
context,
ref,
'dashboardLayoutHorizontal'.tr(),
horizontalLayouts,
true,
showSearchBar,
showClockAndCountdown,
),
],
),
),
],
),
),
],
),
),
);
}
List<String> _migrateHorizontalLayouts(List<String>? existingLayouts) {
if (existingLayouts == null || existingLayouts.isEmpty) {
// Default horizontal layout using column groups
return ['activityColumn', 'postsColumn', 'socialColumn', 'chatsColumn'];
}
// If it already contains column groups, use as-is
if (existingLayouts.any((id) => id.contains('Column'))) {
return existingLayouts.where((id) => id != 'accountUnactivated').toList();
}
// Migrate from old individual card format to column groups
// This is a simple migration - in a real app you might want more sophisticated logic
return ['activityColumn', 'postsColumn', 'socialColumn', 'chatsColumn'];
}
Widget _buildSliverLayoutEditor(
BuildContext context,
WidgetRef ref,
String title,
ValueNotifier<List<String>> layouts,
bool isHorizontal,
ValueNotifier<bool> showSearchBar,
ValueNotifier<bool> showClockAndCountdown,
) {
final cardMetadata = _getCardMetadata(context);
// Filter available cards based on layout mode
final relevantCards = isHorizontal
? cardMetadata.entries
.where((entry) => entry.key.contains('Column'))
.map((e) => e.key)
.toList()
: cardMetadata.entries
.where((entry) => !entry.key.contains('Column'))
.map((e) => e.key)
.toList();
final availableCards = relevantCards
.where((cardId) => !layouts.value.contains(cardId))
.toList();
return CustomScrollView(
slivers: [
// Title
SliverToBoxAdapter(
child: Text(
title,
style: Theme.of(
context,
).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
).padding(horizontal: 24, top: 16, bottom: 8),
),
// Reorderable list for cards
SliverReorderableList(
itemCount: layouts.value.length,
itemBuilder: (context, index) {
final cardId = layouts.value[index];
final metadata =
cardMetadata[cardId] ?? {'name': cardId, 'icon': Symbols.help};
return ReorderableDragStartListener(
key: ValueKey(cardId),
index: index,
child: Card(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: ListTile(
dense: true,
leading: Icon(
metadata['icon'] as IconData,
color: Theme.of(context).colorScheme.primary,
),
contentPadding: const EdgeInsets.fromLTRB(16, 0, 8, 0),
title: Text(metadata['name'] as String),
subtitle: isHorizontal && metadata.containsKey('description')
? Text(
metadata['description'] as String,
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: Theme.of(
context,
).colorScheme.onSurfaceVariant,
),
)
: null,
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Symbols.drag_handle,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
IconButton(
icon: Icon(
Symbols.close,
size: 20,
color: Theme.of(context).colorScheme.error,
),
onPressed: () {
layouts.value = layouts.value
.where((id) => id != cardId)
.toList();
},
),
],
),
),
),
);
},
onReorder: (oldIndex, newIndex) {
if (oldIndex < newIndex) {
newIndex -= 1;
}
final item = layouts.value.removeAt(oldIndex);
layouts.value.insert(newIndex, item);
layouts.value = List.from(layouts.value);
},
),
// Available cards to add back
if (availableCards.isNotEmpty)
SliverToBoxAdapter(
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'dashboardAvailableCards'.tr(),
style: Theme.of(context).textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.bold,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 8,
children: availableCards.map((cardId) {
final metadata =
cardMetadata[cardId] ??
{'name': cardId, 'icon': Symbols.help};
return ActionChip(
avatar: Icon(
metadata['icon'] as IconData,
size: 16,
color: Theme.of(context).colorScheme.primary,
),
label: Text(metadata['name'] as String),
onPressed: () {
layouts.value = [...layouts.value, cardId];
},
);
}).toList(),
),
],
),
),
),
// Divider
const SliverToBoxAdapter(child: Divider()),
// Reset tile
SliverToBoxAdapter(
child: ListTile(
dense: true,
contentPadding: const EdgeInsets.symmetric(horizontal: 24),
leading: Icon(
Symbols.restore,
color: Theme.of(context).colorScheme.primary,
),
title: Text('dashboardResetToDefaults'.tr()),
subtitle: Text('dashboardResetToDefaultsSubtitle'.tr()),
trailing: Icon(
Symbols.chevron_right,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
onTap: () async {
final confirmed = await showConfirmAlert(
'dashboardResetConfirmMessage'.tr(),
'dashboardResetConfirmTitle'.tr(),
isDanger: true,
);
if (confirmed) {
ref.read(appSettingsProvider.notifier).resetDashboardConfig();
if (context.mounted) {
Navigator.of(context).pop(); // Close the sheet
}
}
},
),
),
// Divider
const SliverToBoxAdapter(child: Divider()),
// Settings checkboxes
SliverToBoxAdapter(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'dashboardDisplaySettings'.tr(),
style: Theme.of(
context,
).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
).padding(horizontal: 24, top: 12, bottom: 8),
CheckboxListTile(
dense: true,
title: Text('dashboardShowSearchBar'.tr()),
value: showSearchBar.value,
contentPadding: const EdgeInsets.symmetric(horizontal: 24),
onChanged: (value) {
if (value != null) {
showSearchBar.value = value;
}
},
),
CheckboxListTile(
dense: true,
title: Text('dashboardShowClockAndCountdown'.tr()),
value: showClockAndCountdown.value,
contentPadding: const EdgeInsets.symmetric(horizontal: 24),
onChanged: (value) {
if (value != null) {
showClockAndCountdown.value = value;
}
},
),
],
),
),
],
);
}
}

View File

@@ -1,4 +1,3 @@
import 'package:desktop_drop/desktop_drop.dart';
import 'package:easy_localization/easy_localization.dart'; import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart'; import 'package:go_router/go_router.dart';
@@ -29,10 +28,9 @@ import 'package:island/widgets/realm/realm_card.dart';
import 'package:island/widgets/publisher/publisher_card.dart'; import 'package:island/widgets/publisher/publisher_card.dart';
import 'package:island/widgets/web_article_card.dart'; import 'package:island/widgets/web_article_card.dart';
import 'package:island/services/event_bus.dart'; import 'package:island/services/event_bus.dart';
import 'package:island/widgets/share/share_sheet.dart';
import 'package:styled_widget/styled_widget.dart'; import 'package:styled_widget/styled_widget.dart';
import 'package:super_sliver_list/super_sliver_list.dart'; import 'package:super_sliver_list/super_sliver_list.dart';
import 'package:island/widgets/posts/post_subscription_filter.dart'; import 'package:island/widgets/post/filters/post_subscription_filter.dart';
import 'package:island/pods/post/post_list.dart'; import 'package:island/pods/post/post_list.dart';
class ExploreScreen extends HookConsumerWidget { class ExploreScreen extends HookConsumerWidget {
@@ -193,25 +191,7 @@ class ExploreScreen extends HookConsumerWidget {
hasSubscriptionsSelected, hasSubscriptionsSelected,
); );
final dragging = useState(false); return AppScaffold(
return DropTarget(
onDragDone: (detail) {
dragging.value = false;
if (detail.files.isNotEmpty) {
showModalBottomSheet(
context: context,
isScrollControlled: true,
useRootNavigator: true,
builder: (context) => ShareSheet.files(files: detail.files),
);
}
},
onDragEntered: (_) => dragging.value = true,
onDragExited: (_) => dragging.value = false,
child: Stack(
children: [
AppScaffold(
isNoBackground: false, isNoBackground: false,
appBar: appBar, appBar: appBar,
floatingActionButton: userInfo.value != null floatingActionButton: userInfo.value != null
@@ -245,9 +225,7 @@ class ExploreScreen extends HookConsumerWidget {
title: Text('articleCompose').tr(), title: Text('articleCompose').tr(),
onTap: () async { onTap: () async {
Navigator.of(context).pop(); Navigator.of(context).pop();
GoRouter.of( GoRouter.of(context).pushNamed('articleCompose');
context,
).pushNamed('articleCompose');
}, },
), ),
const Gap(16), const Gap(16),
@@ -273,38 +251,6 @@ class ExploreScreen extends HookConsumerWidget {
selectedTagIds, selectedTagIds,
) )
: _buildNarrowBody(context, ref, currentFilter.value), : _buildNarrowBody(context, ref, currentFilter.value),
),
if (dragging.value)
Positioned.fill(
child: Container(
color: Theme.of(
context,
).colorScheme.primaryContainer.withOpacity(0.9),
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Symbols.upload_file,
size: 64,
color: Theme.of(context).colorScheme.primary,
),
const Gap(16),
Text(
'dropToShare'.tr(),
style: Theme.of(context).textTheme.headlineMedium
?.copyWith(
color: Theme.of(context).colorScheme.primary,
fontWeight: FontWeight.bold,
),
),
],
),
),
),
),
],
),
); );
} }

View File

@@ -2,19 +2,14 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:gap/gap.dart'; import 'package:gap/gap.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/models/file.dart'; import 'package:island/models/file.dart';
import 'package:island/pods/config.dart'; import 'package:island/pods/config.dart';
import 'package:island/pods/drive/file_references.dart';
import 'package:island/services/file_download.dart'; import 'package:island/services/file_download.dart';
import 'package:island/services/responsive.dart'; import 'package:island/services/responsive.dart';
import 'package:island/services/time.dart';
import 'package:island/widgets/app_scaffold.dart'; import 'package:island/widgets/app_scaffold.dart';
import 'package:island/widgets/content/file_info_sheet.dart'; import 'package:island/widgets/content/file_info_sheet.dart';
import 'package:island/widgets/content/file_viewer_contents.dart'; import 'package:island/widgets/content/file_viewer_contents.dart';
import 'package:island/widgets/content/sheet.dart';
import 'package:styled_widget/styled_widget.dart';
class FileDetailScreen extends HookConsumerWidget { class FileDetailScreen extends HookConsumerWidget {
final SnCloudFile item; final SnCloudFile item;
@@ -165,22 +160,6 @@ class FileDetailScreen extends HookConsumerWidget {
break; break;
} }
// Add references button
actions.add(
IconButton(
icon: Icon(Icons.link),
onPressed: () => showModalBottomSheet(
useRootNavigator: true,
context: context,
isScrollControlled: true,
builder: (context) => SheetScaffold(
titleText: 'File References',
child: ReferencesList(fileId: item.id),
),
),
),
);
// Always add info button // Always add info button
actions.add( actions.add(
IconButton(icon: Icon(Icons.info_outline), onPressed: showInfoSheet), IconButton(icon: Icon(Icons.info_outline), onPressed: showInfoSheet),
@@ -206,50 +185,3 @@ class FileDetailScreen extends HookConsumerWidget {
}; };
} }
} }
class ReferencesList extends ConsumerWidget {
const ReferencesList({super.key, required this.fileId});
final String fileId;
@override
Widget build(BuildContext context, WidgetRef ref) {
final asyncReferences = ref.watch(fileReferencesProvider(fileId));
return asyncReferences.when(
data: (references) => ListView.builder(
itemCount: references.length,
itemBuilder: (context, index) {
final reference = references[index];
return ListTile(
leading: const Icon(Icons.link),
title: Row(
spacing: 6,
children: [
Text(
reference.usage,
style: GoogleFonts.robotoMono(
fontWeight: FontWeight.bold,
fontSize: 13,
),
),
Text(reference.id, style: GoogleFonts.robotoMono(fontSize: 13)),
],
),
subtitle: Row(
spacing: 8,
children: [
Text(reference.createdAt.formatRelative(context)),
const VerticalDivider(width: 1, thickness: 1).height(12),
Text(reference.createdAt.formatSystem()),
],
),
);
},
),
loading: () => const Center(child: CircularProgressIndicator()),
error: (error, _) =>
Center(child: Text('Error loading references: $error')),
);
}
}

View File

@@ -31,13 +31,60 @@ class FileListScreen extends HookConsumerWidget {
final quotaAsync = ref.watch(billingQuotaProvider); final quotaAsync = ref.watch(billingQuotaProvider);
final viewMode = useState(FileListViewMode.list); final viewMode = useState(FileListViewMode.list);
final isSelectionMode = useState<bool>(false);
final recycled = useState<bool>(false);
final query = useState<String?>(null);
final unindexedNotifier = ref.read(unindexedFileListProvider.notifier);
return AppScaffold( return AppScaffold(
isNoBackground: false, isNoBackground: false,
appBar: AppBar( appBar: AppBar(
title: Text('files').tr(), title: SearchBar(
constraints: const BoxConstraints(maxWidth: 400, minHeight: 32),
hintText: 'searchFiles'.tr(),
hintStyle: WidgetStatePropertyAll(TextStyle(fontSize: 14)),
textStyle: WidgetStatePropertyAll(TextStyle(fontSize: 14)),
onChanged: (value) {
// Update the query state that will be passed to FileListView
query.value = value.isEmpty ? null : value;
},
leading: Icon(
Symbols.search,
size: 20,
color: Theme.of(context).colorScheme.onSurface,
),
),
leading: const PageBackButton(backTo: '/account'), leading: const PageBackButton(backTo: '/account'),
actions: [ actions: [
// Selection mode toggle
IconButton(
icon: Icon(
isSelectionMode.value ? Symbols.close : Symbols.select_check_box,
),
onPressed: () => isSelectionMode.value = !isSelectionMode.value,
tooltip: isSelectionMode.value
? 'Exit Selection Mode'
: 'Enter Selection Mode',
),
// Recycle toggle (only in unindexed mode)
if (mode.value == FileListMode.unindexed)
IconButton(
icon: Icon(
recycled.value
? Symbols.delete_forever
: Symbols.restore_from_trash,
),
onPressed: () {
recycled.value = !recycled.value;
unindexedNotifier.setRecycled(recycled.value);
},
tooltip: recycled.value
? 'Show Active Files'
: 'Show Recycle Bin',
),
IconButton( IconButton(
icon: const Icon(Symbols.bar_chart), icon: const Icon(Symbols.bar_chart),
onPressed: () => onPressed: () =>
@@ -46,6 +93,18 @@ class FileListScreen extends HookConsumerWidget {
const Gap(8), const Gap(8),
], ],
), ),
floatingActionButton: mode.value == FileListMode.normal
? FloatingActionButton(
onPressed: () => _showActionBottomSheet(
context,
ref,
currentPath,
selectedPool,
),
tooltip: 'Add files or create directory',
child: const Icon(Symbols.add),
)
: null,
body: usageAsync.when( body: usageAsync.when(
data: (usage) => quotaAsync.when( data: (usage) => quotaAsync.when(
data: (quota) => FileListView( data: (quota) => FileListView(
@@ -61,6 +120,8 @@ class FileListScreen extends HookConsumerWidget {
onShowCreateDirectory: _showCreateDirectoryDialog, onShowCreateDirectory: _showCreateDirectoryDialog,
mode: mode, mode: mode,
viewMode: viewMode, viewMode: viewMode,
isSelectionMode: isSelectionMode,
query: query,
), ),
loading: () => const Center(child: CircularProgressIndicator()), loading: () => const Center(child: CircularProgressIndicator()),
error: (e, _) => Center(child: Text('Error loading quota')), error: (e, _) => Center(child: Text('Error loading quota')),
@@ -200,11 +261,50 @@ class FileListScreen extends HookConsumerWidget {
context: context, context: context,
isScrollControlled: true, isScrollControlled: true,
builder: (context) => SheetScaffold( builder: (context) => SheetScaffold(
titleText: 'Usage Overview',
child: UsageOverviewWidget( child: UsageOverviewWidget(
usage: usage, usage: usage,
quota: quota, quota: quota,
).padding(horizontal: 8, vertical: 16), ).padding(horizontal: 8, vertical: 16),
titleText: 'Usage Overview',
),
);
}
void _showActionBottomSheet(
BuildContext context,
WidgetRef ref,
ValueNotifier<String> currentPath,
ValueNotifier<SnFilePool?> selectedPool,
) {
showModalBottomSheet(
context: context,
builder: (context) => Container(
padding: const EdgeInsets.symmetric(vertical: 16),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
leading: const Icon(Symbols.create_new_folder),
title: const Text('Create Directory'),
onTap: () {
Navigator.of(context).pop();
_showCreateDirectoryDialog(context, currentPath);
},
),
ListTile(
leading: const Icon(Symbols.upload_file),
title: const Text('Upload File'),
onTap: () {
Navigator.of(context).pop();
_pickAndUploadFile(
ref,
currentPath.value,
selectedPool.value?.id,
);
},
),
],
),
), ),
); );
} }

View File

@@ -13,12 +13,12 @@ import 'package:island/screens/posts/post_detail.dart';
import 'package:island/services/compose_storage_db.dart'; import 'package:island/services/compose_storage_db.dart';
import 'package:island/services/responsive.dart'; import 'package:island/services/responsive.dart';
import 'package:island/widgets/app_scaffold.dart'; import 'package:island/widgets/app_scaffold.dart';
import 'package:island/widgets/attachment_uploader.dart';
import 'package:island/widgets/content/attachment_preview.dart';
import 'package:island/widgets/content/cloud_files.dart'; import 'package:island/widgets/content/cloud_files.dart';
import 'package:island/widgets/content/markdown.dart'; import 'package:island/widgets/content/markdown.dart';
import 'package:island/widgets/common/responsive_sidebar.dart';
import 'package:island/widgets/post/compose_form_fields.dart'; import 'package:island/widgets/post/compose_form_fields.dart';
import 'package:island/widgets/post/compose_shared.dart'; import 'package:island/widgets/post/compose_shared.dart';
import 'package:island/widgets/post/compose_attachments.dart';
import 'package:island/widgets/post/compose_settings_sheet.dart'; import 'package:island/widgets/post/compose_settings_sheet.dart';
import 'package:island/widgets/post/compose_toolbar.dart'; import 'package:island/widgets/post/compose_toolbar.dart';
import 'package:island/widgets/post/publishers_modal.dart'; import 'package:island/widgets/post/publishers_modal.dart';
@@ -88,9 +88,7 @@ class ArticleComposeScreen extends HookConsumerWidget {
}, [state]); }, [state]);
final showPreview = useState(false); final showPreview = useState(false);
final isAttachmentsExpanded = useState( final showSidebar = useState(false);
true,
); // New state for attachments section
// Initialize publisher once when data is available // Initialize publisher once when data is available
useEffect(() { useEffect(() {
@@ -144,17 +142,9 @@ class ArticleComposeScreen extends HookConsumerWidget {
}, []); }, []);
// Helper methods // Helper methods
void showSettingsSheet() {
showModalBottomSheet(
context: context,
isScrollControlled: true,
builder: (context) => ComposeSettingsSheet(state: state),
);
}
Widget buildPreviewPane() { Widget buildPreviewPane() {
final widgetItem = SingleChildScrollView( final widgetItem = SingleChildScrollView(
padding: const EdgeInsets.symmetric(vertical: 14, horizontal: 8), padding: const EdgeInsets.symmetric(vertical: 24, horizontal: 24),
child: ValueListenableBuilder<TextEditingValue>( child: ValueListenableBuilder<TextEditingValue>(
valueListenable: state.titleController, valueListenable: state.titleController,
builder: (context, titleValue, _) { builder: (context, titleValue, _) {
@@ -174,7 +164,7 @@ class ArticleComposeScreen extends HookConsumerWidget {
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
), ),
), ),
const Gap(16), const Gap(20),
], ],
if (descriptionValue.text.isNotEmpty) ...[ if (descriptionValue.text.isNotEmpty) ...[
Text( Text(
@@ -183,7 +173,7 @@ class ArticleComposeScreen extends HookConsumerWidget {
color: colorScheme.onSurface.withOpacity(0.7), color: colorScheme.onSurface.withOpacity(0.7),
), ),
), ),
const Gap(16), const Gap(20),
], ],
if (contentValue.text.isNotEmpty) if (contentValue.text.isNotEmpty)
MarkdownTextContent( MarkdownTextContent(
@@ -211,6 +201,7 @@ class ArticleComposeScreen extends HookConsumerWidget {
return Container( return Container(
decoration: BoxDecoration( decoration: BoxDecoration(
color: colorScheme.surface,
border: Border.all(color: colorScheme.outline.withOpacity(0.3)), border: Border.all(color: colorScheme.outline.withOpacity(0.3)),
borderRadius: BorderRadius.circular(8), borderRadius: BorderRadius.circular(8),
), ),
@@ -235,19 +226,14 @@ class ArticleComposeScreen extends HookConsumerWidget {
], ],
), ),
), ),
Expanded( Expanded(child: widgetItem),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: widgetItem,
),
),
], ],
), ),
); );
} }
Widget buildEditorPane() { Widget buildEditorPane() {
return Center( final editorContent = Center(
child: ConstrainedBox( child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 560), constraints: const BoxConstraints(maxWidth: 560),
child: Column( child: Column(
@@ -255,6 +241,7 @@ class ArticleComposeScreen extends HookConsumerWidget {
children: [ children: [
Expanded( Expanded(
child: SingleChildScrollView( child: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: ComposeFormFields( child: ComposeFormFields(
state: state, state: state,
showPublisherAvatar: false, showPublisherAvatar: false,
@@ -269,119 +256,27 @@ class ArticleComposeScreen extends HookConsumerWidget {
} }
}); });
}, },
).padding(top: 16),
), ),
), ),
// Attachments preview
ValueListenableBuilder<List<UniversalFile>>(
valueListenable: state.attachments,
builder: (context, attachments, _) {
if (attachments.isEmpty) return const SizedBox.shrink();
return Theme(
data: Theme.of(
context,
).copyWith(dividerColor: Colors.transparent),
child: ExpansionTile(
initiallyExpanded: isAttachmentsExpanded.value,
onExpansionChanged: (expanded) {
isAttachmentsExpanded.value = expanded;
},
collapsedBackgroundColor: Theme.of(
context,
).colorScheme.surfaceContainer,
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('attachments').tr(),
Text(
'articleAttachmentHint'.tr(),
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: Theme.of(
context,
).colorScheme.onSurfaceVariant,
),
), ),
], ],
), ),
children: [
ValueListenableBuilder<Map<int, double?>>(
valueListenable: state.attachmentProgress,
builder: (context, progressMap, _) {
return Wrap(
runSpacing: 8,
spacing: 8,
children: [
for (
var idx = 0;
idx < attachments.length;
idx++
)
SizedBox(
width: 180,
height: 180,
child: AttachmentPreview(
isCompact: true,
item: attachments[idx],
progress: progressMap[idx],
onRequestUpload: () async {
final config =
await showModalBottomSheet<
AttachmentUploadConfig
>(
context: context,
isScrollControlled: true,
builder: (context) =>
AttachmentUploaderSheet(
ref: ref,
state: state,
index: idx,
), ),
); );
if (config != null) {
await ComposeLogic.uploadAttachment( // Add background color for mobile editor pane
ref, if (!isWideScreen(context)) {
state, return Container(
idx, decoration: BoxDecoration(
poolId: config.poolId, color: colorScheme.surface,
borderRadius: BorderRadius.circular(8),
),
margin: const EdgeInsets.symmetric(vertical: 8),
child: editorContent,
); );
} }
},
onUpdate: (value) => return editorContent;
ComposeLogic.updateAttachment(
state,
value,
idx,
),
onDelete: () =>
ComposeLogic.deleteAttachment(
ref,
state,
idx,
),
onInsert: () =>
ComposeLogic.insertAttachment(
ref,
state,
idx,
),
),
),
],
);
},
),
Gap(16),
],
),
);
},
),
],
),
),
);
} }
return PopScope( return PopScope(
@@ -397,8 +292,15 @@ class ArticleComposeScreen extends HookConsumerWidget {
title: ValueListenableBuilder<TextEditingValue>( title: ValueListenableBuilder<TextEditingValue>(
valueListenable: state.titleController, valueListenable: state.titleController,
builder: (context, titleValue, _) { builder: (context, titleValue, _) {
return Text( return AnimatedSwitcher(
duration: const Duration(milliseconds: 150),
switchInCurve: Curves.fastEaseInToSlowEaseOut,
switchOutCurve: Curves.fastEaseInToSlowEaseOut,
child: Text(
titleValue.text.isEmpty ? 'postTitle'.tr() : titleValue.text, titleValue.text.isEmpty ? 'postTitle'.tr() : titleValue.text,
key: ValueKey(titleValue.text),
overflow: TextOverflow.ellipsis,
),
); );
}, },
), ),
@@ -426,31 +328,42 @@ class ArticleComposeScreen extends HookConsumerWidget {
}, },
), ),
IconButton( IconButton(
icon: const Icon(Symbols.settings), icon: const Icon(Symbols.tune),
onPressed: showSettingsSheet, onPressed: () => showSidebar.value = !showSidebar.value,
tooltip: 'postSettings'.tr(), tooltip: 'sidebar'.tr(),
), ),
Tooltip( Tooltip(
message: 'togglePreview'.tr(), message: 'togglePreview'.tr(),
child: IconButton( child: IconButton(
icon: Icon(showPreview.value ? Symbols.edit : Symbols.preview), icon: Icon(
showPreview.value ? Symbols.preview_off : Symbols.preview,
),
onPressed: () => showPreview.value = !showPreview.value, onPressed: () => showPreview.value = !showPreview.value,
), ),
), ),
ValueListenableBuilder<bool>( ValueListenableBuilder<bool>(
valueListenable: state.submitting, valueListenable: state.submitting,
builder: (context, submitting, _) { builder: (context, submitting, _) {
return IconButton( return AnimatedSwitcher(
onPressed: submitting duration: const Duration(milliseconds: 200),
? null switchInCurve: Curves.easeOut,
: () => ComposeLogic.performAction( switchOutCurve: Curves.easeIn,
ref, transitionBuilder:
state, (Widget child, Animation<double> animation) {
context, return FadeTransition(
originalPost: originalPost, opacity: animation,
child: ScaleTransition(
scale: Tween<double>(
begin: 0.8,
end: 1.0,
).animate(animation),
child: child,
), ),
icon: submitting );
},
child: submitting
? SizedBox( ? SizedBox(
key: const ValueKey('submitting'),
width: 28, width: 28,
height: 28, height: 28,
child: const CircularProgressIndicator( child: const CircularProgressIndicator(
@@ -458,8 +371,19 @@ class ArticleComposeScreen extends HookConsumerWidget {
strokeWidth: 2.5, strokeWidth: 2.5,
), ),
).center() ).center()
: Icon( : IconButton(
originalPost != null ? Symbols.edit : Symbols.upload, key: const ValueKey('icon'),
onPressed: () => ComposeLogic.performAction(
ref,
state,
context,
originalPost: originalPost,
),
icon: Icon(
originalPost != null
? Symbols.edit
: Symbols.upload,
),
), ),
); );
}, },
@@ -470,26 +394,68 @@ class ArticleComposeScreen extends HookConsumerWidget {
body: Column( body: Column(
children: [ children: [
Expanded( Expanded(
child: Padding( child: ResponsiveSidebar(
sidebarWidth: 480,
attachmentsContent: ArticleComposeAttachments(state: state),
settingsContent: ComposeSettingsSheet(state: state),
showSidebar: showSidebar,
mainContent: Padding(
padding: const EdgeInsets.only(left: 16, right: 16), padding: const EdgeInsets.only(left: 16, right: 16),
child: AnimatedSwitcher(
duration: const Duration(milliseconds: 250),
switchInCurve: Curves.easeOutCubic,
switchOutCurve: Curves.easeOutCubic,
transitionBuilder:
(Widget child, Animation<double> animation) {
final isWide = isWideScreen(context);
if (isWide) {
// Desktop: scale animation
return ScaleTransition(
scale: Tween<double>(begin: 0.95, end: 1.0)
.animate(
CurvedAnimation(
parent: animation,
curve: Curves.easeOutCubic,
),
),
child: child,
);
} else {
// Mobile: horizontal slide animation
return SlideTransition(
position:
Tween<Offset>(
begin: const Offset(0.05, 0),
end: Offset.zero,
).animate(
CurvedAnimation(
parent: animation,
curve: Curves.easeOutCubic,
),
),
child: child,
);
}
},
child: isWideScreen(context) child: isWideScreen(context)
? Row( ? Row(
spacing: 16, spacing: 16,
children: [ children: [
Expanded( Expanded(child: buildEditorPane()),
flex: showPreview.value ? 1 : 2,
child: buildEditorPane(),
),
if (showPreview.value) const VerticalDivider(),
if (showPreview.value) if (showPreview.value)
Expanded(child: buildPreviewPane()), Expanded(child: buildPreviewPane()),
], ],
) )
: showPreview.value : Container(
key: ValueKey('narrow-${showPreview.value}'),
child: showPreview.value
? buildPreviewPane() ? buildPreviewPane()
: buildEditorPane(), : buildEditorPane(),
), ),
), ),
),
),
),
// Bottom toolbar // Bottom toolbar
ComposeToolbar(state: state, originalPost: originalPost), ComposeToolbar(state: state, originalPost: originalPost),

View File

@@ -459,13 +459,12 @@ class _PostDetailLargeScreenLayout extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final user = ref.watch(userInfoProvider);
return Row( return Row(
children: [ children: [
Expanded( Expanded(
flex: 3, flex: 3,
child: Material(
color: Theme.of(context).cardTheme.color,
elevation: 8,
child: Center( child: Center(
child: Padding( child: Padding(
padding: const EdgeInsets.all(24), padding: const EdgeInsets.all(24),
@@ -477,9 +476,14 @@ class _PostDetailLargeScreenLayout extends StatelessWidget {
), ),
), ),
), ),
),
Expanded( Expanded(
flex: 2, flex: 2,
child: Stack(
fit: StackFit.expand,
children: [
Material(
color: Theme.of(context).colorScheme.surfaceContainer,
elevation: 8,
child: CustomScrollView( child: CustomScrollView(
slivers: [ slivers: [
SliverToBoxAdapter( SliverToBoxAdapter(
@@ -514,11 +518,31 @@ class _PostDetailLargeScreenLayout extends StatelessWidget {
), ),
), ),
), ),
PostRepliesList(postId: postId, maxWidth: 800), PostRepliesList(postId: postId, maxWidth: 680),
SliverGap(MediaQuery.of(context).padding.bottom + 80), SliverGap(MediaQuery.of(context).padding.bottom + 80),
], ],
), ),
), ),
if (user.value != null)
Positioned(
bottom: 16 + MediaQuery.of(context).padding.bottom,
left: 16,
right: 16,
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: 680),
child: PostQuickReply(
parent: post,
onPosted: () {
ref
.read(postRepliesProvider(postId).notifier)
.refresh();
},
),
).center(),
),
],
),
),
], ],
); );
} }
@@ -572,7 +596,7 @@ class PostDetailScreen extends HookConsumerWidget {
SliverToBoxAdapter( SliverToBoxAdapter(
child: Center( child: Center(
child: ConstrainedBox( child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: 800), constraints: BoxConstraints(maxWidth: 680),
child: PostItem( child: PostItem(
item: post!, item: post!,
isFullPost: true, isFullPost: true,
@@ -590,7 +614,7 @@ class PostDetailScreen extends HookConsumerWidget {
SliverToBoxAdapter( SliverToBoxAdapter(
child: Center( child: Center(
child: ConstrainedBox( child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: 800), constraints: BoxConstraints(maxWidth: 680),
child: PostActionButtons( child: PostActionButtons(
post: post, post: post,
renderingPadding: const EdgeInsets.symmetric( renderingPadding: const EdgeInsets.symmetric(
@@ -611,7 +635,7 @@ class PostDetailScreen extends HookConsumerWidget {
), ),
), ),
), ),
PostRepliesList(postId: id, maxWidth: 800), PostRepliesList(postId: id, maxWidth: 680),
SliverGap(MediaQuery.of(context).padding.bottom + 80), SliverGap(MediaQuery.of(context).padding.bottom + 80),
], ],
), ),
@@ -622,7 +646,7 @@ class PostDetailScreen extends HookConsumerWidget {
left: 16, left: 16,
right: 16, right: 16,
child: ConstrainedBox( child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: 800), constraints: BoxConstraints(maxWidth: 680),
child: postState.when( child: postState.when(
data: (post) => PostQuickReply( data: (post) => PostQuickReply(
parent: post!, parent: post!,

View File

@@ -25,7 +25,7 @@ import 'package:island/widgets/content/markdown.dart';
import 'package:island/widgets/post/post_list.dart'; import 'package:island/widgets/post/post_list.dart';
import 'package:island/widgets/post/post_item.dart'; import 'package:island/widgets/post/post_item.dart';
import 'package:island/widgets/activity_heatmap.dart'; import 'package:island/widgets/activity_heatmap.dart';
import 'package:island/widgets/posts/post_filter.dart'; import 'package:island/widgets/post/filters/post_filter.dart';
import 'package:material_symbols_icons/symbols.dart'; import 'package:material_symbols_icons/symbols.dart';
import 'package:island/services/color_extraction.dart'; import 'package:island/services/color_extraction.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart';

View File

@@ -15,7 +15,7 @@ import 'package:island/widgets/extended_refresh_indicator.dart';
import 'package:island/widgets/paging/pagination_list.dart'; import 'package:island/widgets/paging/pagination_list.dart';
import 'package:island/widgets/post/post_item.dart'; import 'package:island/widgets/post/post_item.dart';
import 'package:island/widgets/post/post_item_skeleton.dart'; import 'package:island/widgets/post/post_item_skeleton.dart';
import 'package:island/widgets/posts/post_filter.dart'; import 'package:island/widgets/post/filters/post_filter.dart';
import 'package:material_symbols_icons/symbols.dart'; import 'package:material_symbols_icons/symbols.dart';
import 'package:styled_widget/styled_widget.dart'; import 'package:styled_widget/styled_widget.dart';

View File

@@ -0,0 +1,536 @@
import 'dart:io';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/foundation.dart';
import 'package:island/talker.dart';
class AnalyticsService {
static final AnalyticsService _instance = AnalyticsService._internal();
factory AnalyticsService() => _instance;
AnalyticsService._internal();
FirebaseAnalytics? _analytics;
bool _enabled = true;
bool get _supportsAnalytics =>
kIsWeb || (Platform.isAndroid || Platform.isIOS || Platform.isMacOS);
void initialize() {
if (!_supportsAnalytics) return;
try {
_analytics = FirebaseAnalytics.instance;
} catch (e) {
talker.warning('[Analytics] Failed to init: $e');
_analytics = null;
}
}
void logEvent(String name, Map<String, Object>? parameters) {
if (!_enabled || !_supportsAnalytics) return;
final analytics = _analytics;
if (analytics == null) return;
try {
analytics.logEvent(name: name, parameters: parameters);
} catch (e) {
talker.warning('[Analytics] Failed to log event $name: $e');
}
}
void setEnabled(bool enabled) {
_enabled = enabled;
}
void setUserId(String? id) {
if (!_supportsAnalytics) return;
final analytics = _analytics;
if (analytics == null) return;
try {
analytics.setUserId(id: id);
} catch (e) {
talker.warning('[Analytics] Failed to set user ID: $e');
}
}
void logAppOpen() {
logEvent('app_open', null);
}
void logLogin(String authMethod) {
logEvent('login', {'auth_method': authMethod, 'platform': _getPlatform()});
}
void logLogout() {
logEvent('logout', null);
}
void logPostViewed(String postId, String postType, String viewSource) {
logEvent('post_viewed', {
'post_id': postId,
'post_type': postType,
'view_source': viewSource,
});
}
void logPostCreated(
String postType,
String visibility,
bool hasAttachments,
String publisherId,
) {
logEvent('post_created', {
'post_type': postType,
'visibility': visibility,
'has_attachments': hasAttachments ? 'yes' : 'no',
'publisher_id': publisherId,
});
}
void logPostReacted(
String postId,
String reactionSymbol,
int attitude,
bool isRemoving,
) {
logEvent('post_reacted', {
'post_id': postId,
'reaction_symbol': reactionSymbol,
'attitude': attitude,
'is_removing': isRemoving ? 'yes' : 'no',
});
}
void logPostReplied(
String postId,
String parentId,
int characterCount,
bool hasAttachments,
) {
logEvent('post_replied', {
'post_id': postId,
'parent_id': parentId,
'character_count': characterCount,
'has_attachments': hasAttachments,
});
}
void logPostShared(String postId, String shareMethod, String postType) {
logEvent('post_shared', {
'post_id': postId,
'share_method': shareMethod,
'post_type': postType,
});
}
void logPostEdited(String postId, int contentChangeDelta) {
logEvent('post_edited', {
'post_id': postId,
'content_change_delta': contentChangeDelta,
});
}
void logPostDeleted(String postId, String postType, int timeSinceCreation) {
logEvent('post_deleted', {
'post_id': postId,
'post_type': postType,
'time_since_creation': timeSinceCreation,
});
}
void logPostPinned(String postId, String pinMode, String realmId) {
logEvent('post_pinned', {
'post_id': postId,
'pin_mode': pinMode,
'realm_id': realmId,
});
}
void logPostAwarded(
String postId,
double amount,
String attitude,
bool hasMessage,
) {
logEvent('post_awarded', {
'post_id': postId,
'amount': amount,
'attitude': attitude,
'has_message': hasMessage ? 'yes' : 'no',
'currency': 'NSP',
});
}
void logPostTranslated(
String postId,
String sourceLanguage,
String targetLanguage,
) {
logEvent('post_translated', {
'post_id': postId,
'source_language': sourceLanguage,
'target_language': targetLanguage,
});
}
void logPostForwarded(
String postId,
String originalPostId,
String publisherId,
) {
logEvent('post_forwarded', {
'post_id': postId,
'original_post_id': originalPostId,
'publisher_id': publisherId,
});
}
void logMessageSent(
String channelId,
String messageType,
bool hasAttachments,
int attachmentCount,
) {
logEvent('message_sent', {
'channel_id': channelId,
'message_type': messageType,
'has_attachments': hasAttachments,
'attachment_count': attachmentCount,
});
}
void logMessageReceived(
String channelId,
String messageType,
bool isMentioned,
) {
logEvent('message_received', {
'channel_id': channelId,
'message_type': messageType,
'is_mentioned': isMentioned,
});
}
void logMessageReplied(
String channelId,
String originalMessageId,
int replyDepth,
) {
logEvent('message_replied', {
'channel_id': channelId,
'original_message_id': originalMessageId,
'reply_depth': replyDepth,
});
}
void logMessageEdited(
String channelId,
String messageId,
int contentChangeDelta,
) {
logEvent('message_edited', {
'channel_id': channelId,
'message_id': messageId,
'content_change_delta': contentChangeDelta,
});
}
void logMessageDeleted(
String channelId,
String messageId,
String messageType,
bool isOwn,
) {
logEvent('message_deleted', {
'channel_id': channelId,
'message_id': messageId,
'message_type': messageType,
'is_own': isOwn,
});
}
void logChatRoomOpened(String channelId, String roomType) {
logEvent('chat_room_opened', {
'channel_id': channelId,
'room_type': roomType,
});
}
void logChatJoined(String channelId, String roomType, bool isPublic) {
logEvent('chat_joined', {
'channel_id': channelId,
'room_type': roomType,
'is_public': isPublic,
});
}
void logChatLeft(String channelId, String roomType) {
logEvent('chat_left', {'channel_id': channelId, 'room_type': roomType});
}
void logChatInvited(String channelId, String invitedUserId) {
logEvent('chat_invited', {
'channel_id': channelId,
'invited_user_id': invitedUserId,
});
}
void logFileUploaded(
String fileType,
String fileSizeCategory,
String uploadSource,
) {
logEvent('file_uploaded', {
'file_type': fileType,
'file_size_category': fileSizeCategory,
'upload_source': uploadSource,
});
}
void logFileDownloaded(
String fileType,
String fileSizeCategory,
String downloadMethod,
) {
logEvent('file_downloaded', {
'file_type': fileType,
'file_size_category': fileSizeCategory,
'download_method': downloadMethod,
});
}
void logFileDeleted(
String fileType,
String fileSizeCategory,
String deleteSource,
bool isBatchDelete,
int batchCount,
) {
logEvent('file_deleted', {
'file_type': fileType,
'file_size_category': fileSizeCategory,
'delete_source': deleteSource,
'is_batch_delete': isBatchDelete,
'batch_count': batchCount,
});
}
void logStickerUsed(String packId, String stickerSlug, String context) {
logEvent('sticker_used', {
'pack_id': packId,
'sticker_slug': stickerSlug,
'context': context,
});
}
void logStickerPackAdded(String packId, String packName, int stickerCount) {
logEvent('sticker_pack_added', {
'pack_id': packId,
'pack_name': packName,
'sticker_count': stickerCount,
});
}
void logStickerPackViewed(String packId, int stickerCount, bool isOwned) {
logEvent('sticker_pack_viewed', {
'pack_id': packId,
'sticker_count': stickerCount,
'is_owned': isOwned,
});
}
void logSearchPerformed(
String searchType,
String query,
int resultCount,
bool hasFilters,
) {
logEvent('search_performed', {
'search_type': searchType,
'query': query,
'result_count': resultCount,
'has_filters': hasFilters,
});
}
void logFeedSubscribed(String feedId, String feedUrl, int articleCount) {
logEvent('feed_subscribed', {
'feed_id': feedId,
'feed_url': feedUrl,
'article_count': articleCount,
});
}
void logFeedUnsubscribed(String feedId, String feedUrl) {
logEvent('feed_unsubscribed', {'feed_id': feedId, 'feed_url': feedUrl});
}
void logWalletTransfer(
double amount,
String currency,
String payeeId,
bool hasRemark,
) {
logEvent('wallet_transfer', {
'amount': amount,
'currency': currency,
'payee_id': payeeId,
'has_remark': hasRemark,
});
}
void logWalletBalanceChecked(List<String> currenciesViewed) {
logEvent('wallet_balance_checked', {
'currencies_viewed': currenciesViewed.join(','),
});
}
void logWalletOpened(String activeTab) {
logEvent('wallet_opened', {'active_tab': activeTab});
}
void logRealmJoined(String realmSlug, String realmType) {
logEvent('realm_joined', {
'realm_slug': realmSlug,
'realm_type': realmType,
});
}
void logRealmLeft(String realmSlug) {
logEvent('realm_left', {'realm_slug': realmSlug});
}
void logFriendAdded(String friendId, String pickerMethod) {
logEvent('friend_added', {
'friend_id': friendId,
'picker_method': pickerMethod,
});
}
void logFriendRemoved(String relationshipId, String relationshipType) {
logEvent('friend_removed', {
'relationship_id': relationshipId,
'relationship_type': relationshipType,
});
}
void logUserBlocked(String blockedUserId, String previousRelationship) {
logEvent('user_blocked', {
'blocked_user_id': blockedUserId,
'previous_relationship': previousRelationship,
});
}
void logUserUnblocked(String unblockedUserId) {
logEvent('user_unblocked', {'unblocked_user_id': unblockedUserId});
}
void logFriendRequestAccepted(String requesterId) {
logEvent('friend_request_accepted', {'requester_id': requesterId});
}
void logFriendRequestDeclined(String requesterId) {
logEvent('friend_request_declined', {'requester_id': requesterId});
}
void logThemeChanged(String oldMode, String newMode) {
logEvent('theme_changed', {'old_mode': oldMode, 'new_mode': newMode});
}
void logLanguageChanged(String oldLanguage, String newLanguage) {
logEvent('language_changed', {
'old_language': oldLanguage,
'new_language': newLanguage,
});
}
void logAiQuerySent(
int messageLength,
String contextType,
int attachedPostsCount,
) {
logEvent('ai_query_sent', {
'message_length': messageLength,
'context_type': contextType,
'attached_posts_count': attachedPostsCount,
});
}
void logAiResponseReceived(int responseThoughtCount, String sequenceId) {
logEvent('ai_response_received', {
'response_thought_count': responseThoughtCount,
'sequence_id': sequenceId,
});
}
void logShuffleViewed(int postIndex, int totalPostsLoaded) {
logEvent('shuffle_viewed', {
'post_index': postIndex,
'total_posts_loaded': totalPostsLoaded,
});
}
void logDraftSaved(String draftId, String postType, bool hasContent) {
logEvent('draft_saved', {
'draft_id': draftId,
'post_type': postType,
'has_content': hasContent,
});
}
void logDraftDeleted(String draftId, String postType) {
logEvent('draft_deleted', {'draft_id': draftId, 'post_type': postType});
}
void logCategoryViewed(String categorySlug, String categoryId) {
logEvent('category_viewed', {
'category_slug': categorySlug,
'category_id': categoryId,
});
}
void logTagViewed(String tagSlug, String tagId) {
logEvent('tag_viewed', {'tag_slug': tagSlug, 'tag_id': tagId});
}
void logCategorySubscribed(String categorySlug, String categoryId) {
logEvent('category_subscribed', {
'category_slug': categorySlug,
'category_id': categoryId,
});
}
void logTagSubscribed(String tagSlug, String tagId) {
logEvent('tag_subscribed', {'tag_slug': tagSlug, 'tag_id': tagId});
}
void logNotificationViewed() {
logEvent('notification_viewed', null);
}
void logNotificationActioned(String actionType, String notificationType) {
logEvent('notification_actioned', {
'action_type': actionType,
'notification_type': notificationType,
});
}
void logProfileUpdated(List<String> fieldsUpdated) {
logEvent('profile_updated', {'fields_updated': fieldsUpdated.join(',')});
}
void logAvatarChanged(String imageSource, bool isCropped) {
logEvent('avatar_changed', {
'image_source': imageSource,
'is_cropped': isCropped,
});
}
String _getPlatform() {
if (Platform.isAndroid) return 'android';
if (Platform.isIOS) return 'ios';
if (Platform.isMacOS) return 'macos';
if (Platform.isWindows) return 'windows';
if (Platform.isLinux) return 'linux';
return 'web';
}
}

View File

@@ -1 +0,0 @@
export 'app_intents/ios.dart';

View File

@@ -1,443 +0,0 @@
import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter_app_intents/flutter_app_intents.dart';
import 'package:go_router/go_router.dart';
import 'package:island/models/auth.dart';
import 'package:island/pods/config.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:island/talker.dart';
import 'package:island/route.dart';
class AppIntentsService {
static final AppIntentsService _instance = AppIntentsService._internal();
factory AppIntentsService() => _instance;
AppIntentsService._internal();
FlutterAppIntentsClient? _client;
bool _initialized = false;
Dio? _dio;
Future<void> initialize() async {
if (!Platform.isIOS) {
talker.warning('[AppIntents] App Intents only supported on iOS');
return;
}
if (_initialized) {
talker.info('[AppIntents] Already initialized');
return;
}
try {
talker.info('[AppIntents] Initializing App Intents client...');
_client = FlutterAppIntentsClient.instance;
// Initialize Dio for API calls
final prefs = await SharedPreferences.getInstance();
final serverUrl =
prefs.getString(kNetworkServerStoreKey) ?? kNetworkServerDefault;
final tokenString = prefs.getString(kTokenPairStoreKey);
final headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
};
if (tokenString != null) {
try {
final token = AppToken.fromJson(jsonDecode(tokenString));
headers['Authorization'] = 'AtField ${token.token}';
} catch (e) {
talker.warning('[AppIntents] Failed to parse token: $e');
}
}
_dio = Dio(
BaseOptions(
baseUrl: serverUrl,
connectTimeout: const Duration(seconds: 10),
receiveTimeout: const Duration(seconds: 10),
headers: headers,
),
);
await _registerIntents();
_initialized = true;
talker.info('[AppIntents] All intents registered successfully');
} catch (e, stack) {
talker.error('[AppIntents] Initialization failed', e, stack);
rethrow;
}
}
Future<void> _registerIntents() async {
if (_client == null) {
throw StateError('Client not initialized');
}
// Navigation Intents
await _client!.registerIntent(
AppIntentBuilder()
.identifier('open_chat')
.title('Open Chat')
.description('Open a specific chat room')
.parameter(
const AppIntentParameter(
name: 'channelId',
title: 'Channel ID',
type: AppIntentParameterType.string,
isOptional: false,
),
)
.build(),
_handleOpenChatIntent,
);
await _client!.registerIntent(
AppIntentBuilder()
.identifier('open_post')
.title('Open Post')
.description('Open a specific post')
.parameter(
const AppIntentParameter(
name: 'postId',
title: 'Post ID',
type: AppIntentParameterType.string,
isOptional: false,
),
)
.build(),
_handleOpenPostIntent,
);
await _client!.registerIntent(
AppIntentBuilder()
.identifier('open_compose')
.title('Open Compose')
.description('Open compose post screen')
.build(),
_handleOpenComposeIntent,
);
// Action Intent
await _client!.registerIntent(
AppIntentBuilder()
.identifier('compose_post')
.title('Compose Post')
.description('Create a new post')
.build(),
_handleComposePostIntent,
);
// Query Intents
await _client!.registerIntent(
AppIntentBuilder()
.identifier('search_content')
.title('Search Content')
.description('Search for content')
.parameter(
const AppIntentParameter(
name: 'query',
title: 'Search Query',
type: AppIntentParameterType.string,
isOptional: false,
),
)
.build(),
_handleSearchContentIntent,
);
await _client!.registerIntent(
AppIntentBuilder()
.identifier('view_notifications')
.title('View Notifications')
.description('View notifications')
.build(),
_handleViewNotificationsIntent,
);
await _client!.registerIntent(
AppIntentBuilder()
.identifier('check_notifications')
.title('Check Notifications')
.description('Check notification count')
.build(),
_handleCheckNotificationsIntent,
);
}
void dispose() {
_client = null;
_initialized = false;
}
Future<AppIntentResult> _handleOpenChatIntent(
Map<String, dynamic> parameters,
) async {
try {
final channelId = parameters['channelId'] as String?;
if (channelId == null) {
throw ArgumentError('channelId is required');
}
talker.info('[AppIntents] Opening chat: $channelId');
if (rootNavigatorKey.currentContext == null) {
return AppIntentResult.failed(error: 'App context not available');
}
rootNavigatorKey.currentContext!.push('/chat/$channelId');
return AppIntentResult.successful(
value: 'Opening chat $channelId',
needsToContinueInApp: true,
);
} catch (e, stack) {
talker.error('[AppIntents] Failed to open chat', e, stack);
return AppIntentResult.failed(error: 'Failed to open chat: $e');
}
}
Future<AppIntentResult> _handleOpenPostIntent(
Map<String, dynamic> parameters,
) async {
try {
final postId = parameters['postId'] as String?;
if (postId == null) {
throw ArgumentError('postId is required');
}
talker.info('[AppIntents] Opening post: $postId');
if (rootNavigatorKey.currentContext == null) {
return AppIntentResult.failed(error: 'App context not available');
}
rootNavigatorKey.currentContext!.push('/posts/$postId');
return AppIntentResult.successful(
value: 'Opening post $postId',
needsToContinueInApp: true,
);
} catch (e, stack) {
talker.error('[AppIntents] Failed to open post', e, stack);
return AppIntentResult.failed(error: 'Failed to open post: $e');
}
}
Future<AppIntentResult> _handleOpenComposeIntent(
Map<String, dynamic> parameters,
) async {
try {
talker.info('[AppIntents] Opening compose screen');
if (rootNavigatorKey.currentContext == null) {
return AppIntentResult.failed(error: 'App context not available');
}
rootNavigatorKey.currentContext!.push('/posts/compose');
return AppIntentResult.successful(
value: 'Opening compose screen',
needsToContinueInApp: true,
);
} catch (e, stack) {
talker.error('[AppIntents] Failed to open compose', e, stack);
return AppIntentResult.failed(error: 'Failed to open compose: $e');
}
}
Future<AppIntentResult> _handleComposePostIntent(
Map<String, dynamic> parameters,
) async {
try {
talker.info('[AppIntents] Composing new post');
if (rootNavigatorKey.currentContext == null) {
return AppIntentResult.failed(error: 'App context not available');
}
rootNavigatorKey.currentContext!.push('/posts/compose');
return AppIntentResult.successful(
value: 'Opening compose screen',
needsToContinueInApp: true,
);
} catch (e, stack) {
talker.error('[AppIntents] Failed to compose post', e, stack);
return AppIntentResult.failed(error: 'Failed to compose post: $e');
}
}
Future<AppIntentResult> _handleSearchContentIntent(
Map<String, dynamic> parameters,
) async {
try {
final query = parameters['query'] as String?;
if (query == null) {
throw ArgumentError('query is required');
}
talker.info('[AppIntents] Searching for: $query');
if (rootNavigatorKey.currentContext == null) {
return AppIntentResult.failed(error: 'App context not available');
}
rootNavigatorKey.currentContext!.push('/search?q=$query');
return AppIntentResult.successful(
value: 'Searching for "$query"',
needsToContinueInApp: true,
);
} catch (e, stack) {
talker.error('[AppIntents] Failed to search', e, stack);
return AppIntentResult.failed(error: 'Failed to search: $e');
}
}
Future<AppIntentResult> _handleViewNotificationsIntent(
Map<String, dynamic> parameters,
) async {
try {
talker.info('[AppIntents] Opening notifications');
if (rootNavigatorKey.currentContext == null) {
return AppIntentResult.failed(error: 'App context not available');
}
// Note: You may need to adjust the route based on your actual notifications route
// This is a common pattern - check your route.dart for exact path
// If you don't have a dedicated notifications route, you might need to add one
return AppIntentResult.failed(
error: 'Notifications route not implemented',
);
} catch (e, stack) {
talker.error('[AppIntents] Failed to view notifications', e, stack);
return AppIntentResult.failed(error: 'Failed to view notifications: $e');
}
}
Future<AppIntentResult> _handleCheckNotificationsIntent(
Map<String, dynamic> parameters,
) async {
try {
talker.info('[AppIntents] Checking notifications count');
if (_dio == null) {
return AppIntentResult.failed(error: 'API client not initialized');
}
try {
final response = await _dio!.get('/ring/notifications/count');
final count = (response.data as num).toInt();
final countValue = count;
String message;
if (countValue == 0) {
message = 'You have no new notifications';
} else if (countValue == 1) {
message = 'You have 1 new notification';
} else {
message = 'You have $countValue new notifications';
}
return AppIntentResult.successful(
value: message,
needsToContinueInApp: false,
);
} on DioException catch (e) {
talker.error('[AppIntents] API error checking notifications', e);
return AppIntentResult.failed(
error:
'Failed to fetch notifications: ${e.message ?? 'Network error'}',
);
}
} catch (e, stack) {
talker.error('[AppIntents] Failed to check notifications', e, stack);
return AppIntentResult.failed(error: 'Failed to check notifications: $e');
}
}
// Donation Methods - to be called manually from your app code
Future<void> donateOpenChat(String channelId) async {
if (!_initialized) return;
try {
await FlutterAppIntentsService.donateIntentWithMetadata(
'open_chat',
{'channelId': channelId},
relevanceScore: 0.8,
context: {'feature': 'chat', 'userAction': true},
);
talker.info('[AppIntents] Donated open_chat intent');
} catch (e, stack) {
talker.error('[AppIntents] Failed to donate open_chat', e, stack);
}
}
Future<void> donateOpenPost(String postId) async {
if (!_initialized) return;
try {
await FlutterAppIntentsService.donateIntentWithMetadata(
'open_post',
{'postId': postId},
relevanceScore: 0.8,
context: {'feature': 'posts', 'userAction': true},
);
talker.info('[AppIntents] Donated open_post intent');
} catch (e, stack) {
talker.error('[AppIntents] Failed to donate open_post', e, stack);
}
}
Future<void> donateCompose() async {
if (!_initialized) return;
try {
await FlutterAppIntentsService.donateIntentWithMetadata(
'open_compose',
{},
relevanceScore: 0.9,
context: {'feature': 'compose', 'userAction': true},
);
talker.info('[AppIntents] Donated compose intent');
} catch (e, stack) {
talker.error('[AppIntents] Failed to donate compose', e, stack);
}
}
Future<void> donateSearch(String query) async {
if (!_initialized) return;
try {
await FlutterAppIntentsService.donateIntentWithMetadata(
'search_content',
{'query': query},
relevanceScore: 0.7,
context: {'feature': 'search', 'userAction': true},
);
talker.info('[AppIntents] Donated search intent');
} catch (e, stack) {
talker.error('[AppIntents] Failed to donate search', e, stack);
}
}
Future<void> donateCheckNotifications() async {
if (!_initialized) return;
try {
await FlutterAppIntentsService.donateIntentWithMetadata(
'check_notifications',
{},
relevanceScore: 0.6,
context: {'feature': 'notifications', 'userAction': true},
);
talker.info('[AppIntents] Donated check_notifications intent');
} catch (e, stack) {
talker.error(
'[AppIntents] Failed to donate check_notifications',
e,
stack,
);
}
}
}

View File

@@ -8,14 +8,13 @@ import 'package:flutter/services.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart'; import 'package:go_router/go_router.dart';
import 'package:island/main.dart'; import 'package:island/pods/audio.dart';
import 'package:island/pods/config.dart'; import 'package:island/pods/config.dart';
import 'package:island/pods/notification.dart';
import 'package:island/route.dart'; import 'package:island/route.dart';
import 'package:island/models/account.dart'; import 'package:island/models/account.dart';
import 'package:island/pods/websocket.dart'; import 'package:island/pods/websocket.dart';
import 'package:island/talker.dart'; import 'package:island/talker.dart';
import 'package:island/widgets/app_notification.dart';
import 'package:top_snackbar_flutter/top_snack_bar.dart';
import 'package:url_launcher/url_launcher_string.dart'; import 'package:url_launcher/url_launcher_string.dart';
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
@@ -97,39 +96,14 @@ StreamSubscription<WebSocketPacket> setupNotificationListener(
if (pkt.type == "notifications.new") { if (pkt.type == "notifications.new") {
final notification = SnNotification.fromJson(pkt.data!); final notification = SnNotification.fromJson(pkt.data!);
if (_appLifecycleState == AppLifecycleState.resumed) { if (_appLifecycleState == AppLifecycleState.resumed) {
// App is focused, show in-app notification
talker.info( talker.info(
'[Notification] Showing in-app notification: ${notification.title}', '[Notification] Showing in-app notification: ${notification.title}',
); );
if (settings.notifyWithHaptic) { if (settings.notifyWithHaptic) {
HapticFeedback.heavyImpact(); HapticFeedback.heavyImpact();
} }
showTopSnackBar( playNotificationSfx(ref);
globalOverlay.currentState!, ref.read(notificationStateProvider.notifier).add(notification);
Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 480),
child: NotificationCard(notification: notification),
),
),
onDismissed: () {},
dismissType: DismissType.onSwipe,
displayDuration: const Duration(seconds: 5),
snackBarPosition: SnackBarPosition.top,
padding: EdgeInsets.only(
left: 16,
right: 16,
top:
(!kIsWeb &&
(Platform.isMacOS ||
Platform.isWindows ||
Platform.isLinux))
? 28
// ignore: use_build_context_synchronously
: MediaQuery.of(context).padding.top + 16,
bottom: 16,
),
);
} else { } else {
// App is in background, show system notification (only on supported platforms) // App is in background, show system notification (only on supported platforms)
if (!kIsWeb && !Platform.isIOS) { if (!kIsWeb && !Platform.isIOS) {

View File

@@ -1,25 +1,21 @@
import 'dart:async'; import 'dart:async';
import 'dart:io'; import 'dart:io';
import 'package:dio/dio.dart';
import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart'; import 'package:island/pods/audio.dart';
import 'package:island/main.dart';
import 'package:island/pods/config.dart'; import 'package:island/pods/config.dart';
import 'package:island/route.dart'; import 'package:island/pods/notification.dart';
import 'package:island/models/account.dart'; import 'package:island/models/account.dart';
import 'package:island/pods/websocket.dart'; import 'package:island/pods/websocket.dart';
import 'package:island/talker.dart'; import 'package:island/talker.dart';
import 'package:island/widgets/app_notification.dart';
import 'package:top_snackbar_flutter/top_snack_bar.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart'; import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:windows_notification/windows_notification.dart' as winty; import 'package:windows_notification/windows_notification.dart' as winty;
import 'package:windows_notification/notification_message.dart'; import 'package:windows_notification/notification_message.dart';
import 'package:dio/dio.dart';
// Windows notification instance // Windows notification instance
winty.WindowsNotification? windowsNotification; winty.WindowsNotification? windowsNotification;
@@ -31,9 +27,7 @@ void _onAppLifecycleChanged(AppLifecycleState state) {
Future<void> initializeLocalNotifications() async { Future<void> initializeLocalNotifications() async {
// Initialize Windows notification for Windows platform // Initialize Windows notification for Windows platform
windowsNotification = winty.WindowsNotification( windowsNotification = winty.WindowsNotification(applicationId: "Solian");
applicationId: "Solian",
);
WidgetsBinding.instance.addObserver( WidgetsBinding.instance.addObserver(
LifecycleEventHandler(onAppLifecycleChanged: _onAppLifecycleChanged), LifecycleEventHandler(onAppLifecycleChanged: _onAppLifecycleChanged),
@@ -55,48 +49,20 @@ StreamSubscription<WebSocketPacket> setupNotificationListener(
BuildContext context, BuildContext context,
WidgetRef ref, WidgetRef ref,
) { ) {
final settings = ref.watch(appSettingsProvider);
final ws = ref.watch(websocketProvider); final ws = ref.watch(websocketProvider);
return ws.dataStream.listen((pkt) async { return ws.dataStream.listen((pkt) async {
if (pkt.type == "notifications.new") { if (pkt.type == "notifications.new") {
final notification = SnNotification.fromJson(pkt.data!); final notification = SnNotification.fromJson(pkt.data!);
if (_appLifecycleState == AppLifecycleState.resumed) { if (_appLifecycleState == AppLifecycleState.resumed) {
// App is focused, show in-app notification
talker.info( talker.info(
'[Notification] Showing in-app notification: ${notification.title}', '[Notification] Showing in-app notification: ${notification.title}',
); );
showTopSnackBar( if (settings.notifyWithHaptic) {
globalOverlay.currentState!, HapticFeedback.heavyImpact();
Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 480),
child: NotificationCard(notification: notification),
),
),
onTap: () {
if (notification.meta['action_uri'] != null) {
var uri = notification.meta['action_uri'] as String;
if (uri.startsWith('/')) {
// In-app routes
rootNavigatorKey.currentContext?.push(
notification.meta['action_uri'],
);
} else {
// External URLs
launchUrlString(uri);
} }
} playNotificationSfx(ref);
}, ref.read(notificationStateProvider.notifier).add(notification);
onDismissed: () {},
dismissType: DismissType.onSwipe,
displayDuration: const Duration(seconds: 5),
snackBarPosition: SnackBarPosition.top,
padding: EdgeInsets.only(
left: 16,
right: 16,
top: 28, // Windows specific padding
bottom: 16,
),
);
} else { } else {
// App is in background, show Windows system notification // App is in background, show Windows system notification
talker.info( talker.info(
@@ -139,7 +105,10 @@ StreamSubscription<WebSocketPacket> setupNotificationListener(
final notificationMessage = NotificationMessage.fromPluginTemplate( final notificationMessage = NotificationMessage.fromPluginTemplate(
notification.id, // unique id notification.id, // unique id
notification.title, notification.title,
[notification.subtitle, notification.content].where((e) => e.isNotEmpty).join('\n'), [
notification.subtitle,
notification.content,
].where((e) => e.isNotEmpty).join('\n'),
group: notification.topic, group: notification.topic,
image: imagePath, image: imagePath,
largeImage: largeImagePath, largeImage: largeImagePath,

View File

@@ -11,6 +11,7 @@ import 'package:island/widgets/post/post_shared.dart';
import 'package:path_provider/path_provider.dart' show getTemporaryDirectory; import 'package:path_provider/path_provider.dart' show getTemporaryDirectory;
import 'package:screenshot/screenshot.dart'; import 'package:screenshot/screenshot.dart';
import 'package:share_plus/share_plus.dart'; import 'package:share_plus/share_plus.dart';
import 'package:island/services/analytics_service.dart';
/// Shares a post as a screenshot image /// Shares a post as a screenshot image
Future<void> sharePostAsScreenshot( Future<void> sharePostAsScreenshot(
@@ -62,5 +63,9 @@ Future<void> sharePostAsScreenshot(
.catchError((err) { .catchError((err) {
if (context.mounted) hideLoadingModal(context); if (context.mounted) hideLoadingModal(context);
showErrorAlert(err); showErrorAlert(err);
})
.whenComplete(() {
final postTypeStr = post.type == 0 ? 'regular' : 'article';
AnalyticsService().logPostShared(post.id, 'screenshot', postTypeStr);
}); });
} }

View File

@@ -6,6 +6,8 @@ import 'package:flutter/material.dart';
import 'package:gap/gap.dart'; import 'package:gap/gap.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/main.dart'; import 'package:island/main.dart';
import 'package:island/models/account.dart';
import 'package:island/pods/notification.dart';
import 'package:island/talker.dart'; import 'package:island/talker.dart';
import 'package:material_symbols_icons/symbols.dart'; import 'package:material_symbols_icons/symbols.dart';
import 'package:styled_widget/styled_widget.dart'; import 'package:styled_widget/styled_widget.dart';
@@ -163,7 +165,6 @@ String _parseRemoteError(DioException err) {
return message ?? err.toString(); return message ?? err.toString();
} }
// Track active overlay dialogs for dismissal
final List<void Function()> _activeOverlayDialogs = []; final List<void Function()> _activeOverlayDialogs = [];
Future<T?> showOverlayDialog<T>({ Future<T?> showOverlayDialog<T>({
@@ -229,7 +230,6 @@ Future<T?> showOverlayDialog<T>({
return completer.future; return completer.future;
} }
// Close the topmost overlay dialog if any exists
bool closeTopmostOverlayDialog() { bool closeTopmostOverlayDialog() {
if (_activeOverlayDialogs.isNotEmpty) { if (_activeOverlayDialogs.isNotEmpty) {
final closeFunc = _activeOverlayDialogs.last; final closeFunc = _activeOverlayDialogs.last;
@@ -259,7 +259,8 @@ void showErrorAlert(dynamic err, {IconData? icon}) {
title: null, title: null,
titlePadding: EdgeInsets.zero, titlePadding: EdgeInsets.zero,
contentPadding: const EdgeInsets.fromLTRB(24, 24, 24, 0), contentPadding: const EdgeInsets.fromLTRB(24, 24, 24, 0),
content: Column( content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
@@ -274,10 +275,11 @@ void showErrorAlert(dynamic err, {IconData? icon}) {
style: Theme.of(context).textTheme.titleLarge, style: Theme.of(context).textTheme.titleLarge,
), ),
const Gap(8), const Gap(8),
Text(text), SelectableText(text),
const Gap(8), const Gap(8),
], ],
), ),
),
actions: [ actions: [
TextButton( TextButton(
onPressed: () => close(null), onPressed: () => close(null),
@@ -376,6 +378,34 @@ Future<bool> showConfirmAlert(
return result ?? false; return result ?? false;
} }
void showNotification({
required String title,
String content = '',
String subtitle = '',
Map<String, dynamic> meta = const {},
Duration? duration,
}) {
final context = globalOverlay.currentState!.context;
final ref = ProviderScope.containerOf(context);
final notification = SnNotification(
createdAt: DateTime.now(),
updatedAt: DateTime.now(),
deletedAt: null,
id: 'local_${DateTime.now().millisecondsSinceEpoch}',
topic: 'local',
title: title,
subtitle: subtitle,
content: content,
meta: meta,
priority: 0,
viewedAt: null,
accountId: 'local',
);
ref
.read(notificationStateProvider.notifier)
.add(notification, duration: duration);
}
Future<void> openExternalLink(Uri url, WidgetRef ref) async { Future<void> openExternalLink(Uri url, WidgetRef ref) async {
final whitelistDomains = ['solian.app', 'solsynth.dev']; final whitelistDomains = ['solian.app', 'solsynth.dev'];
if (whitelistDomains.any( if (whitelistDomains.any(

View File

@@ -17,7 +17,8 @@ import 'package:island/services/event_bus.dart';
import 'package:island/services/responsive.dart'; import 'package:island/services/responsive.dart';
import 'package:island/widgets/alert.dart'; import 'package:island/widgets/alert.dart';
import 'package:island/widgets/cmp/pattle.dart'; import 'package:island/widgets/cmp/pattle.dart';
import 'package:island/widgets/upload_overlay.dart'; import 'package:island/widgets/notification_overlay.dart';
import 'package:island/widgets/task_overlay.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart'; import 'package:material_symbols_icons/material_symbols_icons.dart';
import 'package:path_provider/path_provider.dart'; import 'package:path_provider/path_provider.dart';
import 'package:shake/shake.dart'; import 'package:shake/shake.dart';
@@ -125,6 +126,8 @@ class WindowScaffold extends HookConsumerWidget {
); );
useEffect(() { useEffect(() {
if (kIsWeb) return null;
hotKeyManager.register( hotKeyManager.register(
popHotKey, popHotKey,
keyDownHandler: (_) { keyDownHandler: (_) {
@@ -146,16 +149,19 @@ class WindowScaffold extends HookConsumerWidget {
}, },
); );
ShakeDetector detector = ShakeDetector.autoStart( ShakeDetector? detactor;
if (!kIsWeb && (Platform.isIOS && Platform.isAndroid)) {
detactor = ShakeDetector.autoStart(
onPhoneShake: (_) { onPhoneShake: (_) {
showPalette.value = true; showPalette.value = true;
}, },
); );
}
return () { return () {
hotKeyManager.unregister(popHotKey); hotKeyManager.unregister(popHotKey);
hotKeyManager.unregister(cmpHotKey); hotKeyManager.unregister(cmpHotKey);
detector.stopListening(); detactor?.stopListening();
}; };
}, []); }, []);
@@ -255,7 +261,8 @@ class WindowScaffold extends HookConsumerWidget {
], ],
), ),
_WebSocketIndicator(), _WebSocketIndicator(),
const UploadOverlay(), const TaskOverlay(),
const NotificationOverlay(),
if (showPalette.value) if (showPalette.value)
CommandPattleWidget(onDismiss: () => showPalette.value = false), CommandPattleWidget(onDismiss: () => showPalette.value = false),
], ],
@@ -268,7 +275,8 @@ class WindowScaffold extends HookConsumerWidget {
children: [ children: [
Positioned.fill(child: child), Positioned.fill(child: child),
_WebSocketIndicator(), _WebSocketIndicator(),
const UploadOverlay(), const TaskOverlay(),
const NotificationOverlay(),
if (showPalette.value) if (showPalette.value)
CommandPattleWidget(onDismiss: () => showPalette.value = false), CommandPattleWidget(onDismiss: () => showPalette.value = false),
], ],

View File

@@ -162,6 +162,7 @@ class AppWrapper extends HookConsumerWidget {
(now.day >= 22 && now.day <= 28); (now.day >= 22 && now.day <= 28);
useEffect(() { useEffect(() {
Future(() {
final now = DateTime.now(); final now = DateTime.now();
if (doesShowSnow) { if (doesShowSnow) {
isShowSnow.value = true; isShowSnow.value = true;
@@ -192,6 +193,7 @@ class AppWrapper extends HookConsumerWidget {
settingsNotifier.setAskedReview(true); settingsNotifier.setAskedReview(true);
} }
} }
});
return null; return null;
}, []); }, []);

View File

@@ -284,7 +284,12 @@ class ChatInput extends HookConsumerWidget {
onAttachmentsChanged([ onAttachmentsChanged([
...attachments, ...attachments,
UniversalFile( UniversalFile(
data: XFile.fromData(image, mimeType: "image/jpeg"), displayName: 'image.jpeg',
data: XFile.fromData(
image,
mimeType: "image/jpeg",
name: 'image.jpeg',
),
type: UniversalFileType.image, type: UniversalFileType.image,
), ),
]); ]);
@@ -458,6 +463,10 @@ class ChatInput extends HookConsumerWidget {
item: attachments[idx], item: attachments[idx],
progress: progress:
attachmentProgress['chat-upload']?[idx], attachmentProgress['chat-upload']?[idx],
isUploading:
attachmentProgress['chat-upload']
?.containsKey(idx) ??
false,
onRequestUpload: () => onUploadAttachment(idx), onRequestUpload: () => onUploadAttachment(idx),
onDelete: () => onDeleteAttachment(idx), onDelete: () => onDeleteAttachment(idx),
onUpdate: (value) { onUpdate: (value) {

View File

@@ -0,0 +1,129 @@
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/models/chat.dart';
import 'package:island/pods/userinfo.dart';
import 'package:island/widgets/content/cloud_files.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart';
import 'package:material_symbols_icons/symbols.dart';
import 'package:styled_widget/styled_widget.dart';
List<SnChatMember> getValidMembers(List<SnChatMember> members, String? userId) {
return members.where((member) => member.accountId != userId).toList();
}
class RoomAppBar extends ConsumerWidget {
final SnChatRoom room;
final int onlineCount;
final bool compact;
const RoomAppBar({
super.key,
required this.room,
required this.onlineCount,
required this.compact,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
final userInfo = ref.watch(userInfoProvider);
final validMembers = getValidMembers(
room.members ?? [],
userInfo.value?.id,
);
if (compact) {
return Row(
spacing: 8,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.start,
children: [
_OnlineCountBadge(
onlineCount: onlineCount,
child: _RoomAvatar(
room: room,
validMembers: validMembers,
size: 28,
),
),
Text(
(room.type == 1 && room.name == null)
? validMembers.map((e) => e.account.nick).join(', ')
: room.name!,
).fontSize(19),
],
);
}
return Column(
spacing: 4,
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
_OnlineCountBadge(
onlineCount: onlineCount,
child: _RoomAvatar(room: room, validMembers: validMembers, size: 26),
),
Text(
(room.type == 1 && room.name == null)
? validMembers.map((e) => e.account.nick).join(', ')
: room.name!,
).fontSize(15),
],
);
}
}
class _OnlineCountBadge extends StatelessWidget {
final int onlineCount;
final Widget child;
const _OnlineCountBadge({required this.onlineCount, required this.child});
@override
Widget build(BuildContext context) {
return Badge(
isLabelVisible: onlineCount > 1,
label: Text('$onlineCount'),
textStyle: GoogleFonts.robotoMono(fontSize: 10),
textColor: Colors.white,
backgroundColor: onlineCount > 1 ? Colors.green : Colors.grey,
offset: const Offset(6, 14),
child: child,
);
}
}
class _RoomAvatar extends StatelessWidget {
final SnChatRoom room;
final List<SnChatMember> validMembers;
final double size;
const _RoomAvatar({
required this.room,
required this.validMembers,
required this.size,
});
@override
Widget build(BuildContext context) {
return SizedBox(
height: size,
width: size,
child: (room.type == 1 && room.picture == null)
? SplitAvatarWidget(
files: validMembers
.map((e) => e.account.profile.picture)
.toList(),
)
: room.picture != null
? ProfilePictureWidget(file: room.picture, fallbackIcon: Symbols.chat)
: CircleAvatar(
child: Text(
room.name![0].toUpperCase(),
style: const TextStyle(fontSize: 12),
),
),
);
}
}

View File

@@ -0,0 +1,170 @@
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/database/message.dart';
import 'package:island/models/chat.dart';
import 'package:island/pods/config.dart';
import 'package:island/screens/chat/widgets/message_item_wrapper.dart';
import 'package:super_sliver_list/super_sliver_list.dart';
class RoomMessageList extends HookConsumerWidget {
final List<LocalChatMessage> messages;
final AsyncValue<SnChatRoom?> roomAsync;
final AsyncValue<SnChatMember?> chatIdentity;
final ScrollController scrollController;
final ListController listController;
final bool isSelectionMode;
final Set<String> selectedMessages;
final VoidCallback toggleSelectionMode;
final void Function(String) toggleMessageSelection;
final void Function(String action, LocalChatMessage message) onMessageAction;
final void Function(String messageId) onJump;
final Map<String, Map<int, double?>> attachmentProgress;
final bool disableAnimation;
final DateTime roomOpenTime;
final double inputHeight;
final double? previousInputHeight;
const RoomMessageList({
super.key,
required this.messages,
required this.roomAsync,
required this.chatIdentity,
required this.scrollController,
required this.listController,
required this.isSelectionMode,
required this.selectedMessages,
required this.toggleSelectionMode,
required this.toggleMessageSelection,
required this.onMessageAction,
required this.onJump,
required this.attachmentProgress,
required this.disableAnimation,
required this.roomOpenTime,
required this.inputHeight,
this.previousInputHeight,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
final settings = ref.watch(appSettingsProvider);
const messageKeyPrefix = 'message-';
final bottomPadding =
inputHeight + MediaQuery.of(context).padding.bottom + 8;
final listWidget =
previousInputHeight != null && previousInputHeight != inputHeight
? TweenAnimationBuilder<double>(
tween: Tween<double>(begin: previousInputHeight, end: inputHeight),
duration: const Duration(milliseconds: 200),
curve: Curves.easeOut,
builder: (context, height, child) => SuperListView.builder(
listController: listController,
controller: scrollController,
reverse: true,
padding: EdgeInsets.only(
top: 8,
bottom: height + MediaQuery.of(context).padding.bottom + 8,
),
itemCount: messages.length,
findChildIndexCallback: (key) {
if (key is! ValueKey<String>) return null;
final messageId = key.value.substring(messageKeyPrefix.length);
final index = messages.indexWhere(
(m) => (m.nonce ?? m.id) == messageId,
);
return index >= 0 ? index : null;
},
extentEstimation: (_, _) => 40,
itemBuilder: (context, index) {
final message = messages[index];
final nextMessage = index < messages.length - 1
? messages[index + 1]
: null;
final isLastInGroup =
nextMessage == null ||
nextMessage.senderId != message.senderId ||
nextMessage.createdAt
.difference(message.createdAt)
.inMinutes
.abs() >
3;
final key = Key(
'$messageKeyPrefix${message.nonce ?? message.id}',
);
return MessageItemWrapper(
key: key,
message: message,
index: index,
isLastInGroup: isLastInGroup,
isSelectionMode: isSelectionMode,
selectedMessages: selectedMessages,
chatIdentity: chatIdentity,
toggleSelectionMode: toggleSelectionMode,
toggleMessageSelection: toggleMessageSelection,
onMessageAction: onMessageAction,
onJump: onJump,
attachmentProgress: attachmentProgress,
disableAnimation: settings.disableAnimation,
roomOpenTime: roomOpenTime,
);
},
),
)
: SuperListView.builder(
listController: listController,
controller: scrollController,
reverse: true,
padding: EdgeInsets.only(top: 8, bottom: bottomPadding),
itemCount: messages.length,
findChildIndexCallback: (key) {
if (key is! ValueKey<String>) return null;
final messageId = key.value.substring(messageKeyPrefix.length);
final index = messages.indexWhere(
(m) => (m.nonce ?? m.id) == messageId,
);
return index >= 0 ? index : null;
},
extentEstimation: (_, _) => 40,
itemBuilder: (context, index) {
final message = messages[index];
final nextMessage = index < messages.length - 1
? messages[index + 1]
: null;
final isLastInGroup =
nextMessage == null ||
nextMessage.senderId != message.senderId ||
nextMessage.createdAt
.difference(message.createdAt)
.inMinutes
.abs() >
3;
final key = Key(
'$messageKeyPrefix${message.nonce ?? message.id}',
);
return MessageItemWrapper(
key: key,
message: message,
index: index,
isLastInGroup: isLastInGroup,
isSelectionMode: isSelectionMode,
selectedMessages: selectedMessages,
chatIdentity: chatIdentity,
toggleSelectionMode: toggleSelectionMode,
toggleMessageSelection: toggleMessageSelection,
onMessageAction: onMessageAction,
onJump: onJump,
attachmentProgress: attachmentProgress,
disableAnimation: settings.disableAnimation,
roomOpenTime: roomOpenTime,
);
},
);
return listWidget;
}
}

View File

@@ -0,0 +1,103 @@
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/models/chat.dart';
import 'package:island/widgets/chat/call_overlay.dart';
import 'package:styled_widget/styled_widget.dart';
class RoomOverlays extends ConsumerWidget {
final AsyncValue<SnChatRoom?> roomAsync;
final bool isSyncing;
final bool showGradient;
final double bottomGradientOpacity;
final double inputHeight;
const RoomOverlays({
super.key,
required this.roomAsync,
required this.isSyncing,
required this.showGradient,
required this.bottomGradientOpacity,
required this.inputHeight,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
return Stack(
children: [
Positioned(
left: 0,
right: 0,
top: 0,
child: roomAsync.when(
data: (data) => data != null
? CallOverlayBar(room: data).padding(horizontal: 8, top: 12)
: const SizedBox.shrink(),
error: (_, _) => const SizedBox.shrink(),
loading: () => const SizedBox.shrink(),
),
),
if (isSyncing)
Positioned(
top: 8,
right: 16,
child: Container(
padding: EdgeInsets.fromLTRB(
8,
8,
8,
8 + MediaQuery.of(context).padding.bottom,
),
decoration: BoxDecoration(
color: Theme.of(
context,
).scaffoldBackgroundColor.withOpacity(0.8),
borderRadius: BorderRadius.circular(8),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
),
const SizedBox(width: 8),
Text(
'Syncing...',
style: Theme.of(context).textTheme.bodySmall,
),
],
),
),
),
if (showGradient)
Positioned(
left: 0,
right: 0,
bottom: 0,
child: Opacity(
opacity: bottomGradientOpacity,
child: Container(
height: math.min(MediaQuery.of(context).size.height * 0.1, 128),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
colors: [
Theme.of(
context,
).colorScheme.surfaceContainer.withOpacity(0.8),
Theme.of(
context,
).colorScheme.surfaceContainer.withOpacity(0.0),
],
),
),
),
),
),
],
);
}
}

View File

@@ -0,0 +1,54 @@
import 'package:flutter/material.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart';
import 'package:material_symbols_icons/symbols.dart';
class RoomSelectionMode extends StatelessWidget {
final bool visible;
final int selectedCount;
final VoidCallback onClose;
final VoidCallback onAIThink;
const RoomSelectionMode({
super.key,
required this.visible,
required this.selectedCount,
required this.onClose,
required this.onAIThink,
});
@override
Widget build(BuildContext context) {
if (!visible) return const SizedBox.shrink();
return Container(
color: Theme.of(context).colorScheme.surface,
padding: EdgeInsets.only(
left: 16,
right: 16,
top: 8,
bottom: MediaQuery.of(context).padding.bottom + 8,
),
child: Row(
children: [
IconButton(
icon: const Icon(Icons.close),
onPressed: onClose,
tooltip: 'Cancel selection',
),
const SizedBox(width: 8),
Text(
'$selectedCount selected',
style: Theme.of(context).textTheme.titleMedium,
),
const Spacer(),
if (selectedCount > 0)
FilledButton.icon(
onPressed: onAIThink,
icon: const Icon(Symbols.smart_toy),
label: const Text('AI Think'),
),
],
),
);
}
}

View File

@@ -0,0 +1,177 @@
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/services/responsive.dart';
import 'package:island/widgets/post/article_sidebar_panel.dart';
class ResponsiveSidebar extends HookConsumerWidget {
final Widget attachmentsContent;
final Widget settingsContent;
final Widget mainContent;
final double sidebarWidth;
final ValueNotifier<bool> showSidebar;
const ResponsiveSidebar({
super.key,
required this.attachmentsContent,
required this.settingsContent,
required this.mainContent,
this.sidebarWidth = 480,
required this.showSidebar,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
final isWide = isWideScreen(context);
final animationController = useAnimationController(
duration: const Duration(milliseconds: 300),
);
final animation = useMemoized(
() => Tween<double>(begin: 0, end: 1).animate(
CurvedAnimation(parent: animationController, curve: Curves.easeInOut),
),
[animationController],
);
final showDrawer = useState(false);
final scaffoldKey = useMemoized(() => GlobalKey<ScaffoldState>());
useEffect(() {
void listener() {
final currentIsWide = isWideScreen(context);
if (currentIsWide) {
if (showSidebar.value && !showDrawer.value) {
showDrawer.value = true;
animationController.forward();
} else if (!showSidebar.value && showDrawer.value) {
// Don't set showDrawer.value = false here - let animation complete first
animationController.reverse();
}
} else {
if (showSidebar.value) {
scaffoldKey.currentState?.openEndDrawer();
} else {
Navigator.of(context).pop();
}
}
}
showSidebar.addListener(listener);
// Set initial state after first frame
WidgetsBinding.instance.addPostFrameCallback((_) => listener());
return () => showSidebar.removeListener(listener);
}, []);
useEffect(() {
void listener() {
if (!animationController.isAnimating &&
animationController.value == 0) {
showDrawer.value = false;
}
}
animationController.addListener(listener);
return () => animationController.removeListener(listener);
}, [animationController]);
void closeSidebar() {
showSidebar.value = false;
}
if (isWide) {
return LayoutBuilder(
builder: (context, constraints) {
return AnimatedBuilder(
animation: animation,
builder: (context, child) {
return Stack(
children: [
_buildWideScreenContent(
context,
constraints,
animation,
mainContent,
),
if (showDrawer.value)
Positioned(
right: 0,
top: 0,
bottom: 0,
width: sidebarWidth,
child: _buildWideScreenSidebar(
context,
animation,
attachmentsContent,
settingsContent,
closeSidebar,
),
),
],
);
},
);
},
);
} else {
return Scaffold(
key: scaffoldKey,
endDrawer: Drawer(
width: sidebarWidth,
child: ArticleSidebarPanelWidget(
attachmentsContent: attachmentsContent,
settingsContent: settingsContent,
onClose: () {
showSidebar.value = false;
Navigator.of(context).pop();
},
isWide: false,
width: sidebarWidth,
),
),
body: mainContent,
);
}
}
Widget _buildWideScreenContent(
BuildContext context,
BoxConstraints constraints,
Animation<double> animation,
Widget mainContent,
) {
return Positioned(
left: 0,
top: 0,
bottom: 0,
width: constraints.maxWidth - animation.value * sidebarWidth,
child: mainContent,
);
}
Widget _buildWideScreenSidebar(
BuildContext context,
Animation<double> animation,
Widget attachmentsContent,
Widget settingsContent,
VoidCallback onClose,
) {
return Transform.translate(
offset: Offset((1 - animation.value) * sidebarWidth, 0),
child: SizedBox(
width: sidebarWidth,
child: Material(
elevation: 8,
color: Theme.of(context).colorScheme.surfaceContainer,
child: ArticleSidebarPanelWidget(
attachmentsContent: attachmentsContent,
settingsContent: settingsContent,
onClose: onClose,
isWide: true,
width: sidebarWidth,
),
),
),
);
}
}

View File

@@ -2,6 +2,8 @@ import 'dart:convert';
import 'dart:io'; import 'dart:io';
import 'package:cross_file/cross_file.dart'; import 'package:cross_file/cross_file.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:video_thumbnail/video_thumbnail.dart';
import 'package:easy_localization/easy_localization.dart'; import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@@ -14,13 +16,12 @@ import 'package:island/services/file_uploader.dart';
import 'package:island/utils/format.dart'; import 'package:island/utils/format.dart';
import 'package:island/widgets/alert.dart'; import 'package:island/widgets/alert.dart';
import 'package:island/widgets/content/cloud_files.dart'; import 'package:island/widgets/content/cloud_files.dart';
import 'package:island/widgets/content/sensitive.dart';
import 'package:island/widgets/content/sheet.dart'; import 'package:island/widgets/content/sheet.dart';
import 'package:material_symbols_icons/symbols.dart'; import 'package:material_symbols_icons/symbols.dart';
import 'package:styled_widget/styled_widget.dart'; import 'package:styled_widget/styled_widget.dart';
import 'package:super_context_menu/super_context_menu.dart'; import 'package:super_context_menu/super_context_menu.dart';
import 'sensitive.dart';
class SensitiveMarksSelector extends StatefulWidget { class SensitiveMarksSelector extends StatefulWidget {
final List<int> initial; final List<int> initial;
final ValueChanged<List<int>>? onChanged; final ValueChanged<List<int>>? onChanged;
@@ -85,23 +86,31 @@ class SensitiveMarksSelectorState extends State<SensitiveMarksSelector> {
class AttachmentPreview extends HookConsumerWidget { class AttachmentPreview extends HookConsumerWidget {
final UniversalFile item; final UniversalFile item;
final double? progress; final double? progress;
final bool isUploading;
final Function(int)? onMove; final Function(int)? onMove;
final Function? onDelete; final Function? onDelete;
final Function? onInsert; final Function? onInsert;
final Function(UniversalFile)? onUpdate; final Function(UniversalFile)? onUpdate;
final Function? onRequestUpload; final Function? onRequestUpload;
final bool isCompact; final bool isCompact;
final String? thumbnailId;
final Function(String?)? onSetThumbnail;
final bool bordered;
const AttachmentPreview({ const AttachmentPreview({
super.key, super.key,
required this.item, required this.item,
this.progress, this.progress,
this.isUploading = false,
this.onRequestUpload, this.onRequestUpload,
this.onMove, this.onMove,
this.onDelete, this.onDelete,
this.onUpdate, this.onUpdate,
this.onInsert, this.onInsert,
this.isCompact = false, this.isCompact = false,
this.thumbnailId,
this.onSetThumbnail,
this.bordered = false,
}); });
// GlobalKey for selector // GlobalKey for selector
@@ -125,8 +134,7 @@ class AttachmentPreview extends HookConsumerWidget {
context: context, context: context,
isScrollControlled: true, isScrollControlled: true,
useRootNavigator: true, useRootNavigator: true,
builder: builder: (context) => SheetScaffold(
(context) => SheetScaffold(
heightFactor: 0.6, heightFactor: 0.6,
titleText: 'rename'.tr(), titleText: 'rename'.tr(),
child: Column( child: Column(
@@ -134,10 +142,7 @@ class AttachmentPreview extends HookConsumerWidget {
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
Padding( Padding(
padding: const EdgeInsets.symmetric( padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 24),
horizontal: 24,
vertical: 24,
),
child: TextField( child: TextField(
controller: nameController, controller: nameController,
decoration: InputDecoration( decoration: InputDecoration(
@@ -174,10 +179,7 @@ class AttachmentPreview extends HookConsumerWidget {
final newData = item.data; final newData = item.data;
newData.name = newName; newData.name = newName;
onUpdate?.call( onUpdate?.call(
item.copyWith( item.copyWith(data: newData, displayName: newName),
data: newData,
displayName: newName,
),
); );
if (context.mounted) Navigator.pop(context); if (context.mounted) Navigator.pop(context);
} catch (err) { } catch (err) {
@@ -205,8 +207,7 @@ class AttachmentPreview extends HookConsumerWidget {
await showModalBottomSheet( await showModalBottomSheet(
context: context, context: context,
isScrollControlled: true, isScrollControlled: true,
builder: builder: (context) => SheetScaffold(
(context) => SheetScaffold(
heightFactor: 0.6, heightFactor: 0.6,
titleText: 'markAsSensitive'.tr(), titleText: 'markAsSensitive'.tr(),
child: Column( child: Column(
@@ -214,17 +215,13 @@ class AttachmentPreview extends HookConsumerWidget {
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
Padding( Padding(
padding: const EdgeInsets.symmetric( padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 24),
horizontal: 24,
vertical: 24,
),
child: Column( child: Column(
children: [ children: [
// Sensitive categories checklist // Sensitive categories checklist
SensitiveMarksSelector( SensitiveMarksSelector(
key: _sensitiveSelectorKey, key: _sensitiveSelectorKey,
initial: initial: (item.data.sensitiveMarks ?? [])
(item.data.sensitiveMarks ?? [])
.map((e) => e as int) .map((e) => e as int)
.cast<int>() .cast<int>()
.toList(), .toList(),
@@ -253,8 +250,7 @@ class AttachmentPreview extends HookConsumerWidget {
showLoadingModal(context); showLoadingModal(context);
final apiClient = ref.watch(apiClientProvider); final apiClient = ref.watch(apiClientProvider);
// Use the current selections from stateful selector via GlobalKey // Use the current selections from stateful selector via GlobalKey
final selectorState = final selectorState = _sensitiveSelectorKey.currentState;
_sensitiveSelectorKey.currentState;
final marks = selectorState?.current ?? <int>[]; final marks = selectorState?.current ?? <int>[];
await apiClient.put( await apiClient.put(
'/drive/files/${item.data.id}/marks', '/drive/files/${item.data.id}/marks',
@@ -284,26 +280,16 @@ class AttachmentPreview extends HookConsumerWidget {
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
var ratio = var ratio = item.isOnCloud
item.isOnCloud
? (item.data.fileMeta?['ratio'] is num ? (item.data.fileMeta?['ratio'] is num
? item.data.fileMeta!['ratio'].toDouble() ? item.data.fileMeta!['ratio'].toDouble()
: 1.0) : null)
: 1.0; : null;
if (ratio == 0) ratio = 1.0;
final contentWidget = ClipRRect( final innerContentWidget = Stack(
borderRadius: BorderRadius.circular(8),
child: Container(
color: Theme.of(context).colorScheme.surfaceContainer,
child: Stack(
children: [
AspectRatio(
aspectRatio: ratio,
child: Stack(
fit: StackFit.expand, fit: StackFit.expand,
children: [ children: [
Builder( HookBuilder(
key: ValueKey(item.hashCode), key: ValueKey(item.hashCode),
builder: (context) { builder: (context) {
final fallbackIcon = switch (item.type) { final fallbackIcon = switch (item.type) {
@@ -326,9 +312,7 @@ class AttachmentPreview extends HookConsumerWidget {
if (snapshot.hasData) { if (snapshot.hasData) {
return Image.memory(snapshot.data!); return Image.memory(snapshot.data!);
} }
return const Center( return const Center(child: CircularProgressIndicator());
child: CircularProgressIndicator(),
);
}, },
); );
} }
@@ -338,7 +322,52 @@ class AttachmentPreview extends HookConsumerWidget {
return kIsWeb return kIsWeb
? Image.network(file.path) ? Image.network(file.path)
: Image.file(File(file.path)); : Image.file(File(file.path));
case UniversalFileType.video:
if (!kIsWeb) {
final thumbnailFuture = useMemoized(
() => VideoThumbnail.thumbnailData(
video: file.path,
imageFormat: ImageFormat.JPEG,
maxWidth: 320,
quality: 50,
),
[file.path],
);
return FutureBuilder<Uint8List?>(
future: thumbnailFuture,
builder: (context, snapshot) {
if (snapshot.hasData && snapshot.data != null) {
return Stack(
children: [
Image.memory(snapshot.data!),
Positioned.fill(
child: Center(
child: Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.5),
shape: BoxShape.circle,
),
child: const Icon(
Symbols.play_arrow,
color: Colors.white,
size: 32,
),
),
),
),
],
);
}
return const Center(child: CircularProgressIndicator());
},
);
}
break;
default: default:
break;
}
return Column( return Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
@@ -347,6 +376,8 @@ class AttachmentPreview extends HookConsumerWidget {
Text( Text(
_getDisplayName(), _getDisplayName(),
textAlign: TextAlign.center, textAlign: TextAlign.center,
maxLines: 2,
overflow: TextOverflow.ellipsis,
), ),
Text(mimeType, style: TextStyle(fontSize: 10)), Text(mimeType, style: TextStyle(fontSize: 10)),
const Gap(1), const Gap(1),
@@ -355,16 +386,13 @@ class AttachmentPreview extends HookConsumerWidget {
builder: (context, snapshot) { builder: (context, snapshot) {
if (snapshot.hasData) { if (snapshot.hasData) {
final size = snapshot.data as int; final size = snapshot.data as int;
return Text( return Text(formatFileSize(size)).fontSize(11);
formatFileSize(size),
).fontSize(11);
} }
return const SizedBox.shrink(); return const SizedBox.shrink();
}, },
), ),
], ],
); ).padding(vertical: 32);
}
} else if (item is List<int> || item is Uint8List) { } else if (item is List<int> || item is Uint8List) {
switch (item.type) { switch (item.type) {
case UniversalFileType.image: case UniversalFileType.image:
@@ -377,9 +405,7 @@ class AttachmentPreview extends HookConsumerWidget {
const Gap(6), const Gap(6),
Text(mimeType, style: TextStyle(fontSize: 10)), Text(mimeType, style: TextStyle(fontSize: 10)),
const Gap(1), const Gap(1),
Text( Text(formatFileSize(item.data.length)).fontSize(11),
formatFileSize(item.data.length),
).fontSize(11),
], ],
); );
} }
@@ -387,39 +413,110 @@ class AttachmentPreview extends HookConsumerWidget {
return Placeholder(); return Placeholder();
}, },
), ),
if (progress != null) if (isUploading && progress != null && (progress ?? 0) > 0)
Positioned.fill( Positioned.fill(
child: Container( child: Container(
color: Colors.black.withOpacity(0.3), color: Colors.black.withOpacity(0.3),
padding: EdgeInsets.symmetric( padding: EdgeInsets.symmetric(horizontal: 40, vertical: 16),
horizontal: 40,
vertical: 16,
),
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center,
children: [ children: [
if (progress != null)
Text( Text(
'${(progress! * 100).toStringAsFixed(2)}%', '${(progress! * 100).toStringAsFixed(2)}%',
style: TextStyle(color: Colors.white), style: TextStyle(color: Colors.white),
)
else
Text(
'uploading'.tr(),
style: TextStyle(color: Colors.white),
), ),
Gap(6), Gap(6),
Center( Center(
child: LinearProgressIndicator(value: progress), child: TweenAnimationBuilder<double>(
tween: Tween<double>(begin: 0.0, end: progress),
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
builder: (context, value, child) =>
LinearProgressIndicator(value: value),
),
), ),
], ],
), ),
), ),
), ),
if (isUploading && (progress == null || progress == 0))
Positioned.fill(
child: Container(
color: Colors.black.withOpacity(0.3),
padding: EdgeInsets.symmetric(horizontal: 40, vertical: 16),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
'processing'.tr(),
style: TextStyle(color: Colors.white),
),
Gap(6),
Center(child: LinearProgressIndicator(value: null)),
], ],
), ),
).center(), ),
),
if (thumbnailId != null &&
item.isOnCloud &&
(item.data as SnCloudFile).id == thumbnailId)
Positioned.fill(
child: Container(
decoration: BoxDecoration(
border: Border.all(
color: Theme.of(context).colorScheme.primary,
width: 3,
),
borderRadius: BorderRadius.circular(8),
),
),
),
if (thumbnailId != null &&
item.isOnCloud &&
(item.data as SnCloudFile).id == thumbnailId)
Positioned(
bottom: 8,
right: 8,
child: Container(
padding: const EdgeInsets.all(6),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.primary,
shape: BoxShape.circle,
),
child: Icon(
Symbols.image,
size: 16,
color: Theme.of(context).colorScheme.onPrimary,
),
),
),
],
);
final contentWidget = Container(
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceContainer,
border: bordered
? Border.all(
color: Theme.of(context).colorScheme.outline.withOpacity(0.5),
width: 1,
)
: null,
borderRadius: BorderRadius.circular(8),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Stack(
children: [
if (ratio != null)
AspectRatio(
aspectRatio: ratio,
child: innerContentWidget,
).center()
else
IntrinsicHeight(child: innerContentWidget).center(),
Row( Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
@@ -497,8 +594,9 @@ class AttachmentPreview extends HookConsumerWidget {
if (onRequestUpload != null) if (onRequestUpload != null)
InkWell( InkWell(
borderRadius: BorderRadius.circular(8), borderRadius: BorderRadius.circular(8),
onTap: onTap: item.isOnCloud
item.isOnCloud ? null : () => onRequestUpload?.call(), ? null
: () => onRequestUpload?.call(),
child: ClipRRect( child: ClipRRect(
borderRadius: BorderRadius.circular(8), borderRadius: BorderRadius.circular(8),
child: Container( child: Container(
@@ -507,8 +605,7 @@ class AttachmentPreview extends HookConsumerWidget {
horizontal: 8, horizontal: 8,
vertical: 4, vertical: 4,
), ),
child: child: (item.isOnCloud)
(item.isOnCloud)
? Row( ? Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
@@ -552,8 +649,7 @@ class AttachmentPreview extends HookConsumerWidget {
); );
return ContextMenuWidget( return ContextMenuWidget(
menuProvider: menuProvider: (MenuRequest request) => Menu(
(MenuRequest request) => Menu(
children: [ children: [
if (item.isOnDevice && item.type == UniversalFileType.image) if (item.isOnDevice && item.type == UniversalFileType.image)
MenuAction( MenuAction(
@@ -593,6 +689,24 @@ class AttachmentPreview extends HookConsumerWidget {
await _showSensitiveDialog(context, ref); await _showSensitiveDialog(context, ref);
}, },
), ),
if (item.isOnCloud &&
item.type == UniversalFileType.image &&
onSetThumbnail != null)
MenuAction(
title: thumbnailId == (item.data as SnCloudFile).id
? 'unsetAsThumbnail'.tr()
: 'setAsThumbnail'.tr(),
image: MenuImage.icon(Symbols.image),
callback: () {
final isCurrentlyThumbnail =
thumbnailId == (item.data as SnCloudFile).id;
if (isCurrentlyThumbnail) {
onSetThumbnail?.call(null);
} else {
onSetThumbnail?.call((item.data as SnCloudFile).id);
}
},
),
], ],
), ),
child: contentWidget, child: contentWidget,

View File

@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart'; import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:gap/gap.dart'; import 'package:gap/gap.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/pods/config.dart';
import 'package:island/pods/network.dart'; import 'package:island/pods/network.dart';
import 'package:island/services/time.dart'; import 'package:island/services/time.dart';
import 'package:island/talker.dart'; import 'package:island/talker.dart';
@@ -57,10 +58,14 @@ class _UniversalAudioState extends ConsumerState<UniversalAudio> {
final inCacheInfo = await DefaultCacheManager().getFileFromCache(url); final inCacheInfo = await DefaultCacheManager().getFileFromCache(url);
if (inCacheInfo == null) { if (inCacheInfo == null) {
talker.info('[MediaPlayer] Miss cache: $url'); talker.info('[MediaPlayer] Miss cache: $url');
final token = ref.watch(tokenProvider)?.token; final serverUrl = ref.read(serverUrlProvider);
final token = ref.read(tokenProvider);
final authHeaders = url.startsWith(serverUrl) && token != null
? {'Authorization': 'AtField ${token.token}'}
: null;
DefaultCacheManager().downloadFile( DefaultCacheManager().downloadFile(
url, url,
authHeaders: {'Authorization': 'AtField $token'}, authHeaders: authHeaders,
); );
uri = url; uri = url;
} else { } else {
@@ -68,7 +73,13 @@ class _UniversalAudioState extends ConsumerState<UniversalAudio> {
talker.info('[MediaPlayer] Hit cache: $url'); talker.info('[MediaPlayer] Hit cache: $url');
} }
_player!.open(Media(uri), play: widget.autoplay); final serverUrl = ref.read(serverUrlProvider);
final token = ref.read(tokenProvider);
final Map<String, String>? httpHeaders = uri.startsWith(serverUrl) && token != null
? {'Authorization': 'AtField ${token.token}'}
: null;
_player!.open(Media(uri, httpHeaders: httpHeaders), play: widget.autoplay);
} }
@override @override

View File

@@ -244,8 +244,7 @@ class CloudFileList extends HookConsumerWidget {
minWidth: minWidth ?? 0, minWidth: minWidth ?? 0,
maxWidth: files.length == 1 ? maxWidth : double.infinity, maxWidth: files.length == 1 ? maxWidth : double.infinity,
), ),
child: child: (ratio == null && isImage)
(ratio == null && isImage)
? IntrinsicWidth(child: IntrinsicHeight(child: widgetItem)) ? IntrinsicWidth(child: IntrinsicHeight(child: widgetItem))
: (ratio == null && isAudio) : (ratio == null && isAudio)
? IntrinsicHeight(child: widgetItem) ? IntrinsicHeight(child: widgetItem)
@@ -256,8 +255,7 @@ class CloudFileList extends HookConsumerWidget {
); );
} }
final allImages = final allImages = !files.any(
!files.any(
(e) => e.mimeType == null || !e.mimeType!.startsWith('image'), (e) => e.mimeType == null || !e.mimeType!.startsWith('image'),
); );
@@ -270,8 +268,7 @@ class CloudFileList extends HookConsumerWidget {
padding: padding ?? EdgeInsets.zero, padding: padding ?? EdgeInsets.zero,
child: LayoutBuilder( child: LayoutBuilder(
builder: (context, constraints) { builder: (context, constraints) {
final availableWidth = final availableWidth = constraints.maxWidth.isFinite
constraints.maxWidth.isFinite
? constraints.maxWidth ? constraints.maxWidth
: MediaQuery.of(context).size.width; : MediaQuery.of(context).size.width;
final itemExtent = math.min( final itemExtent = math.min(
@@ -339,8 +336,7 @@ class CloudFileList extends HookConsumerWidget {
padding: padding, padding: padding,
itemBuilder: (context, index) { itemBuilder: (context, index) {
return AspectRatio( return AspectRatio(
aspectRatio: aspectRatio: files[index].fileMeta?['ratio'] is num
files[index].fileMeta?['ratio'] is num
? files[index].fileMeta!['ratio'].toDouble() ? files[index].fileMeta!['ratio'].toDouble()
: 1.0, : 1.0,
child: Stack( child: Stack(
@@ -440,8 +436,7 @@ class _CloudFileListEntry extends HookConsumerWidget {
} }
final bool fullyUnlocked = !lockedByDS && !lockedByMature; final bool fullyUnlocked = !lockedByDS && !lockedByMature;
Widget fg = Widget fg = fullyUnlocked
fullyUnlocked
? (isImage ? (isImage
? CloudFileWidget( ? CloudFileWidget(
item: file, item: file,
@@ -458,22 +453,51 @@ class _CloudFileListEntry extends HookConsumerWidget {
)) ))
: const SizedBox.shrink(); : const SizedBox.shrink();
Widget overlays; Widget overlays = AnimatedSwitcher(
if (lockedByDS) { duration: const Duration(milliseconds: 300),
overlays = _DataSavingOverlay(); child: lockedByDS
} else if (file.sensitiveMarks.isNotEmpty) { ? _DataSavingOverlay(key: const ValueKey('ds'))
overlays = _SensitiveOverlay( : (file.sensitiveMarks.isNotEmpty && !showMature.value
? _SensitiveOverlay(
key: const ValueKey('sensitive-blur'),
file: file, file: file,
isRevealed: showMature.value, )
onHide: () => showMature.value = false, : const SizedBox.shrink(key: ValueKey('none'))),
);
Widget hideButton = const SizedBox.shrink();
if (file.sensitiveMarks.isNotEmpty && showMature.value) {
hideButton = Positioned(
top: 3,
left: 4,
child: IconButton(
iconSize: 16,
constraints: const BoxConstraints(),
icon: const Icon(
Icons.visibility_off,
color: Colors.white,
shadows: [
Shadow(
color: Colors.black,
blurRadius: 5.0,
offset: Offset(1.0, 1.0),
),
],
),
tooltip: 'Blur content',
onPressed: () => showMature.value = false,
),
); );
} else {
overlays = const SizedBox.shrink();
} }
final content = Stack( final content = Stack(
fit: StackFit.expand, fit: StackFit.expand,
children: [if (isImage) Positioned.fill(child: bg), fg, overlays], children: [
if (isImage) Positioned.fill(child: bg),
fg,
overlays,
hideButton,
],
); );
return InkWell( return InkWell(
@@ -494,41 +518,11 @@ class _CloudFileListEntry extends HookConsumerWidget {
class _SensitiveOverlay extends StatelessWidget { class _SensitiveOverlay extends StatelessWidget {
final SnCloudFile file; final SnCloudFile file;
final VoidCallback? onHide;
final bool isRevealed;
const _SensitiveOverlay({ const _SensitiveOverlay({required this.file, super.key});
required this.file,
this.onHide,
this.isRevealed = false,
});
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (isRevealed) {
return Positioned(
top: 3,
left: 4,
child: IconButton(
iconSize: 16,
constraints: const BoxConstraints(),
icon: const Icon(
Icons.visibility_off,
color: Colors.white,
shadows: [
Shadow(
color: Colors.black,
blurRadius: 5.0,
offset: Offset(1.0, 1.0),
),
],
),
tooltip: 'Blur content',
onPressed: onHide,
),
);
}
return BackdropFilter( return BackdropFilter(
filter: ImageFilter.blur(sigmaX: 64, sigmaY: 64), filter: ImageFilter.blur(sigmaX: 64, sigmaY: 64),
child: Container( child: Container(
@@ -549,6 +543,8 @@ class _SensitiveOverlay extends StatelessWidget {
} }
class _DataSavingOverlay extends StatelessWidget { class _DataSavingOverlay extends StatelessWidget {
const _DataSavingOverlay({super.key});
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return ColoredBox( return ColoredBox(

View File

@@ -202,9 +202,9 @@ class _EmbedLinkWidgetState extends State<EmbedLinkWidget> {
const Gap(8), const Gap(8),
// Title // Title
if (widget.link.title.isNotEmpty) ...[ if (widget.link.title?.isNotEmpty ?? false) ...[
Text( Text(
widget.link.title, widget.link.title!,
style: theme.textTheme.titleMedium?.copyWith( style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
), ),

View File

@@ -124,24 +124,6 @@ class FileInfoSheet extends StatelessWidget {
}, },
), ),
), ),
if (item.pool != null)
ListTile(
leading: const Icon(Symbols.calendar_today),
title: Text('File Pool').tr(),
subtitle: Text(
item.pool!.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
contentPadding: EdgeInsets.symmetric(horizontal: 24),
trailing: IconButton(
icon: const Icon(Icons.copy),
onPressed: () {
Clipboard.setData(ClipboardData(text: item.pool!.id));
showSnackBar('fileNameCopied'.tr());
},
),
),
ListTile( ListTile(
leading: const Icon(Symbols.launch), leading: const Icon(Symbols.launch),
title: Text('openInBrowser').tr(), title: Text('openInBrowser').tr(),
@@ -176,8 +158,7 @@ class FileInfoSheet extends StatelessWidget {
contentPadding: EdgeInsets.symmetric( contentPadding: EdgeInsets.symmetric(
horizontal: 24, horizontal: 24,
), ),
title: title: Text(
Text(
entry.key.contains('-') entry.key.contains('-')
? entry.key.split('-').last ? entry.key.split('-').last
: entry.key, : entry.key,
@@ -227,8 +208,7 @@ class FileInfoSheet extends StatelessWidget {
contentPadding: EdgeInsets.symmetric( contentPadding: EdgeInsets.symmetric(
horizontal: 24, horizontal: 24,
), ),
title: title: Text(
Text(
entry.key, entry.key,
style: theme.textTheme.bodyMedium?.copyWith( style: theme.textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w500, fontWeight: FontWeight.w500,
@@ -276,8 +256,7 @@ class FileInfoSheet extends StatelessWidget {
contentPadding: EdgeInsets.symmetric( contentPadding: EdgeInsets.symmetric(
horizontal: 24, horizontal: 24,
), ),
title: title: Text(
Text(
entry.key, entry.key,
style: theme.textTheme.bodyMedium?.copyWith( style: theme.textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w500, fontWeight: FontWeight.w500,

View File

@@ -1,10 +1,16 @@
import 'dart:math' as math;
import 'package:cached_network_image/cached_network_image.dart'; import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_blurhash/flutter_blurhash.dart'; import 'package:flutter_blurhash/flutter_blurhash.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_svg/flutter_svg.dart'; import 'package:flutter_svg/flutter_svg.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/pods/config.dart';
import 'package:island/pods/network.dart';
class UniversalImage extends HookWidget { class UniversalImage extends HookConsumerWidget {
final String uri; final String uri;
final String? blurHash; final String? blurHash;
final BoxFit fit; final BoxFit fit;
@@ -27,10 +33,26 @@ class UniversalImage extends HookWidget {
}); });
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context, WidgetRef ref) {
final loaded = useState(false); final loaded = useState(false);
final isCached = useState<bool?>(null);
final isSvgImage = isSvg || uri.toLowerCase().endsWith('.svg'); final isSvgImage = isSvg || uri.toLowerCase().endsWith('.svg');
final serverUrl = ref.watch(serverUrlProvider);
final token = ref.watch(tokenProvider);
final Map<String, String>? httpHeaders =
uri.startsWith(serverUrl) && token != null
? {'Authorization': 'AtField ${token.token}'}
: null;
useEffect(() {
DefaultCacheManager().getFileFromCache(uri).then((fileInfo) {
isCached.value = fileInfo != null;
});
return null;
}, [uri]);
if (isSvgImage) { if (isSvgImage) {
return SvgPicture.network( return SvgPicture.network(
uri, uri,
@@ -59,8 +81,35 @@ class UniversalImage extends HookWidget {
fit: StackFit.expand, fit: StackFit.expand,
children: [ children: [
if (blurHash != null) BlurHash(hash: blurHash!), if (blurHash != null) BlurHash(hash: blurHash!),
if (isCached.value == null)
Center(child: CircularProgressIndicator())
else if (isCached.value!)
CachedNetworkImage( CachedNetworkImage(
imageUrl: uri, imageUrl: uri,
httpHeaders: httpHeaders,
fit: fit,
width: width,
height: height,
memCacheHeight: cacheHeight,
memCacheWidth: cacheWidth,
imageBuilder: (context, imageProvider) => Image(
image: imageProvider,
fit: fit,
width: width,
height: height,
),
errorWidget: (context, url, error) => CachedImageErrorWidget(
useFallbackImage: useFallbackImage,
uri: uri,
blurHash: blurHash,
error: error,
debug: true,
),
)
else
CachedNetworkImage(
imageUrl: uri,
httpHeaders: httpHeaders,
fit: fit, fit: fit,
width: width, width: width,
height: height, height: height,
@@ -76,7 +125,7 @@ class UniversalImage extends HookWidget {
}, },
imageBuilder: (context, imageProvider) { imageBuilder: (context, imageProvider) {
Future(() { Future(() {
if (context.mounted) return loaded.value = true; if (context.mounted) loaded.value = true;
}); });
return AnimatedOpacity( return AnimatedOpacity(
opacity: loaded.value ? 1.0 : 0.0, opacity: loaded.value ? 1.0 : 0.0,
@@ -89,13 +138,13 @@ class UniversalImage extends HookWidget {
), ),
); );
}, },
errorWidget: (context, url, error) => useFallbackImage errorWidget: (context, url, error) => CachedImageErrorWidget(
? Image.asset( useFallbackImage: useFallbackImage,
'assets/images/media-offline.jpg', uri: uri,
fit: BoxFit.cover, blurHash: blurHash,
key: Key('image-broke-$uri'), error: error,
) debug: true,
: SizedBox.shrink(), ),
), ),
], ],
), ),
@@ -103,6 +152,135 @@ class UniversalImage extends HookWidget {
} }
} }
class CachedImageErrorWidget extends StatelessWidget {
final bool useFallbackImage;
final String uri;
final String? blurHash;
final dynamic error;
final bool debug;
const CachedImageErrorWidget({
super.key,
required this.useFallbackImage,
required this.uri,
this.blurHash,
this.error,
this.debug = false,
});
int? _extractStatusCode(dynamic error) {
if (error == null) return null;
final errorString = error.toString();
// Check for HttpException with status code
final httpExceptionRegex = RegExp(r'Invalid statusCode: (\d+)');
final match = httpExceptionRegex.firstMatch(errorString);
if (match != null) {
return int.tryParse(match.group(1) ?? '');
}
// Check if error has statusCode property (like DioError)
if (error.response?.statusCode != null) {
return error.response.statusCode;
}
return null;
}
@override
Widget build(BuildContext context) {
if (debug && error != null) {
debugPrint('Image load error for $uri: $error');
}
if (!useFallbackImage) {
return SizedBox.shrink();
}
final statusCode = _extractStatusCode(error);
return LayoutBuilder(
builder: (context, constraints) {
final minDimension = constraints.maxWidth < constraints.maxHeight
? constraints.maxWidth
: constraints.maxHeight;
final iconSize = math.max(
minDimension * 0.3,
28,
); // 30% of the smaller dimension
final hasEnoughSpace = minDimension > 40;
return Stack(
fit: StackFit.expand,
children: [
if (blurHash != null)
BlurHash(hash: blurHash!)
else
Image.asset(
'assets/images/media-offline.jpg',
fit: BoxFit.cover,
key: Key('-$uri'),
),
Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
_getErrorIcon(statusCode),
color: Colors.white,
size: iconSize * 0.5,
shadows: [
BoxShadow(
color: Colors.black.withOpacity(0.3),
blurRadius: 4,
offset: Offset(0, 2),
),
],
),
if (hasEnoughSpace && statusCode != null) ...[
SizedBox(height: iconSize * 0.1),
Container(
padding: EdgeInsets.symmetric(
horizontal: iconSize * 0.15,
vertical: iconSize * 0.05,
),
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.7),
borderRadius: BorderRadius.circular(iconSize * 0.1),
),
child: Text(
statusCode.toString(),
style: TextStyle(
color: Colors.white,
fontSize: iconSize * 0.15,
fontWeight: FontWeight.bold,
),
),
),
],
],
),
),
],
);
},
);
}
IconData _getErrorIcon(int? statusCode) {
switch (statusCode) {
case 403:
case 401:
return Icons.lock_rounded;
case 404:
return Icons.broken_image_rounded;
case 500:
case 502:
case 503:
return Icons.error_rounded;
default:
return Icons.broken_image_rounded;
}
}
}
class AnimatedCircularProgressIndicator extends HookWidget { class AnimatedCircularProgressIndicator extends HookWidget {
final double? value; final double? value;
final Color? color; final Color? color;

View File

@@ -2,6 +2,8 @@ import 'dart:io';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:island/pods/config.dart';
import 'package:island/pods/network.dart';
import 'package:media_kit/media_kit.dart'; import 'package:media_kit/media_kit.dart';
import 'package:media_kit_video/media_kit_video.dart'; import 'package:media_kit_video/media_kit_video.dart';
@@ -30,7 +32,14 @@ class _UniversalVideoState extends ConsumerState<UniversalVideo> {
_player = Player(); _player = Player();
_videoController = VideoController(_player!); _videoController = VideoController(_player!);
_player!.open(Media(widget.uri), play: widget.autoplay); final serverUrl = ref.read(serverUrlProvider);
final token = ref.read(tokenProvider);
final Map<String, String>? httpHeaders =
widget.uri.startsWith(serverUrl) && token != null
? {'Authorization': 'AtField ${token.token}'}
: null;
_player!.open(Media(widget.uri, httpHeaders: httpHeaders), play: widget.autoplay);
} }
@override @override

View File

@@ -2,11 +2,11 @@ import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/pods/config.dart'; import 'package:island/pods/config.dart';
typedef WidgetBuilder0 = Widget Function(); typedef WidgetBuilder = Widget Function();
class DataSavingGate extends ConsumerWidget { class DataSavingGate extends ConsumerWidget {
final bool bypass; final bool bypass;
final WidgetBuilder0 content; final WidgetBuilder content;
final Widget placeholder; final Widget placeholder;
const DataSavingGate({ const DataSavingGate({

View File

@@ -3,6 +3,7 @@ import 'package:flutter/services.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart'; import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:gap/gap.dart'; import 'package:gap/gap.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/pods/audio.dart';
import 'package:island/pods/message.dart'; import 'package:island/pods/message.dart';
import 'package:island/pods/network.dart'; import 'package:island/pods/network.dart';
import 'package:island/services/update_service.dart'; import 'package:island/services/update_service.dart';
@@ -77,7 +78,7 @@ class DebugSheet extends HookConsumerWidget {
minTileHeight: 48, minTileHeight: 48,
leading: const Icon(Symbols.update), leading: const Icon(Symbols.update),
trailing: const Icon(Symbols.chevron_right), trailing: const Icon(Symbols.chevron_right),
title: Text('Force Update'), title: Text('Force update'),
contentPadding: const EdgeInsets.symmetric(horizontal: 24), contentPadding: const EdgeInsets.symmetric(horizontal: 24),
onTap: () async { onTap: () async {
// Fetch latest release and show the unified sheet // Fetch latest release and show the unified sheet
@@ -102,7 +103,7 @@ class DebugSheet extends HookConsumerWidget {
minTileHeight: 48, minTileHeight: 48,
leading: const Icon(Symbols.wifi), leading: const Icon(Symbols.wifi),
trailing: const Icon(Symbols.chevron_right), trailing: const Icon(Symbols.chevron_right),
title: Text('Connection Status'), title: Text('Connection status'),
contentPadding: EdgeInsets.symmetric(horizontal: 24), contentPadding: EdgeInsets.symmetric(horizontal: 24),
onTap: () { onTap: () {
showModalBottomSheet( showModalBottomSheet(
@@ -128,6 +129,23 @@ class DebugSheet extends HookConsumerWidget {
}, },
), ),
const Divider(height: 8), const Divider(height: 8),
ListTile(
minTileHeight: 48,
leading: const Icon(Symbols.play_arrow),
trailing: const Icon(Symbols.chevron_right),
contentPadding: EdgeInsets.symmetric(horizontal: 24),
title: Text('Play untitled'),
onTap: () async {
final synth = MiniSampleSynth(
sampleAsset: 'assets/audio/messages.mp3',
baseNote: 60,
);
await synth.playMidiAsset(
'assets/midi/never-gonna-give-you-up.mid',
);
},
),
const Divider(height: 8),
ListTile( ListTile(
minTileHeight: 48, minTileHeight: 48,
leading: const Icon(Symbols.copy_all), leading: const Icon(Symbols.copy_all),

View File

@@ -38,6 +38,8 @@ class ExtendedRefreshIndicator extends HookConsumerWidget {
); );
useEffect(() { useEffect(() {
if (kIsWeb) return null;
hotKeyManager.register( hotKeyManager.register(
refreshHotKey, refreshHotKey,
keyDownHandler: (_) { keyDownHandler: (_) {

View File

@@ -1,7 +1,6 @@
import 'dart:async'; import 'dart:async';
import 'package:desktop_drop/desktop_drop.dart'; import 'package:desktop_drop/desktop_drop.dart';
import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:easy_localization/easy_localization.dart'; import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:flutter_hooks/flutter_hooks.dart';
@@ -19,7 +18,7 @@ import 'package:island/services/file_uploader.dart';
import 'package:island/services/responsive.dart'; import 'package:island/services/responsive.dart';
import 'package:island/utils/file_icon_utils.dart'; import 'package:island/utils/file_icon_utils.dart';
import 'package:island/utils/format.dart'; import 'package:island/utils/format.dart';
import 'package:island/utils/text.dart';
import 'package:island/widgets/alert.dart'; import 'package:island/widgets/alert.dart';
import 'package:island/widgets/content/cloud_files.dart'; import 'package:island/widgets/content/cloud_files.dart';
import 'package:island/widgets/paging/pagination_list.dart'; import 'package:island/widgets/paging/pagination_list.dart';
@@ -40,6 +39,8 @@ class FileListView extends HookConsumerWidget {
final Function(BuildContext, ValueNotifier<String>) onShowCreateDirectory; final Function(BuildContext, ValueNotifier<String>) onShowCreateDirectory;
final ValueNotifier<FileListMode> mode; final ValueNotifier<FileListMode> mode;
final ValueNotifier<FileListViewMode> viewMode; final ValueNotifier<FileListViewMode> viewMode;
final ValueNotifier<bool> isSelectionMode;
final ValueNotifier<String?> query;
const FileListView({ const FileListView({
required this.usage, required this.usage,
@@ -50,6 +51,8 @@ class FileListView extends HookConsumerWidget {
required this.onShowCreateDirectory, required this.onShowCreateDirectory,
required this.mode, required this.mode,
required this.viewMode, required this.viewMode,
required this.isSelectionMode,
required this.query,
super.key, super.key,
}); });
@@ -74,7 +77,6 @@ class FileListView extends HookConsumerWidget {
final isSelectionMode = useState<bool>(false); final isSelectionMode = useState<bool>(false);
final selectedFileIds = useState<Set<String>>({}); final selectedFileIds = useState<Set<String>>({});
final currentVisibleItems = useState<List<FileListItem>>([]); final currentVisibleItems = useState<List<FileListItem>>([]);
final query = useState<String?>(null);
final order = useState<String?>('date'); final order = useState<String?>('date');
final orderDesc = useState<bool>(true); final orderDesc = useState<bool>(true);
final queryDebounceTimer = useRef<Timer?>(null); final queryDebounceTimer = useRef<Timer?>(null);
@@ -100,16 +102,16 @@ class FileListView extends HookConsumerWidget {
useEffect(() { useEffect(() {
// Sync query, order, and orderDesc filters // Sync query, order, and orderDesc filters
if (mode.value == FileListMode.unindexed) { if (mode.value == FileListMode.unindexed) {
unindexedNotifier.setQuery(query.value); unindexedNotifier.setQuery(this.query.value);
unindexedNotifier.setOrder(order.value); unindexedNotifier.setOrder(order.value);
unindexedNotifier.setOrderDesc(orderDesc.value); unindexedNotifier.setOrderDesc(orderDesc.value);
} else { } else {
cloudNotifier.setQuery(query.value); cloudNotifier.setQuery(this.query.value);
cloudNotifier.setOrder(order.value); cloudNotifier.setOrder(order.value);
cloudNotifier.setOrderDesc(orderDesc.value); cloudNotifier.setOrderDesc(orderDesc.value);
} }
return null; return null;
}, [query.value, order.value, orderDesc.value, mode.value]); }, [this.query.value, order.value, orderDesc.value, mode.value]);
final isRefreshing = ref.watch( final isRefreshing = ref.watch(
mode.value == FileListMode.normal mode.value == FileListMode.normal
@@ -159,16 +161,99 @@ class FileListView extends HookConsumerWidget {
), ),
}; };
late Widget pathContent; late Widget pathWidget;
if (mode.value == FileListMode.unindexed) { if (mode.value == FileListMode.unindexed) {
pathContent = const Text( pathWidget = InkWell(
'Unindexed Files', onTap: () async {
style: TextStyle(fontWeight: FontWeight.bold), final result = await showMenu<String>(
context: context,
position: const RelativeRect.fromLTRB(50, 100, 50, 100),
items: [
PopupMenuItem<String>(
value: 'root',
child: Row(
children: [
Icon(Symbols.folder),
const Gap(12),
Text('rootDirectory').tr(),
],
),
),
PopupMenuItem<String>(
value: 'unindexed',
child: Row(
children: [
Icon(Symbols.inventory_2),
const Gap(12),
Text('unindexedFiles').tr(),
],
),
),
],
);
if (result == 'root') {
mode.value = FileListMode.normal;
currentPath.value = '/';
}
// 'unindexed' does nothing as we're already in unindexed mode
},
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Symbols.inventory_2, size: 20),
const Gap(8),
Text(
'unindexedFiles',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
).tr(),
],
),
); );
} else if (currentPath.value == '/') { } else if (currentPath.value == '/') {
pathContent = const Text( pathWidget = InkWell(
'Root Directory', onTap: () async {
style: TextStyle(fontWeight: FontWeight.bold), final result = await showMenu<String>(
context: context,
position: const RelativeRect.fromLTRB(50, 100, 50, 100),
items: [
PopupMenuItem<String>(
value: 'unindexed',
child: Row(
children: [
Icon(Symbols.inventory_2),
const Gap(12),
Text('unindexedFiles').tr(),
],
),
),
PopupMenuItem<String>(
value: 'root',
child: Row(
children: [
Icon(Symbols.folder),
const Gap(12),
Text('rootDirectory').tr(),
],
),
),
],
);
if (result == 'unindexed') {
mode.value = FileListMode.unindexed;
}
// 'root' does nothing as we're already at root
},
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Symbols.folder, size: 20),
const Gap(8),
Text(
'rootDirectory',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
).tr(),
],
),
); );
} else { } else {
final pathParts = currentPath.value final pathParts = currentPath.value
@@ -181,7 +266,17 @@ class FileListView extends HookConsumerWidget {
breadcrumbs.add( breadcrumbs.add(
InkWell( InkWell(
onTap: () => currentPath.value = '/', onTap: () => currentPath.value = '/',
child: const Text('Root'), child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Symbols.folder, size: 20),
const Gap(4),
const Text(
'Root',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
),
],
),
), ),
); );
@@ -191,13 +286,13 @@ class FileListView extends HookConsumerWidget {
currentPathBuilder += '/${pathParts[i]}'; currentPathBuilder += '/${pathParts[i]}';
final path = currentPathBuilder; final path = currentPathBuilder;
breadcrumbs.add(const Text(' / ')); breadcrumbs.add(Text('pathSeparator').tr());
if (i == pathParts.length - 1) { if (i == pathParts.length - 1) {
// Current directory // Current directory
breadcrumbs.add( breadcrumbs.add(
Text( Text(
pathParts[i], pathParts[i],
style: const TextStyle(fontWeight: FontWeight.bold), style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
), ),
); );
} else { } else {
@@ -205,13 +300,16 @@ class FileListView extends HookConsumerWidget {
breadcrumbs.add( breadcrumbs.add(
InkWell( InkWell(
onTap: () => currentPath.value = path, onTap: () => currentPath.value = path,
child: Text(pathParts[i]), child: Text(
pathParts[i],
style: const TextStyle(color: Colors.blue),
),
), ),
); );
} }
} }
pathContent = Wrap( pathWidget = Wrap(
crossAxisAlignment: WrapCrossAlignment.center, crossAxisAlignment: WrapCrossAlignment.center,
children: breadcrumbs, children: breadcrumbs,
); );
@@ -248,7 +346,7 @@ class FileListView extends HookConsumerWidget {
} }
}) })
.catchError((error) { .catchError((error) {
showSnackBar('Failed to upload file: $error'); showSnackBar('failedToUploadFile'.tr(args: [error]));
}); });
} }
}, },
@@ -263,10 +361,48 @@ class FileListView extends HookConsumerWidget {
? Theme.of(context).primaryColor.withOpacity(0.1) ? Theme.of(context).primaryColor.withOpacity(0.1)
: null, : null,
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
const Gap(12), const Gap(12),
_buildGlobalFilters(
// Breadcrumbs and view switch at the top
Padding(
padding: const EdgeInsets.fromLTRB(24, 0, 16, 0),
child: Row(
children: [
Expanded(
child: AbsorbPointer(
absorbing: isRefreshing,
child: pathWidget,
),
),
const Gap(12),
SegmentedButton<FileListViewMode>(
segments: [
ButtonSegment<FileListViewMode>(
value: FileListViewMode.list,
icon: Icon(Symbols.list),
tooltip: 'listView'.tr(),
),
ButtonSegment<FileListViewMode>(
value: FileListViewMode.waterfall,
icon: Icon(Symbols.view_module),
tooltip: 'waterfallView'.tr(),
),
],
selected: {viewMode.value},
onSelectionChanged: (Set<FileListViewMode> newSelection) {
viewMode.value = newSelection.first;
},
),
],
),
),
const Gap(12),
// Chip-based filters
_buildChipFilters(
ref, ref,
poolsAsync, poolsAsync,
selectedPool, selectedPool,
@@ -280,128 +416,8 @@ class FileListView extends HookConsumerWidget {
orderDesc, orderDesc,
queryDebounceTimer, queryDebounceTimer,
), ),
const Gap(6),
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
IconButton(
icon: Icon(
mode.value == FileListMode.unindexed
? Symbols.inventory_2
: currentPath.value != '/'
? Symbols.arrow_back
: Symbols.folder,
),
onPressed: isRefreshing
? null
: () {
if (mode.value == FileListMode.unindexed) {
mode.value = FileListMode.normal;
currentPath.value = '/';
} else {
final pathParts = currentPath.value
.split('/')
.where((part) => part.isNotEmpty)
.toList();
if (pathParts.isNotEmpty) {
pathParts.removeLast();
currentPath.value = pathParts.isEmpty
? '/'
: '/${pathParts.join('/')}';
}
}
},
visualDensity: const VisualDensity(
horizontal: -4,
vertical: -4,
),
),
const Gap(8), const Gap(8),
Expanded(
child: AbsorbPointer(
absorbing: isRefreshing,
child: pathContent,
),
),
IconButton(
icon: Icon(
viewMode.value == FileListViewMode.list
? Symbols.view_module
: Symbols.list,
),
onPressed: () => viewMode.value =
viewMode.value == FileListViewMode.list
? FileListViewMode.waterfall
: FileListViewMode.list,
tooltip: viewMode.value == FileListViewMode.list
? 'Switch to Waterfall View'
: 'Switch to List View',
visualDensity: const VisualDensity(
horizontal: -4,
vertical: -4,
),
),
IconButton(
icon: Icon(
isSelectionMode.value
? Symbols.close
: Symbols.select_check_box,
),
onPressed: () =>
isSelectionMode.value = !isSelectionMode.value,
tooltip: isSelectionMode.value
? 'Exit Selection Mode'
: 'Enter Selection Mode',
visualDensity: const VisualDensity(
horizontal: -4,
vertical: -4,
),
),
if (mode.value == FileListMode.normal)
IconButton(
icon: const Icon(Symbols.create_new_folder),
onPressed: () =>
onShowCreateDirectory(ref.context, currentPath),
tooltip: 'Create Directory',
visualDensity: const VisualDensity(
horizontal: -4,
vertical: -4,
),
),
if (mode.value == FileListMode.unindexed)
IconButton(
icon: Icon(
recycled.value
? Symbols.delete_forever
: Symbols.restore_from_trash,
),
onPressed: () {
recycled.value = !recycled.value;
unindexedNotifier.setRecycled(recycled.value);
},
tooltip: recycled.value
? 'Show Active Files'
: 'Show Recycle Bin',
visualDensity: const VisualDensity(
horizontal: -4,
vertical: -4,
),
),
IconButton(
icon: const Icon(Symbols.upload_file),
onPressed: onPickAndUpload,
tooltip: 'Upload File',
visualDensity: const VisualDensity(
horizontal: -4,
vertical: -4,
),
),
],
),
),
).padding(horizontal: 8),
if (mode.value == FileListMode.unindexed && recycled.value) if (mode.value == FileListMode.unindexed && recycled.value)
_buildClearRecycledButton(ref).padding(horizontal: 8), _buildClearRecycledButton(ref).padding(horizontal: 8),
if (isRefreshing) if (isRefreshing)
@@ -409,8 +425,6 @@ class FileListView extends HookConsumerWidget {
minHeight: 4, minHeight: 4,
).padding(horizontal: 16, top: 6, bottom: 4), ).padding(horizontal: 16, top: 6, bottom: 4),
const Gap(8), const Gap(8),
if (mode.value == FileListMode.normal && currentPath.value == '/')
_buildUnindexedFilesEntry(ref).padding(bottom: 12),
Expanded( Expanded(
child: child:
CustomScrollView( CustomScrollView(
@@ -437,7 +451,7 @@ class FileListView extends HookConsumerWidget {
isSelectionMode.value = false; isSelectionMode.value = false;
selectedFileIds.value.clear(); selectedFileIds.value.clear();
}, },
child: const Text('Cancel'), child: Text('cancel').tr(),
), ),
const Gap(12), const Gap(12),
OutlinedButton( OutlinedButton(
@@ -464,7 +478,7 @@ class FileListView extends HookConsumerWidget {
}, },
child: Text( child: Text(
currentVisibleItems.value.isEmpty currentVisibleItems.value.isEmpty
? 'Select All' ? 'selectAll'.tr()
: currentVisibleItems.value : currentVisibleItems.value
.expand( .expand(
(item) => item.maybeMap( (item) => item.maybeMap(
@@ -476,21 +490,29 @@ class FileListView extends HookConsumerWidget {
.toSet() .toSet()
.difference(selectedFileIds.value) .difference(selectedFileIds.value)
.isEmpty .isEmpty
? 'Deselect All' ? 'deselectAll'.tr()
: 'Select All', : 'selectAll'.tr(),
), ),
), ),
const Spacer(), const Spacer(),
Text('${selectedFileIds.value.length} selected'), Text(
selectedFileIds.value.length == 1
? 'fileSelected'.tr(
args: [selectedFileIds.value.length.toString()],
)
: 'filesSelected'.tr(
args: [selectedFileIds.value.length.toString()],
),
),
const Spacer(), const Spacer(),
ElevatedButton.icon( ElevatedButton.icon(
icon: const Icon(Symbols.delete), icon: const Icon(Symbols.delete),
label: const Text('Delete'), label: Text('delete').tr(),
onPressed: selectedFileIds.value.isNotEmpty onPressed: selectedFileIds.value.isNotEmpty
? () async { ? () async {
final confirmed = await showConfirmAlert( final confirmed = await showConfirmAlert(
'Are you sure you want to delete the selected files?', 'confirmDeleteSelectedFiles'.tr(),
'Delete Selected Files', 'deleteSelectedFiles'.tr(),
isDanger: true, isDanger: true,
); );
if (!confirmed) return; if (!confirmed) return;
@@ -514,10 +536,14 @@ class FileListView extends HookConsumerWidget {
? indexedCloudFileListProvider ? indexedCloudFileListProvider
: unindexedFileListProvider, : unindexedFileListProvider,
); );
showSnackBar('Deleted $count files.'); showSnackBar(
'deletedFilesCount'.tr(
args: [count.toString()],
),
);
} catch (e) { } catch (e) {
showSnackBar( showSnackBar(
'Failed to delete selected files.', 'failedToDeleteSelectedFiles'.tr(),
); );
} finally { } finally {
if (context.mounted) { if (context.mounted) {
@@ -631,7 +657,7 @@ class FileListView extends HookConsumerWidget {
maxLines: 1, maxLines: 1,
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
), ),
subtitle: const Text('folder').tr(), subtitle: Text('folder').tr(),
onTap: () { onTap: () {
final newPath = currentPath.value == '/' final newPath = currentPath.value == '/'
? '/${folderItem.folderName}' ? '/${folderItem.folderName}'
@@ -649,35 +675,6 @@ class FileListView extends HookConsumerWidget {
}; };
} }
Widget _buildUnindexedFilesEntry(WidgetRef ref) {
return Container(
decoration: BoxDecoration(
border: Border.all(color: Theme.of(ref.context).colorScheme.outline),
borderRadius: const BorderRadius.all(Radius.circular(8)),
),
margin: const EdgeInsets.symmetric(horizontal: 12),
child: InkWell(
borderRadius: const BorderRadius.all(Radius.circular(8)),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row(
children: [
const Icon(Symbols.inventory_2).padding(horizontal: 8),
const Gap(8),
const Text('Unindexed Files').bold(),
const Spacer(),
const Icon(Symbols.chevron_right).padding(horizontal: 8),
],
),
),
onTap: () {
mode.value = FileListMode.unindexed;
currentPath.value = '/';
},
),
);
}
Widget _buildEmptyDirectoryHint( Widget _buildEmptyDirectoryHint(
WidgetRef ref, WidgetRef ref,
ValueNotifier<String> currentPath, ValueNotifier<String> currentPath,
@@ -694,24 +691,23 @@ class FileListView extends HookConsumerWidget {
const Icon(Symbols.folder_off, size: 64, color: Colors.grey), const Icon(Symbols.folder_off, size: 64, color: Colors.grey),
const Gap(16), const Gap(16),
Text( Text(
'This directory is empty', 'thisDirectoryIsEmpty',
style: TextStyle( style: TextStyle(
fontSize: 18, fontSize: 18,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
color: Theme.of(ref.context).textTheme.bodyLarge?.color, color: Theme.of(ref.context).textTheme.bodyLarge?.color,
), ),
), ).tr(),
const Gap(8), const Gap(8),
Text( Text(
'Upload files or create subdirectories to populate this path.\n' 'emptyDirectoryHint',
'Directories are created implicitly when you upload files to them.',
textAlign: TextAlign.center, textAlign: TextAlign.center,
style: TextStyle( style: TextStyle(
color: Theme.of( color: Theme.of(
ref.context, ref.context,
).textTheme.bodyMedium?.color?.withOpacity(0.7), ).textTheme.bodyMedium?.color?.withOpacity(0.7),
), ),
), ).tr(),
const Gap(16), const Gap(16),
SingleChildScrollView( SingleChildScrollView(
scrollDirection: Axis.horizontal, scrollDirection: Axis.horizontal,
@@ -721,14 +717,14 @@ class FileListView extends HookConsumerWidget {
ElevatedButton.icon( ElevatedButton.icon(
onPressed: onPickAndUpload, onPressed: onPickAndUpload,
icon: const Icon(Symbols.upload_file), icon: const Icon(Symbols.upload_file),
label: const Text('Upload Files'), label: Text('uploadFiles').tr(),
), ),
const Gap(12), const Gap(12),
OutlinedButton.icon( OutlinedButton.icon(
onPressed: () => onPressed: () =>
onShowCreateDirectory(ref.context, currentPath), onShowCreateDirectory(ref.context, currentPath),
icon: const Icon(Symbols.create_new_folder), icon: const Icon(Symbols.create_new_folder),
label: const Text('Create Directory'), label: Text('createDirectory').tr(),
), ),
], ],
), ),
@@ -1270,24 +1266,23 @@ class FileListView extends HookConsumerWidget {
const Icon(Symbols.inventory_2, size: 64, color: Colors.grey), const Icon(Symbols.inventory_2, size: 64, color: Colors.grey),
const Gap(16), const Gap(16),
Text( Text(
'No unindexed files', 'thisDirectoryIsEmpty',
style: TextStyle( style: TextStyle(
fontSize: 18, fontSize: 18,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
color: Theme.of(ref.context).textTheme.bodyLarge?.color, color: Theme.of(ref.context).textTheme.bodyLarge?.color,
), ),
), ).tr(),
const Gap(8), const Gap(8),
Text( Text(
'All files have been assigned to paths.\n' 'emptyDirectoryHint',
'Files without paths will appear here.',
textAlign: TextAlign.center, textAlign: TextAlign.center,
style: TextStyle( style: TextStyle(
color: Theme.of( color: Theme.of(
ref.context, ref.context,
).textTheme.bodyMedium?.color?.withOpacity(0.7), ).textTheme.bodyMedium?.color?.withOpacity(0.7),
), ),
), ).tr(),
], ],
), ),
), ),
@@ -1306,20 +1301,18 @@ class FileListView extends HookConsumerWidget {
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
const Text('Clear All Recycled Files').bold(), Text('clearAllRecycledFiles').tr().bold(),
const Text( Text('clearRecycledFilesDescription').tr().fontSize(13),
'Permanently delete all marked recycled files to free up space.',
).fontSize(13),
], ],
), ),
), ),
ElevatedButton.icon( ElevatedButton.icon(
icon: const Icon(Symbols.delete_forever), icon: const Icon(Symbols.delete_forever),
label: const Text('Clear'), label: Text('clear').tr(),
onPressed: () async { onPressed: () async {
final confirmed = await showConfirmAlert( final confirmed = await showConfirmAlert(
'Are you sure you want to clear all recycled files?', 'confirmClearRecycledFiles'.tr(),
'Clear Recycled Files', 'clearRecycledFiles'.tr(),
); );
if (!confirmed) return; if (!confirmed) return;
@@ -1332,10 +1325,12 @@ class FileListView extends HookConsumerWidget {
'/drive/files/me/recycle', '/drive/files/me/recycle',
); );
final count = response.data['count'] as int? ?? 0; final count = response.data['count'] as int? ?? 0;
showSnackBar('Cleared $count recycled files.'); showSnackBar(
'clearedRecycledFilesCount'.tr(args: [count.toString()]),
);
ref.invalidate(unindexedFileListProvider); ref.invalidate(unindexedFileListProvider);
} catch (e) { } catch (e) {
showSnackBar('Failed to clear recycled files.'); showSnackBar('failedToClearRecycledFiles'.tr());
} finally { } finally {
if (ref.context.mounted) { if (ref.context.mounted) {
hideLoadingModal(ref.context); hideLoadingModal(ref.context);
@@ -1349,7 +1344,7 @@ class FileListView extends HookConsumerWidget {
); );
} }
Widget _buildGlobalFilters( Widget _buildChipFilters(
WidgetRef ref, WidgetRef ref,
AsyncValue<List<SnFilePool>> poolsAsync, AsyncValue<List<SnFilePool>> poolsAsync,
ValueNotifier<SnFilePool?> selectedPool, ValueNotifier<SnFilePool?> selectedPool,
@@ -1363,27 +1358,58 @@ class FileListView extends HookConsumerWidget {
ValueNotifier<bool> orderDesc, ValueNotifier<bool> orderDesc,
ObjectRef<Timer?> queryDebounceTimer, ObjectRef<Timer?> queryDebounceTimer,
) { ) {
final poolDropdownItems = poolsAsync.when( return SingleChildScrollView(
data: (pools) => [ padding: const EdgeInsets.symmetric(horizontal: 16),
const DropdownMenuItem<SnFilePool>( scrollDirection: Axis.horizontal,
child: Row(
children: [
// Pool filter dropdown
Container(
height: 32,
padding: const EdgeInsets.symmetric(horizontal: 8),
decoration: BoxDecoration(
border: Border.all(
color: Theme.of(
ref.context,
).colorScheme.outline.withOpacity(0.5),
),
borderRadius: BorderRadius.circular(8),
),
child: DropdownButtonHideUnderline(
child: DropdownButton<SnFilePool>(
value: selectedPool.value,
items: [
DropdownMenuItem<SnFilePool>(
value: null, value: null,
child: Text('All Pools', style: TextStyle(fontSize: 14)), child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Symbols.database, size: 16),
Gap(6),
Text('allFiles', style: TextStyle(fontSize: 12)).tr(),
],
), ),
...pools.map(
(p) => DropdownMenuItem<SnFilePool>(
value: p,
child: Text(p.name, style: const TextStyle(fontSize: 14)),
), ),
...poolsAsync.maybeWhen(
data: (pools) => pools.map(
(pool) => DropdownMenuItem<SnFilePool>(
value: pool,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Symbols.database, size: 16),
Gap(6),
Text(
pool.name,
style: const TextStyle(fontSize: 12),
),
],
),
),
),
orElse: () => <DropdownMenuItem<SnFilePool>>[],
), ),
], ],
loading: () => const <DropdownMenuItem<SnFilePool>>[],
error: (err, stack) => const <DropdownMenuItem<SnFilePool>>[],
);
final poolDropdown = DropdownButtonHideUnderline(
child: DropdownButton2<SnFilePool>(
value: selectedPool.value,
items: poolDropdownItems,
onChanged: isRefreshing onChanged: isRefreshing
? null ? null
: (value) { : (value) {
@@ -1394,116 +1420,94 @@ class FileListView extends HookConsumerWidget {
cloudNotifier.setPool(value?.id); cloudNotifier.setPool(value?.id);
} }
}, },
customButton: Container( icon: const Icon(Symbols.arrow_drop_down, size: 16),
height: 28,
width: 200,
decoration: BoxDecoration(
border: Border.all(
color: Theme.of(ref.context).colorScheme.outline,
),
borderRadius: const BorderRadius.all(Radius.circular(8)),
),
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
spacing: 6,
children: [
const Icon(Symbols.pool, size: 16),
Flexible(
child: Text(
selectedPool.value?.name ?? 'All files',
maxLines: 1,
overflow: TextOverflow.ellipsis,
).fontSize(12),
),
],
).height(24),
),
buttonStyleData: const ButtonStyleData(
padding: EdgeInsets.zero,
height: 28,
width: 200,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(8)),
),
),
dropdownStyleData: const DropdownStyleData(maxHeight: 200),
),
);
final queryField = SizedBox(
width: 200,
height: 28,
child: TextField(
decoration: InputDecoration(
hintText: 'fileName'.tr(),
isDense: true, isDense: true,
contentPadding: const EdgeInsets.symmetric(
vertical: 12,
horizontal: 6,
), ),
border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
), ),
style: const TextStyle(fontSize: 13, height: 1),
onChanged: (value) {
queryDebounceTimer.value?.cancel();
queryDebounceTimer.value = Timer(
const Duration(milliseconds: 300),
() {
query.value = value.isEmpty ? null : value;
},
);
},
), ),
);
final orderDropdown = DropdownButtonHideUnderline( const Gap(8),
child: DropdownButton2<String>(
value: order.value, // Order filter dropdown
items: ['date', 'size', 'name'] Container(
.map( height: 32,
(e) => DropdownMenuItem( padding: const EdgeInsets.symmetric(horizontal: 8),
value: e,
child: Text(
e == 'date' ? e : 'file${e.capitalizeEachWord()}',
style: const TextStyle(fontSize: 14),
).tr(),
),
)
.toList(),
onChanged: (value) => order.value = value,
customButton: Container(
height: 28,
width: 80,
decoration: BoxDecoration( decoration: BoxDecoration(
border: Border.all( border: Border.all(
color: Theme.of(ref.context).colorScheme.outline, color: Theme.of(
ref.context,
).colorScheme.outline.withOpacity(0.5),
), ),
borderRadius: BorderRadius.circular(8), borderRadius: BorderRadius.circular(8),
), ),
child: Center( child: DropdownButtonHideUnderline(
child: Text( child: DropdownButton<String>(
(order.value ?? 'date') == 'date' value: order.value ?? 'date',
? (order.value ?? 'date') items: [
: 'file${order.value?.capitalizeEachWord()}', DropdownMenuItem<String>(
value: 'date',
child: Row(
spacing: 6,
mainAxisSize: MainAxisSize.min,
children: [
Icon(Symbols.schedule, size: 16),
Text('date', style: const TextStyle(fontSize: 12)).tr(),
if (order.value == 'date')
Icon(
orderDesc.value
? Symbols.arrow_downward
: Symbols.arrow_upward,
size: 14,
),
],
),
),
DropdownMenuItem<String>(
value: 'size',
child: Row(
spacing: 6,
mainAxisSize: MainAxisSize.min,
children: [
Icon(Symbols.data_usage, size: 16),
Text(
'fileSize'.tr(),
style: const TextStyle(fontSize: 12), style: const TextStyle(fontSize: 12),
).tr(), ),
if (order.value == 'size')
Icon(
orderDesc.value
? Symbols.arrow_downward
: Symbols.arrow_upward,
size: 16,
),
],
), ),
), ),
buttonStyleData: const ButtonStyleData( DropdownMenuItem<String>(
height: 28, value: 'name',
width: 80, child: Row(
padding: EdgeInsets.zero, mainAxisSize: MainAxisSize.min,
spacing: 6,
children: [
Icon(Symbols.sort_by_alpha, size: 16),
Text(
'fileName'.tr(),
style: const TextStyle(fontSize: 12),
), ),
dropdownStyleData: const DropdownStyleData(maxHeight: 200), if (order.value == 'name')
Icon(
orderDesc.value
? Symbols.arrow_downward
: Symbols.arrow_upward,
size: 16,
), ),
); ],
final orderDescToggle = IconButton(
icon: Icon(
orderDesc.value ? Symbols.arrow_upward : Symbols.arrow_downward,
), ),
onPressed: () { ),
],
onChanged: (value) {
if (value == order.value) {
// Toggle direction if same option selected
final newValue = !orderDesc.value; final newValue = !orderDesc.value;
orderDesc.value = newValue; orderDesc.value = newValue;
if (mode.value == FileListMode.unindexed) { if (mode.value == FileListMode.unindexed) {
@@ -1511,39 +1515,47 @@ class FileListView extends HookConsumerWidget {
} else { } else {
cloudNotifier.setOrderDesc(newValue); cloudNotifier.setOrderDesc(newValue);
} }
} else {
// Change sort option
order.value = value;
if (mode.value == FileListMode.unindexed) {
unindexedNotifier.setOrder(value);
} else {
cloudNotifier.setOrder(value);
}
}
}, },
tooltip: orderDesc.value ? 'descendingOrder'.tr() : 'ascendingOrder'.tr(), icon: const SizedBox.shrink(),
visualDensity: const VisualDensity(horizontal: -4, vertical: -4), isDense: true,
); ),
),
),
final refreshButton = IconButton( const Gap(8),
icon: const Icon(Symbols.refresh),
onPressed: () { // Refresh chip
FilterChip(
label: Row(
mainAxisSize: MainAxisSize.min,
spacing: 6,
children: [
Icon(Symbols.refresh, size: 16),
Text('refresh', style: TextStyle(fontSize: 12)).tr(),
],
),
selected: false,
onSelected: (selected) {
if (selected) {
if (mode.value == FileListMode.unindexed) { if (mode.value == FileListMode.unindexed) {
ref.invalidate(unindexedFileListProvider); ref.invalidate(unindexedFileListProvider);
} else { } else {
cloudNotifier.setPath(currentPath.value); cloudNotifier.setPath(currentPath.value);
} }
}
}, },
tooltip: 'Refresh',
visualDensity: const VisualDensity(horizontal: -4, vertical: -4),
);
return Card(
margin: EdgeInsets.zero,
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
spacing: 12,
children: [
poolDropdown,
queryField,
orderDropdown,
orderDescToggle,
refreshButton,
],
).padding(horizontal: 20, vertical: 8),
), ),
).padding(horizontal: 12); ],
),
);
} }
} }

View File

@@ -0,0 +1,150 @@
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/pods/notification.dart';
import 'package:island/route.dart';
import 'package:island/widgets/content/cloud_files.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart';
import 'package:styled_widget/styled_widget.dart';
import 'package:url_launcher/url_launcher_string.dart';
const double kNotificationBorderRadius = 8;
class NotificationItemWidget extends HookConsumerWidget {
final NotificationItem item;
final VoidCallback onDismiss;
final bool isDesktop;
final Animation<double> progress;
const NotificationItemWidget({
super.key,
required this.item,
required this.onDismiss,
required this.isDesktop,
required this.progress,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
return GestureDetector(
onTap: () {
if (item.notification.meta['action_uri'] != null) {
var uri = item.notification.meta['action_uri'] as String;
if (uri.startsWith('solian://')) {
uri = uri.replaceFirst('solian://', '');
}
if (uri.startsWith('/')) {
rootNavigatorKey.currentContext?.push(
item.notification.meta['action_uri'],
);
} else {
launchUrlString(uri);
}
}
},
onHorizontalDragEnd: (details) {
if (details.primaryVelocity! > 100) {
onDismiss();
}
},
onVerticalDragEnd: !isDesktop
? (details) {
if (details.primaryVelocity! < -100) {
onDismiss();
}
}
: null,
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: double.infinity),
child: Stack(
children: [
Card(
elevation: 4,
margin: EdgeInsets.zero,
color: Theme.of(context).colorScheme.surfaceContainerHigh,
shape: RoundedRectangleBorder(
borderRadius: const BorderRadius.all(
Radius.circular(kNotificationBorderRadius),
),
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.all(12),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
if (item.notification.meta['pfp'] != null)
ProfilePictureWidget(
fileId: item.notification.meta['pfp'],
radius: 12,
).padding(right: 12, top: 2)
else
Icon(
Symbols.info,
color: Theme.of(context).colorScheme.primary,
size: 24,
).padding(right: 12),
Flexible(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
item.notification.title,
style: Theme.of(context).textTheme.titleMedium
?.copyWith(fontWeight: FontWeight.bold),
),
if (item.notification.content.isNotEmpty)
Text(
item.notification.content,
style: Theme.of(context).textTheme.bodyMedium,
),
if (item.notification.subtitle.isNotEmpty)
Text(
item.notification.subtitle,
style: Theme.of(context).textTheme.bodySmall,
),
],
),
),
],
),
),
AnimatedBuilder(
animation: progress,
builder: (context, child) => LinearProgressIndicator(
value: progress.value,
minHeight: 2,
backgroundColor: Colors.transparent,
valueColor: AlwaysStoppedAnimation<Color>(
Theme.of(context).colorScheme.primary.withOpacity(0.5),
),
),
),
],
),
),
Positioned(
top: 4,
right: 4,
child: IconButton(
icon: Icon(
Symbols.close,
size: 20,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
onPressed: onDismiss,
padding: const EdgeInsets.all(4),
constraints: const BoxConstraints(),
),
),
],
).clipRRect(all: kNotificationBorderRadius),
),
);
}
}

View File

@@ -0,0 +1,177 @@
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/pods/notification.dart';
import 'package:island/services/responsive.dart';
import 'package:island/widgets/notification_item.dart';
import 'package:styled_widget/styled_widget.dart';
class NotificationOverlay extends HookConsumerWidget {
const NotificationOverlay({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final notifications = ref.watch(notificationStateProvider);
final isDesktop = isWideScreen(context);
final devicePadding = MediaQuery.paddingOf(context);
final topOffset =
devicePadding.top +
((!kIsWeb &&
(Platform.isMacOS || Platform.isLinux || Platform.isWindows))
? 40
: 16);
if (notifications.isEmpty) {
return const SizedBox.shrink();
}
final itemWidth = isDesktop ? 420.0 : MediaQuery.sizeOf(context).width;
if (isDesktop) {
return Positioned(
top: topOffset,
left: 0,
right: 0,
child: Material(
color: Colors.transparent,
child: Column(
spacing: 8,
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: notifications.asMap().entries.map((entry) {
final item = entry.value;
return AnimatedNotificationItem(
key: Key(item.id),
item: item,
isDesktop: true,
margin: EdgeInsets.symmetric(horizontal: 16),
onDismiss: () {
ref.read(notificationStateProvider.notifier).dismiss(item.id);
},
);
}).toList(),
),
).width(itemWidth).alignment(Alignment.topRight),
);
} else {
// Non-desktop: use Stack with overlapping
const double overlap = 20.0;
return Positioned(
top: topOffset,
left: 0,
right: 0,
child: Material(
color: Colors.transparent,
child: SizedBox(
height: MediaQuery.sizeOf(context).height,
child: Stack(
alignment: Alignment.topCenter,
children: notifications.asMap().entries.map((entry) {
final index = entry.key;
final item = entry.value;
return Positioned(
top: index * overlap,
left: 16,
right: 16,
child: Container(
decoration: BoxDecoration(
boxShadow: [
BoxShadow(color: Colors.black54, blurRadius: 4.0 + index * 2.0),
],
),
child: AnimatedNotificationItem(
key: Key(item.id),
item: item,
isDesktop: false,
onDismiss: () {
ref
.read(notificationStateProvider.notifier)
.dismiss(item.id);
},
),
),
);
}).toList(),
),
),
).width(itemWidth).alignment(Alignment.topCenter),
);
}
}
}
class AnimatedNotificationItem extends HookConsumerWidget {
final NotificationItem item;
final VoidCallback onDismiss;
final bool isDesktop;
final EdgeInsets? margin;
const AnimatedNotificationItem({
super.key,
required this.item,
required this.onDismiss,
required this.isDesktop,
this.margin,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
final animationController = useAnimationController(
duration: const Duration(milliseconds: 300),
reverseDuration: const Duration(milliseconds: 250),
);
final progressController = useAnimationController(duration: item.duration);
final curvedAnimation = CurvedAnimation(
parent: animationController,
curve: Curves.easeOutCubic,
);
final slideTween = Tween<Offset>(
begin: isDesktop ? Offset(1.0, 0.0) : Offset(0.0, -1.0),
end: Offset.zero,
);
final progressAnimation = Tween<double>(
begin: 1.0,
end: 0.0,
).animate(progressController);
useEffect(() {
animationController.forward();
progressController.forward();
return null;
}, []);
useEffect(() {
if (item.dismissed) {
animationController.reverse().then((_) {
ref.read(notificationStateProvider.notifier).remove(item.id);
});
}
return null;
}, [item.dismissed]);
return SlideTransition(
position: slideTween.animate(curvedAnimation),
child: SizeTransition(
sizeFactor: curvedAnimation,
axis: Axis.vertical,
child: Padding(
padding: margin ?? EdgeInsets.zero,
child: NotificationItemWidget(
item: item,
isDesktop: isDesktop,
onDismiss: onDismiss,
progress: progressAnimation,
),
),
),
);
}
}

View File

@@ -0,0 +1,127 @@
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart';
enum SidebarPanelType { attachments, settings }
class ArticleSidebarPanelWidget extends HookConsumerWidget {
final Widget attachmentsContent;
final Widget settingsContent;
final VoidCallback onClose;
final bool isWide;
final double width;
const ArticleSidebarPanelWidget({
super.key,
required this.attachmentsContent,
required this.settingsContent,
required this.onClose,
required this.isWide,
this.width = 480,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final activePanel = useState<SidebarPanelType>(
SidebarPanelType.attachments,
);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_buildHeader(context, activePanel, colorScheme, onClose, theme),
const Divider(height: 1),
Expanded(
child: AnimatedSwitcher(
duration: const Duration(milliseconds: 200),
switchInCurve: Curves.easeOutCubic,
switchOutCurve: Curves.easeInCubic,
child: activePanel.value == SidebarPanelType.attachments
? Container(
key: const ValueKey(SidebarPanelType.attachments),
alignment: Alignment.topCenter,
child: attachmentsContent,
)
: Container(
key: const ValueKey(SidebarPanelType.settings),
alignment: Alignment.topCenter,
child: settingsContent,
),
),
),
],
);
}
Widget _buildHeader(
BuildContext context,
ValueNotifier<SidebarPanelType> activePanel,
ColorScheme colorScheme,
VoidCallback onClose,
ThemeData theme,
) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row(
children: [
_buildSegmentedTabs(activePanel, colorScheme, theme),
const Spacer(),
if (!isWide)
IconButton(
icon: const Icon(Symbols.close),
onPressed: onClose,
tooltip: 'close'.tr(),
padding: const EdgeInsets.all(8),
constraints: const BoxConstraints(minWidth: 40, minHeight: 40),
),
],
),
);
}
Widget _buildSegmentedTabs(
ValueNotifier<SidebarPanelType> activePanel,
ColorScheme colorScheme,
ThemeData theme,
) {
return SegmentedButton<SidebarPanelType>(
segments: [
ButtonSegment(
value: SidebarPanelType.attachments,
label: Text('attachments'.tr()),
icon: const Icon(Symbols.attach_file, size: 18),
),
ButtonSegment(
value: SidebarPanelType.settings,
label: Text('settings'.tr()),
icon: const Icon(Symbols.settings, size: 18),
),
],
selected: {activePanel.value},
onSelectionChanged: (Set<SidebarPanelType> selected) {
if (selected.isNotEmpty) {
activePanel.value = selected.first;
}
},
style: ButtonStyle(
backgroundColor: WidgetStateProperty.resolveWith((states) {
if (states.contains(WidgetState.selected)) {
return colorScheme.secondaryContainer;
}
return colorScheme.surfaceContainerHighest;
}),
foregroundColor: WidgetStateProperty.resolveWith((states) {
if (states.contains(WidgetState.selected)) {
return colorScheme.onSecondaryContainer;
}
return colorScheme.onSurface;
}),
),
);
}
}

View File

@@ -1,10 +1,15 @@
import 'package:desktop_drop/desktop_drop.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/models/file.dart'; import 'package:island/models/file.dart';
import 'package:island/services/responsive.dart'; import 'package:island/services/responsive.dart';
import 'package:island/services/file_uploader.dart';
import 'package:island/widgets/attachment_uploader.dart'; import 'package:island/widgets/attachment_uploader.dart';
import 'package:island/widgets/content/attachment_preview.dart'; import 'package:island/widgets/content/attachment_preview.dart';
import 'package:island/widgets/post/compose_shared.dart'; import 'package:island/widgets/post/compose_shared.dart';
import 'package:material_symbols_icons/symbols.dart';
/// A reusable widget for displaying attachments in compose screens. /// A reusable widget for displaying attachments in compose screens.
/// Supports both grid and list layouts based on screen width. /// Supports both grid and list layouts based on screen width.
@@ -71,13 +76,13 @@ class ComposeAttachments extends ConsumerWidget {
isCompact: isCompact, isCompact: isCompact,
item: state.attachments.value[idx], item: state.attachments.value[idx],
progress: progressMap[idx], progress: progressMap[idx],
isUploading: progressMap.containsKey(idx),
onRequestUpload: () async { onRequestUpload: () async {
final config = await showModalBottomSheet<AttachmentUploadConfig>( final config = await showModalBottomSheet<AttachmentUploadConfig>(
context: ref.context, context: ref.context,
isScrollControlled: true, isScrollControlled: true,
useRootNavigator: true, useRootNavigator: true,
builder: builder: (context) =>
(context) =>
AttachmentUploaderSheet(ref: ref, state: state, index: idx), AttachmentUploaderSheet(ref: ref, state: state, index: idx),
); );
if (config != null) { if (config != null) {
@@ -102,36 +107,125 @@ class ComposeAttachments extends ConsumerWidget {
} }
} }
/// A specialized attachment widget for article compose with expansion tile. class ArticleComposeAttachments extends HookConsumerWidget {
class ArticleComposeAttachments extends ConsumerWidget {
final ComposeState state; final ComposeState state;
final EdgeInsets? padding;
const ArticleComposeAttachments({super.key, required this.state}); const ArticleComposeAttachments({
super.key,
required this.state,
this.padding,
});
Future<void> _handleDroppedFiles(DropDoneDetails details, ComposeState state) async {
final newFiles = <UniversalFile>[];
for (final xfile in details.files) {
// Create UniversalFile with default type first
final uf = UniversalFile(data: xfile, type: UniversalFileType.file);
// Use FileUploader.getMimeType to get proper MIME type
final mimeType = FileUploader.getMimeType(uf);
final fileType = switch (mimeType.split('/').firstOrNull) {
'image' => UniversalFileType.image,
'video' => UniversalFileType.video,
'audio' => UniversalFileType.audio,
_ => UniversalFileType.file,
};
// Update the file type
final correctedUf = UniversalFile(data: xfile, type: fileType);
newFiles.add(correctedUf);
}
if (newFiles.isNotEmpty) {
state.attachments.value = [...state.attachments.value, ...newFiles];
}
}
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
return Padding(
padding: padding ?? EdgeInsets.all(16),
child: ValueListenableBuilder<String?>(
valueListenable: state.thumbnailId,
builder: (context, thumbnailId, _) {
return ValueListenableBuilder<List<UniversalFile>>( return ValueListenableBuilder<List<UniversalFile>>(
valueListenable: state.attachments, valueListenable: state.attachments,
builder: (context, attachments, _) { builder: (context, attachments, _) {
if (attachments.isEmpty) return const SizedBox.shrink(); return HookBuilder(
return Theme( builder: (context) {
data: Theme.of(context).copyWith(dividerColor: Colors.transparent), final isDragging = useState(false);
child: ExpansionTile( return DropTarget(
initiallyExpanded: true, onDragDone: (details) async =>
title: Column( await _handleDroppedFiles(details, state),
crossAxisAlignment: CrossAxisAlignment.start, onDragEntered: (details) => isDragging.value = true,
onDragExited: (details) => isDragging.value = false,
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
curve: Curves.easeOut,
decoration: isDragging.value ? BoxDecoration(
border: Border.all(
color: Theme.of(context).colorScheme.primary,
width: 2,
),
borderRadius: BorderRadius.circular(12),
) : null,
child: Padding(
padding: isDragging.value ? const EdgeInsets.all(8) : EdgeInsets.zero,
child: attachments.isEmpty
? AnimatedContainer(
duration: const Duration(milliseconds: 200),
curve: Curves.easeOut,
width: double.infinity,
height: 200,
decoration: BoxDecoration(
color: Theme.of(context)
.colorScheme
.surfaceContainerHighest
.withOpacity(0.3),
border: Border.all(
color: Theme.of(
context,
).colorScheme.outline.withOpacity(0.5),
width: 1,
),
borderRadius: BorderRadius.circular(12),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
Text('attachments'), Icon(
Symbols.upload,
size: 48,
color: Theme.of(
context,
).colorScheme.onSurfaceVariant,
),
const SizedBox(height: 16),
Text( Text(
'articleAttachmentHint', 'dropFilesHere',
style: Theme.of(context).textTheme.bodySmall?.copyWith( style: Theme.of(context).textTheme.titleMedium
color: Theme.of(context).colorScheme.onSurfaceVariant, ?.copyWith(
color: Theme.of(
context,
).colorScheme.onSurfaceVariant,
), ),
).tr(),
const SizedBox(height: 8),
Text(
'dragAndDropToAttach',
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: Theme.of(context)
.colorScheme
.onSurfaceVariant
.withOpacity(0.7),
), ),
).tr(),
], ],
), ),
children: [ )
ValueListenableBuilder<Map<int, double?>>( : ValueListenableBuilder<Map<int, double?>>(
valueListenable: state.attachmentProgress, valueListenable: state.attachmentProgress,
builder: (context, progressMap, _) { builder: (context, progressMap, _) {
return Wrap( return Wrap(
@@ -139,21 +233,23 @@ class ArticleComposeAttachments extends ConsumerWidget {
spacing: 8, spacing: 8,
children: [ children: [
for (var idx = 0; idx < attachments.length; idx++) for (var idx = 0; idx < attachments.length; idx++)
SizedBox( _AnimatedAttachmentItem(
width: 180, index: idx,
height: 180,
child: AttachmentPreview(
isCompact: true,
item: attachments[idx], item: attachments[idx],
progress: progressMap[idx], progress: progressMap[idx],
isUploading: progressMap.containsKey(idx),
thumbnailId: thumbnailId,
onSetThumbnail: (id) =>
ComposeLogic.setThumbnail(state, id),
onRequestUpload: () async { onRequestUpload: () async {
final config = await showModalBottomSheet< final config =
await showModalBottomSheet<
AttachmentUploadConfig AttachmentUploadConfig
>( >(
context: context, context: context,
isScrollControlled: true, isScrollControlled: true,
builder: useRootNavigator: true,
(context) => AttachmentUploaderSheet( builder: (context) => AttachmentUploaderSheet(
ref: ref, ref: ref,
state: state, state: state,
index: idx, index: idx,
@@ -168,35 +264,99 @@ class ArticleComposeAttachments extends ConsumerWidget {
); );
} }
}, },
onUpdate: onUpdate: (value) =>
(value) => ComposeLogic.updateAttachment( ComposeLogic.updateAttachment(state, value, idx),
state, onDelete: () =>
value, ComposeLogic.deleteAttachment(ref, state, idx),
idx, onInsert: () =>
), ComposeLogic.insertAttachment(ref, state, idx),
onDelete:
() => ComposeLogic.deleteAttachment(
ref,
state,
idx,
),
onInsert:
() => ComposeLogic.insertAttachment(
ref,
state,
idx,
),
),
), ),
], ],
); );
}, },
), ),
const SizedBox(height: 16), ),
],
), ),
); );
}, },
); );
},
);
},
),
);
}
}
class _AnimatedAttachmentItem extends HookWidget {
final int index;
final UniversalFile item;
final double? progress;
final bool isUploading;
final String? thumbnailId;
final Function(String?) onSetThumbnail;
final VoidCallback onRequestUpload;
final Function(UniversalFile) onUpdate;
final VoidCallback onDelete;
final VoidCallback onInsert;
const _AnimatedAttachmentItem({
required this.index,
required this.item,
required this.progress,
required this.isUploading,
required this.thumbnailId,
required this.onSetThumbnail,
required this.onRequestUpload,
required this.onUpdate,
required this.onDelete,
required this.onInsert,
});
@override
Widget build(BuildContext context) {
final animationController = useAnimationController(
duration: const Duration(milliseconds: 300),
);
final fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
CurvedAnimation(parent: animationController, curve: Curves.easeOut),
);
final slideAnimation =
Tween<Offset>(begin: const Offset(0, 0.1), end: Offset.zero).animate(
CurvedAnimation(
parent: animationController,
curve: Curves.easeOutCubic,
),
);
useEffect(() {
final delay = Duration(milliseconds: 50 * index);
Future.delayed(delay, () {
animationController.forward();
});
return null;
}, [index]);
return FadeTransition(
opacity: fadeAnimation,
child: SlideTransition(
position: slideAnimation,
child: AttachmentPreview(
isCompact: true,
item: item,
progress: progress,
isUploading: isUploading,
thumbnailId: thumbnailId,
onSetThumbnail: onSetThumbnail,
onRequestUpload: onRequestUpload,
onUpdate: onUpdate,
onDelete: onDelete,
onInsert: onInsert,
bordered: true,
),
),
);
} }
} }

View File

@@ -121,8 +121,7 @@ class PostComposeCard extends HookConsumerWidget {
content: composeState.contentController.text, content: composeState.contentController.text,
visibility: composeState.visibility.value, visibility: composeState.visibility.value,
type: composeState.postType, type: composeState.postType,
attachments: attachments: composeState.attachments.value
composeState.attachments.value
.where((e) => e.isOnCloud) .where((e) => e.isOnCloud)
.map((e) => e.data as SnCloudFile) .map((e) => e.data as SnCloudFile)
.toList(), .toList(),
@@ -221,8 +220,7 @@ class PostComposeCard extends HookConsumerWidget {
composeState.currentPublisher.value == null) composeState.currentPublisher.value == null)
? null ? null
: performSubmit, : performSubmit,
icon: icon: composeState.submitting.value
composeState.submitting.value
? SizedBox( ? SizedBox(
width: 24, width: 24,
height: 24, height: 24,
@@ -235,8 +233,7 @@ class PostComposeCard extends HookConsumerWidget {
? Symbols.edit ? Symbols.edit
: Symbols.upload, : Symbols.upload,
), ),
tooltip: tooltip: originalPost != null
originalPost != null
? 'postUpdate'.tr() ? 'postUpdate'.tr()
: 'postPublish'.tr(), : 'postPublish'.tr(),
visualDensity: const VisualDensity( visualDensity: const VisualDensity(
@@ -268,12 +265,9 @@ class PostComposeCard extends HookConsumerWidget {
context: context, context: context,
isScrollControlled: true, isScrollControlled: true,
useRootNavigator: true, useRootNavigator: true,
builder: builder: (context) => SheetScaffold(
(context) => SheetScaffold(
titleText: 'Post Preview', titleText: 'Post Preview',
child: SingleChildScrollView( child: SingleChildScrollView(child: PostItem(item: post)),
child: PostItem(item: post),
),
), ),
); );
}, },
@@ -283,8 +277,7 @@ class PostComposeCard extends HookConsumerWidget {
Expanded( Expanded(
child: KeyboardListener( child: KeyboardListener(
focusNode: FocusNode(), focusNode: FocusNode(),
onKeyEvent: onKeyEvent: (event) => ComposeLogic.handleKeyPress(
(event) => ComposeLogic.handleKeyPress(
event, event,
composeState, composeState,
ref, ref,
@@ -304,8 +297,7 @@ class PostComposeCard extends HookConsumerWidget {
// Publisher profile picture // Publisher profile picture
GestureDetector( GestureDetector(
child: ProfilePictureWidget( child: ProfilePictureWidget(
fileId: fileId: composeState
composeState
.currentPublisher .currentPublisher
.value .value
?.picture ?.picture
@@ -326,8 +318,8 @@ class PostComposeCard extends HookConsumerWidget {
context: context, context: context,
isScrollControlled: true, isScrollControlled: true,
useRootNavigator: true, useRootNavigator: true,
builder: builder: (context) =>
(context) => const NewPublisherScreen(), const NewPublisherScreen(),
).then((value) { ).then((value) {
if (value != null) { if (value != null) {
composeState.currentPublisher.value = composeState.currentPublisher.value =
@@ -370,8 +362,7 @@ class PostComposeCard extends HookConsumerWidget {
context: context, context: context,
isScrollControlled: true, isScrollControlled: true,
useRootNavigator: true, useRootNavigator: true,
builder: builder: (context) =>
(context) =>
const NewPublisherScreen(), const NewPublisherScreen(),
).then((value) { ).then((value) {
if (value != null) { if (value != null) {
@@ -388,8 +379,8 @@ class PostComposeCard extends HookConsumerWidget {
isScrollControlled: true, isScrollControlled: true,
useRootNavigator: true, useRootNavigator: true,
context: context, context: context,
builder: builder: (context) =>
(context) => const PublisherModal(), const PublisherModal(),
).then((value) { ).then((value) {
if (value != null) { if (value != null) {
composeState.currentPublisher.value = composeState.currentPublisher.value =
@@ -415,9 +406,7 @@ class PostComposeCard extends HookConsumerWidget {
), ),
// Bottom toolbar // Bottom toolbar
SizedBox( ClipRRect(
height: 65,
child: ClipRRect(
borderRadius: const BorderRadius.only( borderRadius: const BorderRadius.only(
bottomLeft: Radius.circular(8), bottomLeft: Radius.circular(8),
bottomRight: Radius.circular(8), bottomRight: Radius.circular(8),
@@ -425,11 +414,9 @@ class PostComposeCard extends HookConsumerWidget {
child: ComposeToolbar( child: ComposeToolbar(
state: composeState, state: composeState,
originalPost: originalPost, originalPost: originalPost,
isCompact: true,
useSafeArea: isContained, useSafeArea: isContained,
), ),
), ),
),
], ],
), ),
), ),

View File

@@ -139,10 +139,7 @@ class ComposeSettingsSheet extends HookConsumerWidget {
final tagInputController = useTextEditingController(); final tagInputController = useTextEditingController();
return SheetScaffold( return SingleChildScrollView(
titleText: 'postSettings'.tr(),
heightFactor: 0.6,
child: SingleChildScrollView(
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
@@ -162,8 +159,7 @@ class ComposeSettingsSheet extends HookConsumerWidget {
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
), ),
), ),
onTapOutside: (_) => onTapOutside: (_) => FocusManager.instance.primaryFocus?.unfocus(),
FocusManager.instance.primaryFocus?.unfocus(),
), ),
// Tags field // Tags field
@@ -205,9 +201,7 @@ class ComposeSettingsSheet extends HookConsumerWidget {
Text( Text(
'#$tag', '#$tag',
style: TextStyle( style: TextStyle(
color: Theme.of( color: Theme.of(context).colorScheme.onPrimary,
context,
).colorScheme.onPrimary,
fontSize: 14, fontSize: 14,
), ),
), ),
@@ -222,9 +216,7 @@ class ComposeSettingsSheet extends HookConsumerWidget {
child: Icon( child: Icon(
Icons.close, Icons.close,
size: 16, size: 16,
color: Theme.of( color: Theme.of(context).colorScheme.onPrimary,
context,
).colorScheme.onPrimary,
), ),
), ),
], ],
@@ -265,10 +257,7 @@ class ComposeSettingsSheet extends HookConsumerWidget {
}, },
onSelected: (suggestion) { onSelected: (suggestion) {
if (!state.tags.value.contains(suggestion.slug)) { if (!state.tags.value.contains(suggestion.slug)) {
state.tags.value = [ state.tags.value = [...state.tags.value, suggestion.slug];
...state.tags.value,
suggestion.slug,
];
} }
tagInputController.clear(); tagInputController.clear();
}, },
@@ -404,9 +393,7 @@ class ComposeSettingsSheet extends HookConsumerWidget {
), ),
// Include current realm if it's not null and not in joined realms // Include current realm if it's not null and not in joined realms
if (currentRealm != null && if (currentRealm != null &&
!(userRealms.value ?? []).any( !(userRealms.value ?? []).any((r) => r.id == currentRealm.id))
(r) => r.id == currentRealm.id,
))
DropdownMenuItem<SnRealm?>( DropdownMenuItem<SnRealm?>(
value: currentRealm, value: currentRealm,
child: Row( child: Row(
@@ -497,7 +484,6 @@ class ComposeSettingsSheet extends HookConsumerWidget {
), ),
], ],
), ),
),
); );
} }
} }

View File

@@ -27,6 +27,7 @@ import 'package:island/widgets/post/compose_recorder.dart';
import 'package:island/pods/drive/file_pool.dart'; import 'package:island/pods/drive/file_pool.dart';
import 'package:pasteboard/pasteboard.dart'; import 'package:pasteboard/pasteboard.dart';
import 'package:island/talker.dart'; import 'package:island/talker.dart';
import 'package:island/services/analytics_service.dart';
class ComposeState { class ComposeState {
final TextEditingController titleController; final TextEditingController titleController;
@@ -48,6 +49,8 @@ class ComposeState {
final ValueNotifier<String?> pollId; final ValueNotifier<String?> pollId;
// Linked fund id for this compose session (nullable) // Linked fund id for this compose session (nullable)
final ValueNotifier<String?> fundId; final ValueNotifier<String?> fundId;
// Thumbnail id for article type post (nullable)
final ValueNotifier<String?> thumbnailId;
Timer? _autoSaveTimer; Timer? _autoSaveTimer;
ComposeState({ ComposeState({
@@ -68,8 +71,10 @@ class ComposeState {
this.postType = 0, this.postType = 0,
String? pollId, String? pollId,
String? fundId, String? fundId,
String? thumbnailId,
}) : pollId = ValueNotifier<String?>(pollId), }) : pollId = ValueNotifier<String?>(pollId),
fundId = ValueNotifier<String?>(fundId); fundId = ValueNotifier<String?>(fundId),
thumbnailId = ValueNotifier<String?>(thumbnailId);
void startAutoSave(WidgetRef ref) { void startAutoSave(WidgetRef ref) {
_autoSaveTimer?.cancel(); _autoSaveTimer?.cancel();
@@ -120,6 +125,9 @@ class ComposeLogic {
} catch (_) {} } catch (_) {}
} }
// Extract thumbnail ID from meta
final thumbnailId = originalPost?.meta?['thumbnail'] as String?;
return ComposeState( return ComposeState(
attachments: ValueNotifier<List<UniversalFile>>( attachments: ValueNotifier<List<UniversalFile>>(
originalPost?.attachments originalPost?.attachments
@@ -155,11 +163,13 @@ class ComposeLogic {
postType: postType, postType: postType,
pollId: pollId, pollId: pollId,
fundId: fundId, fundId: fundId,
thumbnailId: thumbnailId,
); );
} }
static ComposeState createStateFromDraft(SnPost draft, {int postType = 0}) { static ComposeState createStateFromDraft(SnPost draft, {int postType = 0}) {
final tags = draft.tags.map((tag) => tag.slug).toList(); final tags = draft.tags.map((tag) => tag.slug).toList();
final thumbnailId = draft.meta?['thumbnail'] as String?;
return ComposeState( return ComposeState(
attachments: ValueNotifier<List<UniversalFile>>( attachments: ValueNotifier<List<UniversalFile>>(
@@ -182,6 +192,7 @@ class ComposeLogic {
pollId: null, pollId: null,
// initialize without fund by default // initialize without fund by default
fundId: null, fundId: null,
thumbnailId: thumbnailId,
); );
} }
@@ -229,7 +240,9 @@ class ComposeLogic {
visibility: state.visibility.value, visibility: state.visibility.value,
content: state.contentController.text, content: state.contentController.text,
type: state.postType, type: state.postType,
meta: null, meta: state.postType == 1 && state.thumbnailId.value != null
? {'thumbnail': state.thumbnailId.value}
: null,
viewsUnique: 0, viewsUnique: 0,
viewsTotal: 0, viewsTotal: 0,
upvotes: 0, upvotes: 0,
@@ -301,7 +314,9 @@ class ComposeLogic {
visibility: state.visibility.value, visibility: state.visibility.value,
content: state.contentController.text, content: state.contentController.text,
type: state.postType, type: state.postType,
meta: null, meta: state.postType == 1 && state.thumbnailId.value != null
? {'thumbnail': state.thumbnailId.value}
: null,
viewsUnique: 0, viewsUnique: 0,
viewsTotal: 0, viewsTotal: 0,
upvotes: 0, upvotes: 0,
@@ -611,6 +626,10 @@ class ComposeLogic {
state.embedView.value = null; state.embedView.value = null;
} }
static void setThumbnail(ComposeState state, String? thumbnailId) {
state.thumbnailId.value = thumbnailId;
}
static Future<void> pickPoll( static Future<void> pickPoll(
WidgetRef ref, WidgetRef ref,
ComposeState state, ComposeState state,
@@ -719,6 +738,8 @@ class ComposeLogic {
if (state.realm.value != null) 'realm_id': state.realm.value?.id, if (state.realm.value != null) 'realm_id': state.realm.value?.id,
if (state.pollId.value != null) 'poll_id': state.pollId.value, if (state.pollId.value != null) 'poll_id': state.pollId.value,
if (state.fundId.value != null) 'fund_id': state.fundId.value, if (state.fundId.value != null) 'fund_id': state.fundId.value,
if (state.postType == 1 && state.thumbnailId.value != null)
'thumbnail_id': state.thumbnailId.value,
if (state.embedView.value != null) if (state.embedView.value != null)
'embed_view': state.embedView.value!.toJson(), 'embed_view': state.embedView.value!.toJson(),
}; };
@@ -738,6 +759,17 @@ class ComposeLogic {
onSuccess(); onSuccess();
eventBus.fire(PostCreatedEvent()); eventBus.fire(PostCreatedEvent());
final postTypeStr = state.postType == 0 ? 'regular' : 'article';
final visibilityStr = state.visibility.value.toString();
final publisherId = state.currentPublisher.value?.id ?? 'unknown';
AnalyticsService().logPostCreated(
postTypeStr,
visibilityStr,
state.attachments.value.isNotEmpty,
publisherId,
);
return post; return post;
} catch (err) { } catch (err) {
showErrorAlert(err); showErrorAlert(err);
@@ -799,7 +831,12 @@ class ComposeLogic {
state.attachments.value = [ state.attachments.value = [
...state.attachments.value, ...state.attachments.value,
UniversalFile( UniversalFile(
data: XFile.fromData(clipboard, mimeType: "image/jpeg"), displayName: 'image.jpeg',
data: XFile.fromData(
clipboard,
mimeType: "image/jpeg",
name: 'image.jpeg',
),
type: UniversalFileType.image, type: UniversalFileType.image,
), ),
]; ];
@@ -855,5 +892,6 @@ class ComposeLogic {
state.embedView.dispose(); state.embedView.dispose();
state.pollId.dispose(); state.pollId.dispose();
state.fundId.dispose(); state.fundId.dispose();
state.thumbnailId.dispose();
} }
} }

View File

@@ -13,14 +13,12 @@ import 'package:styled_widget/styled_widget.dart';
class ComposeToolbar extends HookConsumerWidget { class ComposeToolbar extends HookConsumerWidget {
final ComposeState state; final ComposeState state;
final SnPost? originalPost; final SnPost? originalPost;
final bool isCompact;
final bool useSafeArea; final bool useSafeArea;
const ComposeToolbar({ const ComposeToolbar({
super.key, super.key,
required this.state, required this.state,
this.originalPost, this.originalPost,
this.isCompact = false,
this.useSafeArea = false, this.useSafeArea = false,
}); });
@@ -72,8 +70,7 @@ class ComposeToolbar extends HookConsumerWidget {
context: context, context: context,
isScrollControlled: true, isScrollControlled: true,
useRootNavigator: true, useRootNavigator: true,
builder: builder: (context) => DraftManagerSheet(
(context) => DraftManagerSheet(
onDraftSelected: (draftId) { onDraftSelected: (draftId) {
final draft = ref.read(composeStorageProvider)[draftId]; final draft = ref.read(composeStorageProvider)[draftId];
if (draft != null) { if (draft != null) {
@@ -96,164 +93,21 @@ class ComposeToolbar extends HookConsumerWidget {
final colorScheme = Theme.of(context).colorScheme; final colorScheme = Theme.of(context).colorScheme;
if (isCompact) {
return Container(
color: Theme.of(context).colorScheme.surfaceContainerLow,
padding: EdgeInsets.symmetric(horizontal: 8),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 560),
child: Row(
children: [
Expanded(
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
UploadMenu(
items: uploadMenuItems,
isCompact: isCompact,
),
IconButton(
onPressed: linkAttachment,
icon: const Icon(Symbols.attach_file),
tooltip: 'linkAttachment'.tr(),
color: colorScheme.primary,
visualDensity: const VisualDensity(
horizontal: -4,
vertical: -2,
),
),
// Poll button with visual state when a poll is linked
ListenableBuilder(
listenable: state.pollId,
builder: (context, _) {
return IconButton(
onPressed: pickPoll,
icon: const Icon(Symbols.how_to_vote),
tooltip: 'poll'.tr(),
color: colorScheme.primary,
visualDensity: const VisualDensity(
horizontal: -4,
vertical: -2,
),
style: ButtonStyle(
backgroundColor: WidgetStatePropertyAll(
state.pollId.value != null
? colorScheme.primary.withOpacity(0.15)
: null,
),
),
);
},
),
// Fund button with visual state when a fund is linked
ListenableBuilder(
listenable: state.fundId,
builder: (context, _) {
return IconButton(
onPressed: pickFund,
icon: const Icon(Symbols.account_balance_wallet),
tooltip: 'fund'.tr(),
color: colorScheme.primary,
visualDensity: const VisualDensity(
horizontal: -4,
vertical: -2,
),
style: ButtonStyle(
backgroundColor: WidgetStatePropertyAll(
state.fundId.value != null
? colorScheme.primary.withOpacity(0.15)
: null,
),
),
);
},
),
// Embed button with visual state when embed is present
ListenableBuilder(
listenable: state.embedView,
builder: (context, _) {
return IconButton(
onPressed: showEmbedSheet,
icon: const Icon(Symbols.iframe),
tooltip: 'embedView'.tr(),
color: colorScheme.primary,
visualDensity: const VisualDensity(
horizontal: -4,
vertical: -2,
),
style: ButtonStyle(
backgroundColor: WidgetStatePropertyAll(
state.embedView.value != null
? colorScheme.primary.withOpacity(0.15)
: null,
),
),
);
},
),
],
),
),
),
if (originalPost == null && state.isEmpty)
IconButton(
icon: const Icon(Symbols.draft, size: 20),
color: colorScheme.primary,
onPressed: showDraftManager,
tooltip: 'drafts'.tr(),
visualDensity: const VisualDensity(
horizontal: -4,
vertical: -4,
),
constraints: const BoxConstraints(
minWidth: 32,
minHeight: 48,
),
)
else if (originalPost == null)
IconButton(
icon: const Icon(Symbols.save, size: 20),
color: colorScheme.primary,
onPressed: saveDraft,
onLongPress: showDraftManager,
tooltip: 'saveDraft'.tr(),
visualDensity: const VisualDensity(
horizontal: -4,
vertical: -4,
),
constraints: const BoxConstraints(
minWidth: 32,
minHeight: 48,
),
),
],
).padding(
horizontal: 8,
top: 4,
bottom:
useSafeArea ? MediaQuery.of(context).padding.bottom + 4 : 4,
),
),
),
);
}
return Material( return Material(
elevation: 4, elevation: 8,
color: Theme.of(context).colorScheme.surfaceContainerLow, color: Theme.of(context).colorScheme.surfaceContainer,
child: Center( child: Center(
child: ConstrainedBox( child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 560), constraints: const BoxConstraints(maxWidth: 560),
child: Row( child:
Row(
children: [ children: [
Expanded( Expanded(
child: SingleChildScrollView( child: SingleChildScrollView(
scrollDirection: Axis.horizontal, scrollDirection: Axis.horizontal,
child: Row( child: Row(
children: [ children: [
UploadMenu(items: uploadMenuItems, isCompact: isCompact), UploadMenu(items: uploadMenuItems),
IconButton( IconButton(
onPressed: linkAttachment, onPressed: linkAttachment,
icon: const Icon(Symbols.attach_file), icon: const Icon(Symbols.attach_file),
@@ -285,7 +139,9 @@ class ComposeToolbar extends HookConsumerWidget {
builder: (context, _) { builder: (context, _) {
return IconButton( return IconButton(
onPressed: pickFund, onPressed: pickFund,
icon: const Icon(Symbols.account_balance_wallet), icon: const Icon(
Symbols.account_balance_wallet,
),
tooltip: 'fund'.tr(), tooltip: 'fund'.tr(),
color: colorScheme.primary, color: colorScheme.primary,
style: ButtonStyle( style: ButtonStyle(

View File

@@ -22,7 +22,8 @@ Future<List<SnPost>> featuredPosts(Ref ref) async {
class PostFeaturedList extends HookConsumerWidget { class PostFeaturedList extends HookConsumerWidget {
final bool collapsable; final bool collapsable;
const PostFeaturedList({super.key, this.collapsable = true}); final double? maxHeight;
const PostFeaturedList({super.key, this.collapsable = true, this.maxHeight});
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
@@ -178,7 +179,7 @@ class PostFeaturedList extends HookConsumerWidget {
error: (error, stack) => Center(child: Text('Error: $error')), error: (error, stack) => Center(child: Text('Error: $error')),
data: (posts) { data: (posts) {
return SizedBox( return SizedBox(
height: 344, height: maxHeight == null ? 344 : (maxHeight! - 48),
child: PageView.builder( child: PageView.builder(
controller: pageViewController, controller: pageViewController,
scrollDirection: Axis.horizontal, scrollDirection: Axis.horizontal,

Some files were not shown because too many files have changed in this diff Show More