Compare commits

..

3 Commits

Author SHA1 Message Date
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
33 changed files with 1184 additions and 101 deletions

View File

@ -561,5 +561,10 @@
"noChatRoomsAvailable": "No chat rooms available", "noChatRoomsAvailable": "No chat rooms available",
"failedToLoadChats": "Failed to load chats", "failedToLoadChats": "Failed to load chats",
"contentToShare": "Content to share:", "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?"
} }

View File

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

View File

@ -19,7 +19,6 @@ import 'package:island/pods/userinfo.dart';
import 'package:island/pods/websocket.dart'; import 'package:island/pods/websocket.dart';
import 'package:island/route.dart'; import 'package:island/route.dart';
import 'package:island/services/notify.dart'; import 'package:island/services/notify.dart';
import 'package:island/widgets/app_wrapper.dart';
import 'package:island/services/timezone.dart'; import 'package:island/services/timezone.dart';
import 'package:island/widgets/alert.dart'; import 'package:island/widgets/alert.dart';
import 'package:island/widgets/app_scaffold.dart'; import 'package:island/widgets/app_scaffold.dart';
@ -127,6 +126,8 @@ void main() async {
final appRouter = AppRouter(); final appRouter = AppRouter();
final globalOverlay = GlobalKey<OverlayState>();
class IslandApp extends HookConsumerWidget { class IslandApp extends HookConsumerWidget {
const IslandApp({super.key}); const IslandApp({super.key});
@ -195,6 +196,7 @@ class IslandApp extends HookConsumerWidget {
locale: context.locale, locale: context.locale,
builder: (context, child) { builder: (context, child) {
return Overlay( return Overlay(
key: globalOverlay,
initialEntries: [ initialEntries: [
OverlayEntry( OverlayEntry(
builder: builder:

View File

@ -21,3 +21,22 @@ sealed class SnEmbedLink with _$SnEmbedLink {
factory SnEmbedLink.fromJson(Map<String, dynamic> json) => factory SnEmbedLink.fromJson(Map<String, dynamic> json) =>
_$SnEmbedLinkFromJson(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 // dart format on

View File

@ -35,3 +35,34 @@ Map<String, dynamic> _$SnEmbedLinkToJson(_SnEmbedLink instance) =>
'Author': instance.author, 'Author': instance.author,
'PublishedDate': instance.publishedDate?.toIso8601String(), '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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -49,7 +49,6 @@ class ChatDetailScreen extends HookConsumerWidget {
ref.invalidate(chatroomIdentityProvider(id)); ref.invalidate(chatroomIdentityProvider(id));
if (context.mounted) { if (context.mounted) {
showSnackBar( showSnackBar(
context,
'chatNotifyLevelUpdated'.tr(args: [kNotifyLevelText[level].tr()]), 'chatNotifyLevelUpdated'.tr(args: [kNotifyLevelText[level].tr()]),
); );
} }
@ -140,7 +139,7 @@ class ChatDetailScreen extends HookConsumerWidget {
setChatBreak(now); setChatBreak(now);
Navigator.pop(context); Navigator.pop(context);
if (context.mounted) { 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))); setChatBreak(now.add(const Duration(minutes: 5)));
Navigator.pop(context); Navigator.pop(context);
if (context.mounted) { 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))); setChatBreak(now.add(const Duration(minutes: 10)));
Navigator.pop(context); Navigator.pop(context);
if (context.mounted) { 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))); setChatBreak(now.add(const Duration(minutes: 15)));
Navigator.pop(context); Navigator.pop(context);
if (context.mounted) { 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))); setChatBreak(now.add(const Duration(minutes: 30)));
Navigator.pop(context); Navigator.pop(context);
if (context.mounted) { 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); Navigator.pop(context);
if (context.mounted) { if (context.mounted) {
showSnackBar( showSnackBar(
context,
'chatBreakSet'.tr(args: ['${minutes}m']), 'chatBreakSet'.tr(args: ['${minutes}m']),
); );
} }

View File

@ -8,6 +8,7 @@ import 'package:island/models/activity.dart';
import 'package:island/pods/userinfo.dart'; import 'package:island/pods/userinfo.dart';
import 'package:island/route.gr.dart'; import 'package:island/route.gr.dart';
import 'package:island/services/responsive.dart'; import 'package:island/services/responsive.dart';
import 'package:island/widgets/alert.dart';
import 'package:island/widgets/app_scaffold.dart'; import 'package:island/widgets/app_scaffold.dart';
import 'package:island/models/post.dart'; import 'package:island/models/post.dart';
import 'package:island/widgets/check_in.dart'; import 'package:island/widgets/check_in.dart';
@ -75,6 +76,7 @@ class ExploreScreen extends HookConsumerWidget {
currentFilter.value = 'friends'; currentFilter.value = 'friends';
break; break;
} }
showSnackBar('Browsing ${currentFilter.value}');
} }
tabController.addListener(listener); tabController.addListener(listener);

View File

@ -186,7 +186,6 @@ class NotificationScreen extends HookConsumerWidget {
final uri = Uri.tryParse(href); final uri = Uri.tryParse(href);
if (uri == null) { if (uri == null) {
showSnackBar( showSnackBar(
context,
'brokenLink'.tr(args: []), 'brokenLink'.tr(args: []),
action: SnackBarAction( action: SnackBarAction(
label: 'copyToClipboard'.tr(), 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:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:gap/gap.dart'; import 'package:gap/gap.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/models/file.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:material_symbols_icons/symbols.dart';
import 'package:styled_widget/styled_widget.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() @RoutePage()
class PostEditScreen extends HookConsumerWidget { class PostEditScreen extends HookConsumerWidget {
final String id; final String id;
@ -54,12 +72,14 @@ class PostComposeScreen extends HookConsumerWidget {
final SnPost? repliedPost; final SnPost? repliedPost;
final SnPost? forwardedPost; final SnPost? forwardedPost;
final int? type; final int? type;
final PostComposeInitialState? initialState;
const PostComposeScreen({ const PostComposeScreen({
super.key, super.key,
this.originalPost, this.originalPost,
this.repliedPost, this.repliedPost,
this.forwardedPost, this.forwardedPost,
@QueryParam('type') this.type, @QueryParam('type') this.type,
this.initialState,
}); });
@override @override
@ -107,11 +127,28 @@ class PostComposeScreen extends HookConsumerWidget {
return null; return null;
}, [publishers]); }, [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(() { useEffect(() {
if (originalPost == null && if (originalPost == null &&
effectiveForwardedPost == null && effectiveForwardedPost == null &&
effectiveRepliedPost == null) { effectiveRepliedPost == null &&
initialState == null) {
// Try to load the most recent draft // Try to load the most recent draft
final drafts = ref.read(composeStorageNotifierProvider); final drafts = ref.read(composeStorageNotifierProvider);
if (drafts.isNotEmpty) { 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 ref
.read(appSettingsNotifierProvider.notifier) .read(appSettingsNotifierProvider.notifier)
.setCustomFonts(null); .setCustomFonts(null);
showSnackBar(context, 'settingsApplied'.tr()); showSnackBar('settingsApplied'.tr());
}, },
), ),
border: OutlineInputBorder( border: OutlineInputBorder(
@ -122,7 +122,7 @@ class SettingsScreen extends HookConsumerWidget {
ref ref
.read(appSettingsNotifierProvider.notifier) .read(appSettingsNotifierProvider.notifier)
.setCustomFonts(value.isEmpty ? null : value); .setCustomFonts(value.isEmpty ? null : value);
showSnackBar(context, 'settingsApplied'.tr()); showSnackBar('settingsApplied'.tr());
}, },
), ),
), ),
@ -215,7 +215,7 @@ class SettingsScreen extends HookConsumerWidget {
prefs.setBool(kAppBackgroundStoreKey, true); prefs.setBool(kAppBackgroundStoreKey, true);
ref.invalidate(backgroundImageFileProvider); ref.invalidate(backgroundImageFileProvider);
if (context.mounted) { if (context.mounted) {
showSnackBar(context, 'settingsApplied'.tr()); showSnackBar('settingsApplied'.tr());
} }
}, },
), ),
@ -243,7 +243,7 @@ class SettingsScreen extends HookConsumerWidget {
prefs.remove(kAppBackgroundStoreKey); prefs.remove(kAppBackgroundStoreKey);
ref.invalidate(backgroundImageFileProvider); ref.invalidate(backgroundImageFileProvider);
if (context.mounted) { if (context.mounted) {
showSnackBar(context, 'settingsApplied'.tr()); showSnackBar('settingsApplied'.tr());
} }
}, },
); );
@ -290,7 +290,7 @@ class SettingsScreen extends HookConsumerWidget {
.setAppColorScheme(color.value); .setAppColorScheme(color.value);
if (context.mounted) { if (context.mounted) {
hideLoadingModal(context); hideLoadingModal(context);
showSnackBar(context, 'settingsApplied'.tr()); showSnackBar('settingsApplied'.tr());
} }
}, },
); );
@ -321,7 +321,7 @@ class SettingsScreen extends HookConsumerWidget {
kNetworkServerDefault, kNetworkServerDefault,
); );
ref.invalidate(serverUrlProvider); ref.invalidate(serverUrlProvider);
showSnackBar(context, 'settingsApplied'.tr()); showSnackBar('settingsApplied'.tr());
}, },
), ),
border: OutlineInputBorder( border: OutlineInputBorder(
@ -333,7 +333,7 @@ class SettingsScreen extends HookConsumerWidget {
if (value.isNotEmpty) { if (value.isNotEmpty) {
prefs.setString(kNetworkServerStoreKey, value); prefs.setString(kNetworkServerStoreKey, value);
ref.invalidate(serverUrlProvider); ref.invalidate(serverUrlProvider);
showSnackBar(context, 'settingsApplied'.tr()); showSnackBar('settingsApplied'.tr());
} }
}, },
), ),

View File

@ -3,7 +3,6 @@ import 'package:flutter/material.dart';
import 'package:receive_sharing_intent/receive_sharing_intent.dart'; import 'package:receive_sharing_intent/receive_sharing_intent.dart';
import 'package:island/widgets/share/share_sheet.dart'; import 'package:island/widgets/share/share_sheet.dart';
import 'package:share_plus/share_plus.dart'; import 'package:share_plus/share_plus.dart';
import 'package:easy_localization/easy_localization.dart';
class SharingIntentService { class SharingIntentService {
static final SharingIntentService _instance = static final SharingIntentService _instance =
@ -73,14 +72,44 @@ class SharingIntentService {
); );
} }
// Convert SharedMediaFile to XFile // Convert SharedMediaFile to XFile for files
final List<XFile> files = final List<XFile> files =
sharedFiles 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)) .map((file) => XFile(file.path, name: file.path.split('/').last))
.toList(); .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 // 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 /// Dispose of resources

View File

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

View File

@ -1,31 +1,18 @@
import 'package:easy_localization/easy_localization.dart'; import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:gap/gap.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:styled_widget/styled_widget.dart';
import 'package:top_snackbar_flutter/top_snack_bar.dart';
export 'content/alert.native.dart' export 'content/alert.native.dart'
if (dart.library.html) 'content/alert.web.dart'; if (dart.library.html) 'content/alert.web.dart';
void showSnackBar( void showSnackBar(String message, {SnackBarAction? action}) {
BuildContext context, showTopSnackBar(
String message, { globalOverlay.currentState!,
SnackBarAction? action, Card(child: Text(message).padding(horizontal: 24, vertical: 16)),
}) { snackBarPosition: SnackBarPosition.bottom,
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,
),
),
); );
} }

View File

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

View File

@ -279,7 +279,7 @@ class _PaymentContentState extends ConsumerState<_PaymentContent> {
_isPinMode = true; _isPinMode = true;
}); });
if (message != null && message.isNotEmpty) { 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 = final hasContent =
state.titleController.text.trim().isNotEmpty || state.titleController.text.trim().isNotEmpty ||
state.descriptionController.text.trim().isNotEmpty || state.descriptionController.text.trim().isNotEmpty ||
@ -142,7 +146,9 @@ class ComposeLogic {
fileData: attachment, fileData: attachment,
atk: token, atk: token,
baseUrl: baseUrl, baseUrl: baseUrl,
filename: attachment.data.name ?? (postType == 1 ? 'Article media' : 'Post media'), filename:
attachment.data.name ??
(postType == 1 ? 'Article media' : 'Post media'),
mimetype: mimetype:
attachment.data.mimeType ?? attachment.data.mimeType ??
ComposeLogic.getMimeTypeFromFileType(attachment.type), 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 = final hasContent =
state.titleController.text.trim().isNotEmpty || state.titleController.text.trim().isNotEmpty ||
state.descriptionController.text.trim().isNotEmpty || state.descriptionController.text.trim().isNotEmpty ||
@ -346,12 +356,12 @@ class ComposeLogic {
await ref.read(composeStorageNotifierProvider.notifier).saveDraft(draft); await ref.read(composeStorageNotifierProvider.notifier).saveDraft(draft);
if (context.mounted) { if (context.mounted) {
showSnackBar(context, 'draftSaved'.tr()); showSnackBar('draftSaved'.tr());
} }
} catch (e) { } catch (e) {
log('[ComposeLogic] Failed to save draft manually, error: $e'); log('[ComposeLogic] Failed to save draft manually, error: $e');
if (context.mounted) { if (context.mounted) {
showSnackBar(context, 'draftSaveFailed'.tr()); showSnackBar('draftSaveFailed'.tr());
} }
} }
} }
@ -511,7 +521,7 @@ class ComposeLogic {
if (!hasContent && !hasAttachments) { if (!hasContent && !hasAttachments) {
if (context.mounted) { if (context.mounted) {
showSnackBar(context, 'postContentEmpty'.tr()); showSnackBar('postContentEmpty'.tr());
} }
return; // Don't submit empty posts return; // Don't submit empty posts
} }

View File

@ -1,9 +1,19 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:gap/gap.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/widgets/alert.dart'; import 'package:island/widgets/alert.dart';
import 'package:island/widgets/content/sheet.dart'; import 'package:island/widgets/content/sheet.dart';
import 'package:material_symbols_icons/symbols.dart'; import 'package:material_symbols_icons/symbols.dart';
import 'package: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 'dart:io';
import 'package:path/path.dart' as path; 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:island/widgets/content/cloud_files.dart';
import 'package:easy_localization/easy_localization.dart'; import 'package:easy_localization/easy_localization.dart';
import 'package:share_plus/share_plus.dart'; import 'package:share_plus/share_plus.dart';
import 'package:styled_widget/styled_widget.dart';
enum ShareContentType { text, link, file } enum ShareContentType { text, link, file }
@ -113,6 +124,14 @@ class ShareSheet extends ConsumerStatefulWidget {
class _ShareSheetState extends ConsumerState<ShareSheet> { class _ShareSheetState extends ConsumerState<ShareSheet> {
bool _isLoading = false; bool _isLoading = false;
final TextEditingController _messageController = TextEditingController();
final Map<String, List<double>> _fileUploadProgress = {};
@override
void dispose() {
_messageController.dispose();
super.dispose();
}
void _handleClose() { void _handleClose() {
if (widget.onClose != null) { if (widget.onClose != null) {
@ -125,19 +144,53 @@ class _ShareSheetState extends ConsumerState<ShareSheet> {
Future<void> _shareToPost() async { Future<void> _shareToPost() async {
setState(() => _isLoading = true); setState(() => _isLoading = true);
try { try {
// TODO: Implement share to post functionality // Convert ShareContent to PostComposeInitialState
// This would typically navigate to the post composer with pre-filled content String content = '';
showSnackBar(context, 'Share to post functionality coming soon'); List<UniversalFile> attachments = [];
} catch (e) {
showErrorAlert(e);
} finally {
setState(() => _isLoading = false);
}
}
Future<void> _shareToChat() async { switch (widget.content.type) {
setState(() => _isLoading = true); case ShareContentType.text:
try {} catch (e) { 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); showErrorAlert(e);
} finally { } finally {
setState(() => _isLoading = false); setState(() => _isLoading = false);
@ -147,21 +200,159 @@ class _ShareSheetState extends ConsumerState<ShareSheet> {
Future<void> _shareToSpecificChat(SnChatRoom chatRoom) async { Future<void> _shareToSpecificChat(SnChatRoom chatRoom) async {
setState(() => _isLoading = true); setState(() => _isLoading = true);
try { try {
ScaffoldMessenger.of(context).showSnackBar( final apiClient = ref.read(apiClientProvider);
SnackBar( final userInfo = ref.read(userInfoProvider.notifier);
content: Text( final serverUrl = ref.read(serverUrlProvider);
'shareToSpecificChatComingSoon'.tr(
args: [chatRoom.name ?? 'directChat'.tr()], 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
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'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) { } catch (e) {
ScaffoldMessenger.of( if (mounted) {
context, ScaffoldMessenger.of(context).showSnackBar(
).showSnackBar(SnackBar(content: Text('Failed to share to chat: $e'))); SnackBar(
content: Text('Failed to share to chat: $e'),
backgroundColor: Theme.of(context).colorScheme.error,
),
);
}
} finally { } finally {
setState(() => _isLoading = false); if (mounted) {
setState(() => _isLoading = false);
}
} }
} }
@ -213,7 +404,7 @@ class _ShareSheetState extends ConsumerState<ShareSheet> {
} }
await Clipboard.setData(ClipboardData(text: textToCopy)); await Clipboard.setData(ClipboardData(text: textToCopy));
if (mounted) showSnackBar(context, 'copyToClipboard'.tr()); if (mounted) showSnackBar('copyToClipboard'.tr());
} catch (e) { } catch (e) {
showErrorAlert(e); showErrorAlert(e);
} }
@ -320,6 +511,28 @@ class _ShareSheetState extends ConsumerState<ShareSheet> {
), ),
), ),
const SizedBox(height: 12), 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( _ChatRoomsList(
onChatSelected: onChatSelected:
_isLoading ? null : _shareToSpecificChat, _isLoading ? null : _shareToSpecificChat,
@ -334,11 +547,40 @@ class _ShareSheetState extends ConsumerState<ShareSheet> {
), ),
), ),
// Loading indicator // Loading indicator and file upload progress
if (_isLoading) if (_isLoading)
Container( Container(
padding: const EdgeInsets.all(16), 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,
),
],
);
}),
],
),
), ),
], ],
), ),
@ -664,13 +906,142 @@ class _TextPreview extends StatelessWidget {
} }
} }
class _LinkPreview extends StatelessWidget { class _LinkPreview extends ConsumerWidget {
final String link; final String link;
const _LinkPreview({required this.link}); const _LinkPreview({required this.link});
@override @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( return Container(
constraints: const BoxConstraints(maxHeight: kPreviewMaxHeight), constraints: const BoxConstraints(maxHeight: kPreviewMaxHeight),
child: Column( child: Column(
@ -690,15 +1061,22 @@ class _LinkPreview extends StatelessWidget {
color: Theme.of(context).colorScheme.primary, 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), const SizedBox(height: 8),
SingleChildScrollView( Expanded(
child: SelectableText( child: SingleChildScrollView(
link, child: SelectableText(
style: Theme.of(context).textTheme.bodyMedium?.copyWith( link,
color: Theme.of(context).colorScheme.primary, style: Theme.of(context).textTheme.bodyMedium?.copyWith(
decoration: TextDecoration.underline, color: Theme.of(context).colorScheme.primary,
decoration: TextDecoration.underline,
),
), ),
), ),
), ),
@ -706,6 +1084,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 { class _FilePreview extends StatelessWidget {

View File

@ -11,4 +11,4 @@ PRODUCT_NAME = Solian
PRODUCT_BUNDLE_IDENTIFIER = dev.solsynth.solian PRODUCT_BUNDLE_IDENTIFIER = dev.solsynth.solian
// The copyright displayed in application information // 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

@ -2282,6 +2282,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.0.2" 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: tuple:
dependency: transitive dependency: transitive
description: description:

View File

@ -121,6 +121,7 @@ dependencies:
flutter_math_fork: ^0.7.4 flutter_math_fork: ^0.7.4
share_plus: ^11.0.0 share_plus: ^11.0.0
receive_sharing_intent: ^1.8.1 receive_sharing_intent: ^1.8.1
top_snackbar_flutter: ^3.3.0
dev_dependencies: dev_dependencies:
flutter_test: flutter_test: