feat(auth): 优化登录页布局与字段反馈

This commit is contained in:
Zhou Weidong committed 2026-10-19 10:33:33 +08:00
1 parent e44fbdf6f2
commit 8a96f341c8
12 files changed
+302 -66

No files matched your search

+1
View File
@@ -279,6 +279,7 @@
"authSignInTitle": "Welcome back", "authSignInTitle": "Welcome back",
"authSignUpTitle": "Create your account", "authSignUpTitle": "Create your account",
"authSubtitle": "Sign in with your email and password.", "authSubtitle": "Sign in with your email and password.",
"authSignUpSubtitle": "Create an account to keep your list, history, and progress.",
"authBrandTagline": "Short dramas made for Indonesia", "authBrandTagline": "Short dramas made for Indonesia",
"authEmailLabel": "Email", "authEmailLabel": "Email",
"authPasswordLabel": "Password", "authPasswordLabel": "Password",
+1
View File
@@ -279,6 +279,7 @@
"authSignInTitle": "Selamat datang kembali", "authSignInTitle": "Selamat datang kembali",
"authSignUpTitle": "Buat akun kamu", "authSignUpTitle": "Buat akun kamu",
"authSubtitle": "Masuk dengan email dan kata sandi.", "authSubtitle": "Masuk dengan email dan kata sandi.",
"authSignUpSubtitle": "Buat akun untuk menyimpan daftar, riwayat, dan progresmu.",
"authBrandTagline": "Drama pendek untuk Indonesia", "authBrandTagline": "Drama pendek untuk Indonesia",
"authEmailLabel": "Email", "authEmailLabel": "Email",
"authPasswordLabel": "Kata sandi", "authPasswordLabel": "Kata sandi",
+6
View File
@@ -1330,6 +1330,12 @@ abstract class AppLocalizations {
/// **'Sign in with your email and password.'** /// **'Sign in with your email and password.'**
String get authSubtitle; String get authSubtitle;
/// No description provided for @authSignUpSubtitle.
///
/// In en, this message translates to:
/// **'Create an account to keep your list, history, and progress.'**
String get authSignUpSubtitle;
/// No description provided for @authBrandTagline. /// No description provided for @authBrandTagline.
/// ///
/// In en, this message translates to: /// In en, this message translates to:
+4
View File
@@ -652,6 +652,10 @@ class AppLocalizationsEn extends AppLocalizations {
@override @override
String get authSubtitle => 'Sign in with your email and password.'; String get authSubtitle => 'Sign in with your email and password.';
@override
String get authSignUpSubtitle =>
'Create an account to keep your list, history, and progress.';
@override @override
String get authBrandTagline => 'Short dramas made for Indonesia'; String get authBrandTagline => 'Short dramas made for Indonesia';
+4
View File
@@ -655,6 +655,10 @@ class AppLocalizationsId extends AppLocalizations {
@override @override
String get authSubtitle => 'Masuk dengan email dan kata sandi.'; String get authSubtitle => 'Masuk dengan email dan kata sandi.';
@override
String get authSignUpSubtitle =>
'Buat akun untuk menyimpan daftar, riwayat, dan progresmu.';
@override @override
String get authBrandTagline => 'Drama pendek untuk Indonesia'; String get authBrandTagline => 'Drama pendek untuk Indonesia';
+3
View File
@@ -643,6 +643,9 @@ class AppLocalizationsZh extends AppLocalizations {
@override @override
String get authSubtitle => '用邮箱和密码登录。'; String get authSubtitle => '用邮箱和密码登录。';
@override
String get authSignUpSubtitle => '创建账号,保存你的片单、观看记录和进度。';
@override @override
String get authBrandTagline => '为印尼市场打造的短剧体验'; String get authBrandTagline => '为印尼市场打造的短剧体验';
+1
View File
@@ -241,6 +241,7 @@
"authSignInTitle": "欢迎回来", "authSignInTitle": "欢迎回来",
"authSignUpTitle": "创建账号", "authSignUpTitle": "创建账号",
"authSubtitle": "用邮箱和密码登录。", "authSubtitle": "用邮箱和密码登录。",
"authSignUpSubtitle": "创建账号,保存你的片单、观看记录和进度。",
"authBrandTagline": "为印尼市场打造的短剧体验", "authBrandTagline": "为印尼市场打造的短剧体验",
"authEmailLabel": "邮箱", "authEmailLabel": "邮箱",
"authPasswordLabel": "密码", "authPasswordLabel": "密码",
+76 -23
View File
@@ -10,21 +10,40 @@ class _AuthFields extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final error = state.status.fieldError;
final emailError =
error == AuthFieldError.emailRequired ||
error == AuthFieldError.emailInvalid;
final passwordError =
error == AuthFieldError.passwordRequired ||
error == AuthFieldError.passwordLength ||
error == AuthFieldError.passwordWeak;
return Column( return Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
_fieldLabel(state.l10n.authEmailLabel), _fieldLabel(state.l10n.authEmailLabel),
const SizedBox(height: 8), const SizedBox(height: 8),
_emailField(), _emailField(context, hasError: emailError),
const SizedBox(height: 16), const SizedBox(height: 16),
_fieldLabel(state.l10n.authPasswordLabel), _fieldLabel(state.l10n.authPasswordLabel),
const SizedBox(height: 8), const SizedBox(height: 8),
_passwordField(), _passwordField(context, hasError: passwordError),
if (state.status.signUpMode) ...[
const SizedBox(height: 8),
Text(
state.l10n.authPasswordHint,
key: const Key('auth-password-rule'),
style: const TextStyle(
color: AppColors.muted,
fontSize: AppDimens.caption,
),
),
],
], ],
); );
} }
Widget _emailField() { Widget _emailField(BuildContext context, {required bool hasError}) {
final enabled = !state.status.busy; final enabled = !state.status.busy;
return ListenableBuilder( return ListenableBuilder(
listenable: state.fields.emailFocus, listenable: state.fields.emailFocus,
@@ -43,16 +62,18 @@ class _AuthFields extends StatelessWidget {
onSubmitted: (_) => state.fields.passwordFocus.requestFocus(), onSubmitted: (_) => state.fields.passwordFocus.requestFocus(),
style: const TextStyle(color: AppColors.onPrimary, fontSize: 15), style: const TextStyle(color: AppColors.onPrimary, fontSize: 15),
decoration: _decoration( decoration: _decoration(
context: context,
hint: 'name@example.com', hint: 'name@example.com',
icon: Icons.mail_outline_rounded, icon: Icons.mail_outline_rounded,
focused: state.fields.emailFocus.hasFocus, focused: state.fields.emailFocus.hasFocus,
hasError: hasError,
), ),
), ),
), ),
); );
} }
Widget _passwordField() { Widget _passwordField(BuildContext context, {required bool hasError}) {
final enabled = !state.status.busy; final enabled = !state.status.busy;
final l10n = state.l10n; final l10n = state.l10n;
return ListenableBuilder( return ListenableBuilder(
@@ -72,9 +93,11 @@ class _AuthFields extends StatelessWidget {
onSubmitted: (_) => callbacks.onSubmit(), onSubmitted: (_) => callbacks.onSubmit(),
style: const TextStyle(color: AppColors.onPrimary, fontSize: 15), style: const TextStyle(color: AppColors.onPrimary, fontSize: 15),
decoration: _decoration( decoration: _decoration(
context: context,
hint: l10n.authPasswordHint, hint: l10n.authPasswordHint,
icon: Icons.lock_outline_rounded, icon: Icons.lock_outline_rounded,
focused: state.fields.passwordFocus.hasFocus, focused: state.fields.passwordFocus.hasFocus,
hasError: hasError,
suffix: IconButton( suffix: IconButton(
key: const Key('auth-password-visibility'), key: const Key('auth-password-visibility'),
constraints: const BoxConstraints.tightFor( constraints: const BoxConstraints.tightFor(
@@ -108,15 +131,22 @@ class _AuthFields extends StatelessWidget {
); );
InputDecoration _decoration({ InputDecoration _decoration({
required BuildContext context,
required String hint, required String hint,
required IconData icon, required IconData icon,
required bool focused, required bool focused,
required bool hasError,
Widget? suffix, Widget? suffix,
}) { }) {
final border = OutlineInputBorder( final border = OutlineInputBorder(
borderRadius: BorderRadius.circular(_fieldRadius), borderRadius: BorderRadius.circular(_fieldRadius),
borderSide: BorderSide.none, borderSide: BorderSide.none,
); );
final errorColor = Theme.of(context).colorScheme.error;
final errorBorder = OutlineInputBorder(
borderRadius: BorderRadius.circular(_fieldRadius),
borderSide: BorderSide(color: errorColor, width: _fieldBorderWidth),
);
return InputDecoration( return InputDecoration(
hintText: hint, hintText: hint,
hintStyle: const TextStyle(color: AppColors.muted, fontSize: 14), hintStyle: const TextStyle(color: AppColors.muted, fontSize: 14),
@@ -144,6 +174,8 @@ class _AuthFields extends StatelessWidget {
width: _fieldBorderWidth, width: _fieldBorderWidth,
), ),
), ),
errorBorder: errorBorder,
focusedErrorBorder: errorBorder,
); );
} }
} }
@@ -175,7 +207,10 @@ class _AuthSubmitButton extends StatelessWidget {
return AppColors.blue; return AppColors.blue;
}), }),
foregroundColor: const WidgetStatePropertyAll(AppColors.onPrimary), foregroundColor: const WidgetStatePropertyAll(AppColors.onPrimary),
elevation: const WidgetStatePropertyAll(0), elevation: const WidgetStatePropertyAll(2),
shadowColor: WidgetStatePropertyAll(
AppColors.blue.withValues(alpha: 0.22),
),
padding: const WidgetStatePropertyAll(EdgeInsets.zero), padding: const WidgetStatePropertyAll(EdgeInsets.zero),
shape: WidgetStatePropertyAll( shape: WidgetStatePropertyAll(
RoundedRectangleBorder( RoundedRectangleBorder(
@@ -267,21 +302,36 @@ class _ModeSegment extends StatelessWidget {
} }
class _AuthBrand extends StatelessWidget { class _AuthBrand extends StatelessWidget {
const _AuthBrand({required this.tagline}); const _AuthBrand({required this.tagline, required this.compact});
final String tagline; final String tagline;
final bool compact;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final copy = _brandCopy(context, centered: !compact);
if (compact) {
return Row( return Row(
key: const Key('auth-brand'), key: const Key('auth-brand'),
children: [ children: [
Container( _brandMark(),
const SizedBox(width: 14),
Expanded(child: copy),
],
);
}
return Column(
key: const Key('auth-brand'),
mainAxisSize: MainAxisSize.min,
children: [_brandMark(), const SizedBox(height: 14), copy],
);
}
Widget _brandMark() => Container(
key: const Key('auth-brand-mark'), key: const Key('auth-brand-mark'),
width: _brandMarkSize, width: _brandMarkSize,
height: _brandMarkSize, height: _brandMarkSize,
decoration: BoxDecoration( decoration: BoxDecoration(
color: AppColors.blue,
borderRadius: BorderRadius.circular(14), borderRadius: BorderRadius.circular(14),
boxShadow: [ boxShadow: [
BoxShadow( BoxShadow(
@@ -291,42 +341,45 @@ class _AuthBrand extends StatelessWidget {
), ),
], ],
), ),
child: const Icon( child: ClipRRect(
Icons.movie_filter_rounded, borderRadius: BorderRadius.circular(14),
color: AppColors.onPrimary, child: Image.asset(
size: 26, 'assets/icon/splash_mark.png',
width: _brandMarkSize,
height: _brandMarkSize,
fit: BoxFit.cover,
), ),
), ),
const SizedBox(width: 14), );
Expanded(
child: Column( Widget _brandCopy(BuildContext context, {required bool centered}) => Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: centered
? CrossAxisAlignment.center
: CrossAxisAlignment.start,
children: [ children: [
Text( Text(
AppLocalizations.of(context)!.appName, AppLocalizations.of(context)!.appName,
textAlign: centered ? TextAlign.center : TextAlign.start,
style: const TextStyle( style: const TextStyle(
color: AppColors.onPrimary, color: AppColors.onPrimary,
fontSize: 23, fontSize: 26,
fontWeight: FontWeight.w800, fontWeight: FontWeight.w800,
height: 1.1, height: 1.1,
), ),
), ),
const SizedBox(height: 4), const SizedBox(height: 6),
Text( Text(
tagline, tagline,
textAlign: centered ? TextAlign.center : TextAlign.start,
style: const TextStyle( style: const TextStyle(
color: AppColors.blueSoft, color: AppColors.blueSoft,
fontSize: 13, fontSize: 14,
height: 1.35, height: 1.35,
), ),
), ),
], ],
),
),
],
); );
} }
}
class _AuthError extends StatelessWidget { class _AuthError extends StatelessWidget {
const _AuthError({required this.message}); const _AuthError({required this.message});
+20 -5
View File
@@ -8,29 +8,44 @@ class AuthLogic {
String password = ''; String password = '';
bool busy = false; bool busy = false;
String? errorMessage; String? errorMessage;
AuthFieldError? fieldError;
AuthLogic({this.signUpMode = false, this.errorMessage}); AuthLogic({this.signUpMode = false, this.errorMessage});
void toggleMode() { void toggleMode() {
signUpMode = !signUpMode; signUpMode = !signUpMode;
errorMessage = null; errorMessage = null;
fieldError = null;
} }
/// 返回 null 表示校验通过,否则返回错误文案(由视图用 l10n 映射) /// 返回 null 表示校验通过,否则返回错误文案(由视图用 l10n 映射)
AuthFieldError? validate() { AuthFieldError? validate() {
final mail = email.trim(); final mail = email.trim();
if (mail.isEmpty) return AuthFieldError.emailRequired; if (mail.isEmpty) return _record(AuthFieldError.emailRequired);
if (!_emailPattern.hasMatch(mail)) return AuthFieldError.emailInvalid; if (!_emailPattern.hasMatch(mail)) {
if (password.isEmpty) return AuthFieldError.passwordRequired; return _record(AuthFieldError.emailInvalid);
}
if (password.isEmpty) return _record(AuthFieldError.passwordRequired);
if (password.length < 8 || password.length > 64) { if (password.length < 8 || password.length > 64) {
return AuthFieldError.passwordLength; return _record(AuthFieldError.passwordLength);
} }
if (!_hasLetter.hasMatch(password) || !_hasDigit.hasMatch(password)) { if (!_hasLetter.hasMatch(password) || !_hasDigit.hasMatch(password)) {
return AuthFieldError.passwordWeak; return _record(AuthFieldError.passwordWeak);
} }
fieldError = null;
return null; return null;
} }
/// 清除当前字段错误;输入变化时由页面调用。
void clearFieldError() {
fieldError = null;
}
AuthFieldError _record(AuthFieldError error) {
fieldError = error;
return error;
}
String get normalizedEmail => email.trim().toLowerCase(); String get normalizedEmail => email.trim().toLowerCase();
static final _emailPattern = RegExp( static final _emailPattern = RegExp(
+98 -37
View File
@@ -33,6 +33,13 @@ const double _glowOpacity = 0.18;
const double _errorOpacity = 0.10; const double _errorOpacity = 0.10;
const double _errorBorderOpacity = 0.28; const double _errorBorderOpacity = 0.28;
const double _enterSlideDistance = 16; const double _enterSlideDistance = 16;
const double _topContentPadding = 64;
const double _bottomContentPadding = 28;
const double _compactTopContentPadding = 48;
const double _compactHeightBreakpoint = 720;
const double _compactBrandGap = 16;
const double _warmGlowSize = 260;
const double _warmGlowOpacity = 0.06;
const Duration _enterDuration = Duration(milliseconds: 220); const Duration _enterDuration = Duration(milliseconds: 220);
const Duration _segmentDuration = Duration(milliseconds: 160); const Duration _segmentDuration = Duration(milliseconds: 160);
@@ -89,6 +96,7 @@ class _AuthPageState extends State<AuthPage> {
} }
Future<void> _submit() async { Future<void> _submit() async {
if (_logic.busy) return;
final l10n = AppLocalizations.of(context)!; final l10n = AppLocalizations.of(context)!;
final invalid = _logic.validate(); final invalid = _logic.validate();
if (invalid != null) { if (invalid != null) {
@@ -117,8 +125,10 @@ class _AuthPageState extends State<AuthPage> {
if (!mounted) return; if (!mounted) return;
Navigator.of(context).maybePop(); Navigator.of(context).maybePop();
} on ApiException catch (error) { } on ApiException catch (error) {
if (!mounted) return;
setState(() => _logic.errorMessage = error.message); setState(() => _logic.errorMessage = error.message);
} catch (_) { } catch (_) {
if (!mounted) return;
setState(() => _logic.errorMessage = l10n.authNetworkError); setState(() => _logic.errorMessage = l10n.authNetworkError);
} finally { } finally {
if (mounted) setState(() => _logic.busy = false); if (mounted) setState(() => _logic.busy = false);
@@ -158,67 +168,88 @@ class _AuthPageState extends State<AuthPage> {
), ),
), ),
), ),
Positioned(
top: 72,
right: -80,
width: _warmGlowSize,
height: _warmGlowSize,
child: IgnorePointer(
child: Container(
key: const Key('auth-background-warm-glow'),
decoration: BoxDecoration(
shape: BoxShape.circle,
gradient: RadialGradient(
colors: [
AppColors.gold.withValues(alpha: _warmGlowOpacity),
AppColors.gold.withValues(alpha: 0),
],
),
),
),
),
),
SafeArea( SafeArea(
child: AutofillGroup( child: LayoutBuilder(
child: ListView( builder: (context, constraints) {
final compact =
constraints.maxHeight < _compactHeightBreakpoint;
final top = compact
? _compactTopContentPadding
: _topContentPadding;
final bottom =
_bottomContentPadding +
MediaQuery.viewInsetsOf(context).bottom;
final available = constraints.maxHeight - top - bottom;
final minHeight = available > 0 ? available : 0.0;
return AutofillGroup(
child: SingleChildScrollView(
key: const Key('auth-scroll'), key: const Key('auth-scroll'),
keyboardDismissBehavior: keyboardDismissBehavior:
ScrollViewKeyboardDismissBehavior.onDrag, ScrollViewKeyboardDismissBehavior.onDrag,
padding: EdgeInsets.fromLTRB( padding: EdgeInsets.fromLTRB(
AppDimens.pageHorizontal, AppDimens.pageHorizontal,
12, top,
AppDimens.pageHorizontal, AppDimens.pageHorizontal,
28 + MediaQuery.viewInsetsOf(context).bottom, bottom,
), ),
children: [ child: ConstrainedBox(
Center( constraints: BoxConstraints(minHeight: minHeight),
child: Center(
child: ConstrainedBox( child: ConstrainedBox(
constraints: const BoxConstraints( constraints: const BoxConstraints(
maxWidth: _contentMaxWidth, maxWidth: _contentMaxWidth,
), ),
child: TweenAnimationBuilder<double>( child: _content(l10n, compact: compact),
key: const Key('auth-enter-animation'), ),
tween: Tween(begin: 0, end: 1), ),
duration: _enterDuration, ),
curve: Curves.easeOutCubic, ),
builder: (context, value, child) => Opacity( );
opacity: value, },
child: Transform.translate(
offset: Offset(
0,
_enterSlideDistance * (1 - value),
),
child: child,
), ),
), ),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (Navigator.of(context).canPop()) if (Navigator.of(context).canPop())
Align( Positioned(
alignment: Alignment.centerLeft, top: 0,
left: 0,
right: 0,
child: SafeArea(
child: Align(
alignment: Alignment.topLeft,
child: Padding(
padding: const EdgeInsets.only(left: 4, top: 4),
child: IconButton( child: IconButton(
key: const Key('auth-back'), key: const Key('auth-back'),
tooltip: MaterialLocalizations.of( tooltip: MaterialLocalizations.of(
context, context,
).backButtonTooltip, ).backButtonTooltip,
onPressed: () => onPressed: () => Navigator.of(context).pop(),
Navigator.of(context).pop(),
icon: const Icon( icon: const Icon(
Icons.arrow_back_rounded, Icons.arrow_back_rounded,
color: AppColors.onPrimary, color: AppColors.onPrimary,
), ),
), ),
), ),
_AuthBrand(tagline: l10n.authBrandTagline),
const SizedBox(height: 28),
_authCard(l10n),
],
),
),
),
),
],
), ),
), ),
), ),
@@ -228,6 +259,29 @@ class _AuthPageState extends State<AuthPage> {
); );
} }
Widget _content(AppLocalizations l10n, {required bool compact}) =>
TweenAnimationBuilder<double>(
key: const Key('auth-enter-animation'),
tween: Tween(begin: 0, end: 1),
duration: _enterDuration,
curve: Curves.easeOutCubic,
builder: (context, value, child) => Opacity(
opacity: value,
child: Transform.translate(
offset: Offset(0, _enterSlideDistance * (1 - value)),
child: child,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_AuthBrand(tagline: l10n.authBrandTagline, compact: compact),
SizedBox(height: compact ? _compactBrandGap : 28),
_authCard(l10n),
],
),
);
Widget _authCard(AppLocalizations l10n) => _AuthCard( Widget _authCard(AppLocalizations l10n) => _AuthCard(
state: _AuthCardState( state: _AuthCardState(
l10n: l10n, l10n: l10n,
@@ -235,6 +289,7 @@ class _AuthPageState extends State<AuthPage> {
signUpMode: _logic.signUpMode, signUpMode: _logic.signUpMode,
busy: _logic.busy, busy: _logic.busy,
errorMessage: _logic.errorMessage, errorMessage: _logic.errorMessage,
fieldError: _logic.fieldError,
obscurePassword: _obscurePassword, obscurePassword: _obscurePassword,
), ),
fields: _AuthFieldControllers( fields: _AuthFieldControllers(
@@ -246,8 +301,14 @@ class _AuthPageState extends State<AuthPage> {
), ),
callbacks: _AuthCardCallbacks( callbacks: _AuthCardCallbacks(
onModeSelected: _selectMode, onModeSelected: _selectMode,
onEmailChanged: (value) => _logic.email = value, onEmailChanged: (value) => setState(() {
onPasswordChanged: (value) => _logic.password = value, _logic.email = value;
_logic.clearFieldError();
}),
onPasswordChanged: (value) => setState(() {
_logic.password = value;
_logic.clearFieldError();
}),
onTogglePasswordVisibility: () => onTogglePasswordVisibility: () =>
setState(() => _obscurePassword = !_obscurePassword), setState(() => _obscurePassword = !_obscurePassword),
onSubmit: _submit, onSubmit: _submit,
+3 -1
View File
@@ -19,12 +19,14 @@ class _AuthFormStatus {
required this.signUpMode, required this.signUpMode,
required this.busy, required this.busy,
required this.errorMessage, required this.errorMessage,
required this.fieldError,
required this.obscurePassword, required this.obscurePassword,
}); });
final bool signUpMode; final bool signUpMode;
final bool busy; final bool busy;
final String? errorMessage; final String? errorMessage;
final AuthFieldError? fieldError;
final bool obscurePassword; final bool obscurePassword;
} }
@@ -100,7 +102,7 @@ class _AuthCard extends StatelessWidget {
), ),
const SizedBox(height: 6), const SizedBox(height: 6),
Text( Text(
l10n.authSubtitle, status.signUpMode ? l10n.authSignUpSubtitle : l10n.authSubtitle,
style: const TextStyle( style: const TextStyle(
color: AppColors.muted, color: AppColors.muted,
fontSize: AppDimens.body, fontSize: AppDimens.body,
+85
View File
@@ -0,0 +1,85 @@
// Author: fruit.com.cn
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
import 'package:fruitshorts/core/data/remote/api_client.dart';
import 'package:fruitshorts/core/data/remote/auth_api.dart';
import 'package:fruitshorts/core/data/services/auth_controller.dart';
import 'package:fruitshorts/core/data/services/auth_session_store.dart';
import 'package:fruitshorts/core/platform/haptics.dart';
import 'package:fruitshorts/l10n/app_localizations.dart';
import 'package:fruitshorts/pages/auth/auth_view.dart';
import '../support/fake_haptics.dart';
import '../support/fake_http_adapter.dart';
void main() {
setUp(() {
SharedPreferencesAsyncPlatform.instance =
InMemorySharedPreferencesAsync.empty();
});
testWidgets('should_show_sign_up_subtitle_and_password_rule_when_switched', (
tester,
) async {
await _pumpAuth(tester);
final l10n = await AppLocalizations.delegate.load(const Locale('en'));
expect(find.byKey(const Key('auth-password-rule')), findsNothing);
await tester.tap(find.byKey(const Key('auth-mode-sign-up')));
await tester.pumpAndSettle();
expect(find.text(l10n.authSignUpSubtitle), findsOneWidget);
final rule = find.byKey(const Key('auth-password-rule'));
expect(rule, findsOneWidget);
expect(tester.widget<Text>(rule).data, l10n.authPasswordHint);
});
testWidgets('should_apply_semantic_error_border_when_email_is_invalid', (
tester,
) async {
await _pumpAuth(tester);
await tester.enterText(find.byKey(const Key('auth-email')), 'invalid');
await tester.enterText(find.byKey(const Key('auth-password')), 'abcd1234');
await tester.tap(find.byKey(const Key('auth-submit')));
await tester.pumpAndSettle();
final emailFinder = find.byKey(const Key('auth-email'));
final email = tester.widget<TextField>(emailFinder);
final errorBorder = email.decoration!.errorBorder! as OutlineInputBorder;
final scheme = Theme.of(tester.element(emailFinder)).colorScheme;
expect(errorBorder.borderSide.color, scheme.error);
expect(errorBorder.borderSide.width, 1.5);
});
}
Future<void> _pumpAuth(WidgetTester tester) async {
final auth = AuthController(
AuthApi(
ApiClient(
baseUrl: 'http://127.0.0.1:1',
adapter: FakeHttpAdapter((_) async => FakeHttpResponse('{}', 500)),
),
),
AuthSessionStore(),
);
await tester.pumpWidget(
MultiProvider(
providers: [
ChangeNotifierProvider<AuthController>.value(value: auth),
Provider<Haptics>.value(value: FakeHaptics()),
],
child: MaterialApp(
locale: const Locale('en'),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: const AuthPage(),
),
),
);
await tester.pumpAndSettle();
}