Compare commits

...

44 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
77 changed files with 6496 additions and 3846 deletions

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?",
@@ -1592,5 +1618,39 @@
"tasksCount": { "tasksCount": {
"one": "{} task", "one": "{} task",
"other": "{} tasks" "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

@@ -127,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):
@@ -264,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):
@@ -349,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`)
@@ -373,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`)
@@ -447,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:
@@ -491,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:
@@ -553,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
@@ -585,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

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 {
@@ -16,7 +15,7 @@ import flutter_app_intents
) -> Bool { ) -> Bool {
syncDefaultsToGroup() syncDefaultsToGroup()
WidgetCenter.shared.reloadAllTimelines() WidgetCenter.shared.reloadAllTimelines()
UNUserNotificationCenter.current().delegate = notifyDelegate UNUserNotificationCenter.current().delegate = notifyDelegate
let replyableMessageCategory = UNNotificationCategory( let replyableMessageCategory = UNNotificationCategory(
@@ -32,26 +31,24 @@ import flutter_app_intents
options: [] options: []
) )
UNUserNotificationCenter.current().setNotificationCategories([replyableMessageCategory]) UNUserNotificationCenter.current().setNotificationCategories([replyableMessageCategory])
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 {
print("[iOS] WCSession not supported on this device.") print("[iOS] WCSession not supported on this device.")
} }
return super.application(application, didFinishLaunchingWithOptions: launchOptions) return super.application(application, didFinishLaunchingWithOptions: launchOptions)
} }
private func setupWidgetSyncChannel() { private func setupWidgetSyncChannel() {
let controller = window?.rootViewController as? FlutterViewController let controller = window?.rootViewController as? FlutterViewController
let channel = FlutterMethodChannel(name: "dev.solsynth.solian/widget", binaryMessenger: controller!.binaryMessenger) let channel = FlutterMethodChannel(name: "dev.solsynth.solian/widget", binaryMessenger: controller!.binaryMessenger)
channel.setMethodCallHandler { [weak self] (call, result) in channel.setMethodCallHandler { [weak self] (call, result) in
if call.method == "syncToWidget" { if call.method == "syncToWidget" {
syncDefaultsToGroup() syncDefaultsToGroup()
@@ -62,12 +59,12 @@ import flutter_app_intents
} }
} }
} }
override func applicationDidEnterBackground(_ application: UIApplication) { override func applicationDidEnterBackground(_ application: UIApplication) {
syncDefaultsToGroup() syncDefaultsToGroup()
WidgetCenter.shared.reloadAllTimelines() WidgetCenter.shared.reloadAllTimelines()
} }
override func applicationWillTerminate(_ application: UIApplication) { override func applicationWillTerminate(_ application: UIApplication) {
syncDefaultsToGroup() syncDefaultsToGroup()
} }
@@ -76,7 +73,7 @@ import flutter_app_intents
final class WatchConnectivityService: NSObject, WCSessionDelegate { final class WatchConnectivityService: NSObject, WCSessionDelegate {
static let shared = WatchConnectivityService() static let shared = WatchConnectivityService()
private let session: WCSession = .default private let session: WCSession = .default
private override init() { private override init() {
super.init() super.init()
print("[iOS] Activating WCSession...") print("[iOS] Activating WCSession...")
@@ -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)")
@@ -98,7 +93,7 @@ final class WatchConnectivityService: NSObject, WCSessionDelegate {
} }
func sessionDidBecomeInactive(_ session: WCSession) {} func sessionDidBecomeInactive(_ session: WCSession) {}
func sessionDidDeactivate(_ session: WCSession) { func sessionDidDeactivate(_ session: WCSession) {
session.activate() session.activate()
} }
@@ -108,12 +103,12 @@ final class WatchConnectivityService: NSObject, WCSessionDelegate {
if let request = message["request"] as? String, request == "data" { if let request = message["request"] as? String, request == "data" {
let token = UserDefaults.standard.getFlutterToken() let token = UserDefaults.standard.getFlutterToken()
let serverUrl = UserDefaults.standard.getServerUrl() let serverUrl = UserDefaults.standard.getServerUrl()
var data: [String: Any] = ["serverUrl": serverUrl] var data: [String: Any] = ["serverUrl": serverUrl]
if let token = token { if let token = token {
data["token"] = token data["token"] = token
} }
print("[iOS] Replying with data: \(data)") print("[iOS] Replying with data: \(data)")
replyHandler(data) replyHandler(data)
} }
@@ -123,15 +118,15 @@ final class WatchConnectivityService: NSObject, WCSessionDelegate {
guard session.activationState == .activated else { guard session.activationState == .activated else {
return return
} }
let token = UserDefaults.standard.getFlutterToken() let token = UserDefaults.standard.getFlutterToken()
let serverUrl = UserDefaults.standard.getServerUrl() let serverUrl = UserDefaults.standard.getServerUrl()
var data: [String: Any] = ["serverUrl": serverUrl] var data: [String: Any] = ["serverUrl": serverUrl]
if let token = token { if let token = token {
data["token"] = token data["token"] = token
} }
do { do {
try session.updateApplicationContext(data) try session.updateApplicationContext(data)
print("[iOS] Sent application context: \(data)") print("[iOS] Sent application context: \(data)")
@@ -140,412 +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: "\(value)"
)
} else {
let errorMessage = result["error"] as? String ?? "Failed to check notifications"
throw AppIntentError.executionFailed(errorMessage)
}
}
}
@available(iOS 16.0, *)
struct SendMessageIntent: AppIntent {
static var title: LocalizedStringResource = "Send Message"
static var description = IntentDescription("Send a message to a chat channel")
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 & ReturnsValue<String> & ProvidesDialog {
guard let channelId = channelId, !channelId.isEmpty else {
throw AppIntentError.executionFailed("Channel ID is required")
}
guard let content = content, !content.isEmpty else {
throw AppIntentError.executionFailed("Message content is required")
}
let plugin = FlutterAppIntentsPlugin.shared
let result = await plugin.handleIntentInvocation(
identifier: "send_message",
parameters: ["channelId": channelId, "content": content]
)
if let success = result["success"] as? Bool, success {
let value = result["value"] as? String ?? "Message sent"
return .result(
value: value,
dialog: "\(value)"
)
} else {
let errorMessage = result["error"] as? String ?? "Failed to send message"
throw AppIntentError.executionFailed(errorMessage)
}
}
}
@available(iOS 16.0, *)
struct ReadMessagesIntent: AppIntent {
static var title: LocalizedStringResource = "Read Messages"
static var description = IntentDescription("Read recent messages from a chat channel")
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 & ReturnsValue<String> & ProvidesDialog {
guard let channelId = channelId, !channelId.isEmpty else {
throw AppIntentError.executionFailed("Channel ID is required")
}
let limit = limit ?? "5"
var parameters: [String: Any] = ["channelId": channelId]
parameters["limit"] = limit
let plugin = FlutterAppIntentsPlugin.shared
let result = await plugin.handleIntentInvocation(
identifier: "read_messages",
parameters: parameters
)
if let success = result["success"] as? Bool, success {
let value = result["value"] as? String ?? "Messages retrieved"
return .result(
value: value,
dialog: "\(value)"
)
} else {
let errorMessage = result["error"] as? String ?? "Failed to read messages"
throw AppIntentError.executionFailed(errorMessage)
}
}
}
@available(iOS 16.0, *)
struct CheckUnreadChatsIntent: AppIntent {
static var title: LocalizedStringResource = "Check Unread Chats"
static var description = IntentDescription("Check number of unread chat messages")
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_unread_chats",
parameters: [:]
)
if let success = result["success"] as? Bool, success {
let value = result["value"] as? String ?? "No unread messages"
return .result(
value: value,
dialog: "\(value)"
)
} else {
let errorMessage = result["error"] as? String ?? "Failed to check unread chats"
throw AppIntentError.executionFailed(errorMessage)
}
}
}
@available(iOS 16.0, *)
struct MarkNotificationsReadIntent: AppIntent {
static var title: LocalizedStringResource = "Mark Notifications Read"
static var description = IntentDescription("Mark all notifications as read")
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: "mark_notifications_read",
parameters: [:]
)
if let success = result["success"] as? Bool, success {
let value = result["value"] as? String ?? "Notifications marked as read"
return .result(
value: value,
dialog: "\(value)"
)
} else {
let errorMessage = result["error"] as? String ?? "Failed to mark notifications as read"
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)"
]
),
// Send message
AppShortcut(
intent: SendMessageIntent(),
phrases: [
"Send message with \(.applicationName)",
"Post message using \(.applicationName)",
"Send text using \(.applicationName)"
]
),
// Read messages
AppShortcut(
intent: ReadMessagesIntent(),
phrases: [
"Read messages with \(.applicationName)",
"Get chat using \(.applicationName)",
"Show messages with \(.applicationName)"
]
),
// Check unread chats
AppShortcut(
intent: CheckUnreadChatsIntent(),
phrases: [
"Check unread chats with \(.applicationName)",
"Do I have messages using \(.applicationName)",
"Get unread messages with \(.applicationName)"
]
),
// Mark notifications read
AppShortcut(
intent: MarkNotificationsReadIntent(),
phrases: [
"Mark notifications read with \(.applicationName)",
"Clear notifications using \(.applicationName)",
"Mark all read with \(.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" = "將所有通知標記為已讀";

View File

@@ -143,7 +143,12 @@ RoomInputManager useRoomInputManager(WidgetRef ref, String roomId) {
final newAttachments = [ final newAttachments = [
...attachments.value, ...attachments.value,
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,
), ),
]; ];

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

@@ -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(),

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

@@ -223,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;
} }
@@ -243,11 +243,14 @@ class ChatSubscribeNotifier extends _$ChatSubscribeNotifier {
// Play sound for new messages when app is unfocused // Play sound for new messages when app is unfocused
if (pkt.type == 'messages.new' && if (pkt.type == 'messages.new' &&
message.senderId != _chatIdentity.id && message.senderId != _chatIdentity.id &&
ref.read(appLifecycleStateProvider).value != AppLifecycleState.resumed && ref.read(appLifecycleStateProvider).value !=
AppLifecycleState.resumed &&
ref.read(appSettingsProvider).soundEffects) { ref.read(appSettingsProvider).soundEffects) {
final player = AudioPlayer(); final player = AudioPlayer();
await player.setVolume(0.75); await player.setVolume(0.75);
await player.setAudioSource(AudioSource.asset('assets/audio/messages.mp3')); await player.setAudioSource(
AudioSource.asset('assets/audio/messages.mp3'),
);
await player.play(); await player.play();
player.dispose(); player.dispose();
} }
@@ -288,4 +291,4 @@ class ChatSubscribeNotifier extends _$ChatSubscribeNotifier {
_typingCooldownTimer = null; _typingCooldownTimer = null;
}); });
} }
} }

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

@@ -42,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) {
@@ -68,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({
@@ -94,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;
} }
@@ -126,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),
); );
} }
@@ -158,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) {
@@ -324,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 =
@@ -340,4 +385,4 @@ class UpdateInfoNotifier extends Notifier<(String?, String?)> {
void setUpdate(String newVersion, String newChangelog) { void setUpdate(String newVersion, String newChangelog) {
state = (newVersion, newChangelog); state = (newVersion, newChangelog);
} }
} }

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'64cf6dfda90fc634336d96bd5313b2a07b19eccb'; r'0a7f75bd95850b0c564b29c57912ec8fcac53f09';
abstract class _$AppSettingsNotifier extends $Notifier<AppSettings> { abstract class _$AppSettingsNotifier extends $Notifier<AppSettings> {
AppSettings build(); AppSettings build();

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

@@ -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),

View File

@@ -105,14 +105,12 @@ 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: () => ref.invalidate(
onRetry: webFeedNotifierProvider((pubName: pubName, feedId: feedId)),
() => ref.invalidate( ),
webFeedNotifierProvider((pubName: pubName, feedId: feedId)), ),
),
),
data: (feed) { data: (feed) {
// Initialize form fields if they're empty and we have a feed // Initialize form fields if they're empty and we have a feed
if (titleController.text.isEmpty) { if (titleController.text.isEmpty) {
@@ -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,106 +46,51 @@ class DashboardScreen extends HookConsumerWidget {
} }
} }
class DashboardGrid extends HookConsumerWidget { // Helper functions for dynamic dashboard rendering
const DashboardGrid({super.key}); class DashboardRenderer {
// Map individual card IDs to widgets
@override static Widget buildCard(String cardId, WidgetRef ref) {
Widget build(BuildContext context, WidgetRef ref) { switch (cardId) {
final isWide = isWideScreen(context); case 'checkIn':
final devicePadding = MediaQuery.paddingOf(context); return CheckInWidget(margin: EdgeInsets.zero);
case 'fortuneGraph':
final userInfo = ref.watch(userInfoProvider); return Card(
margin: EdgeInsets.zero,
return Container( child: FortuneGraphWidget(
constraints: BoxConstraints( events: ref.watch(
maxHeight: isWide eventCalendarProvider(
? math.min(640, MediaQuery.sizeOf(context).height * 0.65) EventCalendarQuery(
: MediaQuery.sizeOf(context).height, uname: 'me',
), year: DateTime.now().year,
padding: isWide month: DateTime.now().month,
? EdgeInsets.only(top: devicePadding.top)
: EdgeInsets.only(top: 24 + devicePadding.top),
child: Column(
spacing: 16,
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Clock card spans full width
if (isWide)
ClockCard().padding(horizontal: 24)
else
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Gap(8),
Expanded(child: ClockCard(compact: true)),
IconButton(
onPressed: () {
eventBus.fire(CommandPaletteTriggerEvent());
},
icon: const Icon(Symbols.search),
tooltip: 'searchAnything'.tr(),
), ),
],
).padding(horizontal: 24),
// Row with two cards side by side
if (isWide)
Padding(
padding: EdgeInsets.symmetric(horizontal: isWide ? 24 : 16),
child: SearchBar(
hintText: 'searchAnything'.tr(),
constraints: const BoxConstraints(minHeight: 56),
leading: const Icon(Symbols.search).padding(horizontal: 24),
readOnly: true,
onTap: () {
eventBus.fire(CommandPaletteTriggerEvent());
},
), ),
), ),
if (userInfo.value != null) ),
Expanded( );
child: case 'fortuneCard':
SingleChildScrollView( return FortuneCard(unlimited: true);
padding: isWide case 'postFeatured':
? const EdgeInsets.symmetric(horizontal: 24) return ConstrainedBox(
: EdgeInsets.only( constraints: const BoxConstraints(maxHeight: 400),
bottom: 64 + devicePadding.bottom, child: PostFeaturedList(),
), );
scrollDirection: isWide case 'friendsOverview':
? Axis.horizontal return FriendsOverviewWidget();
: Axis.vertical, case 'notifications':
child: isWide return NotificationsCard();
? _DashboardGridWide() case 'chatList':
: _DashboardGridNarrow(), return ChatListCard();
) default:
.clipRRect( return const SizedBox.shrink();
topLeft: isWide ? 0 : 12, }
topRight: isWide ? 0 : 12,
)
.padding(horizontal: isWide ? 0 : 16),
)
else
Center(
child: _UnauthorizedCard(isWide: isWide),
).padding(horizontal: isWide ? 24 : 16),
],
),
);
} }
}
class _DashboardGridWide extends HookConsumerWidget { // Map column group IDs to column widgets
const _DashboardGridWide(); static Widget buildColumn(String columnId, WidgetRef ref) {
switch (columnId) {
@override case 'activityColumn':
Widget build(BuildContext context, WidgetRef ref) { return SizedBox(
final userInfo = ref.watch(userInfoProvider);
return Row(
spacing: 16,
children: [
if (userInfo.value != null && userInfo.value?.activatedAt == null)
SizedBox(width: 400, child: AccountUnactivatedCard()),
SizedBox(
width: 400, width: 400,
child: Column( child: Column(
spacing: 16, spacing: 16,
@@ -163,9 +113,21 @@ class _DashboardGridWide extends HookConsumerWidget {
Expanded(child: FortuneCard()), Expanded(child: FortuneCard()),
], ],
), ),
), );
SizedBox(width: 400, child: PostFeaturedList(collapsable: false)), case 'postsColumn':
SizedBox( return SizedBox(
width: 400,
child: LayoutBuilder(
builder: (context, constraints) {
return PostFeaturedList(
collapsable: false,
maxHeight: constraints.maxHeight,
);
},
),
);
case 'socialColumn':
return SizedBox(
width: 400, width: 400,
child: Column( child: Column(
spacing: 16, spacing: 16,
@@ -174,56 +136,269 @@ class _DashboardGridWide extends HookConsumerWidget {
Expanded(child: NotificationsCard()), Expanded(child: NotificationsCard()),
], ],
), ),
), );
SizedBox( case 'chatsColumn':
return SizedBox(
width: 400, width: 400,
child: Column( child: Column(
spacing: 16, spacing: 16,
children: [Expanded(child: ChatListCard())], children: [Expanded(child: ChatListCard())],
), ),
), );
], default:
return const SizedBox.shrink();
}
}
}
class DashboardGrid extends HookConsumerWidget {
const DashboardGrid({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final isWide = isWideScreen(context);
final devicePadding = MediaQuery.paddingOf(context);
final userInfo = ref.watch(userInfoProvider);
final appSettings = ref.watch(appSettingsProvider);
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(
maxHeight: isWide
? math.min(640, MediaQuery.sizeOf(context).height * 0.65)
: MediaQuery.sizeOf(context).height,
),
padding: isWide
? EdgeInsets.only(top: devicePadding.top)
: EdgeInsets.only(top: 24 + devicePadding.top),
child: Column(
spacing: 16,
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Clock card spans full width (only if enabled in settings)
if (isWide &&
(appSettings.dashboardConfig?.showClockAndCountdown ??
true))
ClockCard().padding(horizontal: 24)
else if (!isWide)
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Gap(8),
if (appSettings.dashboardConfig?.showClockAndCountdown ??
true)
Expanded(child: ClockCard(compact: true)),
if (appSettings.dashboardConfig?.showSearchBar ?? true)
IconButton(
onPressed: () {
eventBus.fire(CommandPaletteTriggerEvent());
},
icon: const Icon(Symbols.search),
tooltip: 'searchAnything'.tr(),
),
],
).padding(horizontal: 24),
// Row with two cards side by side (only if enabled in settings)
if (isWide &&
(appSettings.dashboardConfig?.showSearchBar ?? true))
Padding(
padding: EdgeInsets.symmetric(horizontal: isWide ? 24 : 16),
child: SearchBar(
hintText: 'searchAnything'.tr(),
constraints: const BoxConstraints(minHeight: 56),
leading: const Icon(
Symbols.search,
).padding(horizontal: 24),
readOnly: true,
onTap: () {
eventBus.fire(CommandPaletteTriggerEvent());
},
),
),
if (userInfo.value != null)
Expanded(
child:
SingleChildScrollView(
padding: isWide
? const EdgeInsets.symmetric(horizontal: 24)
: EdgeInsets.only(
bottom: 64 + devicePadding.bottom,
),
scrollDirection: isWide
? Axis.horizontal
: Axis.vertical,
child: isWide
? _DashboardGridWide()
: _DashboardGridNarrow(),
)
.clipRRect(
topLeft: isWide ? 0 : 12,
topRight: isWide ? 0 : 12,
)
.padding(horizontal: isWide ? 0 : 16),
)
else
Center(
child: _UnauthorizedCard(isWide: isWide),
).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,
),
),
],
),
),
),
),
],
),
); );
} }
} }
class _DashboardGridWide extends HookConsumerWidget {
const _DashboardGridWide();
@override
Widget build(BuildContext context, WidgetRef ref) {
final userInfo = ref.watch(userInfoProvider);
final appSettings = ref.watch(appSettingsProvider);
final List<Widget> children = [];
// Always include account unactivated card if user is not activated
if (userInfo.value != null && userInfo.value?.activatedAt == null) {
children.add(SizedBox(width: 400, child: AccountUnactivatedCard()));
}
// Add configured columns in the specified order
final horizontalLayouts =
appSettings.dashboardConfig?.horizontalLayouts ??
['activityColumn', 'postsColumn', 'socialColumn', 'chatsColumn'];
for (final columnId in horizontalLayouts) {
children.add(DashboardRenderer.buildColumn(columnId, ref));
}
// If no children, add a SizedBox.expand to maintain width
if (children.isEmpty) {
children.add(SizedBox(width: MediaQuery.sizeOf(context).width));
}
return Row(spacing: 16, children: children);
}
}
class _DashboardGridNarrow extends HookConsumerWidget { class _DashboardGridNarrow extends HookConsumerWidget {
const _DashboardGridNarrow(); const _DashboardGridNarrow();
@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,19 +479,22 @@ class ClockCard extends HookConsumerWidget {
), ),
], ],
), ),
Row( SingleChildScrollView(
spacing: 5, scrollDirection: Axis.horizontal,
children: [ child: Row(
notableDay.when( spacing: 5,
data: (day) => day == null children: [
? Text('unauthorized').tr() notableDay.when(
: _buildNotableDayText(context, day), data: (day) => day == null
error: (err, _) => ? Text('unauthorized').tr()
Text(err.toString()).fontSize(12), : _buildNotableDayText(context, day),
loading: () => error: (err, _) =>
const Text('loading').tr().fontSize(12), Text(err.toString()).fontSize(12),
), loading: () =>
], const Text('loading').tr().fontSize(12),
),
],
),
), ),
], ],
), ),
@@ -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,118 +191,66 @@ class ExploreScreen extends HookConsumerWidget {
hasSubscriptionsSelected, hasSubscriptionsSelected,
); );
final dragging = useState(false); return AppScaffold(
isNoBackground: false,
return DropTarget( appBar: appBar,
onDragDone: (detail) { floatingActionButton: userInfo.value != null
dragging.value = false; ? FloatingActionButton(
if (detail.files.isNotEmpty) { child: const Icon(Symbols.create),
showModalBottomSheet( onPressed: () {
context: context, showModalBottomSheet(
isScrollControlled: true, context: context,
useRootNavigator: true, isScrollControlled: true,
builder: (context) => ShareSheet.files(files: detail.files), useRootNavigator: true,
); builder: (context) => Column(
}
},
onDragEntered: (_) => dragging.value = true,
onDragExited: (_) => dragging.value = false,
child: Stack(
children: [
AppScaffold(
isNoBackground: false,
appBar: appBar,
floatingActionButton: userInfo.value != null
? FloatingActionButton(
child: const Icon(Symbols.create),
onPressed: () {
showModalBottomSheet(
context: context,
isScrollControlled: true,
useRootNavigator: true,
builder: (context) => Column(
mainAxisSize: MainAxisSize.min,
children: [
const Gap(40),
ListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 24,
),
leading: const Icon(Symbols.post_add_rounded),
title: Text('postCompose').tr(),
onTap: () async {
Navigator.of(context).pop();
await PostComposeSheet.show(context);
},
),
ListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 24,
),
leading: const Icon(Symbols.article),
title: Text('articleCompose').tr(),
onTap: () async {
Navigator.of(context).pop();
GoRouter.of(
context,
).pushNamed('articleCompose');
},
),
const Gap(16),
],
),
);
},
).padding(bottom: MediaQuery.of(context).padding.bottom)
: null,
body: isWide
? _buildWideBody(
context,
ref,
filterBar,
user,
notificationCount,
query,
events,
selectedDay,
currentFilter.value,
selectedPublisherNames,
selectedCategoryIds,
selectedTagIds,
)
: _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, mainAxisSize: MainAxisSize.min,
children: [ children: [
Icon( const Gap(40),
Symbols.upload_file, ListTile(
size: 64, contentPadding: const EdgeInsets.symmetric(
color: Theme.of(context).colorScheme.primary, horizontal: 24,
),
leading: const Icon(Symbols.post_add_rounded),
title: Text('postCompose').tr(),
onTap: () async {
Navigator.of(context).pop();
await PostComposeSheet.show(context);
},
),
ListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 24,
),
leading: const Icon(Symbols.article),
title: Text('articleCompose').tr(),
onTap: () async {
Navigator.of(context).pop();
GoRouter.of(context).pushNamed('articleCompose');
},
), ),
const Gap(16), const Gap(16),
Text(
'dropToShare'.tr(),
style: Theme.of(context).textTheme.headlineMedium
?.copyWith(
color: Theme.of(context).colorScheme.primary,
fontWeight: FontWeight.bold,
),
),
], ],
), ),
), );
), },
), ).padding(bottom: MediaQuery.of(context).padding.bottom)
], : null,
), body: isWide
? _buildWideBody(
context,
ref,
filterBar,
user,
notificationCount,
query,
events,
selectedDay,
currentFilter.value,
selectedPublisherNames,
selectedCategoryIds,
selectedTagIds,
)
: _buildNarrowBody(context, ref, currentFilter.value),
); );
} }

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,120 +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],
isUploading: progressMap.containsKey(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(
ref,
state,
idx,
poolId: config.poolId,
);
}
},
onUpdate: (value) =>
ComposeLogic.updateAttachment(
state,
value,
idx,
),
onDelete: () =>
ComposeLogic.deleteAttachment(
ref,
state,
idx,
),
onInsert: () =>
ComposeLogic.insertAttachment(
ref,
state,
idx,
),
),
),
],
);
},
),
Gap(16),
],
),
);
},
),
], ],
), ),
), ),
); );
// Add background color for mobile editor pane
if (!isWideScreen(context)) {
return Container(
decoration: BoxDecoration(
color: colorScheme.surface,
borderRadius: BorderRadius.circular(8),
),
margin: const EdgeInsets.symmetric(vertical: 8),
child: editorContent,
);
}
return editorContent;
} }
return PopScope( return PopScope(
@@ -398,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(
titleValue.text.isEmpty ? 'postTitle'.tr() : titleValue.text, duration: const Duration(milliseconds: 150),
switchInCurve: Curves.fastEaseInToSlowEaseOut,
switchOutCurve: Curves.fastEaseInToSlowEaseOut,
child: Text(
titleValue.text.isEmpty ? 'postTitle'.tr() : titleValue.text,
key: ValueKey(titleValue.text),
overflow: TextOverflow.ellipsis,
),
); );
}, },
), ),
@@ -427,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(
icon: submitting scale: Tween<double>(
begin: 0.8,
end: 1.0,
).animate(animation),
child: child,
),
);
},
child: submitting
? SizedBox( ? SizedBox(
key: const ValueKey('submitting'),
width: 28, width: 28,
height: 28, height: 28,
child: const CircularProgressIndicator( child: const CircularProgressIndicator(
@@ -459,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,
),
), ),
); );
}, },
@@ -471,24 +394,66 @@ class ArticleComposeScreen extends HookConsumerWidget {
body: Column( body: Column(
children: [ children: [
Expanded( Expanded(
child: Padding( child: ResponsiveSidebar(
padding: const EdgeInsets.only(left: 16, right: 16), sidebarWidth: 480,
child: isWideScreen(context) attachmentsContent: ArticleComposeAttachments(state: state),
? Row( settingsContent: ComposeSettingsSheet(state: state),
spacing: 16, showSidebar: showSidebar,
children: [ mainContent: Padding(
Expanded( padding: const EdgeInsets.only(left: 16, right: 16),
flex: showPreview.value ? 1 : 2, child: AnimatedSwitcher(
child: buildEditorPane(), 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)
? Row(
spacing: 16,
children: [
Expanded(child: buildEditorPane()),
if (showPreview.value)
Expanded(child: buildPreviewPane()),
],
)
: Container(
key: ValueKey('narrow-${showPreview.value}'),
child: showPreview.value
? buildPreviewPane()
: buildEditorPane(),
), ),
if (showPreview.value) const VerticalDivider(), ),
if (showPreview.value) ),
Expanded(child: buildPreviewPane()),
],
)
: showPreview.value
? buildPreviewPane()
: buildEditorPane(),
), ),
), ),

View File

@@ -518,7 +518,7 @@ 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),
], ],
), ),
@@ -529,11 +529,13 @@ class _PostDetailLargeScreenLayout extends StatelessWidget {
left: 16, left: 16,
right: 16, right: 16,
child: ConstrainedBox( child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: 800), constraints: BoxConstraints(maxWidth: 680),
child: PostQuickReply( child: PostQuickReply(
parent: post, parent: post,
onPosted: () { onPosted: () {
ref.read(postRepliesProvider(postId).notifier).refresh(); ref
.read(postRepliesProvider(postId).notifier)
.refresh();
}, },
), ),
).center(), ).center(),
@@ -594,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,
@@ -612,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(
@@ -633,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),
], ],
), ),
@@ -644,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!,
@@ -668,4 +670,4 @@ class PostDetailScreen extends HookConsumerWidget {
), ),
); );
} }
} }

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

@@ -1,21 +1,20 @@
import 'dart:io'; import 'dart:io';
import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/foundation.dart';
import 'package:island/talker.dart'; import 'package:island/talker.dart';
class AnalyticsService { class AnalyticsService {
static final AnalyticsService _instance = AnalyticsService._internal(); static final AnalyticsService _instance = AnalyticsService._internal();
factory AnalyticsService() => _instance; factory AnalyticsService() => _instance;
AnalyticsService._internal() { AnalyticsService._internal();
_init();
}
FirebaseAnalytics? _analytics; FirebaseAnalytics? _analytics;
bool _enabled = true; bool _enabled = true;
bool get _supportsAnalytics => bool get _supportsAnalytics =>
Platform.isAndroid || Platform.isIOS || Platform.isMacOS; kIsWeb || (Platform.isAndroid || Platform.isIOS || Platform.isMacOS);
void _init() { void initialize() {
if (!_supportsAnalytics) return; if (!_supportsAnalytics) return;
try { try {
_analytics = FirebaseAnalytics.instance; _analytics = FirebaseAnalytics.instance;

View File

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

View File

@@ -1,777 +0,0 @@
import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:firebase_analytics/firebase_analytics.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/services/event_bus.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,
);
// Message Intents
await _client!.registerIntent(
AppIntentBuilder()
.identifier('send_message')
.title('Send Message')
.description('Send a message to a chat channel')
.parameter(
const AppIntentParameter(
name: 'channelId',
title: 'Channel ID',
type: AppIntentParameterType.string,
isOptional: false,
),
)
.parameter(
const AppIntentParameter(
name: 'content',
title: 'Message Content',
type: AppIntentParameterType.string,
isOptional: false,
),
)
.build(),
_handleSendMessageIntent,
);
await _client!.registerIntent(
AppIntentBuilder()
.identifier('read_messages')
.title('Read Messages')
.description('Read recent messages from a chat channel')
.parameter(
const AppIntentParameter(
name: 'channelId',
title: 'Channel ID',
type: AppIntentParameterType.string,
isOptional: false,
),
)
.parameter(
const AppIntentParameter(
name: 'limit',
title: 'Number of Messages',
type: AppIntentParameterType.string,
isOptional: true,
),
)
.build(),
_handleReadMessagesIntent,
);
await _client!.registerIntent(
AppIntentBuilder()
.identifier('check_unread_chats')
.title('Check Unread Chats')
.description('Check number of unread chat messages')
.build(),
_handleCheckUnreadChatsIntent,
);
await _client!.registerIntent(
AppIntentBuilder()
.identifier('mark_notifications_read')
.title('Mark Notifications Read')
.description('Mark all notifications as read')
.build(),
_handleMarkNotificationsReadIntent,
);
}
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');
eventBus.fire(ShowComposeSheetEvent());
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');
eventBus.fire(ShowComposeSheetEvent());
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');
}
}
Future<AppIntentResult> _handleSendMessageIntent(
Map<String, dynamic> parameters,
) async {
try {
final channelId = parameters['channelId'] as String?;
final content = parameters['content'] as String?;
if (channelId == null) {
throw ArgumentError('channelId is required');
}
if (content == null || content.isEmpty) {
throw ArgumentError('content is required');
}
talker.info('[AppIntents] Sending message to $channelId: $content');
if (_dio == null) {
return AppIntentResult.failed(error: 'API client not initialized');
}
try {
final nonce = _generateNonce();
await _dio!.post(
'/messager/chat/$channelId/messages',
data: {'content': content, 'nonce': nonce},
);
talker.info('[AppIntents] Message sent successfully');
return AppIntentResult.successful(
value: 'Message sent to channel $channelId',
needsToContinueInApp: false,
);
} on DioException catch (e) {
talker.error('[AppIntents] API error sending message', e);
return AppIntentResult.failed(
error: 'Failed to send message: ${e.message ?? 'Network error'}',
);
}
} catch (e, stack) {
talker.error('[AppIntents] Failed to send message', e, stack);
return AppIntentResult.failed(error: 'Failed to send message: $e');
}
}
Future<AppIntentResult> _handleReadMessagesIntent(
Map<String, dynamic> parameters,
) async {
try {
final channelId = parameters['channelId'] as String?;
final limitParam = parameters['limit'] as String?;
final limit = limitParam != null ? int.tryParse(limitParam) ?? 5 : 5;
if (channelId == null) {
throw ArgumentError('channelId is required');
}
if (limit < 1 || limit > 20) {
return AppIntentResult.failed(error: 'limit must be between 1 and 20');
}
talker.info('[AppIntents] Reading $limit messages from $channelId');
if (_dio == null) {
return AppIntentResult.failed(error: 'API client not initialized');
}
try {
final response = await _dio!.get(
'/messager/chat/$channelId/messages',
queryParameters: {'offset': 0, 'take': limit},
);
final messages = response.data as List;
if (messages.isEmpty) {
return AppIntentResult.successful(
value: 'No messages found in channel $channelId',
needsToContinueInApp: false,
);
}
final formattedMessages = messages
.map((msg) {
final senderName =
msg['sender']?['account']?['name'] ?? 'Unknown';
final messageContent = msg['content'] ?? '';
return '$senderName: $messageContent';
})
.join('\n');
talker.info('[AppIntents] Retrieved ${messages.length} messages');
return AppIntentResult.successful(
value: formattedMessages,
needsToContinueInApp: false,
);
} on DioException catch (e) {
talker.error('[AppIntents] API error reading messages', e);
return AppIntentResult.failed(
error: 'Failed to read messages: ${e.message ?? 'Network error'}',
);
}
} catch (e, stack) {
talker.error('[AppIntents] Failed to read messages', e, stack);
return AppIntentResult.failed(error: 'Failed to read messages: $e');
}
}
String _generateNonce() {
return '${DateTime.now().millisecondsSinceEpoch}-${DateTime.now().microsecondsSinceEpoch}';
}
void _logDonation(String eventName, Map<String, Object> parameters) {
try {
FirebaseAnalytics.instance.logEvent(
name: eventName,
parameters: parameters.isEmpty ? null : parameters,
);
} catch (e) {
talker.warning('[AppIntents] Failed to log analytics: $e');
}
}
Future<AppIntentResult> _handleCheckUnreadChatsIntent(
Map<String, dynamic> parameters,
) async {
try {
talker.info('[AppIntents] Checking unread chats count');
if (_dio == null) {
return AppIntentResult.failed(error: 'API client not initialized');
}
try {
final response = await _dio!.get('/messager/chat/unread');
final count = response.data as int? ?? 0;
String message;
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 AppIntentResult.successful(
value: message,
needsToContinueInApp: false,
);
} on DioException catch (e) {
talker.error('[AppIntents] API error checking unread chats', e);
return AppIntentResult.failed(
error:
'Failed to fetch unread chats: ${e.message ?? 'Network error'}',
);
}
} catch (e, stack) {
talker.error('[AppIntents] Failed to check unread chats', e, stack);
return AppIntentResult.failed(error: 'Failed to check unread chats: $e');
}
}
Future<AppIntentResult> _handleMarkNotificationsReadIntent(
Map<String, dynamic> parameters,
) async {
try {
talker.info('[AppIntents] Marking all notifications as read');
if (_dio == null) {
return AppIntentResult.failed(error: 'API client not initialized');
}
try {
await _dio!.post('/ring/notifications/all/read');
talker.info('[AppIntents] Notifications marked as read');
return AppIntentResult.successful(
value: 'All notifications marked as read',
needsToContinueInApp: false,
);
} on DioException catch (e) {
talker.error('[AppIntents] API error marking notifications read', e);
return AppIntentResult.failed(
error:
'Failed to mark notifications: ${e.message ?? 'Network error'}',
);
}
} catch (e, stack) {
talker.error('[AppIntents] Failed to mark notifications read', e, stack);
return AppIntentResult.failed(
error: 'Failed to mark notifications read: $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},
);
_logDonation('open_chat', {'channel_id': channelId});
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},
);
_logDonation('open_post', {'post_id': postId});
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},
);
_logDonation('open_compose', {});
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},
);
_logDonation('search_content', {'query': query});
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},
);
_logDonation('check_notifications', {});
talker.info('[AppIntents] Donated check_notifications intent');
} catch (e, stack) {
talker.error(
'[AppIntents] Failed to donate check_notifications',
e,
stack,
);
}
}
Future<void> donateSendMessage(String channelId, String content) async {
if (!_initialized) return;
try {
await FlutterAppIntentsService.donateIntentWithMetadata(
'send_message',
{'channelId': channelId, 'content': content},
relevanceScore: 0.8,
context: {'feature': 'chat', 'userAction': true},
);
_logDonation('send_message', {'channel_id': channelId});
talker.info('[AppIntents] Donated send_message intent');
} catch (e, stack) {
talker.error('[AppIntents] Failed to donate send_message', e, stack);
}
}
Future<void> donateReadMessages(String channelId) async {
if (!_initialized) return;
try {
await FlutterAppIntentsService.donateIntentWithMetadata(
'read_messages',
{'channelId': channelId},
relevanceScore: 0.7,
context: {'feature': 'chat', 'userAction': true},
);
_logDonation('read_messages', {'channel_id': channelId});
talker.info('[AppIntents] Donated read_messages intent');
} catch (e, stack) {
talker.error('[AppIntents] Failed to donate read_messages', e, stack);
}
}
Future<void> donateCheckUnreadChats() async {
if (!_initialized) return;
try {
await FlutterAppIntentsService.donateIntentWithMetadata(
'check_unread_chats',
{},
relevanceScore: 0.7,
context: {'feature': 'chat', 'userAction': true},
);
_logDonation('check_unread_chats', {});
talker.info('[AppIntents] Donated check_unread_chats intent');
} catch (e, stack) {
talker.error(
'[AppIntents] Failed to donate check_unread_chats',
e,
stack,
);
}
}
Future<void> donateMarkNotificationsRead() async {
if (!_initialized) return;
try {
await FlutterAppIntentsService.donateIntentWithMetadata(
'mark_notifications_read',
{},
relevanceScore: 0.6,
context: {'feature': 'notifications', 'userAction': true},
);
_logDonation('mark_notifications_read', {});
talker.info('[AppIntents] Donated mark_notifications_read intent');
} catch (e, stack) {
talker.error(
'[AppIntents] Failed to donate mark_notifications_read',
e,
stack,
);
}
}
}

View File

@@ -1,6 +1,5 @@
import 'dart:async'; import 'dart:async';
import 'dart:io'; import 'dart:io';
import 'package:just_audio/just_audio.dart';
import 'package:dio/dio.dart'; 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';
@@ -9,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 =
@@ -98,46 +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();
} }
if (settings.soundEffects) { playNotificationSfx(ref);
final player = AudioPlayer(); ref.read(notificationStateProvider.notifier).add(notification);
await player.setVolume(0.75);
await player.setAudioSource(AudioSource.asset('assets/audio/notification.mp3'));
await player.play();
player.dispose();
}
showTopSnackBar(
globalOverlay.currentState!,
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) {
@@ -228,4 +194,4 @@ Future<void> _putTokenToRemote(
"/ring/notifications/subscription", "/ring/notifications/subscription",
data: {"provider": provider, "device_token": token}, data: {"provider": provider, "device_token": token},
); );
} }

View File

@@ -1,27 +1,21 @@
import 'dart:async'; import 'dart:async';
import 'dart:io'; import 'dart:io';
import 'package:just_audio/just_audio.dart'; 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/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;
@@ -61,53 +55,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();
} }
if (settings.soundEffects) { playNotificationSfx(ref);
final player = AudioPlayer(); ref.read(notificationStateProvider.notifier).add(notification);
await player.setVolume(0.75);
await player.setAudioSource(AudioSource.asset('assets/audio/notification.mp3'));
await player.play();
player.dispose();
}
showTopSnackBar(
globalOverlay.currentState!,
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);
}
}
},
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(
@@ -221,4 +176,4 @@ Future<void> _putTokenToRemote(
"/ring/notifications/subscription", "/ring/notifications/subscription",
data: {"provider": provider, "device_token": token}, data: {"provider": provider, "device_token": token},
); );
} }

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;
@@ -378,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,6 +17,7 @@ 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/notification_overlay.dart';
import 'package:island/widgets/task_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';
@@ -125,6 +126,8 @@ class WindowScaffold extends HookConsumerWidget {
); );
useEffect(() { useEffect(() {
if (kIsWeb) return null;
hotKeyManager.register( hotKeyManager.register(
popHotKey, popHotKey,
keyDownHandler: (_) { keyDownHandler: (_) {
@@ -259,6 +262,7 @@ class WindowScaffold extends HookConsumerWidget {
), ),
_WebSocketIndicator(), _WebSocketIndicator(),
const TaskOverlay(), const TaskOverlay(),
const NotificationOverlay(),
if (showPalette.value) if (showPalette.value)
CommandPattleWidget(onDismiss: () => showPalette.value = false), CommandPattleWidget(onDismiss: () => showPalette.value = false),
], ],
@@ -272,6 +276,7 @@ class WindowScaffold extends HookConsumerWidget {
Positioned.fill(child: child), Positioned.fill(child: child),
_WebSocketIndicator(), _WebSocketIndicator(),
const TaskOverlay(), const TaskOverlay(),
const NotificationOverlay(),
if (showPalette.value) if (showPalette.value)
CommandPattleWidget(onDismiss: () => showPalette.value = false), CommandPattleWidget(onDismiss: () => showPalette.value = false),
], ],
@@ -632,4 +637,4 @@ class _WebSocketIndicator extends HookConsumerWidget {
), ),
); );
} }
} }

View File

@@ -162,36 +162,38 @@ class AppWrapper extends HookConsumerWidget {
(now.day >= 22 && now.day <= 28); (now.day >= 22 && now.day <= 28);
useEffect(() { useEffect(() {
final now = DateTime.now(); Future(() {
if (doesShowSnow) { final now = DateTime.now();
isShowSnow.value = true; if (doesShowSnow) {
Future.delayed(const Duration(seconds: 60), () { isShowSnow.value = true;
if (!context.mounted) return; Future.delayed(const Duration(seconds: 60), () {
isShowSnow.value = false;
Future.delayed(const Duration(seconds: 3), () {
if (!context.mounted) return; if (!context.mounted) return;
isSnowGone.value = true; isShowSnow.value = false;
Future.delayed(const Duration(seconds: 3), () {
if (!context.mounted) return;
isSnowGone.value = true;
});
}); });
});
}
if (settings.firstLaunchAt == null) {
settingsNotifier.setFirstLaunchAt(now.toIso8601String());
} else if (!settings.askedReview) {
final launchAt = DateTime.parse(settings.firstLaunchAt!);
final daysSinceFirstLaunch = now.difference(launchAt).inDays;
if (daysSinceFirstLaunch >= 3 &&
!kIsWeb &&
(Platform.isAndroid || Platform.isIOS || Platform.isMacOS)) {
final InAppReview inAppReview = InAppReview.instance;
Future(() async {
if (await inAppReview.isAvailable()) {
inAppReview.requestReview();
}
});
settingsNotifier.setAskedReview(true);
} }
}
if (settings.firstLaunchAt == null) {
settingsNotifier.setFirstLaunchAt(now.toIso8601String());
} else if (!settings.askedReview) {
final launchAt = DateTime.parse(settings.firstLaunchAt!);
final daysSinceFirstLaunch = now.difference(launchAt).inDays;
if (daysSinceFirstLaunch >= 3 &&
!kIsWeb &&
(Platform.isAndroid || Platform.isIOS || Platform.isMacOS)) {
final InAppReview inAppReview = InAppReview.instance;
Future(() async {
if (await inAppReview.isAvailable()) {
inAppReview.requestReview();
}
});
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,
), ),
]); ]);

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

@@ -93,6 +93,9 @@ class AttachmentPreview extends HookConsumerWidget {
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,
@@ -105,6 +108,9 @@ class AttachmentPreview extends HookConsumerWidget {
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
@@ -453,13 +459,55 @@ class AttachmentPreview extends HookConsumerWidget {
), ),
), ),
), ),
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 = ClipRRect( final contentWidget = Container(
borderRadius: BorderRadius.circular(8), decoration: BoxDecoration(
child: Container(
color: Theme.of(context).colorScheme.surfaceContainer, 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( child: Stack(
children: [ children: [
if (ratio != null) if (ratio != null)
@@ -468,7 +516,7 @@ class AttachmentPreview extends HookConsumerWidget {
child: innerContentWidget, child: innerContentWidget,
).center() ).center()
else else
IntrinsicHeight(child: innerContentWidget), IntrinsicHeight(child: innerContentWidget).center(),
Row( Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
@@ -641,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
@@ -164,4 +175,4 @@ class _UniversalAudioState extends ConsumerState<UniversalAudio> {
).padding(horizontal: 24, vertical: 16), ).padding(horizontal: 24, vertical: 16),
); );
} }
} }

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,15 +158,14 @@ 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, style: theme.textTheme.bodyMedium?.copyWith(
style: theme.textTheme.bodyMedium?.copyWith( fontWeight: FontWeight.w500,
fontWeight: FontWeight.w500, ),
), ).bold(),
).bold(),
subtitle: Text( subtitle: Text(
'${entry.value}'.isNotEmpty '${entry.value}'.isNotEmpty
? '${entry.value}' ? '${entry.value}'
@@ -227,13 +208,12 @@ 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, ),
), ).bold(),
).bold(),
subtitle: Text( subtitle: Text(
jsonEncode(entry.value), jsonEncode(entry.value),
style: theme.textTheme.bodyMedium, style: theme.textTheme.bodyMedium,
@@ -276,13 +256,12 @@ 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, ),
), ).bold(),
).bold(),
subtitle: Text( subtitle: Text(
jsonEncode(entry.value), jsonEncode(entry.value),
style: theme.textTheme.bodyMedium, style: theme.textTheme.bodyMedium,

View File

@@ -1,11 +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_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;
@@ -28,11 +33,19 @@ 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 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(() { useEffect(() {
DefaultCacheManager().getFileFromCache(uri).then((fileInfo) { DefaultCacheManager().getFileFromCache(uri).then((fileInfo) {
isCached.value = fileInfo != null; isCached.value = fileInfo != null;
@@ -73,6 +86,7 @@ class UniversalImage extends HookWidget {
else if (isCached.value!) else if (isCached.value!)
CachedNetworkImage( CachedNetworkImage(
imageUrl: uri, imageUrl: uri,
httpHeaders: httpHeaders,
fit: fit, fit: fit,
width: width, width: width,
height: height, height: height,
@@ -84,17 +98,18 @@ class UniversalImage extends HookWidget {
width: width, width: width,
height: height, height: height,
), ),
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(), ),
) )
else else
CachedNetworkImage( CachedNetworkImage(
imageUrl: uri, imageUrl: uri,
httpHeaders: httpHeaders,
fit: fit, fit: fit,
width: width, width: width,
height: height, height: height,
@@ -123,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(), ),
), ),
], ],
), ),
@@ -137,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;
@@ -172,4 +316,4 @@ class AnimatedCircularProgressIndicator extends HookWidget {
backgroundColor: Colors.transparent, backgroundColor: Colors.transparent,
); );
} }
} }

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
@@ -61,4 +70,4 @@ class _UniversalVideoState extends ConsumerState<UniversalVideo> {
: MaterialDesktopVideoControls, : MaterialDesktopVideoControls,
); );
} }
} }

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: (_) {

File diff suppressed because it is too large Load Diff

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.
@@ -102,94 +107,256 @@ 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 ValueListenableBuilder<List<UniversalFile>>( return Padding(
valueListenable: state.attachments, padding: padding ?? EdgeInsets.all(16),
builder: (context, attachments, _) { child: ValueListenableBuilder<String?>(
if (attachments.isEmpty) return const SizedBox.shrink(); valueListenable: state.thumbnailId,
return Theme( builder: (context, thumbnailId, _) {
data: Theme.of(context).copyWith(dividerColor: Colors.transparent), return ValueListenableBuilder<List<UniversalFile>>(
child: ExpansionTile( valueListenable: state.attachments,
initiallyExpanded: true, builder: (context, attachments, _) {
title: Column( return HookBuilder(
crossAxisAlignment: CrossAxisAlignment.start, builder: (context) {
children: [ final isDragging = useState(false);
Text('attachments'), return DropTarget(
Text( onDragDone: (details) async =>
'articleAttachmentHint', await _handleDroppedFiles(details, state),
style: Theme.of(context).textTheme.bodySmall?.copyWith( onDragEntered: (details) => isDragging.value = true,
color: Theme.of(context).colorScheme.onSurfaceVariant, onDragExited: (details) => isDragging.value = false,
), child: AnimatedContainer(
), duration: const Duration(milliseconds: 200),
], curve: Curves.easeOut,
), decoration: isDragging.value ? BoxDecoration(
children: [ border: Border.all(
ValueListenableBuilder<Map<int, double?>>( color: Theme.of(context).colorScheme.primary,
valueListenable: state.attachmentProgress, width: 2,
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],
isUploading: progressMap.containsKey(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(
ref,
state,
idx,
poolId: config.poolId,
);
}
},
onUpdate: (value) => ComposeLogic.updateAttachment(
state,
value,
idx,
),
onDelete: () =>
ComposeLogic.deleteAttachment(ref, state, idx),
onInsert: () =>
ComposeLogic.insertAttachment(ref, state, idx),
),
), ),
], 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: [
Icon(
Symbols.upload,
size: 48,
color: Theme.of(
context,
).colorScheme.onSurfaceVariant,
),
const SizedBox(height: 16),
Text(
'dropFilesHere',
style: Theme.of(context).textTheme.titleMedium
?.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(),
],
),
)
: 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++)
_AnimatedAttachmentItem(
index: idx,
item: attachments[idx],
progress: progressMap[idx],
isUploading: progressMap.containsKey(idx),
thumbnailId: thumbnailId,
onSetThumbnail: (id) =>
ComposeLogic.setThumbnail(state, id),
onRequestUpload: () async {
final config =
await showModalBottomSheet<
AttachmentUploadConfig
>(
context: context,
isScrollControlled: true,
useRootNavigator: true,
builder: (context) => AttachmentUploaderSheet(
ref: ref,
state: state,
index: idx,
),
);
if (config != null) {
await ComposeLogic.uploadAttachment(
ref,
state,
idx,
poolId: config.poolId,
);
}
},
onUpdate: (value) =>
ComposeLogic.updateAttachment(state, value, 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,11 +121,10 @@ 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(),
publisher: composeState.currentPublisher.value!, publisher: composeState.currentPublisher.value!,
updatedAt: DateTime.now(), updatedAt: DateTime.now(),
); );
@@ -218,27 +217,25 @@ class PostComposeCard extends HookConsumerWidget {
IconButton( IconButton(
onPressed: onPressed:
(composeState.submitting.value || (composeState.submitting.value ||
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, child: const CircularProgressIndicator(
child: const CircularProgressIndicator( strokeWidth: 2,
strokeWidth: 2,
),
)
: Icon(
originalPost != null
? Symbols.edit
: Symbols.upload,
), ),
tooltip: )
originalPost != null : Icon(
? 'postUpdate'.tr() originalPost != null
: 'postPublish'.tr(), ? Symbols.edit
: Symbols.upload,
),
tooltip: originalPost != null
? 'postUpdate'.tr()
: 'postPublish'.tr(),
visualDensity: const VisualDensity( visualDensity: const VisualDensity(
horizontal: -4, horizontal: -4,
vertical: -2, vertical: -2,
@@ -268,13 +265,10 @@ 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: PostItem(item: post)),
child: SingleChildScrollView( ),
child: PostItem(item: post),
),
),
); );
}, },
), ),
@@ -283,16 +277,15 @@ 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, context,
context, originalPost: originalPost,
originalPost: originalPost, repliedPost: repliedPost,
repliedPost: repliedPost, forwardedPost: forwardedPost,
forwardedPost: forwardedPost, ),
),
child: SingleChildScrollView( child: SingleChildScrollView(
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
child: ConstrainedBox( child: ConstrainedBox(
@@ -304,17 +297,16 @@ 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 ?.id,
?.id,
radius: 20, radius: 20,
fallbackIcon: fallbackIcon:
composeState.currentPublisher.value == null composeState.currentPublisher.value == null
? Symbols.question_mark ? Symbols.question_mark
: null, : null,
), ),
onTap: () { onTap: () {
if (composeState.currentPublisher.value == null) { if (composeState.currentPublisher.value == null) {
@@ -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,9 +362,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 =
@@ -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,19 +406,15 @@ class PostComposeCard extends HookConsumerWidget {
), ),
// Bottom toolbar // Bottom toolbar
SizedBox( ClipRRect(
height: 65, borderRadius: const BorderRadius.only(
child: ClipRRect( bottomLeft: Radius.circular(8),
borderRadius: const BorderRadius.only( bottomRight: Radius.circular(8),
bottomLeft: Radius.circular(8), ),
bottomRight: Radius.circular(8), child: ComposeToolbar(
), state: composeState,
child: ComposeToolbar( originalPost: originalPost,
state: composeState, useSafeArea: isContained,
originalPost: originalPost,
isCompact: true,
useSafeArea: isContained,
),
), ),
), ),
], ],

View File

@@ -139,364 +139,350 @@ class ComposeSettingsSheet extends HookConsumerWidget {
final tagInputController = useTextEditingController(); final tagInputController = useTextEditingController();
return SheetScaffold( return SingleChildScrollView(
titleText: 'postSettings'.tr(), padding: const EdgeInsets.all(16),
heightFactor: 0.6, child: Column(
child: SingleChildScrollView( crossAxisAlignment: CrossAxisAlignment.start,
padding: const EdgeInsets.all(16), spacing: 16,
child: Column( children: [
crossAxisAlignment: CrossAxisAlignment.start, // Slug field
spacing: 16, TextField(
children: [ controller: state.slugController,
// Slug field decoration: InputDecoration(
TextField( labelText: 'postSlug'.tr(),
controller: state.slugController, hintText: 'postSlugHint'.tr(),
decoration: InputDecoration( contentPadding: const EdgeInsets.symmetric(
labelText: 'postSlug'.tr(), vertical: 9,
hintText: 'postSlugHint'.tr(), horizontal: 16,
contentPadding: const EdgeInsets.symmetric(
vertical: 9,
horizontal: 16,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
), ),
onTapOutside: (_) => border: OutlineInputBorder(
FocusManager.instance.primaryFocus?.unfocus(),
),
// Tags field
Container(
decoration: BoxDecoration(
border: Border.all(
color: Theme.of(context).colorScheme.outline,
width: 1,
),
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
), ),
padding: const EdgeInsets.all(16), ),
child: Column( onTapOutside: (_) => FocusManager.instance.primaryFocus?.unfocus(),
crossAxisAlignment: CrossAxisAlignment.start, ),
spacing: 12,
children: [ // Tags field
Text( Container(
'tags'.tr(), decoration: BoxDecoration(
style: Theme.of(context).textTheme.labelLarge, border: Border.all(
color: Theme.of(context).colorScheme.outline,
width: 1,
),
borderRadius: BorderRadius.circular(12),
),
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
spacing: 12,
children: [
Text(
'tags'.tr(),
style: Theme.of(context).textTheme.labelLarge,
),
// Existing tags display
if (currentTags.isNotEmpty)
Wrap(
spacing: 8,
runSpacing: 8,
children: currentTags.map((tag) {
return Container(
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.primary,
borderRadius: BorderRadius.circular(16),
),
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 6,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'#$tag',
style: TextStyle(
color: Theme.of(context).colorScheme.onPrimary,
fontSize: 14,
),
),
const Gap(4),
InkWell(
onTap: () {
final newTags = List<String>.from(
state.tags.value,
)..remove(tag);
state.tags.value = newTags;
},
child: Icon(
Icons.close,
size: 16,
color: Theme.of(context).colorScheme.onPrimary,
),
),
],
),
);
}).toList(),
), ),
// Existing tags display // Tag input with autocomplete
if (currentTags.isNotEmpty) TypeAheadField<SnPostTag>(
Wrap( controller: tagInputController,
spacing: 8, builder: (context, controller, focusNode) {
runSpacing: 8, return TextField(
children: currentTags.map((tag) { controller: controller,
return Container( focusNode: focusNode,
decoration: InputDecoration(
hintText: 'addTag'.tr(),
border: InputBorder.none,
isCollapsed: true,
contentPadding: EdgeInsets.zero,
),
onSubmitted: (value) {
state.tags.value = [...state.tags.value, value];
controller.clear();
},
);
},
suggestionsCallback: (pattern) =>
_fetchTagSuggestions(pattern, ref),
itemBuilder: (context, suggestion) {
return ListTile(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(8)),
),
title: Text('#${suggestion.slug}'),
subtitle: Text('${suggestion.usage} posts'),
dense: true,
);
},
onSelected: (suggestion) {
if (!state.tags.value.contains(suggestion.slug)) {
state.tags.value = [...state.tags.value, suggestion.slug];
}
tagInputController.clear();
},
direction: VerticalDirection.down,
hideOnEmpty: true,
hideOnLoading: true,
debounceDuration: const Duration(milliseconds: 300),
),
],
),
),
// Categories field
DropdownButtonFormField2<SnPostCategory>(
isExpanded: true,
decoration: InputDecoration(
contentPadding: const EdgeInsets.symmetric(vertical: 9),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
),
hint: Text('categories'.tr(), style: TextStyle(fontSize: 15)),
items: (postCategories.value?.items ?? <SnPostCategory>[]).map((
item,
) {
return DropdownMenuItem(
value: item,
enabled: false,
child: StatefulBuilder(
builder: (context, menuSetState) {
final isSelected = state.categories.value.contains(item);
return InkWell(
onTap: () {
isSelected
? state.categories.value = state.categories.value
.where((e) => e != item)
.toList()
: state.categories.value = [
...state.categories.value,
item,
];
menuSetState(() {});
},
child: Container(
height: double.infinity,
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Row(
children: [
if (isSelected)
const Icon(Icons.check_box_outlined)
else
const Icon(Icons.check_box_outline_blank),
const SizedBox(width: 16),
Expanded(
child: Text(
item.categoryDisplayTitle,
style: const TextStyle(fontSize: 14),
),
),
],
),
),
);
},
),
);
}).toList(),
value: currentCategories.isEmpty ? null : currentCategories.last,
onChanged: (_) {},
selectedItemBuilder: (context) {
return (postCategories.value?.items ?? []).map((item) {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
for (final category in currentCategories)
Container(
decoration: BoxDecoration( decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: Theme.of(context).colorScheme.primary, color: Theme.of(context).colorScheme.primary,
borderRadius: BorderRadius.circular(16),
), ),
padding: const EdgeInsets.symmetric( padding: const EdgeInsets.symmetric(
horizontal: 12, horizontal: 12,
vertical: 6, vertical: 4,
), ),
child: Row( margin: const EdgeInsets.only(right: 4),
mainAxisSize: MainAxisSize.min, child: Text(
children: [ category.categoryDisplayTitle,
Text( style: TextStyle(
'#$tag', color: Theme.of(context).colorScheme.onPrimary,
style: TextStyle( fontSize: 13,
color: Theme.of( ),
context,
).colorScheme.onPrimary,
fontSize: 14,
),
),
const Gap(4),
InkWell(
onTap: () {
final newTags = List<String>.from(
state.tags.value,
)..remove(tag);
state.tags.value = newTags;
},
child: Icon(
Icons.close,
size: 16,
color: Theme.of(
context,
).colorScheme.onPrimary,
),
),
],
),
);
}).toList(),
),
// Tag input with autocomplete
TypeAheadField<SnPostTag>(
controller: tagInputController,
builder: (context, controller, focusNode) {
return TextField(
controller: controller,
focusNode: focusNode,
decoration: InputDecoration(
hintText: 'addTag'.tr(),
border: InputBorder.none,
isCollapsed: true,
contentPadding: EdgeInsets.zero,
),
onSubmitted: (value) {
state.tags.value = [...state.tags.value, value];
controller.clear();
},
);
},
suggestionsCallback: (pattern) =>
_fetchTagSuggestions(pattern, ref),
itemBuilder: (context, suggestion) {
return ListTile(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(8)),
),
title: Text('#${suggestion.slug}'),
subtitle: Text('${suggestion.usage} posts'),
dense: true,
);
},
onSelected: (suggestion) {
if (!state.tags.value.contains(suggestion.slug)) {
state.tags.value = [
...state.tags.value,
suggestion.slug,
];
}
tagInputController.clear();
},
direction: VerticalDirection.down,
hideOnEmpty: true,
hideOnLoading: true,
debounceDuration: const Duration(milliseconds: 300),
),
],
),
),
// Categories field
DropdownButtonFormField2<SnPostCategory>(
isExpanded: true,
decoration: InputDecoration(
contentPadding: const EdgeInsets.symmetric(vertical: 9),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
),
hint: Text('categories'.tr(), style: TextStyle(fontSize: 15)),
items: (postCategories.value?.items ?? <SnPostCategory>[]).map((
item,
) {
return DropdownMenuItem(
value: item,
enabled: false,
child: StatefulBuilder(
builder: (context, menuSetState) {
final isSelected = state.categories.value.contains(item);
return InkWell(
onTap: () {
isSelected
? state.categories.value = state.categories.value
.where((e) => e != item)
.toList()
: state.categories.value = [
...state.categories.value,
item,
];
menuSetState(() {});
},
child: Container(
height: double.infinity,
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Row(
children: [
if (isSelected)
const Icon(Icons.check_box_outlined)
else
const Icon(Icons.check_box_outline_blank),
const SizedBox(width: 16),
Expanded(
child: Text(
item.categoryDisplayTitle,
style: const TextStyle(fontSize: 14),
),
),
],
), ),
), ),
); ],
},
), ),
); );
}).toList(), }).toList();
value: currentCategories.isEmpty ? null : currentCategories.last, },
onChanged: (_) {}, buttonStyleData: const ButtonStyleData(
selectedItemBuilder: (context) { padding: EdgeInsets.only(left: 16, right: 8),
return (postCategories.value?.items ?? []).map((item) { height: 38,
return SingleChildScrollView( ),
scrollDirection: Axis.horizontal, menuItemStyleData: const MenuItemStyleData(
child: Row( height: 38,
children: [ padding: EdgeInsets.zero,
for (final category in currentCategories) ),
Container( ),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20), // Realm selection
color: Theme.of(context).colorScheme.primary, DropdownButtonFormField2<SnRealm?>(
), isExpanded: true,
padding: const EdgeInsets.symmetric( decoration: InputDecoration(
horizontal: 12, contentPadding: const EdgeInsets.symmetric(vertical: 9),
vertical: 4, border: OutlineInputBorder(
), borderRadius: BorderRadius.circular(12),
margin: const EdgeInsets.only(right: 4),
child: Text(
category.categoryDisplayTitle,
style: TextStyle(
color: Theme.of(context).colorScheme.onPrimary,
fontSize: 13,
),
),
),
],
),
);
}).toList();
},
buttonStyleData: const ButtonStyleData(
padding: EdgeInsets.only(left: 16, right: 8),
height: 38,
),
menuItemStyleData: const MenuItemStyleData(
height: 38,
padding: EdgeInsets.zero,
), ),
), ),
hint: Text('realm'.tr(), style: const TextStyle(fontSize: 15)),
// Realm selection items: [
DropdownButtonFormField2<SnRealm?>( DropdownMenuItem<SnRealm?>(
isExpanded: true, value: null,
decoration: InputDecoration( child: Row(
contentPadding: const EdgeInsets.symmetric(vertical: 9), children: [
border: OutlineInputBorder( const CircleAvatar(
borderRadius: BorderRadius.circular(12), radius: 16,
), child: Icon(Symbols.link_off, fill: 1),
),
const SizedBox(width: 12),
Text('postUnlinkRealm').tr(),
],
).padding(left: 16, right: 8),
), ),
hint: Text('realm'.tr(), style: const TextStyle(fontSize: 15)), // Include current realm if it's not null and not in joined realms
items: [ if (currentRealm != null &&
!(userRealms.value ?? []).any((r) => r.id == currentRealm.id))
DropdownMenuItem<SnRealm?>( DropdownMenuItem<SnRealm?>(
value: null, value: currentRealm,
child: Row( child: Row(
children: [ children: [
const CircleAvatar( ProfilePictureWidget(
file: currentRealm.picture,
fallbackIcon: Symbols.workspaces,
radius: 16, radius: 16,
child: Icon(Symbols.link_off, fill: 1),
), ),
const SizedBox(width: 12), const SizedBox(width: 12),
Text('postUnlinkRealm').tr(), Text(currentRealm.name),
], ],
).padding(left: 16, right: 8), ).padding(left: 16, right: 8),
), ),
// Include current realm if it's not null and not in joined realms if (userRealms.hasValue)
if (currentRealm != null && ...(userRealms.value ?? []).map(
!(userRealms.value ?? []).any( (realm) => DropdownMenuItem<SnRealm?>(
(r) => r.id == currentRealm.id, value: realm,
))
DropdownMenuItem<SnRealm?>(
value: currentRealm,
child: Row( child: Row(
children: [ children: [
ProfilePictureWidget( ProfilePictureWidget(
file: currentRealm.picture, file: realm.picture,
fallbackIcon: Symbols.workspaces, fallbackIcon: Symbols.workspaces,
radius: 16, radius: 16,
), ),
const SizedBox(width: 12), const SizedBox(width: 12),
Text(currentRealm.name), Text(realm.name),
], ],
).padding(left: 16, right: 8), ).padding(left: 16, right: 8),
), ),
if (userRealms.hasValue) ),
...(userRealms.value ?? []).map( ],
(realm) => DropdownMenuItem<SnRealm?>( value: currentRealm,
value: realm, onChanged: (value) {
child: Row( state.realm.value = value;
children: [ },
ProfilePictureWidget( selectedItemBuilder: (context) {
file: realm.picture, return (userRealms.value ?? []).map((_) {
fallbackIcon: Symbols.workspaces, return Row(
radius: 16, children: [
), if (currentRealm == null)
const SizedBox(width: 12), const CircleAvatar(
Text(realm.name), radius: 16,
], child: Icon(Symbols.link_off, fill: 1),
).padding(left: 16, right: 8), )
), else
), ProfilePictureWidget(
], file: currentRealm.picture,
value: currentRealm, fallbackIcon: Symbols.workspaces,
onChanged: (value) { radius: 16,
state.realm.value = value; ),
}, const SizedBox(width: 12),
selectedItemBuilder: (context) { Text(currentRealm?.name ?? 'postUnlinkRealm'.tr()),
return (userRealms.value ?? []).map((_) { ],
return Row( );
children: [ }).toList();
if (currentRealm == null) },
const CircleAvatar( buttonStyleData: const ButtonStyleData(
radius: 16, padding: EdgeInsets.only(left: 16, right: 8),
child: Icon(Symbols.link_off, fill: 1), height: 40,
)
else
ProfilePictureWidget(
file: currentRealm.picture,
fallbackIcon: Symbols.workspaces,
radius: 16,
),
const SizedBox(width: 12),
Text(currentRealm?.name ?? 'postUnlinkRealm'.tr()),
],
);
}).toList();
},
buttonStyleData: const ButtonStyleData(
padding: EdgeInsets.only(left: 16, right: 8),
height: 40,
),
menuItemStyleData: const MenuItemStyleData(
height: 56,
padding: EdgeInsets.zero,
),
), ),
menuItemStyleData: const MenuItemStyleData(
height: 56,
padding: EdgeInsets.zero,
),
),
// Visibility setting // Visibility setting
Container( Container(
decoration: BoxDecoration( decoration: BoxDecoration(
border: Border.all(color: colorScheme.outline, width: 1), border: Border.all(color: colorScheme.outline, width: 1),
borderRadius: BorderRadius.circular(12),
),
child: ListTile(
leading: Icon(getVisibilityIcon(currentVisibility)),
title: Text('postVisibility'.tr()),
subtitle: Text(getVisibilityText(currentVisibility).tr()),
trailing: const Icon(Symbols.chevron_right),
onTap: showVisibilitySheet,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
), ),
child: ListTile( contentPadding: const EdgeInsets.symmetric(
leading: Icon(getVisibilityIcon(currentVisibility)), horizontal: 16,
title: Text('postVisibility'.tr()), vertical: 8,
subtitle: Text(getVisibilityText(currentVisibility).tr()),
trailing: const Icon(Symbols.chevron_right),
onTap: showVisibilitySheet,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 8,
),
), ),
), ),
], ),
), ],
), ),
); );
} }

View File

@@ -49,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({
@@ -69,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();
@@ -121,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
@@ -156,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>>(
@@ -183,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,
); );
} }
@@ -230,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,
@@ -302,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,
@@ -612,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,
@@ -720,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(),
}; };
@@ -811,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,
), ),
]; ];
@@ -867,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,18 +70,17 @@ 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) { state.titleController.text = draft.title ?? '';
state.titleController.text = draft.title ?? ''; state.descriptionController.text = draft.description ?? '';
state.descriptionController.text = draft.description ?? ''; state.contentController.text = draft.content ?? '';
state.contentController.text = draft.content ?? ''; state.visibility.value = draft.visibility;
state.visibility.value = draft.visibility; }
} },
}, ),
),
); );
} }
@@ -96,252 +93,111 @@ 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:
children: [ Row(
Expanded( children: [
child: SingleChildScrollView( Expanded(
scrollDirection: Axis.horizontal, child: SingleChildScrollView(
child: Row( scrollDirection: Axis.horizontal,
children: [ child: Row(
UploadMenu(items: uploadMenuItems, isCompact: isCompact), children: [
IconButton( UploadMenu(items: uploadMenuItems),
onPressed: linkAttachment, IconButton(
icon: const Icon(Symbols.attach_file), onPressed: linkAttachment,
tooltip: 'linkAttachment'.tr(), icon: const Icon(Symbols.attach_file),
color: colorScheme.primary, tooltip: 'linkAttachment'.tr(),
),
// 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, color: colorScheme.primary,
style: ButtonStyle( ),
backgroundColor: WidgetStatePropertyAll( // Poll button with visual state when a poll is linked
state.pollId.value != null ListenableBuilder(
? colorScheme.primary.withOpacity(0.15) listenable: state.pollId,
: null, builder: (context, _) {
), return IconButton(
), onPressed: pickPoll,
); icon: const Icon(Symbols.how_to_vote),
}, tooltip: 'poll'.tr(),
color: colorScheme.primary,
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,
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,
style: ButtonStyle(
backgroundColor: WidgetStatePropertyAll(
state.embedView.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,
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,
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),
color: colorScheme.primary,
onPressed: showDraftManager,
tooltip: 'drafts'.tr(),
)
else if (originalPost == null)
IconButton(
icon: const Icon(Symbols.save),
color: colorScheme.primary,
onPressed: saveDraft,
onLongPress: showDraftManager,
tooltip: 'saveDraft'.tr(),
),
],
).padding(
bottom: MediaQuery.of(context).padding.bottom + 16,
horizontal: 16,
top: 8,
), ),
if (originalPost == null && state.isEmpty)
IconButton(
icon: const Icon(Symbols.draft),
color: colorScheme.primary,
onPressed: showDraftManager,
tooltip: 'drafts'.tr(),
)
else if (originalPost == null)
IconButton(
icon: const Icon(Symbols.save),
color: colorScheme.primary,
onPressed: saveDraft,
onLongPress: showDraftManager,
tooltip: 'saveDraft'.tr(),
),
],
).padding(
bottom: MediaQuery.of(context).padding.bottom + 16,
horizontal: 16,
top: 8,
),
), ),
), ),
); );

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,

View File

@@ -8,6 +8,7 @@ import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:html2md/html2md.dart' as html2md; import 'package:html2md/html2md.dart' as html2md;
import 'package:island/models/account.dart'; import 'package:island/models/account.dart';
import 'package:island/models/file.dart';
import 'package:island/models/post.dart'; import 'package:island/models/post.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';
@@ -1030,6 +1031,16 @@ class PostBody extends ConsumerWidget {
); );
} }
SnCloudFile? getThumbnailAttachment() {
final thumbnailId = item.meta?['thumbnail'] as String?;
if (thumbnailId == null) return null;
try {
return item.attachments.firstWhere((a) => a.id == thumbnailId);
} catch (_) {
return null;
}
}
return Column( return Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
@@ -1042,7 +1053,6 @@ class PostBody extends ConsumerWidget {
), ),
borderRadius: const BorderRadius.all(Radius.circular(8)), borderRadius: const BorderRadius.all(Radius.circular(8)),
), ),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
margin: EdgeInsets.only( margin: EdgeInsets.only(
top: 4, top: 4,
left: renderingPadding.horizontal, left: renderingPadding.horizontal,
@@ -1052,33 +1062,38 @@ class PostBody extends ConsumerWidget {
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
Align( if (getThumbnailAttachment() != null)
alignment: Alignment.centerLeft, ClipRRect(
child: Badge( borderRadius: const BorderRadius.vertical(
label: const Text('postArticle').tr(), top: Radius.circular(8),
backgroundColor: Theme.of(context).colorScheme.primary,
textColor: Theme.of(context).colorScheme.onPrimary,
),
),
const Gap(4),
if (item.title != null)
Text(
item.title!,
style: Theme.of(context).textTheme.titleMedium!.copyWith(
fontWeight: FontWeight.bold,
), ),
child: CloudFileWidget(item: getThumbnailAttachment()!),
), ),
if (item.description != null) Column(
Text( crossAxisAlignment: CrossAxisAlignment.stretch,
item.description!, children: [
style: Theme.of(context).textTheme.bodyMedium, Align(
) alignment: Alignment.centerLeft,
else child: Badge(
MarkdownTextContent( label: const Text('postArticle').tr(),
content: '${_convertContentToMarkdown(item)}...', backgroundColor: Theme.of(context).colorScheme.primary,
attachments: item.attachments, textColor: Theme.of(context).colorScheme.onPrimary,
noMentionChip: item.fediverseUri != null, ),
), ),
const Gap(4),
if (item.title != null)
Text(
item.title!,
style: Theme.of(context).textTheme.titleMedium!
.copyWith(fontWeight: FontWeight.bold),
),
if (item.description?.isNotEmpty ?? false)
Text(
item.description!,
style: Theme.of(context).textTheme.bodyMedium,
),
],
).padding(horizontal: 16, vertical: 12),
], ],
), ),
) )

View File

@@ -33,7 +33,6 @@ import media_kit_libs_macos_video
import media_kit_video import media_kit_video
import package_info_plus import package_info_plus
import pasteboard import pasteboard
import path_provider_foundation
import protocol_handler_macos import protocol_handler_macos
import record_macos import record_macos
import screen_retriever_macos import screen_retriever_macos
@@ -78,7 +77,6 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
MediaKitVideoPlugin.register(with: registry.registrar(forPlugin: "MediaKitVideoPlugin")) MediaKitVideoPlugin.register(with: registry.registrar(forPlugin: "MediaKitVideoPlugin"))
FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin")) FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin"))
PasteboardPlugin.register(with: registry.registrar(forPlugin: "PasteboardPlugin")) PasteboardPlugin.register(with: registry.registrar(forPlugin: "PasteboardPlugin"))
PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin"))
ProtocolHandlerMacosPlugin.register(with: registry.registrar(forPlugin: "ProtocolHandlerMacosPlugin")) ProtocolHandlerMacosPlugin.register(with: registry.registrar(forPlugin: "ProtocolHandlerMacosPlugin"))
RecordMacOsPlugin.register(with: registry.registrar(forPlugin: "RecordMacOsPlugin")) RecordMacOsPlugin.register(with: registry.registrar(forPlugin: "RecordMacOsPlugin"))
ScreenRetrieverMacosPlugin.register(with: registry.registrar(forPlugin: "ScreenRetrieverMacosPlugin")) ScreenRetrieverMacosPlugin.register(with: registry.registrar(forPlugin: "ScreenRetrieverMacosPlugin"))

View File

@@ -204,9 +204,6 @@ PODS:
- FlutterMacOS - FlutterMacOS
- pasteboard (0.0.1): - pasteboard (0.0.1):
- FlutterMacOS - FlutterMacOS
- path_provider_foundation (0.0.1):
- Flutter
- FlutterMacOS
- PromisesObjC (2.4.0) - PromisesObjC (2.4.0)
- PromisesSwift (2.4.0): - PromisesSwift (2.4.0):
- PromisesObjC (= 2.4.0) - PromisesObjC (= 2.4.0)
@@ -296,7 +293,6 @@ DEPENDENCIES:
- media_kit_video (from `Flutter/ephemeral/.symlinks/plugins/media_kit_video/macos`) - media_kit_video (from `Flutter/ephemeral/.symlinks/plugins/media_kit_video/macos`)
- package_info_plus (from `Flutter/ephemeral/.symlinks/plugins/package_info_plus/macos`) - package_info_plus (from `Flutter/ephemeral/.symlinks/plugins/package_info_plus/macos`)
- pasteboard (from `Flutter/ephemeral/.symlinks/plugins/pasteboard/macos`) - pasteboard (from `Flutter/ephemeral/.symlinks/plugins/pasteboard/macos`)
- path_provider_foundation (from `Flutter/ephemeral/.symlinks/plugins/path_provider_foundation/darwin`)
- protocol_handler_macos (from `Flutter/ephemeral/.symlinks/plugins/protocol_handler_macos/macos`) - protocol_handler_macos (from `Flutter/ephemeral/.symlinks/plugins/protocol_handler_macos/macos`)
- record_macos (from `Flutter/ephemeral/.symlinks/plugins/record_macos/macos`) - record_macos (from `Flutter/ephemeral/.symlinks/plugins/record_macos/macos`)
- screen_retriever_macos (from `Flutter/ephemeral/.symlinks/plugins/screen_retriever_macos/macos`) - screen_retriever_macos (from `Flutter/ephemeral/.symlinks/plugins/screen_retriever_macos/macos`)
@@ -397,8 +393,6 @@ EXTERNAL SOURCES:
:path: Flutter/ephemeral/.symlinks/plugins/package_info_plus/macos :path: Flutter/ephemeral/.symlinks/plugins/package_info_plus/macos
pasteboard: pasteboard:
:path: Flutter/ephemeral/.symlinks/plugins/pasteboard/macos :path: Flutter/ephemeral/.symlinks/plugins/pasteboard/macos
path_provider_foundation:
:path: Flutter/ephemeral/.symlinks/plugins/path_provider_foundation/darwin
protocol_handler_macos: protocol_handler_macos:
:path: Flutter/ephemeral/.symlinks/plugins/protocol_handler_macos/macos :path: Flutter/ephemeral/.symlinks/plugins/protocol_handler_macos/macos
record_macos: record_macos:
@@ -476,7 +470,6 @@ SPEC CHECKSUMS:
OrderedSet: e539b66b644ff081c73a262d24ad552a69be3a94 OrderedSet: e539b66b644ff081c73a262d24ad552a69be3a94
package_info_plus: f0052d280d17aa382b932f399edf32507174e870 package_info_plus: f0052d280d17aa382b932f399edf32507174e870
pasteboard: 278d8100149f940fb795d6b3a74f0720c890ecb7 pasteboard: 278d8100149f940fb795d6b3a74f0720c890ecb7
path_provider_foundation: bb55f6dbba17d0dccd6737fe6f7f34fbd0376880
PromisesObjC: f5707f49cb48b9636751c5b2e7d227e43fba9f47 PromisesObjC: f5707f49cb48b9636751c5b2e7d227e43fba9f47
PromisesSwift: 9d77319bbe72ebf6d872900551f7eeba9bce2851 PromisesSwift: 9d77319bbe72ebf6d872900551f7eeba9bce2851
protocol_handler_macos: f9cd7b13bcaf6b0425f7410cbe52376cb843a936 protocol_handler_macos: f9cd7b13bcaf6b0425f7410cbe52376cb843a936

View File

@@ -98,7 +98,7 @@ packages:
source: hosted source: hosted
version: "2.13.0" version: "2.13.0"
audio_session: audio_session:
dependency: transitive dependency: "direct main"
description: description:
name: audio_session name: audio_session
sha256: "8f96a7fecbb718cb093070f868b4cdcb8a9b1053dce342ff8ab2fde10eb9afb7" sha256: "8f96a7fecbb718cb093070f868b4cdcb8a9b1053dce342ff8ab2fde10eb9afb7"
@@ -133,10 +133,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: build name: build
sha256: c1668065e9ba04752570ad7e038288559d1e2ca5c6d0131c0f5f55e39e777413 sha256: "275bf6bb2a00a9852c28d4e0b410da1d833a734d57d39d44f94bfc895a484ec3"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "4.0.3" version: "4.0.4"
build_config: build_config:
dependency: transitive dependency: transitive
description: description:
@@ -157,10 +157,10 @@ packages:
dependency: "direct dev" dependency: "direct dev"
description: description:
name: build_runner name: build_runner
sha256: "110c56ef29b5eb367b4d17fc79375fa8c18a6cd7acd92c05bb3986c17a079057" sha256: b4d854962a32fd9f8efc0b76f98214790b833af8b2e9b2df6bfc927c0415a072
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.10.4" version: "2.10.5"
built_collection: built_collection:
dependency: transitive dependency: transitive
description: description:
@@ -173,10 +173,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: built_value name: built_value
sha256: "426cf75afdb23aa74bd4e471704de3f9393f3c7b04c1e2d9c6f1073ae0b8b139" sha256: "7931c90b84bc573fef103548e354258ae4c9d28d140e41961df6843c5d60d4d8"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "8.12.1" version: "8.12.3"
cached_network_image: cached_network_image:
dependency: "direct main" dependency: "direct main"
description: description:
@@ -273,6 +273,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.1.2" version: "1.1.2"
code_assets:
dependency: transitive
description:
name: code_assets
sha256: ae0db647e668cbb295a3527f0938e4039e004c80099dce2f964102373f5ce0b5
url: "https://pub.dev"
source: hosted
version: "0.19.10"
code_builder: code_builder:
dependency: transitive dependency: transitive
description: description:
@@ -409,6 +417,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "3.3.1" version: "3.3.1"
dart_midi_pro:
dependency: "direct main"
description:
name: dart_midi_pro
sha256: "9a0273c92c0336e5694c7318fd936f64f06e938a936dd5fac6563c39954b7f6d"
url: "https://pub.dev"
source: hosted
version: "1.0.4+2"
dart_style: dart_style:
dependency: transitive dependency: transitive
description: description:
@@ -501,18 +517,18 @@ packages:
dependency: "direct main" dependency: "direct main"
description: description:
name: drift name: drift
sha256: "3669e1b68d7bffb60192ac6ba9fd2c0306804d7a00e5879f6364c69ecde53a7f" sha256: "5ea2f718558c0b31d4b8c36a3d8e5b7016f1265f46ceb5a5920e16117f0c0d6a"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.30.0" version: "2.30.1"
drift_dev: drift_dev:
dependency: "direct dev" dependency: "direct dev"
description: description:
name: drift_dev name: drift_dev
sha256: afe4d1d2cfce6606c86f11a6196e974a2ddbfaa992956ce61e054c9b1899c769 sha256: "892dfb5d69d9e604bdcd102a9376de8b41768cf7be93fd26b63cfc4d8f91ad5f"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.30.0" version: "2.30.1"
drift_flutter: drift_flutter:
dependency: "direct main" dependency: "direct main"
description: description:
@@ -761,14 +777,6 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.1.1" version: "1.1.1"
fl_heatmap:
dependency: "direct main"
description:
name: fl_heatmap
sha256: cbf60d737fb2ab216f99e155f197441a07e760aaacb18ecf528095aace99dbf6
url: "https://pub.dev"
source: hosted
version: "0.4.6"
flutter: flutter:
dependency: "direct main" dependency: "direct main"
description: flutter description: flutter
@@ -782,14 +790,6 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "4.5.2" version: "4.5.2"
flutter_app_intents:
dependency: "direct main"
description:
name: flutter_app_intents
sha256: bec5a1ec991b93d475435205dbdca6efdd8979749f2a3c73ebb9f8334b9d3fa2
url: "https://pub.dev"
source: hosted
version: "0.7.0"
flutter_app_update: flutter_app_update:
dependency: "direct main" dependency: "direct main"
description: description:
@@ -1281,10 +1281,10 @@ packages:
dependency: "direct main" dependency: "direct main"
description: description:
name: google_fonts name: google_fonts
sha256: eefe5ee217f331627d8bbcf01f91b21c730bf66e225d6dc8a148370b0819168d sha256: ca1cc501704c47e478f69a667d7f2d882755ddf7baad3f60c3b1256594467022
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "7.0.0" version: "7.0.2"
graphs: graphs:
dependency: transitive dependency: transitive
description: description:
@@ -1317,6 +1317,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.2.3" version: "2.2.3"
hooks:
dependency: transitive
description:
name: hooks
sha256: "5410b9f4f6c9f01e8ff0eb81c9801ea13a3c3d39f8f0b1613cda08e27eab3c18"
url: "https://pub.dev"
source: hosted
version: "0.20.5"
hooks_riverpod: hooks_riverpod:
dependency: "direct main" dependency: "direct main"
description: description:
@@ -1833,10 +1841,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: mockito name: mockito
sha256: dac24d461418d363778d53198d9ac0510b9d073869f078450f195766ec48d05e sha256: a45d1aa065b796922db7b9e7e7e45f921aed17adf3a8318a1f47097e7e695566
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "5.6.1" version: "5.6.3"
mocktail: mocktail:
dependency: transitive dependency: transitive
description: description:
@@ -1869,6 +1877,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.6.2" version: "0.6.2"
native_toolchain_c:
dependency: transitive
description:
name: native_toolchain_c
sha256: f8872ea6c7a50ce08db9ae280ca2b8efdd973157ce462826c82f3c3051d154ce
url: "https://pub.dev"
source: hosted
version: "0.17.2"
nested: nested:
dependency: transitive dependency: transitive
description: description:
@@ -1893,6 +1909,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.0.2" version: "2.0.2"
objective_c:
dependency: transitive
description:
name: objective_c
sha256: "55eb67ede1002d9771b3f9264d2c9d30bc364f0267bc1c6cc0883280d5f0c7cb"
url: "https://pub.dev"
source: hosted
version: "9.2.2"
octo_image: octo_image:
dependency: transitive dependency: transitive
description: description:
@@ -1969,10 +1993,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: path_provider_foundation name: path_provider_foundation
sha256: "6d13aece7b3f5c5a9731eaf553ff9dcbc2eff41087fd2df587fd0fed9a3eb0c4" sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.5.1" version: "2.6.0"
path_provider_linux: path_provider_linux:
dependency: transitive dependency: transitive
description: description:
@@ -2711,10 +2735,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: source_gen name: source_gen
sha256: "07b277b67e0096c45196cbddddf2d8c6ffc49342e88bf31d460ce04605ddac75" sha256: "585bc140f20da42c584ece2df28f4d9ef2566955332b626f655957b3a8c8ad54"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "4.1.1" version: "4.1.2"
source_helper: source_helper:
dependency: transitive dependency: transitive
description: description:
@@ -2807,10 +2831,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: sqlparser name: sqlparser
sha256: "162435ede92bcc793ea939fdc0452eef0a73d11f8ed053b58a89792fba749da5" sha256: f52f5d5649dcc13ed198c4176ddef74bf6851c30f4f31603f1b37788695b93e2
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.42.1" version: "0.43.0"
stack_trace: stack_trace:
dependency: transitive dependency: transitive
description: description:
@@ -2983,42 +3007,42 @@ packages:
dependency: "direct main" dependency: "direct main"
description: description:
name: talker name: talker
sha256: e5d4f7cce6a639037e551660ae1b93b451f107e78dabcc9f89fc52ffeb6d63d5 sha256: c300f9ea5f5433b2db03b6ff61224f25e024ad94b0b6ed996f61686118ae68ec
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "5.1.9" version: "5.1.11"
talker_dio_logger: talker_dio_logger:
dependency: "direct main" dependency: "direct main"
description: description:
name: talker_dio_logger name: talker_dio_logger
sha256: "634434970a8f9428fd753aaae204f453eee65244562f69af117a4474d9b98d35" sha256: a55fe723f3d6f34ecc7ec589b6d66dd6cf9465bd70ea2243573926c994b01255
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "5.1.9" version: "5.1.11"
talker_flutter: talker_flutter:
dependency: "direct main" dependency: "direct main"
description: description:
name: talker_flutter name: talker_flutter
sha256: c4b77632e9fe9cc2c370b7ea294294973ce4d394c584f28e87f7f8b5f5f31a51 sha256: "5010a5309c8ff2910407634d38415576a52e689bd631378d0882db5d2e129a31"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "5.1.9" version: "5.1.11"
talker_logger: talker_logger:
dependency: "direct main" dependency: "direct main"
description: description:
name: talker_logger name: talker_logger
sha256: "0c9f37cd17012e5f45986007340de95e9ebccb7a64c5375919cb27e2f0cc60ee" sha256: "6ae95df093f1eabd2827b2e2d72c96ca881acb47dd19456beb1b1e589304916e"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "5.1.9" version: "5.1.11"
talker_riverpod_logger: talker_riverpod_logger:
dependency: "direct main" dependency: "direct main"
description: description:
name: talker_riverpod_logger name: talker_riverpod_logger
sha256: "5b90312fe87d4e047b131e219254a4e4e1110582b87cff173e8607d10ce104af" sha256: "60ffe027b45a7fde3bc77af63e111ae0eae4c77dde1f0700aa564b43866f7036"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "5.1.9" version: "5.1.11"
term_glyph: term_glyph:
dependency: transitive dependency: transitive
description: description:
@@ -3175,10 +3199,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: url_launcher_web name: url_launcher_web
sha256: "4bd2b7b4dc4d4d0b94e5babfffbca8eac1a126c7f3d6ecbc1a11013faa3abba2" sha256: d0412fcf4c6b31ecfdb7762359b7206ffba3bbffd396c6d9f9c4616ece476c1f
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.4.1" version: "2.4.2"
url_launcher_windows: url_launcher_windows:
dependency: transitive dependency: transitive
description: description:
@@ -3388,5 +3412,5 @@ packages:
source: hosted source: hosted
version: "2.2.3" version: "2.2.3"
sdks: sdks:
dart: ">=3.9.0 <4.0.0" dart: ">=3.10.3 <4.0.0"
flutter: ">=3.35.1" flutter: ">=3.38.4"

View File

@@ -16,7 +16,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts # In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix. # of the product and file versions while build-number is used as the build suffix.
version: 3.5.0+162 version: 3.5.0+164
environment: environment:
sdk: ^3.8.0 sdk: ^3.8.0
@@ -52,7 +52,7 @@ dependencies:
flutter_highlight: ^0.7.0 flutter_highlight: ^0.7.0
uuid: ^4.5.2 uuid: ^4.5.2
url_launcher: ^6.3.2 url_launcher: ^6.3.2
google_fonts: ^7.0.0 google_fonts: ^7.0.2
gap: ^3.0.1 gap: ^3.0.1
cached_network_image: ^3.4.1 cached_network_image: ^3.4.1
web: ^1.1.1 web: ^1.1.1
@@ -61,7 +61,6 @@ dependencies:
media_kit_video: ^2.0.1 media_kit_video: ^2.0.1
media_kit_libs_video: ^1.0.7 media_kit_libs_video: ^1.0.7
flutter_cache_manager: ^3.4.1 flutter_cache_manager: ^3.4.1
email_validator: ^3.0.0 email_validator: ^3.0.0
easy_localization: ^3.0.8 easy_localization: ^3.0.8
flutter_inappwebview: ^6.1.5 flutter_inappwebview: ^6.1.5
@@ -82,7 +81,7 @@ dependencies:
firebase_core: ^4.3.0 firebase_core: ^4.3.0
web_socket_channel: ^3.0.3 web_socket_channel: ^3.0.3
material_symbols_icons: ^4.2892.0 material_symbols_icons: ^4.2892.0
drift: ^2.30.0 drift: ^2.30.1
drift_flutter: ^0.2.8 drift_flutter: ^0.2.8
path: ^1.9.1 path: ^1.9.1
collection: ^1.19.1 collection: ^1.19.1
@@ -108,7 +107,6 @@ dependencies:
qr_flutter: ^4.1.0 qr_flutter: ^4.1.0
flutter_otp_text_field: ^1.5.1+1 flutter_otp_text_field: ^1.5.1+1
flutter_staggered_grid_view: ^0.7.0 flutter_staggered_grid_view: ^0.7.0
flutter_popup_card: ^0.0.6 flutter_popup_card: ^0.0.6
timezone: ^0.10.1 timezone: ^0.10.1
flutter_timezone: ^5.0.1 flutter_timezone: ^5.0.1
@@ -152,14 +150,13 @@ dependencies:
dart_ipc: ^1.0.1 dart_ipc: ^1.0.1
pretty_diff_text: ^2.1.0 pretty_diff_text: ^2.1.0
window_manager: ^0.5.1 window_manager: ^0.5.1
talker: ^5.1.9 talker: ^5.1.11
talker_flutter: ^5.1.9 talker_flutter: ^5.1.11
talker_logger: ^5.1.9 talker_logger: ^5.1.11
talker_dio_logger: ^5.1.9 talker_dio_logger: ^5.1.11
talker_riverpod_logger: ^5.1.9 talker_riverpod_logger: ^5.1.11
syncfusion_flutter_pdfviewer: ^31.1.21 syncfusion_flutter_pdfviewer: ^31.1.21
swipe_to: ^1.0.6 swipe_to: ^1.0.6
fl_heatmap: ^0.4.6
dio_smart_retry: ^7.0.1 dio_smart_retry: ^7.0.1
flutter_expandable_fab: ^2.5.2 flutter_expandable_fab: ^2.5.2
event_bus: ^2.0.1 event_bus: ^2.0.1
@@ -174,9 +171,10 @@ dependencies:
shake: ^3.0.0 shake: ^3.0.0
in_app_review: ^2.0.11 in_app_review: ^2.0.11
snow_fall_animation: ^0.0.1+3 snow_fall_animation: ^0.0.1+3
flutter_app_intents: ^0.7.0
video_thumbnail: ^0.5.6 video_thumbnail: ^0.5.6
just_audio: ^0.10.5 just_audio: ^0.10.5
audio_session: ^0.2.2
dart_midi_pro: ^1.0.4+2
dev_dependencies: dev_dependencies:
flutter_test: flutter_test:
@@ -188,13 +186,13 @@ dev_dependencies:
# package. See that file for information about deactivating specific lint # package. See that file for information about deactivating specific lint
# rules and activating additional ones. # rules and activating additional ones.
flutter_lints: ^6.0.0 flutter_lints: ^6.0.0
build_runner: ^2.10.4 build_runner: ^2.10.5
freezed: ^3.2.3 freezed: ^3.2.3
json_serializable: ^6.11.2 json_serializable: ^6.11.2
riverpod_generator: ^4.0.0+1 riverpod_generator: ^4.0.0+1
custom_lint: ^0.8.1 custom_lint: ^0.8.1
riverpod_lint: ^3.1.0 riverpod_lint: ^3.1.0
drift_dev: ^2.30.0 drift_dev: ^2.30.1
flutter_launcher_icons: ^0.14.4 flutter_launcher_icons: ^0.14.4
msix: ^3.16.12 msix: ^3.16.12
@@ -210,6 +208,7 @@ flutter:
# To add assets to your application, add an assets section, like this: # To add assets to your application, add an assets section, like this:
assets: assets:
- assets/midi/
- assets/i18n/ - assets/i18n/
- assets/images/ - assets/images/
- assets/images/oidc/ - assets/images/oidc/
@@ -278,4 +277,3 @@ msix_config:
protocol_activation: solian, https protocol_activation: solian, https
app_uri_handler_hosts: solian.app app_uri_handler_hosts: solian.app
capabilities: internetClientServer, location, microphone, webcam capabilities: internetClientServer, location, microphone, webcam