diff --git a/apps/android/app/src/main/AndroidManifest.xml b/apps/android/app/src/main/AndroidManifest.xml
index db2d5ab..98a8f89 100644
--- a/apps/android/app/src/main/AndroidManifest.xml
+++ b/apps/android/app/src/main/AndroidManifest.xml
@@ -19,6 +19,9 @@
+
diff --git a/apps/ios/Runner/AppDelegate.swift b/apps/ios/Runner/AppDelegate.swift
index bde714f..1e8d67e 100644
--- a/apps/ios/Runner/AppDelegate.swift
+++ b/apps/ios/Runner/AppDelegate.swift
@@ -1,4 +1,5 @@
import Flutter
+import flutter_local_notifications
import UIKit
import UserNotifications
@@ -8,6 +9,9 @@ import UserNotifications
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
+ FlutterLocalNotificationsPlugin.setPluginRegistrantCallback { registry in
+ GeneratedPluginRegistrant.register(with: registry)
+ }
GeneratedPluginRegistrant.register(with: self)
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self
diff --git a/apps/lib/core/di/injection.dart b/apps/lib/core/di/injection.dart
index 01d26ee..60c3822 100644
--- a/apps/lib/core/di/injection.dart
+++ b/apps/lib/core/di/injection.dart
@@ -20,6 +20,7 @@ import '../../features/calendar/ui/calendar_state_manager.dart';
import '../../features/friends/data/friends_api.dart';
import '../../features/messages/data/inbox_api.dart';
import '../../features/settings/data/settings_api.dart';
+import '../../features/settings/data/services/settings_user_cache.dart';
import '../../features/users/data/users_api.dart';
import '../../features/todo/data/todo_api.dart';
@@ -82,6 +83,8 @@ Future configureDependencies() async {
final settingsApi = SettingsApi(apiClient);
sl.registerSingleton(settingsApi);
+ sl.registerSingleton(SettingsUserCache());
+
final inboxApi = InboxApi(apiClient);
sl.registerSingleton(inboxApi);
@@ -93,6 +96,9 @@ Future configureDependencies() async {
tokenStorage: tokenStorage,
onLogout: () async {
apiClient.resetInterceptor();
+ if (sl.isRegistered()) {
+ sl().invalidate();
+ }
},
);
sl.registerSingleton(authRepository);
@@ -110,6 +116,9 @@ Future configureDependencies() async {
});
apiClient.setAuthFailureCallback(() async {
+ if (sl.isRegistered()) {
+ sl().invalidate();
+ }
authBloc.add(
const AuthSessionInvalidated(
source: AuthInvalidationSource.unauthorized401,
diff --git a/apps/lib/core/notifications/local_notification_service.dart b/apps/lib/core/notifications/local_notification_service.dart
index 424b51d..2a9de1e 100644
--- a/apps/lib/core/notifications/local_notification_service.dart
+++ b/apps/lib/core/notifications/local_notification_service.dart
@@ -1,13 +1,18 @@
+import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
+import 'package:flutter/widgets.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
+import 'package:shared_preferences/shared_preferences.dart';
import 'package:timezone/data/latest.dart' as tz_data;
import 'package:timezone/timezone.dart' as tz;
+import 'reminder_notification_callbacks.dart';
import '../../features/calendar/data/models/schedule_item_model.dart';
import '../../features/calendar/reminders/models/reminder_action.dart';
import '../../features/calendar/reminders/models/reminder_payload.dart';
+import '../../features/calendar/reminders/reminder_action_dedupe_store.dart';
import '../../features/calendar/reminders/reminder_overlap_policy.dart';
typedef ReminderNotificationActionHandler =
@@ -16,26 +21,51 @@ typedef ReminderNotificationActionHandler =
required ReminderPayload payload,
});
+typedef ReminderPermissionFallbackTracker =
+ void Function({
+ required String actionExecutionId,
+ required String permissionState,
+ required String appLifecycleState,
+ required String platform,
+ });
+
+typedef ReminderInAppReminderHandler =
+ Future Function(ReminderPayload payload);
+
class LocalNotificationService {
- static const String _iosCategoryId = 'calendar_reminder_actions_v1';
+ static const String _iosCategoryId = 'calendar_reminder_v2';
static const String _actionCancel = 'cancel';
- static const String _actionSnooze = 'snooze_10m';
+ static const String _actionSnooze = 'snooze10m';
final FlutterLocalNotificationsPlugin _plugin;
final ReminderOverlapPolicy _overlapPolicy;
+ final ReminderPermissionFallbackTracker? _permissionFallbackTracker;
+ ReminderActionDedupeStore? _dedupeStore;
bool _initialized = false;
+ bool _canDeliverSystemNotification = true;
ReminderNotificationActionHandler? _actionHandler;
+ ReminderInAppReminderHandler? _inAppReminderHandler;
+ final Map> _inAppFallbackTimersByEventId =
+ >{};
LocalNotificationService({
FlutterLocalNotificationsPlugin? plugin,
ReminderOverlapPolicy? overlapPolicy,
+ ReminderActionDedupeStore? dedupeStore,
+ ReminderPermissionFallbackTracker? permissionFallbackTracker,
}) : _plugin = plugin ?? FlutterLocalNotificationsPlugin(),
- _overlapPolicy = overlapPolicy ?? const ReminderOverlapPolicy();
+ _overlapPolicy = overlapPolicy ?? const ReminderOverlapPolicy(),
+ _dedupeStore = dedupeStore,
+ _permissionFallbackTracker = permissionFallbackTracker;
void bindActionHandler(ReminderNotificationActionHandler handler) {
_actionHandler = handler;
}
+ void bindInAppReminderHandler(ReminderInAppReminderHandler handler) {
+ _inAppReminderHandler = handler;
+ }
+
Future initialize() async {
if (_initialized) {
return;
@@ -67,14 +97,28 @@ class LocalNotificationService {
await _plugin.initialize(
settings,
- onDidReceiveNotificationResponse: _onNotificationResponse,
+ onDidReceiveNotificationResponse:
+ ReminderNotificationCallbacks.onForegroundResponse,
+ onDidReceiveBackgroundNotificationResponse:
+ reminderNotificationTapBackground,
);
final androidImpl = _plugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>();
- await androidImpl?.requestNotificationsPermission();
+ final androidPermissionGranted = await androidImpl
+ ?.requestNotificationsPermission();
+ if (defaultTargetPlatform == TargetPlatform.android &&
+ androidPermissionGranted == false) {
+ _canDeliverSystemNotification = false;
+ _permissionFallbackTracker?.call(
+ actionExecutionId: 'permission_check',
+ permissionState: 'denied',
+ appLifecycleState: 'unknown',
+ platform: 'android',
+ );
+ }
await androidImpl?.requestExactAlarmsPermission();
await androidImpl?.requestFullScreenIntentPermission();
@@ -84,11 +128,37 @@ class LocalNotificationService {
>();
await iosImpl?.requestPermissions(alert: true, badge: true, sound: true);
+ await _ensureDedupeStore();
+
_initialized = true;
}
+ Future _ensureDedupeStore() async {
+ if (_dedupeStore != null) {
+ return;
+ }
+ final prefs = await SharedPreferences.getInstance();
+ _dedupeStore = ReminderActionDedupeStore(prefs);
+ }
+
+ Future _refreshAndroidNotificationAvailability() async {
+ if (defaultTargetPlatform != TargetPlatform.android) {
+ return;
+ }
+ final androidImpl = _plugin
+ .resolvePlatformSpecificImplementation<
+ AndroidFlutterLocalNotificationsPlugin
+ >();
+ final enabled = await androidImpl?.areNotificationsEnabled();
+ if (enabled == null) {
+ return;
+ }
+ _canDeliverSystemNotification = enabled;
+ }
+
Future upsertEventReminder(ScheduleItemModel event) async {
await initialize();
+ await _refreshAndroidNotificationAvailability();
if (event.status != ScheduleStatus.active ||
event.metadata?.reminderMinutes == null) {
await cancelEventReminder(event.id);
@@ -102,6 +172,14 @@ class LocalNotificationService {
return;
}
+ if (!_canDeliverSystemNotification) {
+ await _scheduleInAppFallbackRemindersFrom(
+ event: event,
+ firstFireAt: fireAt,
+ );
+ return;
+ }
+
await cancelEventReminder(event.id);
await _scheduleRemindersFrom(event: event, firstFireAt: fireAt);
}
@@ -111,12 +189,22 @@ class LocalNotificationService {
DateTime fireAt,
) async {
await initialize();
+ await _refreshAndroidNotificationAvailability();
+ if (!_canDeliverSystemNotification) {
+ await _scheduleInAppFallbackRemindersFrom(
+ event: event,
+ firstFireAt: fireAt,
+ );
+ return;
+ }
await cancelEventReminder(event.id);
await _scheduleRemindersFrom(event: event, firstFireAt: fireAt);
}
Future cancelEventReminder(String eventId) async {
await initialize();
+ _cancelInAppFallbackTimers(eventId);
+
final pending = await _plugin.pendingNotificationRequests();
for (final request in pending) {
final payload = _decodePayload(request.payload);
@@ -136,6 +224,23 @@ class LocalNotificationService {
Iterable events,
) async {
await initialize();
+ await _refreshAndroidNotificationAvailability();
+ if (!_canDeliverSystemNotification) {
+ _clearAllInAppFallbackTimers();
+ final now = DateTime.now();
+ final groups = _overlapPolicy.groupByMinute(events, now: now);
+ for (final group in groups) {
+ if (group.isAggregate) {
+ await _scheduleInAppAggregateFallback(group.events, group.fireAt);
+ continue;
+ }
+ await _scheduleInAppFallbackRemindersFrom(
+ event: group.events.first,
+ firstFireAt: group.fireAt,
+ );
+ }
+ return;
+ }
final now = DateTime.now();
final groups = _overlapPolicy.groupByMinute(events, now: now);
@@ -236,6 +341,9 @@ class LocalNotificationService {
notes: event.metadata?.notes,
color: event.metadata?.color,
mode: ReminderPayloadMode.single,
+ fireTimeBucket:
+ fireAt.millisecondsSinceEpoch ~/
+ const Duration(minutes: 1).inMilliseconds,
version: 1,
);
@@ -270,6 +378,185 @@ class LocalNotificationService {
}
}
+ Future _scheduleInAppAggregateFallback(
+ List events,
+ DateTime fireAt,
+ ) async {
+ if (events.isEmpty) {
+ return;
+ }
+
+ final aggregateIds = events.map((event) => event.id).toList();
+ for (final eventId in aggregateIds) {
+ _cancelInAppFallbackTimers(eventId);
+ }
+
+ final first = events.first;
+ final payload = ReminderPayload(
+ eventId: first.id,
+ title: '你有${events.length}个日程提醒',
+ startAt: first.startAt,
+ endAt: first.endAt,
+ timezone: first.timezone,
+ mode: ReminderPayloadMode.aggregate,
+ aggregateIds: aggregateIds,
+ fireTimeBucket:
+ fireAt.millisecondsSinceEpoch ~/
+ const Duration(minutes: 1).inMilliseconds,
+ version: 1,
+ );
+ await _scheduleInAppFallbackPayload(
+ eventId: first.id,
+ fireAt: fireAt,
+ payload: payload,
+ relatedEventIds: aggregateIds,
+ );
+ }
+
+ Future _scheduleInAppFallbackRemindersFrom({
+ required ScheduleItemModel event,
+ required DateTime firstFireAt,
+ }) async {
+ _cancelInAppFallbackTimers(event.id);
+
+ final endAt = event.endAt;
+ var cursor = firstFireAt;
+ Future scheduleAt(DateTime fireAt) async {
+ final payload = ReminderPayload(
+ eventId: event.id,
+ title: event.title,
+ startAt: event.startAt,
+ endAt: event.endAt,
+ timezone: event.timezone,
+ location: event.metadata?.location,
+ notes: event.metadata?.notes,
+ color: event.metadata?.color,
+ mode: ReminderPayloadMode.single,
+ fireTimeBucket:
+ fireAt.millisecondsSinceEpoch ~/
+ const Duration(minutes: 1).inMilliseconds,
+ version: 1,
+ );
+ await _scheduleInAppFallbackPayload(
+ eventId: event.id,
+ fireAt: fireAt,
+ payload: payload,
+ relatedEventIds: [event.id],
+ );
+ }
+
+ if (endAt == null) {
+ await scheduleAt(cursor);
+ return;
+ }
+
+ while (cursor.isBefore(endAt)) {
+ await scheduleAt(cursor);
+ cursor = cursor.add(const Duration(minutes: 10));
+ }
+ }
+
+ Future _scheduleInAppFallbackPayload({
+ required String eventId,
+ required DateTime fireAt,
+ required ReminderPayload payload,
+ required List relatedEventIds,
+ }) async {
+ final handler = _inAppReminderHandler;
+ final bucket =
+ fireAt.millisecondsSinceEpoch ~/
+ const Duration(minutes: 1).inMilliseconds;
+ final actionExecutionId = '$eventId|fallback|$bucket';
+ _trackFallback(
+ actionExecutionId: actionExecutionId,
+ permissionState: 'denied',
+ );
+
+ if (handler == null) {
+ return null;
+ }
+
+ final now = DateTime.now();
+ final delay = fireAt.isAfter(now) ? fireAt.difference(now) : Duration.zero;
+ late final Timer timer;
+ timer = Timer(delay, () {
+ final activeHandler = _inAppReminderHandler;
+ if (activeHandler == null) {
+ _unregisterInAppFallbackTimer(relatedEventIds, timer);
+ return;
+ }
+ activeHandler(payload);
+ _unregisterInAppFallbackTimer(relatedEventIds, timer);
+ });
+ _registerInAppFallbackTimer(relatedEventIds, timer);
+ return timer;
+ }
+
+ void _registerInAppFallbackTimer(List eventIds, Timer timer) {
+ for (final eventId in eventIds) {
+ final timers = _inAppFallbackTimersByEventId.putIfAbsent(
+ eventId,
+ () => [],
+ );
+ timers.add(timer);
+ }
+ }
+
+ void _unregisterInAppFallbackTimer(List eventIds, Timer timer) {
+ for (final eventId in eventIds) {
+ final timers = _inAppFallbackTimersByEventId[eventId];
+ if (timers == null) {
+ continue;
+ }
+ timers.remove(timer);
+ if (timers.isEmpty) {
+ _inAppFallbackTimersByEventId.remove(eventId);
+ }
+ }
+ }
+
+ void _cancelInAppFallbackTimers(String eventId) {
+ final timers = _inAppFallbackTimersByEventId.remove(eventId);
+ if (timers == null) {
+ return;
+ }
+
+ for (final timer in timers.toSet()) {
+ for (final entry in _inAppFallbackTimersByEventId.entries) {
+ entry.value.remove(timer);
+ }
+ timer.cancel();
+ }
+
+ _inAppFallbackTimersByEventId.removeWhere((_, value) => value.isEmpty);
+ }
+
+ void _clearAllInAppFallbackTimers() {
+ final allTimers = {};
+ for (final timers in _inAppFallbackTimersByEventId.values) {
+ allTimers.addAll(timers);
+ }
+ _inAppFallbackTimersByEventId.clear();
+
+ for (final timer in allTimers) {
+ timer.cancel();
+ }
+ }
+
+ void _trackFallback({
+ required String actionExecutionId,
+ required String permissionState,
+ }) {
+ final lifecycleState =
+ WidgetsBinding.instance.lifecycleState?.name ?? 'unknown';
+ _permissionFallbackTracker?.call(
+ actionExecutionId: actionExecutionId,
+ permissionState: permissionState,
+ appLifecycleState: lifecycleState,
+ platform: 'android',
+ );
+ }
+
Future _scheduleRemindersFrom({
required ScheduleItemModel event,
required DateTime firstFireAt,
@@ -309,6 +596,9 @@ class LocalNotificationService {
timezone: first.timezone,
mode: ReminderPayloadMode.aggregate,
aggregateIds: aggregateIds,
+ fireTimeBucket:
+ fireAt.millisecondsSinceEpoch ~/
+ const Duration(minutes: 1).inMilliseconds,
version: 1,
);
@@ -364,31 +654,60 @@ class LocalNotificationService {
return buffer.toString();
}
- Future _onNotificationResponse(NotificationResponse response) async {
+ Future handleNotificationResponse(NotificationResponse response) async {
final payloadRaw = response.payload;
if (payloadRaw == null || payloadRaw.isEmpty) {
return;
}
+ ReminderPayload payload;
+ try {
+ payload = ReminderPayload.fromJson(
+ Map.from(jsonDecode(payloadRaw) as Map),
+ );
+ } catch (_) {
+ debugPrint('failed to handle reminder notification response');
+ return;
+ }
+
+ final actionId = response.actionId;
+ ReminderAction? action;
+ if (actionId == _actionCancel) {
+ action = ReminderAction.archive;
+ } else if (actionId == _actionSnooze) {
+ action = ReminderAction.snooze10m;
+ }
+
+ if (action == null) {
+ if (response.notificationResponseType ==
+ NotificationResponseType.selectedNotification) {
+ final presenter = _inAppReminderHandler;
+ if (presenter != null) {
+ await presenter(payload);
+ }
+ }
+ return;
+ }
+
final handler = _actionHandler;
if (handler == null) {
return;
}
- try {
- final payload = ReminderPayload.fromJson(
- Map.from(jsonDecode(payloadRaw) as Map),
- );
- final actionId = response.actionId;
- if (actionId == _actionCancel) {
- await handler(action: ReminderAction.cancel, payload: payload);
+ final dedupeStore = _dedupeStore;
+ if (dedupeStore != null) {
+ final notificationId = response.id?.toString() ?? payload.eventId;
+ final fireTimeBucket =
+ payload.fireTimeBucket ??
+ (payload.startAt.millisecondsSinceEpoch ~/
+ const Duration(minutes: 1).inMilliseconds);
+ final actionExecutionId =
+ '$notificationId|${action.value}|$fireTimeBucket';
+ final isNew = await dedupeStore.markIfNew(actionExecutionId);
+ if (!isNew) {
return;
}
- if (actionId == _actionSnooze) {
- await handler(action: ReminderAction.snooze10m, payload: payload);
- }
- } catch (_) {
- debugPrint('failed to handle reminder notification response');
- return;
}
+
+ await handler(action: action, payload: payload);
}
}
diff --git a/apps/lib/core/notifications/reminder_notification_callbacks.dart b/apps/lib/core/notifications/reminder_notification_callbacks.dart
new file mode 100644
index 0000000..f8f16dd
--- /dev/null
+++ b/apps/lib/core/notifications/reminder_notification_callbacks.dart
@@ -0,0 +1,156 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter_local_notifications/flutter_local_notifications.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+
+import '../../features/calendar/reminders/reminder_cold_start_queue.dart';
+
+typedef ReminderNotificationResponseHandler =
+ Future Function(NotificationResponse response);
+
+class ReminderNotificationCallbacks {
+ static const String _pendingKey =
+ 'calendar_reminder_pending_notification_responses_v1';
+ static ReminderNotificationResponseHandler? _responseHandler;
+ static Future _pendingStorageLock = Future.value();
+ static final ReminderColdStartQueue _coldStartQueue =
+ ReminderColdStartQueue();
+
+ @visibleForTesting
+ static Future resetForTest() async {
+ _responseHandler = null;
+ _pendingStorageLock = Future.value();
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.remove(_pendingKey);
+ }
+
+ static Future bindResponseHandler(
+ ReminderNotificationResponseHandler handler,
+ ) async {
+ _responseHandler = handler;
+ await _drainPendingResponses();
+ }
+
+ static Future onForegroundResponse(
+ NotificationResponse response,
+ ) async {
+ final handler = _responseHandler;
+ if (handler == null) {
+ await _enqueuePendingResponse(response);
+ return;
+ }
+ try {
+ await handler(response);
+ } catch (_) {
+ await _enqueuePendingResponse(response);
+ }
+ }
+
+ static Future onBackgroundResponse(
+ NotificationResponse response,
+ ) async {
+ final handler = _responseHandler;
+ if (handler == null) {
+ await _enqueuePendingResponse(response);
+ return;
+ }
+ try {
+ await handler(response);
+ } catch (_) {
+ await _enqueuePendingResponse(response);
+ }
+ }
+
+ static Future _withPendingStorageLock(Future Function() operation) {
+ final completer = Completer();
+ final waitForTurn = _pendingStorageLock;
+ _pendingStorageLock = waitForTurn.then((_) => completer.future);
+
+ return waitForTurn.then((_) => operation()).whenComplete(() {
+ if (!completer.isCompleted) {
+ completer.complete();
+ }
+ });
+ }
+
+ static Future _enqueuePendingResponse(
+ NotificationResponse response,
+ ) async {
+ await _withPendingStorageLock(() async {
+ final prefs = await SharedPreferences.getInstance();
+ final current = prefs.getStringList(_pendingKey) ?? const [];
+ final encoded = jsonEncode({
+ 'id': response.id,
+ 'actionId': response.actionId,
+ 'payload': response.payload,
+ 'type': response.notificationResponseType.index,
+ 'input': response.input,
+ });
+ await prefs.setStringList(_pendingKey, [...current, encoded]);
+ });
+ }
+
+ static Future _drainPendingResponses() async {
+ final handler = _responseHandler;
+ if (handler == null) {
+ return;
+ }
+ await _withPendingStorageLock(() async {
+ final prefs = await SharedPreferences.getInstance();
+ final pending = prefs.getStringList(_pendingKey) ?? const [];
+ if (pending.isEmpty) {
+ return;
+ }
+
+ final remaining = [];
+ for (final raw in pending) {
+ _coldStartQueue.enqueue(() async {
+ Map parsed;
+ try {
+ parsed = Map.from(jsonDecode(raw) as Map);
+ } catch (_) {
+ return;
+ }
+
+ final id = parsed['id'] as int?;
+ final actionId = parsed['actionId'] as String?;
+ final payload = parsed['payload'] as String?;
+ final typeIndex = (parsed['type'] as int?) ?? 0;
+ final input = parsed['input'] as String?;
+ final type = NotificationResponseType.values[typeIndex.clamp(0, 1)];
+
+ try {
+ await handler(
+ NotificationResponse(
+ id: id,
+ actionId: actionId,
+ payload: payload,
+ input: input,
+ notificationResponseType: type,
+ ),
+ );
+ } catch (_) {
+ remaining.add(raw);
+ }
+ });
+ }
+
+ await _coldStartQueue.replay();
+ if (remaining.isEmpty) {
+ await prefs.remove(_pendingKey);
+ return;
+ }
+
+ await prefs.setStringList(_pendingKey, remaining);
+ });
+ }
+}
+
+@pragma('vm:entry-point')
+Future reminderNotificationTapBackground(
+ NotificationResponse response,
+) async {
+ await ReminderNotificationCallbacks.onBackgroundResponse(response);
+}
diff --git a/apps/lib/core/router/app_router.dart b/apps/lib/core/router/app_router.dart
index 88fed0c..7ad6485 100644
--- a/apps/lib/core/router/app_router.dart
+++ b/apps/lib/core/router/app_router.dart
@@ -24,7 +24,6 @@ import '../../features/todo/ui/screens/todo_edit_screen.dart';
import '../../features/settings/ui/screens/settings_screen.dart';
import '../../features/settings/ui/screens/features_screen.dart';
import '../../features/settings/ui/screens/memory_screen.dart';
-import '../../features/settings/ui/screens/account_screen.dart';
import '../../features/settings/ui/screens/edit_profile_screen.dart';
final _protectedRoutes = [
@@ -38,7 +37,6 @@ final _protectedRoutes = [
AppRoutes.settingsMain,
AppRoutes.settingsFeatures,
AppRoutes.settingsMemory,
- AppRoutes.settingsAccount,
AppRoutes.settingsEditProfile,
AppRoutes.messageInviteList,
];
@@ -174,10 +172,6 @@ GoRouter createAppRouter(AuthBloc authBloc) {
path: AppRoutes.settingsMemory,
builder: (context, state) => const MemoryScreen(),
),
- GoRoute(
- path: AppRoutes.settingsAccount,
- builder: (context, state) => const AccountScreen(),
- ),
GoRoute(
path: AppRoutes.settingsEditProfile,
builder: (context, state) => const EditProfileScreen(),
diff --git a/apps/lib/core/router/app_routes.dart b/apps/lib/core/router/app_routes.dart
index 9585b7e..70f819f 100644
--- a/apps/lib/core/router/app_routes.dart
+++ b/apps/lib/core/router/app_routes.dart
@@ -27,6 +27,5 @@ class AppRoutes {
static const settingsMain = '/settings';
static const settingsFeatures = '/settings/features';
static const settingsMemory = '/settings/memory';
- static const settingsAccount = '/settings/account';
static const settingsEditProfile = '/edit-profile';
}
diff --git a/apps/lib/features/auth/ui/screens/login_screen.dart b/apps/lib/features/auth/ui/screens/login_screen.dart
index 8a7bf76..a9e673d 100644
--- a/apps/lib/features/auth/ui/screens/login_screen.dart
+++ b/apps/lib/features/auth/ui/screens/login_screen.dart
@@ -175,6 +175,9 @@ class _LoginViewState extends State {
mainContent: LayoutBuilder(
builder: (context, constraints) {
final bottomInset = MediaQuery.of(context).viewInsets.bottom;
+ final minContentHeight = constraints.hasBoundedHeight
+ ? constraints.maxHeight
+ : AppSpacing.none;
return SingleChildScrollView(
padding: EdgeInsets.fromLTRB(
AppSpacing.lg,
@@ -183,7 +186,7 @@ class _LoginViewState extends State {
bottomInset + AppSpacing.lg,
),
child: ConstrainedBox(
- constraints: BoxConstraints(minHeight: constraints.maxHeight),
+ constraints: BoxConstraints(minHeight: minContentHeight),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 320),
diff --git a/apps/lib/features/calendar/reminders/models/reminder_action.dart b/apps/lib/features/calendar/reminders/models/reminder_action.dart
index 2fadcce..6e9da43 100644
--- a/apps/lib/features/calendar/reminders/models/reminder_action.dart
+++ b/apps/lib/features/calendar/reminders/models/reminder_action.dart
@@ -1,17 +1,23 @@
enum ReminderAction {
- cancel('cancel'),
- snooze10m('snooze_10m'),
- timeout30s('timeout_30s'),
- autoArchive('auto_archive');
+ archive('archive'),
+ snooze10m('snooze10m');
const ReminderAction(this.value);
final String value;
static ReminderAction fromValue(String raw) {
- return ReminderAction.values.firstWhere(
- (item) => item.value == raw,
- orElse: () => ReminderAction.timeout30s,
- );
+ switch (raw) {
+ case 'archive':
+ case 'cancel':
+ case 'auto_archive':
+ return ReminderAction.archive;
+ case 'snooze10m':
+ case 'snooze_10m':
+ case 'timeout_30s':
+ return ReminderAction.snooze10m;
+ default:
+ throw ArgumentError.value(raw, 'raw', 'Unsupported reminder action');
+ }
}
}
diff --git a/apps/lib/features/calendar/reminders/models/reminder_payload.dart b/apps/lib/features/calendar/reminders/models/reminder_payload.dart
index c427ea9..af09c6e 100644
--- a/apps/lib/features/calendar/reminders/models/reminder_payload.dart
+++ b/apps/lib/features/calendar/reminders/models/reminder_payload.dart
@@ -9,6 +9,7 @@ class ReminderPayload {
final String? color;
final ReminderPayloadMode mode;
final List aggregateIds;
+ final int? fireTimeBucket;
final int version;
const ReminderPayload({
@@ -22,6 +23,7 @@ class ReminderPayload {
this.color,
this.mode = ReminderPayloadMode.single,
this.aggregateIds = const [],
+ this.fireTimeBucket,
this.version = 1,
});
@@ -36,6 +38,7 @@ class ReminderPayload {
String? color,
ReminderPayloadMode? mode,
List? aggregateIds,
+ int? fireTimeBucket,
int? version,
}) {
return ReminderPayload(
@@ -49,6 +52,7 @@ class ReminderPayload {
color: color ?? this.color,
mode: mode ?? this.mode,
aggregateIds: aggregateIds ?? this.aggregateIds,
+ fireTimeBucket: fireTimeBucket ?? this.fireTimeBucket,
version: version ?? this.version,
);
}
@@ -65,6 +69,7 @@ class ReminderPayload {
'color': color,
'mode': mode.value,
'aggregateIds': aggregateIds,
+ 'fireTimeBucket': fireTimeBucket,
'version': version,
};
}
@@ -104,6 +109,7 @@ class ReminderPayload {
color: json['color'] as String?,
mode: mode,
aggregateIds: aggregateIds,
+ fireTimeBucket: json['fireTimeBucket'] as int?,
version: (json['version'] as int?) ?? 1,
);
}
@@ -124,6 +130,7 @@ class ReminderPayload {
other.color == color &&
other.mode == mode &&
_listEquals(other.aggregateIds, aggregateIds) &&
+ other.fireTimeBucket == fireTimeBucket &&
other.version == version;
}
@@ -140,6 +147,7 @@ class ReminderPayload {
color,
mode,
Object.hashAll(aggregateIds),
+ fireTimeBucket,
version,
);
}
diff --git a/apps/lib/features/calendar/reminders/reminder_action_dedupe_store.dart b/apps/lib/features/calendar/reminders/reminder_action_dedupe_store.dart
new file mode 100644
index 0000000..f7c23df
--- /dev/null
+++ b/apps/lib/features/calendar/reminders/reminder_action_dedupe_store.dart
@@ -0,0 +1,52 @@
+import 'dart:async';
+
+import 'package:shared_preferences/shared_preferences.dart';
+
+typedef SetStringListFn = Future Function(String key, List value);
+
+class ReminderActionDedupeStore {
+ static const String _key = 'calendar_reminder_action_dedupe_v1';
+ static const int _maxEntries = 512;
+
+ final SharedPreferences _prefs;
+ final SetStringListFn _setStringList;
+ Future _queue = Future.value();
+
+ ReminderActionDedupeStore(
+ SharedPreferences prefs, {
+ SetStringListFn? setStringList,
+ }) : _prefs = prefs,
+ _setStringList = setStringList ?? prefs.setStringList;
+
+ Future markIfNew(String actionExecutionId) async {
+ final completer = Completer();
+ _queue = _queue
+ .then((_) async {
+ completer.complete(await _markIfNewInternal(actionExecutionId));
+ })
+ .catchError((_) {
+ if (!completer.isCompleted) {
+ completer.complete(false);
+ }
+ });
+
+ return completer.future;
+ }
+
+ Future _markIfNewInternal(String actionExecutionId) async {
+ final current = List.from(
+ _prefs.getStringList(_key) ?? const [],
+ );
+ if (current.contains(actionExecutionId)) {
+ return false;
+ }
+
+ current.add(actionExecutionId);
+ if (current.length > _maxEntries) {
+ current.removeRange(0, current.length - _maxEntries);
+ }
+
+ final saved = await _setStringList(_key, current);
+ return saved;
+ }
+}
diff --git a/apps/lib/features/calendar/reminders/reminder_action_executor.dart b/apps/lib/features/calendar/reminders/reminder_action_executor.dart
index ee90689..c956cae 100644
--- a/apps/lib/features/calendar/reminders/reminder_action_executor.dart
+++ b/apps/lib/features/calendar/reminders/reminder_action_executor.dart
@@ -27,19 +27,20 @@ class ReminderActionExecutor {
required ReminderPayload payload,
}) async {
final ids = payload.mode == ReminderPayloadMode.aggregate
- ? payload.aggregateIds
+ ? (payload.aggregateIds.isNotEmpty
+ ? payload.aggregateIds
+ : [payload.eventId])
: [payload.eventId];
- if (action == ReminderAction.cancel) {
+ if (action == ReminderAction.archive) {
for (final id in ids) {
await _notificationService.cancelEventReminder(id);
- await _archiveEvent(id, ReminderAction.cancel);
+ await _archiveEvent(id, ReminderAction.archive);
}
return;
}
- if (action == ReminderAction.snooze10m ||
- action == ReminderAction.timeout30s) {
+ if (action == ReminderAction.snooze10m) {
for (final id in ids) {
await _snoozeEvent(id);
}
@@ -50,7 +51,6 @@ class ReminderActionExecutor {
final pending = await _outboxStore.listPending();
for (final item in pending) {
if (item.targetStatus != 'archived') {
- await _outboxStore.markDone(item.opId);
continue;
}
try {
@@ -71,14 +71,14 @@ class ReminderActionExecutor {
final endAt = event.endAt;
if (endAt != null && !now.isBefore(endAt)) {
await _notificationService.cancelEventReminder(eventId);
- await _archiveEvent(eventId, ReminderAction.autoArchive);
+ await _archiveEvent(eventId, ReminderAction.archive);
return;
}
final nextAt = now.add(const Duration(minutes: 10));
if (endAt != null && !nextAt.isBefore(endAt)) {
await _notificationService.cancelEventReminder(eventId);
- await _archiveEvent(eventId, ReminderAction.autoArchive);
+ await _archiveEvent(eventId, ReminderAction.archive);
return;
}
diff --git a/apps/lib/features/calendar/reminders/reminder_cold_start_queue.dart b/apps/lib/features/calendar/reminders/reminder_cold_start_queue.dart
new file mode 100644
index 0000000..823531a
--- /dev/null
+++ b/apps/lib/features/calendar/reminders/reminder_cold_start_queue.dart
@@ -0,0 +1,57 @@
+import 'dart:async';
+import 'dart:collection';
+
+typedef ReminderColdStartReplayTask = Future Function();
+typedef ReminderColdStartTaskErrorHandler =
+ void Function(Object error, StackTrace stackTrace);
+
+class ReminderColdStartQueue {
+ final Queue _tasks =
+ Queue();
+ final ReminderColdStartTaskErrorHandler? _onTaskError;
+ Future? _inFlightReplay;
+
+ ReminderColdStartQueue({ReminderColdStartTaskErrorHandler? onTaskError})
+ : _onTaskError = onTaskError;
+
+ void enqueue(ReminderColdStartReplayTask task) {
+ _tasks.add(task);
+ }
+
+ Future replay() {
+ final inFlightReplay = _inFlightReplay;
+ if (inFlightReplay != null) {
+ return inFlightReplay;
+ }
+
+ final replayCompleter = Completer();
+ final replayFuture = replayCompleter.future;
+ _inFlightReplay = replayFuture;
+
+ scheduleMicrotask(() async {
+ try {
+ await _replayInternal();
+ replayCompleter.complete();
+ } catch (error, stackTrace) {
+ replayCompleter.completeError(error, stackTrace);
+ } finally {
+ if (identical(_inFlightReplay, replayFuture)) {
+ _inFlightReplay = null;
+ }
+ }
+ });
+
+ return replayFuture;
+ }
+
+ Future _replayInternal() async {
+ while (_tasks.isNotEmpty) {
+ final task = _tasks.removeFirst();
+ try {
+ await task();
+ } catch (error, stackTrace) {
+ _onTaskError?.call(error, stackTrace);
+ }
+ }
+ }
+}
diff --git a/apps/lib/features/calendar/reminders/ui/reminder_foreground_presenter.dart b/apps/lib/features/calendar/reminders/ui/reminder_foreground_presenter.dart
new file mode 100644
index 0000000..7253566
--- /dev/null
+++ b/apps/lib/features/calendar/reminders/ui/reminder_foreground_presenter.dart
@@ -0,0 +1,73 @@
+import 'package:flutter/material.dart';
+
+import '../../../../core/theme/design_tokens.dart';
+import '../models/reminder_action.dart';
+import '../models/reminder_payload.dart';
+import '../reminder_action_executor.dart';
+import 'reminder_presentation_coordinator.dart';
+import 'widgets/reminder_action_sheet.dart';
+
+class ReminderForegroundPresenter {
+ final GlobalKey _navigatorKey;
+ final ReminderActionExecutor _executor;
+ final ReminderPresentationCoordinator _coordinator;
+ bool _isPresenting = false;
+
+ ReminderForegroundPresenter({
+ required GlobalKey navigatorKey,
+ required ReminderActionExecutor executor,
+ ReminderPresentationCoordinator? coordinator,
+ }) : _navigatorKey = navigatorKey,
+ _executor = executor,
+ _coordinator = coordinator ?? ReminderPresentationCoordinator();
+
+ Future present(ReminderPayload payload) async {
+ final context = _navigatorKey.currentContext;
+ if (context == null) {
+ return;
+ }
+
+ final lifecycleState = WidgetsBinding.instance.lifecycleState;
+ final isAppActive = lifecycleState == AppLifecycleState.resumed;
+ final shouldPresent = _coordinator.shouldPresent(
+ eventId: payload.eventId,
+ isAppActive: isAppActive,
+ );
+ if (!shouldPresent || _isPresenting) {
+ return;
+ }
+
+ _isPresenting = true;
+ try {
+ final action = await showModalBottomSheet(
+ context: context,
+ useRootNavigator: true,
+ isScrollControlled: true,
+ backgroundColor: Colors.transparent,
+ builder: (sheetContext) {
+ return SafeArea(
+ child: Padding(
+ padding: const EdgeInsets.all(AppSpacing.md),
+ child: ReminderActionSheet(
+ onSnooze: () {
+ Navigator.of(sheetContext).pop(ReminderAction.snooze10m);
+ },
+ onArchive: () {
+ Navigator.of(sheetContext).pop(ReminderAction.archive);
+ },
+ ),
+ ),
+ );
+ },
+ );
+
+ if (action == null) {
+ return;
+ }
+
+ await _executor.handleAction(action: action, payload: payload);
+ } finally {
+ _isPresenting = false;
+ }
+ }
+}
diff --git a/apps/lib/features/calendar/reminders/ui/reminder_presentation_coordinator.dart b/apps/lib/features/calendar/reminders/ui/reminder_presentation_coordinator.dart
new file mode 100644
index 0000000..fc5e85b
--- /dev/null
+++ b/apps/lib/features/calendar/reminders/ui/reminder_presentation_coordinator.dart
@@ -0,0 +1,29 @@
+typedef ReminderPresentationNow = DateTime Function();
+
+class ReminderPresentationCoordinator {
+ final Duration _dedupeWindow;
+ final ReminderPresentationNow _now;
+ final Map _lastPresentedAtByEventId = {};
+
+ ReminderPresentationCoordinator({
+ Duration dedupeWindow = const Duration(seconds: 30),
+ ReminderPresentationNow? now,
+ }) : _dedupeWindow = dedupeWindow,
+ _now = now ?? DateTime.now;
+
+ bool shouldPresent({required String eventId, required bool isAppActive}) {
+ if (!isAppActive) {
+ return false;
+ }
+
+ final currentTime = _now();
+ final lastPresentedAt = _lastPresentedAtByEventId[eventId];
+ if (lastPresentedAt != null &&
+ currentTime.difference(lastPresentedAt) < _dedupeWindow) {
+ return false;
+ }
+
+ _lastPresentedAtByEventId[eventId] = currentTime;
+ return true;
+ }
+}
diff --git a/apps/lib/features/calendar/reminders/ui/widgets/reminder_action_sheet.dart b/apps/lib/features/calendar/reminders/ui/widgets/reminder_action_sheet.dart
new file mode 100644
index 0000000..911530e
--- /dev/null
+++ b/apps/lib/features/calendar/reminders/ui/widgets/reminder_action_sheet.dart
@@ -0,0 +1,58 @@
+import 'package:flutter/material.dart';
+
+import '../../../../../core/theme/design_tokens.dart';
+import '../../../../../shared/widgets/app_button.dart';
+
+class ReminderActionSheet extends StatelessWidget {
+ const ReminderActionSheet({
+ super.key,
+ required this.onSnooze,
+ required this.onArchive,
+ });
+
+ final VoidCallback onSnooze;
+ final VoidCallback onArchive;
+
+ @override
+ Widget build(BuildContext context) {
+ return Container(
+ width: double.infinity,
+ padding: const EdgeInsets.all(AppSpacing.lg),
+ decoration: BoxDecoration(
+ color: AppColors.white,
+ borderRadius: BorderRadius.circular(AppRadius.xl),
+ border: Border.all(color: AppColors.borderSecondary),
+ ),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ '提醒操作',
+ textAlign: TextAlign.center,
+ style: Theme.of(
+ context,
+ ).textTheme.titleMedium?.copyWith(color: AppColors.slate900),
+ ),
+ const SizedBox(height: AppSpacing.lg),
+ Row(
+ crossAxisAlignment: CrossAxisAlignment.center,
+ children: [
+ Expanded(
+ child: AppButton(
+ text: '稍后提醒',
+ isOutlined: true,
+ onPressed: onSnooze,
+ ),
+ ),
+ const SizedBox(width: AppSpacing.md),
+ Expanded(
+ child: AppButton(text: '归档', onPressed: onArchive),
+ ),
+ ],
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/apps/lib/features/calendar/ui/screens/calendar_event_detail_screen.dart b/apps/lib/features/calendar/ui/screens/calendar_event_detail_screen.dart
index 7165744..8c1e6eb 100644
--- a/apps/lib/features/calendar/ui/screens/calendar_event_detail_screen.dart
+++ b/apps/lib/features/calendar/ui/screens/calendar_event_detail_screen.dart
@@ -9,11 +9,13 @@ import '../../../../shared/widgets/app_loading_indicator.dart';
import '../../../../shared/widgets/back_title_page_header.dart';
import '../../../../shared/widgets/detail_header_action_menu.dart';
import '../../../../shared/widgets/destructive_action_sheet.dart';
+import '../../../../shared/widgets/toast/toast.dart';
+import '../../../../shared/widgets/toast/toast_type.dart';
import '../../data/services/calendar_service.dart';
import '../../data/models/schedule_item_model.dart';
import '../utils/event_color_resolver.dart';
-enum _CalendarHeaderAction { edit, delete, share }
+enum _CalendarHeaderAction { edit, delete, share, archive }
class CalendarEventDetailScreen extends StatefulWidget {
final String eventId;
@@ -190,6 +192,17 @@ class _CalendarEventDetailScreenState extends State {
),
);
}
+ if (event.status != ScheduleStatus.archived && event.canEdit) {
+ final isExpired = _isEventExpired(event);
+ items.add(
+ DetailHeaderActionItem<_CalendarHeaderAction>(
+ value: _CalendarHeaderAction.archive,
+ label: '归档',
+ icon: LucideIcons.archive,
+ enabled: !isExpired,
+ ),
+ );
+ }
return DetailHeaderActionMenu<_CalendarHeaderAction>(
items: items,
@@ -197,6 +210,14 @@ class _CalendarEventDetailScreenState extends State {
);
}
+ bool _isEventExpired(ScheduleItemModel event) {
+ final now = DateTime.now();
+ if (event.endAt != null) {
+ return event.endAt!.isBefore(now);
+ }
+ return event.startAt.isBefore(now);
+ }
+
void _handleHeaderAction(
_CalendarHeaderAction action,
ScheduleItemModel event,
@@ -213,6 +234,9 @@ class _CalendarEventDetailScreenState extends State {
case _CalendarHeaderAction.share:
context.push(AppRoutes.calendarEventShare(event.id));
return;
+ case _CalendarHeaderAction.archive:
+ _archiveEvent();
+ return;
}
}
@@ -460,6 +484,29 @@ class _CalendarEventDetailScreenState extends State {
context.pop();
}
+ Future _archiveEvent() async {
+ final confirmed = await showDestructiveActionSheet(
+ context,
+ title: '归档日程',
+ message: '归档后此日程将标记为过期,确定要归档吗?',
+ confirmText: '确认归档',
+ );
+ if (!confirmed) {
+ return;
+ }
+ try {
+ await sl().archiveEvent(widget.eventId);
+ await _loadEvent();
+ if (mounted) {
+ Toast.show(context, '已归档', type: ToastType.success);
+ }
+ } catch (e) {
+ if (mounted) {
+ Toast.show(context, '归档失败', type: ToastType.error);
+ }
+ }
+ }
+
String _formatRangeLabel(DateTime startAt, DateTime? endAt) {
final dateLabel =
'${startAt.month}月${startAt.day}日 ${_getWeekday(startAt.weekday)}';
diff --git a/apps/lib/features/calendar/ui/widgets/create_event_sheet.dart b/apps/lib/features/calendar/ui/widgets/create_event_sheet.dart
index 1944604..07ed0b8 100644
--- a/apps/lib/features/calendar/ui/widgets/create_event_sheet.dart
+++ b/apps/lib/features/calendar/ui/widgets/create_event_sheet.dart
@@ -4,6 +4,7 @@ import '../../../../core/di/injection.dart';
import '../../../../core/notifications/local_notification_service.dart';
import '../../../../core/theme/design_tokens.dart';
import '../../../../shared/widgets/app_loading_indicator.dart';
+import '../../../../shared/widgets/app_selection_sheet.dart';
import '../../../../shared/widgets/app_sheet_input_field.dart';
import '../../../../shared/widgets/back_title_page_header.dart';
import '../../../../shared/widgets/toast/toast.dart';
@@ -107,12 +108,21 @@ class _CreateEventSheetState extends State
event.metadata?.reminderMinutes,
);
} else {
- final now =
- widget.initialDate ?? _roundToNearestMinute(DateTime.now(), 5);
- _startDate = now;
- _startTime = now;
- _endDate = now;
- _endTime = now.add(const Duration(hours: 1));
+ final now = DateTime.now();
+ final initial = widget.initialDate;
+ final rounded = _roundToNearestMinute(now, 5);
+ _startDate = initial != null
+ ? DateTime(
+ initial.year,
+ initial.month,
+ initial.day,
+ rounded.hour,
+ rounded.minute,
+ )
+ : rounded;
+ _startTime = _startDate;
+ _endDate = _startDate;
+ _endTime = _startDate.add(const Duration(hours: 1));
}
}
@@ -139,15 +149,19 @@ class _CreateEventSheetState extends State
@override
Widget build(BuildContext context) {
if (widget.pageMode) {
- return Container(
- color: AppColors.background,
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- _buildPageHeader(),
- _buildTabBar(),
- Expanded(child: _buildTabContent()),
- ],
+ return GestureDetector(
+ behavior: HitTestBehavior.translucent,
+ onTap: () => FocusScope.of(context).unfocus(),
+ child: Container(
+ color: AppColors.background,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ _buildPageHeader(),
+ _buildTabBar(),
+ Expanded(child: _buildTabContent()),
+ ],
+ ),
),
);
}
@@ -331,12 +345,7 @@ class _CreateEventSheetState extends State
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- _buildTextField(
- '标题',
- _titleController,
- '请输入日程标题',
- autofocus: !_isEditing,
- ),
+ _buildTextField('标题', _titleController, '请输入日程标题'),
const SizedBox(height: 20),
_buildDateTimePicker('开始', _startDate, _startTime, (date, time) {
setState(() {
@@ -580,7 +589,6 @@ class _CreateEventSheetState extends State
}
Widget _buildReminderPicker() {
- final options = _buildReminderOptions();
String labelOf(int? value) {
if (value == null) {
return '无提醒';
@@ -603,37 +611,51 @@ class _CreateEventSheetState extends State
),
),
const SizedBox(height: 8),
- Container(
- width: double.infinity,
- padding: const EdgeInsets.symmetric(horizontal: 12),
- decoration: BoxDecoration(
- color: Colors.white,
- borderRadius: BorderRadius.circular(AppRadius.lg),
- border: Border.all(color: AppColors.border),
- ),
- child: DropdownButtonHideUnderline(
- child: DropdownButton(
- value: _reminderMinutes,
- isExpanded: true,
+ InkWell(
+ onTap: () async {
+ final options = _buildReminderOptions();
+ final selected = await showAppSelectionSheet(
+ context,
+ title: '选择提醒时间',
items: options
- .map(
- (value) => DropdownMenuItem(
- value: value,
- child: Text(
- labelOf(value),
- style: const TextStyle(
- fontSize: 14,
- color: AppColors.slate700,
- ),
- ),
- ),
- )
+ .map((v) => AppSelectionItem(value: v, label: labelOf(v)))
.toList(),
- onChanged: (value) {
- setState(() {
- _reminderMinutes = value;
- });
- },
+ selectedValue: _reminderMinutes,
+ );
+ if (selected != null) {
+ setState(() {
+ _reminderMinutes = selected;
+ });
+ }
+ },
+ borderRadius: BorderRadius.circular(AppRadius.md),
+ child: Container(
+ width: double.infinity,
+ padding: const EdgeInsets.all(AppSpacing.md),
+ decoration: BoxDecoration(
+ color: AppColors.slate50,
+ borderRadius: BorderRadius.circular(AppRadius.md),
+ border: Border.all(color: AppColors.borderSecondary),
+ ),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.center,
+ children: [
+ Expanded(
+ child: Text(
+ labelOf(_reminderMinutes),
+ style: const TextStyle(
+ fontSize: 15,
+ fontWeight: FontWeight.w500,
+ color: AppColors.slate900,
+ ),
+ ),
+ ),
+ const Icon(
+ LucideIcons.chevronRight,
+ size: 16,
+ color: AppColors.slate400,
+ ),
+ ],
),
),
),
diff --git a/apps/lib/features/calendar/ui/widgets/date_time_picker_sheet.dart b/apps/lib/features/calendar/ui/widgets/date_time_picker_sheet.dart
index 598727c..b861e07 100644
--- a/apps/lib/features/calendar/ui/widgets/date_time_picker_sheet.dart
+++ b/apps/lib/features/calendar/ui/widgets/date_time_picker_sheet.dart
@@ -54,7 +54,7 @@ class _DateTimePickerSheetState extends State {
if (_selectedYear == minDate.year &&
_selectedMonth == minDate.month &&
_selectedDay == minDate.day) {
- return _allHours.where((h) => h > minDate.hour).toList();
+ return _allHours.where((h) => h >= minDate.hour).toList();
}
return _allHours;
}
@@ -73,7 +73,7 @@ class _DateTimePickerSheetState extends State {
_selectedMonth == minDate.month &&
_selectedDay == minDate.day &&
_selectedHour == minDate.hour) {
- return _allMinutes.where((m) => m > minDate.minute).toList();
+ return _allMinutes.where((m) => m >= minDate.minute).toList();
}
return _allMinutes;
}
@@ -100,6 +100,12 @@ class _DateTimePickerSheetState extends State {
_hourController = FixedExtentScrollController(
initialItem: _filteredHours.indexOf(_selectedHour),
);
+
+ if (_filteredMinutes.isEmpty) {
+ _selectedMinute = 0;
+ } else if (!_filteredMinutes.contains(_selectedMinute)) {
+ _selectedMinute = _filteredMinutes.first;
+ }
_minuteController = FixedExtentScrollController(
initialItem: _filteredMinutes.indexOf(_selectedMinute),
);
diff --git a/apps/lib/features/home/ui/controllers/home_keyboard_inset_calculator.dart b/apps/lib/features/home/ui/controllers/home_keyboard_inset_calculator.dart
new file mode 100644
index 0000000..a0a7ba3
--- /dev/null
+++ b/apps/lib/features/home/ui/controllers/home_keyboard_inset_calculator.dart
@@ -0,0 +1,19 @@
+import '../../../../core/theme/design_tokens.dart';
+
+class HomeKeyboardInsetCalculator {
+ static double compute({
+ required double rawViewInsetBottom,
+ required double bottomViewPadding,
+ }) {
+ if (rawViewInsetBottom <= AppSpacing.xs) {
+ return 0;
+ }
+
+ final adjustedInset = rawViewInsetBottom - bottomViewPadding;
+ if (adjustedInset <= AppSpacing.xs) {
+ return 0;
+ }
+
+ return adjustedInset;
+ }
+}
diff --git a/apps/lib/features/home/ui/screens/home_screen.dart b/apps/lib/features/home/ui/screens/home_screen.dart
index d303c1c..fce7278 100644
--- a/apps/lib/features/home/ui/screens/home_screen.dart
+++ b/apps/lib/features/home/ui/screens/home_screen.dart
@@ -14,6 +14,7 @@ import '../../../chat/presentation/bloc/agent_stage.dart';
import '../../../chat/presentation/bloc/chat_bloc.dart';
import '../../../messages/data/inbox_api.dart';
import '../../data/voice_recorder.dart';
+import '../controllers/home_keyboard_inset_calculator.dart';
import '../controllers/home_message_viewport_controller.dart';
import '../controllers/home_viewport_coordinator.dart';
import '../../../../shared/widgets/app_pull_refresh_feedback.dart';
@@ -100,7 +101,6 @@ class _HomeScreenState extends State
double? _historyViewportMaxExtent;
final GlobalKey _inputHostKey =
GlobalKey();
- double _stableKeyboardInset = 0;
@override
void initState() {
@@ -541,16 +541,10 @@ class _HomeScreenState extends State
double _effectiveKeyboardInset(BuildContext context) {
final mediaQuery = MediaQuery.of(context);
- final rawInset = mediaQuery.viewInsets.bottom;
- if (rawInset <= AppSpacing.xs) {
- _stableKeyboardInset = 0;
- return 0;
- }
- // Only update stable if new value is larger (never decrease on jitter down)
- if (rawInset > _stableKeyboardInset) {
- _stableKeyboardInset = rawInset;
- }
- return _stableKeyboardInset;
+ return HomeKeyboardInsetCalculator.compute(
+ rawViewInsetBottom: mediaQuery.viewInsets.bottom,
+ bottomViewPadding: mediaQuery.viewPadding.bottom,
+ );
}
void _dismissKeyboard() {
diff --git a/apps/lib/features/settings/data/services/settings_user_cache.dart b/apps/lib/features/settings/data/services/settings_user_cache.dart
new file mode 100644
index 0000000..4cc1e90
--- /dev/null
+++ b/apps/lib/features/settings/data/services/settings_user_cache.dart
@@ -0,0 +1,49 @@
+import '../../../users/data/models/user_response.dart';
+
+class SettingsUserCache {
+ UserResponse? _cachedUser;
+ Future? _inflight;
+ int _generation = 0;
+
+ UserResponse? get cachedUser => _cachedUser;
+
+ Future getOrLoad(Future Function() loader) {
+ final cached = _cachedUser;
+ if (cached != null) {
+ return Future.value(cached);
+ }
+
+ final inflight = _inflight;
+ if (inflight != null) {
+ return inflight;
+ }
+
+ final generation = _generation;
+ late final Future request;
+ request = loader()
+ .then((user) {
+ if (generation == _generation) {
+ _cachedUser = user;
+ }
+ return user;
+ })
+ .whenComplete(() {
+ if (identical(_inflight, request)) {
+ _inflight = null;
+ }
+ });
+
+ _inflight = request;
+ return request;
+ }
+
+ void set(UserResponse user) {
+ _cachedUser = user;
+ }
+
+ void invalidate() {
+ _generation += 1;
+ _cachedUser = null;
+ _inflight = null;
+ }
+}
diff --git a/apps/lib/features/settings/ui/screens/account_screen.dart b/apps/lib/features/settings/ui/screens/account_screen.dart
deleted file mode 100644
index c592571..0000000
--- a/apps/lib/features/settings/ui/screens/account_screen.dart
+++ /dev/null
@@ -1,223 +0,0 @@
-import 'package:flutter/material.dart';
-import 'package:flutter_bloc/flutter_bloc.dart';
-import 'package:go_router/go_router.dart';
-import '../../../../core/theme/design_tokens.dart';
-import '../../../../shared/widgets/app_pressable.dart';
-import '../../../../shared/widgets/toast/toast.dart';
-import '../../../../shared/widgets/toast/toast_type.dart';
-import '../../../auth/presentation/bloc/auth_bloc.dart';
-import '../../../auth/presentation/bloc/auth_event.dart';
-import '../../../auth/presentation/bloc/auth_state.dart';
-import '../../../../shared/widgets/app_button.dart';
-import '../widgets/account_section_card.dart';
-import '../widgets/settings_page_scaffold.dart';
-
-class AccountScreen extends StatelessWidget {
- const AccountScreen({super.key});
-
- static const double _menuItemHeight = AppSpacing.xl * 2 + AppSpacing.md;
- static const double _menuItemHorizontalPadding = AppSpacing.md;
- static const double _menuIconSize = 20;
- static const double _menuChevronSize = 18;
-
- @override
- Widget build(BuildContext context) {
- return SettingsPageScaffold(
- title: '账户',
- onBack: () => context.pop(),
- body: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [_buildListSurface(context)],
- ),
- );
- }
-
- Widget _buildListSurface(BuildContext context) {
- return AccountSectionCard(
- backgroundColor: AppColors.white,
- borderColor: AppColors.borderSecondary,
- contentPadding: const EdgeInsets.symmetric(
- horizontal: AppSpacing.md,
- vertical: AppSpacing.sm,
- ),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- _buildMenuItem(
- icon: Icons.edit,
- title: '编辑资料',
- onTap: () => context.push('/edit-profile'),
- ),
- _buildDivider(),
- _buildMenuItem(
- icon: Icons.logout,
- title: '退出登录',
- titleColor: AppColors.feedbackErrorText,
- iconColor: AppColors.feedbackErrorIcon,
- trailingColor: AppColors.feedbackErrorIcon,
- onTap: () => _showLogoutSheet(context),
- ),
- ],
- ),
- );
- }
-
- Widget _buildMenuItem({
- required IconData icon,
- required String title,
- required VoidCallback onTap,
- Color titleColor = AppColors.slate900,
- Color iconColor = AppColors.slate500,
- Color trailingColor = AppColors.slate400,
- }) {
- return AppPressable(
- onTap: onTap,
- borderRadius: BorderRadius.circular(AppRadius.md),
- child: Container(
- constraints: const BoxConstraints(minHeight: _menuItemHeight),
- padding: const EdgeInsets.symmetric(
- horizontal: _menuItemHorizontalPadding,
- vertical: AppSpacing.sm,
- ),
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.center,
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- Row(
- crossAxisAlignment: CrossAxisAlignment.center,
- children: [
- SizedBox(
- width: _menuIconSize,
- child: Icon(icon, size: _menuIconSize, color: iconColor),
- ),
- const SizedBox(width: AppSpacing.md),
- Text(
- title,
- style: TextStyle(
- fontSize: 16,
- fontWeight: FontWeight.w600,
- color: titleColor,
- ),
- ),
- ],
- ),
- Icon(
- Icons.chevron_right,
- size: _menuChevronSize,
- color: trailingColor,
- ),
- ],
- ),
- ),
- );
- }
-
- Widget _buildDivider() {
- return Container(
- height: 1,
- margin: const EdgeInsets.only(
- left: _menuItemHorizontalPadding + _menuIconSize + AppSpacing.md,
- right: _menuItemHorizontalPadding,
- ),
- color: AppColors.borderTertiary,
- );
- }
-
- void _showLogoutSheet(BuildContext context) {
- showModalBottomSheet(
- context: context,
- backgroundColor: Colors.transparent,
- isScrollControlled: true,
- builder: (sheetContext) => SafeArea(
- top: false,
- child: Container(
- margin: const EdgeInsets.fromLTRB(
- AppSpacing.md,
- AppSpacing.none,
- AppSpacing.md,
- AppSpacing.md,
- ),
- padding: const EdgeInsets.all(AppSpacing.lg),
- decoration: BoxDecoration(
- color: AppColors.white,
- borderRadius: BorderRadius.circular(AppRadius.xl),
- border: Border.all(color: AppColors.borderSecondary),
- ),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- const Text(
- '退出登录',
- style: TextStyle(
- fontSize: 18,
- fontWeight: FontWeight.w700,
- color: AppColors.slate900,
- ),
- textAlign: TextAlign.center,
- ),
- const SizedBox(height: AppSpacing.xs),
- const Text(
- '确定退出当前账户吗?',
- style: TextStyle(fontSize: 14, color: AppColors.slate500),
- textAlign: TextAlign.center,
- ),
- const SizedBox(height: AppSpacing.lg),
- SizedBox(
- height: 52,
- child: GestureDetector(
- onTap: () async {
- Navigator.of(sheetContext).pop();
- final authBloc = context.read();
- authBloc.add(AuthLoggedOut());
- try {
- await authBloc.stream
- .firstWhere((state) => state is AuthUnauthenticated)
- .timeout(const Duration(seconds: 5));
- } catch (_) {
- if (context.mounted) {
- Toast.show(
- context,
- '退出失败,请稍后重试',
- type: ToastType.error,
- );
- }
- return;
- }
- if (context.mounted) {
- context.go('/');
- }
- },
- child: Container(
- decoration: BoxDecoration(
- color: AppColors.feedbackErrorIcon,
- borderRadius: BorderRadius.circular(AppRadius.full),
- ),
- alignment: Alignment.center,
- child: const Text(
- '确认退出',
- style: TextStyle(
- fontSize: 15,
- fontWeight: FontWeight.w700,
- color: AppColors.white,
- ),
- ),
- ),
- ),
- ),
- const SizedBox(height: AppSpacing.sm),
- SizedBox(
- height: 52,
- child: AppButton(
- text: '取消',
- isOutlined: true,
- onPressed: () => Navigator.of(sheetContext).pop(),
- ),
- ),
- ],
- ),
- ),
- ),
- );
- }
-}
diff --git a/apps/lib/features/settings/ui/screens/edit_profile_screen.dart b/apps/lib/features/settings/ui/screens/edit_profile_screen.dart
index 8f516fc..4b51bdf 100644
--- a/apps/lib/features/settings/ui/screens/edit_profile_screen.dart
+++ b/apps/lib/features/settings/ui/screens/edit_profile_screen.dart
@@ -6,6 +6,7 @@ import '../../../../shared/widgets/app_button.dart';
import '../../../../shared/widgets/app_loading_indicator.dart';
import '../../../../shared/widgets/toast/toast.dart';
import '../../../../shared/widgets/toast/toast_type.dart';
+import '../../data/services/settings_user_cache.dart';
import '../../../users/data/models/user_response.dart';
import '../../../users/data/users_api.dart';
import '../widgets/account_section_card.dart';
@@ -22,6 +23,7 @@ class _EditProfileScreenState extends State {
final _usernameController = TextEditingController();
final _bioController = TextEditingController();
final _usersApi = sl();
+ final _userCache = sl();
UserResponse? _user;
bool _isLoading = true;
@@ -35,9 +37,21 @@ class _EditProfileScreenState extends State {
}
Future _loadUser() async {
+ final cached = _userCache.cachedUser;
+ if (cached != null) {
+ setState(() {
+ _user = cached;
+ _usernameController.text = cached.username;
+ _bioController.text = cached.bio ?? '';
+ _isLoading = false;
+ });
+ return;
+ }
+
try {
final user = await _usersApi.getMe();
if (mounted) {
+ _userCache.set(user);
setState(() {
_user = user;
_usernameController.text = user.username;
@@ -91,7 +105,8 @@ class _EditProfileScreenState extends State {
username: newUsername,
bio: newBio.isEmpty ? null : newBio,
);
- await _usersApi.updateMe(request);
+ final updatedUser = await _usersApi.updateMe(request);
+ _userCache.set(updatedUser);
if (mounted) {
Toast.show(context, '保存成功', type: ToastType.success);
diff --git a/apps/lib/features/settings/ui/screens/settings_screen.dart b/apps/lib/features/settings/ui/screens/settings_screen.dart
index 6b5f631..f645069 100644
--- a/apps/lib/features/settings/ui/screens/settings_screen.dart
+++ b/apps/lib/features/settings/ui/screens/settings_screen.dart
@@ -1,18 +1,30 @@
import 'package:flutter/material.dart';
+import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:social_app/core/constants/app_constants.dart';
import 'package:social_app/core/di/injection.dart';
+import 'package:social_app/core/router/app_routes.dart';
import 'package:social_app/core/theme/design_tokens.dart';
+import 'package:social_app/shared/widgets/app_button.dart';
import 'package:social_app/shared/widgets/app_loading_indicator.dart';
+import 'package:social_app/shared/widgets/app_pressable.dart';
+import 'package:social_app/shared/widgets/destructive_action_sheet.dart';
import 'package:social_app/shared/widgets/toast/toast.dart';
import 'package:social_app/shared/widgets/toast/toast_type.dart';
import 'package:social_app/shared/utils/phone_display_formatter.dart';
+import 'package:social_app/features/auth/presentation/bloc/auth_bloc.dart';
+import 'package:social_app/features/auth/presentation/bloc/auth_event.dart';
+import 'package:social_app/features/auth/presentation/bloc/auth_state.dart';
import 'package:social_app/features/friends/data/friends_api.dart';
import 'package:social_app/features/settings/data/settings_api.dart';
+import 'package:social_app/features/settings/data/services/settings_user_cache.dart';
import 'package:social_app/features/users/data/models/user_response.dart';
import 'package:social_app/features/users/data/users_api.dart';
import '../widgets/settings_page_scaffold.dart';
+const settingsProfileEditButtonKey = ValueKey('settings_profile_edit_button');
+const settingsLogoutButtonKey = ValueKey('settings_logout_button');
+
class SettingsScreen extends StatefulWidget {
const SettingsScreen({super.key});
@@ -21,6 +33,10 @@ class SettingsScreen extends StatefulWidget {
}
class _SettingsScreenState extends State {
+ final UsersApi _usersApi = sl();
+ final FriendsApi _friendsApi = sl();
+ final SettingsUserCache _userCache = sl();
+
UserResponse? _user;
bool _isLoading = true;
int _friendsCount = 0;
@@ -29,39 +45,45 @@ class _SettingsScreenState extends State {
@override
void initState() {
super.initState();
+ final cachedUser = _userCache.cachedUser;
+ if (cachedUser != null) {
+ _user = cachedUser;
+ _isLoading = false;
+ }
_loadData();
}
Future _loadData() async {
try {
- final usersApi = sl();
- final friendsApi = sl();
-
- final results = await Future.wait([
- usersApi.getMe(),
- friendsApi.getFriends(),
- ]);
-
- final user = results[0] as UserResponse;
- final friends = results[1] as List;
-
+ final user = await _userCache.getOrLoad(_usersApi.getMe);
if (mounted) {
setState(() {
_user = user;
- _friendsCount = friends.length;
- _firstFriendName = friends.isNotEmpty
- ? friends.first.friend.username
- : null;
_isLoading = false;
});
}
} catch (e) {
- if (mounted) {
+ if (mounted && _user == null) {
setState(() {
_isLoading = false;
});
}
}
+
+ try {
+ final friends = await _friendsApi.getFriends();
+
+ if (mounted) {
+ setState(() {
+ _friendsCount = friends.length;
+ _firstFriendName = friends.isNotEmpty
+ ? friends.first.friend.username
+ : null;
+ });
+ }
+ } catch (e) {
+ // Keep profile available even when contacts fail.
+ }
}
@override
@@ -73,17 +95,33 @@ class _SettingsScreenState extends State {
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_buildProfileHero(),
- const SizedBox(height: 16),
+ const SizedBox(height: AppSpacing.lg),
_buildQuickActions(context),
- const SizedBox(height: 16),
+ const SizedBox(height: AppSpacing.lg),
_buildSubscriptionCard(),
- const SizedBox(height: 16),
+ const SizedBox(height: AppSpacing.lg),
_buildMenuCard(context),
+ const SizedBox(height: AppSpacing.xl),
+ _buildLogoutAction(),
],
),
);
}
+ Widget _buildSectionLabel(String label) {
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: AppSpacing.xs),
+ child: Text(
+ label,
+ style: const TextStyle(
+ fontSize: 13,
+ fontWeight: FontWeight.w600,
+ color: AppColors.slate500,
+ ),
+ ),
+ );
+ }
+
Widget _buildProfileHero() {
if (_isLoading) {
return Container(
@@ -92,7 +130,7 @@ class _SettingsScreenState extends State {
padding: const EdgeInsets.all(AppSpacing.xl),
decoration: BoxDecoration(
color: AppColors.white,
- borderRadius: BorderRadius.circular(24),
+ borderRadius: BorderRadius.circular(AppRadius.xxl),
),
child: const Center(child: AppLoadingIndicator(size: 22)),
);
@@ -110,109 +148,147 @@ class _SettingsScreenState extends State {
gradient: const LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
- colors: [AppColors.white, Color(0xF8F9FCFF)],
+ colors: [AppColors.white, AppColors.surfaceInfoLight],
),
- borderRadius: BorderRadius.circular(24),
- border: Border.all(color: AppColors.borderSecondary),
- boxShadow: const [
+ borderRadius: BorderRadius.circular(AppRadius.xxl),
+ border: Border.all(color: AppColors.borderTertiary),
+ boxShadow: [
BoxShadow(
- color: Color(0x05000000),
- blurRadius: 12,
- offset: Offset(0, 3),
+ color: AppColors.blue100.withValues(alpha: 0.35),
+ blurRadius: 14,
+ offset: const Offset(0, 4),
),
],
),
- child: Row(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- Container(
- width: 64,
- height: 64,
- decoration: BoxDecoration(
- gradient: LinearGradient(
- begin: Alignment.topLeft,
- end: Alignment.bottomRight,
- colors: [AppColors.blue100, AppColors.blue50],
- ),
- borderRadius: BorderRadius.circular(32),
- boxShadow: [
- BoxShadow(
- color: Color.fromRGBO(
- AppColors.blue400.r.toInt(),
- AppColors.blue400.g.toInt(),
- AppColors.blue400.b.toInt(),
- 0.2,
+ Row(
+ crossAxisAlignment: CrossAxisAlignment.center,
+ children: [
+ Container(
+ width: 64,
+ height: 64,
+ decoration: BoxDecoration(
+ gradient: LinearGradient(
+ begin: Alignment.topLeft,
+ end: Alignment.bottomRight,
+ colors: [AppColors.blue100, AppColors.blue50],
),
- blurRadius: 12,
- offset: const Offset(0, 4),
- ),
- ],
- ),
- child: const Icon(Icons.person, size: 28, color: AppColors.blue600),
- ),
- const SizedBox(width: AppSpacing.lg),
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- mainAxisAlignment: MainAxisAlignment.center,
- children: [
- Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- crossAxisAlignment: CrossAxisAlignment.center,
- children: [
- Expanded(
- child: Text(
- username,
- style: const TextStyle(
- fontSize: 20,
- fontWeight: FontWeight.w700,
- color: AppColors.slate900,
- ),
- overflow: TextOverflow.ellipsis,
+ borderRadius: BorderRadius.circular(32),
+ boxShadow: [
+ BoxShadow(
+ color: Color.fromRGBO(
+ AppColors.blue400.r.toInt(),
+ AppColors.blue400.g.toInt(),
+ AppColors.blue400.b.toInt(),
+ 0.2,
),
+ blurRadius: 12,
+ offset: const Offset(0, 4),
),
- Container(
- padding: const EdgeInsets.symmetric(
- horizontal: 10,
- vertical: 5,
+ ],
+ ),
+ child: const Icon(
+ Icons.person,
+ size: 28,
+ color: AppColors.blue600,
+ ),
+ ),
+ const SizedBox(width: AppSpacing.lg),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Text(
+ username,
+ style: const TextStyle(
+ fontSize: 20,
+ fontWeight: FontWeight.w700,
+ color: AppColors.slate900,
),
- decoration: BoxDecoration(
- gradient: LinearGradient(
- colors: [
- AppColors.blue50,
- AppColors.surfaceInfoLight,
- ],
- ),
- borderRadius: BorderRadius.circular(12),
- border: Border.all(color: AppColors.borderQuaternary),
- ),
- child: const Text(
- 'Free',
- style: TextStyle(
- fontSize: 11,
- fontWeight: FontWeight.w600,
- color: AppColors.blue600,
- ),
+ overflow: TextOverflow.ellipsis,
+ ),
+ const SizedBox(height: 6),
+ Text(
+ phone,
+ style: TextStyle(
+ fontSize: 13,
+ fontWeight: FontWeight.w500,
+ color: AppColors.slate500,
),
),
],
),
- const SizedBox(height: 6),
- Text(
- phone,
- style: TextStyle(
- fontSize: 13,
- fontWeight: FontWeight.w500,
- color: AppColors.slate500,
+ ),
+ const SizedBox(width: AppSpacing.md),
+ Column(
+ crossAxisAlignment: CrossAxisAlignment.end,
+ children: [
+ AppPressable(
+ key: settingsProfileEditButtonKey,
+ onTap: _onTapEditProfile,
+ borderRadius: BorderRadius.circular(AppRadius.lg),
+ child: SizedBox(
+ width: AppSpacing.xl * 2,
+ height: AppSpacing.xl * 2,
+ child: Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ crossAxisAlignment: CrossAxisAlignment.center,
+ children: [
+ const Icon(
+ Icons.edit,
+ size: 14,
+ color: AppColors.slate500,
+ ),
+ const SizedBox(height: 3),
+ Container(
+ width: 12,
+ height: 1.5,
+ decoration: BoxDecoration(
+ color: AppColors.slate400,
+ borderRadius: BorderRadius.circular(
+ AppRadius.full,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
),
- ),
- ],
- ),
+ const SizedBox(height: AppSpacing.sm),
+ _buildFreeBadge(),
+ ],
+ ),
+ ],
),
],
),
);
}
+ Widget _buildFreeBadge() {
+ return Container(
+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
+ decoration: BoxDecoration(
+ gradient: LinearGradient(
+ colors: [AppColors.blue50, AppColors.surfaceInfoLight],
+ ),
+ borderRadius: BorderRadius.circular(12),
+ border: Border.all(color: AppColors.borderQuaternary),
+ ),
+ child: const Text(
+ 'Free',
+ style: TextStyle(
+ fontSize: 11,
+ fontWeight: FontWeight.w600,
+ color: AppColors.blue600,
+ ),
+ ),
+ );
+ }
+
String _buildFriendsSubtitle() {
if (_friendsCount == 0) {
return '暂无联系人';
@@ -232,17 +308,17 @@ class _SettingsScreenState extends State {
iconColor: AppColors.blue500,
title: '联系人',
subtitle: _buildFriendsSubtitle(),
- onTap: () => context.push('/contacts'),
+ onTap: () => context.push(AppRoutes.contactsList),
),
),
const SizedBox(width: AppSpacing.md),
Expanded(
child: _buildActionCard(
icon: Icons.auto_awesome,
- iconColor: const Color(0xFF8B5CF6),
+ iconColor: AppColors.violet500,
title: '周期计划',
subtitle: '已启用:会议提醒',
- onTap: () => context.push('/settings/features'),
+ onTap: () => context.push(AppRoutes.settingsFeatures),
),
),
],
@@ -256,19 +332,21 @@ class _SettingsScreenState extends State {
required String subtitle,
required VoidCallback onTap,
}) {
- return GestureDetector(
+ return AppPressable(
onTap: onTap,
+ borderRadius: BorderRadius.circular(AppRadius.xl),
child: Container(
+ constraints: const BoxConstraints(minHeight: 136),
padding: const EdgeInsets.all(AppSpacing.lg),
decoration: BoxDecoration(
color: AppColors.white,
- borderRadius: BorderRadius.circular(20),
+ borderRadius: BorderRadius.circular(AppRadius.xl),
border: Border.all(color: AppColors.borderSecondary),
- boxShadow: const [
+ boxShadow: [
BoxShadow(
- color: Color(0x04000000),
- blurRadius: 6,
- offset: Offset(0, 1),
+ color: AppColors.slate200.withValues(alpha: 0.45),
+ blurRadius: 8,
+ offset: const Offset(0, 2),
),
],
),
@@ -323,15 +401,15 @@ class _SettingsScreenState extends State {
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
- colors: [AppColors.white, const Color(0xFFFAFBFF)],
+ colors: [AppColors.white, AppColors.surfaceInfoLight],
),
- borderRadius: BorderRadius.circular(20),
- border: Border.all(color: AppColors.borderSecondary),
- boxShadow: const [
+ borderRadius: BorderRadius.circular(AppRadius.xl),
+ border: Border.all(color: AppColors.borderTertiary),
+ boxShadow: [
BoxShadow(
- color: Color(0x03000000),
- blurRadius: 6,
- offset: Offset(0, 1),
+ color: AppColors.slate200.withValues(alpha: 0.4),
+ blurRadius: 8,
+ offset: const Offset(0, 2),
),
],
),
@@ -419,7 +497,7 @@ class _SettingsScreenState extends State {
return Container(
decoration: BoxDecoration(
color: AppColors.white,
- borderRadius: BorderRadius.circular(16),
+ borderRadius: BorderRadius.circular(AppRadius.xl),
border: Border.all(color: AppColors.borderSecondary),
),
child: Column(
@@ -433,13 +511,7 @@ class _SettingsScreenState extends State {
_buildMenuItem(
icon: Icons.bookmark,
title: '我的记忆',
- onTap: () => context.push('/settings/memory'),
- ),
- _buildDivider(),
- _buildMenuItem(
- icon: Icons.person,
- title: '我的账户',
- onTap: () => context.push('/settings/account'),
+ onTap: () => context.push(AppRoutes.settingsMemory),
),
_buildDivider(),
_buildMenuItem(
@@ -459,9 +531,9 @@ class _SettingsScreenState extends State {
String? trailing,
required VoidCallback onTap,
}) {
- return GestureDetector(
+ return AppPressable(
onTap: onTap,
- behavior: HitTestBehavior.opaque,
+ borderRadius: BorderRadius.circular(AppRadius.md),
child: Container(
height: 56,
padding: const EdgeInsets.symmetric(horizontal: 14),
@@ -515,6 +587,45 @@ class _SettingsScreenState extends State {
);
}
+ Future _onTapEditProfile() async {
+ final changed = await context.push(AppRoutes.settingsEditProfile);
+ if (changed == true && mounted) {
+ final cached = _userCache.cachedUser;
+ if (cached != null) {
+ setState(() {
+ _user = cached;
+ });
+ }
+ }
+ }
+
+ Future _onTapLogout() async {
+ final confirmed = await showDestructiveActionSheet(
+ context,
+ title: '退出登录',
+ message: '确定退出当前账户吗?',
+ confirmText: '确认退出',
+ );
+ if (!confirmed || !mounted) {
+ return;
+ }
+
+ _userCache.invalidate();
+ final authBloc = context.read();
+ authBloc.add(AuthLoggedOut());
+ try {
+ await authBloc.stream
+ .firstWhere((state) => state is AuthUnauthenticated)
+ .timeout(const Duration(seconds: 5));
+ } catch (_) {
+ if (!mounted) return;
+ Toast.show(context, '退出失败,请稍后重试', type: ToastType.error);
+ return;
+ }
+ if (!mounted) return;
+ context.go(AppRoutes.authLogin);
+ }
+
Future _checkForUpdates() async {
try {
final settingsApi = sl();
@@ -566,4 +677,17 @@ class _SettingsScreenState extends State {
Toast.show(context, '检查更新失败', type: ToastType.error);
}
}
+
+ Widget _buildLogoutAction() {
+ return SizedBox(
+ width: double.infinity,
+ height: 52,
+ child: AppButton(
+ key: settingsLogoutButtonKey,
+ text: '退出登录',
+ isOutlined: true,
+ onPressed: () => _onTapLogout(),
+ ),
+ );
+ }
}
diff --git a/apps/lib/features/settings/ui/widgets/settings_page_scaffold.dart b/apps/lib/features/settings/ui/widgets/settings_page_scaffold.dart
index 5f2a300..b8d9284 100644
--- a/apps/lib/features/settings/ui/widgets/settings_page_scaffold.dart
+++ b/apps/lib/features/settings/ui/widgets/settings_page_scaffold.dart
@@ -51,15 +51,7 @@ class SettingsPageScaffold extends StatelessWidget {
AppSpacing.xl,
AppSpacing.xl,
),
- child: Container(
- padding: const EdgeInsets.all(AppSpacing.md),
- decoration: BoxDecoration(
- color: AppColors.surfaceInfoLight,
- borderRadius: BorderRadius.circular(AppRadius.xl),
- border: Border.all(color: AppColors.borderTertiary),
- ),
- child: footer,
- ),
+ child: footer,
),
],
),
diff --git a/apps/lib/features/todo/data/todo_api.dart b/apps/lib/features/todo/data/todo_api.dart
index c4543f8..49e9ef9 100644
--- a/apps/lib/features/todo/data/todo_api.dart
+++ b/apps/lib/features/todo/data/todo_api.dart
@@ -59,6 +59,14 @@ class TodoApi {
return TodoResponse.fromJson(response.data);
}
+ Future updateTodoPriority(String id, int priority) async {
+ try {
+ await _client.patch('$_prefix/$id', data: {'priority': priority});
+ } catch (_) {
+ // Ignore response parsing errors, just need to know if request succeeded
+ }
+ }
+
Future completeTodo(String id) async {
final response = await _client.post('$_prefix/$id/complete', data: {});
return TodoResponse.fromJson(response.data);
diff --git a/apps/lib/features/todo/ui/screens/todo_edit_screen.dart b/apps/lib/features/todo/ui/screens/todo_edit_screen.dart
index 438efa1..5da20c3 100644
--- a/apps/lib/features/todo/ui/screens/todo_edit_screen.dart
+++ b/apps/lib/features/todo/ui/screens/todo_edit_screen.dart
@@ -12,6 +12,7 @@ import '../../../../shared/widgets/full_screen_loading.dart';
import '../../../../shared/widgets/toast/toast.dart';
import '../../../../shared/widgets/toast/toast_type.dart';
import '../../../calendar/data/calendar_api.dart';
+import '../../../calendar/data/models/schedule_item_model.dart';
import '../../data/todo_api.dart';
class TodoEditScreen extends StatefulWidget {
@@ -88,6 +89,7 @@ class _TodoEditScreenState extends State {
..clear()
..addAll(todo?.scheduleItems.map((item) => item.id) ?? const []);
_scheduleItems = scheduleItems
+ .where((item) => item.status == ScheduleStatus.active)
.map(
(item) => _ScheduleItemSimple(
id: item.id,
@@ -115,22 +117,29 @@ class _TodoEditScreenState extends State {
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppColors.todoBg,
+ resizeToAvoidBottomInset: false,
body: SafeArea(
- child: Container(
- decoration: const BoxDecoration(
- gradient: LinearGradient(
- begin: Alignment.topCenter,
- end: Alignment.bottomCenter,
- colors: [AppColors.homeBackgroundTop, AppColors.todoBg],
+ child: GestureDetector(
+ behavior: HitTestBehavior.translucent,
+ onTap: () => FocusScope.of(context).unfocus(),
+ child: Container(
+ decoration: const BoxDecoration(
+ gradient: LinearGradient(
+ begin: Alignment.topCenter,
+ end: Alignment.bottomCenter,
+ colors: [AppColors.homeBackgroundTop, AppColors.todoBg],
+ ),
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ BackTitlePageHeader(
+ title: widget.isCreateMode ? '新建待办' : '编辑待办',
+ ),
+ Expanded(child: _buildBody()),
+ _buildBottomAction(),
+ ],
),
- ),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- BackTitlePageHeader(title: widget.isCreateMode ? '新建待办' : '编辑待办'),
- Expanded(child: _buildBody()),
- _buildBottomAction(),
- ],
),
),
),
@@ -406,11 +415,6 @@ class _TodoEditScreenState extends State {
if (!mounted) {
return;
}
- Toast.show(
- context,
- widget.isCreateMode ? '待办已创建' : '待办已更新',
- type: ToastType.success,
- );
context.pop(true);
} catch (error) {
if (!mounted) {
diff --git a/apps/lib/features/todo/ui/screens/todo_quadrants_screen.dart b/apps/lib/features/todo/ui/screens/todo_quadrants_screen.dart
index 075af86..aaecf4a 100644
--- a/apps/lib/features/todo/ui/screens/todo_quadrants_screen.dart
+++ b/apps/lib/features/todo/ui/screens/todo_quadrants_screen.dart
@@ -15,6 +15,7 @@ import '../../../../shared/widgets/toast/toast_type.dart';
import '../../../calendar/ui/calendar_state_manager.dart';
import '../../../calendar/ui/widgets/bottom_dock.dart';
import '../../data/todo_api.dart';
+import '../widgets/todo_drag_item.dart';
class TodoQuadrantsScreen extends StatefulWidget {
const TodoQuadrantsScreen({super.key});
@@ -32,6 +33,78 @@ class _TodoQuadrantsScreenState extends State {
bool _loadingTodosRequest = false;
String? _error;
+ String? _draggingTodoId;
+ int? _dragTargetQuadrant;
+ int? _dragInsertIndex;
+
+ bool get _isDragging => _draggingTodoId != null;
+
+ void _onDragStart(String todoId) {
+ setState(() {
+ _draggingTodoId = todoId;
+ _dragTargetQuadrant = null;
+ _dragInsertIndex = null;
+ });
+ }
+
+ void _onDragEnd() {
+ setState(() {
+ _draggingTodoId = null;
+ _dragTargetQuadrant = null;
+ _dragInsertIndex = null;
+ });
+ }
+
+ void _onDragEnterQuadrant(int quadrant) {
+ setState(() {
+ _dragTargetQuadrant = quadrant;
+ });
+ }
+
+ void _onDragUpdateInsertIndex(int index) {
+ setState(() {
+ _dragInsertIndex = index;
+ });
+ }
+
+ Future _onDrop(
+ String todoId,
+ int targetQuadrant,
+ int insertIndex,
+ ) async {
+ final previousTodos = List.from(_todos);
+ try {
+ final todo = _todos.firstWhere((t) => t.id == todoId);
+ final sourceQuadrant = todo.priority;
+
+ if (sourceQuadrant == targetQuadrant) {
+ _onDragEnd();
+ return;
+ }
+
+ setState(() {
+ final index = _todos.indexWhere((t) => t.id == todoId);
+ if (index != -1) {
+ _todos[index] = _todos[index].copyWith(priority: targetQuadrant);
+ }
+ });
+
+ await _todoApi.updateTodoPriority(todoId, targetQuadrant);
+ } catch (e) {
+ if (!mounted) return;
+ setState(() {
+ _todos = previousTodos;
+ });
+ Toast.show(context, '移动失败', type: ToastType.error);
+ } finally {
+ if (mounted) _onDragEnd();
+ }
+ }
+
+ void _onDragLeave() {
+ // 清除高亮
+ }
+
@override
void initState() {
super.initState();
@@ -140,7 +213,7 @@ class _TodoQuadrantsScreenState extends State {
child: Column(
children: [
_buildHeader(),
- Expanded(child: _buildContent()),
+ Expanded(child: _buildContent(withScroll: true)),
_buildBottomDock(),
],
),
@@ -205,7 +278,7 @@ class _TodoQuadrantsScreenState extends State {
);
}
- Widget _buildContent() {
+ Widget _buildContent({bool withScroll = false}) {
if (_isLoading) {
return const FullScreenLoading();
}
@@ -214,58 +287,71 @@ class _TodoQuadrantsScreenState extends State {
return ErrorRetrySurface(message: '加载失败: $_error', onRetry: _loadTodos);
}
- return Stack(
+ Widget content = Column(
+ mainAxisSize: MainAxisSize.min,
children: [
- RefreshIndicator.noSpinner(
- onRefresh: _onPullRefresh,
- child: Padding(
- padding: const EdgeInsets.only(
- left: 16,
- right: 16,
- top: 4,
- bottom: 96,
- ),
- child: ListView(
- children: [
- _buildQuadrant(
- title: '重要紧急',
- textColor: AppColors.g1Text,
- dividerColor: AppColors.g1Divider,
- borderColor: AppColors.g1Border,
- items: _importantUrgent,
- onComplete: _completeTodo,
- onTap: _navigateToDetail,
- ),
- const SizedBox(height: 12),
- _buildQuadrant(
- title: '紧急不重要',
- textColor: AppColors.g2Text,
- dividerColor: AppColors.g2Divider,
- borderColor: AppColors.g2Border,
- items: _urgentNotImportant,
- onComplete: _completeTodo,
- onTap: _navigateToDetail,
- ),
- const SizedBox(height: 12),
- _buildQuadrant(
- title: '重要不紧急',
- textColor: AppColors.g3Text,
- dividerColor: AppColors.g3Divider,
- borderColor: AppColors.g3Border,
- items: _importantNotUrgent,
- onComplete: _completeTodo,
- onTap: _navigateToDetail,
- ),
- ],
- ),
- ),
+ _buildQuadrant(
+ title: '重要紧急',
+ textColor: AppColors.g1Text,
+ dividerColor: AppColors.g1Divider,
+ borderColor: AppColors.g1Border,
+ items: _importantUrgent,
+ quadrantValue: 1,
+ onComplete: _completeTodo,
+ onTap: _navigateToDetail,
),
- Align(
- alignment: Alignment.topCenter,
- child: AppPullRefreshFeedback(visible: _isPullRefreshing),
+ const SizedBox(height: 12),
+ _buildQuadrant(
+ title: '紧急不重要',
+ textColor: AppColors.g2Text,
+ dividerColor: AppColors.g2Divider,
+ borderColor: AppColors.g2Border,
+ items: _urgentNotImportant,
+ quadrantValue: 3,
+ onComplete: _completeTodo,
+ onTap: _navigateToDetail,
+ ),
+ const SizedBox(height: 12),
+ _buildQuadrant(
+ title: '重要不紧急',
+ textColor: AppColors.g3Text,
+ dividerColor: AppColors.g3Divider,
+ borderColor: AppColors.g3Border,
+ items: _importantNotUrgent,
+ quadrantValue: 2,
+ onComplete: _completeTodo,
+ onTap: _navigateToDetail,
),
],
);
+
+ if (withScroll) {
+ return Stack(
+ children: [
+ RefreshIndicator.noSpinner(
+ onRefresh: _onPullRefresh,
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.only(
+ left: 16,
+ right: 16,
+ top: 4,
+ bottom: 96,
+ ),
+ child: content,
+ ),
+ ),
+ Align(
+ alignment: Alignment.topCenter,
+ child: AppPullRefreshFeedback(visible: _isPullRefreshing),
+ ),
+ ],
+ );
+ }
+
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(16, 4, 16, 16),
+ child: content,
+ );
}
Widget _buildQuadrant({
@@ -274,73 +360,132 @@ class _TodoQuadrantsScreenState extends State {
required Color dividerColor,
required Color borderColor,
required List items,
+ required int quadrantValue,
required Future Function(TodoResponse) onComplete,
required void Function(TodoResponse) onTap,
}) {
return Container(
- width: double.infinity,
- padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: AppColors.todoCardBg,
borderRadius: BorderRadius.circular(14),
border: Border.all(color: borderColor, width: 1),
),
child: Column(
+ mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- Text(
- title,
- style: TextStyle(
- fontFamily: 'Inter',
- fontSize: 15,
- fontWeight: FontWeight.w700,
- color: textColor,
- ),
- ),
- Text(
- '${items.length}项',
- style: TextStyle(
- fontFamily: 'Inter',
- fontSize: 12,
- fontWeight: FontWeight.w700,
- color: textColor,
- ),
- ),
- ],
- ),
- const SizedBox(height: 8),
+ _buildQuadrantHeader(title, textColor, items.length),
Container(height: 1, color: dividerColor),
const SizedBox(height: 8),
- if (items.isEmpty)
- const Padding(
- padding: EdgeInsets.symmetric(vertical: 16),
- child: Center(
- child: Text(
- '暂无待办',
- style: TextStyle(
- fontFamily: 'Inter',
- fontSize: 13,
- color: AppColors.slate400,
+ Padding(
+ padding: const EdgeInsets.fromLTRB(6, 0, 6, 8),
+ child: DragTarget(
+ onWillAcceptWithDetails: (details) {
+ _onDragEnterQuadrant(quadrantValue);
+ return true;
+ },
+ onAcceptWithDetails: (details) {
+ final parts = details.data.split(':');
+ final todoId = parts[0];
+ _onDrop(todoId, quadrantValue, 0);
+ },
+ onLeave: (_) {
+ _onDragLeave();
+ },
+ builder: (context, candidateData, rejectedData) {
+ final isDragOver = candidateData.isNotEmpty;
+ return Container(
+ decoration: BoxDecoration(
+ color: isDragOver
+ ? AppColors.blue50.withValues(alpha: 0.3)
+ : Colors.transparent,
+ borderRadius: BorderRadius.circular(8),
+ border: isDragOver
+ ? Border.all(color: AppColors.blue400, width: 2)
+ : null,
),
- ),
- ),
- )
- else
- ...items.map(
- (item) => _TodoItemWidget(
- item: item,
- onComplete: () => onComplete(item),
- onTap: () => onTap(item),
- ),
+ child: items.isEmpty
+ ? SizedBox(
+ height: 60,
+ child: Center(
+ child: Text(
+ '暂无待办',
+ style: TextStyle(
+ fontFamily: 'Inter',
+ fontSize: 13,
+ color: AppColors.slate400,
+ ),
+ ),
+ ),
+ )
+ : _buildQuadrantItemList(
+ items,
+ quadrantValue,
+ onComplete,
+ onTap,
+ ),
+ );
+ },
),
+ ),
],
),
);
}
+ Widget _buildQuadrantHeader(String title, Color textColor, int itemCount) {
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(10, 10, 10, 8),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text(
+ title,
+ style: TextStyle(
+ fontFamily: 'Inter',
+ fontSize: 15,
+ fontWeight: FontWeight.w700,
+ color: textColor,
+ ),
+ ),
+ Text(
+ '${itemCount}项',
+ style: TextStyle(
+ fontFamily: 'Inter',
+ fontSize: 12,
+ fontWeight: FontWeight.w700,
+ color: textColor,
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ Widget _buildQuadrantItemList(
+ List items,
+ int quadrantValue,
+ Future Function(TodoResponse) onComplete,
+ void Function(TodoResponse) onTap,
+ ) {
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ children: items.map((item) {
+ return TodoDragItem(
+ todo: item,
+ quadrant: quadrantValue,
+ onDragStarted: () => _onDragStart(item.id),
+ onDragEnd: _onDragEnd,
+ child: _TodoItemWidget(
+ item: item,
+ onComplete: () => onComplete(item),
+ onTap: () => onTap(item),
+ ),
+ );
+ }).toList(),
+ );
+ }
+
Widget _buildBottomDock() {
return BottomDock(
activeTab: DockTab.todo,
diff --git a/apps/lib/features/todo/ui/widgets/todo_drag_item.dart b/apps/lib/features/todo/ui/widgets/todo_drag_item.dart
new file mode 100644
index 0000000..51c6391
--- /dev/null
+++ b/apps/lib/features/todo/ui/widgets/todo_drag_item.dart
@@ -0,0 +1,74 @@
+import 'package:flutter/material.dart';
+import 'package:social_app/core/theme/design_tokens.dart';
+import 'package:social_app/features/todo/data/todo_api.dart';
+
+class TodoDragItem extends StatelessWidget {
+ final TodoResponse todo;
+ final int quadrant;
+ final VoidCallback onDragStarted;
+ final VoidCallback onDragEnd;
+ final Widget child;
+
+ const TodoDragItem({
+ super.key,
+ required this.todo,
+ required this.quadrant,
+ required this.onDragStarted,
+ required this.onDragEnd,
+ required this.child,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ return LongPressDraggable(
+ data: '${todo.id}:$quadrant',
+ delay: const Duration(milliseconds: 150),
+ feedback: Material(
+ elevation: 8,
+ borderRadius: BorderRadius.circular(AppRadius.md),
+ child: Transform.scale(
+ scale: 1.03,
+ child: SizedBox(width: 280, child: _buildDragFeedback()),
+ ),
+ ),
+ childWhenDragging: AnimatedOpacity(
+ duration: const Duration(milliseconds: 100),
+ opacity: 0.3,
+ child: child,
+ ),
+ onDragStarted: onDragStarted,
+ onDragEnd: (_) => onDragEnd(),
+ child: child,
+ );
+ }
+
+ Widget _buildDragFeedback() {
+ return Container(
+ padding: const EdgeInsets.symmetric(
+ horizontal: AppSpacing.md,
+ vertical: AppSpacing.sm,
+ ),
+ decoration: BoxDecoration(
+ color: AppColors.white,
+ borderRadius: BorderRadius.circular(AppRadius.md),
+ boxShadow: [
+ BoxShadow(
+ color: AppColors.slate400.withValues(alpha: 0.3),
+ blurRadius: 12,
+ offset: const Offset(0, 4),
+ ),
+ ],
+ ),
+ child: Text(
+ todo.title,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(
+ fontSize: 13,
+ fontWeight: FontWeight.w600,
+ color: AppColors.slate700,
+ ),
+ ),
+ );
+ }
+}
diff --git a/apps/lib/main.dart b/apps/lib/main.dart
index cf23d3e..2636733 100644
--- a/apps/lib/main.dart
+++ b/apps/lib/main.dart
@@ -6,6 +6,7 @@ import 'package:flutter_bloc/flutter_bloc.dart';
import 'core/constants/app_constants.dart';
import 'core/di/injection.dart';
import 'core/notifications/local_notification_service.dart';
+import 'core/notifications/reminder_notification_callbacks.dart';
import 'core/router/app_router.dart';
import 'core/startup/auth_session_bootstrapper.dart';
import 'core/theme/app_theme.dart';
@@ -14,12 +15,18 @@ import 'features/auth/presentation/bloc/auth_event.dart';
import 'features/auth/presentation/bloc/auth_state.dart';
import 'features/calendar/data/services/calendar_service.dart';
import 'features/calendar/reminders/reminder_action_executor.dart';
+import 'features/calendar/reminders/ui/reminder_foreground_presenter.dart';
import 'features/chat/presentation/bloc/chat_bloc.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await configureDependencies();
await AppConstants.init();
+ final rootNavigatorKey = GlobalKey();
+ final reminderForegroundPresenter = ReminderForegroundPresenter(
+ navigatorKey: rootNavigatorKey,
+ executor: sl(),
+ );
sl().bindActionHandler(({
required action,
required payload,
@@ -29,6 +36,9 @@ void main() async {
payload: payload,
);
});
+ sl().bindInAppReminderHandler(
+ reminderForegroundPresenter.present,
+ );
await sl().initialize();
final authBloc = sl();
@@ -37,6 +47,7 @@ void main() async {
runApp(
LinksyApp(
authBloc: authBloc,
+ rootNavigatorKey: rootNavigatorKey,
sessionBootstrapper: AuthSessionBootstrapper(
calendarService: sl(),
notificationService: sl(),
@@ -44,15 +55,25 @@ void main() async {
),
),
);
+
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ unawaited(
+ ReminderNotificationCallbacks.bindResponseHandler(
+ sl().handleNotificationResponse,
+ ),
+ );
+ });
}
class LinksyApp extends StatelessWidget {
final AuthBloc authBloc;
+ final GlobalKey rootNavigatorKey;
final AuthSessionBootstrapper sessionBootstrapper;
const LinksyApp({
super.key,
required this.authBloc,
+ required this.rootNavigatorKey,
required this.sessionBootstrapper,
});
diff --git a/apps/lib/shared/widgets/app_selection_sheet.dart b/apps/lib/shared/widgets/app_selection_sheet.dart
new file mode 100644
index 0000000..429005c
--- /dev/null
+++ b/apps/lib/shared/widgets/app_selection_sheet.dart
@@ -0,0 +1,117 @@
+import 'package:flutter/material.dart';
+
+import '../../core/theme/design_tokens.dart';
+import 'app_button.dart';
+
+class AppSelectionItem {
+ const AppSelectionItem({required this.value, required this.label});
+
+ final T value;
+ final String label;
+}
+
+Future showAppSelectionSheet(
+ BuildContext context, {
+ required String title,
+ required List> items,
+ required T? selectedValue,
+}) async {
+ final result = await showModalBottomSheet(
+ context: context,
+ isScrollControlled: true,
+ backgroundColor: Colors.transparent,
+ builder: (sheetContext) {
+ return SafeArea(
+ top: false,
+ child: Container(
+ margin: const EdgeInsets.fromLTRB(
+ AppSpacing.md,
+ AppSpacing.none,
+ AppSpacing.md,
+ AppSpacing.md,
+ ),
+ padding: const EdgeInsets.symmetric(vertical: AppSpacing.lg),
+ decoration: BoxDecoration(
+ color: AppColors.white,
+ borderRadius: BorderRadius.circular(AppRadius.xl),
+ border: Border.all(color: AppColors.borderSecondary),
+ ),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg),
+ child: Text(
+ title,
+ textAlign: TextAlign.center,
+ style: const TextStyle(
+ fontSize: 17,
+ fontWeight: FontWeight.w700,
+ color: AppColors.slate900,
+ ),
+ ),
+ ),
+ const SizedBox(height: AppSpacing.md),
+ ...items.map((item) {
+ final isSelected = item.value == selectedValue;
+ return _buildItem(
+ sheetContext,
+ item: item,
+ isSelected: isSelected,
+ );
+ }),
+ const SizedBox(height: AppSpacing.sm),
+ const Divider(height: 1, color: AppColors.border),
+ const SizedBox(height: AppSpacing.sm),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg),
+ child: SizedBox(
+ height: 48,
+ child: AppButton(
+ text: '取消',
+ isOutlined: true,
+ onPressed: () => Navigator.of(sheetContext).pop(),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ },
+ );
+ return result;
+}
+
+Widget _buildItem(
+ BuildContext sheetContext, {
+ required AppSelectionItem item,
+ required bool isSelected,
+}) {
+ return InkWell(
+ onTap: () => Navigator.of(sheetContext).pop(item.value),
+ child: Container(
+ padding: const EdgeInsets.symmetric(
+ horizontal: AppSpacing.lg,
+ vertical: AppSpacing.md,
+ ),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ item.label,
+ style: TextStyle(
+ fontSize: 15,
+ fontWeight: isSelected ? FontWeight.w600 : FontWeight.w500,
+ color: isSelected ? AppColors.blue600 : AppColors.slate800,
+ ),
+ ),
+ ),
+ if (isSelected)
+ const Icon(Icons.check, size: 20, color: AppColors.blue600),
+ ],
+ ),
+ ),
+ );
+}
diff --git a/apps/lib/shared/widgets/detail_header_action_menu.dart b/apps/lib/shared/widgets/detail_header_action_menu.dart
index 0db7cf9..d37ddb6 100644
--- a/apps/lib/shared/widgets/detail_header_action_menu.dart
+++ b/apps/lib/shared/widgets/detail_header_action_menu.dart
@@ -8,12 +8,14 @@ class DetailHeaderActionItem {
required this.label,
required this.icon,
this.isDestructive = false,
+ this.enabled = true,
});
final T value;
final String label;
final IconData icon;
final bool isDestructive;
+ final bool enabled;
}
class DetailHeaderActionMenu extends StatefulWidget {
@@ -141,7 +143,7 @@ class _DetailHeaderActionMenuState extends State> {
Widget _buildMenuItem(DetailHeaderActionItem item) {
final textColor = item.isDestructive
? AppColors.red500
- : AppColors.slate700;
+ : (item.enabled ? AppColors.slate700 : AppColors.slate400);
final pressedColor = item.isDestructive
? AppColors.feedbackErrorSurface
: AppColors.surfaceInfoLight;
@@ -152,9 +154,9 @@ class _DetailHeaderActionMenuState extends State> {
color: Colors.transparent,
child: InkWell(
borderRadius: BorderRadius.circular(AppRadius.md),
- splashColor: pressedColor,
- highlightColor: pressedColor,
- onTap: () => _handleSelect(item.value),
+ splashColor: item.enabled ? pressedColor : Colors.transparent,
+ highlightColor: item.enabled ? pressedColor : Colors.transparent,
+ onTap: item.enabled ? () => _handleSelect(item.value) : null,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
child: Row(
diff --git a/apps/test/features/calendar/reminders/reminder_action_dedupe_store_test.dart b/apps/test/features/calendar/reminders/reminder_action_dedupe_store_test.dart
new file mode 100644
index 0000000..34af9a9
--- /dev/null
+++ b/apps/test/features/calendar/reminders/reminder_action_dedupe_store_test.dart
@@ -0,0 +1,78 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+import 'package:social_app/features/calendar/reminders/reminder_action_dedupe_store.dart';
+
+void main() {
+ const dedupeKey = 'calendar_reminder_action_dedupe_v1';
+
+ setUp(() {
+ SharedPreferences.setMockInitialValues({});
+ });
+
+ test('markIfNew returns true first and false for duplicate id', () async {
+ final prefs = await SharedPreferences.getInstance();
+ final store = ReminderActionDedupeStore(prefs);
+
+ expect(await store.markIfNew('action_1'), isTrue);
+ expect(await store.markIfNew('action_1'), isFalse);
+ });
+
+ test('markIfNew dedupes after store re-initialization', () async {
+ final firstPrefs = await SharedPreferences.getInstance();
+ final firstStore = ReminderActionDedupeStore(firstPrefs);
+
+ expect(await firstStore.markIfNew('action_restart'), isTrue);
+
+ final secondPrefs = await SharedPreferences.getInstance();
+ final secondStore = ReminderActionDedupeStore(secondPrefs);
+
+ expect(await secondStore.markIfNew('action_restart'), isFalse);
+ });
+
+ test('markIfNew trims history to max capacity', () async {
+ final prefs = await SharedPreferences.getInstance();
+ final store = ReminderActionDedupeStore(prefs);
+
+ for (var i = 0; i < 513; i++) {
+ expect(await store.markIfNew('action_$i'), isTrue);
+ }
+
+ final stored = prefs.getStringList(dedupeKey)!;
+ expect(stored.length, 512);
+ expect(stored.first, 'action_1');
+ expect(stored.last, 'action_512');
+ });
+
+ test(
+ 'markIfNew is serialized and does not return true twice in parallel',
+ () async {
+ final prefs = await SharedPreferences.getInstance();
+ final store = ReminderActionDedupeStore(
+ prefs,
+ setStringList: (key, value) async {
+ await Future.delayed(const Duration(milliseconds: 20));
+ return prefs.setStringList(key, value);
+ },
+ );
+
+ final results = await Future.wait([
+ store.markIfNew('parallel_action'),
+ store.markIfNew('parallel_action'),
+ ]);
+
+ expect(results.where((item) => item).length, 1);
+ expect(results.where((item) => !item).length, 1);
+ },
+ );
+
+ test('markIfNew returns false when persistence write fails', () async {
+ final prefs = await SharedPreferences.getInstance();
+ final store = ReminderActionDedupeStore(
+ prefs,
+ setStringList: (key, value) async => false,
+ );
+
+ expect(await store.markIfNew('action_write_fail'), isFalse);
+ expect(prefs.getStringList(dedupeKey), isNull);
+ });
+}
diff --git a/apps/test/features/calendar/reminders/reminder_action_executor_test.dart b/apps/test/features/calendar/reminders/reminder_action_executor_test.dart
index 248f50b..02a5a06 100644
--- a/apps/test/features/calendar/reminders/reminder_action_executor_test.dart
+++ b/apps/test/features/calendar/reminders/reminder_action_executor_test.dart
@@ -33,7 +33,7 @@ void main() {
);
});
- test('cancel archives remotely and cancels local reminder', () async {
+ test('archive archives remotely and cancels local reminder', () async {
when(
() => notificationService.cancelEventReminder('evt_1'),
).thenAnswer((_) async {});
@@ -42,7 +42,7 @@ void main() {
).thenAnswer((_) async => null);
await executor.handleAction(
- action: ReminderAction.cancel,
+ action: ReminderAction.archive,
payload: ReminderPayload(
eventId: 'evt_1',
title: 'sync',
@@ -66,7 +66,7 @@ void main() {
).thenThrow(Exception('offline'));
await executor.handleAction(
- action: ReminderAction.cancel,
+ action: ReminderAction.archive,
payload: ReminderPayload(
eventId: 'evt_1',
title: 'sync',
@@ -114,4 +114,60 @@ void main() {
).called(1);
verifyNever(() => calendarService.archiveEvent(any()));
});
+
+ test('fromValue throws on unknown action', () {
+ expect(
+ () => ReminderAction.fromValue('unknown_action'),
+ throwsA(isA()),
+ );
+ });
+
+ test(
+ 'aggregate action falls back to eventId when aggregateIds is empty',
+ () async {
+ when(
+ () => notificationService.cancelEventReminder('evt_fallback'),
+ ).thenAnswer((_) async {});
+ when(
+ () => calendarService.archiveEvent('evt_fallback'),
+ ).thenAnswer((_) async => null);
+
+ await executor.handleAction(
+ action: ReminderAction.archive,
+ payload: ReminderPayload(
+ eventId: 'evt_fallback',
+ title: 'sync',
+ startAt: DateTime.parse('2026-03-18T16:00:00+08:00'),
+ timezone: 'Asia/Shanghai',
+ mode: ReminderPayloadMode.aggregate,
+ aggregateIds: const [],
+ ),
+ );
+
+ verify(
+ () => notificationService.cancelEventReminder('evt_fallback'),
+ ).called(1);
+ verify(() => calendarService.archiveEvent('evt_fallback')).called(1);
+ },
+ );
+
+ test('replay keeps pending item when targetStatus is not archived', () async {
+ const opId = 'op_non_archived';
+ await outboxStore.enqueue(
+ ReminderOutboxItem(
+ opId: opId,
+ eventId: 'evt_1',
+ action: ReminderAction.archive,
+ targetStatus: 'ignored',
+ occurredAt: DateTime.parse('2026-03-18T16:00:00+08:00'),
+ ),
+ );
+
+ await executor.replayPendingActions();
+
+ final pending = await outboxStore.listPending();
+ expect(pending.length, 1);
+ expect(pending.first.opId, opId);
+ verifyNever(() => calendarService.archiveEvent(any()));
+ });
}
diff --git a/apps/test/features/calendar/reminders/reminder_action_sheet_test.dart b/apps/test/features/calendar/reminders/reminder_action_sheet_test.dart
new file mode 100644
index 0000000..9d2a284
--- /dev/null
+++ b/apps/test/features/calendar/reminders/reminder_action_sheet_test.dart
@@ -0,0 +1,41 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:social_app/features/calendar/reminders/ui/widgets/reminder_action_sheet.dart';
+
+void main() {
+ Future pumpSheet(
+ WidgetTester tester, {
+ required VoidCallback onSnooze,
+ required VoidCallback onArchive,
+ }) {
+ return tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: ReminderActionSheet(onSnooze: onSnooze, onArchive: onArchive),
+ ),
+ ),
+ );
+ }
+
+ testWidgets('tap snooze button triggers onSnooze', (tester) async {
+ var snoozed = false;
+
+ await pumpSheet(tester, onSnooze: () => snoozed = true, onArchive: () {});
+
+ await tester.tap(find.text('稍后提醒'));
+ await tester.pump();
+
+ expect(snoozed, isTrue);
+ });
+
+ testWidgets('tap archive button triggers onArchive', (tester) async {
+ var archived = false;
+
+ await pumpSheet(tester, onSnooze: () {}, onArchive: () => archived = true);
+
+ await tester.tap(find.text('归档'));
+ await tester.pump();
+
+ expect(archived, isTrue);
+ });
+}
diff --git a/apps/test/features/calendar/reminders/reminder_cold_start_queue_test.dart b/apps/test/features/calendar/reminders/reminder_cold_start_queue_test.dart
new file mode 100644
index 0000000..2019791
--- /dev/null
+++ b/apps/test/features/calendar/reminders/reminder_cold_start_queue_test.dart
@@ -0,0 +1,123 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:social_app/features/calendar/reminders/reminder_cold_start_queue.dart';
+
+void main() {
+ test('replays queued actions in enqueue order', () async {
+ final queue = ReminderColdStartQueue();
+ final events = [];
+
+ queue.enqueue(() async {
+ await Future.delayed(const Duration(milliseconds: 20));
+ events.add('first');
+ });
+ queue.enqueue(() async {
+ events.add('second');
+ });
+ queue.enqueue(() async {
+ events.add('third');
+ });
+
+ await queue.replay();
+
+ expect(events, ['first', 'second', 'third']);
+ });
+
+ test('single failure does not block following queued actions', () async {
+ final queue = ReminderColdStartQueue();
+ final events = [];
+ final errors =