From e06e12fbbcce8c00a403dc3fae854b8f252daeb0 Mon Sep 17 00:00:00 2001 From: TongTongStudio Date: Mon, 9 Nov 2026 09:24:51 +0800 Subject: [PATCH] =?UTF-8?q?feat(profile):=20=E5=AE=9E=E7=8E=B0=E4=B8=AA?= =?UTF-8?q?=E4=BA=BA=E8=B5=84=E6=96=99=E7=BC=96=E8=BE=91=E4=B8=8E=E7=AD=96?= =?UTF-8?q?=E7=95=A5=E6=9C=AC=E5=9C=B0=E7=BC=93=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 将资料编辑页重构为可交互表单,支持昵称、签名编辑与头像更换 - 新增 DioClient 本地缓存读取与写入方法,支持离线读取策略快照 - 设备策略切换后自动使本地缓存失效,避免数据不一致 - Home Tab 切换时选中态跟随可见页面,滑动过程中实时更新底栏高亮 - 系统设置页引入 loading 遮罩层,防止切换开关时重复操作 - 个人资料页接入 profileController 展示真实用户信息与加载状态 - 适配深色模式,修正 home_tab 中头像与文字颜色硬编码问题 --- lib/core/network/dio_client.dart | 28 + lib/features/device/data/device_api.dart | 14 + .../device/data/device_repository_impl.dart | 3 + .../device/domain/device_repository.dart | 3 + lib/features/home/presentation/home_page.dart | 35 +- lib/features/home/presentation/home_tab.dart | 21 +- .../home/presentation/home_tab_pager.dart | 26 +- .../system_settings_controller.dart | 72 +++ .../presentation/system_settings_page.dart | 130 +++-- .../profile/data/profile_repository_impl.dart | 82 +++ .../data/profile_repository_impl.g.dart | 28 + .../profile/domain/profile_models.dart | 53 ++ .../domain/profile_models.freezed.dart | 535 ++++++++++++++++++ .../profile/domain/profile_models.g.dart | 52 ++ .../profile/domain/profile_repository.dart | 7 + .../profile/presentation/profile_avatar.dart | 44 ++ .../presentation/profile_controller.dart | 86 +++ .../presentation/profile_controller.g.dart | 26 + .../presentation/profile_edit_page.dart | 290 +++++----- .../profile/presentation/profile_tab.dart | 444 ++++++++++----- lib/l10n/app_localizations.dart | 30 + lib/l10n/app_localizations_en.dart | 16 + lib/l10n/app_localizations_zh.dart | 15 + lib/l10n/intl_en.arb | 7 +- lib/l10n/intl_zh.arb | 7 +- test/core/network/dio_client_test.dart | 10 + test/features/home/home_tab_pager_test.dart | 22 + .../home/system_settings_controller_test.dart | 91 +++ .../profile/profile_controller_test.dart | 83 +++ test/features/profile/profile_edit_test.dart | 135 +++++ 30 files changed, 2059 insertions(+), 336 deletions(-) create mode 100644 lib/features/home/presentation/system_settings_controller.dart create mode 100644 lib/features/profile/data/profile_repository_impl.dart create mode 100644 lib/features/profile/data/profile_repository_impl.g.dart create mode 100644 lib/features/profile/domain/profile_models.dart create mode 100644 lib/features/profile/domain/profile_models.freezed.dart create mode 100644 lib/features/profile/domain/profile_models.g.dart create mode 100644 lib/features/profile/domain/profile_repository.dart create mode 100644 lib/features/profile/presentation/profile_avatar.dart create mode 100644 lib/features/profile/presentation/profile_controller.dart create mode 100644 lib/features/profile/presentation/profile_controller.g.dart create mode 100644 test/features/home/system_settings_controller_test.dart create mode 100644 test/features/profile/profile_controller_test.dart create mode 100644 test/features/profile/profile_edit_test.dart diff --git a/lib/core/network/dio_client.dart b/lib/core/network/dio_client.dart index 316925c..302908a 100644 --- a/lib/core/network/dio_client.dart +++ b/lib/core/network/dio_client.dart @@ -163,6 +163,22 @@ class DioClient { } } + /// 读取当前账号的接口缓存,不发起网络请求。 + static Future readCachedGet( + String path, { + Map? queryParameters, + }) async { + final account = TokenStorage.currentAccountId; + if (kIsWeb || account == null) return null; + final version = TokenStorage.sessionVersion; + final uri = Options() + .compose(instance.options, path, queryParameters: queryParameters) + .uri; + final file = await ResponseCache.fileFor(account, uri); + final cached = file == null ? null : await ResponseCache.read(file); + return version == TokenStorage.sessionVersion ? cached?.data : null; + } + /// 统一 GET 请求,返回解析后的 data。 static Future get( String path, { @@ -259,6 +275,18 @@ class DioClient { if (file != null) await ResponseCache.remove(file); } + /// Update the local snapshot after an endpoint returns an updated resource. + static Future storeReadCache(String path, Object? data) async { + final account = kIsWeb ? null : TokenStorage.currentAccountId; + if (account == null) return; + final version = TokenStorage.sessionVersion; + final uri = Options().compose(instance.options, path).uri; + final file = await ResponseCache.fileFor(account, uri); + if (file != null && version == TokenStorage.sessionVersion) { + await ResponseCache.write(file, data); + } + } + /// 统一 POST 请求,返回解析后的 data。 static Future post( String path, { diff --git a/lib/features/device/data/device_api.dart b/lib/features/device/data/device_api.dart index 14af687..ed16a3f 100644 --- a/lib/features/device/data/device_api.dart +++ b/lib/features/device/data/device_api.dart @@ -123,6 +123,7 @@ class DeviceApi { try { final data = await DioClient.get( 'v1/client/sn/policy', + allowStale: true, queryParameters: {'sn': sn}, ); return data is Map ? DevicePolicy.fromJson(data) : null; @@ -131,6 +132,15 @@ class DeviceApi { } } + /// 读取本地策略快照,不发起网络请求。 + Future getCachedPolicy(String sn) async { + final data = await DioClient.readCachedGet( + 'v1/client/sn/policy', + queryParameters: {'sn': sn}, + ); + return data is Map ? DevicePolicy.fromJson(data) : null; + } + /// 单独设置某个策略开关。 /// /// 对应后台 `PUT /api/v1/client/sn/policy/toggle`,请求体 `{field, value}`。 @@ -142,6 +152,10 @@ class DeviceApi { data: {'field': field, 'value': value}, ); debugPrint('[DeviceApi] togglePolicy sn=$sn field=$field value=$value data=$data'); + await DioClient.invalidateReadCache( + 'v1/client/sn/policy', + queryParameters: {'sn': sn}, + ); return null; } on ApiException catch (e) { debugPrint('[DeviceApi] togglePolicy sn=$sn field=$field value=$value failed: ${e.message}'); diff --git a/lib/features/device/data/device_repository_impl.dart b/lib/features/device/data/device_repository_impl.dart index 1a88d13..73f1b9c 100644 --- a/lib/features/device/data/device_repository_impl.dart +++ b/lib/features/device/data/device_repository_impl.dart @@ -37,6 +37,9 @@ class DeviceRepositoryImpl implements DeviceRepository { @override Future getPolicy(String sn) => _api.getPolicy(sn); + @override + Future getCachedPolicy(String sn) => _api.getCachedPolicy(sn); + @override Future togglePolicy(String sn, String field, int value) => _api.togglePolicy(sn, field, value); diff --git a/lib/features/device/domain/device_repository.dart b/lib/features/device/domain/device_repository.dart index d831406..db82a08 100644 --- a/lib/features/device/domain/device_repository.dart +++ b/lib/features/device/domain/device_repository.dart @@ -32,6 +32,9 @@ abstract class DeviceRepository { /// 已绑定设备策略信息(功能开关),无记录时为 null。 Future getPolicy(String sn); + /// 读取当前账号、设备的上一次策略缓存。 + Future getCachedPolicy(String sn); + /// 单独设置某个策略开关(field 为策略字段名,value 为 0/1)。 /// /// 成功返回 null;失败返回错误提示。 diff --git a/lib/features/home/presentation/home_page.dart b/lib/features/home/presentation/home_page.dart index 72f1510..742fb0f 100644 --- a/lib/features/home/presentation/home_page.dart +++ b/lib/features/home/presentation/home_page.dart @@ -24,9 +24,19 @@ class HomePage extends StatefulWidget { class _HomePageState extends State { final _dragPage = ValueNotifier(null); + final _visibleIndex = ValueNotifier(null); int? _tabPointer; Offset _tabPointerStart = Offset.zero; + @override + void didUpdateWidget(covariant HomePage oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.navigationShell.currentIndex != + oldWidget.navigationShell.currentIndex) { + _visibleIndex.value = null; + } + } + void _finishTabDrag(PointerEvent event) { if (event.pointer != _tabPointer) return; _tabPointer = null; @@ -36,6 +46,7 @@ class _HomePageState extends State { @override void dispose() { _dragPage.dispose(); + _visibleIndex.dispose(); super.dispose(); } @@ -75,7 +86,11 @@ class _HomePageState extends State { resizeToAvoidBottomInset: false, child: Stack( children: [ - HomeTabDragScope(page: _dragPage, child: navigationShell), + HomeTabDragScope( + page: _dragPage, + visibleIndex: _visibleIndex, + child: navigationShell, + ), Align( alignment: Alignment.bottomCenter, child: SafeArea( @@ -118,13 +133,17 @@ class _HomePageState extends State { // GlassTabBar 仍读取 Flutter SDK 的 Cupertino 主题。 // ignore: deprecated_member_use child: CupertinoUiCompatibilityBridge( - child: GlassTabBar.bottom( - selectedIndex: index, - onTabSelected: navigationShell.goBranch, - horizontalPadding: tabBarMargin, - verticalPadding: 0, - iconSize: 26, - tabs: tabs, + child: ValueListenableBuilder( + valueListenable: _visibleIndex, + builder: (context, visibleIndex, _) => + GlassTabBar.bottom( + selectedIndex: visibleIndex ?? index, + onTabSelected: navigationShell.goBranch, + horizontalPadding: tabBarMargin, + verticalPadding: 0, + iconSize: 26, + tabs: tabs, + ), ), ), ); diff --git a/lib/features/home/presentation/home_tab.dart b/lib/features/home/presentation/home_tab.dart index 25b3436..75d8afe 100644 --- a/lib/features/home/presentation/home_tab.dart +++ b/lib/features/home/presentation/home_tab.dart @@ -239,8 +239,10 @@ class HomeTab extends ConsumerWidget { Container( width: 64, height: 64, - decoration: const BoxDecoration( - color: CupertinoColors.white, shape: BoxShape.circle), + decoration: BoxDecoration( + color: DarkMode.color(context, AppColors.card), + shape: BoxShape.circle, + ), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ @@ -274,7 +276,20 @@ class HomeTab extends ConsumerWidget { padding: const EdgeInsets.only(bottom: 8), child: Row( children: [ - SizedBox(width: 42, child: Text(name, style: const TextStyle(fontSize: 12, color: Color(0xFF4B5563)))), + SizedBox( + width: 42, + child: Text( + name, + style: TextStyle( + fontSize: 12, + color: DarkMode.tone( + context, + const Color(0xFF4B5563), + DarkMode.color(context, AppColors.ink), + ), + ), + ), + ), Expanded( child: Container( height: 7, diff --git a/lib/features/home/presentation/home_tab_pager.dart b/lib/features/home/presentation/home_tab_pager.dart index 11665d7..5fb58c5 100644 --- a/lib/features/home/presentation/home_tab_pager.dart +++ b/lib/features/home/presentation/home_tab_pager.dart @@ -4,12 +4,19 @@ import 'package:go_router/go_router.dart'; /// Fractional page selected by the bottom bar while a pointer is dragging. class HomeTabDragScope extends InheritedWidget { - const HomeTabDragScope({required this.page, required super.child, super.key}); + const HomeTabDragScope({ + required this.page, + required this.visibleIndex, + required super.child, + super.key, + }); final ValueNotifier page; + final ValueNotifier visibleIndex; @override - bool updateShouldNotify(HomeTabDragScope oldWidget) => page != oldWidget.page; + bool updateShouldNotify(HomeTabDragScope oldWidget) => + page != oldWidget.page || visibleIndex != oldWidget.visibleIndex; } /// Displays the shell's existing branch navigators as swipeable pages. @@ -34,13 +41,15 @@ class _HomeTabPagerState extends State { ); ValueNotifier? _dragPage; Drag? _tabDrag; + ValueNotifier? _visibleIndex; @override void didChangeDependencies() { super.didChangeDependencies(); - final page = context - .dependOnInheritedWidgetOfExactType() - ?.page; + final scope = context + .dependOnInheritedWidgetOfExactType(); + _visibleIndex = scope?.visibleIndex; + final page = scope?.page; if (page == _dragPage) return; _dragPage?.removeListener(_updateTabDrag); _dragPage = page; @@ -81,7 +90,9 @@ class _HomeTabPagerState extends State { void didUpdateWidget(covariant HomeTabPager oldWidget) { super.didUpdateWidget(oldWidget); final index = widget.navigationShell.currentIndex; - if (index != oldWidget.navigationShell.currentIndex) _animateToIndex(index); + if (index != oldWidget.navigationShell.currentIndex) { + _animateToIndex(index); + } } void _animateToIndex(int index) { @@ -118,6 +129,9 @@ class _HomeTabPagerState extends State { }, child: PageView( controller: _controller, + // Update the bar at the page midpoint, without waiting for settling + // or changing the route while the user's gesture is still active. + onPageChanged: (index) => _visibleIndex?.value = index, children: [ for (final (index, child) in widget.children.indexed) _KeepAlivePage( diff --git a/lib/features/home/presentation/system_settings_controller.dart b/lib/features/home/presentation/system_settings_controller.dart new file mode 100644 index 0000000..768b3b4 --- /dev/null +++ b/lib/features/home/presentation/system_settings_controller.dart @@ -0,0 +1,72 @@ +import 'dart:async'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../../core/network/api_exception.dart'; +import '../../device/data/device_providers.dart'; +import '../../device/domain/device_models.dart'; + +// Keep this declaration explicit, as in device_providers.dart: the pinned +// Riverpod generator cannot parse the current Flutter SDK's dot shorthand. +final systemSettingsControllerProvider = NotifierProvider.autoDispose + .family, String>( + SystemSettingsController.new, + ); + +/// 页面级策略状态:先展示缓存,请求期间保留数据并锁定操作。 +class SystemSettingsController + extends AutoDisposeFamilyNotifier, String> { + late String _sn; + bool _active = true; + + @override + AsyncValue build(String sn) { + _sn = sn; + _active = true; + ref.onDispose(() => _active = false); + unawaited(Future.microtask(_load)); + return const AsyncLoading(); + } + + Future _load() async { + final repo = ref.read(deviceRepositoryProvider); + try { + final cached = await repo.getCachedPolicy(_sn); + if (!_active) return; + if (cached != null) { + state = const AsyncLoading().copyWithPrevious( + AsyncData(cached), + ); + } + final policy = await repo.getPolicy(_sn); + if (_active) state = AsyncData(policy); + } catch (error, stack) { + if (_active) state = AsyncError(error, stack); + } + } + + Future toggle(String field, bool enabled) async { + if (state.isLoading || state.valueOrNull == null) return; + final previous = state; + state = const AsyncLoading().copyWithPrevious(previous); + try { + final repo = ref.read(deviceRepositoryProvider); + final error = await repo.togglePolicy(_sn, field, enabled ? 1 : 0); + if (!_active) return; + if (error != null) { + throw ApiException(code: 'policy_toggle', message: error); + } + final policy = await repo.getPolicy(_sn); + if (!_active) return; + state = AsyncData(policy); + ref.invalidate(devicePolicyProvider(_sn)); + } catch (error, stack) { + if (_active) { + state = AsyncError( + error, + stack, + ).copyWithPrevious(previous); + } + } + } +} diff --git a/lib/features/home/presentation/system_settings_page.dart b/lib/features/home/presentation/system_settings_page.dart index aeed981..a895c46 100644 --- a/lib/features/home/presentation/system_settings_page.dart +++ b/lib/features/home/presentation/system_settings_page.dart @@ -6,6 +6,8 @@ import 'package:ttstd_family_care/app/theme/dark_mode.dart'; import 'package:ttstd_family_care/core/widgets/app_page_scaffold.dart'; import '../../../core/widgets/feature_ui.dart'; +import '../../../core/network/error_message.dart'; +import 'system_settings_controller.dart'; import '../../../features/device/data/device_providers.dart'; import '../../../features/device/domain/device_models.dart'; import '../../../features/device/presentation/device_switcher.dart'; @@ -28,46 +30,67 @@ class SystemSettingsPage extends ConsumerWidget { final sn = ref.watch(selectedDeviceSnProvider); final policyAsync = sn == null ? const AsyncValue.data(null) - : ref.watch(devicePolicyProvider(sn)); + : ref.watch(systemSettingsControllerProvider(sn)); final policy = policyAsync.valueOrNull; + final busy = policyAsync.isLoading; + if (sn != null) { + ref.listen(systemSettingsControllerProvider(sn), (previous, next) { + if (next.hasError && previous?.error != next.error) { + _showToast(context, userMessageOf(next.error!)); + } + }); + } return PopScope( canPop: false, onPopInvokedWithResult: (didPop, _) { - if (didPop) return; + if (didPop || busy) return; if (context.canPop()) { context.pop(); } else { context.go('/home'); } }, - child: AppPageScaffold( - navigationBar: CupertinoNavigationBar( - middle: DeviceContextTitle(l10n.ssTitle), - leading: CupertinoButton( - padding: EdgeInsets.zero, - child: const Icon(CupertinoIcons.back), - onPressed: () => context.pop(), - ), - ), - child: SafeArea( - child: policyAsync.when( - loading: () => const Center(child: CupertinoActivityIndicator()), - error: (e, _) => Center( - child: Text(l10n.commonLoadFailed, - style: TextStyle(color: DarkMode.color(context, AppColors.sub))), + child: Stack( + children: [ + AppPageScaffold( + navigationBar: CupertinoNavigationBar( + middle: DeviceContextTitle(l10n.ssTitle), + leading: CupertinoButton( + padding: EdgeInsets.zero, + onPressed: busy ? null : () => context.pop(), + child: const Icon(CupertinoIcons.back), + ), + ), + child: SafeArea( + child: policy != null + ? _buildGroups(context, ref, l10n, sn, policy) + : Center( + child: busy + ? const SizedBox.shrink() + : Text( + l10n.ssLoadFailed, + style: TextStyle( + color: DarkMode.color(context, AppColors.sub), + ), + ), + ), ), - data: (data) { - if (data == null) { - return Center( - child: Text(l10n.ssLoadFailed, - style: TextStyle(color: DarkMode.color(context, AppColors.sub))), - ); - } - return _buildGroups(context, ref, l10n, sn, data); - }, ), - ), + if (busy) ...[ + const Positioned.fill( + child: ModalBarrier(dismissible: false, color: Color(0x55000000)), + ), + const Center( + child: CupertinoPopupSurface( + child: Padding( + padding: EdgeInsets.all(28), + child: CupertinoActivityIndicator(radius: 14), + ), + ), + ), + ], + ], ), ); } @@ -181,54 +204,39 @@ class SystemSettingsPage extends ConsumerWidget { Expanded( child: Text( item.label, - style: TextStyle(fontSize: 14.5, color: DarkMode.color(context, AppColors.ink)), + style: TextStyle( + fontSize: 14.5, + color: DarkMode.color(context, AppColors.ink), + ), ), ), CupertinoSwitch( value: enabled, - activeColor: AppColors.green, - onChanged: (value) => - _onToggle(context, ref, l10n, sn, item.field, value ? 1 : 0), + activeTrackColor: AppColors.green, + onChanged: + sn == null || + ref.watch(systemSettingsControllerProvider(sn)).isLoading + ? null + : (value) => ref + .read(systemSettingsControllerProvider(sn).notifier) + .toggle(item.field, value), ), ], ), ); } - /// 调用 toggle 接口并刷新策略状态。 - Future _onToggle( - BuildContext context, - WidgetRef ref, - AppLocalizations l10n, - String? sn, - String field, - int value, - ) async { - if (sn == null || sn.isEmpty) { - _showToast(context, l10n.opCmdFailed); - return; - } - final error = await ref - .read(deviceRepositoryProvider) - .togglePolicy(sn, field, value); - if (!context.mounted) return; - if (error == null) { - // 成功后仅刷新该策略数据,保证开关状态与后台一致。 - ref.invalidate(devicePolicyProvider(sn)); - } else { - _showToast(context, error); - } - } - /// 轻提示:以 SnackBar 展示结果,避免连续切换时被弹窗打断。 void _showToast(BuildContext context, String message) { ScaffoldMessenger.of(context) ..clearSnackBars() - ..showSnackBar(SnackBar( - content: Text(message), - duration: const Duration(seconds: 2), - behavior: SnackBarBehavior.floating, - )); + ..showSnackBar( + SnackBar( + content: Text(message), + duration: const Duration(seconds: 2), + behavior: SnackBarBehavior.floating, + ), + ); } } diff --git a/lib/features/profile/data/profile_repository_impl.dart b/lib/features/profile/data/profile_repository_impl.dart new file mode 100644 index 0000000..f8d8d33 --- /dev/null +++ b/lib/features/profile/data/profile_repository_impl.dart @@ -0,0 +1,82 @@ +import 'package:dio/dio.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../../../core/network/dio_client.dart'; +import '../../../core/storage/token_storage.dart'; +import '../domain/profile_models.dart'; +import '../domain/profile_repository.dart'; + +part 'profile_repository_impl.g.dart'; + +@riverpod +ProfileRepository profileRepository(ProfileRepositoryRef ref) => + ProfileRepositoryImpl(); + +class ProfileRepositoryImpl implements ProfileRepository { + static const _path = 'v1/client/account/profile'; + final _picker = ImagePicker(); + + UserProfile _parse(dynamic data) { + final profile = UserProfile.fromJson( + Map.from(data as Map), + ); + final avatar = profile.avatar; + if (avatar == null || avatar.isEmpty) return profile; + return profile.copyWith( + avatar: Uri.parse( + DioClient.instance.options.baseUrl, + ).resolve(avatar).toString(), + ); + } + + @override + Future load() async => + _parse(await DioClient.get(_path, allowStale: true)); + + @override + Future save(String nickname, String signature) async { + final profile = _parse( + await DioClient.put( + _path, + data: {'nickname': nickname, 'signature': signature}, + ), + ); + await DioClient.storeReadCache(_path, profile.toJson()); + return profile; + } + + @override + Future chooseAvatar() async { + final version = TokenStorage.sessionVersion; + final image = await _picker.pickImage( + source: ImageSource.gallery, + maxWidth: 1024, + maxHeight: 1024, + imageQuality: 85, + ); + if (image == null || version != TokenStorage.sessionVersion) return null; + if (await image.length() > 5 * 1024 * 1024) { + throw const ProfileInputException(ProfileIssue.avatarTooLarge); + } + final name = image.name.toLowerCase(); + final png = name.endsWith('.png'); + if (!png && !name.endsWith('.jpg') && !name.endsWith('.jpeg')) { + throw const ProfileInputException(ProfileIssue.avatarUnsupported); + } + final bytes = await image.readAsBytes(); + if (version != TokenStorage.sessionVersion) return null; + final data = FormData.fromMap({ + 'file': MultipartFile.fromBytes( + bytes, + filename: png ? 'avatar.png' : 'avatar.jpg', + contentType: DioMediaType('image', png ? 'png' : 'jpeg'), + ), + }); + final profile = _parse( + await DioClient.postMultipart('$_path/avatar', formData: data), + ); + await DioClient.storeReadCache(_path, profile.toJson()); + return profile; + } +} diff --git a/lib/features/profile/data/profile_repository_impl.g.dart b/lib/features/profile/data/profile_repository_impl.g.dart new file mode 100644 index 0000000..65cb87e --- /dev/null +++ b/lib/features/profile/data/profile_repository_impl.g.dart @@ -0,0 +1,28 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'profile_repository_impl.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +String _$profileRepositoryHash() => r'53edb40b05a538aa85e7ff4d1d82072e4c31e5d0'; + +/// See also [profileRepository]. +@ProviderFor(profileRepository) +final profileRepositoryProvider = + AutoDisposeProvider.internal( + profileRepository, + name: r'profileRepositoryProvider', + debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') + ? null + : _$profileRepositoryHash, + dependencies: null, + allTransitiveDependencies: null, + ); + +@Deprecated('Will be removed in 3.0. Use Ref instead') +// ignore: unused_element +typedef ProfileRepositoryRef = AutoDisposeProviderRef; +// ignore_for_file: type=lint +// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member, deprecated_member_use_from_same_package diff --git a/lib/features/profile/domain/profile_models.dart b/lib/features/profile/domain/profile_models.dart new file mode 100644 index 0000000..27392fe --- /dev/null +++ b/lib/features/profile/domain/profile_models.dart @@ -0,0 +1,53 @@ +// Freezed forwards factory parameter annotations to generated fields. +// ignore_for_file: invalid_annotation_target + +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'profile_models.freezed.dart'; +part 'profile_models.g.dart'; + +@freezed +class UserProfile with _$UserProfile { + const UserProfile._(); + + const factory UserProfile({ + @JsonKey(fromJson: _idToString) required String id, + @Default('') String username, + @Default('') String nickname, + @Default('') String signature, + String? avatar, + }) = _UserProfile; + + factory UserProfile.fromJson(Map json) => + _$UserProfileFromJson(json); + + String get displayName => nickname.isNotEmpty ? nickname : username; +} + +String _idToString(Object? value) => value?.toString() ?? ''; + +enum ProfileIssue { + nicknameInvalid, + signatureInvalid, + avatarTooLarge, + avatarUnsupported, +} + +class ProfileInputException implements Exception { + const ProfileInputException(this.issue); + final ProfileIssue issue; +} + +@freezed +class ProfileState with _$ProfileState { + const factory ProfileState({ + UserProfile? profile, + @Default(true) bool loading, + @Default(false) bool saving, + String? alert, + ProfileIssue? issue, + }) = _ProfileState; + + factory ProfileState.fromJson(Map json) => + _$ProfileStateFromJson(json); +} diff --git a/lib/features/profile/domain/profile_models.freezed.dart b/lib/features/profile/domain/profile_models.freezed.dart new file mode 100644 index 0000000..1b8a2a7 --- /dev/null +++ b/lib/features/profile/domain/profile_models.freezed.dart @@ -0,0 +1,535 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'profile_models.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models', +); + +UserProfile _$UserProfileFromJson(Map json) { + return _UserProfile.fromJson(json); +} + +/// @nodoc +mixin _$UserProfile { + @JsonKey(fromJson: _idToString) + String get id => throw _privateConstructorUsedError; + String get username => throw _privateConstructorUsedError; + String get nickname => throw _privateConstructorUsedError; + String get signature => throw _privateConstructorUsedError; + String? get avatar => throw _privateConstructorUsedError; + + /// Serializes this UserProfile to a JSON map. + Map toJson() => throw _privateConstructorUsedError; + + /// Create a copy of UserProfile + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + $UserProfileCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $UserProfileCopyWith<$Res> { + factory $UserProfileCopyWith( + UserProfile value, + $Res Function(UserProfile) then, + ) = _$UserProfileCopyWithImpl<$Res, UserProfile>; + @useResult + $Res call({ + @JsonKey(fromJson: _idToString) String id, + String username, + String nickname, + String signature, + String? avatar, + }); +} + +/// @nodoc +class _$UserProfileCopyWithImpl<$Res, $Val extends UserProfile> + implements $UserProfileCopyWith<$Res> { + _$UserProfileCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of UserProfile + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? username = null, + Object? nickname = null, + Object? signature = null, + Object? avatar = freezed, + }) { + return _then( + _value.copyWith( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as String, + username: null == username + ? _value.username + : username // ignore: cast_nullable_to_non_nullable + as String, + nickname: null == nickname + ? _value.nickname + : nickname // ignore: cast_nullable_to_non_nullable + as String, + signature: null == signature + ? _value.signature + : signature // ignore: cast_nullable_to_non_nullable + as String, + avatar: freezed == avatar + ? _value.avatar + : avatar // ignore: cast_nullable_to_non_nullable + as String?, + ) + as $Val, + ); + } +} + +/// @nodoc +abstract class _$$UserProfileImplCopyWith<$Res> + implements $UserProfileCopyWith<$Res> { + factory _$$UserProfileImplCopyWith( + _$UserProfileImpl value, + $Res Function(_$UserProfileImpl) then, + ) = __$$UserProfileImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({ + @JsonKey(fromJson: _idToString) String id, + String username, + String nickname, + String signature, + String? avatar, + }); +} + +/// @nodoc +class __$$UserProfileImplCopyWithImpl<$Res> + extends _$UserProfileCopyWithImpl<$Res, _$UserProfileImpl> + implements _$$UserProfileImplCopyWith<$Res> { + __$$UserProfileImplCopyWithImpl( + _$UserProfileImpl _value, + $Res Function(_$UserProfileImpl) _then, + ) : super(_value, _then); + + /// Create a copy of UserProfile + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? username = null, + Object? nickname = null, + Object? signature = null, + Object? avatar = freezed, + }) { + return _then( + _$UserProfileImpl( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as String, + username: null == username + ? _value.username + : username // ignore: cast_nullable_to_non_nullable + as String, + nickname: null == nickname + ? _value.nickname + : nickname // ignore: cast_nullable_to_non_nullable + as String, + signature: null == signature + ? _value.signature + : signature // ignore: cast_nullable_to_non_nullable + as String, + avatar: freezed == avatar + ? _value.avatar + : avatar // ignore: cast_nullable_to_non_nullable + as String?, + ), + ); + } +} + +/// @nodoc +@JsonSerializable() +class _$UserProfileImpl extends _UserProfile { + const _$UserProfileImpl({ + @JsonKey(fromJson: _idToString) required this.id, + this.username = '', + this.nickname = '', + this.signature = '', + this.avatar, + }) : super._(); + + factory _$UserProfileImpl.fromJson(Map json) => + _$$UserProfileImplFromJson(json); + + @override + @JsonKey(fromJson: _idToString) + final String id; + @override + @JsonKey() + final String username; + @override + @JsonKey() + final String nickname; + @override + @JsonKey() + final String signature; + @override + final String? avatar; + + @override + String toString() { + return 'UserProfile(id: $id, username: $username, nickname: $nickname, signature: $signature, avatar: $avatar)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$UserProfileImpl && + (identical(other.id, id) || other.id == id) && + (identical(other.username, username) || + other.username == username) && + (identical(other.nickname, nickname) || + other.nickname == nickname) && + (identical(other.signature, signature) || + other.signature == signature) && + (identical(other.avatar, avatar) || other.avatar == avatar)); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode => + Object.hash(runtimeType, id, username, nickname, signature, avatar); + + /// Create a copy of UserProfile + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$UserProfileImplCopyWith<_$UserProfileImpl> get copyWith => + __$$UserProfileImplCopyWithImpl<_$UserProfileImpl>(this, _$identity); + + @override + Map toJson() { + return _$$UserProfileImplToJson(this); + } +} + +abstract class _UserProfile extends UserProfile { + const factory _UserProfile({ + @JsonKey(fromJson: _idToString) required final String id, + final String username, + final String nickname, + final String signature, + final String? avatar, + }) = _$UserProfileImpl; + const _UserProfile._() : super._(); + + factory _UserProfile.fromJson(Map json) = + _$UserProfileImpl.fromJson; + + @override + @JsonKey(fromJson: _idToString) + String get id; + @override + String get username; + @override + String get nickname; + @override + String get signature; + @override + String? get avatar; + + /// Create a copy of UserProfile + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + _$$UserProfileImplCopyWith<_$UserProfileImpl> get copyWith => + throw _privateConstructorUsedError; +} + +ProfileState _$ProfileStateFromJson(Map json) { + return _ProfileState.fromJson(json); +} + +/// @nodoc +mixin _$ProfileState { + UserProfile? get profile => throw _privateConstructorUsedError; + bool get loading => throw _privateConstructorUsedError; + bool get saving => throw _privateConstructorUsedError; + String? get alert => throw _privateConstructorUsedError; + ProfileIssue? get issue => throw _privateConstructorUsedError; + + /// Serializes this ProfileState to a JSON map. + Map toJson() => throw _privateConstructorUsedError; + + /// Create a copy of ProfileState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + $ProfileStateCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $ProfileStateCopyWith<$Res> { + factory $ProfileStateCopyWith( + ProfileState value, + $Res Function(ProfileState) then, + ) = _$ProfileStateCopyWithImpl<$Res, ProfileState>; + @useResult + $Res call({ + UserProfile? profile, + bool loading, + bool saving, + String? alert, + ProfileIssue? issue, + }); + + $UserProfileCopyWith<$Res>? get profile; +} + +/// @nodoc +class _$ProfileStateCopyWithImpl<$Res, $Val extends ProfileState> + implements $ProfileStateCopyWith<$Res> { + _$ProfileStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of ProfileState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? profile = freezed, + Object? loading = null, + Object? saving = null, + Object? alert = freezed, + Object? issue = freezed, + }) { + return _then( + _value.copyWith( + profile: freezed == profile + ? _value.profile + : profile // ignore: cast_nullable_to_non_nullable + as UserProfile?, + loading: null == loading + ? _value.loading + : loading // ignore: cast_nullable_to_non_nullable + as bool, + saving: null == saving + ? _value.saving + : saving // ignore: cast_nullable_to_non_nullable + as bool, + alert: freezed == alert + ? _value.alert + : alert // ignore: cast_nullable_to_non_nullable + as String?, + issue: freezed == issue + ? _value.issue + : issue // ignore: cast_nullable_to_non_nullable + as ProfileIssue?, + ) + as $Val, + ); + } + + /// Create a copy of ProfileState + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $UserProfileCopyWith<$Res>? get profile { + if (_value.profile == null) { + return null; + } + + return $UserProfileCopyWith<$Res>(_value.profile!, (value) { + return _then(_value.copyWith(profile: value) as $Val); + }); + } +} + +/// @nodoc +abstract class _$$ProfileStateImplCopyWith<$Res> + implements $ProfileStateCopyWith<$Res> { + factory _$$ProfileStateImplCopyWith( + _$ProfileStateImpl value, + $Res Function(_$ProfileStateImpl) then, + ) = __$$ProfileStateImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({ + UserProfile? profile, + bool loading, + bool saving, + String? alert, + ProfileIssue? issue, + }); + + @override + $UserProfileCopyWith<$Res>? get profile; +} + +/// @nodoc +class __$$ProfileStateImplCopyWithImpl<$Res> + extends _$ProfileStateCopyWithImpl<$Res, _$ProfileStateImpl> + implements _$$ProfileStateImplCopyWith<$Res> { + __$$ProfileStateImplCopyWithImpl( + _$ProfileStateImpl _value, + $Res Function(_$ProfileStateImpl) _then, + ) : super(_value, _then); + + /// Create a copy of ProfileState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? profile = freezed, + Object? loading = null, + Object? saving = null, + Object? alert = freezed, + Object? issue = freezed, + }) { + return _then( + _$ProfileStateImpl( + profile: freezed == profile + ? _value.profile + : profile // ignore: cast_nullable_to_non_nullable + as UserProfile?, + loading: null == loading + ? _value.loading + : loading // ignore: cast_nullable_to_non_nullable + as bool, + saving: null == saving + ? _value.saving + : saving // ignore: cast_nullable_to_non_nullable + as bool, + alert: freezed == alert + ? _value.alert + : alert // ignore: cast_nullable_to_non_nullable + as String?, + issue: freezed == issue + ? _value.issue + : issue // ignore: cast_nullable_to_non_nullable + as ProfileIssue?, + ), + ); + } +} + +/// @nodoc +@JsonSerializable() +class _$ProfileStateImpl implements _ProfileState { + const _$ProfileStateImpl({ + this.profile, + this.loading = true, + this.saving = false, + this.alert, + this.issue, + }); + + factory _$ProfileStateImpl.fromJson(Map json) => + _$$ProfileStateImplFromJson(json); + + @override + final UserProfile? profile; + @override + @JsonKey() + final bool loading; + @override + @JsonKey() + final bool saving; + @override + final String? alert; + @override + final ProfileIssue? issue; + + @override + String toString() { + return 'ProfileState(profile: $profile, loading: $loading, saving: $saving, alert: $alert, issue: $issue)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ProfileStateImpl && + (identical(other.profile, profile) || other.profile == profile) && + (identical(other.loading, loading) || other.loading == loading) && + (identical(other.saving, saving) || other.saving == saving) && + (identical(other.alert, alert) || other.alert == alert) && + (identical(other.issue, issue) || other.issue == issue)); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode => + Object.hash(runtimeType, profile, loading, saving, alert, issue); + + /// Create a copy of ProfileState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$ProfileStateImplCopyWith<_$ProfileStateImpl> get copyWith => + __$$ProfileStateImplCopyWithImpl<_$ProfileStateImpl>(this, _$identity); + + @override + Map toJson() { + return _$$ProfileStateImplToJson(this); + } +} + +abstract class _ProfileState implements ProfileState { + const factory _ProfileState({ + final UserProfile? profile, + final bool loading, + final bool saving, + final String? alert, + final ProfileIssue? issue, + }) = _$ProfileStateImpl; + + factory _ProfileState.fromJson(Map json) = + _$ProfileStateImpl.fromJson; + + @override + UserProfile? get profile; + @override + bool get loading; + @override + bool get saving; + @override + String? get alert; + @override + ProfileIssue? get issue; + + /// Create a copy of ProfileState + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + _$$ProfileStateImplCopyWith<_$ProfileStateImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/features/profile/domain/profile_models.g.dart b/lib/features/profile/domain/profile_models.g.dart new file mode 100644 index 0000000..29f4272 --- /dev/null +++ b/lib/features/profile/domain/profile_models.g.dart @@ -0,0 +1,52 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'profile_models.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$UserProfileImpl _$$UserProfileImplFromJson(Map json) => + _$UserProfileImpl( + id: _idToString(json['id']), + username: json['username'] as String? ?? '', + nickname: json['nickname'] as String? ?? '', + signature: json['signature'] as String? ?? '', + avatar: json['avatar'] as String?, + ); + +Map _$$UserProfileImplToJson(_$UserProfileImpl instance) => + { + 'id': instance.id, + 'username': instance.username, + 'nickname': instance.nickname, + 'signature': instance.signature, + 'avatar': instance.avatar, + }; + +_$ProfileStateImpl _$$ProfileStateImplFromJson(Map json) => + _$ProfileStateImpl( + profile: json['profile'] == null + ? null + : UserProfile.fromJson(json['profile'] as Map), + loading: json['loading'] as bool? ?? true, + saving: json['saving'] as bool? ?? false, + alert: json['alert'] as String?, + issue: $enumDecodeNullable(_$ProfileIssueEnumMap, json['issue']), + ); + +Map _$$ProfileStateImplToJson(_$ProfileStateImpl instance) => + { + 'profile': instance.profile, + 'loading': instance.loading, + 'saving': instance.saving, + 'alert': instance.alert, + 'issue': _$ProfileIssueEnumMap[instance.issue], + }; + +const _$ProfileIssueEnumMap = { + ProfileIssue.nicknameInvalid: 'nicknameInvalid', + ProfileIssue.signatureInvalid: 'signatureInvalid', + ProfileIssue.avatarTooLarge: 'avatarTooLarge', + ProfileIssue.avatarUnsupported: 'avatarUnsupported', +}; diff --git a/lib/features/profile/domain/profile_repository.dart b/lib/features/profile/domain/profile_repository.dart new file mode 100644 index 0000000..f9f868b --- /dev/null +++ b/lib/features/profile/domain/profile_repository.dart @@ -0,0 +1,7 @@ +import 'profile_models.dart'; + +abstract class ProfileRepository { + Future load(); + Future save(String nickname, String signature); + Future chooseAvatar(); +} diff --git a/lib/features/profile/presentation/profile_avatar.dart b/lib/features/profile/presentation/profile_avatar.dart new file mode 100644 index 0000000..b9a9558 --- /dev/null +++ b/lib/features/profile/presentation/profile_avatar.dart @@ -0,0 +1,44 @@ +import 'package:cupertino_ui/cupertino_ui.dart'; + +import '../../../core/network/cached_network_image.dart'; +import '../../../core/widgets/feature_ui.dart'; + +class ProfileAvatar extends StatelessWidget { + const ProfileAvatar({this.url, this.name = '', this.size = 58, super.key}); + + final String? url; + final String name; + final double size; + + @override + Widget build(BuildContext context) { + final fallback = Center( + child: Text( + name.isEmpty ? 'U' : name.characters.first, + style: TextStyle( + fontSize: size * 0.4, + fontWeight: FontWeight.w700, + color: CupertinoColors.white, + ), + ), + ); + return ClipOval( + child: Container( + width: size, + height: size, + decoration: const BoxDecoration( + gradient: LinearGradient(colors: [AppColors.green, AppColors.blue]), + ), + child: url == null || url!.isEmpty + ? fallback + : Image( + image: cachedNetworkImage(url!), + fit: BoxFit.cover, + frameBuilder: (_, child, frame, synchronous) => + frame == null && !synchronous ? fallback : child, + errorBuilder: (_, _, _) => fallback, + ), + ), + ); + } +} diff --git a/lib/features/profile/presentation/profile_controller.dart b/lib/features/profile/presentation/profile_controller.dart new file mode 100644 index 0000000..227de3d --- /dev/null +++ b/lib/features/profile/presentation/profile_controller.dart @@ -0,0 +1,86 @@ +import 'dart:async'; + +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../../../core/network/error_message.dart'; +import '../data/profile_repository_impl.dart'; +import '../domain/profile_models.dart'; + +part 'profile_controller.g.dart'; + +@riverpod +class ProfileController extends _$ProfileController { + bool _active = true; + int _generation = 0; + + @override + ProfileState build() { + _active = true; + ref.onDispose(() => _active = false); + unawaited(Future.microtask(reload)); + return const ProfileState(); + } + + Future reload() async { + if (!_active || state.saving) return; + final generation = ++_generation; + state = state.copyWith(loading: true, alert: null, issue: null); + try { + final profile = await ref.read(profileRepositoryProvider).load(); + if (_active && generation == _generation) { + state = state.copyWith(profile: profile, loading: false); + } + } catch (_) { + if (_active && generation == _generation) { + state = state.copyWith(loading: false); + } + } + } + + Future save(String nickname, String signature) async { + if (state.saving) return false; + final name = nickname.trim(); + if (name.isEmpty || name.length > 64) { + state = state.copyWith(issue: ProfileIssue.nicknameInvalid); + return false; + } + if (signature.trim().length > 200) { + state = state.copyWith(issue: ProfileIssue.signatureInvalid); + return false; + } + return _write( + () => ref.read(profileRepositoryProvider).save(name, signature.trim()), + ); + } + + Future changeAvatar() async { + await _write(() => ref.read(profileRepositoryProvider).chooseAvatar()); + } + + Future _write(Future Function() action) async { + if (state.saving) return false; + ++_generation; + state = state.copyWith( + saving: true, + loading: false, + alert: null, + issue: null, + ); + try { + final profile = await action(); + if (!_active) return false; + state = state.copyWith(profile: profile ?? state.profile, saving: false); + return profile != null; + } on ProfileInputException catch (error) { + if (_active) state = state.copyWith(saving: false, issue: error.issue); + return false; + } catch (error) { + if (_active) { + state = state.copyWith(saving: false, alert: userMessageOf(error)); + } + return false; + } + } + + void consumeAlert() => state = state.copyWith(alert: null, issue: null); +} diff --git a/lib/features/profile/presentation/profile_controller.g.dart b/lib/features/profile/presentation/profile_controller.g.dart new file mode 100644 index 0000000..be43cc7 --- /dev/null +++ b/lib/features/profile/presentation/profile_controller.g.dart @@ -0,0 +1,26 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'profile_controller.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +String _$profileControllerHash() => r'dbdebff74e6f706416c46f5dff9007f99c67c4ff'; + +/// See also [ProfileController]. +@ProviderFor(ProfileController) +final profileControllerProvider = + AutoDisposeNotifierProvider.internal( + ProfileController.new, + name: r'profileControllerProvider', + debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') + ? null + : _$profileControllerHash, + dependencies: null, + allTransitiveDependencies: null, + ); + +typedef _$ProfileController = AutoDisposeNotifier; +// ignore_for_file: type=lint +// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member, deprecated_member_use_from_same_package diff --git a/lib/features/profile/presentation/profile_edit_page.dart b/lib/features/profile/presentation/profile_edit_page.dart index 4f29cf8..99b1666 100644 --- a/lib/features/profile/presentation/profile_edit_page.dart +++ b/lib/features/profile/presentation/profile_edit_page.dart @@ -1,144 +1,182 @@ import 'package:cupertino_ui/cupertino_ui.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; -import 'package:ttstd_family_care/app/theme/dark_mode.dart'; -import 'package:ttstd_family_care/core/widgets/app_page_scaffold.dart'; +import '../../../app/theme/dark_mode.dart'; +import '../../../core/widgets/app_page_scaffold.dart'; import '../../../core/widgets/feature_ui.dart'; +import '../../../core/widgets/settings_ui.dart'; import '../../../l10n/app_localizations.dart'; +import '../domain/profile_models.dart'; +import 'profile_avatar.dart'; +import 'profile_controller.dart'; -/// 个人资料页(我的 → 编辑资料)。 -/// -/// 头像、昵称、个性签名的独立展示页面;从「我的」页头部的编辑资料入口进入。 -class ProfileEditPage extends StatelessWidget { +class ProfileEditPage extends ConsumerStatefulWidget { const ProfileEditPage({super.key}); @override - Widget build(BuildContext context) { - final l10n = AppLocalizations.of(context); + ConsumerState createState() => _ProfileEditPageState(); +} - return PopScope( - canPop: false, - onPopInvokedWithResult: (didPop, _) { - if (didPop) return; - if (context.canPop()) { - context.pop(); - } else { - context.go('/profile'); - } - }, - child: AppPageScaffold( - navigationBar: CupertinoNavigationBar( - middle: Text(l10n.profileInfo), - leading: CupertinoButton( - padding: EdgeInsets.zero, - child: const Icon(CupertinoIcons.back), - onPressed: () => context.pop(), +class _ProfileEditPageState extends ConsumerState { + final _nickname = TextEditingController(); + final _signature = TextEditingController(); + bool _initialized = false; + + @override + void initState() { + super.initState(); + _fill(ref.read(profileControllerProvider).profile); + } + + void _fill(UserProfile? profile) { + if (_initialized || profile == null) return; + _nickname.text = profile.nickname; + _signature.text = profile.signature; + _initialized = true; + } + + @override + void dispose() { + _nickname.dispose(); + _signature.dispose(); + super.dispose(); + } + + void _alert(String message) { + showCupertinoDialog( + context: context, + builder: (context) => CupertinoAlertDialog( + content: Text(message), + actions: [ + CupertinoDialogAction( + onPressed: () => Navigator.of(context).pop(), + child: Text(AppLocalizations.of(context).commonConfirm), ), - ), - child: SafeArea( - child: ListView( - padding: const EdgeInsets.only(bottom: 24), - children: [ - SectionTitle(l10n.profileInfo), - CardBox( - padding: EdgeInsets.zero, - child: Column( - children: [ - _infoRow( - context, - '🖼️', - AppColors.purple, - l10n.piAvatar, - const _AvatarPreview(), - ), - const AppDivider(), - _infoRow( - context, - '📛', - AppColors.blue, - l10n.piName, - const Text('用户名'), - ), - const AppDivider(), - _infoRow( - context, - '✍️', - AppColors.orange, - l10n.piSign, - const Text('热爱生活'), - ), - ], - ), - ), - ], - ), - ), + ], ), ); } - Widget _infoRow( - BuildContext context, - String emoji, - Color color, - String label, - Widget trailing, - ) => - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), - child: Row( - children: [ - Container( - width: 36, - height: 36, - decoration: - BoxDecoration(color: color, borderRadius: BorderRadius.circular(11)), - child: Center(child: Text(emoji, style: const TextStyle(fontSize: 17))), - ), - const SizedBox(width: 12), - Text( - label, - style: TextStyle( - fontSize: 14.5, - fontWeight: FontWeight.w600, - color: DarkMode.color(context, AppColors.ink), - ), - ), - const Spacer(), - DefaultTextStyle.merge( - style: TextStyle(fontSize: 13, color: DarkMode.color(context, AppColors.sub)), - child: trailing, - ), - ], - ), - ); -} - -/// 资料页头像预览(与「我的」页头部样式一致)。 -class _AvatarPreview extends StatelessWidget { - const _AvatarPreview(); - @override - Widget build(BuildContext context) => Container( - width: 34, - height: 34, - decoration: const BoxDecoration( - shape: BoxShape.circle, - gradient: LinearGradient( - colors: [AppColors.green, AppColors.blue], - begin: Alignment.topLeft, - end: Alignment.bottomRight, - ), + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context); + final state = ref.watch(profileControllerProvider); + ref.listen(profileControllerProvider, (previous, next) { + _fill(next.profile); + if (next.alert == null && next.issue == null) return; + final message = switch (next.issue) { + ProfileIssue.nicknameInvalid => l10n.profileNicknameInvalid, + ProfileIssue.signatureInvalid => l10n.profileSignatureInvalid, + ProfileIssue.avatarTooLarge => l10n.profileAvatarTooLarge, + ProfileIssue.avatarUnsupported => l10n.profileAvatarUnsupported, + null => next.alert!, + }; + ref.read(profileControllerProvider.notifier).consumeAlert(); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) _alert(message); + }); + }); + final profile = state.profile; + return AppPageScaffold( + navigationBar: CupertinoNavigationBar( + middle: Text(l10n.profileEdit), + leading: CupertinoButton( + padding: EdgeInsets.zero, + onPressed: state.saving ? null : () => context.pop(), + child: const Icon(CupertinoIcons.back), ), - child: const Center( - child: Text( - 'U', - style: TextStyle( - fontSize: 15, - fontWeight: FontWeight.w700, - color: CupertinoColors.white, - ), - ), + trailing: CupertinoButton( + padding: EdgeInsets.zero, + onPressed: state.saving || profile == null + ? null + : () async { + final saved = await ref + .read(profileControllerProvider.notifier) + .save(_nickname.text, _signature.text); + if (saved && context.mounted) context.pop(); + }, + child: state.saving + ? const CupertinoActivityIndicator() + : Text(l10n.commonSave), ), - ); -} \ No newline at end of file + ), + child: SafeArea( + child: profile == null + ? Center( + child: state.loading + ? const CupertinoActivityIndicator() + : CupertinoButton( + onPressed: ref + .read(profileControllerProvider.notifier) + .reload, + child: Text(l10n.commonRetry), + ), + ) + : ListView( + padding: const EdgeInsets.only(top: 16, bottom: 32), + children: [ + Center( + child: CupertinoButton( + onPressed: state.saving + ? null + : ref + .read(profileControllerProvider.notifier) + .changeAvatar, + child: Column( + children: [ + ProfileAvatar( + url: profile.avatar, + name: profile.displayName, + size: 84, + ), + const SizedBox(height: 10), + Text(l10n.profileChangeAvatar), + ], + ), + ), + ), + LabeledField( + label: l10n.piName, + controller: _nickname, + maxLength: 64, + enabled: !state.saving, + ), + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 8, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + l10n.piSign, + style: TextStyle( + color: DarkMode.color(context, AppColors.sub), + ), + ), + const SizedBox(height: 6), + CupertinoTextField( + controller: _signature, + maxLength: 200, + maxLines: 3, + enabled: !state.saving, + padding: const EdgeInsets.all(14), + style: TextStyle( + color: DarkMode.color(context, AppColors.ink), + ), + decoration: BoxDecoration( + color: DarkMode.color(context, AppColors.card), + borderRadius: BorderRadius.circular(12), + ), + ), + ], + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/features/profile/presentation/profile_tab.dart b/lib/features/profile/presentation/profile_tab.dart index 6efcdd0..16f2f48 100644 --- a/lib/features/profile/presentation/profile_tab.dart +++ b/lib/features/profile/presentation/profile_tab.dart @@ -9,6 +9,8 @@ import '../../../features/device/data/device_providers.dart'; import '../../../features/device/domain/device_models.dart'; import '../../../l10n/app_localizations.dart'; import '../../auth/presentation/auth_controller.dart'; +import 'profile_avatar.dart'; +import 'profile_controller.dart'; /// 我的 Tab 内容(特性模块:profile / presentation)。 /// @@ -20,6 +22,8 @@ class ProfileTab extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final l10n = AppLocalizations.of(context); + final profileState = ref.watch(profileControllerProvider); + final profile = profileState.profile; return AppPageScaffold( child: SafeArea( @@ -31,23 +35,30 @@ class ProfileTab extends ConsumerWidget { padding: const EdgeInsets.all(18), child: Row( children: [ - Container( - width: 58, - height: 58, - decoration: const BoxDecoration( - shape: BoxShape.circle, - gradient: LinearGradient( - colors: [AppColors.green, AppColors.blue], - begin: Alignment.topLeft, - end: Alignment.bottomRight, - ), - ), - child: const Center( - child: Text('U', - style: TextStyle( - fontSize: 24, - fontWeight: FontWeight.w700, - color: CupertinoColors.white)), + GestureDetector( + onTap: profileState.saving + ? null + : () => context.push('/profile/edit'), + child: Stack( + alignment: Alignment.center, + children: [ + ProfileAvatar( + url: profile?.avatar, + name: profile?.displayName ?? '', + ), + if (profileState.loading && profile == null) + const Positioned.fill( + child: DecoratedBox( + decoration: BoxDecoration( + color: Color(0x55000000), + shape: BoxShape.circle, + ), + child: CupertinoActivityIndicator( + color: CupertinoColors.white, + ), + ), + ), + ], ), ), const SizedBox(width: 14), @@ -55,33 +66,70 @@ class ProfileTab extends ConsumerWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text('用户名', - style: TextStyle( - fontSize: 17, - fontWeight: FontWeight.w700, - color: DarkMode.color(context, AppColors.ink))), + Text( + profile?.displayName.isNotEmpty == true + ? profile!.displayName + : l10n.piName, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 17, + fontWeight: FontWeight.w700, + color: DarkMode.color(context, AppColors.ink), + ), + ), const SizedBox(height: 4), - Text('ID: u_8821 · 平板管家 Pro', + Text( + profile == null ? '' : 'ID: ${profile.id}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 12.5, + color: DarkMode.color(context, AppColors.sub), + ), + ), + const SizedBox(height: 4), + // Reserve two signature lines before the profile arrives. + SizedBox( + height: + (MediaQuery.textScalerOf(context).scale(12) * 1.3) + .ceilToDouble() * + 2, + child: Text( + profile?.signature ?? '', + maxLines: 2, + overflow: TextOverflow.ellipsis, style: TextStyle( - fontSize: 12.5, - color: DarkMode.color(context, AppColors.sub))), + fontSize: 12, + height: 1.3, + color: DarkMode.color(context, AppColors.sub), + ), + ), + ), ], ), ), GestureDetector( - onTap: () => context.push('/profile/edit'), + onTap: profileState.saving + ? null + : () => context.push('/profile/edit'), child: Container( - padding: - const EdgeInsets.symmetric(horizontal: 14, vertical: 7), + padding: const EdgeInsets.symmetric( + horizontal: 14, + vertical: 7, + ), decoration: BoxDecoration( color: AppColors.green.withValues(alpha: 0.12), borderRadius: BorderRadius.circular(20), ), - child: Text(l10n.profileEdit, - style: const TextStyle( - fontSize: 12.5, - fontWeight: FontWeight.w600, - color: AppColors.green)), + child: Text( + l10n.profileEdit, + style: const TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w600, + color: AppColors.green, + ), + ), ), ), ], @@ -100,16 +148,40 @@ class ProfileTab extends ConsumerWidget { padding: EdgeInsets.zero, child: Column( children: [ - _settingRow(context, '🔔', AppColors.teal, l10n.setNotify, '消息、设备状态提醒'), + _settingRow( + context, + '🔔', + AppColors.teal, + l10n.setNotify, + '消息、设备状态提醒', + ), const AppDivider(), - _settingRow(context, '🔒', const Color(0xFF22C55E), l10n.setPrivacy, '定位、相册、权限管理'), + _settingRow( + context, + '🔒', + const Color(0xFF22C55E), + l10n.setPrivacy, + '定位、相册、权限管理', + ), const AppDivider(), - _settingRow(context, '🛡️', AppColors.red, l10n.setSecurity, '登录设备、密码', - onTap: () => context.push('/security')), + _settingRow( + context, + '🛡️', + AppColors.red, + l10n.setSecurity, + '登录设备、密码', + onTap: () => context.push('/security'), + ), const AppDivider(), _settingRow(context, '❓', AppColors.gray, l10n.setHelp, null), const AppDivider(), - _settingRow(context, 'ℹ️', const Color(0xFF64748B), l10n.setAbout, '平板管家 v3.2.1'), + _settingRow( + context, + 'ℹ️', + const Color(0xFF64748B), + l10n.setAbout, + '平板管家 v3.2.1', + ), ], ), ), @@ -126,7 +198,11 @@ class ProfileTab extends ConsumerWidget { color: DarkMode.color(context, AppColors.card), borderRadius: BorderRadius.circular(14), boxShadow: const [ - BoxShadow(color: Color(0x14141E3C), blurRadius: 16, offset: Offset(0, 4)), + BoxShadow( + color: Color(0x14141E3C), + blurRadius: 16, + offset: Offset(0, 4), + ), ], ), child: Center( @@ -152,7 +228,10 @@ class ProfileTab extends ConsumerWidget { } Widget _boundDeviceCard( - BuildContext context, WidgetRef ref, AppLocalizations l10n) { + BuildContext context, + WidgetRef ref, + AppLocalizations l10n, + ) { final devicesAsync = ref.watch(myDevicesProvider); final device = ref.watch(currentDeviceProvider); return CardBox( @@ -162,116 +241,221 @@ class ProfileTab extends ConsumerWidget { begin: Alignment.topLeft, end: Alignment.bottomRight, ), - child: devicesAsync.when( - loading: () => const Padding( - padding: EdgeInsets.symmetric(vertical: 24), - child: Center(child: CupertinoActivityIndicator()), - ), - error: (e, _) => Padding( - padding: const EdgeInsets.all(16), - child: Text('${l10n.deviceLoadFailed}:$e', - style: TextStyle(fontSize: 12, color: DarkMode.color(context, AppColors.sub))), - ), - data: (_) { - if (device == null) { - // 无绑定设备时也可点击进入设备管理页添加设备。 + child: SizedBox( + height: + 28 + + ((MediaQuery.textScalerOf(context).scale(14.5) * 1.3) + .ceilToDouble() + + 2 + + (MediaQuery.textScalerOf(context).scale(12) * 1.3) + .ceilToDouble()) + .clamp(36.0, double.infinity), + child: devicesAsync.when( + loading: () => const Padding( + padding: EdgeInsets.symmetric(vertical: 24), + child: Center(child: CupertinoActivityIndicator()), + ), + error: (e, _) => Padding( + padding: const EdgeInsets.all(16), + child: Text( + '${l10n.deviceLoadFailed}:$e', + style: TextStyle( + fontSize: 12, + color: DarkMode.color(context, AppColors.sub), + ), + ), + ), + data: (_) { + if (device == null) { + // 无绑定设备时也可点击进入设备管理页添加设备。 + return GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () => context.push('/device/manage'), + child: Padding( + padding: const EdgeInsets.all(16), + child: Row( + children: [ + Expanded( + child: Text( + l10n.deviceNone, + style: TextStyle( + fontSize: 13, + color: DarkMode.color(context, AppColors.sub), + ), + ), + ), + Text( + '${l10n.deviceManageAdd} ›', + style: const TextStyle( + fontSize: 13, + color: AppColors.green, + ), + ), + ], + ), + ), + ); + } return GestureDetector( behavior: HitTestBehavior.opaque, onTap: () => context.push('/device/manage'), - child: Padding( - padding: const EdgeInsets.all(16), - child: Row( - children: [ - Expanded( - child: Text(l10n.deviceNone, - style: TextStyle(fontSize: 13, color: DarkMode.color(context, AppColors.sub))), - ), - Text('${l10n.deviceManageAdd} ›', - style: const TextStyle(fontSize: 13, color: AppColors.green)), - ], - ), - ), + child: _deviceCard(context, device, l10n), ); - } - return GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () => context.push('/device/manage'), - child: _deviceCard(context, device, l10n), - ); - }, + }, + ), ), ); } - Widget _deviceCard(BuildContext context, DeviceBrief device, AppLocalizations l10n) { + Widget _deviceCard( + BuildContext context, + DeviceBrief device, + AppLocalizations l10n, + ) { final status = device.isOnline ? l10n.deviceOnline : l10n.deviceOffline; final sub = device.snModel?.isNotEmpty == true ? '$status · ${device.snModel}' : status; - return _deviceRow(context, '📱', - device.isOnline ? AppColors.green : DarkMode.color(context, AppColors.track), - device.snName?.isNotEmpty == true ? device.snName! : device.serialno, sub, - l10n.deviceManage); + return _deviceRow( + context, + '📱', + device.isOnline + ? AppColors.green + : DarkMode.color(context, AppColors.track), + device.snName?.isNotEmpty == true ? device.snName! : device.serialno, + sub, + l10n.deviceManage, + ); } - Widget _deviceRow(BuildContext context, String emoji, Color color, String title, String sub, String? action) => Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), - child: Row( - children: [ - Container( - width: 36, - height: 36, - decoration: BoxDecoration(color: color, borderRadius: BorderRadius.circular(11)), - child: Center(child: Text(emoji, style: const TextStyle(fontSize: 17))), - ), - const SizedBox(width: 12), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(title, style: TextStyle(fontSize: 14.5, fontWeight: FontWeight.w600, color: DarkMode.color(context, AppColors.ink))), - const SizedBox(height: 2), - Text(sub, style: TextStyle(fontSize: 12, color: DarkMode.color(context, AppColors.sub))), - ], - ), - ), - if (action != null) - Text('$action ›', style: TextStyle(fontSize: 13, color: DarkMode.color(context, AppColors.sub))) - else - const Text('›', style: TextStyle(fontSize: 16, color: Color(0xFFCBD2DC))), - ], + Widget _deviceRow( + BuildContext context, + String emoji, + Color color, + String title, + String sub, + String? action, + ) => Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), + child: Row( + children: [ + Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: color, + borderRadius: BorderRadius.circular(11), + ), + child: Center( + child: Text(emoji, style: const TextStyle(fontSize: 17)), + ), ), - ); + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 14.5, + height: 1.3, + fontWeight: FontWeight.w600, + color: DarkMode.color(context, AppColors.ink), + ), + ), + const SizedBox(height: 2), + Text( + sub, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 12, + height: 1.3, + color: DarkMode.color(context, AppColors.sub), + ), + ), + ], + ), + ), + if (action != null) + Text( + '$action ›', + style: TextStyle( + fontSize: 13, + color: DarkMode.color(context, AppColors.sub), + ), + ) + else + const Text( + '›', + style: TextStyle(fontSize: 16, color: Color(0xFFCBD2DC)), + ), + ], + ), + ); - Widget _settingRow(BuildContext context, String emoji, Color color, String label, String? sub, - {VoidCallback? onTap}) { + Widget _settingRow( + BuildContext context, + String emoji, + Color color, + String label, + String? sub, { + VoidCallback? onTap, + }) { final row = Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 13), - child: Row( - children: [ - Container( - width: 36, - height: 36, - decoration: BoxDecoration(color: color, borderRadius: BorderRadius.circular(11)), - child: Center(child: Text(emoji, style: const TextStyle(fontSize: 17))), + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 13), + child: Row( + children: [ + Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: color, + borderRadius: BorderRadius.circular(11), ), - const SizedBox(width: 12), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(label, style: TextStyle(fontSize: 14.5, fontWeight: FontWeight.w600, color: DarkMode.color(context, AppColors.ink))), - if (sub != null) ...[ - const SizedBox(height: 2), - Text(sub, style: TextStyle(fontSize: 12, color: DarkMode.color(context, AppColors.sub))), - ], + child: Center( + child: Text(emoji, style: const TextStyle(fontSize: 17)), + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: TextStyle( + fontSize: 14.5, + fontWeight: FontWeight.w600, + color: DarkMode.color(context, AppColors.ink), + ), + ), + if (sub != null) ...[ + const SizedBox(height: 2), + Text( + sub, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 12, + height: 1.3, + color: DarkMode.color(context, AppColors.sub), + ), + ), ], - ), + ], ), - const Text('›', style: TextStyle(fontSize: 16, color: Color(0xFFCBD2DC))), - ], - ), - ); + ), + const Text( + '›', + style: TextStyle(fontSize: 16, color: Color(0xFFCBD2DC)), + ), + ], + ), + ); if (onTap == null) return row; return GestureDetector( behavior: HitTestBehavior.opaque, diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index eae1f0c..3cec067 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -2287,6 +2287,36 @@ abstract class AppLocalizations { /// In zh, this message translates to: /// **'当前平台暂不支持该功能'** String get featureUnsupported; + + /// No description provided for @profileChangeAvatar. + /// + /// In zh, this message translates to: + /// **'更换头像'** + String get profileChangeAvatar; + + /// No description provided for @profileNicknameInvalid. + /// + /// In zh, this message translates to: + /// **'昵称须为1至64个字符'** + String get profileNicknameInvalid; + + /// No description provided for @profileSignatureInvalid. + /// + /// In zh, this message translates to: + /// **'个性签名不能超过200个字符'** + String get profileSignatureInvalid; + + /// No description provided for @profileAvatarTooLarge. + /// + /// In zh, this message translates to: + /// **'请选择不超过5MB的头像图片'** + String get profileAvatarTooLarge; + + /// No description provided for @profileAvatarUnsupported. + /// + /// In zh, this message translates to: + /// **'头像仅支持JPEG或PNG图片'** + String get profileAvatarUnsupported; } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 3dde15d..46e7604 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1144,4 +1144,20 @@ class AppLocalizationsEn extends AppLocalizations { @override String get featureUnsupported => 'This feature is not supported on this platform yet'; + + @override + String get profileChangeAvatar => 'Change avatar'; + + @override + String get profileNicknameInvalid => 'Enter a nickname with 1–64 characters'; + + @override + String get profileSignatureInvalid => + 'Your signature must be 200 characters or fewer'; + + @override + String get profileAvatarTooLarge => 'Choose an avatar no larger than 5 MB'; + + @override + String get profileAvatarUnsupported => 'Choose a JPEG or PNG image'; } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index c6b2d4a..f863c7d 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1118,4 +1118,19 @@ class AppLocalizationsZh extends AppLocalizations { @override String get featureUnsupported => '当前平台暂不支持该功能'; + + @override + String get profileChangeAvatar => '更换头像'; + + @override + String get profileNicknameInvalid => '昵称须为1至64个字符'; + + @override + String get profileSignatureInvalid => '个性签名不能超过200个字符'; + + @override + String get profileAvatarTooLarge => '请选择不超过5MB的头像图片'; + + @override + String get profileAvatarUnsupported => '头像仅支持JPEG或PNG图片'; } diff --git a/lib/l10n/intl_en.arb b/lib/l10n/intl_en.arb index 0524832..b629c21 100644 --- a/lib/l10n/intl_en.arb +++ b/lib/l10n/intl_en.arb @@ -376,5 +376,10 @@ "commonRetry": "Retry", "commonLoadFailed": "Failed to load", "albumLoadMore": "Load more", - "featureUnsupported": "This feature is not supported on this platform yet" + "featureUnsupported": "This feature is not supported on this platform yet", + "profileChangeAvatar": "Change avatar", + "profileNicknameInvalid": "Enter a nickname with 1–64 characters", + "profileSignatureInvalid": "Your signature must be 200 characters or fewer", + "profileAvatarTooLarge": "Choose an avatar no larger than 5 MB", + "profileAvatarUnsupported": "Choose a JPEG or PNG image" } diff --git a/lib/l10n/intl_zh.arb b/lib/l10n/intl_zh.arb index 74d6b4d..b9476dc 100644 --- a/lib/l10n/intl_zh.arb +++ b/lib/l10n/intl_zh.arb @@ -1489,5 +1489,10 @@ "featureUnsupported": "当前平台暂不支持该功能", "@featureUnsupported": { "description": "通用:当前平台不支持该功能" - } + }, + "profileChangeAvatar": "更换头像", + "profileNicknameInvalid": "昵称须为1至64个字符", + "profileSignatureInvalid": "个性签名不能超过200个字符", + "profileAvatarTooLarge": "请选择不超过5MB的头像图片", + "profileAvatarUnsupported": "头像仅支持JPEG或PNG图片" } diff --git a/test/core/network/dio_client_test.dart b/test/core/network/dio_client_test.dart index d1b677e..6689b5a 100644 --- a/test/core/network/dio_client_test.dart +++ b/test/core/network/dio_client_test.dart @@ -71,8 +71,10 @@ void main() { var code = '00000'; String? message; var offline = false; + var requests = 0; DioClient.useAdapterForTesting( FakeAdapter((options) async { + requests++; if (offline) { throw DioException( requestOptions: options, @@ -91,6 +93,12 @@ void main() { await signIn(1); expect(await read(), ['previous']); + final beforeCacheRead = requests; + expect(await DioClient.readCachedGet('devices', + queryParameters: {'sn': 'one'}), ['previous']); + expect(await DioClient.readCachedGet('devices', + queryParameters: {'sn': 'two'}), isNull); + expect(requests, beforeCacheRead); await signIn(1); offline = true; expect(await read(), ['previous']); @@ -104,6 +112,8 @@ void main() { message = '系统执行出错'; expect(await read(), ['previous']); await signIn(2); + expect(await DioClient.readCachedGet('devices', + queryParameters: {'sn': 'one'}), isNull); await expectLater(read(), throwsA(isA())); await signIn(1); status = 403; diff --git a/test/features/home/home_tab_pager_test.dart b/test/features/home/home_tab_pager_test.dart index 088abbe..4fa8408 100644 --- a/test/features/home/home_tab_pager_test.dart +++ b/test/features/home/home_tab_pager_test.dart @@ -46,6 +46,24 @@ void main() { await tester.pump(); expect(tester.getCenter(home).dx, lessThan(initialX)); expect(router.routeInformationProvider.value.uri.path, '/home'); + expect( + tester.widget(find.byType(GlassTabBar)).selectedIndex, + 1, + ); + + // Reversing an unfinished swipe must restore the bar immediately. + await gesture.moveBy(const Offset(200, 0)); + await tester.pump(); + expect( + tester.widget(find.byType(GlassTabBar)).selectedIndex, + 0, + ); + await gesture.moveBy(const Offset(-200, 0)); + await tester.pump(); + expect( + tester.widget(find.byType(GlassTabBar)).selectedIndex, + 1, + ); await gesture.up(); await tester.pumpAndSettle(); @@ -65,6 +83,10 @@ void main() { await tester.pump(); expect(tester.getCenter(profile).dx, greaterThan(initialX)); expect(router.routeInformationProvider.value.uri.path, '/profile'); + expect( + tester.widget(find.byType(GlassTabBar)).selectedIndex, + 1, + ); await tester.pump(const Duration(milliseconds: 200)); await tabDrag.up(); diff --git a/test/features/home/system_settings_controller_test.dart b/test/features/home/system_settings_controller_test.dart new file mode 100644 index 0000000..68e1b0e --- /dev/null +++ b/test/features/home/system_settings_controller_test.dart @@ -0,0 +1,91 @@ +import 'dart:async'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ttstd_family_care/features/device/data/device_api.dart'; +import 'package:ttstd_family_care/features/device/data/device_providers.dart'; +import 'package:ttstd_family_care/features/device/data/device_repository_impl.dart'; +import 'package:ttstd_family_care/features/device/domain/device_models.dart'; +import 'package:ttstd_family_care/features/home/presentation/system_settings_controller.dart'; + +class _Repository extends DeviceRepositoryImpl { + _Repository() : super(const DeviceApi()); + DevicePolicy? cached = const DevicePolicy(bluetooth: 1); + Completer response = Completer(); + Completer saved = Completer(); + int writes = 0; + + @override + Future getCachedPolicy(String sn) async => cached; + + @override + Future getPolicy(String sn) => response.future; + + @override + Future togglePolicy(String sn, String field, int value) { + writes++; + return saved.future; + } +} + +void main() { + late _Repository repository; + late ProviderContainer container; + final provider = systemSettingsControllerProvider('device-one'); + + setUp(() { + repository = _Repository(); + container = ProviderContainer(overrides: [ + deviceRepositoryProvider.overrideWithValue(repository), + ]); + container.listen(provider, (_, _) {}); + }); + tearDown(() => container.dispose()); + + test('cached switches remain visible and locked until network completes', () async { + await pumpEventQueue(); + expect(container.read(provider).valueOrNull?.bluetooth, 1); + expect(container.read(provider).isLoading, isTrue); + await container.read(provider.notifier).toggle('bluetooth', false); + expect(repository.writes, 0); + repository.response.complete(const DevicePolicy(bluetooth: 0)); + await pumpEventQueue(); + expect(container.read(provider).isLoading, isFalse); + expect(container.read(provider).valueOrNull?.bluetooth, 0); + }); + + test('save and refresh stay locked and reject duplicate toggles', () async { + repository.response.complete(const DevicePolicy(bluetooth: 1)); + await pumpEventQueue(); + repository.response = Completer(); + final pending = container.read(provider.notifier).toggle('bluetooth', false); + await container.read(provider.notifier).toggle('bluetooth', false); + expect(repository.writes, 1); + repository.saved.complete(null); + await pumpEventQueue(); + expect(container.read(provider).isLoading, isTrue); + repository.response.complete(const DevicePolicy(bluetooth: 0)); + await pending; + expect(container.read(provider).isLoading, isFalse); + expect(container.read(provider).valueOrNull?.bluetooth, 0); + }); + + test('failed load unlocks and clears cached switches', () async { + await pumpEventQueue(); + repository.response.complete(null); + await pumpEventQueue(); + expect(container.read(provider).isLoading, isFalse); + expect(container.read(provider).valueOrNull, isNull); + }); + + test('failed save unlocks with previous switches and exposes error', () async { + repository.response.complete(const DevicePolicy(bluetooth: 1)); + await pumpEventQueue(); + final pending = container.read(provider.notifier).toggle('bluetooth', false); + repository.saved.complete('保存失败'); + await pending; + expect(container.read(provider).isLoading, isFalse); + expect(container.read(provider).hasError, isTrue); + expect(container.read(provider).valueOrNull?.bluetooth, 1); + }); +} diff --git a/test/features/profile/profile_controller_test.dart b/test/features/profile/profile_controller_test.dart new file mode 100644 index 0000000..65c0066 --- /dev/null +++ b/test/features/profile/profile_controller_test.dart @@ -0,0 +1,83 @@ +import 'dart:async'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ttstd_family_care/core/network/api_exception.dart'; +import 'package:ttstd_family_care/features/profile/data/profile_repository_impl.dart'; +import 'package:ttstd_family_care/features/profile/domain/profile_models.dart'; +import 'package:ttstd_family_care/features/profile/domain/profile_repository.dart'; +import 'package:ttstd_family_care/features/profile/presentation/profile_controller.dart'; + +class FakeProfileRepository implements ProfileRepository { + final pendingLoad = Completer(); + bool failSave = false; + int saves = 0; + + @override + Future load() => pendingLoad.future; + + @override + Future save(String nickname, String signature) async { + saves++; + if (failSave) throw const ApiException(code: '400', message: 'Save failed'); + return UserProfile(id: '7', nickname: nickname, signature: signature); + } + + @override + Future chooseAvatar() async => null; +} + +void main() { + test( + 'late loads cannot overwrite saved profile, failed saves retain data', + () async { + final repository = FakeProfileRepository(); + final container = ProviderContainer( + overrides: [profileRepositoryProvider.overrideWithValue(repository)], + ); + addTearDown(container.dispose); + container.listen(profileControllerProvider, (_, _) {}); + await Future.delayed(Duration.zero); + final controller = container.read(profileControllerProvider.notifier); + + expect(await controller.save(' 家人 ', ' 你好 '), isTrue); + repository.pendingLoad.complete( + const UserProfile(id: '7', nickname: 'old'), + ); + await Future.delayed(Duration.zero); + expect(container.read(profileControllerProvider).profile?.nickname, '家人'); + expect( + container.read(profileControllerProvider).profile?.signature, + '你好', + ); + + await controller.changeAvatar(); + expect(container.read(profileControllerProvider).profile?.nickname, '家人'); + expect(container.read(profileControllerProvider).saving, isFalse); + + repository.failSave = true; + expect(await controller.save('new', ''), isFalse); + expect(container.read(profileControllerProvider).profile?.nickname, '家人'); + expect(container.read(profileControllerProvider).alert, 'Save failed'); + + final calls = repository.saves; + expect(await controller.save(' ', ''), isFalse); + expect(repository.saves, calls); + expect( + container.read(profileControllerProvider).issue, + ProfileIssue.nicknameInvalid, + ); + }, + ); + + test('numeric user IDs and absent optional profile fields decode', () { + final profile = UserProfile.fromJson({ + 'id': 7, + 'nickname': null, + 'signature': null, + }); + expect(profile.id, '7'); + expect(profile.nickname, ''); + expect(profile.signature, ''); + }); +} diff --git a/test/features/profile/profile_edit_test.dart b/test/features/profile/profile_edit_test.dart new file mode 100644 index 0000000..8e14b4d --- /dev/null +++ b/test/features/profile/profile_edit_test.dart @@ -0,0 +1,135 @@ +import 'dart:async'; + +import 'package:cupertino_ui/cupertino_ui.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:go_router/go_router.dart'; +import 'package:ttstd_family_care/app/app.dart'; +import 'package:ttstd_family_care/features/device/data/device_providers.dart'; +import 'package:ttstd_family_care/features/device/domain/device_models.dart'; +import 'package:ttstd_family_care/features/profile/data/profile_repository_impl.dart'; +import 'package:ttstd_family_care/features/profile/domain/profile_models.dart'; +import 'package:ttstd_family_care/features/profile/domain/profile_repository.dart'; +import 'package:ttstd_family_care/features/profile/presentation/profile_edit_page.dart'; +import 'package:ttstd_family_care/features/profile/presentation/profile_tab.dart'; +import 'package:ttstd_family_care/l10n/app_localizations.dart'; + +class _ProfileRepository implements ProfileRepository { + Completer? pendingLoad; + UserProfile profile = const UserProfile(id: '7', nickname: 'Old name'); + + @override + Future load() async => + pendingLoad == null ? profile : await pendingLoad!.future; + + @override + Future save(String nickname, String signature) async { + profile = profile.copyWith(nickname: nickname, signature: signature); + return profile; + } + + @override + Future chooseAvatar() async => null; +} + +void main() { + for (final signature in ['', 'First line\nSecond line\nMore text']) { + testWidgets( + 'profile and devices load without shifting sections ($signature)', + (tester) async { + final repository = _ProfileRepository() + ..pendingLoad = Completer(); + final devices = Completer>(); + final router = GoRouter( + routes: [GoRoute(path: '/', builder: (_, _) => const ProfileTab())], + ); + addTearDown(router.dispose); + await tester.pumpWidget( + ProviderScope( + overrides: [ + profileRepositoryProvider.overrideWithValue(repository), + myDevicesProvider.overrideWith((_) => devices.future), + ], + child: App(router: router), + ), + ); + await tester.pump(); + final l10n = AppLocalizations.of( + tester.element(find.byType(ProfileTab)), + ); + final boundBefore = tester.getTopLeft(find.text(l10n.deviceBound)); + final settingsBefore = tester.getTopLeft(find.text(l10n.settingsTitle)); + repository.pendingLoad!.complete( + UserProfile( + id: '123456789012345678901234567890', + nickname: 'A very long nickname that must stay on one line', + signature: signature, + ), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + expect(tester.getTopLeft(find.text(l10n.deviceBound)), boundBefore); + expect( + tester.getTopLeft(find.text(l10n.settingsTitle)), + settingsBefore, + ); + devices.complete([ + const DeviceBrief( + serialno: 'one', + snName: 'A very long device name that stays on one line', + snModel: 'Tablet model', + online: 1, + ), + ]); + await tester.pumpAndSettle(); + expect( + tester.getTopLeft(find.text(l10n.settingsTitle)), + settingsBefore, + ); + expect(tester.takeException(), isNull); + }, + ); + } + + testWidgets('editing from profile updates the header after saving', ( + tester, + ) async { + final repository = _ProfileRepository(); + final router = GoRouter( + initialLocation: '/profile', + routes: [ + GoRoute(path: '/profile', builder: (_, _) => const ProfileTab()), + GoRoute( + path: '/profile/edit', + builder: (_, _) => const ProfileEditPage(), + ), + ], + ); + addTearDown(router.dispose); + await tester.pumpWidget( + ProviderScope( + overrides: [ + profileRepositoryProvider.overrideWithValue(repository), + myDevicesProvider.overrideWith((_) async => []), + ], + child: App(router: router), + ), + ); + await tester.pumpAndSettle(); + expect(find.text('Old name'), findsOneWidget); + final l10n = AppLocalizations.of(tester.element(find.byType(ProfileTab))); + await tester.tap(find.text(l10n.profileEdit)); + await tester.pumpAndSettle(); + + final fields = find.byType(CupertinoTextField); + await tester.enterText(fields.at(0), 'New name'); + await tester.enterText(fields.at(1), 'My signature'); + await tester.tap(find.text(l10n.commonSave)); + await tester.pumpAndSettle(); + + expect(router.routeInformationProvider.value.uri.path, '/profile'); + expect(find.text('New name'), findsOneWidget); + expect(find.text('My signature'), findsOneWidget); + expect(repository.profile.nickname, 'New name'); + }); +}