refactor(apps): 重构数据层目录结构并新增启动预热编排器
This commit is contained in:
+4
-4
@@ -1,7 +1,7 @@
|
||||
import 'package:social_app/core/network/i_api_client.dart';
|
||||
import 'models/signup_request.dart';
|
||||
import 'models/login_request.dart';
|
||||
import 'models/auth_response.dart';
|
||||
import 'package:social_app/data/network/i_api_client.dart';
|
||||
import '../models/signup_request.dart';
|
||||
import '../models/login_request.dart';
|
||||
import '../models/auth_response.dart';
|
||||
|
||||
class AuthApi {
|
||||
final IApiClient _client;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import 'package:social_app/features/auth/data/models/auth_response.dart';
|
||||
import '../models/auth_response.dart';
|
||||
|
||||
abstract class AuthRepository {
|
||||
Future<void> sendOtp(String phone);
|
||||
+5
-5
@@ -1,9 +1,9 @@
|
||||
import 'package:social_app/core/storage/token_storage.dart';
|
||||
import 'auth_api.dart';
|
||||
import 'package:social_app/data/storage/token_storage.dart';
|
||||
import '../apis/auth_api.dart';
|
||||
import 'auth_repository.dart';
|
||||
import 'models/signup_request.dart';
|
||||
import 'models/login_request.dart';
|
||||
import 'models/auth_response.dart';
|
||||
import '../models/signup_request.dart';
|
||||
import '../models/login_request.dart';
|
||||
import '../models/auth_response.dart';
|
||||
|
||||
class AuthRepositoryImpl implements AuthRepository {
|
||||
final AuthApi _api;
|
||||
@@ -1,5 +1,5 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../data/auth_repository.dart';
|
||||
import '../../data/repositories/auth_repository.dart';
|
||||
import 'auth_event.dart';
|
||||
import 'auth_state.dart';
|
||||
|
||||
|
||||
@@ -3,9 +3,9 @@ import 'dart:async';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:formz/formz.dart';
|
||||
import 'package:equatable/equatable.dart';
|
||||
import '../../../../core/network/api_exception.dart';
|
||||
import '../../../../data/network/api_exception.dart';
|
||||
import '../../../../core/l10n/l10n.dart';
|
||||
import '../../data/auth_repository.dart';
|
||||
import '../../data/repositories/auth_repository.dart';
|
||||
import '../../data/models/auth_response.dart';
|
||||
import '../../../../shared/forms/inputs.dart';
|
||||
|
||||
|
||||
@@ -1,18 +1,45 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
class AuthBootScreen extends StatelessWidget {
|
||||
import '../../../../app/di/injection.dart';
|
||||
import '../../../../app/services/app_prewarm_orchestrator.dart';
|
||||
import '../bloc/auth_bloc.dart';
|
||||
import '../bloc/auth_state.dart';
|
||||
|
||||
class AuthBootScreen extends StatefulWidget {
|
||||
const AuthBootScreen({super.key});
|
||||
|
||||
@override
|
||||
State<AuthBootScreen> createState() => _AuthBootScreenState();
|
||||
}
|
||||
|
||||
class _AuthBootScreenState extends State<AuthBootScreen> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_triggerPrewarmIfAuthenticated(context.read<AuthBloc>().state);
|
||||
}
|
||||
|
||||
void _triggerPrewarmIfAuthenticated(AuthState state) {
|
||||
if (state is! AuthAuthenticated) {
|
||||
return;
|
||||
}
|
||||
sl<AppPrewarmOrchestrator>().ensureStartedFor(state.user.id);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return Scaffold(
|
||||
backgroundColor: colorScheme.surface,
|
||||
body: SafeArea(
|
||||
child: Center(
|
||||
child: Image.asset(
|
||||
'assets/branding/assistant_octopus_foreground.png',
|
||||
width: 260,
|
||||
return BlocListener<AuthBloc, AuthState>(
|
||||
listener: (context, state) => _triggerPrewarmIfAuthenticated(state),
|
||||
child: Scaffold(
|
||||
backgroundColor: colorScheme.surface,
|
||||
body: SafeArea(
|
||||
child: Center(
|
||||
child: Image.asset(
|
||||
'assets/branding/assistant_octopus_foreground.png',
|
||||
width: 260,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -14,7 +14,7 @@ import '../../../../shared/widgets/confirm_sheet.dart';
|
||||
import '../../../../shared/widgets/link_button.dart';
|
||||
import '../../../../shared/widgets/phone_prefix_selector.dart';
|
||||
import '../../../../shared/widgets/toast/toast_type.dart';
|
||||
import '../../data/auth_repository.dart';
|
||||
import '../../data/repositories/auth_repository.dart';
|
||||
import '../../presentation/bloc/auth_bloc.dart';
|
||||
import '../../presentation/bloc/auth_event.dart';
|
||||
import '../../presentation/cubits/login_cubit.dart';
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
import 'package:social_app/core/network/i_api_client.dart';
|
||||
import 'package:social_app/data/repositories/models/schedule_item_model.dart';
|
||||
import 'package:social_app/data/network/i_api_client.dart';
|
||||
import 'package:social_app/features/calendar/data/models/schedule_item_model.dart';
|
||||
|
||||
class CalendarApi {
|
||||
final IApiClient _client;
|
||||
@@ -0,0 +1,287 @@
|
||||
enum ScheduleSourceType { manual, imported, agentGenerated }
|
||||
|
||||
enum ScheduleStatus { active, archived }
|
||||
|
||||
class ScheduleItemModel {
|
||||
final String id;
|
||||
final String ownerId;
|
||||
final int permission;
|
||||
final bool isOwner;
|
||||
final String title;
|
||||
final String? description;
|
||||
final DateTime startAt;
|
||||
final DateTime? endAt;
|
||||
final String timezone;
|
||||
final ScheduleMetadata? metadata;
|
||||
final ScheduleSourceType sourceType;
|
||||
final ScheduleStatus status;
|
||||
final DateTime createdAt;
|
||||
final DateTime updatedAt;
|
||||
|
||||
static const int permissionView = 1;
|
||||
static const int permissionInvite = 2;
|
||||
static const int permissionEdit = 4;
|
||||
|
||||
bool get canEdit => isOwner || (permission & permissionEdit) != 0;
|
||||
bool get canInvite => isOwner || (permission & permissionInvite) != 0;
|
||||
bool get canDelete => isOwner;
|
||||
|
||||
ScheduleItemModel({
|
||||
required this.id,
|
||||
required this.ownerId,
|
||||
this.permission = 1,
|
||||
this.isOwner = false,
|
||||
required this.title,
|
||||
this.description,
|
||||
required this.startAt,
|
||||
this.endAt,
|
||||
this.timezone = 'Asia/Shanghai',
|
||||
this.metadata,
|
||||
this.sourceType = ScheduleSourceType.manual,
|
||||
this.status = ScheduleStatus.active,
|
||||
DateTime? createdAt,
|
||||
DateTime? updatedAt,
|
||||
}) : createdAt = createdAt ?? DateTime.now(),
|
||||
updatedAt = updatedAt ?? DateTime.now();
|
||||
|
||||
ScheduleItemModel copyWith({
|
||||
String? id,
|
||||
String? ownerId,
|
||||
int? permission,
|
||||
bool? isOwner,
|
||||
String? title,
|
||||
String? description,
|
||||
DateTime? startAt,
|
||||
DateTime? endAt,
|
||||
String? timezone,
|
||||
ScheduleMetadata? metadata,
|
||||
ScheduleSourceType? sourceType,
|
||||
ScheduleStatus? status,
|
||||
DateTime? createdAt,
|
||||
DateTime? updatedAt,
|
||||
}) {
|
||||
return ScheduleItemModel(
|
||||
id: id ?? this.id,
|
||||
ownerId: ownerId ?? this.ownerId,
|
||||
permission: permission ?? this.permission,
|
||||
isOwner: isOwner ?? this.isOwner,
|
||||
title: title ?? this.title,
|
||||
description: description ?? this.description,
|
||||
startAt: startAt ?? this.startAt,
|
||||
endAt: endAt ?? this.endAt,
|
||||
timezone: timezone ?? this.timezone,
|
||||
metadata: metadata ?? this.metadata,
|
||||
sourceType: sourceType ?? this.sourceType,
|
||||
status: status ?? this.status,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
updatedAt: updatedAt ?? this.updatedAt,
|
||||
);
|
||||
}
|
||||
|
||||
factory ScheduleItemModel.fromJson(Map<String, dynamic> json) {
|
||||
return ScheduleItemModel(
|
||||
id: json['id'] as String,
|
||||
ownerId: json['owner_id'] as String,
|
||||
permission: json['permission'] as int,
|
||||
isOwner: json['is_owner'] as bool,
|
||||
title: json['title'] as String,
|
||||
description: json['description'] as String?,
|
||||
startAt: DateTime.parse(json['start_at'] as String).toLocal(),
|
||||
endAt: json['end_at'] != null
|
||||
? DateTime.parse(json['end_at'] as String).toLocal()
|
||||
: null,
|
||||
timezone: json['timezone'] as String,
|
||||
metadata: json['metadata'] is Map<String, dynamic>
|
||||
? ScheduleMetadata.fromJson(json['metadata'] as Map<String, dynamic>)
|
||||
: null,
|
||||
sourceType: _sourceTypeFromApi(json['source_type'] as String),
|
||||
status: _statusFromApi(json['status'] as String),
|
||||
createdAt: DateTime.parse(json['created_at'] as String).toLocal(),
|
||||
updatedAt: DateTime.parse(json['updated_at'] as String).toLocal(),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toCreateJson() {
|
||||
return {
|
||||
'title': title,
|
||||
'description': description,
|
||||
'start_at': startAt.toUtc().toIso8601String(),
|
||||
'end_at': endAt?.toUtc().toIso8601String(),
|
||||
'timezone': timezone,
|
||||
'metadata': metadata?.toJson(),
|
||||
};
|
||||
}
|
||||
|
||||
Map<String, dynamic> toUpdateJson() {
|
||||
return {
|
||||
'title': title,
|
||||
'description': description,
|
||||
'start_at': startAt.toUtc().toIso8601String(),
|
||||
'end_at': endAt?.toUtc().toIso8601String(),
|
||||
'timezone': timezone,
|
||||
'metadata': metadata?.toJson(),
|
||||
'status': _statusToApi(status),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class ScheduleMetadata {
|
||||
final String? color;
|
||||
final String? location;
|
||||
final String? notes;
|
||||
final int? reminderMinutes;
|
||||
final List<Attachment> attachments;
|
||||
final int version;
|
||||
final Map<String, dynamic> raw;
|
||||
|
||||
ScheduleMetadata({
|
||||
this.color,
|
||||
this.location,
|
||||
this.notes,
|
||||
this.reminderMinutes,
|
||||
List<Attachment>? attachments,
|
||||
this.version = 1,
|
||||
Map<String, dynamic>? raw,
|
||||
}) : attachments = attachments ?? const [],
|
||||
raw = raw ?? const {};
|
||||
|
||||
ScheduleMetadata copyWith({
|
||||
String? color,
|
||||
String? location,
|
||||
String? notes,
|
||||
int? reminderMinutes,
|
||||
List<Attachment>? attachments,
|
||||
int? version,
|
||||
Map<String, dynamic>? raw,
|
||||
}) {
|
||||
return ScheduleMetadata(
|
||||
color: color ?? this.color,
|
||||
location: location ?? this.location,
|
||||
notes: notes ?? this.notes,
|
||||
reminderMinutes: reminderMinutes ?? this.reminderMinutes,
|
||||
attachments: attachments ?? this.attachments,
|
||||
version: version ?? this.version,
|
||||
raw: raw ?? this.raw,
|
||||
);
|
||||
}
|
||||
|
||||
factory ScheduleMetadata.fromJson(Map<String, dynamic> json) {
|
||||
final rawAttachments = json['attachments'] as List<dynamic>;
|
||||
final attachments = rawAttachments
|
||||
.map((item) => Attachment.fromJson(item as Map<String, dynamic>))
|
||||
.toList(growable: false);
|
||||
return ScheduleMetadata(
|
||||
color: json['color'] as String?,
|
||||
location: json['location'] as String?,
|
||||
notes: json['notes'] as String?,
|
||||
reminderMinutes: json['reminder_minutes'] as int?,
|
||||
attachments: attachments,
|
||||
version: json['version'] as int,
|
||||
raw: Map<String, dynamic>.from(json),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'color': color,
|
||||
'location': location,
|
||||
'notes': notes,
|
||||
'reminder_minutes': reminderMinutes,
|
||||
'attachments': attachments.map((item) => item.toJson()).toList(),
|
||||
'version': version,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class Attachment {
|
||||
final String name;
|
||||
final List<String> visibleTo;
|
||||
final String? url;
|
||||
final String? note;
|
||||
final String? content;
|
||||
final String type;
|
||||
|
||||
Attachment({
|
||||
required this.name,
|
||||
this.visibleTo = const [],
|
||||
this.url,
|
||||
this.note,
|
||||
this.content,
|
||||
this.type = 'document',
|
||||
});
|
||||
|
||||
Attachment copyWith({
|
||||
String? name,
|
||||
List<String>? visibleTo,
|
||||
String? url,
|
||||
String? note,
|
||||
String? content,
|
||||
String? type,
|
||||
}) {
|
||||
return Attachment(
|
||||
name: name ?? this.name,
|
||||
visibleTo: visibleTo ?? this.visibleTo,
|
||||
url: url ?? this.url,
|
||||
note: note ?? this.note,
|
||||
content: content ?? this.content,
|
||||
type: type ?? this.type,
|
||||
);
|
||||
}
|
||||
|
||||
factory Attachment.fromJson(Map<String, dynamic> json) {
|
||||
final rawVisibleTo = json['visible_to'] as List<dynamic>;
|
||||
final visibleTo = rawVisibleTo.map((item) => item.toString()).toList();
|
||||
return Attachment(
|
||||
name: json['name'] as String,
|
||||
visibleTo: visibleTo,
|
||||
url: json['url'] as String?,
|
||||
note: json['note'] as String?,
|
||||
content: json['content'] as String?,
|
||||
type: json['type'] as String,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'name': name,
|
||||
'visible_to': visibleTo,
|
||||
'url': url,
|
||||
'note': note,
|
||||
'content': content,
|
||||
'type': type,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
ScheduleSourceType _sourceTypeFromApi(String raw) {
|
||||
switch (raw) {
|
||||
case 'imported':
|
||||
return ScheduleSourceType.imported;
|
||||
case 'agent_generated':
|
||||
return ScheduleSourceType.agentGenerated;
|
||||
case 'manual':
|
||||
return ScheduleSourceType.manual;
|
||||
default:
|
||||
throw StateError('Unsupported schedule source type: $raw');
|
||||
}
|
||||
}
|
||||
|
||||
ScheduleStatus _statusFromApi(String raw) {
|
||||
switch (raw) {
|
||||
case 'archived':
|
||||
return ScheduleStatus.archived;
|
||||
case 'active':
|
||||
return ScheduleStatus.active;
|
||||
default:
|
||||
throw StateError('Unsupported schedule status: $raw');
|
||||
}
|
||||
}
|
||||
|
||||
String _statusToApi(ScheduleStatus status) {
|
||||
switch (status) {
|
||||
case ScheduleStatus.active:
|
||||
return 'active';
|
||||
case ScheduleStatus.archived:
|
||||
return 'archived';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
import '../../../../data/cache/cache_policy.dart';
|
||||
import '../../../../data/cache/cached_repository.dart';
|
||||
import '../../../../data/network/i_api_client.dart';
|
||||
import '../models/schedule_item_model.dart';
|
||||
|
||||
class CalendarRepository extends CachedRepository<List<ScheduleItemModel>> {
|
||||
final IApiClient _apiClient;
|
||||
static const _prefix = '/api/v1/schedule-items';
|
||||
|
||||
CalendarRepository({
|
||||
required super.store,
|
||||
required IApiClient apiClient,
|
||||
CachePolicy? policy,
|
||||
super.now,
|
||||
}) : _apiClient = apiClient,
|
||||
super(
|
||||
policy:
|
||||
policy ??
|
||||
const CachePolicy(
|
||||
softTtl: Duration(minutes: 1),
|
||||
hardTtl: Duration(minutes: 10),
|
||||
minRefreshInterval: Duration(seconds: 30),
|
||||
),
|
||||
encodeValue: _encodeEventList,
|
||||
decodeValue: _decodeEventList,
|
||||
);
|
||||
|
||||
static String dayKey(DateTime date) {
|
||||
final day =
|
||||
'${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
|
||||
return 'calendar:day:$day';
|
||||
}
|
||||
|
||||
static String monthKey(DateTime date) {
|
||||
return 'calendar:month:${date.year}-${date.month.toString().padLeft(2, '0')}';
|
||||
}
|
||||
|
||||
Future<List<ScheduleItemModel>> getDayEvents(
|
||||
DateTime date, {
|
||||
bool forceRefresh = false,
|
||||
}) async {
|
||||
final key = dayKey(date);
|
||||
final start = DateTime(date.year, date.month, date.day);
|
||||
final end = DateTime(date.year, date.month, date.day, 23, 59, 59);
|
||||
return getOrLoad(
|
||||
key: key,
|
||||
forceRefresh: forceRefresh,
|
||||
loadFromRemote: () => _listByRange(startAt: start, endAt: end),
|
||||
);
|
||||
}
|
||||
|
||||
Future<List<ScheduleItemModel>> getMonthEvents(
|
||||
DateTime monthStart, {
|
||||
bool forceRefresh = false,
|
||||
}) async {
|
||||
final key = monthKey(monthStart);
|
||||
final start = DateTime(monthStart.year, monthStart.month, 1);
|
||||
final end = DateTime(monthStart.year, monthStart.month + 1, 0, 23, 59, 59);
|
||||
return getOrLoad(
|
||||
key: key,
|
||||
forceRefresh: forceRefresh,
|
||||
loadFromRemote: () => _listByRange(startAt: start, endAt: end),
|
||||
);
|
||||
}
|
||||
|
||||
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> getById(String id) {
|
||||
return getEventById(id);
|
||||
}
|
||||
|
||||
Future<List<ScheduleItemModel>> listEventsByRange({
|
||||
required DateTime start,
|
||||
required DateTime end,
|
||||
}) {
|
||||
return _listByRange(startAt: start, endAt: end);
|
||||
}
|
||||
|
||||
Future<List<ScheduleItemModel>> listByRange({
|
||||
required DateTime startAt,
|
||||
required DateTime endAt,
|
||||
}) {
|
||||
return _listByRange(startAt: startAt, endAt: endAt);
|
||||
}
|
||||
|
||||
Future<void> acceptSubscription(String itemId) {
|
||||
return _apiClient.post<void>('$_prefix/$itemId/accept');
|
||||
}
|
||||
|
||||
Future<void> rejectSubscription(String itemId) {
|
||||
return _apiClient.post<void>('$_prefix/$itemId/reject');
|
||||
}
|
||||
|
||||
Future<List<ScheduleItemModel>> _listByRange({
|
||||
required DateTime startAt,
|
||||
required DateTime endAt,
|
||||
}) async {
|
||||
final start = Uri.encodeQueryComponent(startAt.toUtc().toIso8601String());
|
||||
final end = Uri.encodeQueryComponent(endAt.toUtc().toIso8601String());
|
||||
final response = await _apiClient.get<List<dynamic>>(
|
||||
'$_prefix?start_at=$start&end_at=$end',
|
||||
);
|
||||
final data = response.data;
|
||||
if (data == null) {
|
||||
throw StateError('Invalid listByRange response: empty payload');
|
||||
}
|
||||
return data
|
||||
.whereType<Map<String, dynamic>>()
|
||||
.map(ScheduleItemModel.fromJson)
|
||||
.toList(growable: false);
|
||||
}
|
||||
|
||||
static Object? _encodeEventList(List<ScheduleItemModel> events) {
|
||||
return events.map(_encodeEvent).toList(growable: false);
|
||||
}
|
||||
|
||||
static List<ScheduleItemModel> _decodeEventList(Object? raw) {
|
||||
if (raw is! List) {
|
||||
throw const FormatException('Invalid cached calendar event list payload');
|
||||
}
|
||||
return raw
|
||||
.whereType<Map>()
|
||||
.map(
|
||||
(item) => ScheduleItemModel.fromJson(Map<String, dynamic>.from(item)),
|
||||
)
|
||||
.toList(growable: false);
|
||||
}
|
||||
|
||||
static Map<String, Object?> _encodeEvent(ScheduleItemModel item) {
|
||||
return <String, Object?>{
|
||||
'id': item.id,
|
||||
'owner_id': item.ownerId,
|
||||
'permission': item.permission,
|
||||
'is_owner': item.isOwner,
|
||||
'title': item.title,
|
||||
'description': item.description,
|
||||
'start_at': item.startAt.toIso8601String(),
|
||||
'end_at': item.endAt?.toIso8601String(),
|
||||
'timezone': item.timezone,
|
||||
'metadata': item.metadata?.toJson(),
|
||||
'source_type': _sourceTypeToApi(item.sourceType),
|
||||
'status': _statusToApi(item.status),
|
||||
'created_at': item.createdAt.toIso8601String(),
|
||||
'updated_at': item.updatedAt.toIso8601String(),
|
||||
};
|
||||
}
|
||||
|
||||
static String _sourceTypeToApi(ScheduleSourceType sourceType) {
|
||||
switch (sourceType) {
|
||||
case ScheduleSourceType.manual:
|
||||
return 'manual';
|
||||
case ScheduleSourceType.imported:
|
||||
return 'imported';
|
||||
case ScheduleSourceType.agentGenerated:
|
||||
return 'agent_generated';
|
||||
}
|
||||
}
|
||||
|
||||
static String _statusToApi(ScheduleStatus status) {
|
||||
switch (status) {
|
||||
case ScheduleStatus.active:
|
||||
return 'active';
|
||||
case ScheduleStatus.archived:
|
||||
return 'archived';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import '../../../../data/network/i_api_client.dart';
|
||||
import '../../../../data/cache/cache_store.dart';
|
||||
import '../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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import '../../../../data/repositories/models/schedule_item_model.dart';
|
||||
import '../../../../features/calendar/data/models/schedule_item_model.dart';
|
||||
import 'day_timeline_metrics.dart';
|
||||
import 'day_view_scale.dart';
|
||||
|
||||
|
||||
@@ -7,11 +7,11 @@ import '../../../../app/router/home_return_policy.dart';
|
||||
import '../../../../app/di/injection.dart';
|
||||
import '../../../../core/l10n/l10n.dart';
|
||||
import '../../../../core/theme/design_tokens.dart';
|
||||
import '../../../../data/repositories/calendar_repository.dart';
|
||||
import '../../../../features/calendar/data/repositories/calendar_repository.dart';
|
||||
import '../../../../shared/widgets/app_pressable.dart';
|
||||
import '../../../../shared/widgets/bottom_dock.dart';
|
||||
import '../../../../shared/state/calendar_state_manager.dart';
|
||||
import '../../../../data/repositories/models/schedule_item_model.dart';
|
||||
import '../../../../features/calendar/data/models/schedule_item_model.dart';
|
||||
import '../calendar_time_utils.dart';
|
||||
import '../utils/event_color_resolver.dart';
|
||||
import '../dayweek/day_event_layout_engine.dart';
|
||||
|
||||
@@ -4,7 +4,6 @@ import 'package:go_router/go_router.dart';
|
||||
import 'package:social_app/core/l10n/l10n.dart';
|
||||
import '../../../../app/di/injection.dart';
|
||||
import '../../../../app/router/app_routes.dart';
|
||||
import '../../../../data/services/local_notification_service.dart';
|
||||
import '../../../../core/theme/design_tokens.dart';
|
||||
import '../../../../shared/widgets/app_loading_indicator.dart';
|
||||
import '../../../../shared/widgets/back_title_page_header.dart';
|
||||
@@ -12,8 +11,8 @@ 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/repositories/models/schedule_item_model.dart';
|
||||
import '../../../../features/calendar/data/services/calendar_service.dart';
|
||||
import '../../../../features/calendar/data/models/schedule_item_model.dart';
|
||||
import '../utils/event_color_resolver.dart';
|
||||
|
||||
enum _CalendarHeaderAction { edit, delete, share, archive }
|
||||
@@ -505,9 +504,6 @@ class _CalendarEventDetailScreenState extends State<CalendarEventDetailScreen> {
|
||||
return;
|
||||
}
|
||||
await sl<CalendarService>().deleteEvent(widget.eventId);
|
||||
try {
|
||||
await sl<LocalNotificationService>().cancelEventReminder(widget.eventId);
|
||||
} catch (_) {}
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -4,8 +4,8 @@ import '../../../../app/di/injection.dart';
|
||||
import '../../../../core/l10n/l10n.dart';
|
||||
import '../../../../shared/widgets/app_loading_indicator.dart';
|
||||
import '../widgets/create_event_sheet.dart';
|
||||
import '../../../../data/repositories/models/schedule_item_model.dart';
|
||||
import '../../../../data/services/calendar_service.dart';
|
||||
import '../../../../features/calendar/data/models/schedule_item_model.dart';
|
||||
import '../../../../features/calendar/data/services/calendar_service.dart';
|
||||
|
||||
class CalendarEventEditScreen extends StatefulWidget {
|
||||
final String eventId;
|
||||
|
||||
@@ -4,8 +4,8 @@ import '../../../../app/di/injection.dart';
|
||||
import '../../../../core/l10n/l10n.dart';
|
||||
import '../../../../shared/widgets/app_loading_indicator.dart';
|
||||
import '../../../../shared/widgets/back_title_page_header.dart';
|
||||
import '../../../../data/repositories/models/schedule_item_model.dart';
|
||||
import '../../../../data/services/calendar_service.dart';
|
||||
import '../../../../features/calendar/data/models/schedule_item_model.dart';
|
||||
import '../../../../features/calendar/data/services/calendar_service.dart';
|
||||
import '../widgets/calendar_share_dialog.dart';
|
||||
|
||||
class CalendarEventShareScreen extends StatefulWidget {
|
||||
|
||||
@@ -6,14 +6,14 @@ import 'package:social_app/core/l10n/l10n.dart';
|
||||
import '../../../../app/di/injection.dart';
|
||||
import '../../../../app/router/app_routes.dart';
|
||||
import '../../../../core/theme/design_tokens.dart';
|
||||
import '../../../../data/repositories/calendar_repository.dart';
|
||||
import '../../../../features/calendar/data/repositories/calendar_repository.dart';
|
||||
import '../../../../shared/widgets/app_pressable.dart';
|
||||
import '../../../../shared/widgets/bottom_dock.dart';
|
||||
import '../../../../shared/state/calendar_state_manager.dart';
|
||||
import '../../../../app/router/home_return_policy.dart';
|
||||
import '../calendar_time_utils.dart';
|
||||
import '../utils/event_color_resolver.dart';
|
||||
import '../../../../data/repositories/models/schedule_item_model.dart';
|
||||
import '../../../../features/calendar/data/models/schedule_item_model.dart';
|
||||
|
||||
class CalendarMonthScreen extends StatefulWidget {
|
||||
final bool resetToToday;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../../data/repositories/models/schedule_item_model.dart';
|
||||
import '../../../../features/calendar/data/models/schedule_item_model.dart';
|
||||
|
||||
Color resolveEventColor({
|
||||
required ScheduleStatus status,
|
||||
|
||||
@@ -6,7 +6,7 @@ import '../../../../core/theme/design_tokens.dart';
|
||||
import '../../../../shared/widgets/app_button.dart';
|
||||
import '../../../../shared/widgets/toast/toast.dart';
|
||||
import '../../../../shared/widgets/toast/toast_type.dart';
|
||||
import '../../data/calendar_api.dart';
|
||||
import '../../data/apis/calendar_api.dart';
|
||||
|
||||
class CalendarShareDialog extends StatefulWidget {
|
||||
final String eventId;
|
||||
|
||||
@@ -2,7 +2,6 @@ import 'package:flutter/material.dart';
|
||||
import 'package:lucide_icons/lucide_icons.dart';
|
||||
import 'package:social_app/core/l10n/l10n.dart';
|
||||
import '../../../../app/di/injection.dart';
|
||||
import '../../../../data/services/local_notification_service.dart';
|
||||
import '../../../../core/theme/design_tokens.dart';
|
||||
import '../../../../shared/widgets/app_loading_indicator.dart';
|
||||
import '../../../../shared/widgets/app_selection_sheet.dart';
|
||||
@@ -11,8 +10,8 @@ import '../../../../shared/widgets/back_title_page_header.dart';
|
||||
import '../../../../shared/widgets/toast/toast.dart';
|
||||
import '../../../../shared/widgets/toast/toast_type.dart';
|
||||
import 'date_time_picker_sheet.dart';
|
||||
import '../../../../data/repositories/models/schedule_item_model.dart';
|
||||
import '../../../../data/services/calendar_service.dart';
|
||||
import '../../../../features/calendar/data/models/schedule_item_model.dart';
|
||||
import '../../../../features/calendar/data/services/calendar_service.dart';
|
||||
|
||||
final _defaultColors = AppColorPalette.light.eventPresetColors;
|
||||
|
||||
@@ -786,25 +785,11 @@ class _CreateEventSheetState extends State<CreateEventSheet>
|
||||
|
||||
try {
|
||||
final service = sl<CalendarService>();
|
||||
late final ScheduleItemModel saved;
|
||||
|
||||
if (_isEditing) {
|
||||
saved = await service.updateEvent(event);
|
||||
await service.updateEvent(event);
|
||||
} else {
|
||||
saved = await service.addEvent(event);
|
||||
}
|
||||
|
||||
try {
|
||||
final notificationService = sl<LocalNotificationService>();
|
||||
await notificationService.upsertEventReminder(saved);
|
||||
} catch (_) {
|
||||
if (mounted) {
|
||||
Toast.show(
|
||||
context,
|
||||
context.l10n.calendarCreateReminderPermissionFailed,
|
||||
type: ToastType.warning,
|
||||
);
|
||||
}
|
||||
await service.addEvent(event);
|
||||
}
|
||||
|
||||
widget.onSaved?.call();
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import 'package:social_app/data/network/i_api_client.dart';
|
||||
import 'package:social_app/data/cache/cache_policy.dart';
|
||||
import 'package:social_app/data/cache/cached_repository.dart';
|
||||
|
||||
import '../models/ag_ui_event.dart';
|
||||
|
||||
class ChatHistoryRepository extends CachedRepository<HistorySnapshot> {
|
||||
ChatHistoryRepository({required IApiClient apiClient, required super.store})
|
||||
: _apiClient = apiClient,
|
||||
super(
|
||||
policy: const CachePolicy(
|
||||
softTtl: Duration(seconds: 30),
|
||||
hardTtl: Duration(minutes: 5),
|
||||
minRefreshInterval: Duration(seconds: 15),
|
||||
),
|
||||
encodeValue: _encodeSnapshot,
|
||||
decodeValue: _decodeSnapshot,
|
||||
);
|
||||
|
||||
final IApiClient _apiClient;
|
||||
|
||||
Future<HistorySnapshot> loadHistory({
|
||||
String? threadId,
|
||||
DateTime? beforeDate,
|
||||
bool forceRefresh = false,
|
||||
}) {
|
||||
final key = _keyFor(threadId: threadId, beforeDate: beforeDate);
|
||||
return getOrLoad(
|
||||
key: key,
|
||||
forceRefresh: forceRefresh,
|
||||
loadFromRemote: () =>
|
||||
_loadHistoryRemote(threadId: threadId, beforeDate: beforeDate),
|
||||
);
|
||||
}
|
||||
|
||||
Future<HistorySnapshot> _loadHistoryRemote({
|
||||
String? threadId,
|
||||
DateTime? beforeDate,
|
||||
}) async {
|
||||
final path = _buildHistoryPath(threadId: threadId, beforeDate: beforeDate);
|
||||
final response = await _apiClient.get<Map<String, dynamic>>(path);
|
||||
final payload = response.data;
|
||||
if (payload is! Map<String, dynamic>) {
|
||||
throw StateError('Invalid /agent/history response');
|
||||
}
|
||||
return HistorySnapshot.fromJson(payload);
|
||||
}
|
||||
|
||||
static String _buildHistoryPath({String? threadId, DateTime? beforeDate}) {
|
||||
final query = <String>[];
|
||||
if (threadId != null && threadId.isNotEmpty) {
|
||||
query.add('threadId=$threadId');
|
||||
}
|
||||
if (beforeDate != null) {
|
||||
final day = DateTime(beforeDate.year, beforeDate.month, beforeDate.day);
|
||||
query.add('before=${day.toIso8601String().substring(0, 10)}');
|
||||
}
|
||||
if (query.isEmpty) {
|
||||
return '/api/v1/agent/history';
|
||||
}
|
||||
return '/api/v1/agent/history?${query.join('&')}';
|
||||
}
|
||||
|
||||
static String _keyFor({String? threadId, DateTime? beforeDate}) {
|
||||
final threadPart = (threadId == null || threadId.isEmpty)
|
||||
? 'default'
|
||||
: threadId;
|
||||
if (beforeDate == null) {
|
||||
return 'chat:history:first:$threadPart';
|
||||
}
|
||||
final day = DateTime(
|
||||
beforeDate.year,
|
||||
beforeDate.month,
|
||||
beforeDate.day,
|
||||
).toIso8601String().substring(0, 10);
|
||||
return 'chat:history:before:$threadPart:$day';
|
||||
}
|
||||
|
||||
static Object? _encodeSnapshot(HistorySnapshot snapshot) {
|
||||
return <String, Object?>{
|
||||
'scope': snapshot.scope,
|
||||
'threadId': snapshot.threadId,
|
||||
'day': snapshot.day,
|
||||
'hasMore': snapshot.hasMore,
|
||||
'messages': snapshot.messages.map(_encodeMessage).toList(growable: false),
|
||||
};
|
||||
}
|
||||
|
||||
static HistorySnapshot _decodeSnapshot(Object? raw) {
|
||||
if (raw is! Map) {
|
||||
throw const FormatException('Invalid cached history snapshot payload');
|
||||
}
|
||||
return HistorySnapshot.fromJson(Map<String, dynamic>.from(raw));
|
||||
}
|
||||
|
||||
static Map<String, Object?> _encodeMessage(HistoryMessage message) {
|
||||
return <String, Object?>{
|
||||
'id': message.id,
|
||||
'seq': message.seq,
|
||||
'role': message.role,
|
||||
'content': message.content,
|
||||
'timestamp': message.timestamp.toIso8601String(),
|
||||
'attachments': message.attachments
|
||||
.map(
|
||||
(attachment) => <String, Object?>{
|
||||
'url': attachment.url,
|
||||
'mimeType': attachment.mimeType,
|
||||
},
|
||||
)
|
||||
.toList(growable: false),
|
||||
'ui_schema': message.uiSchema,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -5,9 +5,10 @@ import 'dart:typed_data';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:image_picker/image_picker.dart';
|
||||
import 'package:social_app/core/network/i_api_client.dart';
|
||||
import 'package:social_app/data/network/i_api_client.dart';
|
||||
|
||||
import '../models/ag_ui_event.dart';
|
||||
import '../repositories/chat_history_repository.dart';
|
||||
|
||||
typedef EventCallback = void Function(AgUiEvent event);
|
||||
|
||||
@@ -43,6 +44,7 @@ class _RunInputPayload {
|
||||
|
||||
class AgUiService {
|
||||
final IApiClient _apiClient;
|
||||
final ChatHistoryRepository? _historyRepository;
|
||||
EventCallback onEvent;
|
||||
final Map<String, String> _lastEventIdByThread = {};
|
||||
int _activeStreamToken = 0;
|
||||
@@ -54,9 +56,13 @@ class AgUiService {
|
||||
String? _activeRunId;
|
||||
bool _hasMoreHistory = false;
|
||||
|
||||
AgUiService({EventCallback? onEvent, required IApiClient apiClient})
|
||||
: onEvent = onEvent ?? ((_) {}),
|
||||
_apiClient = apiClient;
|
||||
AgUiService({
|
||||
EventCallback? onEvent,
|
||||
required IApiClient apiClient,
|
||||
ChatHistoryRepository? historyRepository,
|
||||
}) : onEvent = onEvent ?? ((_) {}),
|
||||
_apiClient = apiClient,
|
||||
_historyRepository = historyRepository;
|
||||
|
||||
Future<SendMessageResult> sendMessage(
|
||||
String content, {
|
||||
@@ -105,18 +111,28 @@ class AgUiService {
|
||||
}
|
||||
|
||||
Future<HistorySnapshot> loadHistory({DateTime? beforeDate}) async {
|
||||
final repository = _historyRepository;
|
||||
final snapshot = repository != null
|
||||
? await repository.loadHistory(
|
||||
threadId: _threadId,
|
||||
beforeDate: beforeDate,
|
||||
)
|
||||
: await _loadHistoryFromApi(beforeDate: beforeDate);
|
||||
if (snapshot.threadId != null && snapshot.threadId!.isNotEmpty) {
|
||||
_threadId = snapshot.threadId;
|
||||
}
|
||||
_hasMoreHistory = snapshot.hasMore;
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
Future<HistorySnapshot> _loadHistoryFromApi({DateTime? beforeDate}) async {
|
||||
final path = _buildHistoryPath(beforeDate: beforeDate);
|
||||
final response = await _apiClient.get<Map<String, dynamic>>(path);
|
||||
final payload = response.data;
|
||||
if (payload is! Map<String, dynamic>) {
|
||||
throw StateError('Invalid /agent/history response');
|
||||
}
|
||||
final snapshot = HistorySnapshot.fromJson(payload);
|
||||
if (snapshot.threadId != null && snapshot.threadId!.isNotEmpty) {
|
||||
_threadId = snapshot.threadId;
|
||||
}
|
||||
_hasMoreHistory = snapshot.hasMore;
|
||||
return snapshot;
|
||||
return HistorySnapshot.fromJson(payload);
|
||||
}
|
||||
|
||||
Future<Uint8List> fetchAttachmentPreview(String previewPath) async {
|
||||
|
||||
@@ -5,10 +5,11 @@ import 'package:image_picker/image_picker.dart';
|
||||
import 'package:social_app/core/chat/agent_stage.dart';
|
||||
import 'package:social_app/core/chat/chat_list_item.dart';
|
||||
import 'package:social_app/core/chat/chat_orchestrator.dart';
|
||||
import 'package:social_app/core/network/i_api_client.dart';
|
||||
import 'package:social_app/data/network/i_api_client.dart';
|
||||
import 'package:social_app/core/l10n/l10n.dart';
|
||||
|
||||
import '../../data/models/ag_ui_event.dart';
|
||||
import '../../data/repositories/chat_history_repository.dart';
|
||||
import '../../data/services/ag_ui_service.dart';
|
||||
|
||||
class ChatState implements ChatOrchestratorState {
|
||||
@@ -95,9 +96,17 @@ class ChatState implements ChatOrchestratorState {
|
||||
}
|
||||
|
||||
class ChatBloc extends Cubit<ChatState> implements ChatOrchestrator {
|
||||
ChatBloc({AgUiService? service, required IApiClient apiClient})
|
||||
: _service = service ?? AgUiService(apiClient: apiClient),
|
||||
super(const ChatState()) {
|
||||
ChatBloc({
|
||||
AgUiService? service,
|
||||
required IApiClient apiClient,
|
||||
ChatHistoryRepository? historyRepository,
|
||||
}) : _service =
|
||||
service ??
|
||||
AgUiService(
|
||||
apiClient: apiClient,
|
||||
historyRepository: historyRepository,
|
||||
),
|
||||
super(const ChatState()) {
|
||||
_service.onEvent = _handleEvent;
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import 'package:social_app/core/network/i_api_client.dart';
|
||||
import 'package:social_app/data/network/i_api_client.dart';
|
||||
|
||||
class FriendsApi {
|
||||
final IApiClient _client;
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
import 'dart:io';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:social_app/core/network/i_api_client.dart';
|
||||
import 'package:social_app/data/models/user_profile.dart';
|
||||
import 'package:social_app/data/network/i_api_client.dart';
|
||||
import '../models/user_profile.dart';
|
||||
|
||||
class UserBasicInfo {
|
||||
final String id;
|
||||
@@ -0,0 +1,63 @@
|
||||
enum FriendRequestStatus { pending, accepted, rejected }
|
||||
|
||||
class FriendUser {
|
||||
final String id;
|
||||
final String username;
|
||||
final String? avatarUrl;
|
||||
|
||||
const FriendUser({
|
||||
required this.id,
|
||||
required this.username,
|
||||
required this.avatarUrl,
|
||||
});
|
||||
|
||||
factory FriendUser.fromJson(Map<String, dynamic> json) {
|
||||
return FriendUser(
|
||||
id: json['id'] as String,
|
||||
username: json['username'] as String,
|
||||
avatarUrl: json['avatar_url'] as String?,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class FriendRequest {
|
||||
final String id;
|
||||
final FriendUser sender;
|
||||
final FriendUser recipient;
|
||||
final String? content;
|
||||
final FriendRequestStatus status;
|
||||
final DateTime createdAt;
|
||||
|
||||
const FriendRequest({
|
||||
required this.id,
|
||||
required this.sender,
|
||||
required this.recipient,
|
||||
required this.content,
|
||||
required this.status,
|
||||
required this.createdAt,
|
||||
});
|
||||
|
||||
factory FriendRequest.fromJson(Map<String, dynamic> json) {
|
||||
return FriendRequest(
|
||||
id: json['id'] as String,
|
||||
sender: FriendUser.fromJson(json['sender'] as Map<String, dynamic>),
|
||||
recipient: FriendUser.fromJson(json['recipient'] as Map<String, dynamic>),
|
||||
content: json['content'] as String?,
|
||||
status: _friendRequestStatusFromApi(json['status'] as String),
|
||||
createdAt: DateTime.parse(json['created_at'] as String),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
FriendRequestStatus _friendRequestStatusFromApi(String raw) {
|
||||
switch (raw) {
|
||||
case 'pending':
|
||||
return FriendRequestStatus.pending;
|
||||
case 'accepted':
|
||||
return FriendRequestStatus.accepted;
|
||||
case 'rejected':
|
||||
return FriendRequestStatus.rejected;
|
||||
default:
|
||||
throw StateError('Unsupported friend request status: $raw');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
class UserProfile {
|
||||
final String id;
|
||||
final String username;
|
||||
final String? phone;
|
||||
final String? avatarUrl;
|
||||
final String? bio;
|
||||
|
||||
const UserProfile({
|
||||
required this.id,
|
||||
required this.username,
|
||||
this.phone,
|
||||
this.avatarUrl,
|
||||
this.bio,
|
||||
});
|
||||
|
||||
factory UserProfile.fromJson(Map<String, dynamic> json) {
|
||||
return UserProfile(
|
||||
id: json['id'] as String,
|
||||
username: json['username'] as String,
|
||||
phone: json['phone'] as String?,
|
||||
avatarUrl: json['avatar_url'] as String?,
|
||||
bio: json['bio'] as String?,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class UserUpdateRequest {
|
||||
final String? username;
|
||||
final String? avatarUrl;
|
||||
final String? bio;
|
||||
|
||||
const UserUpdateRequest({this.username, this.avatarUrl, this.bio});
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
if (username != null) 'username': username,
|
||||
if (avatarUrl != null) 'avatar_url': avatarUrl,
|
||||
if (bio != null) 'bio': bio,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
class UserSummary {
|
||||
final String id;
|
||||
final String username;
|
||||
final String? avatarUrl;
|
||||
|
||||
const UserSummary({
|
||||
required this.id,
|
||||
required this.username,
|
||||
required this.avatarUrl,
|
||||
});
|
||||
|
||||
factory UserSummary.fromJson(Map<String, dynamic> json) {
|
||||
return UserSummary(
|
||||
id: json['id'] as String,
|
||||
username: json['username'] as String,
|
||||
avatarUrl: json['avatar_url'] as String?,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import '../../../../data/network/i_api_client.dart';
|
||||
import '../../../../data/cache/cache_policy.dart';
|
||||
import '../../../../data/cache/cached_repository.dart';
|
||||
import '../models/friend_request.dart';
|
||||
|
||||
abstract class FriendRepository {
|
||||
Future<List<FriendUser>> getFriends();
|
||||
Future<FriendRequest> getRequestById(String friendshipId);
|
||||
Future<Map<String, FriendRequest>> getRequestsByIds(
|
||||
List<String> friendshipIds,
|
||||
);
|
||||
Future<FriendRequest> acceptRequest(String friendshipId);
|
||||
Future<FriendRequest> declineRequest(String friendshipId);
|
||||
}
|
||||
|
||||
class FriendRepositoryImpl extends CachedRepository<List<FriendUser>>
|
||||
implements FriendRepository {
|
||||
final IApiClient _apiClient;
|
||||
static const _prefix = '/api/v1/friends';
|
||||
|
||||
FriendRepositoryImpl({required IApiClient apiClient, required super.store})
|
||||
: _apiClient = apiClient,
|
||||
super(
|
||||
policy: const CachePolicy(
|
||||
softTtl: Duration(seconds: 30),
|
||||
hardTtl: Duration(minutes: 5),
|
||||
minRefreshInterval: Duration(seconds: 15),
|
||||
),
|
||||
encodeValue: _encodeFriendUsers,
|
||||
decodeValue: _decodeFriendUsers,
|
||||
);
|
||||
|
||||
@override
|
||||
Future<List<FriendUser>> getFriends() async {
|
||||
return getOrLoad(key: _friendsKey, loadFromRemote: _loadFriendsFromRemote);
|
||||
}
|
||||
|
||||
Future<List<FriendUser>> _loadFriendsFromRemote() async {
|
||||
final response = await _apiClient.get<List<dynamic>>(_prefix);
|
||||
final data = response.data;
|
||||
if (data == null) {
|
||||
throw StateError('Invalid getFriends response: empty payload');
|
||||
}
|
||||
return data
|
||||
.map((item) => item as Map<String, dynamic>)
|
||||
.map(
|
||||
(item) => FriendUser.fromJson(item['friend'] as Map<String, dynamic>),
|
||||
)
|
||||
.toList(growable: false);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<FriendRequest> getRequestById(String friendshipId) async {
|
||||
return _loadRequestById(friendshipId);
|
||||
}
|
||||
|
||||
Future<FriendRequest> _loadRequestById(String friendshipId) async {
|
||||
final response = await _apiClient.get<Map<String, dynamic>>(
|
||||
'$_prefix/requests/$friendshipId',
|
||||
);
|
||||
final data = response.data;
|
||||
if (data == null) {
|
||||
throw StateError('Invalid getRequestById response: empty payload');
|
||||
}
|
||||
return FriendRequest.fromJson(data);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Map<String, FriendRequest>> getRequestsByIds(
|
||||
List<String> friendshipIds,
|
||||
) async {
|
||||
if (friendshipIds.isEmpty) {
|
||||
return const <String, FriendRequest>{};
|
||||
}
|
||||
|
||||
final pairs = await Future.wait(
|
||||
friendshipIds.map((id) async {
|
||||
final request = await getRequestById(id);
|
||||
return MapEntry(id, request);
|
||||
}),
|
||||
);
|
||||
|
||||
return Map<String, FriendRequest>.fromEntries(pairs);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<FriendRequest> acceptRequest(String friendshipId) async {
|
||||
final response = await _apiClient.post<Map<String, dynamic>>(
|
||||
'$_prefix/requests/$friendshipId/accept',
|
||||
);
|
||||
final data = response.data;
|
||||
if (data == null) {
|
||||
throw StateError('Invalid acceptRequest response: empty payload');
|
||||
}
|
||||
final request = FriendRequest.fromJson(data);
|
||||
await _invalidateFriendCaches(friendshipId);
|
||||
return request;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<FriendRequest> declineRequest(String friendshipId) async {
|
||||
final response = await _apiClient.post<Map<String, dynamic>>(
|
||||
'$_prefix/requests/$friendshipId/decline',
|
||||
);
|
||||
final data = response.data;
|
||||
if (data == null) {
|
||||
throw StateError('Invalid declineRequest response: empty payload');
|
||||
}
|
||||
final request = FriendRequest.fromJson(data);
|
||||
await _invalidateFriendCaches(friendshipId);
|
||||
return request;
|
||||
}
|
||||
|
||||
Future<void> _invalidateFriendCaches(String friendshipId) {
|
||||
final _ = friendshipId;
|
||||
return removeCacheKey(_friendsKey);
|
||||
}
|
||||
|
||||
static const _friendsKey = 'friends:list';
|
||||
|
||||
static Object? _encodeFriendUsers(List<FriendUser> users) {
|
||||
return users.map(_encodeFriendUser).toList(growable: false);
|
||||
}
|
||||
|
||||
static List<FriendUser> _decodeFriendUsers(Object? raw) {
|
||||
if (raw is! List) {
|
||||
throw const FormatException('Invalid cached friend list payload');
|
||||
}
|
||||
return raw
|
||||
.whereType<Map>()
|
||||
.map((item) => FriendUser.fromJson(Map<String, dynamic>.from(item)))
|
||||
.toList(growable: false);
|
||||
}
|
||||
|
||||
static Map<String, Object?> _encodeFriendUser(FriendUser user) {
|
||||
return <String, Object?>{
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'avatar_url': user.avatarUrl,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import '../../../../data/network/i_api_client.dart';
|
||||
import '../models/user_summary.dart';
|
||||
|
||||
abstract class UserRepository {
|
||||
Future<UserSummary> getById(String userId);
|
||||
Future<UserSummary> getMe();
|
||||
}
|
||||
|
||||
class UserRepositoryImpl implements UserRepository {
|
||||
final IApiClient _apiClient;
|
||||
static const _prefix = '/api/v1/users';
|
||||
|
||||
UserRepositoryImpl(this._apiClient);
|
||||
|
||||
@override
|
||||
Future<UserSummary> getById(String userId) async {
|
||||
final response = await _apiClient.get<Map<String, dynamic>>(
|
||||
'$_prefix/$userId',
|
||||
);
|
||||
final user = response.data;
|
||||
if (user == null) {
|
||||
throw StateError('Invalid getById response: empty payload');
|
||||
}
|
||||
return UserSummary.fromJson(user);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<UserSummary> getMe() async {
|
||||
final response = await _apiClient.get<Map<String, dynamic>>('$_prefix/me');
|
||||
final user = response.data;
|
||||
if (user == null) {
|
||||
throw StateError('Invalid getMe response: empty payload');
|
||||
}
|
||||
return UserSummary.fromJson(user);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import '../../../../data/models/user_profile.dart';
|
||||
import '../models/user_profile.dart';
|
||||
|
||||
abstract class UsersRepository {
|
||||
Future<UserProfile> getMe();
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
import 'users_api.dart';
|
||||
import '../apis/users_api.dart';
|
||||
import 'users_repository.dart';
|
||||
import '../../../../data/models/user_profile.dart';
|
||||
import '../models/user_profile.dart';
|
||||
|
||||
class UsersRepositoryImpl implements UsersRepository {
|
||||
final UsersApi _api;
|
||||
@@ -2,14 +2,14 @@ import 'package:flutter/material.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import '../../../../app/di/injection.dart';
|
||||
import '../../../../core/l10n/l10n.dart';
|
||||
import '../../../../data/models/user_profile.dart';
|
||||
import '../../data/models/user_profile.dart';
|
||||
import '../../../../core/theme/design_tokens.dart';
|
||||
import '../../../../shared/widgets/app_loading_indicator.dart';
|
||||
import '../../../../shared/widgets/toast/index.dart';
|
||||
import '../../../../shared/widgets/app_button.dart';
|
||||
import '../../../../shared/widgets/back_title_page_header.dart';
|
||||
import '../../../contacts/data/friends_api.dart';
|
||||
import '../../../contacts/data/users/users_api.dart';
|
||||
import '../../../contacts/data/apis/friends_api.dart';
|
||||
import '../../../contacts/data/apis/users_api.dart';
|
||||
|
||||
class ContactsScreen extends StatefulWidget {
|
||||
const ContactsScreen({super.key});
|
||||
|
||||
@@ -6,13 +6,13 @@ import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:image_picker/image_picker.dart';
|
||||
import 'package:social_app/core/chat/agent_stage.dart';
|
||||
import '../../../../core/network/api_exception.dart';
|
||||
import '../../../../data/network/api_exception.dart';
|
||||
import '../../../../app/di/injection.dart';
|
||||
import '../../../../app/router/app_route_observer.dart';
|
||||
import '../../../../app/router/app_routes.dart';
|
||||
import '../../../../core/l10n/l10n.dart';
|
||||
import '../../../../core/theme/design_tokens.dart';
|
||||
import '../../../../data/repositories/inbox_repository.dart';
|
||||
import '../../../../features/messages/data/repositories/inbox_repository.dart';
|
||||
import '../../../chat/presentation/bloc/chat_bloc.dart';
|
||||
import '../../data/voice_recorder.dart';
|
||||
import '../controllers/home_keyboard_inset_calculator.dart';
|
||||
|
||||
@@ -8,7 +8,7 @@ import '../../../../core/l10n/l10n.dart';
|
||||
import '../../../../core/theme/design_tokens.dart';
|
||||
import '../../../../core/utils/tool_name_localizer.dart';
|
||||
import '../../../../shared/widgets/app_loading_indicator.dart';
|
||||
import '../../../ui_schema/presentation/widgets/ui_schema_renderer.dart';
|
||||
import '../../../../shared/widgets/ui_schema/ui_schema_renderer.dart';
|
||||
|
||||
const _messagePaddingH = 13.0;
|
||||
const _messagePaddingV = 9.0;
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import 'package:social_app/core/network/i_api_client.dart';
|
||||
import 'package:social_app/data/network/i_api_client.dart';
|
||||
|
||||
class InboxApi {
|
||||
final IApiClient _client;
|
||||
@@ -0,0 +1,74 @@
|
||||
enum InboxMessageType { friendRequest, calendar, system, group }
|
||||
|
||||
enum InboxMessageStatus { pending, accepted, rejected, dismissed }
|
||||
|
||||
class InboxMessage {
|
||||
final String id;
|
||||
final String recipientId;
|
||||
final String? senderId;
|
||||
final InboxMessageType messageType;
|
||||
final String? scheduleItemId;
|
||||
final String? friendshipId;
|
||||
final Map<String, dynamic>? content;
|
||||
final bool isRead;
|
||||
final InboxMessageStatus status;
|
||||
final DateTime createdAt;
|
||||
|
||||
const InboxMessage({
|
||||
required this.id,
|
||||
required this.recipientId,
|
||||
required this.senderId,
|
||||
required this.messageType,
|
||||
required this.scheduleItemId,
|
||||
required this.friendshipId,
|
||||
required this.content,
|
||||
required this.isRead,
|
||||
required this.status,
|
||||
required this.createdAt,
|
||||
});
|
||||
|
||||
factory InboxMessage.fromJson(Map<String, dynamic> json) {
|
||||
return InboxMessage(
|
||||
id: json['id'] as String,
|
||||
recipientId: json['recipient_id'] as String,
|
||||
senderId: json['sender_id'] as String?,
|
||||
messageType: _messageTypeFromApi(json['message_type'] as String),
|
||||
scheduleItemId: json['schedule_item_id'] as String?,
|
||||
friendshipId: json['friendship_id'] as String?,
|
||||
content: json['content'] as Map<String, dynamic>?,
|
||||
isRead: json['is_read'] as bool,
|
||||
status: _messageStatusFromApi(json['status'] as String),
|
||||
createdAt: DateTime.parse(json['created_at'] as String),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
InboxMessageType _messageTypeFromApi(String raw) {
|
||||
switch (raw) {
|
||||
case 'friend_request':
|
||||
return InboxMessageType.friendRequest;
|
||||
case 'calendar':
|
||||
return InboxMessageType.calendar;
|
||||
case 'system':
|
||||
return InboxMessageType.system;
|
||||
case 'group':
|
||||
return InboxMessageType.group;
|
||||
default:
|
||||
throw StateError('Unsupported inbox message type: $raw');
|
||||
}
|
||||
}
|
||||
|
||||
InboxMessageStatus _messageStatusFromApi(String raw) {
|
||||
switch (raw) {
|
||||
case 'pending':
|
||||
return InboxMessageStatus.pending;
|
||||
case 'accepted':
|
||||
return InboxMessageStatus.accepted;
|
||||
case 'rejected':
|
||||
return InboxMessageStatus.rejected;
|
||||
case 'dismissed':
|
||||
return InboxMessageStatus.dismissed;
|
||||
default:
|
||||
throw StateError('Unsupported inbox message status: $raw');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import '../../../../data/network/i_api_client.dart';
|
||||
import '../../../../data/cache/cache_policy.dart';
|
||||
import '../../../../data/cache/cached_repository.dart';
|
||||
import '../models/inbox_message.dart';
|
||||
|
||||
abstract class InboxRepository {
|
||||
Future<List<InboxMessage>> getMessages({bool? isRead});
|
||||
Future<InboxMessage> markAsRead(String messageId);
|
||||
}
|
||||
|
||||
class InboxRepositoryImpl extends CachedRepository<List<InboxMessage>>
|
||||
implements InboxRepository {
|
||||
final IApiClient _apiClient;
|
||||
static const _prefix = '/api/v1/inbox/messages';
|
||||
|
||||
InboxRepositoryImpl({required IApiClient apiClient, required super.store})
|
||||
: _apiClient = apiClient,
|
||||
super(
|
||||
policy: const CachePolicy(
|
||||
softTtl: Duration(seconds: 15),
|
||||
hardTtl: Duration(minutes: 2),
|
||||
minRefreshInterval: Duration(seconds: 10),
|
||||
),
|
||||
encodeValue: _encodeMessages,
|
||||
decodeValue: _decodeMessages,
|
||||
);
|
||||
|
||||
@override
|
||||
Future<List<InboxMessage>> getMessages({bool? isRead}) async {
|
||||
return getOrLoad(
|
||||
key: _messagesKey(isRead),
|
||||
loadFromRemote: () => _loadMessagesFromRemote(isRead: isRead),
|
||||
);
|
||||
}
|
||||
|
||||
Future<List<InboxMessage>> _loadMessagesFromRemote({bool? isRead}) async {
|
||||
final queryParams = isRead != null ? '?is_read=$isRead' : '';
|
||||
final response = await _apiClient.get<List<dynamic>>(
|
||||
'$_prefix$queryParams',
|
||||
);
|
||||
final data = response.data;
|
||||
if (data == null) {
|
||||
throw StateError('Invalid getMessages response: empty payload');
|
||||
}
|
||||
return data
|
||||
.whereType<Map<String, dynamic>>()
|
||||
.map(InboxMessage.fromJson)
|
||||
.toList(growable: false);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<InboxMessage> markAsRead(String messageId) async {
|
||||
final response = await _apiClient.patch<Map<String, dynamic>>(
|
||||
'$_prefix/$messageId/read',
|
||||
);
|
||||
final data = response.data;
|
||||
if (data == null) {
|
||||
throw StateError('Invalid markAsRead response: empty payload');
|
||||
}
|
||||
final message = InboxMessage.fromJson(data);
|
||||
await Future.wait([
|
||||
removeCacheKey(_messagesKey(false)),
|
||||
removeCacheKey(_messagesKey(true)),
|
||||
removeCacheKey(_messagesKey(null)),
|
||||
]);
|
||||
return message;
|
||||
}
|
||||
|
||||
static String _messagesKey(bool? isRead) {
|
||||
if (isRead == null) {
|
||||
return 'inbox:list:all';
|
||||
}
|
||||
return isRead ? 'inbox:list:read' : 'inbox:list:unread';
|
||||
}
|
||||
|
||||
static Object? _encodeMessages(List<InboxMessage> messages) {
|
||||
return messages.map(_encodeMessage).toList(growable: false);
|
||||
}
|
||||
|
||||
static List<InboxMessage> _decodeMessages(Object? raw) {
|
||||
if (raw is! List) {
|
||||
throw const FormatException('Invalid cached inbox message payload');
|
||||
}
|
||||
return raw
|
||||
.whereType<Map>()
|
||||
.map((item) => InboxMessage.fromJson(Map<String, dynamic>.from(item)))
|
||||
.toList(growable: false);
|
||||
}
|
||||
|
||||
static Map<String, Object?> _encodeMessage(InboxMessage message) {
|
||||
return <String, Object?>{
|
||||
'id': message.id,
|
||||
'recipient_id': message.recipientId,
|
||||
'sender_id': message.senderId,
|
||||
'message_type': _messageTypeToApi(message.messageType),
|
||||
'schedule_item_id': message.scheduleItemId,
|
||||
'friendship_id': message.friendshipId,
|
||||
'content': message.content,
|
||||
'is_read': message.isRead,
|
||||
'status': _messageStatusToApi(message.status),
|
||||
'created_at': message.createdAt.toIso8601String(),
|
||||
};
|
||||
}
|
||||
|
||||
static String _messageTypeToApi(InboxMessageType type) {
|
||||
switch (type) {
|
||||
case InboxMessageType.friendRequest:
|
||||
return 'friend_request';
|
||||
case InboxMessageType.calendar:
|
||||
return 'calendar';
|
||||
case InboxMessageType.system:
|
||||
return 'system';
|
||||
case InboxMessageType.group:
|
||||
return 'group';
|
||||
}
|
||||
}
|
||||
|
||||
static String _messageStatusToApi(InboxMessageStatus status) {
|
||||
switch (status) {
|
||||
case InboxMessageStatus.pending:
|
||||
return 'pending';
|
||||
case InboxMessageStatus.accepted:
|
||||
return 'accepted';
|
||||
case InboxMessageStatus.rejected:
|
||||
return 'rejected';
|
||||
case InboxMessageStatus.dismissed:
|
||||
return 'dismissed';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,10 @@ import 'package:go_router/go_router.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
|
||||
import '../../../../app/di/injection.dart';
|
||||
import '../../../../data/repositories/calendar_event_repository.dart';
|
||||
import '../../../../data/repositories/models/inbox_message.dart';
|
||||
import '../../../../data/repositories/inbox_repository.dart';
|
||||
import '../../../../data/repositories/user_repository.dart';
|
||||
import '../../../../features/calendar/data/repositories/calendar_repository.dart';
|
||||
import '../../../../features/messages/data/models/inbox_message.dart';
|
||||
import '../../../../features/messages/data/repositories/inbox_repository.dart';
|
||||
import '../../../../features/contacts/data/repositories/user_repository.dart';
|
||||
import '../../../../core/l10n/l10n.dart';
|
||||
import '../../../../shared/widgets/app_loading_indicator.dart';
|
||||
import '../../../../shared/widgets/page_header.dart';
|
||||
@@ -25,7 +25,7 @@ class MessageInviteDetailScreen extends StatefulWidget {
|
||||
|
||||
class _MessageInviteDetailScreenState extends State<MessageInviteDetailScreen> {
|
||||
late final InboxRepository _inboxRepository;
|
||||
late final CalendarEventRepository _calendarRepository;
|
||||
late final CalendarRepository _calendarRepository;
|
||||
late final UserRepository _userRepository;
|
||||
|
||||
InboxMessage? _message;
|
||||
@@ -43,7 +43,7 @@ class _MessageInviteDetailScreenState extends State<MessageInviteDetailScreen> {
|
||||
void initState() {
|
||||
super.initState();
|
||||
_inboxRepository = sl<InboxRepository>();
|
||||
_calendarRepository = sl<CalendarEventRepository>();
|
||||
_calendarRepository = sl<CalendarRepository>();
|
||||
_userRepository = sl<UserRepository>();
|
||||
_loadDetail();
|
||||
}
|
||||
|
||||
@@ -3,10 +3,10 @@ import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../../../app/di/injection.dart';
|
||||
import '../../../../app/router/app_routes.dart';
|
||||
import '../../../../data/repositories/friend_repository.dart';
|
||||
import '../../../../data/repositories/inbox_repository.dart';
|
||||
import '../../../../data/repositories/models/friend_request.dart';
|
||||
import '../../../../data/repositories/models/inbox_message.dart';
|
||||
import '../../../../features/contacts/data/repositories/friend_repository.dart';
|
||||
import '../../../../features/messages/data/repositories/inbox_repository.dart';
|
||||
import '../../../../features/contacts/data/models/friend_request.dart';
|
||||
import '../../../../features/messages/data/models/inbox_message.dart';
|
||||
import '../../../../core/l10n/l10n.dart';
|
||||
import '../../../../shared/widgets/app_loading_indicator.dart';
|
||||
import '../../../../shared/widgets/app_pull_refresh_feedback.dart';
|
||||
|
||||
@@ -3,7 +3,7 @@ import 'package:social_app/core/l10n/l10n.dart';
|
||||
|
||||
import '../../../../core/theme/design_tokens.dart';
|
||||
import '../../../../shared/widgets/app_button.dart';
|
||||
import '../../data/inbox_api.dart';
|
||||
import '../../data/apis/inbox_api.dart';
|
||||
|
||||
class CalendarInviteCard extends StatelessWidget {
|
||||
final InboxMessageResponse message;
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
enum ReminderAction {
|
||||
archive('archive'),
|
||||
snooze10m('snooze10m');
|
||||
|
||||
const ReminderAction(this.value);
|
||||
|
||||
final String value;
|
||||
|
||||
static ReminderAction fromValue(String raw) {
|
||||
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');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
import '../../../../data/services/calendar_service.dart';
|
||||
import '../../../../data/models/reminder_payload.dart';
|
||||
import '../../../../data/repositories/models/schedule_item_model.dart';
|
||||
import '../../../../data/services/local_notification_service.dart';
|
||||
import '../models/reminder_action.dart';
|
||||
|
||||
class ReminderActionExecutor {
|
||||
final CalendarService _calendarService;
|
||||
final LocalNotificationService _notificationService;
|
||||
|
||||
ReminderActionExecutor({
|
||||
required CalendarService calendarService,
|
||||
required LocalNotificationService notificationService,
|
||||
}) : _calendarService = calendarService,
|
||||
_notificationService = notificationService;
|
||||
|
||||
Future<void> handleAction({
|
||||
required ReminderAction action,
|
||||
required ReminderPayload payload,
|
||||
}) async {
|
||||
final ids = payload.mode == ReminderPayloadMode.aggregate
|
||||
? (payload.aggregateIds.isNotEmpty
|
||||
? payload.aggregateIds
|
||||
: <String>[payload.eventId])
|
||||
: <String>[payload.eventId];
|
||||
|
||||
if (action == ReminderAction.archive) {
|
||||
for (final id in ids) {
|
||||
await _notificationService.cancelEventReminder(id);
|
||||
await _archiveEvent(id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (action == ReminderAction.snooze10m) {
|
||||
for (final id in ids) {
|
||||
await _snoozeEvent(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _snoozeEvent(String eventId) async {
|
||||
late final ScheduleItemModel event;
|
||||
try {
|
||||
event = await _calendarService.getEventById(eventId);
|
||||
} catch (_) {
|
||||
await _notificationService.cancelEventReminder(eventId);
|
||||
return;
|
||||
}
|
||||
final now = DateTime.now();
|
||||
final endAt = event.endAt;
|
||||
if (endAt != null && !now.isBefore(endAt)) {
|
||||
await _notificationService.cancelEventReminder(eventId);
|
||||
await _archiveEvent(eventId);
|
||||
return;
|
||||
}
|
||||
|
||||
final nextAt = now.add(const Duration(minutes: 10));
|
||||
if (endAt != null && !nextAt.isBefore(endAt)) {
|
||||
await _notificationService.cancelEventReminder(eventId);
|
||||
await _archiveEvent(eventId);
|
||||
return;
|
||||
}
|
||||
|
||||
await _notificationService.scheduleReminderAt(event, nextAt);
|
||||
}
|
||||
|
||||
Future<void> _archiveEvent(String eventId) async {
|
||||
try {
|
||||
await _calendarService.archiveEvent(eventId);
|
||||
} catch (_) {
|
||||
await _notificationService.cancelEventReminder(eventId);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
import '../../../../data/models/reminder_payload.dart';
|
||||
|
||||
class ReminderQueueManager {
|
||||
ReminderPayload? _currentPayload;
|
||||
final List<ReminderPayload> _pending = [];
|
||||
|
||||
void enqueueFromClick(ReminderPayload payload) {
|
||||
_currentPayload = payload;
|
||||
}
|
||||
|
||||
void enqueuePending(List<ReminderPayload> payloads) {
|
||||
payloads.sort((a, b) => a.startAt.compareTo(b.startAt));
|
||||
_pending.addAll(payloads);
|
||||
}
|
||||
|
||||
ReminderPayload? get currentPayload => _currentPayload;
|
||||
|
||||
bool get isEmpty => _currentPayload == null && _pending.isEmpty;
|
||||
|
||||
void dequeueCurrent() {
|
||||
_currentPayload = null;
|
||||
if (_pending.isNotEmpty) {
|
||||
_currentPayload = _pending.removeAt(0);
|
||||
}
|
||||
}
|
||||
|
||||
void clear() {
|
||||
_currentPayload = null;
|
||||
_pending.clear();
|
||||
}
|
||||
}
|
||||
@@ -1,195 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import '../../../../core/l10n/l10n.dart';
|
||||
import '../../../../core/theme/design_tokens.dart';
|
||||
import '../../../../data/models/reminder_payload.dart';
|
||||
import '../../../../shared/widgets/app_button.dart';
|
||||
import '../../domain/services/reminder_queue_manager.dart';
|
||||
|
||||
class ReminderOverlay extends StatefulWidget {
|
||||
const ReminderOverlay({
|
||||
super.key,
|
||||
required this.queueManager,
|
||||
required this.onComplete,
|
||||
required this.onSnooze,
|
||||
required this.onArchive,
|
||||
});
|
||||
|
||||
final ReminderQueueManager queueManager;
|
||||
final VoidCallback onComplete;
|
||||
final void Function(int minutes) onSnooze;
|
||||
final VoidCallback onArchive;
|
||||
|
||||
@override
|
||||
State<ReminderOverlay> createState() => _ReminderOverlayState();
|
||||
}
|
||||
|
||||
class _ReminderOverlayState extends State<ReminderOverlay> {
|
||||
OverlayEntry? _overlayEntry;
|
||||
|
||||
ReminderPayload? get _currentPayload => widget.queueManager.currentPayload;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_hideSnoozeOptions();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _hideSnoozeOptions() {
|
||||
_overlayEntry?.remove();
|
||||
_overlayEntry = null;
|
||||
}
|
||||
|
||||
void _showSnoozeDropdown() {
|
||||
_hideSnoozeOptions();
|
||||
|
||||
final box = context.findRenderObject() as RenderBox?;
|
||||
if (box == null) return;
|
||||
|
||||
final button = box.localToGlobal(Offset.zero);
|
||||
|
||||
_overlayEntry = OverlayEntry(
|
||||
builder: (context) => Positioned(
|
||||
left: button.dx,
|
||||
top: button.dy + box.size.height + 4,
|
||||
width: 120,
|
||||
child: Builder(
|
||||
builder: (context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return Material(
|
||||
elevation: 4,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surface,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: colorScheme.outlineVariant),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
_SnoozeOption(
|
||||
label: context.l10n.notificationSnoozeMinutes(5),
|
||||
onTap: () {
|
||||
_hideSnoozeOptions();
|
||||
_handleSnooze(5);
|
||||
},
|
||||
),
|
||||
Divider(height: 1, color: colorScheme.outlineVariant),
|
||||
_SnoozeOption(
|
||||
label: context.l10n.notificationSnoozeMinutes(15),
|
||||
onTap: () {
|
||||
_hideSnoozeOptions();
|
||||
_handleSnooze(15);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
Overlay.of(context).insert(_overlayEntry!);
|
||||
}
|
||||
|
||||
void _handleComplete() {
|
||||
widget.onArchive();
|
||||
widget.queueManager.dequeueCurrent();
|
||||
widget.onComplete();
|
||||
}
|
||||
|
||||
void _handleSnooze(int minutes) {
|
||||
widget.onSnooze(minutes);
|
||||
widget.queueManager.dequeueCurrent();
|
||||
widget.onComplete();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final payload = _currentPayload;
|
||||
if (payload == null) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
return Container(
|
||||
color: colorScheme.surface,
|
||||
child: SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(AppSpacing.lg),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
payload.title,
|
||||
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
|
||||
color: colorScheme.onSurface,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: AppSpacing.sm),
|
||||
Text(
|
||||
DateFormat('HH:mm').format(DateTime.now()),
|
||||
style: Theme.of(context).textTheme.titleLarge?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: AppSpacing.xl),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: AppButton(
|
||||
text: context.l10n.notificationSnoozeLater,
|
||||
isOutlined: true,
|
||||
onPressed: _showSnoozeDropdown,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: AppSpacing.md),
|
||||
Expanded(
|
||||
child: AppButton(
|
||||
text: context.l10n.commonDone,
|
||||
onPressed: _handleComplete,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SnoozeOption extends StatelessWidget {
|
||||
const _SnoozeOption({required this.label, required this.onTap});
|
||||
|
||||
final String label;
|
||||
final VoidCallback onTap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return InkWell(
|
||||
onTap: onTap,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: AppSpacing.md,
|
||||
vertical: AppSpacing.sm,
|
||||
),
|
||||
child: Text(
|
||||
label,
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.bodyMedium?.copyWith(color: colorScheme.onSurface),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import 'package:social_app/core/network/i_api_client.dart';
|
||||
import 'package:social_app/data/network/i_api_client.dart';
|
||||
import '../models/automation_job_model.dart';
|
||||
|
||||
class AutomationJobsApi {
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import 'package:social_app/core/network/i_api_client.dart';
|
||||
import 'package:social_app/data/network/i_api_client.dart';
|
||||
|
||||
class AppVersionResponse {
|
||||
final bool hasUpdate;
|
||||
+20
-1
@@ -1,6 +1,6 @@
|
||||
import '../../../../data/cache/cache_policy.dart';
|
||||
import '../../../../data/cache/cached_repository.dart';
|
||||
import '../../../../data/models/user_profile.dart';
|
||||
import '../../../contacts/data/models/user_profile.dart';
|
||||
|
||||
class UserProfileCacheRepository extends CachedRepository<UserProfile> {
|
||||
static const String cacheKey = 'settings:user_profile';
|
||||
@@ -22,6 +22,8 @@ class UserProfileCacheRepository extends CachedRepository<UserProfile> {
|
||||
hardTtl: Duration(minutes: 30),
|
||||
minRefreshInterval: Duration(minutes: 1),
|
||||
),
|
||||
encodeValue: _encodeUserProfile,
|
||||
decodeValue: _decodeUserProfile,
|
||||
);
|
||||
|
||||
UserProfile? get cachedUser => _cachedUser;
|
||||
@@ -64,4 +66,21 @@ class UserProfileCacheRepository extends CachedRepository<UserProfile> {
|
||||
}
|
||||
return remote;
|
||||
}
|
||||
|
||||
static Object? _encodeUserProfile(UserProfile user) {
|
||||
return <String, Object?>{
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'phone': user.phone,
|
||||
'avatar_url': user.avatarUrl,
|
||||
'bio': user.bio,
|
||||
};
|
||||
}
|
||||
|
||||
static UserProfile _decodeUserProfile(Object? raw) {
|
||||
if (raw is! Map) {
|
||||
throw const FormatException('Invalid cached user profile payload');
|
||||
}
|
||||
return UserProfile.fromJson(Map<String, dynamic>.from(raw));
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import 'package:social_app/core/network/i_api_client.dart';
|
||||
import 'package:social_app/data/network/i_api_client.dart';
|
||||
import '../models/memory_models.dart';
|
||||
|
||||
class MemoryService {
|
||||
|
||||
@@ -2,8 +2,8 @@ import 'dart:io';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../../../../core/network/i_api_client.dart';
|
||||
import '../../../../data/models/user_profile.dart';
|
||||
import '../../../../data/network/i_api_client.dart';
|
||||
import '../../../contacts/data/models/user_profile.dart';
|
||||
|
||||
class UserProfileService {
|
||||
static const _prefix = '/api/v1/users';
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../data/models/automation_job_model.dart';
|
||||
import '../../data/services/automation_jobs_api.dart';
|
||||
import '../../data/apis/automation_jobs_api.dart';
|
||||
|
||||
class AutomationJobsState extends Equatable {
|
||||
final List<AutomationJobModel> jobs;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../data/models/automation_job_model.dart';
|
||||
import '../../data/services/automation_jobs_api.dart';
|
||||
import '../../data/apis/automation_jobs_api.dart';
|
||||
|
||||
class JobDetailState extends Equatable {
|
||||
final AutomationJobModel? job;
|
||||
|
||||
@@ -10,8 +10,8 @@ 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/models/user_profile.dart';
|
||||
import '../../data/services/user_profile_cache_repository.dart';
|
||||
import '../../../contacts/data/models/user_profile.dart';
|
||||
import '../../data/repositories/user_profile_cache_repository.dart';
|
||||
import '../../data/services/user_profile_service.dart';
|
||||
import '../widgets/account_section_card.dart';
|
||||
import '../widgets/settings_page_scaffold.dart';
|
||||
|
||||
@@ -12,7 +12,7 @@ import '../../../../shared/widgets/app_toggle_switch.dart';
|
||||
import '../../../../shared/widgets/toast/toast.dart';
|
||||
import '../../../../shared/widgets/toast/toast_type.dart';
|
||||
import '../../data/models/automation_job_model.dart';
|
||||
import '../../data/services/automation_jobs_api.dart';
|
||||
import '../../data/apis/automation_jobs_api.dart';
|
||||
import '../../presentation/cubits/automation_jobs_cubit.dart';
|
||||
import '../widgets/settings_page_scaffold.dart';
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ import '../../../../shared/widgets/toast/toast.dart';
|
||||
import '../../../../shared/widgets/toast/toast_type.dart';
|
||||
import '../../../../core/utils/tool_name_localizer.dart';
|
||||
import '../../data/models/automation_job_model.dart';
|
||||
import '../../data/services/automation_jobs_api.dart';
|
||||
import '../../data/apis/automation_jobs_api.dart';
|
||||
import '../../presentation/cubits/job_detail_cubit.dart';
|
||||
import '../widgets/settings_page_scaffold.dart';
|
||||
|
||||
|
||||
@@ -6,8 +6,8 @@ import 'package:social_app/app/router/app_routes.dart';
|
||||
import 'package:social_app/core/l10n/l10n.dart';
|
||||
import 'package:social_app/core/theme/design_tokens.dart';
|
||||
import 'package:social_app/core/auth/session_controller.dart';
|
||||
import 'package:social_app/data/models/user_profile.dart';
|
||||
import 'package:social_app/data/repositories/friend_repository.dart';
|
||||
import 'package:social_app/features/contacts/data/models/user_profile.dart';
|
||||
import 'package:social_app/features/contacts/data/repositories/friend_repository.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';
|
||||
@@ -15,9 +15,9 @@ 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/core/utils/phone_display_formatter.dart';
|
||||
import 'package:social_app/features/settings/data/settings_api.dart';
|
||||
import 'package:social_app/features/settings/data/services/automation_jobs_api.dart';
|
||||
import 'package:social_app/features/settings/data/services/user_profile_cache_repository.dart';
|
||||
import 'package:social_app/features/settings/data/apis/settings_api.dart';
|
||||
import 'package:social_app/features/settings/data/apis/automation_jobs_api.dart';
|
||||
import 'package:social_app/features/settings/data/repositories/user_profile_cache_repository.dart';
|
||||
import 'package:social_app/app/router/home_return_policy.dart';
|
||||
import '../widgets/settings_page_scaffold.dart';
|
||||
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import 'package:social_app/core/network/i_api_client.dart';
|
||||
import 'package:social_app/data/network/i_api_client.dart';
|
||||
|
||||
class TodoApi {
|
||||
final IApiClient _client;
|
||||
@@ -0,0 +1,104 @@
|
||||
import 'dart:async';
|
||||
|
||||
import '../../../../data/cache/cache_store.dart';
|
||||
import '../../../../data/cache/cache_policy.dart';
|
||||
import '../../../../data/cache/cached_repository.dart';
|
||||
import '../apis/todo_api.dart';
|
||||
|
||||
class TodoRepository extends CachedRepository<List<TodoResponse>> {
|
||||
static const String pendingListKey = 'todo:list:pending';
|
||||
|
||||
final TodoApi api;
|
||||
final CacheInvalidator invalidator;
|
||||
|
||||
TodoRepository({
|
||||
required this.api,
|
||||
required super.store,
|
||||
required this.invalidator,
|
||||
super.now,
|
||||
}) : super(
|
||||
policy: const CachePolicy(
|
||||
softTtl: Duration(seconds: 30),
|
||||
hardTtl: Duration(minutes: 10),
|
||||
minRefreshInterval: Duration(seconds: 15),
|
||||
),
|
||||
encodeValue: _encodeTodoList,
|
||||
decodeValue: _decodeTodoList,
|
||||
);
|
||||
|
||||
Future<List<TodoResponse>> getPendingTodos({
|
||||
bool forceRefresh = false,
|
||||
}) async {
|
||||
return getOrLoad(
|
||||
key: pendingListKey,
|
||||
forceRefresh: forceRefresh,
|
||||
loadFromRemote: api.getPendingTodos,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> completeTodo(String id) async {
|
||||
final CacheEntry<List<TodoResponse>>? cached = await readCacheEntry(
|
||||
pendingListKey,
|
||||
);
|
||||
if (cached != null) {
|
||||
final next = cached.value
|
||||
.where((todo) => todo.id != id)
|
||||
.toList(growable: false);
|
||||
await writeCacheEntry(pendingListKey, next);
|
||||
}
|
||||
|
||||
try {
|
||||
await api.completeTodo(id);
|
||||
invalidator.invalidate(pendingListKey);
|
||||
} catch (error) {
|
||||
if (cached != null) {
|
||||
await writeCacheEntry(pendingListKey, cached.value);
|
||||
}
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> invalidatePending() {
|
||||
invalidator.invalidate(pendingListKey);
|
||||
return Future<void>.value();
|
||||
}
|
||||
|
||||
static Object? _encodeTodoList(List<TodoResponse> todos) {
|
||||
return todos.map(_encodeTodo).toList(growable: false);
|
||||
}
|
||||
|
||||
static List<TodoResponse> _decodeTodoList(Object? raw) {
|
||||
if (raw is! List) {
|
||||
throw const FormatException('Invalid cached todo list payload');
|
||||
}
|
||||
return raw
|
||||
.whereType<Map>()
|
||||
.map((item) => TodoResponse.fromJson(Map<String, dynamic>.from(item)))
|
||||
.toList(growable: false);
|
||||
}
|
||||
|
||||
static Map<String, Object?> _encodeTodo(TodoResponse todo) {
|
||||
return <String, Object?>{
|
||||
'id': todo.id,
|
||||
'owner_id': todo.ownerId,
|
||||
'title': todo.title,
|
||||
'description': todo.description,
|
||||
'order': todo.order,
|
||||
'priority': todo.priority,
|
||||
'status': todo.status,
|
||||
'completed_at': todo.completedAt?.toIso8601String(),
|
||||
'created_at': todo.createdAt.toIso8601String(),
|
||||
'updated_at': todo.updatedAt.toIso8601String(),
|
||||
'schedule_items': todo.scheduleItems.map(_encodeScheduleItem).toList(),
|
||||
};
|
||||
}
|
||||
|
||||
static Map<String, Object?> _encodeScheduleItem(ScheduleItemBasic item) {
|
||||
return <String, Object?>{
|
||||
'id': item.id,
|
||||
'title': item.title,
|
||||
'start_at': item.startAt.toIso8601String(),
|
||||
'end_at': item.endAt?.toIso8601String(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
import 'dart:async';
|
||||
|
||||
import '../../../data/cache/cache_entry.dart';
|
||||
import '../../../data/cache/cache_invalidator.dart';
|
||||
import '../../../data/cache/cache_policy.dart';
|
||||
import '../../../data/cache/cached_repository.dart';
|
||||
import 'todo_api.dart';
|
||||
|
||||
class TodoRepository extends CachedRepository<List<TodoResponse>> {
|
||||
static const String pendingListKey = 'todo:list:pending';
|
||||
|
||||
final TodoApi api;
|
||||
final CacheInvalidator invalidator;
|
||||
|
||||
TodoRepository({
|
||||
required this.api,
|
||||
required super.store,
|
||||
required this.invalidator,
|
||||
super.now,
|
||||
}) : super(
|
||||
policy: const CachePolicy(
|
||||
softTtl: Duration(days: 3650),
|
||||
hardTtl: Duration(days: 3650),
|
||||
minRefreshInterval: Duration(days: 3650),
|
||||
),
|
||||
);
|
||||
|
||||
Future<List<TodoResponse>> getPendingTodos({
|
||||
bool forceRefresh = false,
|
||||
}) async {
|
||||
return getOrLoad(
|
||||
key: pendingListKey,
|
||||
forceRefresh: forceRefresh,
|
||||
loadFromRemote: api.getPendingTodos,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> completeTodo(String id) async {
|
||||
final CacheEntry<List<TodoResponse>>? cached = await readCacheEntry(
|
||||
pendingListKey,
|
||||
);
|
||||
if (cached != null) {
|
||||
final next = cached.value
|
||||
.where((todo) => todo.id != id)
|
||||
.toList(growable: false);
|
||||
await writeCacheEntry(pendingListKey, next);
|
||||
}
|
||||
|
||||
try {
|
||||
await api.completeTodo(id);
|
||||
invalidator.invalidate(pendingListKey);
|
||||
} catch (error) {
|
||||
if (cached != null) {
|
||||
await store.write<CacheEntry<List<TodoResponse>>>(
|
||||
pendingListKey,
|
||||
cached,
|
||||
);
|
||||
}
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> invalidatePending() {
|
||||
invalidator.invalidate(pendingListKey);
|
||||
return Future<void>.value();
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import '../../../../shared/widgets/error_retry_surface.dart';
|
||||
import '../../../../shared/widgets/full_screen_loading.dart';
|
||||
import '../../../../shared/widgets/toast/toast.dart';
|
||||
import '../../../../shared/widgets/toast/toast_type.dart';
|
||||
import '../../data/todo_api.dart';
|
||||
import '../../data/apis/todo_api.dart';
|
||||
|
||||
enum _TodoHeaderAction { edit, delete }
|
||||
|
||||
|
||||
@@ -3,8 +3,8 @@ import 'package:go_router/go_router.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
|
||||
import '../../../../app/di/injection.dart';
|
||||
import '../../../../data/repositories/calendar_event_repository.dart';
|
||||
import '../../../../data/repositories/models/calendar_event.dart';
|
||||
import '../../../../features/calendar/data/repositories/calendar_repository.dart';
|
||||
import '../../../../features/calendar/data/models/schedule_item_model.dart';
|
||||
import '../../../../core/l10n/l10n.dart';
|
||||
import '../../../../core/theme/design_tokens.dart';
|
||||
import '../../../../shared/widgets/app_button.dart';
|
||||
@@ -15,7 +15,7 @@ import '../../../../shared/widgets/error_retry_surface.dart';
|
||||
import '../../../../shared/widgets/full_screen_loading.dart';
|
||||
import '../../../../shared/widgets/toast/toast.dart';
|
||||
import '../../../../shared/widgets/toast/toast_type.dart';
|
||||
import '../../data/todo_api.dart';
|
||||
import '../../data/apis/todo_api.dart';
|
||||
|
||||
class TodoEditScreen extends StatefulWidget {
|
||||
final String? todoId;
|
||||
@@ -32,8 +32,7 @@ class TodoEditScreen extends StatefulWidget {
|
||||
|
||||
class _TodoEditScreenState extends State<TodoEditScreen> {
|
||||
final TodoApi _todoApi = sl<TodoApi>();
|
||||
final CalendarEventRepository _calendarRepository =
|
||||
sl<CalendarEventRepository>();
|
||||
final CalendarRepository _calendarRepository = sl<CalendarRepository>();
|
||||
|
||||
final TextEditingController _titleController = TextEditingController();
|
||||
final TextEditingController _descriptionController = TextEditingController();
|
||||
@@ -94,7 +93,7 @@ class _TodoEditScreenState extends State<TodoEditScreen> {
|
||||
..clear()
|
||||
..addAll(todo?.scheduleItems.map((item) => item.id) ?? const []);
|
||||
_scheduleItems = scheduleItems
|
||||
.where((item) => item.status == CalendarEventStatus.active)
|
||||
.where((item) => item.status == ScheduleStatus.active)
|
||||
.map(
|
||||
(item) => _ScheduleItemSimple(
|
||||
id: item.id,
|
||||
|
||||
@@ -16,8 +16,8 @@ import '../../../../shared/widgets/bottom_dock.dart';
|
||||
import '../../../../shared/state/calendar_state_manager.dart';
|
||||
import '../../../../shared/widgets/toast/toast.dart';
|
||||
import '../../../../shared/widgets/toast/toast_type.dart';
|
||||
import '../../data/todo_api.dart';
|
||||
import '../../data/todo_repository.dart';
|
||||
import '../../data/apis/todo_api.dart';
|
||||
import '../../data/repositories/todo_repository.dart';
|
||||
|
||||
class TodoQuadrantsScreen extends StatefulWidget {
|
||||
const TodoQuadrantsScreen({super.key});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:social_app/core/theme/design_tokens.dart';
|
||||
import 'package:social_app/features/todo/data/todo_api.dart';
|
||||
import 'package:social_app/features/todo/data/apis/todo_api.dart';
|
||||
|
||||
class TodoDragItem extends StatelessWidget {
|
||||
final TodoResponse todo;
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
// UI Schema Protocol Implementation.
|
||||
///
|
||||
/// This file is the single source of truth for UI Schema.
|
||||
/// All implementations must follow docs/protocols/ui-schema.md.
|
||||
///
|
||||
/// Version: 1.0
|
||||
library;
|
||||
|
||||
part 'ui_schema/enums.dart';
|
||||
part 'ui_schema/common_types.dart';
|
||||
part 'ui_schema/actions.dart';
|
||||
part 'ui_schema/nodes.dart';
|
||||
part 'ui_schema/document.dart';
|
||||
part 'ui_schema/builders.dart';
|
||||
@@ -1,205 +0,0 @@
|
||||
part of '../ui_schema.dart';
|
||||
|
||||
abstract class ActionSpec {
|
||||
String get type;
|
||||
Map<String, dynamic> toJson();
|
||||
}
|
||||
|
||||
class NavigateAction implements ActionSpec {
|
||||
final String path;
|
||||
final Map<String, dynamic>? params;
|
||||
|
||||
const NavigateAction({required this.path, this.params});
|
||||
|
||||
@override
|
||||
String get type => 'navigation';
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() {
|
||||
return {'type': type, 'path': path, if (params != null) 'params': params};
|
||||
}
|
||||
}
|
||||
|
||||
class LinkAction implements ActionSpec {
|
||||
final String url;
|
||||
final String? target;
|
||||
|
||||
const LinkAction({required this.url, this.target});
|
||||
|
||||
@override
|
||||
String get type => 'url';
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() {
|
||||
return {'type': type, 'url': url, if (target != null) 'target': target};
|
||||
}
|
||||
}
|
||||
|
||||
class EventAction implements ActionSpec {
|
||||
final String event;
|
||||
final Map<String, dynamic>? payload;
|
||||
|
||||
const EventAction({required this.event, this.payload});
|
||||
|
||||
@override
|
||||
String get type => 'event';
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'type': type,
|
||||
'event': event,
|
||||
if (payload != null) 'payload': payload,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class ToolAction implements ActionSpec {
|
||||
final String toolId;
|
||||
final Map<String, dynamic>? params;
|
||||
|
||||
const ToolAction({required this.toolId, this.params});
|
||||
|
||||
@override
|
||||
String get type => 'tool';
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'type': type,
|
||||
'toolId': toolId,
|
||||
if (params != null) 'params': params,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class CopyAction implements ActionSpec {
|
||||
final String content;
|
||||
final String? successMessage;
|
||||
|
||||
const CopyAction({required this.content, this.successMessage});
|
||||
|
||||
@override
|
||||
String get type => 'copy';
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'type': type,
|
||||
'content': content,
|
||||
if (successMessage != null) 'successMessage': successMessage,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class PayloadAction implements ActionSpec {
|
||||
final Map<String, dynamic> payload;
|
||||
final String? submitTo;
|
||||
|
||||
const PayloadAction({required this.payload, this.submitTo});
|
||||
|
||||
@override
|
||||
String get type => 'payload';
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'type': type,
|
||||
'payload': payload,
|
||||
if (submitTo != null) 'submitTo': submitTo,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
ActionSpec actionSpecFromJson(Map<String, dynamic> json) {
|
||||
final type = json['type'] as String? ?? '';
|
||||
switch (type) {
|
||||
case 'navigation':
|
||||
return NavigateAction(
|
||||
path: json['path'] as String? ?? '',
|
||||
params: json['params'] as Map<String, dynamic>?,
|
||||
);
|
||||
case 'url':
|
||||
return LinkAction(
|
||||
url: json['url'] as String? ?? '',
|
||||
target: json['target'] as String?,
|
||||
);
|
||||
case 'event':
|
||||
return EventAction(
|
||||
event: json['event'] as String? ?? '',
|
||||
payload: json['payload'] as Map<String, dynamic>?,
|
||||
);
|
||||
case 'tool':
|
||||
return ToolAction(
|
||||
toolId: json['toolId'] as String? ?? '',
|
||||
params: json['params'] as Map<String, dynamic>?,
|
||||
);
|
||||
case 'copy':
|
||||
return CopyAction(
|
||||
content: json['content'] as String? ?? '',
|
||||
successMessage: json['successMessage'] as String?,
|
||||
);
|
||||
case 'payload':
|
||||
return PayloadAction(
|
||||
payload: json['payload'] as Map<String, dynamic>? ?? {},
|
||||
submitTo: json['submitTo'] as String?,
|
||||
);
|
||||
default:
|
||||
return EventAction(event: 'unknown');
|
||||
}
|
||||
}
|
||||
|
||||
class UiAction {
|
||||
final String id;
|
||||
final String label;
|
||||
final UiIcon? icon;
|
||||
final ActionStyle? style;
|
||||
final bool disabled;
|
||||
final ActionSpec action;
|
||||
final ActionConfirm? confirm;
|
||||
|
||||
const UiAction({
|
||||
required this.id,
|
||||
required this.label,
|
||||
this.icon,
|
||||
this.style,
|
||||
this.disabled = false,
|
||||
required this.action,
|
||||
this.confirm,
|
||||
});
|
||||
|
||||
factory UiAction.fromJson(Map<String, dynamic> json) {
|
||||
return UiAction(
|
||||
id: json['id'] as String? ?? '',
|
||||
label: json['label'] as String? ?? '',
|
||||
icon: json['icon'] != null
|
||||
? UiIcon.fromJson(json['icon'] as Map<String, dynamic>)
|
||||
: null,
|
||||
style: json['style'] != null
|
||||
? ActionStyle.values.firstWhere(
|
||||
(e) => e.value == json['style'],
|
||||
orElse: () => ActionStyle.primary,
|
||||
)
|
||||
: null,
|
||||
disabled: json['disabled'] as bool? ?? false,
|
||||
action: actionSpecFromJson(
|
||||
json['action'] as Map<String, dynamic>? ?? {'type': 'event'},
|
||||
),
|
||||
confirm: json['confirm'] != null
|
||||
? ActionConfirm.fromJson(json['confirm'] as Map<String, dynamic>)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'label': label,
|
||||
if (icon != null) 'icon': icon!.toJson(),
|
||||
if (style != null) 'style': style!.value,
|
||||
'disabled': disabled,
|
||||
'action': action.toJson(),
|
||||
if (confirm != null) 'confirm': confirm!.toJson(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
part of '../ui_schema.dart';
|
||||
|
||||
UiSchemaDocument buildSuccessDocument(
|
||||
List<UiNode> nodes, {
|
||||
String version = '1.0',
|
||||
SchemaType schemaType = SchemaType.toolResult,
|
||||
String? docId,
|
||||
String? timestamp,
|
||||
String locale = 'zh-CN',
|
||||
RendererConfig? renderer,
|
||||
DocumentMeta? meta,
|
||||
}) {
|
||||
return UiSchemaDocument(
|
||||
version: version,
|
||||
schemaType: schemaType,
|
||||
docId: docId,
|
||||
timestamp: timestamp,
|
||||
locale: locale,
|
||||
status: UiStatus.success,
|
||||
renderer: renderer,
|
||||
meta: meta,
|
||||
nodes: nodes,
|
||||
);
|
||||
}
|
||||
|
||||
UiSchemaDocument buildErrorDocument(
|
||||
List<UiNode> nodes, {
|
||||
String version = '1.0',
|
||||
SchemaType schemaType = SchemaType.toolResult,
|
||||
String? docId,
|
||||
String? timestamp,
|
||||
String locale = 'zh-CN',
|
||||
RendererConfig? renderer,
|
||||
DocumentMeta? meta,
|
||||
}) {
|
||||
return UiSchemaDocument(
|
||||
version: version,
|
||||
schemaType: schemaType,
|
||||
docId: docId,
|
||||
timestamp: timestamp,
|
||||
locale: locale,
|
||||
status: UiStatus.error,
|
||||
renderer: renderer,
|
||||
meta: meta,
|
||||
nodes: nodes,
|
||||
);
|
||||
}
|
||||
@@ -1,273 +0,0 @@
|
||||
part of '../ui_schema.dart';
|
||||
|
||||
class UiIcon {
|
||||
final IconSource source;
|
||||
final String value;
|
||||
final String? color;
|
||||
final int? size;
|
||||
|
||||
const UiIcon({
|
||||
required this.source,
|
||||
required this.value,
|
||||
this.color,
|
||||
this.size,
|
||||
});
|
||||
|
||||
factory UiIcon.fromJson(Map<String, dynamic> json) {
|
||||
return UiIcon(
|
||||
source: IconSource.values.firstWhere(
|
||||
(e) => e.value == json['source'],
|
||||
orElse: () => IconSource.icon,
|
||||
),
|
||||
value: json['value'] as String? ?? '',
|
||||
color: json['color'] as String?,
|
||||
size: json['size'] as int?,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'source': source.value,
|
||||
'value': value,
|
||||
if (color != null) 'color': color,
|
||||
if (size != null) 'size': size,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class UiBadge {
|
||||
final String label;
|
||||
final BadgeVariant variant;
|
||||
|
||||
const UiBadge({required this.label, this.variant = BadgeVariant.def});
|
||||
|
||||
factory UiBadge.fromJson(Map<String, dynamic> json) {
|
||||
return UiBadge(
|
||||
label: json['label'] as String? ?? '',
|
||||
variant: BadgeVariant.values.firstWhere(
|
||||
(e) => e.value == json['variant'],
|
||||
orElse: () => BadgeVariant.def,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {'label': label, 'variant': variant.value};
|
||||
}
|
||||
}
|
||||
|
||||
class Pagination {
|
||||
final int page;
|
||||
final int pageSize;
|
||||
final int total;
|
||||
final bool hasMore;
|
||||
|
||||
const Pagination({
|
||||
required this.page,
|
||||
required this.pageSize,
|
||||
required this.total,
|
||||
required this.hasMore,
|
||||
});
|
||||
|
||||
factory Pagination.fromJson(Map<String, dynamic> json) {
|
||||
return Pagination(
|
||||
page: json['page'] as int? ?? 1,
|
||||
pageSize: json['pageSize'] as int? ?? 20,
|
||||
total: json['total'] as int? ?? 0,
|
||||
hasMore: json['hasMore'] as bool? ?? false,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'page': page,
|
||||
'pageSize': pageSize,
|
||||
'total': total,
|
||||
'hasMore': hasMore,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class ActionConfirm {
|
||||
final String? title;
|
||||
final String? message;
|
||||
final String? confirmLabel;
|
||||
final String? cancelLabel;
|
||||
|
||||
const ActionConfirm({
|
||||
this.title,
|
||||
this.message,
|
||||
this.confirmLabel,
|
||||
this.cancelLabel,
|
||||
});
|
||||
|
||||
factory ActionConfirm.fromJson(Map<String, dynamic> json) {
|
||||
return ActionConfirm(
|
||||
title: json['title'] as String?,
|
||||
message: json['message'] as String?,
|
||||
confirmLabel: json['confirmLabel'] as String?,
|
||||
cancelLabel: json['cancelLabel'] as String?,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
if (title != null) 'title': title,
|
||||
if (message != null) 'message': message,
|
||||
if (confirmLabel != null) 'confirmLabel': confirmLabel,
|
||||
if (cancelLabel != null) 'cancelLabel': cancelLabel,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class KeyValuePair {
|
||||
final String key;
|
||||
final String? label;
|
||||
final dynamic value;
|
||||
final bool? copyable;
|
||||
|
||||
const KeyValuePair({
|
||||
required this.key,
|
||||
this.label,
|
||||
required this.value,
|
||||
this.copyable,
|
||||
});
|
||||
|
||||
factory KeyValuePair.fromJson(Map<String, dynamic> json) {
|
||||
return KeyValuePair(
|
||||
key: json['key'] as String? ?? '',
|
||||
label: json['label'] as String?,
|
||||
value: json['value'],
|
||||
copyable: json['copyable'] as bool?,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'key': key,
|
||||
if (label != null) 'label': label,
|
||||
'value': value,
|
||||
if (copyable != null) 'copyable': copyable,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class TableColumn {
|
||||
final String key;
|
||||
final String label;
|
||||
final String? width;
|
||||
final String? align;
|
||||
|
||||
const TableColumn({
|
||||
required this.key,
|
||||
required this.label,
|
||||
this.width,
|
||||
this.align,
|
||||
});
|
||||
|
||||
factory TableColumn.fromJson(Map<String, dynamic> json) {
|
||||
return TableColumn(
|
||||
key: json['key'] as String? ?? '',
|
||||
label: json['label'] as String? ?? '',
|
||||
width: json['width'] as String?,
|
||||
align: json['align'] as String?,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'key': key,
|
||||
'label': label,
|
||||
if (width != null) 'width': width,
|
||||
if (align != null) 'align': align,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class TableRow {
|
||||
final String id;
|
||||
final Map<String, dynamic> cells;
|
||||
final Map<String, dynamic>? metadata;
|
||||
final List<UiAction>? actions;
|
||||
|
||||
const TableRow({
|
||||
required this.id,
|
||||
required this.cells,
|
||||
this.metadata,
|
||||
this.actions,
|
||||
});
|
||||
|
||||
factory TableRow.fromJson(Map<String, dynamic> json) {
|
||||
return TableRow(
|
||||
id: json['id'] as String? ?? '',
|
||||
cells: json['cells'] as Map<String, dynamic>? ?? {},
|
||||
metadata: json['metadata'] as Map<String, dynamic>?,
|
||||
actions: (json['actions'] as List<dynamic>?)
|
||||
?.map((e) => UiAction.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'cells': cells,
|
||||
if (metadata != null) 'metadata': metadata,
|
||||
if (actions != null) 'actions': actions!.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class ListItem {
|
||||
final String id;
|
||||
final String title;
|
||||
final String? subtitle;
|
||||
final String? description;
|
||||
final UiIcon? icon;
|
||||
final UiBadge? badge;
|
||||
final Map<String, dynamic>? metadata;
|
||||
final List<UiAction>? actions;
|
||||
|
||||
const ListItem({
|
||||
required this.id,
|
||||
required this.title,
|
||||
this.subtitle,
|
||||
this.description,
|
||||
this.icon,
|
||||
this.badge,
|
||||
this.metadata,
|
||||
this.actions,
|
||||
});
|
||||
|
||||
factory ListItem.fromJson(Map<String, dynamic> json) {
|
||||
return ListItem(
|
||||
id: json['id'] as String? ?? '',
|
||||
title: json['title'] as String? ?? '',
|
||||
subtitle: json['subtitle'] as String?,
|
||||
description: json['description'] as String?,
|
||||
icon: json['icon'] != null
|
||||
? UiIcon.fromJson(json['icon'] as Map<String, dynamic>)
|
||||
: null,
|
||||
badge: json['badge'] != null
|
||||
? UiBadge.fromJson(json['badge'] as Map<String, dynamic>)
|
||||
: null,
|
||||
metadata: json['metadata'] as Map<String, dynamic>?,
|
||||
actions: (json['actions'] as List<dynamic>?)
|
||||
?.map((e) => UiAction.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'title': title,
|
||||
if (subtitle != null) 'subtitle': subtitle,
|
||||
if (description != null) 'description': description,
|
||||
if (icon != null) 'icon': icon!.toJson(),
|
||||
if (badge != null) 'badge': badge!.toJson(),
|
||||
if (metadata != null) 'metadata': metadata,
|
||||
if (actions != null) 'actions': actions!.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
part of '../ui_schema.dart';
|
||||
|
||||
class RendererConfig {
|
||||
final String? renderer;
|
||||
final RendererTheme? theme;
|
||||
|
||||
const RendererConfig({this.renderer, this.theme});
|
||||
|
||||
factory RendererConfig.fromJson(Map<String, dynamic> json) {
|
||||
return RendererConfig(
|
||||
renderer: json['renderer'] as String?,
|
||||
theme: json['theme'] != null
|
||||
? RendererTheme.values.firstWhere(
|
||||
(e) => e.value == json['theme'],
|
||||
orElse: () => RendererTheme.def,
|
||||
)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
if (renderer != null) 'renderer': renderer,
|
||||
if (theme != null) 'theme': theme!.value,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class DocumentMeta {
|
||||
final String? requestId;
|
||||
final String? toolId;
|
||||
final String? traceId;
|
||||
final String? userId;
|
||||
final Map<String, dynamic>? extra;
|
||||
|
||||
const DocumentMeta({
|
||||
this.requestId,
|
||||
this.toolId,
|
||||
this.traceId,
|
||||
this.userId,
|
||||
this.extra,
|
||||
});
|
||||
|
||||
factory DocumentMeta.fromJson(Map<String, dynamic> json) {
|
||||
return DocumentMeta(
|
||||
requestId: json['requestId'] as String?,
|
||||
toolId: json['toolId'] as String?,
|
||||
traceId: json['traceId'] as String?,
|
||||
userId: json['userId'] as String?,
|
||||
extra: json,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
if (requestId != null) 'requestId': requestId,
|
||||
if (toolId != null) 'toolId': toolId,
|
||||
if (traceId != null) 'traceId': traceId,
|
||||
if (userId != null) 'userId': userId,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class UiSchemaDocument {
|
||||
final String version;
|
||||
final SchemaType schemaType;
|
||||
final String? docId;
|
||||
final String? timestamp;
|
||||
final String? locale;
|
||||
final UiStatus status;
|
||||
final RendererConfig? renderer;
|
||||
final DocumentMeta? meta;
|
||||
final List<UiNode> nodes;
|
||||
|
||||
const UiSchemaDocument({
|
||||
required this.version,
|
||||
required this.schemaType,
|
||||
this.docId,
|
||||
this.timestamp,
|
||||
this.locale,
|
||||
required this.status,
|
||||
this.renderer,
|
||||
this.meta,
|
||||
required this.nodes,
|
||||
});
|
||||
|
||||
factory UiSchemaDocument.fromJson(Map<String, dynamic> json) {
|
||||
return UiSchemaDocument(
|
||||
version: json['version'] as String? ?? '1.0',
|
||||
schemaType: SchemaType.values.firstWhere(
|
||||
(e) => e.value == json['schemaType'],
|
||||
orElse: () => SchemaType.toolResult,
|
||||
),
|
||||
docId: json['docId'] as String?,
|
||||
timestamp: json['timestamp'] as String?,
|
||||
locale: json['locale'] as String?,
|
||||
status: UiStatus.values.firstWhere(
|
||||
(e) => e.value == json['status'],
|
||||
orElse: () => UiStatus.info,
|
||||
),
|
||||
renderer: json['renderer'] != null
|
||||
? RendererConfig.fromJson(json['renderer'] as Map<String, dynamic>)
|
||||
: null,
|
||||
meta: json['meta'] != null
|
||||
? DocumentMeta.fromJson(json['meta'] as Map<String, dynamic>)
|
||||
: null,
|
||||
nodes:
|
||||
(json['nodes'] as List<dynamic>?)
|
||||
?.map((e) => UiNode.fromJson(e as Map<String, dynamic>))
|
||||
.toList() ??
|
||||
[],
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'version': version,
|
||||
'schemaType': schemaType.value,
|
||||
if (docId != null) 'docId': docId,
|
||||
if (timestamp != null) 'timestamp': timestamp,
|
||||
if (locale != null) 'locale': locale,
|
||||
'status': status.value,
|
||||
if (renderer != null) 'renderer': renderer!.toJson(),
|
||||
if (meta != null) 'meta': meta!.toJson(),
|
||||
'nodes': nodes.map((e) => (e as dynamic).toJson()).toList(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
part of '../ui_schema.dart';
|
||||
|
||||
enum SchemaType {
|
||||
toolResult('tool_result'),
|
||||
agentResponse('agent_response'),
|
||||
notification('notification');
|
||||
|
||||
final String value;
|
||||
const SchemaType(this.value);
|
||||
}
|
||||
|
||||
enum UiStatus {
|
||||
info('info'),
|
||||
success('success'),
|
||||
warning('warning'),
|
||||
error('error'),
|
||||
pending('pending');
|
||||
|
||||
final String value;
|
||||
const UiStatus(this.value);
|
||||
}
|
||||
|
||||
enum IconSource {
|
||||
icon('icon'),
|
||||
emoji('emoji'),
|
||||
url('url');
|
||||
|
||||
final String value;
|
||||
const IconSource(this.value);
|
||||
}
|
||||
|
||||
enum OperationType {
|
||||
create('create'),
|
||||
update('update'),
|
||||
delete('delete'),
|
||||
execute('execute');
|
||||
|
||||
final String value;
|
||||
const OperationType(this.value);
|
||||
}
|
||||
|
||||
enum OperationResult {
|
||||
success('success'),
|
||||
failure('failure'),
|
||||
partial('partial');
|
||||
|
||||
final String value;
|
||||
const OperationResult(this.value);
|
||||
}
|
||||
|
||||
enum ContainerDirection {
|
||||
vertical('vertical'),
|
||||
horizontal('horizontal');
|
||||
|
||||
final String value;
|
||||
const ContainerDirection(this.value);
|
||||
}
|
||||
|
||||
enum TextFormat {
|
||||
plain('plain'),
|
||||
markdown('markdown');
|
||||
|
||||
final String value;
|
||||
const TextFormat(this.value);
|
||||
}
|
||||
|
||||
enum KvLayout {
|
||||
vertical('vertical'),
|
||||
horizontal('horizontal'),
|
||||
grid('grid');
|
||||
|
||||
final String value;
|
||||
const KvLayout(this.value);
|
||||
}
|
||||
|
||||
enum BadgeVariant {
|
||||
def('default'),
|
||||
success('success'),
|
||||
warning('warning'),
|
||||
error('error'),
|
||||
info('info');
|
||||
|
||||
final String value;
|
||||
const BadgeVariant(this.value);
|
||||
}
|
||||
|
||||
enum ActionStyle {
|
||||
primary('primary'),
|
||||
secondary('secondary'),
|
||||
ghost('ghost'),
|
||||
danger('danger');
|
||||
|
||||
final String value;
|
||||
const ActionStyle(this.value);
|
||||
}
|
||||
|
||||
enum RendererTheme {
|
||||
def('default'),
|
||||
dark('dark'),
|
||||
light('light');
|
||||
|
||||
final String value;
|
||||
const RendererTheme(this.value);
|
||||
}
|
||||
@@ -1,595 +0,0 @@
|
||||
part of '../ui_schema.dart';
|
||||
|
||||
abstract class UiNode {
|
||||
String get type;
|
||||
String? get id;
|
||||
|
||||
factory UiNode.fromJson(Map<String, dynamic> json) {
|
||||
final type = json['type'] as String? ?? '';
|
||||
switch (type) {
|
||||
case 'text':
|
||||
return UiTextNode.fromJson(json);
|
||||
case 'card':
|
||||
return UiCardNode.fromJson(json);
|
||||
case 'list':
|
||||
return UiListNode.fromJson(json);
|
||||
case 'table':
|
||||
return UiTableNode.fromJson(json);
|
||||
case 'kv':
|
||||
return UiKvNode.fromJson(json);
|
||||
case 'operation':
|
||||
return UiOperationNode.fromJson(json);
|
||||
case 'error':
|
||||
return UiErrorNode.fromJson(json);
|
||||
case 'container':
|
||||
return UiContainerNode.fromJson(json);
|
||||
default:
|
||||
return UiTextNode(content: 'Unknown node type: $type');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class UiTextNode implements UiNode {
|
||||
@override
|
||||
final String? id;
|
||||
@override
|
||||
String get type => 'text';
|
||||
final String content;
|
||||
final TextFormat format;
|
||||
final UiIcon? icon;
|
||||
final List<UiAction>? actions;
|
||||
|
||||
const UiTextNode({
|
||||
this.id,
|
||||
required this.content,
|
||||
this.format = TextFormat.plain,
|
||||
this.icon,
|
||||
this.actions,
|
||||
});
|
||||
|
||||
factory UiTextNode.fromJson(Map<String, dynamic> json) {
|
||||
return UiTextNode(
|
||||
id: json['id'] as String?,
|
||||
content: json['content'] as String? ?? '',
|
||||
format: TextFormat.values.firstWhere(
|
||||
(e) => e.value == json['format'],
|
||||
orElse: () => TextFormat.plain,
|
||||
),
|
||||
icon: json['icon'] != null
|
||||
? UiIcon.fromJson(json['icon'] as Map<String, dynamic>)
|
||||
: null,
|
||||
actions: (json['actions'] as List<dynamic>?)
|
||||
?.map((e) => UiAction.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'type': type,
|
||||
'content': content,
|
||||
'format': format.value,
|
||||
if (icon != null) 'icon': icon!.toJson(),
|
||||
if (actions != null) 'actions': actions!.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class UiCardNode implements UiNode {
|
||||
@override
|
||||
final String? id;
|
||||
@override
|
||||
String get type => 'card';
|
||||
final String? title;
|
||||
final String? description;
|
||||
final UiIcon? icon;
|
||||
final UiStatus? status;
|
||||
final String? timestamp;
|
||||
final List<UiNode>? children;
|
||||
final UiTextNode? footer;
|
||||
final Map<String, dynamic>? extensions;
|
||||
final List<UiAction>? actions;
|
||||
|
||||
const UiCardNode({
|
||||
this.id,
|
||||
this.title,
|
||||
this.description,
|
||||
this.icon,
|
||||
this.status,
|
||||
this.timestamp,
|
||||
this.children,
|
||||
this.footer,
|
||||
this.extensions,
|
||||
this.actions,
|
||||
});
|
||||
|
||||
factory UiCardNode.fromJson(Map<String, dynamic> json) {
|
||||
return UiCardNode(
|
||||
id: json['id'] as String?,
|
||||
title: json['title'] as String?,
|
||||
description: json['description'] as String?,
|
||||
icon: json['icon'] != null
|
||||
? UiIcon.fromJson(json['icon'] as Map<String, dynamic>)
|
||||
: null,
|
||||
status: json['status'] != null
|
||||
? UiStatus.values.firstWhere(
|
||||
(e) => e.value == json['status'],
|
||||
orElse: () => UiStatus.info,
|
||||
)
|
||||
: null,
|
||||
timestamp: json['timestamp'] as String?,
|
||||
children: (json['children'] as List<dynamic>?)
|
||||
?.map((e) => UiNode.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
footer: json['footer'] != null
|
||||
? UiTextNode.fromJson(json['footer'] as Map<String, dynamic>)
|
||||
: null,
|
||||
extensions: json['extensions'] as Map<String, dynamic>?,
|
||||
actions: (json['actions'] as List<dynamic>?)
|
||||
?.map((e) => UiAction.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'type': type,
|
||||
if (title != null) 'title': title,
|
||||
if (description != null) 'description': description,
|
||||
if (icon != null) 'icon': icon!.toJson(),
|
||||
if (status != null) 'status': status!.value,
|
||||
if (timestamp != null) 'timestamp': timestamp,
|
||||
if (children != null)
|
||||
'children': children!.map((e) => (e as dynamic).toJson()).toList(),
|
||||
if (footer != null) 'footer': footer!.toJson(),
|
||||
if (extensions != null) 'extensions': extensions,
|
||||
if (actions != null) 'actions': actions!.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class UiListNode implements UiNode {
|
||||
@override
|
||||
final String? id;
|
||||
@override
|
||||
String get type => 'list';
|
||||
final String? title;
|
||||
final String? description;
|
||||
final UiIcon? icon;
|
||||
final UiStatus? status;
|
||||
final List<ListItem> items;
|
||||
final Pagination? pagination;
|
||||
final String? emptyText;
|
||||
final Map<String, dynamic>? extensions;
|
||||
final List<UiAction>? actions;
|
||||
|
||||
const UiListNode({
|
||||
this.id,
|
||||
this.title,
|
||||
this.description,
|
||||
this.icon,
|
||||
this.status,
|
||||
required this.items,
|
||||
this.pagination,
|
||||
this.emptyText,
|
||||
this.extensions,
|
||||
this.actions,
|
||||
});
|
||||
|
||||
factory UiListNode.fromJson(Map<String, dynamic> json) {
|
||||
return UiListNode(
|
||||
id: json['id'] as String?,
|
||||
title: json['title'] as String?,
|
||||
description: json['description'] as String?,
|
||||
icon: json['icon'] != null
|
||||
? UiIcon.fromJson(json['icon'] as Map<String, dynamic>)
|
||||
: null,
|
||||
status: json['status'] != null
|
||||
? UiStatus.values.firstWhere(
|
||||
(e) => e.value == json['status'],
|
||||
orElse: () => UiStatus.info,
|
||||
)
|
||||
: null,
|
||||
items:
|
||||
(json['items'] as List<dynamic>?)
|
||||
?.map((e) => ListItem.fromJson(e as Map<String, dynamic>))
|
||||
.toList() ??
|
||||
[],
|
||||
pagination: json['pagination'] != null
|
||||
? Pagination.fromJson(json['pagination'] as Map<String, dynamic>)
|
||||
: null,
|
||||
emptyText: json['emptyText'] as String?,
|
||||
extensions: json['extensions'] as Map<String, dynamic>?,
|
||||
actions: (json['actions'] as List<dynamic>?)
|
||||
?.map((e) => UiAction.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'type': type,
|
||||
if (title != null) 'title': title,
|
||||
if (description != null) 'description': description,
|
||||
if (icon != null) 'icon': icon!.toJson(),
|
||||
if (status != null) 'status': status!.value,
|
||||
'items': items.map((e) => e.toJson()).toList(),
|
||||
if (pagination != null) 'pagination': pagination!.toJson(),
|
||||
if (emptyText != null) 'emptyText': emptyText,
|
||||
if (extensions != null) 'extensions': extensions,
|
||||
if (actions != null) 'actions': actions!.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class UiTableNode implements UiNode {
|
||||
@override
|
||||
final String? id;
|
||||
@override
|
||||
String get type => 'table';
|
||||
final String? title;
|
||||
final String? description;
|
||||
final UiIcon? icon;
|
||||
final UiStatus? status;
|
||||
final List<TableColumn> columns;
|
||||
final List<TableRow> rows;
|
||||
final Pagination? pagination;
|
||||
final Map<String, dynamic>? extensions;
|
||||
final List<UiAction>? actions;
|
||||
|
||||
const UiTableNode({
|
||||
this.id,
|
||||
this.title,
|
||||
this.description,
|
||||
this.icon,
|
||||
this.status,
|
||||
required this.columns,
|
||||
required this.rows,
|
||||
this.pagination,
|
||||
this.extensions,
|
||||
this.actions,
|
||||
});
|
||||
|
||||
factory UiTableNode.fromJson(Map<String, dynamic> json) {
|
||||
return UiTableNode(
|
||||
id: json['id'] as String?,
|
||||
title: json['title'] as String?,
|
||||
description: json['description'] as String?,
|
||||
icon: json['icon'] != null
|
||||
? UiIcon.fromJson(json['icon'] as Map<String, dynamic>)
|
||||
: null,
|
||||
status: json['status'] != null
|
||||
? UiStatus.values.firstWhere(
|
||||
(e) => e.value == json['status'],
|
||||
orElse: () => UiStatus.info,
|
||||
)
|
||||
: null,
|
||||
columns:
|
||||
(json['columns'] as List<dynamic>?)
|
||||
?.map((e) => TableColumn.fromJson(e as Map<String, dynamic>))
|
||||
.toList() ??
|
||||
[],
|
||||
rows:
|
||||
(json['rows'] as List<dynamic>?)
|
||||
?.map((e) => TableRow.fromJson(e as Map<String, dynamic>))
|
||||
.toList() ??
|
||||
[],
|
||||
pagination: json['pagination'] != null
|
||||
? Pagination.fromJson(json['pagination'] as Map<String, dynamic>)
|
||||
: null,
|
||||
extensions: json['extensions'] as Map<String, dynamic>?,
|
||||
actions: (json['actions'] as List<dynamic>?)
|
||||
?.map((e) => UiAction.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'type': type,
|
||||
if (title != null) 'title': title,
|
||||
if (description != null) 'description': description,
|
||||
if (icon != null) 'icon': icon!.toJson(),
|
||||
if (status != null) 'status': status!.value,
|
||||
'columns': columns.map((e) => e.toJson()).toList(),
|
||||
'rows': rows.map((e) => e.toJson()).toList(),
|
||||
if (pagination != null) 'pagination': pagination!.toJson(),
|
||||
if (extensions != null) 'extensions': extensions,
|
||||
if (actions != null) 'actions': actions!.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class UiKvNode implements UiNode {
|
||||
@override
|
||||
final String? id;
|
||||
@override
|
||||
String get type => 'kv';
|
||||
final String? title;
|
||||
final String? description;
|
||||
final UiIcon? icon;
|
||||
final UiStatus? status;
|
||||
final List<KeyValuePair> pairs;
|
||||
final KvLayout layout;
|
||||
final Map<String, dynamic>? extensions;
|
||||
final List<UiAction>? actions;
|
||||
|
||||
const UiKvNode({
|
||||
this.id,
|
||||
this.title,
|
||||
this.description,
|
||||
this.icon,
|
||||
this.status,
|
||||
required this.pairs,
|
||||
this.layout = KvLayout.vertical,
|
||||
this.extensions,
|
||||
this.actions,
|
||||
});
|
||||
|
||||
factory UiKvNode.fromJson(Map<String, dynamic> json) {
|
||||
return UiKvNode(
|
||||
id: json['id'] as String?,
|
||||
title: json['title'] as String?,
|
||||
description: json['description'] as String?,
|
||||
icon: json['icon'] != null
|
||||
? UiIcon.fromJson(json['icon'] as Map<String, dynamic>)
|
||||
: null,
|
||||
status: json['status'] != null
|
||||
? UiStatus.values.firstWhere(
|
||||
(e) => e.value == json['status'],
|
||||
orElse: () => UiStatus.info,
|
||||
)
|
||||
: null,
|
||||
pairs:
|
||||
(json['pairs'] as List<dynamic>?)
|
||||
?.map((e) => KeyValuePair.fromJson(e as Map<String, dynamic>))
|
||||
.toList() ??
|
||||
[],
|
||||
layout: KvLayout.values.firstWhere(
|
||||
(e) => e.value == json['layout'],
|
||||
orElse: () => KvLayout.vertical,
|
||||
),
|
||||
extensions: json['extensions'] as Map<String, dynamic>?,
|
||||
actions: (json['actions'] as List<dynamic>?)
|
||||
?.map((e) => UiAction.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'type': type,
|
||||
if (title != null) 'title': title,
|
||||
if (description != null) 'description': description,
|
||||
if (icon != null) 'icon': icon!.toJson(),
|
||||
if (status != null) 'status': status!.value,
|
||||
'pairs': pairs.map((e) => e.toJson()).toList(),
|
||||
'layout': layout.value,
|
||||
if (extensions != null) 'extensions': extensions,
|
||||
if (actions != null) 'actions': actions!.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class UiOperationNode implements UiNode {
|
||||
@override
|
||||
final String? id;
|
||||
@override
|
||||
String get type => 'operation';
|
||||
final String? title;
|
||||
final String? description;
|
||||
final UiIcon? icon;
|
||||
final UiStatus? status;
|
||||
final OperationType operation;
|
||||
final OperationResult result;
|
||||
final String? message;
|
||||
final int? affectedCount;
|
||||
final UiNode? details;
|
||||
final UiAction? rollback;
|
||||
final Map<String, dynamic>? extensions;
|
||||
final List<UiAction>? actions;
|
||||
|
||||
const UiOperationNode({
|
||||
this.id,
|
||||
this.title,
|
||||
this.description,
|
||||
this.icon,
|
||||
this.status,
|
||||
required this.operation,
|
||||
required this.result,
|
||||
this.message,
|
||||
this.affectedCount,
|
||||
this.details,
|
||||
this.rollback,
|
||||
this.extensions,
|
||||
this.actions,
|
||||
});
|
||||
|
||||
factory UiOperationNode.fromJson(Map<String, dynamic> json) {
|
||||
return UiOperationNode(
|
||||
id: json['id'] as String?,
|
||||
title: json['title'] as String?,
|
||||
description: json['description'] as String?,
|
||||
icon: json['icon'] != null
|
||||
? UiIcon.fromJson(json['icon'] as Map<String, dynamic>)
|
||||
: null,
|
||||
status: json['status'] != null
|
||||
? UiStatus.values.firstWhere(
|
||||
(e) => e.value == json['status'],
|
||||
orElse: () => UiStatus.info,
|
||||
)
|
||||
: null,
|
||||
operation: OperationType.values.firstWhere(
|
||||
(e) => e.value == json['operation'],
|
||||
orElse: () => OperationType.execute,
|
||||
),
|
||||
result: OperationResult.values.firstWhere(
|
||||
(e) => e.value == json['result'],
|
||||
orElse: () => OperationResult.failure,
|
||||
),
|
||||
message: json['message'] as String?,
|
||||
affectedCount: json['affectedCount'] as int?,
|
||||
details: json['details'] != null
|
||||
? UiNode.fromJson(json['details'] as Map<String, dynamic>)
|
||||
: null,
|
||||
rollback: json['rollback'] != null
|
||||
? UiAction.fromJson(json['rollback'] as Map<String, dynamic>)
|
||||
: null,
|
||||
extensions: json['extensions'] as Map<String, dynamic>?,
|
||||
actions: (json['actions'] as List<dynamic>?)
|
||||
?.map((e) => UiAction.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'type': type,
|
||||
if (title != null) 'title': title,
|
||||
if (description != null) 'description': description,
|
||||
if (icon != null) 'icon': icon!.toJson(),
|
||||
if (status != null) 'status': status!.value,
|
||||
'operation': operation.value,
|
||||
'result': result.value,
|
||||
if (message != null) 'message': message,
|
||||
if (affectedCount != null) 'affectedCount': affectedCount,
|
||||
if (details != null) 'details': (details as dynamic).toJson(),
|
||||
if (rollback != null) 'rollback': rollback!.toJson(),
|
||||
if (extensions != null) 'extensions': extensions,
|
||||
if (actions != null) 'actions': actions!.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class UiErrorNode implements UiNode {
|
||||
@override
|
||||
final String? id;
|
||||
@override
|
||||
String get type => 'error';
|
||||
final String? title;
|
||||
final UiIcon? icon;
|
||||
final String errorCode;
|
||||
final String message;
|
||||
final String? details;
|
||||
final String? stack;
|
||||
final bool retryable;
|
||||
final List<String>? suggestions;
|
||||
final UiAction? retry;
|
||||
final UiAction? support;
|
||||
final List<UiAction>? actions;
|
||||
|
||||
const UiErrorNode({
|
||||
this.id,
|
||||
this.title,
|
||||
this.icon,
|
||||
required this.errorCode,
|
||||
required this.message,
|
||||
this.details,
|
||||
this.stack,
|
||||
this.retryable = false,
|
||||
this.suggestions,
|
||||
this.retry,
|
||||
this.support,
|
||||
this.actions,
|
||||
});
|
||||
|
||||
factory UiErrorNode.fromJson(Map<String, dynamic> json) {
|
||||
return UiErrorNode(
|
||||
id: json['id'] as String?,
|
||||
title: json['title'] as String?,
|
||||
icon: json['icon'] != null
|
||||
? UiIcon.fromJson(json['icon'] as Map<String, dynamic>)
|
||||
: null,
|
||||
errorCode: json['errorCode'] as String? ?? 'UNKNOWN',
|
||||
message: json['message'] as String? ?? 'An error occurred',
|
||||
details: json['details'] as String?,
|
||||
stack: json['stack'] as String?,
|
||||
retryable: json['retryable'] as bool? ?? false,
|
||||
suggestions: (json['suggestions'] as List<dynamic>?)
|
||||
?.map((e) => e as String)
|
||||
.toList(),
|
||||
retry: json['retry'] != null
|
||||
? UiAction.fromJson(json['retry'] as Map<String, dynamic>)
|
||||
: null,
|
||||
support: json['support'] != null
|
||||
? UiAction.fromJson(json['support'] as Map<String, dynamic>)
|
||||
: null,
|
||||
actions: (json['actions'] as List<dynamic>?)
|
||||
?.map((e) => UiAction.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'type': type,
|
||||
if (title != null) 'title': title,
|
||||
if (icon != null) 'icon': icon!.toJson(),
|
||||
'errorCode': errorCode,
|
||||
'message': message,
|
||||
if (details != null) 'details': details,
|
||||
if (stack != null) 'stack': stack,
|
||||
'retryable': retryable,
|
||||
if (suggestions != null) 'suggestions': suggestions,
|
||||
if (retry != null) 'retry': retry!.toJson(),
|
||||
if (support != null) 'support': support!.toJson(),
|
||||
if (actions != null) 'actions': actions!.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class UiContainerNode implements UiNode {
|
||||
@override
|
||||
final String? id;
|
||||
@override
|
||||
String get type => 'container';
|
||||
final ContainerDirection direction;
|
||||
final int? gap;
|
||||
final List<UiNode> children;
|
||||
final List<UiAction>? actions;
|
||||
|
||||
const UiContainerNode({
|
||||
this.id,
|
||||
this.direction = ContainerDirection.vertical,
|
||||
this.gap,
|
||||
required this.children,
|
||||
this.actions,
|
||||
});
|
||||
|
||||
factory UiContainerNode.fromJson(Map<String, dynamic> json) {
|
||||
return UiContainerNode(
|
||||
id: json['id'] as String?,
|
||||
direction: ContainerDirection.values.firstWhere(
|
||||
(e) => e.value == json['direction'],
|
||||
orElse: () => ContainerDirection.vertical,
|
||||
),
|
||||
gap: json['gap'] as int?,
|
||||
children:
|
||||
(json['children'] as List<dynamic>?)
|
||||
?.map((e) => UiNode.fromJson(e as Map<String, dynamic>))
|
||||
.toList() ??
|
||||
[],
|
||||
actions: (json['actions'] as List<dynamic>?)
|
||||
?.map((e) => UiAction.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'type': type,
|
||||
'direction': direction.value,
|
||||
if (gap != null) 'gap': gap,
|
||||
'children': children.map((e) => (e as dynamic).toJson()).toList(),
|
||||
if (actions != null) 'actions': actions!.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
bool isValidInternalNavigationPath(String path) {
|
||||
if (path.isEmpty || !path.startsWith('/')) {
|
||||
return false;
|
||||
}
|
||||
return !path.startsWith('//') &&
|
||||
!path.contains('://') &&
|
||||
!path.contains('?') &&
|
||||
!path.contains('#') &&
|
||||
!path.contains(':');
|
||||
}
|
||||
|
||||
String buildUiSchemaNavigationTarget({
|
||||
required String path,
|
||||
Map<String, dynamic>? params,
|
||||
}) {
|
||||
final baseUri = Uri.parse(path);
|
||||
final queryParams = <String, String>{};
|
||||
|
||||
if (params != null) {
|
||||
for (final entry in params.entries) {
|
||||
final value = entry.value;
|
||||
if (value is String && value.isNotEmpty) {
|
||||
queryParams[entry.key] = value;
|
||||
} else if (value is num || value is bool) {
|
||||
queryParams[entry.key] = value.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final mergedQueryParams = {...baseUri.queryParameters, ...queryParams};
|
||||
final targetUri = baseUri.replace(
|
||||
queryParameters: mergedQueryParams.isEmpty ? null : mergedQueryParams,
|
||||
);
|
||||
return targetUri.toString();
|
||||
}
|
||||
@@ -1,412 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:social_app/core/l10n/l10n.dart';
|
||||
import 'package:social_app/core/theme/design_tokens.dart';
|
||||
|
||||
class UiSchemaRenderer {
|
||||
final ColorScheme colorScheme;
|
||||
|
||||
UiSchemaRenderer(this.colorScheme);
|
||||
|
||||
Widget renderSchema(Map<String, dynamic>? schema) {
|
||||
if (schema == null || schema.isEmpty) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
final root = _asMap(schema['root']);
|
||||
if (root == null) {
|
||||
return _fallback(L10n.current.uiSchemaInvalid);
|
||||
}
|
||||
return _renderLayoutNode(root);
|
||||
}
|
||||
|
||||
Widget _renderLayoutNode(Map<String, dynamic> node) {
|
||||
final type = _asString(node['type']);
|
||||
return switch (type) {
|
||||
'stack' => _renderStack(node),
|
||||
'grid' => _renderGrid(node),
|
||||
_ => _fallback(L10n.current.uiSchemaUnsupportedLayout(type)),
|
||||
};
|
||||
}
|
||||
|
||||
Widget _renderNode(Map<String, dynamic> node) {
|
||||
final type = _asString(node['type']);
|
||||
if (node['visible'] == false) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return switch (type) {
|
||||
'text' => _renderText(node),
|
||||
'icon' => _renderIcon(node),
|
||||
'badge' => _renderBadge(node),
|
||||
'button' => _renderButton(node),
|
||||
'kv' => _renderKv(node),
|
||||
'divider' => _renderDivider(node),
|
||||
'stack' => _renderStack(node),
|
||||
'grid' => _renderGrid(node),
|
||||
_ => _fallback(L10n.current.uiSchemaUnknownNode(type)),
|
||||
};
|
||||
}
|
||||
|
||||
Widget _renderStack(Map<String, dynamic> node) {
|
||||
final children = _asList(
|
||||
node['children'],
|
||||
).whereType<Map<String, dynamic>>().map(_renderNode).toList();
|
||||
final gap = _asDouble(node['gap'], fallback: AppSpacing.sm);
|
||||
final direction = _asString(node['direction'], fallback: 'vertical');
|
||||
|
||||
Widget content;
|
||||
if (direction == 'horizontal') {
|
||||
content = Wrap(
|
||||
direction: Axis.horizontal,
|
||||
spacing: gap,
|
||||
runSpacing: gap,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: children,
|
||||
);
|
||||
} else {
|
||||
content = Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: _withGap(children, gap),
|
||||
);
|
||||
}
|
||||
return _wrapSurface(node, content);
|
||||
}
|
||||
|
||||
Widget _renderGrid(Map<String, dynamic> node) {
|
||||
final children = _asList(
|
||||
node['children'],
|
||||
).whereType<Map<String, dynamic>>().map(_renderNode).toList();
|
||||
final columns = _asInt(node['columns'], fallback: 2).clamp(1, 3);
|
||||
final gap = _asDouble(node['gap'], fallback: AppSpacing.sm);
|
||||
return _wrapSurface(
|
||||
node,
|
||||
GridView.count(
|
||||
crossAxisCount: columns,
|
||||
crossAxisSpacing: gap,
|
||||
mainAxisSpacing: gap,
|
||||
childAspectRatio: 1.6,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
shrinkWrap: true,
|
||||
children: children,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _renderText(Map<String, dynamic> node) {
|
||||
final role = _asString(node['role'], fallback: 'body');
|
||||
final status = _asString(node['status']);
|
||||
final style = switch (role) {
|
||||
'title' => TextStyle(
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: colorScheme.onSurface,
|
||||
height: 1.2,
|
||||
),
|
||||
'subtitle' => TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: colorScheme.onSurface,
|
||||
),
|
||||
'caption' => TextStyle(
|
||||
fontSize: 11,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
height: 1.4,
|
||||
),
|
||||
'code' => TextStyle(
|
||||
fontSize: 12,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontFamily: 'monospace',
|
||||
),
|
||||
_ => TextStyle(
|
||||
fontSize: 13,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
height: 1.35,
|
||||
),
|
||||
};
|
||||
return Text(
|
||||
_asString(node['content']),
|
||||
maxLines: _asIntOrNull(node['maxLines']),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: style.copyWith(color: _statusTextColor(status, style.color)),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _renderIcon(Map<String, dynamic> node) {
|
||||
final value = _asString(node['value']);
|
||||
if (_asString(node['source']) == 'emoji' && value.isNotEmpty) {
|
||||
return Text(value, style: const TextStyle(fontSize: 18));
|
||||
}
|
||||
return Icon(Icons.bubble_chart_rounded, color: _statusTextColor('', null));
|
||||
}
|
||||
|
||||
Widget _renderBadge(Map<String, dynamic> node) {
|
||||
final status = _asString(node['status']);
|
||||
final fg =
|
||||
_statusTextColor(status, colorScheme.onSurfaceVariant) ??
|
||||
colorScheme.onSurfaceVariant;
|
||||
final bg = _statusBackground(status);
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: AppSpacing.md,
|
||||
vertical: AppSpacing.xs,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: bg,
|
||||
borderRadius: BorderRadius.circular(AppRadius.full),
|
||||
border: Border.all(color: _statusBorder(status)),
|
||||
),
|
||||
child: Text(
|
||||
_asString(node['label']),
|
||||
style: TextStyle(fontSize: 12, fontWeight: FontWeight.w700, color: fg),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _renderButton(Map<String, dynamic> node) {
|
||||
final style = _asString(node['style'], fallback: 'secondary');
|
||||
final action = _asMap(node['action']);
|
||||
final disabled = node['disabled'] == true;
|
||||
return ElevatedButton(
|
||||
onPressed: disabled
|
||||
? null
|
||||
: () {
|
||||
_handleAction(action);
|
||||
},
|
||||
style: ElevatedButton.styleFrom(
|
||||
elevation: 0,
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: AppSpacing.lg,
|
||||
vertical: AppSpacing.sm,
|
||||
),
|
||||
backgroundColor: style == 'primary'
|
||||
? colorScheme.primary
|
||||
: colorScheme.surfaceContainerHighest,
|
||||
foregroundColor: style == 'primary'
|
||||
? colorScheme.onPrimary
|
||||
: colorScheme.onSurfaceVariant,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(AppRadius.full),
|
||||
side: style == 'primary'
|
||||
? BorderSide.none
|
||||
: BorderSide(color: colorScheme.outlineVariant),
|
||||
),
|
||||
),
|
||||
child: Text(
|
||||
_asString(node['label'], fallback: L10n.current.uiSchemaActionFallback),
|
||||
style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _handleAction(Map<String, dynamic>? action) {}
|
||||
|
||||
Widget _renderKv(Map<String, dynamic> node) {
|
||||
final items = _asList(
|
||||
node['items'],
|
||||
).whereType<Map<String, dynamic>>().toList();
|
||||
if (items.isEmpty) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: _withGap(
|
||||
items.map((item) {
|
||||
final label = _asString(
|
||||
item['label'],
|
||||
fallback: _asString(item['key']),
|
||||
);
|
||||
final value = item['value']?.toString() ?? '-';
|
||||
return Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: AppSpacing.md,
|
||||
vertical: AppSpacing.xs,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(AppRadius.md),
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
flex: 3,
|
||||
child: Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: AppSpacing.sm),
|
||||
Expanded(
|
||||
flex: 5,
|
||||
child: Text(
|
||||
value,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: colorScheme.onSurface,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}).toList(),
|
||||
AppSpacing.xs,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _renderDivider(Map<String, dynamic> node) {
|
||||
final inset = _asDouble(node['inset'], fallback: 0);
|
||||
return Padding(
|
||||
padding: EdgeInsets.symmetric(horizontal: inset),
|
||||
child: Divider(height: 1, color: colorScheme.outlineVariant),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _wrapSurface(Map<String, dynamic> node, Widget child) {
|
||||
final appearance = _asString(node['appearance'], fallback: 'plain');
|
||||
final status = _asString(node['status']);
|
||||
if (appearance == 'plain') {
|
||||
return child;
|
||||
}
|
||||
final bg = switch (appearance) {
|
||||
'section' => colorScheme.surfaceContainerHighest,
|
||||
'card' => colorScheme.surface,
|
||||
_ => _statusBackground(status),
|
||||
};
|
||||
final borderColor = switch (status) {
|
||||
'success' => colorScheme.tertiary,
|
||||
'warning' => colorScheme.secondary,
|
||||
'error' => colorScheme.error,
|
||||
_ => colorScheme.outlineVariant,
|
||||
};
|
||||
return Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(AppSpacing.md),
|
||||
decoration: BoxDecoration(
|
||||
color: bg,
|
||||
borderRadius: BorderRadius.circular(AppRadius.lg),
|
||||
border: Border.all(color: borderColor),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: colorScheme.shadow.withValues(alpha: 0.08),
|
||||
blurRadius: 12,
|
||||
offset: const Offset(0, 6),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
|
||||
Widget _fallback(String text) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(AppSpacing.md),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.secondaryContainer,
|
||||
border: Border.all(color: colorScheme.secondary),
|
||||
borderRadius: BorderRadius.circular(AppRadius.md),
|
||||
),
|
||||
child: Text(
|
||||
text,
|
||||
style: TextStyle(fontSize: 12, color: colorScheme.onSecondaryContainer),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
List<Widget> _withGap(List<Widget> widgets, double gap) {
|
||||
if (widgets.isEmpty) return const [];
|
||||
return [
|
||||
widgets.first,
|
||||
for (int i = 1; i < widgets.length; i++) ...[
|
||||
SizedBox(height: gap),
|
||||
widgets[i],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
Color _statusBackground(String status) {
|
||||
return switch (status) {
|
||||
'success' => colorScheme.tertiaryContainer,
|
||||
'warning' => colorScheme.secondaryContainer,
|
||||
'error' => colorScheme.errorContainer,
|
||||
'pending' => colorScheme.primaryContainer,
|
||||
_ => colorScheme.surfaceContainerHighest,
|
||||
};
|
||||
}
|
||||
|
||||
Color _statusBorder(String status) {
|
||||
return switch (status) {
|
||||
'success' => colorScheme.tertiary,
|
||||
'warning' => colorScheme.secondary,
|
||||
'error' => colorScheme.error,
|
||||
'pending' => colorScheme.primary,
|
||||
_ => colorScheme.outlineVariant,
|
||||
};
|
||||
}
|
||||
|
||||
Color? _statusTextColor(String status, Color? fallback) {
|
||||
return switch (status) {
|
||||
'success' => colorScheme.onTertiaryContainer,
|
||||
'warning' => colorScheme.onSecondaryContainer,
|
||||
'error' => colorScheme.onErrorContainer,
|
||||
'pending' => colorScheme.onPrimaryContainer,
|
||||
_ => fallback,
|
||||
};
|
||||
}
|
||||
|
||||
static Map<String, dynamic>? _asMap(Object? value) {
|
||||
if (value is Map<String, dynamic>) {
|
||||
return value;
|
||||
}
|
||||
if (value is Map) {
|
||||
return Map<String, dynamic>.from(value);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static List<dynamic> _asList(Object? value) {
|
||||
return value is List ? value : const [];
|
||||
}
|
||||
|
||||
static String _asString(Object? value, {String fallback = ''}) {
|
||||
return value is String ? value : fallback;
|
||||
}
|
||||
|
||||
static int _asInt(Object? value, {int fallback = 0}) {
|
||||
if (value is int) {
|
||||
return value;
|
||||
}
|
||||
if (value is double) {
|
||||
return value.toInt();
|
||||
}
|
||||
if (value is String) {
|
||||
return int.tryParse(value) ?? fallback;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
static int? _asIntOrNull(Object? value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
return _asInt(value);
|
||||
}
|
||||
|
||||
static double _asDouble(Object? value, {double fallback = 0}) {
|
||||
if (value is double) {
|
||||
return value;
|
||||
}
|
||||
if (value is int) {
|
||||
return value.toDouble();
|
||||
}
|
||||
if (value is String) {
|
||||
return double.tryParse(value) ?? fallback;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user