Compare commits

...

2 Commits

Author SHA1 Message Date
217a0c0a54 🐛 Fix notification push doesn't work 2025-06-15 01:09:24 +08:00
5c0f7225e6 🐛 Fixes 2025-06-15 00:59:11 +08:00
2 changed files with 134 additions and 129 deletions

View File

@ -104,7 +104,7 @@ void main() async {
); );
} }
final _appRouter = AppRouter(); final appRouter = AppRouter();
class IslandApp extends HookConsumerWidget { class IslandApp extends HookConsumerWidget {
const IslandApp({super.key}); const IslandApp({super.key});
@ -118,7 +118,7 @@ class IslandApp extends HookConsumerWidget {
var uri = notification.data['action_uri'] as String; var uri = notification.data['action_uri'] as String;
if (uri.startsWith('/')) { if (uri.startsWith('/')) {
// In-app routes // In-app routes
_appRouter.pushPath(notification.data['action_uri']); appRouter.pushPath(notification.data['action_uri']);
} else { } else {
// External links // External links
launchUrlString(uri); launchUrlString(uri);
@ -164,7 +164,7 @@ class IslandApp extends HookConsumerWidget {
theme: theme?.light, theme: theme?.light,
darkTheme: theme?.dark, darkTheme: theme?.dark,
themeMode: ThemeMode.system, themeMode: ThemeMode.system,
routerConfig: _appRouter.config( routerConfig: appRouter.config(
navigatorObservers: navigatorObservers:
() => [ () => [
TabNavigationObserver( TabNavigationObserver(
@ -187,9 +187,9 @@ class IslandApp extends HookConsumerWidget {
OverlayEntry( OverlayEntry(
builder: builder:
(_) => WindowScaffold( (_) => WindowScaffold(
router: _appRouter, router: appRouter,
child: TabsNavigationWidget( child: TabsNavigationWidget(
router: _appRouter, router: appRouter,
child: child ?? const SizedBox.shrink(), child: child ?? const SizedBox.shrink(),
), ),
), ),

View File

@ -1,16 +1,16 @@
import 'dart:async'; import 'dart:async';
import 'dart:developer'; import 'dart:developer';
import 'dart:io';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:collection/collection.dart'; import 'package:collection/collection.dart';
import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:island/main.dart';
import 'package:island/models/user.dart'; import 'package:island/models/user.dart';
import 'package:island/pods/websocket.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:material_symbols_icons/material_symbols_icons.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:styled_widget/styled_widget.dart'; import 'package:styled_widget/styled_widget.dart';
@ -25,16 +25,16 @@ class AppNotificationToast extends HookConsumerWidget {
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
final notifications = ref.watch(appNotificationsProvider); final notifications = ref.watch(appNotificationsProvider);
final isDesktop =
!kIsWeb && (Platform.isMacOS || Platform.isWindows || Platform.isLinux);
// Calculate position based on device type
final safeAreaTop = MediaQuery.of(context).padding.top;
final notificationTop = safeAreaTop + (isDesktop ? 30 : 10);
// Create a global key for AnimatedList // Create a global key for AnimatedList
final listKey = useMemoized(() => GlobalKey<AnimatedListState>()); 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 // Track previous notifications to detect changes
final previousNotifications = usePrevious(notifications) ?? []; final previousNotifications = usePrevious(notifications) ?? [];
@ -46,6 +46,11 @@ class AppNotificationToast extends HookConsumerWidget {
// Find new notifications (added) // Find new notifications (added)
final newIds = currentIds.difference(previousIds); final newIds = currentIds.difference(previousIds);
// Update visual count for new notifications
if (newIds.isNotEmpty) {
visualCount.value += newIds.length;
}
// Insert new notifications with animation // Insert new notifications with animation
for (final id in newIds) { for (final id in newIds) {
final index = notifications.indexWhere((n) => n.data.id == id); final index = notifications.indexWhere((n) => n.data.id == id);
@ -69,121 +74,115 @@ class AppNotificationToast extends HookConsumerWidget {
}, [notifications]); }, [notifications]);
return Positioned( return Positioned(
top: notificationTop, top: MediaQuery.of(context).padding.top + 50,
left: 16, left: 16,
right: 16, right: 16,
bottom: 16, // Add bottom constraint to make it take full height child: SizedBox(
child: Column( // Use visualCount instead of notifications.length for height calculation
children: [ height: visualCount.value * 80,
// Test button for development child: AnimatedList(
if (kDebugMode) physics: NeverScrollableScrollPhysics(),
ElevatedButton( padding: EdgeInsets.zero,
onPressed: () { key: listKey,
ref initialItemCount: notifications.length,
.read(appNotificationsProvider.notifier) itemBuilder: (context, index, animation) {
.addNotification( // Safely access notifications with bounds check
AppNotification( if (index >= notifications.length) {
data: SnNotification( return const SizedBox.shrink(); // Return empty widget if out of bounds
createdAt: DateTime.now(), }
updatedAt: DateTime.now(),
deletedAt: null, final notification = notifications[index];
id: final now = DateTime.now();
'test-notification-${DateTime.now().millisecondsSinceEpoch}', final createdAt = notification.createdAt ?? now;
topic: 'test', final duration =
title: 'Test Notification', notification.duration ?? const Duration(seconds: 5);
content: 'This is a test notification content', final elapsedTime = now.difference(createdAt);
priority: 1, final remainingTime = duration - elapsedTime;
viewedAt: null, final progress =
accountId: 'test-account-123', 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
),
), ),
icon: Symbols.info, duration: const Duration(milliseconds: 150),
createdAt: DateTime.now(), // When animation completes, update the visual count
duration: const Duration(seconds: 5),
),
);
},
child: Text('test notification'),
),
// Use AnimatedList for notifications with Expanded to take full height
Expanded(
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,
); );
if (currentIndex != -1 && // Schedule decrementing the visual count after animation completes
listKey.currentState != null && Future.delayed(const Duration(milliseconds: 150), () {
currentIndex >= 0 && if (animatingOutIds.value.contains(notificationId)) {
currentIndex < notifications.length) { visualCount.value =
try { visualCount.value > 0 ? visualCount.value - 1 : 0;
// Remove the item with animation animatingOutIds.value =
listKey.currentState!.removeItem( animatingOutIds.value
currentIndex, .where((id) => id != notificationId)
(context, animation) => SizeTransition( .toSet();
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,
), // Make removal animation faster
);
} catch (e) {
// Log error but don't crash the app
debugPrint('Error removing notification: $e');
} }
} });
} 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 // Actually remove from state
ref ref
.read(appNotificationsProvider.notifier) .read(appNotificationsProvider.notifier)
.removeNotification(notification); .removeNotification(notification);
}, },
), ),
); );
}, },
), ),
),
],
), ),
); );
} }
@ -235,7 +234,9 @@ class _NotificationCard extends HookConsumerWidget {
return Card( return Card(
elevation: 4, elevation: 4,
margin: const EdgeInsets.only(bottom: 8), margin: const EdgeInsets.only(bottom: 8),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(bottom: Radius.circular(8)),
),
child: InkWell( child: InkWell(
borderRadius: const BorderRadius.all(Radius.circular(8)), borderRadius: const BorderRadius.all(Radius.circular(8)),
onTap: () { onTap: () {
@ -243,11 +244,12 @@ class _NotificationCard extends HookConsumerWidget {
var uri = notification.data.meta['action_uri'] as String; var uri = notification.data.meta['action_uri'] as String;
if (uri.startsWith('/')) { if (uri.startsWith('/')) {
// In-app routes // In-app routes
context.router.pushPath(notification.data.meta['action_uri']); appRouter.pushPath(notification.data.meta['action_uri']);
} else { } else {
// External URLs // External URLs
launchUrlString(uri); launchUrlString(uri);
} }
onDismiss();
} }
}, },
child: Column( child: Column(
@ -265,9 +267,7 @@ class _NotificationCard extends HookConsumerWidget {
), ),
value: 1.0 - progressState.value, value: 1.0 - progressState.value,
backgroundColor: Colors.transparent, backgroundColor: Colors.transparent,
color: Theme.of( color: Theme.of(context).colorScheme.tertiary,
context,
).colorScheme.primary.withOpacity(0.5),
minHeight: 3, minHeight: 3,
stopIndicatorColor: Colors.transparent, stopIndicatorColor: Colors.transparent,
stopIndicatorRadius: 0, stopIndicatorRadius: 0,
@ -279,7 +279,12 @@ class _NotificationCard extends HookConsumerWidget {
child: Row( child: Row(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
if (notification.icon != null) 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( Icon(
notification.icon, notification.icon,
color: Theme.of(context).colorScheme.primary, color: Theme.of(context).colorScheme.primary,
@ -298,12 +303,12 @@ class _NotificationCard extends HookConsumerWidget {
Text( Text(
notification.data.content, notification.data.content,
style: Theme.of(context).textTheme.bodyMedium, style: Theme.of(context).textTheme.bodyMedium,
).padding(top: 4), ),
if (notification.data.subtitle.isNotEmpty) if (notification.data.subtitle.isNotEmpty)
Text( Text(
notification.data.subtitle, notification.data.subtitle,
style: Theme.of(context).textTheme.bodySmall, style: Theme.of(context).textTheme.bodySmall,
).padding(top: 2), ),
], ],
), ),
), ),