refactor(apps): 主题系统迁移至 ColorScheme + 扩展架构并支持 Dark Mode

This commit is contained in:
qzl
2026-03-27 19:07:39 +08:00
parent ecc1ec6ce4
commit ae29a8209b
146 changed files with 4301 additions and 3200 deletions
@@ -0,0 +1,112 @@
import '../../core/network/i_api_client.dart';
import '../cache/cache_invalidator.dart';
import '../repositories/models/schedule_item_model.dart';
class CalendarService {
static const _prefix = '/api/v1/schedule-items';
final IApiClient _apiClient;
final CacheInvalidator _invalidator;
CalendarService({
required IApiClient apiClient,
required CacheInvalidator invalidator,
}) : _apiClient = apiClient,
_invalidator = invalidator;
Future<List<ScheduleItemModel>> getEventsForDay(DateTime date) async {
final start = DateTime(date.year, date.month, date.day);
final end = DateTime(date.year, date.month, date.day, 23, 59, 59);
return getEventsForRange(start, end);
}
Future<List<ScheduleItemModel>> getEventsForRange(
DateTime start,
DateTime end,
) async {
final startParam = Uri.encodeQueryComponent(
start.toUtc().toIso8601String(),
);
final endParam = Uri.encodeQueryComponent(end.toUtc().toIso8601String());
final response = await _apiClient.get<List<dynamic>>(
'$_prefix?start_at=$startParam&end_at=$endParam',
);
final data = response.data;
if (data == null) {
throw StateError('Invalid getEventsForRange response: empty payload');
}
return data
.map((item) => item as Map<String, dynamic>)
.map(ScheduleItemModel.fromJson)
.toList(growable: false);
}
Future<ScheduleItemModel> getEventById(String id) async {
final response = await _apiClient.get<Map<String, dynamic>>('$_prefix/$id');
final data = response.data;
if (data == null) {
throw StateError('Invalid getEventById response: empty payload');
}
return ScheduleItemModel.fromJson(data);
}
Future<ScheduleItemModel> addEvent(ScheduleItemModel event) async {
final response = await _apiClient.post<Map<String, dynamic>>(
_prefix,
data: event.toCreateJson(),
);
final data = response.data;
if (data == null) {
throw StateError('Invalid addEvent response: empty payload');
}
final created = ScheduleItemModel.fromJson(data);
_invalidateEventCache(created);
return created;
}
Future<ScheduleItemModel> updateEvent(ScheduleItemModel event) async {
final response = await _apiClient.patch<Map<String, dynamic>>(
'$_prefix/${event.id}',
data: event.toUpdateJson(),
);
final data = response.data;
if (data == null) {
throw StateError('Invalid updateEvent response: empty payload');
}
final updated = ScheduleItemModel.fromJson(data);
_invalidateEventCache(updated);
return updated;
}
Future<ScheduleItemModel> archiveEvent(String id) async {
final event = await getEventById(id);
final updatedEvent = await updateEvent(
event.copyWith(status: ScheduleStatus.archived),
);
_invalidateEventCache(updatedEvent);
return updatedEvent;
}
Future<void> deleteEvent(String id) async {
final event = await getEventById(id);
_invalidateEventCache(event);
await _apiClient.delete<void>('$_prefix/$id');
}
void _invalidateEventCache(ScheduleItemModel event) {
var current = DateTime(
event.startAt.year,
event.startAt.month,
event.startAt.day,
);
final end = DateTime(
event.endAt?.year ?? event.startAt.year,
event.endAt?.month ?? event.startAt.month,
event.endAt?.day ?? event.startAt.day,
);
while (!current.isAfter(end)) {
_invalidator.invalidateCalendarDay(current);
current = current.add(const Duration(days: 1));
}
}
}
@@ -0,0 +1,20 @@
import '../../core/storage/app_preferences.dart';
import '../models/reminder_payload.dart';
class IOSNotificationPayloadBridge {
final AppPreferences _prefs;
IOSNotificationPayloadBridge(this._prefs);
ReminderPayload? getPendingPayload() {
return _prefs.pendingNotificationPayload;
}
Future<void> setPendingPayload(ReminderPayload payload) {
return _prefs.setPendingNotificationPayload(payload);
}
Future<void> clearPendingPayload() {
return _prefs.clearPendingNotificationPayload();
}
}
@@ -0,0 +1,307 @@
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/data/latest.dart' as tz_data;
import 'package:timezone/timezone.dart' as tz;
import '../../core/l10n/l10n.dart';
import '../models/reminder_payload.dart';
import '../repositories/models/schedule_item_model.dart';
import 'reminder_notification_callbacks.dart';
class LocalNotificationService {
final FlutterLocalNotificationsPlugin _plugin;
bool _initialized = false;
LocalNotificationService({FlutterLocalNotificationsPlugin? plugin})
: _plugin = plugin ?? FlutterLocalNotificationsPlugin();
Future<void> initialize() async {
if (_initialized) {
return;
}
tz_data.initializeTimeZones();
const android = AndroidInitializationSettings('@mipmap/ic_launcher');
const ios = DarwinInitializationSettings(
requestAlertPermission: false,
requestBadgePermission: false,
requestSoundPermission: false,
);
final settings = InitializationSettings(android: android, iOS: ios);
await _plugin.initialize(
settings,
onDidReceiveNotificationResponse:
ReminderNotificationCallbacks.onForegroundResponse,
onDidReceiveBackgroundNotificationResponse:
reminderNotificationTapBackground,
);
final androidImpl = _plugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>();
await androidImpl?.requestNotificationsPermission();
await androidImpl?.requestExactAlarmsPermission();
await androidImpl?.requestFullScreenIntentPermission();
final iosImpl = _plugin
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin
>();
await iosImpl?.requestPermissions(alert: true, badge: true, sound: true);
_initialized = true;
}
Future<void> upsertEventReminder(ScheduleItemModel event) async {
await initialize();
if (event.status != ScheduleStatus.active ||
event.metadata?.reminderMinutes == null) {
await cancelEventReminder(event.id);
return;
}
final now = DateTime.now();
final reminderMinutes = event.metadata?.reminderMinutes ?? 0;
final fireAt = event.startAt.subtract(Duration(minutes: reminderMinutes));
if (fireAt.isBefore(now)) {
await cancelEventReminder(event.id);
return;
}
await cancelEventReminder(event.id);
await _scheduleRemindersFrom(event: event, firstFireAt: fireAt);
}
Future<void> scheduleReminderAt(
ScheduleItemModel event,
DateTime fireAt,
) async {
await initialize();
await cancelEventReminder(event.id);
await _scheduleRemindersFrom(event: event, firstFireAt: fireAt);
}
Future<void> cancelEventReminder(String eventId) async {
await initialize();
final pending = await _plugin.pendingNotificationRequests();
for (final request in pending) {
final payload = _decodePayload(request.payload);
if (payload == null) {
continue;
}
if (payload.eventId == eventId ||
payload.aggregateIds.contains(eventId)) {
await _plugin.cancel(request.id);
}
}
await _plugin.cancel(_notificationIdForEvent(eventId));
}
Future<void> rebuildUpcomingReminders(
Iterable<ScheduleItemModel> events,
) async {
await initialize();
for (final event in events) {
await upsertEventReminder(event);
}
}
int _notificationIdForEvent(String eventId) {
return eventId.hashCode & 0x7fffffff;
}
int _notificationIdForEventCycle(
String eventId,
DateTime fireAt,
ReminderPayloadMode mode,
) {
final cycleMinute =
fireAt.millisecondsSinceEpoch ~/
const Duration(minutes: 1).inMilliseconds;
return '$eventId|$cycleMinute|${mode.value}'.hashCode & 0x7fffffff;
}
Future<AndroidScheduleMode> _resolveAndroidScheduleMode() async {
final androidImpl = _plugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>();
if (androidImpl == null) {
return AndroidScheduleMode.exactAllowWhileIdle;
}
final canScheduleExact =
await androidImpl.canScheduleExactNotifications() ?? false;
return canScheduleExact
? AndroidScheduleMode.exactAllowWhileIdle
: AndroidScheduleMode.inexactAllowWhileIdle;
}
NotificationDetails _buildNotificationDetails(DateTime fireAt) {
return NotificationDetails(
android: AndroidNotificationDetails(
'calendar_alarm_channel_v2',
L10n.current.notificationChannelName,
channelDescription: L10n.current.notificationChannelDescription,
importance: Importance.max,
priority: Priority.max,
category: AndroidNotificationCategory.alarm,
audioAttributesUsage: AudioAttributesUsage.alarm,
fullScreenIntent: true,
playSound: true,
enableVibration: true,
vibrationPattern: Int64List.fromList([0, 1000, 500, 1200]),
timeoutAfter: 30000,
autoCancel: true,
groupKey: _getGroupKey(fireAt),
),
iOS: DarwinNotificationDetails(
presentAlert: true,
presentSound: true,
presentBadge: true,
threadIdentifier: _getThreadIdentifier(fireAt),
),
);
}
String _getThreadIdentifier(DateTime fireAt) {
final bucket =
fireAt.millisecondsSinceEpoch ~/
const Duration(minutes: 1).inMilliseconds;
return 'calendar_reminder_$bucket';
}
String _getGroupKey(DateTime fireAt) {
final bucket =
fireAt.millisecondsSinceEpoch ~/
const Duration(minutes: 1).inMilliseconds;
return 'com.socialapp.calendar.$bucket';
}
Future<void> _scheduleSingleReminder({
required ScheduleItemModel event,
required DateTime fireAt,
}) async {
final notificationId = _notificationIdForEventCycle(
event.id,
fireAt,
ReminderPayloadMode.single,
);
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,
);
final details = _buildNotificationDetails(fireAt);
final scheduledAt = tz.TZDateTime.from(fireAt, tz.local);
final mode = await _resolveAndroidScheduleMode();
try {
await _plugin.zonedSchedule(
notificationId,
event.title,
_buildReminderBody(event, event.metadata?.reminderMinutes ?? 0),
scheduledAt,
details,
payload: jsonEncode(payload.toJson()),
androidScheduleMode: mode,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
);
} catch (_) {
await _plugin.zonedSchedule(
notificationId,
event.title,
_buildReminderBody(event, event.metadata?.reminderMinutes ?? 0),
scheduledAt,
details,
payload: jsonEncode(payload.toJson()),
androidScheduleMode: AndroidScheduleMode.inexactAllowWhileIdle,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
);
}
}
Future<void> _scheduleRemindersFrom({
required ScheduleItemModel event,
required DateTime firstFireAt,
}) async {
final endAt = event.endAt;
var cursor = firstFireAt;
if (endAt == null) {
await _scheduleSingleReminder(event: event, fireAt: cursor);
return;
}
while (cursor.isBefore(endAt)) {
await _scheduleSingleReminder(event: event, fireAt: cursor);
cursor = cursor.add(const Duration(minutes: 10));
}
}
ReminderPayload? _decodePayload(String? raw) {
if (raw == null || raw.isEmpty) {
return null;
}
try {
return ReminderPayload.fromJson(jsonDecode(raw) as Map<String, dynamic>);
} catch (_) {
return null;
}
}
String _buildReminderBody(ScheduleItemModel event, int reminderMinutes) {
final when = reminderMinutes == 0
? L10n.current.notificationStartsNow
: L10n.current.notificationStartsInMinutes(reminderMinutes);
final location = event.metadata?.location;
final notes = event.metadata?.notes;
final buffer = StringBuffer(when);
if (location != null && location.isNotEmpty) {
buffer.write('\n${L10n.current.notificationLocation(location)}');
}
if (notes != null && notes.isNotEmpty) {
final preview = notes.length > 30
? '${notes.substring(0, 30)}...'
: notes;
buffer.write('\n${L10n.current.notificationNotes(preview)}');
}
return buffer.toString();
}
Future<void> handleNotificationResponse(NotificationResponse response) async {
final payloadRaw = response.payload;
if (payloadRaw == null || payloadRaw.isEmpty) {
return;
}
ReminderPayload payload;
try {
payload = ReminderPayload.fromJson(
Map<String, dynamic>.from(jsonDecode(payloadRaw) as Map),
);
} catch (_) {
debugPrint('failed to handle reminder notification response');
return;
}
ReminderNotificationCallbacks.onNotificationPayloadReceived?.call(payload);
}
}
@@ -0,0 +1,146 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../core/storage/app_preferences.dart';
import '../models/reminder_payload.dart';
typedef ReminderNotificationResponseHandler =
Future<void> Function(NotificationResponse response);
class ReminderNotificationCallbacks {
static ReminderNotificationResponseHandler? _responseHandler;
static Future<void> _pendingStorageLock = Future<void>.value();
static void Function(ReminderPayload)? onNotificationPayloadReceived;
static AppPreferences? _appPreferences;
static Future<AppPreferences> _resolvePrefs() async {
final prefs = _appPreferences;
if (prefs != null) {
return prefs;
}
final sharedPreferences = await SharedPreferences.getInstance();
final fallback = AppPreferences(sharedPreferences);
_appPreferences = fallback;
return fallback;
}
static void setAppPreferences(AppPreferences prefs) {
_appPreferences = prefs;
}
@visibleForTesting
static Future<void> resetForTest() async {
_responseHandler = null;
_pendingStorageLock = Future<void>.value();
final prefs = await _resolvePrefs();
await prefs.clearPendingNotifications();
}
static Future<void> bindResponseHandler(
ReminderNotificationResponseHandler handler,
) async {
_responseHandler = handler;
await _drainPendingResponses();
}
static Future<void> onForegroundResponse(
NotificationResponse response,
) async {
final handler = _responseHandler;
if (handler == null) {
await _enqueuePendingResponse(response);
return;
}
try {
await handler(response);
} catch (_) {
await _enqueuePendingResponse(response);
}
}
static Future<void> onBackgroundResponse(
NotificationResponse response,
) async {
final handler = _responseHandler;
if (handler == null) {
await _enqueuePendingResponse(response);
return;
}
try {
await handler(response);
} catch (_) {
await _enqueuePendingResponse(response);
}
}
static Future<T> _withPendingStorageLock<T>(Future<T> Function() operation) {
final completer = Completer<void>();
final waitForTurn = _pendingStorageLock;
_pendingStorageLock = waitForTurn.then((_) => completer.future);
return waitForTurn.then((_) => operation()).whenComplete(() {
if (!completer.isCompleted) {
completer.complete();
}
});
}
static Future<void> _enqueuePendingResponse(
NotificationResponse response,
) async {
final prefs = await _resolvePrefs();
await _withPendingStorageLock(() async {
final current = prefs.pendingNotifications;
await prefs.setPendingNotifications([
...current,
NotificationResponse(
id: response.id,
actionId: response.actionId,
payload: response.payload,
input: response.input,
notificationResponseType: response.notificationResponseType,
),
]);
});
}
static Future<void> _drainPendingResponses() async {
final handler = _responseHandler;
if (handler == null) {
return;
}
final prefs = await _resolvePrefs();
await _withPendingStorageLock(() async {
final pending = prefs.pendingNotifications;
if (pending.isEmpty) {
return;
}
final remaining = <NotificationResponse>[];
for (final response in pending) {
try {
await handler(response);
} catch (_) {
remaining.add(response);
}
}
if (remaining.isEmpty) {
await prefs.clearPendingNotifications();
return;
}
await prefs.setPendingNotifications(remaining);
});
}
}
@pragma('vm:entry-point')
Future<void> reminderNotificationTapBackground(
NotificationResponse response,
) async {
await ReminderNotificationCallbacks.onBackgroundResponse(response);
}