Compare commits

..

11 Commits

Author SHA1 Message Date
825e6b5b6d 🚀 Launch 3.0.0+107 2025-06-26 02:23:36 +08:00
2a3276973c ♻️ Moved to new snackbar 2025-06-26 02:15:19 +08:00
f4e10afa8f 🗑️ Remove snackbar testing code 2025-06-26 02:13:32 +08:00
60c5e584be 💄 Optimized notification snack bar 2025-06-26 02:12:38 +08:00
2b237eaad9 💄 Optimized bottom nav 2025-06-26 01:54:43 +08:00
891a0b999c Update Crowdin configuration file 2025-06-26 00:15:08 +08:00
01da729365 Abuse report 2025-06-25 23:57:55 +08:00
cef313b356 🗑️ Clean up code 2025-06-25 23:03:55 +08:00
8bc8556f06 Share to chat 2025-06-25 23:02:14 +08:00
1a8abe5849 Better link previewing 2025-06-25 22:33:12 +08:00
86258acc6e ♻️ Refactor snackbar 2025-06-25 22:05:37 +08:00
56 changed files with 1756 additions and 934 deletions

View File

@ -51,8 +51,6 @@ android {
buildTypes {
release {
signingConfig = signingConfigs.getByName("release")
minifyEnabled = true
shrinkResources = true
}
}
}

File diff suppressed because one or more lines are too long

View File

@ -48,6 +48,28 @@
"deletePublisherHint": "Are you sure to delete this publisher? This will also deleted all the post and collections under this publisher.",
"somethingWentWrong": "Something went wrong...",
"deletePost": "Delete Post",
"safetyReport": "Report",
"safetyReportTitle": "Safety Report",
"safetyReportDescription": "Help us keep the community safe by reporting inappropriate content or behavior.",
"safetyReportType": "Report Type",
"safetyReportReason": "Additional Details",
"safetyReportReasonHint": "Please provide more details about the issue...",
"safetyReportSubmit": "Submit Report",
"safetyReportSubmitting": "Submitting...",
"safetyReportSuccess": "Report submitted successfully. Thank you for helping keep our community safe.",
"safetyReportError": "Failed to submit report. Please try again.",
"safetyReportReasonRequired": "Please provide details about the issue",
"safetyReportTypeSpam": "Spam or Misleading",
"safetyReportTypeHarassment": "Harassment or Abuse",
"safetyReportTypeHateSpeech": "Hate Speech",
"safetyReportTypeViolence": "Violence or Threats",
"safetyReportTypeAdultContent": "Adult Content",
"safetyReportTypeIntellectualProperty": "Intellectual Property Violation",
"safetyReportTypeOther": "Other",
"safetyReportTypeInappropriate": "Inappropriate Content",
"safetyReportTypeCopyright": "Copyright Violation",
"safetyReportSuccessTitle": "Report Submitted",
"safetyReportErrorTitle": "Error",
"deletePostHint": "Are you sure to delete this post?",
"copyLink": "Copy Link",
"postCreateAccountTitle": "Thanks for joining!",
@ -561,5 +583,32 @@
"noChatRoomsAvailable": "No chat rooms available",
"failedToLoadChats": "Failed to load chats",
"contentToShare": "Content to share:",
"unknownChat": "Unknown Chat"
"unknownChat": "Unknown Chat",
"addAdditionalMessage": "Add additional message...",
"uploadingFiles": "Uploading files...",
"sharedSuccessfully": "Shared successfully!",
"navigateToChat": "Navigate to Chat",
"wouldYouLikeToNavigateToChat": "Would you like to navigate to the chat?",
"abuseReport": "Report",
"abuseReportTitle": "Report Content",
"abuseReportDescription": "Help us keep the community safe by reporting inappropriate content or behavior.",
"abuseReportType": "Report Type",
"abuseReportReason": "Additional Details",
"abuseReportReasonHint": "Please provide more details about the issue...",
"abuseReportSubmit": "Submit Report",
"abuseReportSuccess": "Report submitted successfully. Thank you for helping keep our community safe.",
"abuseReportError": "Failed to submit report. Please try again.",
"abuseReportReasonRequired": "Please provide details about the issue",
"abuseReportSuccessTitle": "Report Submitted",
"abuseReportErrorTitle": "Error",
"abuseReportTypeSpam": "Spam or Misleading",
"abuseReportTypeHarassment": "Harassment or Abuse",
"abuseReportTypeInappropriate": "Inappropriate Content",
"abuseReportTypeViolence": "Violence or Threats",
"abuseReportTypeCopyright": "Copyright Violation",
"abuseReportTypeImpersonation": "Impersonation",
"abuseReportTypeOffensiveContent": "Offensive Content",
"abuseReportTypePrivacyViolation": "Privacy Violation",
"abuseReportTypeIllegalContent": "Illegal Content",
"abuseReportTypeOther": "Other"
}

2
crowdin.yml Normal file
View File

@ -0,0 +1,2 @@
bundles:
- 6

View File

@ -23,6 +23,8 @@
<true/>
<key>NSExtensionActivationSupportsWebURLWithMaxCount</key>
<integer>1</integer>
<key>NSExtensionActivationSupportsWebPageWithMaxCount</key>
<integer>1</integer>
<key>NSExtensionActivationSupportsImageWithMaxCount</key>
<integer>100</integer>
<key>NSExtensionActivationSupportsMovieWithMaxCount</key>

View File

@ -9,6 +9,6 @@ import receive_sharing_intent
class ShareViewController: RSIShareViewController {
override func shouldAutoRedirect() -> Bool {
return false
return true
}
}

View File

@ -18,8 +18,8 @@ import 'package:bitsdojo_window/bitsdojo_window.dart';
import 'package:island/pods/userinfo.dart';
import 'package:island/pods/websocket.dart';
import 'package:island/route.dart';
import 'package:island/screens/tabs.dart';
import 'package:island/services/notify.dart';
import 'package:island/widgets/app_wrapper.dart';
import 'package:island/services/timezone.dart';
import 'package:island/widgets/alert.dart';
import 'package:island/widgets/app_scaffold.dart';
@ -127,6 +127,8 @@ void main() async {
final appRouter = AppRouter();
final globalOverlay = GlobalKey<OverlayState>();
class IslandApp extends HookConsumerWidget {
const IslandApp({super.key});
@ -185,7 +187,16 @@ class IslandApp extends HookConsumerWidget {
theme: theme?.light,
darkTheme: theme?.dark,
themeMode: ThemeMode.system,
routerConfig: appRouter.config(),
routerConfig: appRouter.config(
navigatorObservers:
() => [
TabNavigationObserver(
onChange: (route) {
ref.read(currentRouteProvider.notifier).state = route;
},
),
],
),
supportedLocales: context.supportedLocales,
localizationsDelegates: [
...context.localizationDelegates,
@ -195,6 +206,7 @@ class IslandApp extends HookConsumerWidget {
locale: context.locale,
builder: (context, child) {
return Overlay(
key: globalOverlay,
initialEntries: [
OverlayEntry(
builder:

View File

@ -21,3 +21,22 @@ sealed class SnEmbedLink with _$SnEmbedLink {
factory SnEmbedLink.fromJson(Map<String, dynamic> json) =>
_$SnEmbedLinkFromJson(json);
}
@freezed
sealed class SnScrappedLink with _$SnScrappedLink {
const factory SnScrappedLink({
required String type,
required String url,
required String title,
required String? description,
required String? imageUrl,
required String faviconUrl,
required String siteName,
required String? contentType,
required String? author,
required DateTime? publishedDate,
}) = _SnScrappedLink;
factory SnScrappedLink.fromJson(Map<String, dynamic> json) =>
_$SnScrappedLinkFromJson(json);
}

View File

@ -170,6 +170,166 @@ as DateTime?,
}
}
/// @nodoc
mixin _$SnScrappedLink {
String get type; String get url; String get title; String? get description; String? get imageUrl; String get faviconUrl; String get siteName; String? get contentType; String? get author; DateTime? get publishedDate;
/// Create a copy of SnScrappedLink
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$SnScrappedLinkCopyWith<SnScrappedLink> get copyWith => _$SnScrappedLinkCopyWithImpl<SnScrappedLink>(this as SnScrappedLink, _$identity);
/// Serializes this SnScrappedLink to a JSON map.
Map<String, dynamic> toJson();
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is SnScrappedLink&&(identical(other.type, type) || other.type == type)&&(identical(other.url, url) || other.url == url)&&(identical(other.title, title) || other.title == title)&&(identical(other.description, description) || other.description == description)&&(identical(other.imageUrl, imageUrl) || other.imageUrl == imageUrl)&&(identical(other.faviconUrl, faviconUrl) || other.faviconUrl == faviconUrl)&&(identical(other.siteName, siteName) || other.siteName == siteName)&&(identical(other.contentType, contentType) || other.contentType == contentType)&&(identical(other.author, author) || other.author == author)&&(identical(other.publishedDate, publishedDate) || other.publishedDate == publishedDate));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,type,url,title,description,imageUrl,faviconUrl,siteName,contentType,author,publishedDate);
@override
String toString() {
return 'SnScrappedLink(type: $type, url: $url, title: $title, description: $description, imageUrl: $imageUrl, faviconUrl: $faviconUrl, siteName: $siteName, contentType: $contentType, author: $author, publishedDate: $publishedDate)';
}
}
/// @nodoc
abstract mixin class $SnScrappedLinkCopyWith<$Res> {
factory $SnScrappedLinkCopyWith(SnScrappedLink value, $Res Function(SnScrappedLink) _then) = _$SnScrappedLinkCopyWithImpl;
@useResult
$Res call({
String type, String url, String title, String? description, String? imageUrl, String faviconUrl, String siteName, String? contentType, String? author, DateTime? publishedDate
});
}
/// @nodoc
class _$SnScrappedLinkCopyWithImpl<$Res>
implements $SnScrappedLinkCopyWith<$Res> {
_$SnScrappedLinkCopyWithImpl(this._self, this._then);
final SnScrappedLink _self;
final $Res Function(SnScrappedLink) _then;
/// Create a copy of SnScrappedLink
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? type = null,Object? url = null,Object? title = null,Object? description = freezed,Object? imageUrl = freezed,Object? faviconUrl = null,Object? siteName = null,Object? contentType = freezed,Object? author = freezed,Object? publishedDate = freezed,}) {
return _then(_self.copyWith(
type: null == type ? _self.type : type // ignore: cast_nullable_to_non_nullable
as String,url: null == url ? _self.url : url // ignore: cast_nullable_to_non_nullable
as String,title: null == title ? _self.title : title // ignore: cast_nullable_to_non_nullable
as String,description: freezed == description ? _self.description : description // ignore: cast_nullable_to_non_nullable
as String?,imageUrl: freezed == imageUrl ? _self.imageUrl : imageUrl // ignore: cast_nullable_to_non_nullable
as String?,faviconUrl: null == faviconUrl ? _self.faviconUrl : faviconUrl // ignore: cast_nullable_to_non_nullable
as String,siteName: null == siteName ? _self.siteName : siteName // ignore: cast_nullable_to_non_nullable
as String,contentType: freezed == contentType ? _self.contentType : contentType // ignore: cast_nullable_to_non_nullable
as String?,author: freezed == author ? _self.author : author // ignore: cast_nullable_to_non_nullable
as String?,publishedDate: freezed == publishedDate ? _self.publishedDate : publishedDate // ignore: cast_nullable_to_non_nullable
as DateTime?,
));
}
}
/// @nodoc
@JsonSerializable()
class _SnScrappedLink implements SnScrappedLink {
const _SnScrappedLink({required this.type, required this.url, required this.title, required this.description, required this.imageUrl, required this.faviconUrl, required this.siteName, required this.contentType, required this.author, required this.publishedDate});
factory _SnScrappedLink.fromJson(Map<String, dynamic> json) => _$SnScrappedLinkFromJson(json);
@override final String type;
@override final String url;
@override final String title;
@override final String? description;
@override final String? imageUrl;
@override final String faviconUrl;
@override final String siteName;
@override final String? contentType;
@override final String? author;
@override final DateTime? publishedDate;
/// Create a copy of SnScrappedLink
/// with the given fields replaced by the non-null parameter values.
@override @JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$SnScrappedLinkCopyWith<_SnScrappedLink> get copyWith => __$SnScrappedLinkCopyWithImpl<_SnScrappedLink>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$SnScrappedLinkToJson(this, );
}
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _SnScrappedLink&&(identical(other.type, type) || other.type == type)&&(identical(other.url, url) || other.url == url)&&(identical(other.title, title) || other.title == title)&&(identical(other.description, description) || other.description == description)&&(identical(other.imageUrl, imageUrl) || other.imageUrl == imageUrl)&&(identical(other.faviconUrl, faviconUrl) || other.faviconUrl == faviconUrl)&&(identical(other.siteName, siteName) || other.siteName == siteName)&&(identical(other.contentType, contentType) || other.contentType == contentType)&&(identical(other.author, author) || other.author == author)&&(identical(other.publishedDate, publishedDate) || other.publishedDate == publishedDate));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,type,url,title,description,imageUrl,faviconUrl,siteName,contentType,author,publishedDate);
@override
String toString() {
return 'SnScrappedLink(type: $type, url: $url, title: $title, description: $description, imageUrl: $imageUrl, faviconUrl: $faviconUrl, siteName: $siteName, contentType: $contentType, author: $author, publishedDate: $publishedDate)';
}
}
/// @nodoc
abstract mixin class _$SnScrappedLinkCopyWith<$Res> implements $SnScrappedLinkCopyWith<$Res> {
factory _$SnScrappedLinkCopyWith(_SnScrappedLink value, $Res Function(_SnScrappedLink) _then) = __$SnScrappedLinkCopyWithImpl;
@override @useResult
$Res call({
String type, String url, String title, String? description, String? imageUrl, String faviconUrl, String siteName, String? contentType, String? author, DateTime? publishedDate
});
}
/// @nodoc
class __$SnScrappedLinkCopyWithImpl<$Res>
implements _$SnScrappedLinkCopyWith<$Res> {
__$SnScrappedLinkCopyWithImpl(this._self, this._then);
final _SnScrappedLink _self;
final $Res Function(_SnScrappedLink) _then;
/// Create a copy of SnScrappedLink
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? type = null,Object? url = null,Object? title = null,Object? description = freezed,Object? imageUrl = freezed,Object? faviconUrl = null,Object? siteName = null,Object? contentType = freezed,Object? author = freezed,Object? publishedDate = freezed,}) {
return _then(_SnScrappedLink(
type: null == type ? _self.type : type // ignore: cast_nullable_to_non_nullable
as String,url: null == url ? _self.url : url // ignore: cast_nullable_to_non_nullable
as String,title: null == title ? _self.title : title // ignore: cast_nullable_to_non_nullable
as String,description: freezed == description ? _self.description : description // ignore: cast_nullable_to_non_nullable
as String?,imageUrl: freezed == imageUrl ? _self.imageUrl : imageUrl // ignore: cast_nullable_to_non_nullable
as String?,faviconUrl: null == faviconUrl ? _self.faviconUrl : faviconUrl // ignore: cast_nullable_to_non_nullable
as String,siteName: null == siteName ? _self.siteName : siteName // ignore: cast_nullable_to_non_nullable
as String,contentType: freezed == contentType ? _self.contentType : contentType // ignore: cast_nullable_to_non_nullable
as String?,author: freezed == author ? _self.author : author // ignore: cast_nullable_to_non_nullable
as String?,publishedDate: freezed == publishedDate ? _self.publishedDate : publishedDate // ignore: cast_nullable_to_non_nullable
as DateTime?,
));
}
}
// dart format on

View File

@ -35,3 +35,34 @@ Map<String, dynamic> _$SnEmbedLinkToJson(_SnEmbedLink instance) =>
'Author': instance.author,
'PublishedDate': instance.publishedDate?.toIso8601String(),
};
_SnScrappedLink _$SnScrappedLinkFromJson(Map<String, dynamic> json) =>
_SnScrappedLink(
type: json['type'] as String,
url: json['url'] as String,
title: json['title'] as String,
description: json['description'] as String?,
imageUrl: json['image_url'] as String?,
faviconUrl: json['favicon_url'] as String,
siteName: json['site_name'] as String,
contentType: json['content_type'] as String?,
author: json['author'] as String?,
publishedDate:
json['published_date'] == null
? null
: DateTime.parse(json['published_date'] as String),
);
Map<String, dynamic> _$SnScrappedLinkToJson(_SnScrappedLink instance) =>
<String, dynamic>{
'type': instance.type,
'url': instance.url,
'title': instance.title,
'description': instance.description,
'image_url': instance.imageUrl,
'favicon_url': instance.faviconUrl,
'site_name': instance.siteName,
'content_type': instance.contentType,
'author': instance.author,
'published_date': instance.publishedDate?.toIso8601String(),
};

View File

@ -0,0 +1,28 @@
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:island/models/embed.dart';
import 'package:island/pods/network.dart';
part 'link_preview.g.dart';
@riverpod
class LinkPreview extends _$LinkPreview {
@override
Future<SnScrappedLink?> build(String url) async {
final client = ref.read(apiClientProvider);
try {
final response = await client.get(
'/scrap/link',
queryParameters: {'url': url},
);
if (response.statusCode == 200 && response.data != null) {
return SnScrappedLink.fromJson(response.data);
}
return null;
} catch (e) {
// Return null on error to show fallback UI
return null;
}
}
}

View File

@ -0,0 +1,164 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'link_preview.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
String _$linkPreviewHash() => r'5130593d3066155cb958d20714ee577df1f940d7';
/// Copied from Dart SDK
class _SystemHash {
_SystemHash._();
static int combine(int hash, int value) {
// ignore: parameter_assignments
hash = 0x1fffffff & (hash + value);
// ignore: parameter_assignments
hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10));
return hash ^ (hash >> 6);
}
static int finish(int hash) {
// ignore: parameter_assignments
hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3));
// ignore: parameter_assignments
hash = hash ^ (hash >> 11);
return 0x1fffffff & (hash + ((0x00003fff & hash) << 15));
}
}
abstract class _$LinkPreview
extends BuildlessAutoDisposeAsyncNotifier<SnScrappedLink?> {
late final String url;
FutureOr<SnScrappedLink?> build(String url);
}
/// See also [LinkPreview].
@ProviderFor(LinkPreview)
const linkPreviewProvider = LinkPreviewFamily();
/// See also [LinkPreview].
class LinkPreviewFamily extends Family<AsyncValue<SnScrappedLink?>> {
/// See also [LinkPreview].
const LinkPreviewFamily();
/// See also [LinkPreview].
LinkPreviewProvider call(String url) {
return LinkPreviewProvider(url);
}
@override
LinkPreviewProvider getProviderOverride(
covariant LinkPreviewProvider provider,
) {
return call(provider.url);
}
static const Iterable<ProviderOrFamily>? _dependencies = null;
@override
Iterable<ProviderOrFamily>? get dependencies => _dependencies;
static const Iterable<ProviderOrFamily>? _allTransitiveDependencies = null;
@override
Iterable<ProviderOrFamily>? get allTransitiveDependencies =>
_allTransitiveDependencies;
@override
String? get name => r'linkPreviewProvider';
}
/// See also [LinkPreview].
class LinkPreviewProvider
extends AutoDisposeAsyncNotifierProviderImpl<LinkPreview, SnScrappedLink?> {
/// See also [LinkPreview].
LinkPreviewProvider(String url)
: this._internal(
() => LinkPreview()..url = url,
from: linkPreviewProvider,
name: r'linkPreviewProvider',
debugGetCreateSourceHash:
const bool.fromEnvironment('dart.vm.product')
? null
: _$linkPreviewHash,
dependencies: LinkPreviewFamily._dependencies,
allTransitiveDependencies: LinkPreviewFamily._allTransitiveDependencies,
url: url,
);
LinkPreviewProvider._internal(
super._createNotifier, {
required super.name,
required super.dependencies,
required super.allTransitiveDependencies,
required super.debugGetCreateSourceHash,
required super.from,
required this.url,
}) : super.internal();
final String url;
@override
FutureOr<SnScrappedLink?> runNotifierBuild(covariant LinkPreview notifier) {
return notifier.build(url);
}
@override
Override overrideWith(LinkPreview Function() create) {
return ProviderOverride(
origin: this,
override: LinkPreviewProvider._internal(
() => create()..url = url,
from: from,
name: null,
dependencies: null,
allTransitiveDependencies: null,
debugGetCreateSourceHash: null,
url: url,
),
);
}
@override
AutoDisposeAsyncNotifierProviderElement<LinkPreview, SnScrappedLink?>
createElement() {
return _LinkPreviewProviderElement(this);
}
@override
bool operator ==(Object other) {
return other is LinkPreviewProvider && other.url == url;
}
@override
int get hashCode {
var hash = _SystemHash.combine(0, runtimeType.hashCode);
hash = _SystemHash.combine(hash, url.hashCode);
return _SystemHash.finish(hash);
}
}
@Deprecated('Will be removed in 3.0. Use Ref instead')
// ignore: unused_element
mixin LinkPreviewRef on AutoDisposeAsyncNotifierProviderRef<SnScrappedLink?> {
/// The parameter `url` of this provider.
String get url;
}
class _LinkPreviewProviderElement
extends
AutoDisposeAsyncNotifierProviderElement<LinkPreview, SnScrappedLink?>
with LinkPreviewRef {
_LinkPreviewProviderElement(super.provider);
@override
String get url => (origin as LinkPreviewProvider).url;
}
// ignore_for_file: type=lint
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member, deprecated_member_use_from_same_package

View File

@ -12,10 +12,13 @@ class AppRouter extends RootStackRouter {
];
List<AutoRoute> get _appRoutes => [
// Standalone routes without bottom navigation
AutoRoute(page: PostComposeRoute.page, path: 'posts/compose'),
AutoRoute(page: PostEditRoute.page, path: 'posts/:id/edit'),
AutoRoute(page: CallRoute.page, path: 'chat/:id/call'),
AutoRoute(page: EventCalanderRoute.page, path: 'account/:name/calendar'),
// Main tabs with bottom navigation and shell routes for desktop layout
AutoRoute(
page: TabsRoute.page,
path: '',

View File

@ -1266,6 +1266,7 @@ class PostComposeRoute extends _i31.PageRouteInfo<PostComposeRouteArgs> {
_i34.SnPost? repliedPost,
_i34.SnPost? forwardedPost,
int? type,
_i22.PostComposeInitialState? initialState,
List<_i31.PageRouteInfo>? children,
}) : super(
PostComposeRoute.name,
@ -1275,6 +1276,7 @@ class PostComposeRoute extends _i31.PageRouteInfo<PostComposeRouteArgs> {
repliedPost: repliedPost,
forwardedPost: forwardedPost,
type: type,
initialState: initialState,
),
rawQueryParams: {'type': type},
initialChildren: children,
@ -1295,6 +1297,7 @@ class PostComposeRoute extends _i31.PageRouteInfo<PostComposeRouteArgs> {
repliedPost: args.repliedPost,
forwardedPost: args.forwardedPost,
type: args.type,
initialState: args.initialState,
);
},
);
@ -1307,6 +1310,7 @@ class PostComposeRouteArgs {
this.repliedPost,
this.forwardedPost,
this.type,
this.initialState,
});
final _i32.Key? key;
@ -1319,9 +1323,11 @@ class PostComposeRouteArgs {
final int? type;
final _i22.PostComposeInitialState? initialState;
@override
String toString() {
return 'PostComposeRouteArgs{key: $key, originalPost: $originalPost, repliedPost: $repliedPost, forwardedPost: $forwardedPost, type: $type}';
return 'PostComposeRouteArgs{key: $key, originalPost: $originalPost, repliedPost: $repliedPost, forwardedPost: $forwardedPost, type: $type, initialState: $initialState}';
}
@override
@ -1332,7 +1338,8 @@ class PostComposeRouteArgs {
originalPost == other.originalPost &&
repliedPost == other.repliedPost &&
forwardedPost == other.forwardedPost &&
type == other.type;
type == other.type &&
initialState == other.initialState;
}
@override
@ -1341,7 +1348,8 @@ class PostComposeRouteArgs {
originalPost.hashCode ^
repliedPost.hashCode ^
forwardedPost.hashCode ^
type.hashCode;
type.hashCode ^
initialState.hashCode;
}
/// generated route for

View File

@ -641,7 +641,7 @@ class LevelingScreen extends HookConsumerWidget {
ref.invalidate(accountStellarSubscriptionProvider);
ref.read(userInfoProvider.notifier).fetchUser();
if (context.mounted) {
showSnackBar(context, 'membershipPurchaseSuccess'.tr());
showSnackBar('membershipPurchaseSuccess'.tr());
}
}
} catch (err) {

View File

@ -72,7 +72,7 @@ class AccountSettingsScreen extends HookConsumerWidget {
final client = ref.read(apiClientProvider);
await client.delete('/accounts/me');
if (context.mounted) {
showSnackBar(context, 'accountDeletionSent'.tr());
showSnackBar('accountDeletionSent'.tr());
}
} catch (err) {
showErrorAlert(err);
@ -100,7 +100,7 @@ class AccountSettingsScreen extends HookConsumerWidget {
data: {'account': userInfo.value!.name, 'captcha_token': captchaTk},
);
if (context.mounted) {
showSnackBar(context, 'accountPasswordChangeSent'.tr());
showSnackBar('accountPasswordChangeSent'.tr());
}
} catch (err) {
showErrorAlert(err);

View File

@ -205,7 +205,7 @@ class AuthFactorNewSheet extends HookConsumerWidget {
builder: (context) => AuthFactorNewAdditonalSheet(factor: factor),
).then((_) {
if (context.mounted) {
showSnackBar(context, 'contactMethodVerificationNeeded'.tr());
showSnackBar('contactMethodVerificationNeeded'.tr());
}
if (context.mounted) Navigator.pop(context, true);
});

View File

@ -181,7 +181,7 @@ class AccountConnectionNewSheet extends HookConsumerWidget {
},
);
if (context.mounted) {
showSnackBar(context, 'accountConnectionAddSuccess'.tr());
showSnackBar('accountConnectionAddSuccess'.tr());
Navigator.pop(context, true);
}
} catch (err) {
@ -208,7 +208,7 @@ class AccountConnectionNewSheet extends HookConsumerWidget {
if (context.mounted) Navigator.pop(context, true);
break;
default:
showSnackBar(context, 'accountConnectionAddError'.tr());
showSnackBar('accountConnectionAddError'.tr());
return;
}
}

View File

@ -40,7 +40,7 @@ class ContactMethodSheet extends HookConsumerWidget {
final client = ref.read(apiClientProvider);
await client.post('/accounts/me/contacts/${contact.id}/verify');
if (context.mounted) {
showSnackBar(context, 'contactMethodVerificationSent'.tr());
showSnackBar('contactMethodVerificationSent'.tr());
}
} catch (err) {
showErrorAlert(err);
@ -152,7 +152,7 @@ class ContactMethodNewSheet extends HookConsumerWidget {
Future<void> addContactMethod() async {
if (contentController.text.isEmpty) {
showSnackBar(context, 'contactMethodContentEmpty'.tr());
showSnackBar('contactMethodContentEmpty'.tr());
return;
}
@ -164,7 +164,7 @@ class ContactMethodNewSheet extends HookConsumerWidget {
data: {'type': contactType.value, 'content': contentController.text},
);
if (context.mounted) {
showSnackBar(context, 'contactMethodVerificationNeeded'.tr());
showSnackBar('contactMethodVerificationNeeded'.tr());
Navigator.pop(context, true);
}
} catch (err) {

View File

@ -242,12 +242,10 @@ class RelationshipScreen extends HookConsumerWidget {
if (!context.mounted) return;
if (isAccept) {
showSnackBar(
context,
'friendRequestAccepted'.tr(args: ['@${relationship.account.name}']),
);
} else {
showSnackBar(
context,
'friendRequestDeclined'.tr(args: ['@${relationship.account.name}']),
);
}

View File

@ -427,7 +427,7 @@ class _LoginPickerScreen extends HookConsumerWidget {
onPickFactor(factors!.where((x) => x == factorPicked.value).first);
onNext();
if (context.mounted) {
showSnackBar(context, err.response!.data.toString());
showSnackBar(err.response!.data.toString());
}
return;
}

View File

@ -10,6 +10,7 @@ import 'package:gap/gap.dart';
import 'package:island/pods/config.dart';
import 'package:island/pods/network.dart';
import 'package:island/services/udid.dart';
import 'package:island/widgets/alert.dart';
import 'package:island/widgets/app_scaffold.dart';
import 'package:styled_widget/styled_widget.dart';
@ -204,12 +205,7 @@ class _OidcScreenState extends ConsumerState<OidcScreen> {
onPressed: () {
if (currentUrl != null) {
Clipboard.setData(ClipboardData(text: currentUrl!));
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('copyToClipboard').tr(),
duration: const Duration(seconds: 1),
),
);
showSnackBar('copyToClipboard');
}
},
),

View File

@ -49,7 +49,6 @@ class ChatDetailScreen extends HookConsumerWidget {
ref.invalidate(chatroomIdentityProvider(id));
if (context.mounted) {
showSnackBar(
context,
'chatNotifyLevelUpdated'.tr(args: [kNotifyLevelText[level].tr()]),
);
}
@ -140,7 +139,7 @@ class ChatDetailScreen extends HookConsumerWidget {
setChatBreak(now);
Navigator.pop(context);
if (context.mounted) {
showSnackBar(context, 'chatBreakCleared'.tr());
showSnackBar('chatBreakCleared'.tr());
}
},
),
@ -152,7 +151,7 @@ class ChatDetailScreen extends HookConsumerWidget {
setChatBreak(now.add(const Duration(minutes: 5)));
Navigator.pop(context);
if (context.mounted) {
showSnackBar(context, 'chatBreakSet'.tr(args: ['5m']));
showSnackBar('chatBreakSet'.tr(args: ['5m']));
}
},
),
@ -164,7 +163,7 @@ class ChatDetailScreen extends HookConsumerWidget {
setChatBreak(now.add(const Duration(minutes: 10)));
Navigator.pop(context);
if (context.mounted) {
showSnackBar(context, 'chatBreakSet'.tr(args: ['10m']));
showSnackBar('chatBreakSet'.tr(args: ['10m']));
}
},
),
@ -176,7 +175,7 @@ class ChatDetailScreen extends HookConsumerWidget {
setChatBreak(now.add(const Duration(minutes: 15)));
Navigator.pop(context);
if (context.mounted) {
showSnackBar(context, 'chatBreakSet'.tr(args: ['15m']));
showSnackBar('chatBreakSet'.tr(args: ['15m']));
}
},
),
@ -188,7 +187,7 @@ class ChatDetailScreen extends HookConsumerWidget {
setChatBreak(now.add(const Duration(minutes: 30)));
Navigator.pop(context);
if (context.mounted) {
showSnackBar(context, 'chatBreakSet'.tr(args: ['30m']));
showSnackBar('chatBreakSet'.tr(args: ['30m']));
}
},
),
@ -208,7 +207,6 @@ class ChatDetailScreen extends HookConsumerWidget {
Navigator.pop(context);
if (context.mounted) {
showSnackBar(
context,
'chatBreakSet'.tr(args: ['${minutes}m']),
);
}

View File

@ -186,7 +186,6 @@ class NotificationScreen extends HookConsumerWidget {
final uri = Uri.tryParse(href);
if (uri == null) {
showSnackBar(
context,
'brokenLink'.tr(args: []),
action: SnackBarAction(
label: 'copyToClipboard'.tr(),

View File

@ -2,6 +2,7 @@ import 'package:auto_route/auto_route.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:gap/gap.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/models/file.dart';
@ -22,6 +23,23 @@ import 'package:island/widgets/post/draft_manager.dart';
import 'package:material_symbols_icons/symbols.dart';
import 'package:styled_widget/styled_widget.dart';
part 'compose.freezed.dart';
part 'compose.g.dart';
@freezed
sealed class PostComposeInitialState with _$PostComposeInitialState {
const factory PostComposeInitialState({
String? title,
String? description,
String? content,
@Default([]) List<UniversalFile> attachments,
int? visibility,
}) = _PostComposeInitialState;
factory PostComposeInitialState.fromJson(Map<String, dynamic> json) =>
_$PostComposeInitialStateFromJson(json);
}
@RoutePage()
class PostEditScreen extends HookConsumerWidget {
final String id;
@ -54,12 +72,14 @@ class PostComposeScreen extends HookConsumerWidget {
final SnPost? repliedPost;
final SnPost? forwardedPost;
final int? type;
final PostComposeInitialState? initialState;
const PostComposeScreen({
super.key,
this.originalPost,
this.repliedPost,
this.forwardedPost,
@QueryParam('type') this.type,
this.initialState,
});
@override
@ -107,11 +127,28 @@ class PostComposeScreen extends HookConsumerWidget {
return null;
}, [publishers]);
// Load draft if available (only for new posts)
// Load initial state if provided (for sharing functionality)
useEffect(() {
if (initialState != null) {
state.titleController.text = initialState!.title ?? '';
state.descriptionController.text = initialState!.description ?? '';
state.contentController.text = initialState!.content ?? '';
if (initialState!.visibility != null) {
state.visibility.value = initialState!.visibility!;
}
if (initialState!.attachments.isNotEmpty) {
state.attachments.value = List.from(initialState!.attachments);
}
}
return null;
}, [initialState]);
// Load draft if available (only for new posts without initial state)
useEffect(() {
if (originalPost == null &&
effectiveForwardedPost == null &&
effectiveRepliedPost == null) {
effectiveRepliedPost == null &&
initialState == null) {
// Try to load the most recent draft
final drafts = ref.read(composeStorageNotifierProvider);
if (drafts.isNotEmpty) {

View File

@ -0,0 +1,166 @@
// dart format width=80
// coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'compose.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// dart format off
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$PostComposeInitialState {
String? get title; String? get description; String? get content; List<UniversalFile> get attachments; int? get visibility;
/// Create a copy of PostComposeInitialState
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$PostComposeInitialStateCopyWith<PostComposeInitialState> get copyWith => _$PostComposeInitialStateCopyWithImpl<PostComposeInitialState>(this as PostComposeInitialState, _$identity);
/// Serializes this PostComposeInitialState to a JSON map.
Map<String, dynamic> toJson();
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is PostComposeInitialState&&(identical(other.title, title) || other.title == title)&&(identical(other.description, description) || other.description == description)&&(identical(other.content, content) || other.content == content)&&const DeepCollectionEquality().equals(other.attachments, attachments)&&(identical(other.visibility, visibility) || other.visibility == visibility));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,title,description,content,const DeepCollectionEquality().hash(attachments),visibility);
@override
String toString() {
return 'PostComposeInitialState(title: $title, description: $description, content: $content, attachments: $attachments, visibility: $visibility)';
}
}
/// @nodoc
abstract mixin class $PostComposeInitialStateCopyWith<$Res> {
factory $PostComposeInitialStateCopyWith(PostComposeInitialState value, $Res Function(PostComposeInitialState) _then) = _$PostComposeInitialStateCopyWithImpl;
@useResult
$Res call({
String? title, String? description, String? content, List<UniversalFile> attachments, int? visibility
});
}
/// @nodoc
class _$PostComposeInitialStateCopyWithImpl<$Res>
implements $PostComposeInitialStateCopyWith<$Res> {
_$PostComposeInitialStateCopyWithImpl(this._self, this._then);
final PostComposeInitialState _self;
final $Res Function(PostComposeInitialState) _then;
/// Create a copy of PostComposeInitialState
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? title = freezed,Object? description = freezed,Object? content = freezed,Object? attachments = null,Object? visibility = freezed,}) {
return _then(_self.copyWith(
title: freezed == title ? _self.title : title // ignore: cast_nullable_to_non_nullable
as String?,description: freezed == description ? _self.description : description // ignore: cast_nullable_to_non_nullable
as String?,content: freezed == content ? _self.content : content // ignore: cast_nullable_to_non_nullable
as String?,attachments: null == attachments ? _self.attachments : attachments // ignore: cast_nullable_to_non_nullable
as List<UniversalFile>,visibility: freezed == visibility ? _self.visibility : visibility // ignore: cast_nullable_to_non_nullable
as int?,
));
}
}
/// @nodoc
@JsonSerializable()
class _PostComposeInitialState implements PostComposeInitialState {
const _PostComposeInitialState({this.title, this.description, this.content, final List<UniversalFile> attachments = const [], this.visibility}): _attachments = attachments;
factory _PostComposeInitialState.fromJson(Map<String, dynamic> json) => _$PostComposeInitialStateFromJson(json);
@override final String? title;
@override final String? description;
@override final String? content;
final List<UniversalFile> _attachments;
@override@JsonKey() List<UniversalFile> get attachments {
if (_attachments is EqualUnmodifiableListView) return _attachments;
// ignore: implicit_dynamic_type
return EqualUnmodifiableListView(_attachments);
}
@override final int? visibility;
/// Create a copy of PostComposeInitialState
/// with the given fields replaced by the non-null parameter values.
@override @JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$PostComposeInitialStateCopyWith<_PostComposeInitialState> get copyWith => __$PostComposeInitialStateCopyWithImpl<_PostComposeInitialState>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$PostComposeInitialStateToJson(this, );
}
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _PostComposeInitialState&&(identical(other.title, title) || other.title == title)&&(identical(other.description, description) || other.description == description)&&(identical(other.content, content) || other.content == content)&&const DeepCollectionEquality().equals(other._attachments, _attachments)&&(identical(other.visibility, visibility) || other.visibility == visibility));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,title,description,content,const DeepCollectionEquality().hash(_attachments),visibility);
@override
String toString() {
return 'PostComposeInitialState(title: $title, description: $description, content: $content, attachments: $attachments, visibility: $visibility)';
}
}
/// @nodoc
abstract mixin class _$PostComposeInitialStateCopyWith<$Res> implements $PostComposeInitialStateCopyWith<$Res> {
factory _$PostComposeInitialStateCopyWith(_PostComposeInitialState value, $Res Function(_PostComposeInitialState) _then) = __$PostComposeInitialStateCopyWithImpl;
@override @useResult
$Res call({
String? title, String? description, String? content, List<UniversalFile> attachments, int? visibility
});
}
/// @nodoc
class __$PostComposeInitialStateCopyWithImpl<$Res>
implements _$PostComposeInitialStateCopyWith<$Res> {
__$PostComposeInitialStateCopyWithImpl(this._self, this._then);
final _PostComposeInitialState _self;
final $Res Function(_PostComposeInitialState) _then;
/// Create a copy of PostComposeInitialState
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? title = freezed,Object? description = freezed,Object? content = freezed,Object? attachments = null,Object? visibility = freezed,}) {
return _then(_PostComposeInitialState(
title: freezed == title ? _self.title : title // ignore: cast_nullable_to_non_nullable
as String?,description: freezed == description ? _self.description : description // ignore: cast_nullable_to_non_nullable
as String?,content: freezed == content ? _self.content : content // ignore: cast_nullable_to_non_nullable
as String?,attachments: null == attachments ? _self._attachments : attachments // ignore: cast_nullable_to_non_nullable
as List<UniversalFile>,visibility: freezed == visibility ? _self.visibility : visibility // ignore: cast_nullable_to_non_nullable
as int?,
));
}
}
// dart format on

View File

@ -0,0 +1,31 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'compose.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_PostComposeInitialState _$PostComposeInitialStateFromJson(
Map<String, dynamic> json,
) => _PostComposeInitialState(
title: json['title'] as String?,
description: json['description'] as String?,
content: json['content'] as String?,
attachments:
(json['attachments'] as List<dynamic>?)
?.map((e) => UniversalFile.fromJson(e as Map<String, dynamic>))
.toList() ??
const [],
visibility: (json['visibility'] as num?)?.toInt(),
);
Map<String, dynamic> _$PostComposeInitialStateToJson(
_PostComposeInitialState instance,
) => <String, dynamic>{
'title': instance.title,
'description': instance.description,
'content': instance.content,
'attachments': instance.attachments.map((e) => e.toJson()).toList(),
'visibility': instance.visibility,
};

View File

@ -110,7 +110,7 @@ class SettingsScreen extends HookConsumerWidget {
ref
.read(appSettingsNotifierProvider.notifier)
.setCustomFonts(null);
showSnackBar(context, 'settingsApplied'.tr());
showSnackBar('settingsApplied'.tr());
},
),
border: OutlineInputBorder(
@ -122,7 +122,7 @@ class SettingsScreen extends HookConsumerWidget {
ref
.read(appSettingsNotifierProvider.notifier)
.setCustomFonts(value.isEmpty ? null : value);
showSnackBar(context, 'settingsApplied'.tr());
showSnackBar('settingsApplied'.tr());
},
),
),
@ -215,7 +215,7 @@ class SettingsScreen extends HookConsumerWidget {
prefs.setBool(kAppBackgroundStoreKey, true);
ref.invalidate(backgroundImageFileProvider);
if (context.mounted) {
showSnackBar(context, 'settingsApplied'.tr());
showSnackBar('settingsApplied'.tr());
}
},
),
@ -243,7 +243,7 @@ class SettingsScreen extends HookConsumerWidget {
prefs.remove(kAppBackgroundStoreKey);
ref.invalidate(backgroundImageFileProvider);
if (context.mounted) {
showSnackBar(context, 'settingsApplied'.tr());
showSnackBar('settingsApplied'.tr());
}
},
);
@ -290,7 +290,7 @@ class SettingsScreen extends HookConsumerWidget {
.setAppColorScheme(color.value);
if (context.mounted) {
hideLoadingModal(context);
showSnackBar(context, 'settingsApplied'.tr());
showSnackBar('settingsApplied'.tr());
}
},
);
@ -321,7 +321,7 @@ class SettingsScreen extends HookConsumerWidget {
kNetworkServerDefault,
);
ref.invalidate(serverUrlProvider);
showSnackBar(context, 'settingsApplied'.tr());
showSnackBar('settingsApplied'.tr());
},
),
border: OutlineInputBorder(
@ -333,7 +333,7 @@ class SettingsScreen extends HookConsumerWidget {
if (value.isNotEmpty) {
prefs.setString(kNetworkServerStoreKey, value);
ref.invalidate(serverUrlProvider);
showSnackBar(context, 'settingsApplied'.tr());
showSnackBar('settingsApplied'.tr());
}
},
),

View File

@ -1,3 +1,4 @@
import 'dart:developer';
import 'dart:ui';
import 'package:auto_route/auto_route.dart';
import 'package:easy_localization/easy_localization.dart';
@ -6,8 +7,40 @@ import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/route.gr.dart';
import 'package:island/screens/notification.dart';
import 'package:island/services/responsive.dart';
import 'package:island/widgets/navigation/conditional_bottom_nav.dart';
import 'package:material_symbols_icons/symbols.dart';
final currentRouteProvider = StateProvider<String?>((ref) => null);
class TabNavigationObserver extends AutoRouterObserver {
Function(String?) onChange;
TabNavigationObserver({required this.onChange});
@override
void didPush(Route route, Route? previousRoute) {
log('pushed ${previousRoute?.settings.name} -> ${route.settings.name}');
if (route is DialogRoute) return;
final name = route.settings.name;
if (name == null) return;
if (name.contains('Shell')) return;
Future(() {
onChange(name);
});
}
@override
void didPop(Route route, Route? previousRoute) {
log('popped ${route.settings.name} -> ${previousRoute?.settings.name}');
if (previousRoute is DialogRoute) return;
final name = previousRoute?.settings.name;
if (name == null) return;
if (name.contains('Shell')) return;
Future(() {
onChange(name);
});
}
}
@RoutePage()
class TabsScreen extends HookConsumerWidget {
const TabsScreen({super.key});
@ -41,10 +74,10 @@ class TabsScreen extends HookConsumerWidget {
];
final routes = <PageRouteInfo>[
ExploreRoute(),
ChatListRoute(),
ExploreShellRoute(),
ChatShellRoute(),
RealmListRoute(),
AccountRoute(),
AccountShellRoute(),
];
return AutoTabsRouter.tabBar(
@ -83,31 +116,33 @@ class TabsScreen extends HookConsumerWidget {
left: 0,
right: 0,
bottom: 0,
child: ClipRRect(
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
child: Container(
decoration: BoxDecoration(
color: Theme.of(
context,
).colorScheme.surface.withOpacity(0.8),
),
child: MediaQuery.removePadding(
context: context,
removeTop: true,
child: NavigationBar(
backgroundColor: Colors.transparent,
shadowColor: Colors.transparent,
overlayColor: WidgetStatePropertyAll(
Colors.transparent,
child: ConditionalBottomNav(
child: ClipRRect(
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
child: Container(
decoration: BoxDecoration(
color: Theme.of(
context,
).colorScheme.surface.withOpacity(0.8),
),
child: MediaQuery.removePadding(
context: context,
removeTop: true,
child: NavigationBar(
backgroundColor: Colors.transparent,
shadowColor: Colors.transparent,
overlayColor: const WidgetStatePropertyAll(
Colors.transparent,
),
surfaceTintColor: Colors.transparent,
height: 56,
labelBehavior:
NavigationDestinationLabelBehavior.alwaysHide,
selectedIndex: tabsRouter.activeIndex,
onDestinationSelected: tabsRouter.setActiveIndex,
destinations: destinations,
),
surfaceTintColor: Colors.transparent,
height: 56,
labelBehavior:
NavigationDestinationLabelBehavior.alwaysHide,
selectedIndex: tabsRouter.activeIndex,
onDestinationSelected: tabsRouter.setActiveIndex,
destinations: destinations,
),
),
),

View File

@ -1,9 +1,57 @@
import 'dart:async';
import 'dart:developer';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:island/main.dart';
import 'package:island/models/user.dart';
import 'package:island/pods/websocket.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';
StreamSubscription<WebSocketPacket> setupNotificationListener(
BuildContext context,
WidgetRef ref,
) {
final ws = ref.watch(websocketProvider);
return ws.dataStream.listen((pkt) {
if (pkt.type == "notifications.new") {
final notification = SnNotification.fromJson(pkt.data!);
showTopSnackBar(
globalOverlay.currentState!,
NotificationCard(notification: notification),
onTap: () {
if (notification.meta['action_uri'] != null) {
var uri = notification.meta['action_uri'] as String;
if (uri.startsWith('/')) {
// In-app routes
appRouter.pushPath(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,
// ignore: use_build_context_synchronously
top: MediaQuery.of(context).padding.top + 24,
bottom: 16,
),
);
}
});
}
Future<void> subscribePushNotification(Dio apiClient) async {
await FirebaseMessaging.instance.requestPermission(

View File

@ -1,9 +1,10 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:receive_sharing_intent/receive_sharing_intent.dart';
import 'package:island/widgets/share/share_sheet.dart';
import 'package:share_plus/share_plus.dart';
import 'package:easy_localization/easy_localization.dart';
class SharingIntentService {
static final SharingIntentService _instance =
@ -16,6 +17,7 @@ class SharingIntentService {
/// Initialize the sharing intent service
void initialize(BuildContext context) {
if (kIsWeb || !(Platform.isIOS || Platform.isAndroid)) return;
debugPrint("SharingIntentService: Initializing with context");
_context = context;
_setupSharingListeners();
@ -73,14 +75,44 @@ class SharingIntentService {
);
}
// Convert SharedMediaFile to XFile
// Convert SharedMediaFile to XFile for files
final List<XFile> files =
sharedFiles
.where(
(file) =>
file.type == SharedMediaType.file ||
file.type == SharedMediaType.video ||
file.type == SharedMediaType.image,
)
.map((file) => XFile(file.path, name: file.path.split('/').last))
.toList();
// Extract links from shared content
final List<String> links =
sharedFiles
.where((file) => file.type == SharedMediaType.url)
.map((file) => file.path)
.toList();
// Show ShareSheet with the shared files
showShareSheet(context: _context!, content: ShareContent.files(files));
if (files.isNotEmpty) {
showShareSheet(context: _context!, content: ShareContent.files(files));
} else if (links.isNotEmpty) {
showShareSheet(
context: _context!,
content: ShareContent.link(links.first),
);
} else {
showShareSheet(
context: _context!,
content: ShareContent.text(
sharedFiles
.where((file) => file.type == SharedMediaType.text)
.map((text) => text.message)
.join('\n'),
),
);
}
}
/// Dispose of resources

View File

@ -38,7 +38,7 @@ class RestorePurchaseSheet extends HookConsumerWidget {
if (context.mounted) {
Navigator.pop(context);
showSnackBar(context, 'Purchase restored successfully!');
showSnackBar('Purchase restored successfully!');
}
} catch (err) {
showErrorAlert(err);

View File

@ -1,31 +1,18 @@
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:gap/gap.dart';
import 'package:island/services/responsive.dart';
import 'package:island/main.dart';
import 'package:styled_widget/styled_widget.dart';
import 'package:top_snackbar_flutter/top_snack_bar.dart';
export 'content/alert.native.dart'
if (dart.library.html) 'content/alert.web.dart';
void showSnackBar(
BuildContext context,
String message, {
SnackBarAction? action,
}) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(message),
action: action,
margin:
isWideScreen(context)
? null
: EdgeInsets.fromLTRB(
15.0,
5.0,
15.0,
MediaQuery.of(context).padding.bottom + 28,
),
),
void showSnackBar(String message, {SnackBarAction? action}) {
showTopSnackBar(
globalOverlay.currentState!,
Card(child: Text(message).padding(horizontal: 20, vertical: 16)),
snackBarPosition: SnackBarPosition.bottom,
);
}

View File

@ -1,235 +1,18 @@
import 'dart:async';
import 'dart:developer';
import 'package:flutter/foundation.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/main.dart';
import 'package:island/models/user.dart';
import 'package:island/pods/websocket.dart';
import 'package:island/widgets/content/cloud_files.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:styled_widget/styled_widget.dart';
import 'package:url_launcher/url_launcher_string.dart';
part 'app_notification.freezed.dart';
part 'app_notification.g.dart';
class NotificationCard extends HookConsumerWidget {
final SnNotification notification;
class AppNotificationToast extends HookConsumerWidget {
const AppNotificationToast({super.key});
const NotificationCard({super.key, required this.notification});
@override
Widget build(BuildContext context, WidgetRef ref) {
final notifications = ref.watch(appNotificationsProvider);
// Create a global key for AnimatedList
final listKey = useMemoized(() => GlobalKey<AnimatedListState>());
// Track visual notification count (including those being animated out)
final visualCount = useState(notifications.length);
// Track notifications being removed to manage visual count
final animatingOutIds = useState<Set<String>>({});
// Track previous notifications to detect changes
final previousNotifications = usePrevious(notifications) ?? [];
// Handle notification changes
useEffect(() {
final currentIds = notifications.map((n) => n.data.id).toSet();
final previousIds = previousNotifications.map((n) => n.data.id).toSet();
// Find new notifications (added)
final newIds = currentIds.difference(previousIds);
// Update visual count for new notifications
if (newIds.isNotEmpty) {
visualCount.value += newIds.length;
}
// Insert new notifications with animation
for (final id in newIds) {
final index = notifications.indexWhere((n) => n.data.id == id);
if (index != -1 &&
listKey.currentState != null &&
index >= 0 &&
index <= notifications.length) {
try {
listKey.currentState!.insertItem(
index,
duration: const Duration(milliseconds: 150),
);
} catch (e) {
// Log error but don't crash the app
debugPrint('Error inserting notification: $e');
}
}
}
return null;
}, [notifications]);
return Positioned(
top: MediaQuery.of(context).padding.top + 50,
left: 16,
right: 16,
child: SizedBox(
// Use visualCount instead of notifications.length for height calculation
height: visualCount.value * 80,
child: AnimatedList(
physics: NeverScrollableScrollPhysics(),
padding: EdgeInsets.zero,
key: listKey,
initialItemCount: notifications.length,
itemBuilder: (context, index, animation) {
// Safely access notifications with bounds check
if (index >= notifications.length) {
return const SizedBox.shrink(); // Return empty widget if out of bounds
}
final notification = notifications[index];
final now = DateTime.now();
final createdAt = notification.createdAt ?? now;
final duration =
notification.duration ?? const Duration(seconds: 5);
final elapsedTime = now.difference(createdAt);
final remainingTime = duration - elapsedTime;
final progress =
1.0 -
(remainingTime.inMilliseconds / duration.inMilliseconds).clamp(
0.0,
1.0,
); // Ensure progress is clamped
return SizeTransition(
sizeFactor: animation.drive(
CurveTween(curve: Curves.fastLinearToSlowEaseIn),
),
child: _NotificationCard(
notification: notification,
progress: progress.clamp(0.0, 1.0),
onDismiss: () {
// Find the current index before removal
final currentIndex = notifications.indexWhere(
(n) => n.data.id == notification.data.id,
);
// Add to animating out set
final notificationId = notification.data.id;
if (!animatingOutIds.value.contains(notificationId)) {
animatingOutIds.value = {
...animatingOutIds.value,
notificationId,
};
}
if (currentIndex != -1 &&
listKey.currentState != null &&
currentIndex >= 0 &&
currentIndex < notifications.length) {
try {
// Remove the item with animation
listKey.currentState!.removeItem(
currentIndex,
(context, animation) => SizeTransition(
sizeFactor: animation.drive(
CurveTween(curve: Curves.fastLinearToSlowEaseIn),
),
child: _NotificationCard(
notification: notification,
progress: progress.clamp(0.0, 1.0),
onDismiss:
() {}, // Empty because it's being removed
),
),
duration: const Duration(milliseconds: 150),
// When animation completes, update the visual count
);
// Schedule decrementing the visual count after animation completes
Future.delayed(const Duration(milliseconds: 150), () {
if (animatingOutIds.value.contains(notificationId)) {
visualCount.value =
visualCount.value > 0 ? visualCount.value - 1 : 0;
animatingOutIds.value =
animatingOutIds.value
.where((id) => id != notificationId)
.toSet();
}
});
} catch (e) {
// Log error but don't crash the app
log('[Notification] Error removing notification: $e');
// Still update visual count in case of error
visualCount.value =
visualCount.value > 0 ? visualCount.value - 1 : 0;
animatingOutIds.value =
animatingOutIds.value
.where((id) => id != notificationId)
.toSet();
}
}
// Actually remove from state
ref
.read(appNotificationsProvider.notifier)
.removeNotification(notification);
},
),
);
},
),
),
);
}
}
class _NotificationCard extends HookConsumerWidget {
final AppNotification notification;
final double progress;
final VoidCallback onDismiss;
const _NotificationCard({
required this.notification,
required this.progress,
required this.onDismiss,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
// Use state to track the current progress for smooth animation
final progressState = useState(progress);
// Use effect to update progress smoothly
useEffect(() {
if (progress < 1.0) {
// Update progress every 16ms (roughly 60fps) for smooth animation
final timer = Timer.periodic(const Duration(milliseconds: 16), (_) {
final now = DateTime.now();
final createdAt = notification.createdAt ?? now;
final duration = notification.duration ?? const Duration(seconds: 5);
final elapsedTime = now.difference(createdAt);
final remainingTime = duration - elapsedTime;
final newProgress = (1.0 -
(remainingTime.inMilliseconds / duration.inMilliseconds))
.clamp(0.0, 1.0);
progressState.value = newProgress;
// Auto-dismiss when complete
if (newProgress >= 1.0) {
onDismiss();
}
});
return timer.cancel;
}
return null;
}, [notification.createdAt, notification.duration]);
final icon = Symbols.info;
return Card(
elevation: 4,
@ -237,225 +20,52 @@ class _NotificationCard extends HookConsumerWidget {
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(bottom: Radius.circular(8)),
),
child: InkWell(
borderRadius: const BorderRadius.all(Radius.circular(8)),
onTap: () {
if (notification.data.meta['action_uri'] != null) {
var uri = notification.data.meta['action_uri'] as String;
if (uri.startsWith('/')) {
// In-app routes
appRouter.pushPath(notification.data.meta['action_uri']);
} else {
// External URLs
launchUrlString(uri);
}
onDismiss();
}
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
// Progress indicator
if (progressState.value > 0 && progressState.value < 1.0)
AnimatedBuilder(
animation: progressState,
builder: (context, _) {
return LinearProgressIndicator(
borderRadius: BorderRadius.vertical(
top: Radius.circular(16),
),
value: 1.0 - progressState.value,
backgroundColor: Colors.transparent,
color: Theme.of(context).colorScheme.tertiary,
minHeight: 3,
stopIndicatorColor: Colors.transparent,
stopIndicatorRadius: 0,
);
},
),
Padding(
padding: const EdgeInsets.all(12),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (notification.data.meta['avatar'] != null)
ProfilePictureWidget(
fileId: notification.data.meta['avatar'],
radius: 12,
).padding(right: 12, top: 2)
else if (notification.icon != null)
Icon(
notification.icon,
color: Theme.of(context).colorScheme.primary,
size: 24,
).padding(right: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.all(12),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (notification.meta['pfp'] != null)
ProfilePictureWidget(
fileId: notification.meta['pfp'],
radius: 12,
).padding(right: 12, top: 2)
else
Icon(
icon,
color: Theme.of(context).colorScheme.primary,
size: 24,
).padding(right: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
notification.title,
style: Theme.of(context).textTheme.titleMedium
?.copyWith(fontWeight: FontWeight.bold),
),
if (notification.content.isNotEmpty)
Text(
notification.data.title,
style: Theme.of(context).textTheme.titleMedium
?.copyWith(fontWeight: FontWeight.bold),
notification.content,
style: Theme.of(context).textTheme.bodyMedium,
),
if (notification.data.content.isNotEmpty)
Text(
notification.data.content,
style: Theme.of(context).textTheme.bodyMedium,
),
if (notification.data.subtitle.isNotEmpty)
Text(
notification.data.subtitle,
style: Theme.of(context).textTheme.bodySmall,
),
],
),
if (notification.subtitle.isNotEmpty)
Text(
notification.subtitle,
style: Theme.of(context).textTheme.bodySmall,
),
],
),
IconButton(
icon: const Icon(Symbols.close, size: 18),
onPressed: onDismiss,
padding: EdgeInsets.zero,
constraints: const BoxConstraints(),
),
],
),
),
],
),
],
),
),
);
}
}
@freezed
sealed class AppNotification with _$AppNotification {
const factory AppNotification({
required SnNotification data,
@JsonKey(ignore: true) IconData? icon,
@JsonKey(ignore: true) Duration? duration,
@Default(null) DateTime? createdAt,
@Default(false) @JsonKey(ignore: true) bool isAnimatingOut,
}) = _AppNotification;
factory AppNotification.fromJson(Map<String, dynamic> json) =>
_$AppNotificationFromJson(json);
}
// Using riverpod_generator for cleaner provider code
@riverpod
class AppNotifications extends _$AppNotifications {
StreamSubscription? _subscription;
@override
List<AppNotification> build() {
ref.onDispose(() {
_subscription?.cancel();
});
_initWebSocketListener();
return [];
}
void _initWebSocketListener() {
final service = ref.read(websocketProvider);
_subscription = service.dataStream.listen((packet) {
// Handle notification packets
if (packet.type == 'notifications.new') {
try {
final data = SnNotification.fromJson(packet.data!);
IconData? icon;
switch (data.topic) {
case 'general':
default:
icon = Symbols.info;
break;
}
addNotification(
AppNotification(
data: data,
icon: icon,
createdAt: data.createdAt.toLocal(),
duration: const Duration(seconds: 5),
),
);
} catch (e) {
log('[Notification] Error processing notification: $e');
}
}
});
}
void addNotification(AppNotification notification) {
// Create a new notification with createdAt if not provided
final newNotification =
notification.createdAt == null
? notification.copyWith(createdAt: DateTime.now())
: notification;
// Add to state
state = [...state, newNotification];
// Auto-remove notification after duration
final duration = newNotification.duration ?? const Duration(seconds: 5);
Future.delayed(duration, () {
// Find the notification in the current state
final notificationToRemove = state.firstWhereOrNull(
(n) => n.data.id == newNotification.data.id,
);
// Only proceed if the notification still exists in state
if (notificationToRemove != null) {
// Call removeNotification which will handle the animation
removeNotification(notificationToRemove);
}
});
}
// Map to track notifications that are being animated out
final Map<String, bool> _animatingNotifications = {};
// Map to track which notifications should animate out
final Map<String, bool> _animatingOutNotifications = {};
void removeNotification(AppNotification notification) {
final notificationId = notification.data.id;
// If this notification is already being removed, don't do anything
if (_animatingNotifications[notificationId] == true) {
return;
}
// Mark this notification as being removed
_animatingNotifications[notificationId] = true;
// Remove from state immediately - AnimatedList handles the animation
state = state.where((n) => n.data.id != notificationId).toList();
// Clean up tracking
_animatingNotifications.remove(notificationId);
_animatingOutNotifications.remove(notificationId);
}
// Helper method to check if a notification should animate out
bool isAnimatingOut(String notificationId) {
return _animatingOutNotifications[notificationId] == true;
}
// Helper method to manually add a notification for testing
void showNotification({
required SnNotification data,
IconData? icon,
Duration? duration,
}) {
addNotification(
AppNotification(
data: data,
icon: icon,
duration: duration,
createdAt: data.createdAt,
),
],
),
);
}

View File

@ -1,190 +0,0 @@
// dart format width=80
// coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'app_notification.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// dart format off
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$AppNotification implements DiagnosticableTreeMixin {
SnNotification get data;@JsonKey(ignore: true) IconData? get icon;@JsonKey(ignore: true) Duration? get duration; DateTime? get createdAt;@JsonKey(ignore: true) bool get isAnimatingOut;
/// Create a copy of AppNotification
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$AppNotificationCopyWith<AppNotification> get copyWith => _$AppNotificationCopyWithImpl<AppNotification>(this as AppNotification, _$identity);
/// Serializes this AppNotification to a JSON map.
Map<String, dynamic> toJson();
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
properties
..add(DiagnosticsProperty('type', 'AppNotification'))
..add(DiagnosticsProperty('data', data))..add(DiagnosticsProperty('icon', icon))..add(DiagnosticsProperty('duration', duration))..add(DiagnosticsProperty('createdAt', createdAt))..add(DiagnosticsProperty('isAnimatingOut', isAnimatingOut));
}
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is AppNotification&&(identical(other.data, data) || other.data == data)&&(identical(other.icon, icon) || other.icon == icon)&&(identical(other.duration, duration) || other.duration == duration)&&(identical(other.createdAt, createdAt) || other.createdAt == createdAt)&&(identical(other.isAnimatingOut, isAnimatingOut) || other.isAnimatingOut == isAnimatingOut));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,data,icon,duration,createdAt,isAnimatingOut);
@override
String toString({ DiagnosticLevel minLevel = DiagnosticLevel.info }) {
return 'AppNotification(data: $data, icon: $icon, duration: $duration, createdAt: $createdAt, isAnimatingOut: $isAnimatingOut)';
}
}
/// @nodoc
abstract mixin class $AppNotificationCopyWith<$Res> {
factory $AppNotificationCopyWith(AppNotification value, $Res Function(AppNotification) _then) = _$AppNotificationCopyWithImpl;
@useResult
$Res call({
SnNotification data,@JsonKey(ignore: true) IconData? icon,@JsonKey(ignore: true) Duration? duration, DateTime? createdAt,@JsonKey(ignore: true) bool isAnimatingOut
});
$SnNotificationCopyWith<$Res> get data;
}
/// @nodoc
class _$AppNotificationCopyWithImpl<$Res>
implements $AppNotificationCopyWith<$Res> {
_$AppNotificationCopyWithImpl(this._self, this._then);
final AppNotification _self;
final $Res Function(AppNotification) _then;
/// Create a copy of AppNotification
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? data = null,Object? icon = freezed,Object? duration = freezed,Object? createdAt = freezed,Object? isAnimatingOut = null,}) {
return _then(_self.copyWith(
data: null == data ? _self.data : data // ignore: cast_nullable_to_non_nullable
as SnNotification,icon: freezed == icon ? _self.icon : icon // ignore: cast_nullable_to_non_nullable
as IconData?,duration: freezed == duration ? _self.duration : duration // ignore: cast_nullable_to_non_nullable
as Duration?,createdAt: freezed == createdAt ? _self.createdAt : createdAt // ignore: cast_nullable_to_non_nullable
as DateTime?,isAnimatingOut: null == isAnimatingOut ? _self.isAnimatingOut : isAnimatingOut // ignore: cast_nullable_to_non_nullable
as bool,
));
}
/// Create a copy of AppNotification
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$SnNotificationCopyWith<$Res> get data {
return $SnNotificationCopyWith<$Res>(_self.data, (value) {
return _then(_self.copyWith(data: value));
});
}
}
/// @nodoc
@JsonSerializable()
class _AppNotification with DiagnosticableTreeMixin implements AppNotification {
const _AppNotification({required this.data, @JsonKey(ignore: true) this.icon, @JsonKey(ignore: true) this.duration, this.createdAt = null, @JsonKey(ignore: true) this.isAnimatingOut = false});
factory _AppNotification.fromJson(Map<String, dynamic> json) => _$AppNotificationFromJson(json);
@override final SnNotification data;
@override@JsonKey(ignore: true) final IconData? icon;
@override@JsonKey(ignore: true) final Duration? duration;
@override@JsonKey() final DateTime? createdAt;
@override@JsonKey(ignore: true) final bool isAnimatingOut;
/// Create a copy of AppNotification
/// with the given fields replaced by the non-null parameter values.
@override @JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$AppNotificationCopyWith<_AppNotification> get copyWith => __$AppNotificationCopyWithImpl<_AppNotification>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$AppNotificationToJson(this, );
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
properties
..add(DiagnosticsProperty('type', 'AppNotification'))
..add(DiagnosticsProperty('data', data))..add(DiagnosticsProperty('icon', icon))..add(DiagnosticsProperty('duration', duration))..add(DiagnosticsProperty('createdAt', createdAt))..add(DiagnosticsProperty('isAnimatingOut', isAnimatingOut));
}
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _AppNotification&&(identical(other.data, data) || other.data == data)&&(identical(other.icon, icon) || other.icon == icon)&&(identical(other.duration, duration) || other.duration == duration)&&(identical(other.createdAt, createdAt) || other.createdAt == createdAt)&&(identical(other.isAnimatingOut, isAnimatingOut) || other.isAnimatingOut == isAnimatingOut));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,data,icon,duration,createdAt,isAnimatingOut);
@override
String toString({ DiagnosticLevel minLevel = DiagnosticLevel.info }) {
return 'AppNotification(data: $data, icon: $icon, duration: $duration, createdAt: $createdAt, isAnimatingOut: $isAnimatingOut)';
}
}
/// @nodoc
abstract mixin class _$AppNotificationCopyWith<$Res> implements $AppNotificationCopyWith<$Res> {
factory _$AppNotificationCopyWith(_AppNotification value, $Res Function(_AppNotification) _then) = __$AppNotificationCopyWithImpl;
@override @useResult
$Res call({
SnNotification data,@JsonKey(ignore: true) IconData? icon,@JsonKey(ignore: true) Duration? duration, DateTime? createdAt,@JsonKey(ignore: true) bool isAnimatingOut
});
@override $SnNotificationCopyWith<$Res> get data;
}
/// @nodoc
class __$AppNotificationCopyWithImpl<$Res>
implements _$AppNotificationCopyWith<$Res> {
__$AppNotificationCopyWithImpl(this._self, this._then);
final _AppNotification _self;
final $Res Function(_AppNotification) _then;
/// Create a copy of AppNotification
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? data = null,Object? icon = freezed,Object? duration = freezed,Object? createdAt = freezed,Object? isAnimatingOut = null,}) {
return _then(_AppNotification(
data: null == data ? _self.data : data // ignore: cast_nullable_to_non_nullable
as SnNotification,icon: freezed == icon ? _self.icon : icon // ignore: cast_nullable_to_non_nullable
as IconData?,duration: freezed == duration ? _self.duration : duration // ignore: cast_nullable_to_non_nullable
as Duration?,createdAt: freezed == createdAt ? _self.createdAt : createdAt // ignore: cast_nullable_to_non_nullable
as DateTime?,isAnimatingOut: null == isAnimatingOut ? _self.isAnimatingOut : isAnimatingOut // ignore: cast_nullable_to_non_nullable
as bool,
));
}
/// Create a copy of AppNotification
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$SnNotificationCopyWith<$Res> get data {
return $SnNotificationCopyWith<$Res>(_self.data, (value) {
return _then(_self.copyWith(data: value));
});
}
}
// dart format on

View File

@ -1,48 +0,0 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'app_notification.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_AppNotification _$AppNotificationFromJson(Map<String, dynamic> json) =>
_AppNotification(
data: SnNotification.fromJson(json['data'] as Map<String, dynamic>),
createdAt:
json['created_at'] == null
? null
: DateTime.parse(json['created_at'] as String),
);
Map<String, dynamic> _$AppNotificationToJson(_AppNotification instance) =>
<String, dynamic>{
'data': instance.data.toJson(),
'created_at': instance.createdAt?.toIso8601String(),
};
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
String _$appNotificationsHash() => r'a7e7e1d1533e329b000d4b294e455b8420ec3c4d';
/// See also [AppNotifications].
@ProviderFor(AppNotifications)
final appNotificationsProvider = AutoDisposeNotifierProvider<
AppNotifications,
List<AppNotification>
>.internal(
AppNotifications.new,
name: r'appNotificationsProvider',
debugGetCreateSourceHash:
const bool.fromEnvironment('dart.vm.product')
? null
: _$appNotificationsHash,
dependencies: null,
allTransitiveDependencies: null,
);
typedef _$AppNotifications = AutoDisposeNotifier<List<AppNotification>>;
// ignore_for_file: type=lint
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member, deprecated_member_use_from_same_package

View File

@ -12,7 +12,6 @@ import 'package:island/pods/userinfo.dart';
import 'package:island/pods/websocket.dart';
import 'package:island/route.dart';
import 'package:island/services/responsive.dart';
import 'package:island/widgets/app_notification.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart';
import 'package:path_provider/path_provider.dart';
import 'package:styled_widget/styled_widget.dart';
@ -26,24 +25,31 @@ class WindowScaffold extends HookConsumerWidget {
Widget build(BuildContext context, WidgetRef ref) {
// Add window resize listener for desktop platforms
useEffect(() {
if (!kIsWeb && (Platform.isWindows || Platform.isLinux || Platform.isMacOS)) {
if (!kIsWeb &&
(Platform.isWindows || Platform.isLinux || Platform.isMacOS)) {
void saveWindowSize() {
final size = appWindow.size;
final settingsNotifier = ref.read(appSettingsNotifierProvider.notifier);
final settingsNotifier = ref.read(
appSettingsNotifierProvider.notifier,
);
settingsNotifier.setWindowSize(size);
}
// Save window size when app is about to close
WidgetsBinding.instance.addObserver(_WindowSizeObserver(saveWindowSize));
WidgetsBinding.instance.addObserver(
_WindowSizeObserver(saveWindowSize),
);
return () {
// Cleanup observer when widget is disposed
WidgetsBinding.instance.removeObserver(_WindowSizeObserver(saveWindowSize));
WidgetsBinding.instance.removeObserver(
_WindowSizeObserver(saveWindowSize),
);
};
}
return null;
}, []);
if (!kIsWeb &&
(Platform.isWindows || Platform.isLinux || Platform.isMacOS)) {
final devicePixelRatio = MediaQuery.of(context).devicePixelRatio;
@ -106,7 +112,6 @@ class WindowScaffold extends HookConsumerWidget {
],
),
_WebSocketIndicator(),
AppNotificationToast(),
],
),
);
@ -114,39 +119,37 @@ class WindowScaffold extends HookConsumerWidget {
return Stack(
fit: StackFit.expand,
children: [
Positioned.fill(child: child),
_WebSocketIndicator(),
AppNotificationToast(),
],
children: [Positioned.fill(child: child), _WebSocketIndicator()],
);
}
}
class _WindowSizeObserver extends WidgetsBindingObserver {
final VoidCallback onSaveWindowSize;
_WindowSizeObserver(this.onSaveWindowSize);
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
// Save window size when app is paused, detached, or hidden
if (state == AppLifecycleState.paused ||
if (state == AppLifecycleState.paused ||
state == AppLifecycleState.detached ||
state == AppLifecycleState.hidden) {
if (!kIsWeb && (Platform.isWindows || Platform.isLinux || Platform.isMacOS)) {
if (!kIsWeb &&
(Platform.isWindows || Platform.isLinux || Platform.isMacOS)) {
onSaveWindowSize();
}
}
}
@override
bool operator ==(Object other) {
return other is _WindowSizeObserver && other.onSaveWindowSize == onSaveWindowSize;
return other is _WindowSizeObserver &&
other.onSaveWindowSize == onSaveWindowSize;
}
@override
int get hashCode => onSaveWindowSize.hashCode;
}

View File

@ -1,7 +1,10 @@
import 'dart:async';
import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/services/notify.dart';
import 'package:island/services/sharing_intent.dart';
@RoutePage()
@ -11,10 +14,15 @@ class AppWrapper extends HookConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
useEffect(() {
StreamSubscription? ntySubs;
Future(() {
if (context.mounted) ntySubs = setupNotificationListener(context, ref);
});
final sharingService = SharingIntentService();
sharingService.initialize(context);
return () {
sharingService.dispose();
ntySubs?.cancel();
};
}, const []);

View File

@ -5,6 +5,7 @@ import 'package:gap/gap.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/pods/call.dart';
import 'package:island/route.gr.dart';
import 'package:island/widgets/alert.dart';
import 'package:island/widgets/chat/call_participant_tile.dart';
import 'package:island/widgets/content/sheet.dart';
import 'package:styled_widget/styled_widget.dart';
@ -175,14 +176,7 @@ class CallControlsBar extends HookConsumerWidget {
},
);
} catch (e) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('${'failedToEnumerateDevices'.tr()}: $e'),
backgroundColor: Colors.red,
),
);
}
showErrorAlert(e);
}
}

View File

@ -11,6 +11,7 @@ import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/models/file.dart';
import 'package:island/pods/config.dart';
import 'package:island/pods/network.dart';
import 'package:island/widgets/alert.dart';
import 'package:island/widgets/content/cloud_files.dart';
import 'package:path/path.dart' show extension;
import 'package:path_provider/path_provider.dart';
@ -215,14 +216,7 @@ class CloudFileZoomIn extends HookConsumerWidget {
),
);
} catch (e) {
// Show error message
if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Failed to save image: $e'),
duration: const Duration(seconds: 2),
),
);
showErrorAlert(e);
}
}

View File

@ -94,7 +94,6 @@ class MarkdownTextContent extends HookConsumerWidget {
});
} else {
showSnackBar(
context,
'brokenLink'.tr(args: [href]),
action: SnackBarAction(
label: 'copyToClipboard'.tr(),

View File

@ -0,0 +1,27 @@
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/route.gr.dart';
import 'package:island/screens/tabs.dart';
class ConditionalBottomNav extends HookConsumerWidget {
final Widget child;
const ConditionalBottomNav({super.key, required this.child});
@override
Widget build(BuildContext context, WidgetRef ref) {
final currentRouteName = ref.watch(currentRouteProvider);
const mainTabRoutes = {
ExploreRoute.name,
ChatListRoute.name,
RealmListRoute.name,
AccountRoute.name,
};
debugPrint(currentRouteName);
final shouldShowBottomNav = mainTabRoutes.contains(currentRouteName);
return shouldShowBottomNav ? child : const SizedBox.shrink();
}
}

View File

@ -106,7 +106,9 @@ class _PaymentContent extends ConsumerStatefulWidget {
class _PaymentContentState extends ConsumerState<_PaymentContent> {
static const String _pinStorageKey = 'app_pin_code';
static final _secureStorage = FlutterSecureStorage();
static final _secureStorage = FlutterSecureStorage(
aOptions: AndroidOptions(encryptedSharedPreferences: true),
);
final LocalAuthentication _localAuth = LocalAuthentication();
@ -279,7 +281,7 @@ class _PaymentContentState extends ConsumerState<_PaymentContent> {
_isPinMode = true;
});
if (message != null && message.isNotEmpty) {
showSnackBar(context, message);
showSnackBar(message);
}
}

View File

@ -112,7 +112,11 @@ class ComposeLogic {
);
}
static Future<void> saveDraft(WidgetRef ref, ComposeState state, {int postType = 0}) async {
static Future<void> saveDraft(
WidgetRef ref,
ComposeState state, {
int postType = 0,
}) async {
final hasContent =
state.titleController.text.trim().isNotEmpty ||
state.descriptionController.text.trim().isNotEmpty ||
@ -142,7 +146,9 @@ class ComposeLogic {
fileData: attachment,
atk: token,
baseUrl: baseUrl,
filename: attachment.data.name ?? (postType == 1 ? 'Article media' : 'Post media'),
filename:
attachment.data.name ??
(postType == 1 ? 'Article media' : 'Post media'),
mimetype:
attachment.data.mimeType ??
ComposeLogic.getMimeTypeFromFileType(attachment.type),
@ -217,7 +223,11 @@ class ComposeLogic {
}
}
static Future<void> saveDraftWithoutUpload(WidgetRef ref, ComposeState state, {int postType = 0}) async {
static Future<void> saveDraftWithoutUpload(
WidgetRef ref,
ComposeState state, {
int postType = 0,
}) async {
final hasContent =
state.titleController.text.trim().isNotEmpty ||
state.descriptionController.text.trim().isNotEmpty ||
@ -346,12 +356,12 @@ class ComposeLogic {
await ref.read(composeStorageNotifierProvider.notifier).saveDraft(draft);
if (context.mounted) {
showSnackBar(context, 'draftSaved'.tr());
showSnackBar('draftSaved'.tr());
}
} catch (e) {
log('[ComposeLogic] Failed to save draft manually, error: $e');
if (context.mounted) {
showSnackBar(context, 'draftSaveFailed'.tr());
showSnackBar('draftSaveFailed'.tr());
}
}
}
@ -511,7 +521,7 @@ class ComposeLogic {
if (!hasContent && !hasAttachments) {
if (context.mounted) {
showSnackBar(context, 'postContentEmpty'.tr());
showSnackBar('postContentEmpty'.tr());
}
return; // Don't submit empty posts
}

View File

@ -8,6 +8,7 @@ import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'dart:math' as math;
import 'package:island/models/embed.dart';
import 'package:island/models/post.dart';
import 'package:island/pods/config.dart';
import 'package:island/pods/network.dart';
import 'package:island/pods/userinfo.dart';
import 'package:island/route.gr.dart';
@ -20,6 +21,7 @@ import 'package:island/widgets/content/cloud_file_collection.dart';
import 'package:island/widgets/content/cloud_files.dart';
import 'package:island/widgets/content/embed/link.dart';
import 'package:island/widgets/content/markdown.dart';
import 'package:island/widgets/safety/abuse_report_helper.dart';
import 'package:island/widgets/post/post_replies_sheet.dart';
import 'package:island/widgets/share/share_sheet.dart';
import 'package:material_symbols_icons/symbols.dart';
@ -125,18 +127,29 @@ class PostItem extends HookConsumerWidget {
context.router.push(PostComposeRoute(forwardedPost: item));
},
),
MenuSeparator(),
MenuAction(
title: 'share'.tr(),
image: MenuImage.icon(Symbols.share),
callback: () {
showShareSheetLink(
context: context,
link: 'https://solsynth.dev/posts/${item.id}',
link: '${ref.read(serverUrlProvider)}/posts/${item.id}',
title: 'sharePost'.tr(),
toSystem: true,
);
},
),
MenuAction(
title: 'abuseReport'.tr(),
image: MenuImage.icon(Symbols.flag),
callback: () {
showAbuseReportSheet(
context,
resourceIdentifier: 'posts:${item.id}',
);
},
),
],
);
},
@ -720,12 +733,16 @@ class _PostTruncateHint extends StatelessWidget {
color: Theme.of(context).colorScheme.secondary,
),
SizedBox(width: isCompact ? 4 : 6),
Text(
'postTruncated'.tr(),
style: TextStyle(
fontSize: isCompact ? 10 : 12,
color: Theme.of(context).colorScheme.secondary,
fontStyle: FontStyle.italic,
Flexible(
child: Text(
'postTruncated'.tr(),
style: TextStyle(
fontSize: isCompact ? 10 : 12,
color: Theme.of(context).colorScheme.secondary,
fontStyle: FontStyle.italic,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
SizedBox(width: isCompact ? 3 : 4),

View File

@ -0,0 +1,24 @@
import 'package:flutter/material.dart';
import 'package:island/widgets/safety/abuse_report_sheet.dart';
/// Helper function to show the safety report sheet
///
/// [context] - The build context
/// [resourceIdentifier] - The identifier of the resource being reported (e.g., post ID, user ID, etc.)
/// [initialReason] - Optional initial reason text to pre-fill the form
Future<void> showAbuseReportSheet(
BuildContext context, {
required String resourceIdentifier,
String? initialReason,
}) {
return showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
useRootNavigator: true,
builder:
(context) => AbuseReportSheet(
resourceIdentifier: resourceIdentifier,
initialReason: initialReason,
),
);
}

View File

@ -0,0 +1,184 @@
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:gap/gap.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/pods/network.dart';
import 'package:island/widgets/alert.dart';
import 'package:island/widgets/content/sheet.dart';
import 'package:material_symbols_icons/symbols.dart';
class AbuseReportSheet extends HookConsumerWidget {
final String resourceIdentifier;
final String? initialReason;
const AbuseReportSheet({
super.key,
required this.resourceIdentifier,
this.initialReason,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
final reasonController = useTextEditingController(
text: initialReason ?? '',
);
final selectedType = useState<int>(0);
final isSubmitting = useState<bool>(false);
final reportTypes = [
{'value': 0, 'label': 'abuseReportTypeCopyright'.tr()},
{'value': 1, 'label': 'abuseReportTypeHarassment'.tr()},
{'value': 2, 'label': 'abuseReportTypeImpersonation'.tr()},
{'value': 3, 'label': 'abuseReportTypeOffensiveContent'.tr()},
{'value': 4, 'label': 'abuseReportTypeSpam'.tr()},
{'value': 5, 'label': 'abuseReportTypePrivacyViolation'.tr()},
{'value': 6, 'label': 'abuseReportTypeIllegalContent'.tr()},
{'value': 7, 'label': 'abuseReportTypeOther'.tr()},
];
Future<void> submitReport() async {
isSubmitting.value = true;
try {
final client = ref.read(apiClientProvider);
await client.post(
'/safety/reports',
data: {
'resource_identifier': resourceIdentifier,
'type': selectedType.value,
'reason': reasonController.text.trim(),
},
);
if (context.mounted) {
Navigator.of(context).pop();
showDialog(
context: context,
builder:
(contextDialog) => AlertDialog(
icon: const Icon(
Icons.check_circle,
color: Colors.green,
size: 36,
),
title: Text('abuseReportSuccessTitle'.tr()),
content: Text('abuseReportSuccess'.tr()),
actions: [
TextButton(
onPressed: () {
Navigator.of(contextDialog).pop();
Navigator.of(context).pop();
},
child: const Text('OK'),
),
],
),
);
}
} catch (err) {
showErrorAlert(err);
} finally {
isSubmitting.value = false;
}
}
return SheetScaffold(
titleText: 'abuseReportTitle'.tr(),
child: SingleChildScrollView(
padding: EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Information text
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceVariant,
borderRadius: BorderRadius.circular(8),
),
child: Row(
children: [
Icon(
Symbols.info,
size: 20,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
const Gap(8),
Expanded(
child: Text(
'abuseReportDescription'.tr(),
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
),
],
),
),
const Gap(24),
// Report type selection
Text(
'abuseReportType'.tr(),
style: Theme.of(
context,
).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w600),
),
const Gap(12),
...reportTypes.map((type) {
return RadioListTile<int>(
value: type['value'] as int,
groupValue: selectedType.value,
onChanged: (value) => selectedType.value = value!,
title: Text(type['label'] as String),
contentPadding: EdgeInsets.zero,
visualDensity: VisualDensity.compact,
);
}),
const Gap(24),
// Reason text field
Text(
'abuseReportReason'.tr(),
style: Theme.of(
context,
).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w600),
),
const Gap(8),
TextField(
controller: reasonController,
maxLines: 4,
decoration: InputDecoration(
hintText: 'abuseReportReasonHint'.tr(),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
filled: true,
fillColor: Theme.of(context).colorScheme.surface,
),
),
const Gap(24),
// Submit button
SizedBox(
width: double.infinity,
child: FilledButton(
onPressed: isSubmitting.value ? null : submitReport,
child:
isSubmitting.value
? const SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Text('abuseReportSubmit'.tr()),
),
),
const Gap(16),
],
),
),
);
}
}

View File

@ -1,9 +1,19 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:gap/gap.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/widgets/alert.dart';
import 'package:island/widgets/content/sheet.dart';
import 'package:material_symbols_icons/symbols.dart';
import 'package:auto_route/auto_route.dart';
import 'package:island/route.gr.dart';
import 'package:island/screens/posts/compose.dart';
import 'package:island/models/file.dart';
import 'package:island/pods/link_preview.dart';
import 'package:island/pods/network.dart';
import 'package:island/pods/config.dart';
import 'package:island/pods/userinfo.dart';
import 'package:island/services/file.dart';
import 'dart:io';
import 'package:path/path.dart' as path;
@ -12,6 +22,7 @@ import 'package:island/screens/chat/chat.dart';
import 'package:island/widgets/content/cloud_files.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:share_plus/share_plus.dart';
import 'package:styled_widget/styled_widget.dart';
enum ShareContentType { text, link, file }
@ -113,31 +124,65 @@ class ShareSheet extends ConsumerStatefulWidget {
class _ShareSheetState extends ConsumerState<ShareSheet> {
bool _isLoading = false;
final TextEditingController _messageController = TextEditingController();
final Map<String, List<double>> _fileUploadProgress = {};
void _handleClose() {
if (widget.onClose != null) {
widget.onClose!();
} else {
Navigator.of(context).pop();
}
@override
void dispose() {
_messageController.dispose();
super.dispose();
}
Future<void> _shareToPost() async {
setState(() => _isLoading = true);
try {
// TODO: Implement share to post functionality
// This would typically navigate to the post composer with pre-filled content
showSnackBar(context, 'Share to post functionality coming soon');
} catch (e) {
showErrorAlert(e);
} finally {
setState(() => _isLoading = false);
}
}
// Convert ShareContent to PostComposeInitialState
String content = '';
List<UniversalFile> attachments = [];
Future<void> _shareToChat() async {
setState(() => _isLoading = true);
try {} catch (e) {
switch (widget.content.type) {
case ShareContentType.text:
content = widget.content.text ?? '';
break;
case ShareContentType.link:
content = widget.content.link ?? '';
break;
case ShareContentType.file:
if (widget.content.files != null) {
// Convert XFiles to UniversalFiles
for (final xFile in widget.content.files!) {
final file = File(xFile.path);
final mimeType = xFile.mimeType;
UniversalFileType fileType;
if (mimeType?.startsWith('image/') == true) {
fileType = UniversalFileType.image;
} else if (mimeType?.startsWith('video/') == true) {
fileType = UniversalFileType.video;
} else if (mimeType?.startsWith('audio/') == true) {
fileType = UniversalFileType.audio;
} else {
fileType = UniversalFileType.file;
}
attachments.add(UniversalFile(data: file, type: fileType));
}
}
break;
}
final initialState = PostComposeInitialState(
title: widget.title,
content: content,
attachments: attachments,
);
// Navigate to compose screen
if (mounted) {
context.router.push(PostComposeRoute(initialState: initialState));
Navigator.of(context).pop(); // Close the share sheet
}
} catch (e) {
showErrorAlert(e);
} finally {
setState(() => _isLoading = false);
@ -147,21 +192,155 @@ class _ShareSheetState extends ConsumerState<ShareSheet> {
Future<void> _shareToSpecificChat(SnChatRoom chatRoom) async {
setState(() => _isLoading = true);
try {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'shareToSpecificChatComingSoon'.tr(
args: [chatRoom.name ?? 'directChat'.tr()],
),
),
),
final apiClient = ref.read(apiClientProvider);
final userInfo = ref.read(userInfoProvider.notifier);
final serverUrl = ref.read(serverUrlProvider);
String content = _messageController.text.trim();
List<String> attachmentIds = [];
// Handle different content types
switch (widget.content.type) {
case ShareContentType.text:
if (content.isEmpty) {
content = widget.content.text ?? '';
} else if (widget.content.text?.isNotEmpty == true) {
content = '$content\n\n${widget.content.text}';
}
break;
case ShareContentType.link:
if (content.isEmpty) {
content = widget.content.link ?? '';
} else if (widget.content.link?.isNotEmpty == true) {
content = '$content\n\n${widget.content.link}';
}
break;
case ShareContentType.file:
// Upload files to cloud storage
if (widget.content.files?.isNotEmpty == true) {
final token = await userInfo.getAccessToken();
if (token == null) {
throw Exception('Authentication required');
}
final universalFiles =
widget.content.files!.map((file) {
UniversalFileType fileType;
if (file.mimeType?.startsWith('image/') == true) {
fileType = UniversalFileType.image;
} else if (file.mimeType?.startsWith('video/') == true) {
fileType = UniversalFileType.video;
} else if (file.mimeType?.startsWith('audio/') == true) {
fileType = UniversalFileType.audio;
} else {
fileType = UniversalFileType.file;
}
return UniversalFile(data: file, type: fileType);
}).toList();
// Initialize progress tracking
final messageId = DateTime.now().millisecondsSinceEpoch.toString();
_fileUploadProgress[messageId] = List.filled(
universalFiles.length,
0.0,
);
// Upload each file
for (var idx = 0; idx < universalFiles.length; idx++) {
final file = universalFiles[idx];
final cloudFile =
await putMediaToCloud(
fileData: file,
atk: token,
baseUrl: serverUrl,
filename: file.data.name ?? 'Shared file',
mimetype:
file.data.mimeType ??
switch (file.type) {
UniversalFileType.image => 'image/unknown',
UniversalFileType.video => 'video/unknown',
UniversalFileType.audio => 'audio/unknown',
UniversalFileType.file => 'application/octet-stream',
},
onProgress: (progress, _) {
if (mounted) {
setState(() {
_fileUploadProgress[messageId]?[idx] = progress;
});
}
},
).future;
if (cloudFile == null) {
throw Exception('Failed to upload file: ${file.data.name}');
}
attachmentIds.add(cloudFile.id);
}
}
break;
}
if (content.isEmpty && attachmentIds.isEmpty) {
throw Exception('No content to share');
}
// Send message to chat room
await apiClient.post(
'/chat/${chatRoom.id}/messages',
data: {'content': content, 'attachments_id': attachmentIds, 'meta': {}},
);
if (mounted) {
// Show success message
showSnackBar(
'shareToSpecificChatSuccess'.tr(
args: [chatRoom.name ?? 'directChat'.tr()],
),
);
// Show navigation prompt
final shouldNavigate = await showDialog<bool>(
context: context,
builder:
(context) => AlertDialog(
title: Text('shareSuccess'.tr()),
content: Text('wouldYouLikeToGoToChat'.tr()),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: Text('no'.tr()),
),
TextButton(
onPressed: () => Navigator.of(context).pop(true),
child: Text('yes'.tr()),
),
],
),
);
// Close the share sheet
if (mounted) {
Navigator.of(context).pop();
}
// Navigate to chat if requested
if (shouldNavigate == true && mounted) {
context.router.pushPath('/chat/$chatRoom');
}
}
} catch (e) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text('Failed to share to chat: $e')));
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Failed to share to chat: $e'),
backgroundColor: Theme.of(context).colorScheme.error,
),
);
}
} finally {
setState(() => _isLoading = false);
if (mounted) {
setState(() => _isLoading = false);
}
}
}
@ -213,7 +392,7 @@ class _ShareSheetState extends ConsumerState<ShareSheet> {
}
await Clipboard.setData(ClipboardData(text: textToCopy));
if (mounted) showSnackBar(context, 'copyToClipboard'.tr());
if (mounted) showSnackBar('copyToClipboard'.tr());
} catch (e) {
showErrorAlert(e);
}
@ -320,6 +499,28 @@ class _ShareSheetState extends ConsumerState<ShareSheet> {
),
),
const SizedBox(height: 12),
// Additional message input
Container(
margin: const EdgeInsets.only(bottom: 16),
child: TextField(
controller: _messageController,
decoration: InputDecoration(
hintText: 'addAdditionalMessage'.tr(),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 12,
),
),
maxLines: 3,
minLines: 1,
enabled: !_isLoading,
),
),
_ChatRoomsList(
onChatSelected:
_isLoading ? null : _shareToSpecificChat,
@ -334,11 +535,40 @@ class _ShareSheetState extends ConsumerState<ShareSheet> {
),
),
// Loading indicator
// Loading indicator and file upload progress
if (_isLoading)
Container(
padding: const EdgeInsets.all(16),
child: const CircularProgressIndicator(),
child: Column(
children: [
const CircularProgressIndicator(),
const SizedBox(height: 8),
if (_fileUploadProgress.isNotEmpty)
..._fileUploadProgress.entries.map((entry) {
final progress = entry.value;
final averageProgress =
progress.isEmpty
? 0.0
: progress.reduce((a, b) => a + b) /
progress.length;
return Column(
children: [
Text(
'uploadingFiles'.tr(),
style: Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: 4),
LinearProgressIndicator(value: averageProgress),
const SizedBox(height: 4),
Text(
'${(averageProgress * 100).toInt()}%',
style: Theme.of(context).textTheme.bodySmall,
),
],
);
}),
],
),
),
],
),
@ -571,63 +801,6 @@ class _CompactShareOption extends StatelessWidget {
}
}
class _ShareOption extends StatelessWidget {
final IconData icon;
final String title;
final String subtitle;
final VoidCallback? onTap;
const _ShareOption({
required this.icon,
required this.title,
required this.subtitle,
this.onTap,
});
@override
Widget build(BuildContext context) {
return Card(
margin: EdgeInsets.zero,
child: ListTile(
leading: Icon(
icon,
color:
onTap != null
? Theme.of(context).colorScheme.primary
: Theme.of(
context,
).colorScheme.onSurfaceVariant.withOpacity(0.5),
),
title: Text(
title,
style: TextStyle(
color:
onTap != null
? null
: Theme.of(
context,
).colorScheme.onSurfaceVariant.withOpacity(0.5),
),
),
subtitle: Text(
subtitle,
style: TextStyle(
color:
onTap != null
? Theme.of(context).colorScheme.onSurfaceVariant
: Theme.of(
context,
).colorScheme.onSurfaceVariant.withOpacity(0.5),
),
),
trailing: onTap != null ? const Icon(Symbols.chevron_right) : null,
onTap: onTap,
enabled: onTap != null,
),
);
}
}
class _ContentPreview extends StatelessWidget {
final ShareContent content;
@ -664,13 +837,142 @@ class _TextPreview extends StatelessWidget {
}
}
class _LinkPreview extends StatelessWidget {
class _LinkPreview extends ConsumerWidget {
final String link;
const _LinkPreview({required this.link});
@override
Widget build(BuildContext context) {
Widget build(BuildContext context, WidgetRef ref) {
final linkPreviewAsync = ref.watch(linkPreviewProvider(link));
return linkPreviewAsync.when(
loading:
() => Container(
constraints: const BoxConstraints(maxHeight: kPreviewMaxHeight),
child: Row(
children: [
const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
),
const SizedBox(width: 8),
Text(
'Loading link preview...',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
],
),
),
error: (error, stackTrace) => _buildFallbackPreview(context),
data: (embed) {
if (embed == null) {
return _buildFallbackPreview(context);
}
return Container(
constraints: const BoxConstraints(
maxHeight: 120,
), // Increased height for rich preview
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Favicon and image
if (embed.imageUrl != null || embed.faviconUrl.isNotEmpty)
Container(
width: 60,
height: 60,
margin: const EdgeInsets.only(right: 12),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color:
Theme.of(context).colorScheme.surfaceContainerHighest,
),
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child:
embed.imageUrl != null
? Image.network(
embed.imageUrl!,
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) {
return _buildFaviconFallback(
context,
embed.faviconUrl,
);
},
)
: _buildFaviconFallback(context, embed.faviconUrl),
),
),
// Content
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Site name
if (embed.siteName.isNotEmpty)
Text(
embed.siteName,
style: Theme.of(context).textTheme.labelSmall?.copyWith(
color: Theme.of(context).colorScheme.primary,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
// Title
Text(
embed.title,
style: Theme.of(context).textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w600,
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
// Description
if (embed.description != null &&
embed.description!.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(
embed.description!,
style: Theme.of(
context,
).textTheme.bodySmall?.copyWith(
color:
Theme.of(context).colorScheme.onSurfaceVariant,
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
// URL
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(
embed.url,
style: Theme.of(context).textTheme.labelSmall?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
decoration: TextDecoration.underline,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
),
],
),
);
},
);
}
Widget _buildFallbackPreview(BuildContext context) {
return Container(
constraints: const BoxConstraints(maxHeight: kPreviewMaxHeight),
child: Column(
@ -690,15 +992,22 @@ class _LinkPreview extends StatelessWidget {
color: Theme.of(context).colorScheme.primary,
),
),
const Gap(6),
Text(
'Link embed was not loaded.',
style: Theme.of(context).textTheme.labelSmall,
).opacity(0.75),
],
),
const SizedBox(height: 8),
SingleChildScrollView(
child: SelectableText(
link,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.primary,
decoration: TextDecoration.underline,
Expanded(
child: SingleChildScrollView(
child: SelectableText(
link,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.primary,
decoration: TextDecoration.underline,
),
),
),
),
@ -706,6 +1015,27 @@ class _LinkPreview extends StatelessWidget {
),
);
}
Widget _buildFaviconFallback(BuildContext context, String faviconUrl) {
if (faviconUrl.isNotEmpty) {
return Image.network(
faviconUrl,
fit: BoxFit.contain,
errorBuilder: (context, error, stackTrace) {
return Icon(
Symbols.link,
color: Theme.of(context).colorScheme.primary,
size: 24,
);
},
);
}
return Icon(
Symbols.link,
color: Theme.of(context).colorScheme.primary,
size: 24,
);
}
}
class _FilePreview extends StatelessWidget {

View File

@ -9,7 +9,7 @@
#include <bitsdojo_window_linux/bitsdojo_window_plugin.h>
#include <file_selector_linux/file_selector_plugin.h>
#include <flutter_platform_alert/flutter_platform_alert_plugin.h>
#include <flutter_secure_storage/flutter_secure_storage_plugin.h>
#include <flutter_secure_storage_linux/flutter_secure_storage_linux_plugin.h>
#include <flutter_timezone/flutter_timezone_plugin.h>
#include <flutter_udid/flutter_udid_plugin.h>
#include <flutter_webrtc/flutter_web_r_t_c_plugin.h>
@ -33,9 +33,9 @@ void fl_register_plugins(FlPluginRegistry* registry) {
g_autoptr(FlPluginRegistrar) flutter_platform_alert_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterPlatformAlertPlugin");
flutter_platform_alert_plugin_register_with_registrar(flutter_platform_alert_registrar);
g_autoptr(FlPluginRegistrar) flutter_secure_storage_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterSecureStoragePlugin");
flutter_secure_storage_plugin_register_with_registrar(flutter_secure_storage_registrar);
g_autoptr(FlPluginRegistrar) flutter_secure_storage_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterSecureStorageLinuxPlugin");
flutter_secure_storage_linux_plugin_register_with_registrar(flutter_secure_storage_linux_registrar);
g_autoptr(FlPluginRegistrar) flutter_timezone_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterTimezonePlugin");
flutter_timezone_plugin_register_with_registrar(flutter_timezone_registrar);

View File

@ -6,7 +6,7 @@ list(APPEND FLUTTER_PLUGIN_LIST
bitsdojo_window_linux
file_selector_linux
flutter_platform_alert
flutter_secure_storage
flutter_secure_storage_linux
flutter_timezone
flutter_udid
flutter_webrtc

View File

@ -14,6 +14,7 @@ import firebase_core
import firebase_messaging
import flutter_inappwebview_macos
import flutter_platform_alert
import flutter_secure_storage_macos
import flutter_timezone
import flutter_udid
import flutter_webrtc
@ -47,6 +48,7 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
FLTFirebaseMessagingPlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseMessagingPlugin"))
InAppWebViewFlutterPlugin.register(with: registry.registrar(forPlugin: "InAppWebViewFlutterPlugin"))
FlutterPlatformAlertPlugin.register(with: registry.registrar(forPlugin: "FlutterPlatformAlertPlugin"))
FlutterSecureStoragePlugin.register(with: registry.registrar(forPlugin: "FlutterSecureStoragePlugin"))
FlutterTimezonePlugin.register(with: registry.registrar(forPlugin: "FlutterTimezonePlugin"))
FlutterUdidPlugin.register(with: registry.registrar(forPlugin: "FlutterUdidPlugin"))
FlutterWebRTCPlugin.register(with: registry.registrar(forPlugin: "FlutterWebRTCPlugin"))

View File

@ -11,4 +11,4 @@ PRODUCT_NAME = Solian
PRODUCT_BUNDLE_IDENTIFIER = dev.solsynth.solian
// The copyright displayed in application information
PRODUCT_COPYRIGHT = Copyright © 2025 Solsynth LLC. All rights reserved.
PRODUCT_COPYRIGHT = Copyright © 2025 Solsynth. All rights reserved.

View File

@ -895,10 +895,50 @@ packages:
dependency: "direct main"
description:
name: flutter_secure_storage
sha256: "9f3dd2ac3b6875b0fde5b04734789c3ef35ba3965c18e99dd564a7a2f8056df6"
sha256: "9cad52d75ebc511adfae3d447d5d13da15a55a92c9410e50f67335b6d21d16ea"
url: "https://pub.dev"
source: hosted
version: "4.2.1"
version: "9.2.4"
flutter_secure_storage_linux:
dependency: transitive
description:
name: flutter_secure_storage_linux
sha256: be76c1d24a97d0b98f8b54bce6b481a380a6590df992d0098f868ad54dc8f688
url: "https://pub.dev"
source: hosted
version: "1.2.3"
flutter_secure_storage_macos:
dependency: transitive
description:
name: flutter_secure_storage_macos
sha256: "6c0a2795a2d1de26ae202a0d78527d163f4acbb11cde4c75c670f3a0fc064247"
url: "https://pub.dev"
source: hosted
version: "3.1.3"
flutter_secure_storage_platform_interface:
dependency: transitive
description:
name: flutter_secure_storage_platform_interface
sha256: cf91ad32ce5adef6fba4d736a542baca9daf3beac4db2d04be350b87f69ac4a8
url: "https://pub.dev"
source: hosted
version: "1.1.2"
flutter_secure_storage_web:
dependency: transitive
description:
name: flutter_secure_storage_web
sha256: f4ebff989b4f07b2656fb16b47852c0aab9fed9b4ec1c70103368337bc1886a9
url: "https://pub.dev"
source: hosted
version: "1.2.1"
flutter_secure_storage_windows:
dependency: transitive
description:
name: flutter_secure_storage_windows
sha256: b20b07cb5ed4ed74fc567b78a72936203f587eba460af1df11281c9326cd3709
url: "https://pub.dev"
source: hosted
version: "3.1.2"
flutter_svg:
dependency: "direct main"
description:
@ -1177,10 +1217,10 @@ packages:
dependency: transitive
description:
name: js
sha256: "53385261521cc4a0c4658fd0ad07a7d14591cf8fc33abbceae306ddb974888dc"
sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3
url: "https://pub.dev"
source: hosted
version: "0.7.2"
version: "0.6.7"
json_annotation:
dependency: "direct main"
description:
@ -2282,6 +2322,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.0.2"
top_snackbar_flutter:
dependency: "direct main"
description:
name: top_snackbar_flutter
sha256: ad3f93062450e8c7db97b271d405c180536408cc2be4380a59da7022eb1d750c
url: "https://pub.dev"
source: hosted
version: "3.3.0"
tuple:
dependency: transitive
description:

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
# 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.
version: 3.0.0+106
version: 3.0.0+107
environment:
sdk: ^3.7.2
@ -117,10 +117,11 @@ dependencies:
flutter_svg: ^2.1.0
native_exif: ^0.6.2
local_auth: ^2.3.0
flutter_secure_storage: ^4.2.1
flutter_secure_storage: ^9.2.4
flutter_math_fork: ^0.7.4
share_plus: ^11.0.0
receive_sharing_intent: ^1.8.1
top_snackbar_flutter: ^3.3.0
dev_dependencies:
flutter_test:

View File

@ -12,6 +12,7 @@
#include <firebase_core/firebase_core_plugin_c_api.h>
#include <flutter_inappwebview_windows/flutter_inappwebview_windows_plugin_c_api.h>
#include <flutter_platform_alert/flutter_platform_alert_plugin.h>
#include <flutter_secure_storage_windows/flutter_secure_storage_windows_plugin.h>
#include <flutter_timezone/flutter_timezone_plugin_c_api.h>
#include <flutter_udid/flutter_udid_plugin_c_api.h>
#include <flutter_webrtc/flutter_web_r_t_c_plugin.h>
@ -42,6 +43,8 @@ void RegisterPlugins(flutter::PluginRegistry* registry) {
registry->GetRegistrarForPlugin("FlutterInappwebviewWindowsPluginCApi"));
FlutterPlatformAlertPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("FlutterPlatformAlertPlugin"));
FlutterSecureStorageWindowsPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("FlutterSecureStorageWindowsPlugin"));
FlutterTimezonePluginCApiRegisterWithRegistrar(
registry->GetRegistrarForPlugin("FlutterTimezonePluginCApi"));
FlutterUdidPluginCApiRegisterWithRegistrar(

View File

@ -9,6 +9,7 @@ list(APPEND FLUTTER_PLUGIN_LIST
firebase_core
flutter_inappwebview_windows
flutter_platform_alert
flutter_secure_storage_windows
flutter_timezone
flutter_udid
flutter_webrtc