π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mob][packages] Refine button execution states (#10443)
Aman Raj8886507215a3
diff --git a/mobile/packages/ente_components/example/lib/main.dart b/mobile/packages/ente_components/example/lib/main.dartindex 08bfe4720a..ba20dc1b2c 100644--- a/mobile/packages/ente_components/example/lib/main.dart+++ b/mobile/packages/ente_components/example/lib/main.dart@@ -48,7 +48,8 @@ class _ComponentsCatalogAppState extends State<ComponentsCatalogApp> {final now = event.timeStamp;final lastPointerUpAt = _lastPointerUpAt;final lastPointerUpPosition = _lastPointerUpPosition;- final isDoubleTap = lastPointerUpAt != null &&+ final isDoubleTap =+ lastPointerUpAt != null &&lastPointerUpPosition != null &&now - lastPointerUpAt <= const Duration(milliseconds: 320) &&(event.position - lastPointerUpPosition).distance <= 48;@@ -114,7 +115,7 @@ class _CatalogHomeState extends State<CatalogHome> {return IconButtonComponent(tooltip: 'Settings',variant: IconButtonComponentVariant.unfilled,- onPressed: () => Scaffold.of(context).openDrawer(),+ onTap: () => Scaffold.of(context).openDrawer(),icon: const _CatalogHugeIcon(HugeIcons.strokeRoundedMenu01),);},@@ -252,23 +253,13 @@ class _CatalogHomeState extends State<CatalogHome> {CatalogSection(title: 'Avatar',icon: HugeIcons.strokeRoundedUser,- components: const [- 'Sizes',- 'Seed palette',- 'Add contact',- ],+ components: const ['Sizes', 'Seed palette', 'Add contact'],previewBuilder: (_) => const _AvatarPreview(),),CatalogSection(title: 'Selection controls',icon: HugeIcons.strokeRoundedSlidersHorizontal,- components: const [- 'Checkbox',- 'Radio',- 'Switch',- 'Slider',- 'Stepper',- ],+ components: const ['Checkbox', 'Radio', 'Switch', 'Slider', 'Stepper'],previewBuilder: (_) => const _SelectionPreview(),),];@@ -312,15 +303,13 @@ class CatalogSettingsDrawer extends StatelessWidget {icon: const _CatalogHugeIcon(HugeIcons.strokeRoundedArrowLeft02,),- onPressed: () => Navigator.of(context).pop(),+ onTap: () => Navigator.of(context).pop(),),const SizedBox(width: Spacing.md),Expanded(child: Text('Settings',- style: TextStyles.h1Bold.copyWith(- color: colors.textBase,- ),+ style: TextStyles.h1Bold.copyWith(color: colors.textBase),),),],@@ -340,11 +329,7 @@ double _drawerWidth(BuildContext context) {}class _CatalogHugeIcon extends StatelessWidget {- const _CatalogHugeIcon(- this.icon, {- this.color,- this.size = 24,- });+ const _CatalogHugeIcon(this.icon, {this.color, this.size = 24});final HugeIconData icon;final Color? color;@@ -423,7 +408,7 @@ class _CatalogThemeCycleButton extends StatelessWidget {tooltip: 'Theme: $_currentLabel. Tap for $_nextLabel',variant: IconButtonComponentVariant.unfilled,icon: _CatalogHugeIcon(_icon),- onPressed: () => onChanged(_nextMode),+ onTap: () => onChanged(_nextMode),);}}@@ -499,7 +484,7 @@ class _CatalogDetailPageState extends State<CatalogDetailPage> {leading: IconButtonComponent(tooltip: 'Back',icon: const _CatalogHugeIcon(HugeIcons.strokeRoundedArrowLeft02),- onPressed: () => Navigator.of(context).pop(),+ onTap: () => Navigator.of(context).pop(),),actions: [_CatalogThemeCycleButton(@@ -510,9 +495,7 @@ class _CatalogDetailPageState extends State<CatalogDetailPage> {),body: ListView(padding: const EdgeInsets.all(Spacing.lg),- children: [- widget.section.previewBuilder(context),- ],+ children: [widget.section.previewBuilder(context)],),backgroundColor: colors.backgroundBase,);@@ -520,10 +503,7 @@ class _CatalogDetailPageState extends State<CatalogDetailPage> {}class _CatalogPreviewGroup extends StatelessWidget {- const _CatalogPreviewGroup({- required this.title,- required this.child,- });+ const _CatalogPreviewGroup({required this.title, required this.child});final String title;final Widget child;@@ -534,10 +514,7 @@ class _CatalogPreviewGroup extends StatelessWidget {return Column(crossAxisAlignment: CrossAxisAlignment.start,children: [- Text(- title,- style: TextStyles.large.copyWith(color: colors.textBase),- ),+ Text(title, style: TextStyles.large.copyWith(color: colors.textBase)),const SizedBox(height: Spacing.md),child,],@@ -627,7 +604,7 @@ class _SettingsMainContent extends StatelessWidget {),trailing: _SettingsTrailingIcon(color: colors.textLight),),- const SizedBox(height: Spacing.xxl),+ const SizedBox(height: Spacing.xl),Center(child: Text('Version 1.0.0',@@ -657,9 +634,9 @@ class _SettingsNavigationItem extends StatelessWidget {leading: _CatalogHugeIcon(icon),trailing: const _SettingsTrailingIcon(),onTap: () {- Navigator.of(context).push(- MaterialPageRoute<void>(builder: (_) => page),- );+ Navigator.of(+ context,+ ).push(MaterialPageRoute<void>(builder: (_) => page));},);}@@ -681,10 +658,7 @@ class _SettingsTrailingIcon extends StatelessWidget {}class _SettingsExampleShell extends StatelessWidget {- const _SettingsExampleShell({- required this.title,- required this.children,- });+ const _SettingsExampleShell({required this.title, required this.children});final String title;final List<Widget> children;@@ -698,7 +672,7 @@ class _SettingsExampleShell extends StatelessWidget {leading: IconButtonComponent(tooltip: 'Back',icon: const _CatalogHugeIcon(HugeIcons.strokeRoundedArrowLeft02),- onPressed: () => Navigator.of(context).pop(),+ onTap: () => Navigator.of(context).pop(),),),body: ListView(@@ -1147,15 +1121,9 @@ class _TypeSample extends StatelessWidget {return Column(crossAxisAlignment: CrossAxisAlignment.start,children: [- Text(- text,- style: style.copyWith(color: color),- ),+ Text(text, style: style.copyWith(color: color)),const SizedBox(height: Spacing.xs),- Text(- detail,- style: TextStyles.mini.copyWith(color: colors.textLight),- ),+ Text(detail, style: TextStyles.mini.copyWith(color: colors.textLight)),],);}@@ -1169,13 +1137,11 @@ class _ButtonMatrix extends StatelessWidget {return const _CatalogPreviewList(children: [ButtonStateCyclePreview(),+ _ButtonExecutionPreview(),_ButtonStateGroup(title: 'Default'),- _ButtonStateGroup(- title: 'Disabled',- disabled: true,- ),+ _ButtonStateGroup(title: 'Disabled', disabled: true),_CatalogPreviewGroup(- title: 'Icon button',+ title: 'Icon button async actions',child: _IconButtonMatrix(),),],@@ -1211,6 +1177,85 @@ class _ButtonStateCyclePreviewState extends State<ButtonStateCyclePreview> {}}+class _ButtonExecutionPreview extends StatelessWidget {+ const _ButtonExecutionPreview();++ @override+ Widget build(BuildContext context) {+ final colors = context.componentColors;+ return _CatalogPreviewGroup(+ title: 'Async actions',+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ 'Success',+ style: TextStyles.large.copyWith(color: colors.textBase),+ ),+ const SizedBox(height: Spacing.xs),+ ButtonComponent(+ label: 'Save changes',+ variant: ButtonComponentVariant.primary,+ size: ButtonComponentSize.large,+ onTap: () =>+ Future<void>.delayed(const Duration(milliseconds: 900)),+ ),+ const SizedBox(height: Spacing.md),+ Text(+ 'Error',+ style: TextStyles.large.copyWith(color: colors.textBase),+ ),+ const SizedBox(height: Spacing.xs),+ ButtonComponent(+ label: 'Sync backup',+ variant: ButtonComponentVariant.critical,+ size: ButtonComponentSize.large,+ onTap: () => _runPreviewError(context),+ ),+ const SizedBox(height: Spacing.md),+ Text(+ 'Fast confirmation',+ style: TextStyles.large.copyWith(color: colors.textBase),+ ),+ const SizedBox(height: Spacing.xs),+ ButtonComponent(+ label: 'Copy link',+ variant: ButtonComponentVariant.secondary,+ size: ButtonComponentSize.large,+ shouldShowSuccessConfirmation: true,+ onTap: () =>+ Future<void>.delayed(const Duration(milliseconds: 120)),+ ),+ const SizedBox(height: Spacing.md),+ Text(+ 'Surface off',+ style: TextStyles.large.copyWith(color: colors.textBase),+ ),+ const SizedBox(height: Spacing.xs),+ ButtonComponent(+ label: 'Refresh',+ variant: ButtonComponentVariant.neutral,+ size: ButtonComponentSize.large,+ shouldSurfaceExecutionStates: false,+ onTap: () =>+ Future<void>.delayed(const Duration(milliseconds: 900)),+ ),+ ],+ ),+ );+ }++ Future<void> _runPreviewError(BuildContext context) async {+ await Future<void>.delayed(const Duration(milliseconds: 900));+ if (context.mounted) {+ ScaffoldMessenger.of(+ context,+ ).showSnackBar(const SnackBar(content: Text('Something went wrong')));+ }+ throw StateError('Preview action failed');+ }+}+const _buttonPreviewSpecs = <_ButtonPreviewSpec>[_ButtonPreviewSpec(type: 'Primary',@@ -1257,10 +1302,7 @@ class _ButtonPreviewSpec {}class _ButtonStateGroup extends StatelessWidget {- const _ButtonStateGroup({- required this.title,- this.disabled = false,- });+ const _ButtonStateGroup({required this.title, this.disabled = false});final String title;final bool disabled;@@ -1286,10 +1328,7 @@ class _ButtonStateGroup extends StatelessWidget {}class _ButtonPreviewRow extends StatelessWidget {- const _ButtonPreviewRow({- required this.spec,- required this.disabled,- });+ const _ButtonPreviewRow({required this.spec, required this.disabled});final _ButtonPreviewSpec spec;final bool disabled;@@ -1321,44 +1360,31 @@ class _IconButtonMatrix extends StatelessWidget {@overrideWidget build(BuildContext context) {- const columns = [- 'Default',- 'Hover',- 'Pressed',- 'Disabled',- 'Loading',- 'Success',- ];+ const columns = ['Default', 'Disabled', 'Loading', 'Success', 'Error'];const rows = [_IconButtonPreviewRow(label: 'Primary',variant: IconButtonComponentVariant.primary,- states: columns,),_IconButtonPreviewRow(label: 'Critical',variant: IconButtonComponentVariant.critical,- states: columns,),_IconButtonPreviewRow(label: 'Unfilled',variant: IconButtonComponentVariant.unfilled,- states: ['Default', 'Disabled', 'Loading', 'Success'],),_IconButtonPreviewRow(label: 'Secondary',variant: IconButtonComponentVariant.secondary,- states: ['Default', 'Disabled', 'Loading', 'Success'],),_IconButtonPreviewRow(label: 'Green',variant: IconButtonComponentVariant.green,- states: columns,),_IconButtonPreviewRow(label: 'Circular',variant: IconButtonComponentVariant.circular,- states: columns,),];final colors = context.componentColors;@@ -1394,15 +1420,10 @@ class _IconButtonMatrix extends StatelessWidget {}class _IconButtonPreviewRow extends StatelessWidget {- const _IconButtonPreviewRow({- required this.label,- required this.variant,- required this.states,- });+ const _IconButtonPreviewRow({required this.label, required this.variant});final String label;final IconButtonComponentVariant variant;- final List<String> states;@overrideWidget build(BuildContext context) {@@ -1418,21 +1439,15 @@ class _IconButtonPreviewRow extends StatelessWidget {),for (final state in const ['Default',- 'Hover',- 'Pressed','Disabled','Loading','Success',+ 'Error',])SizedBox(width: 76,child: Center(- child: states.contains(state)- ? _IconButtonStatePreview(- variant: variant,- state: state,- )- : const SizedBox.square(dimension: 38),+ child: _IconButtonStatePreview(variant: variant, state: state),),),],@@ -1441,10 +1456,7 @@ class _IconButtonPreviewRow extends StatelessWidget {}class _IconButtonStatePreview extends StatelessWidget {- const _IconButtonStatePreview({- required this.variant,- required this.state,- });+ const _IconButtonStatePreview({required this.variant, required this.state});final IconButtonComponentVariant variant;final String state;@@ -1454,20 +1466,29 @@ class _IconButtonStatePreview extends StatelessWidget {return IconButtonComponent(tooltip: state,variant: variant,- state: switch (state) {- 'Hover' => IconButtonComponentState.hover,- 'Pressed' => IconButtonComponentState.pressed,- _ => IconButtonComponentState.normal,- },- isLoading: state == 'Loading',- isSuccess: state == 'Success',- onPressed: state == 'Disabled' ? null : () {},- icon: const _CatalogHugeIcon(- HugeIcons.strokeRoundedAdd01,- size: 18,- ),+ shouldShowSuccessConfirmation: state == 'Success',+ onTap: state == 'Disabled'+ ? null+ : state == 'Loading'+ ? () => Future<void>.delayed(const Duration(milliseconds: 900))+ : state == 'Success'+ ? () => Future<void>.delayed(const Duration(milliseconds: 120))+ : state == 'Error'+ ? () => _runPreviewError(context)+ : () {},+ icon: const _CatalogHugeIcon(HugeIcons.strokeRoundedAdd01, size: 18),);}++ Future<void> _runPreviewError(BuildContext context) async {+ await Future<void>.delayed(const Duration(milliseconds: 900));+ if (context.mounted) {+ ScaffoldMessenger.of(+ context,+ ).showSnackBar(const SnackBar(content: Text('Something went wrong')));+ }+ throw StateError('Preview action failed');+ }}class _FilterChipPreview extends StatefulWidget {@@ -1506,8 +1527,9 @@ class _FilterChipPreviewState extends State<_FilterChipPreview> {label: 'Videos',selected: _selected.contains('Videos'),onChanged: _toggle('Videos'),- trailing:- const _CatalogHugeIcon(HugeIcons.strokeRoundedVideo01),+ trailing: const _CatalogHugeIcon(+ HugeIcons.strokeRoundedVideo01,+ ),),],),@@ -1732,10 +1754,7 @@ class _AvatarTableHeader extends StatelessWidget {}class _AvatarTableRow extends StatelessWidget {- const _AvatarTableRow({- required this.label,- required this.children,- });+ const _AvatarTableRow({required this.label, required this.children});final String label;final List<Widget> children;@@ -1753,11 +1772,7 @@ class _AvatarTableRow extends StatelessWidget {),),for (final child in children)- SizedBox(- width: 96,- height: 64,- child: Center(child: child),- ),+ SizedBox(width: 96, height: 64, child: Center(child: child)),],);}@@ -1796,10 +1811,7 @@ class _EditableChip extends StatelessWidget {}class _FaceAvatar extends StatelessWidget {- const _FaceAvatar({- required this.seed,- required this.initials,- });+ const _FaceAvatar({required this.seed, required this.initials});final int seed;final String initials;@@ -1828,7 +1840,8 @@ class _TextInputPreviewState extends State<_TextInputPreview> {late final TextEditingController _disabledController;late final TextEditingController _clearableController;late final TextEditingController _passwordController;- late final TextEditingController _readOnlyController;+ late final TextEditingController _submitController;+ late final ValueNotifier<int> _submitNotifier;@overridevoid initState() {@@ -1839,7 +1852,8 @@ class _TextInputPreviewState extends State<_TextInputPreview> {_disabledController = TextEditingController(text: '[email protected]');_clearableController = TextEditingController(text: 'family trip');_passwordController = TextEditingController(text: 'correct horse');- _readOnlyController = TextEditingController(text: 'Mira Roy');+ _submitController = TextEditingController(text: 'wrong password');+ _submitNotifier = ValueNotifier<int>(0);}@override@@ -1850,7 +1864,8 @@ class _TextInputPreviewState extends State<_TextInputPreview> {_disabledController.dispose();_clearableController.dispose();_passwordController.dispose();- _readOnlyController.dispose();+ _submitController.dispose();+ _submitNotifier.dispose();super.dispose();}@@ -1860,17 +1875,18 @@ class _TextInputPreviewState extends State<_TextInputPreview> {children: [const _CatalogPreviewGroup(title: 'Normal',- child:- TextInputComponent(label: 'Email address', hintText: 'Hint text'),+ child: TextInputComponent(+ label: 'Email address',+ hintText: 'Hint text',+ ),),_CatalogPreviewGroup(title: 'Focused',child: TextInputComponent(controller: _focusedController,label: 'Email address',- isFocused: true,- prefix: const _CatalogHugeIcon(HugeIcons.strokeRoundedMail01),- suffix: const _CatalogHugeIcon(HugeIcons.strokeRoundedView),+ prefix: const _TextInputPreviewIcon(HugeIcons.strokeRoundedMail01),+ suffix: const _TextInputPreviewIcon(HugeIcons.strokeRoundedView),),),_CatalogPreviewGroup(@@ -1878,10 +1894,43 @@ class _TextInputPreviewState extends State<_TextInputPreview> {child: TextInputComponent(controller: _errorController,label: 'Password',- errorText: 'Use at least 8 characters.',- obscureText: true,- prefix: const _CatalogHugeIcon(HugeIcons.strokeRoundedLockPassword),- suffix: const _CatalogHugeIcon(HugeIcons.strokeRoundedView),+ message: 'Use at least 8 characters.',+ messageType: TextInputComponentMessageType.error,+ isPasswordInput: true,+ prefix: const _TextInputPreviewIcon(+ HugeIcons.strokeRoundedLockPassword,+ ),+ ),+ ),+ _CatalogPreviewGroup(+ title: 'Submit error',+ child: Column(+ children: [+ TextInputComponent(+ controller: _submitController,+ submitNotifier: _submitNotifier,+ label: 'Password',+ hintText: 'Enter password',+ isPasswordInput: true,+ popNavAfterSubmission: true,+ prefix: const _TextInputPreviewIcon(+ HugeIcons.strokeRoundedLockPassword,+ ),+ onSubmit: (_) async {+ await Future<void>.delayed(const Duration(milliseconds: 300));+ throw Exception('Incorrect password');+ },+ ),+ const SizedBox(height: Spacing.md),+ ButtonComponent(+ label: 'Submit',+ size: ButtonComponentSize.small,+ shouldSurfaceExecutionStates: false,+ onTap: () {+ _submitNotifier.value++;+ },+ ),+ ],),),_CatalogPreviewGroup(@@ -1889,8 +1938,9 @@ class _TextInputPreviewState extends State<_TextInputPreview> {child: TextInputComponent(controller: _successController,label: 'Recovery code',- successText: 'Recovery code verified.',- suffix: const _CatalogHugeIcon(+ message: 'Recovery code verified.',+ messageType: TextInputComponentMessageType.success,+ suffix: const _TextInputPreviewIcon(HugeIcons.strokeRoundedCheckmarkCircle01,),),@@ -1900,8 +1950,8 @@ class _TextInputPreviewState extends State<_TextInputPreview> {child: TextInputComponent(controller: _disabledController,label: 'Account email',- enabled: false,- prefix: const _CatalogHugeIcon(HugeIcons.strokeRoundedMail01),+ isDisabled: true,+ prefix: const _TextInputPreviewIcon(HugeIcons.strokeRoundedMail01),),),const _CatalogPreviewGroup(@@ -1921,7 +1971,7 @@ class _TextInputPreviewState extends State<_TextInputPreview> {child: TextInputComponent(label: 'Recovery email',hintText: '[email protected]',- helperText: 'Used for receipts and security alerts.',+ message: 'Used for receipts and security alerts.',),),const _CatalogPreviewGroup(@@ -1929,7 +1979,7 @@ class _TextInputPreviewState extends State<_TextInputPreview> {child: TextInputComponent(label: 'Search',hintText: 'Search albums',- prefix: _CatalogHugeIcon(HugeIcons.strokeRoundedSearch01),+ prefix: _TextInputPreviewIcon(HugeIcons.strokeRoundedSearch01),),),const _CatalogPreviewGroup(@@ -1937,7 +1987,7 @@ class _TextInputPreviewState extends State<_TextInputPreview> {child: TextInputComponent(label: 'Password',hintText: 'Enter password',- suffix: _CatalogHugeIcon(HugeIcons.strokeRoundedView),+ suffix: _TextInputPreviewIcon(HugeIcons.strokeRoundedView),),),const _CatalogPreviewGroup(@@ -1945,8 +1995,8 @@ class _TextInputPreviewState extends State<_TextInputPreview> {child: TextInputComponent(label: 'Search',hintText: 'Search people',- prefix: _CatalogHugeIcon(HugeIcons.strokeRoundedSearch01),- suffix: _CatalogHugeIcon(HugeIcons.strokeRoundedCancel01),+ prefix: _TextInputPreviewIcon(HugeIcons.strokeRoundedSearch01),+ suffix: _TextInputPreviewIcon(HugeIcons.strokeRoundedCancel01),),),_CatalogPreviewGroup(@@ -1955,11 +2005,11 @@ class _TextInputPreviewState extends State<_TextInputPreview> {controller: _clearableController,label: 'Search',hintText: 'Search files',- prefix: const _CatalogHugeIcon(HugeIcons.strokeRoundedSearch01),+ prefix: const _TextInputPreviewIcon(+ HugeIcons.strokeRoundedSearch01,+ ),isClearable: true,- textInputAction: TextInputAction.search,autocorrect: false,- enableSuggestions: false,),),_CatalogPreviewGroup(@@ -1968,9 +2018,10 @@ class _TextInputPreviewState extends State<_TextInputPreview> {controller: _passwordController,label: 'Password',hintText: 'Enter password',- obscureText: true,- showPasswordToggle: true,- prefix: const _CatalogHugeIcon(HugeIcons.strokeRoundedLockPassword),+ isPasswordInput: true,+ prefix: const _TextInputPreviewIcon(+ HugeIcons.strokeRoundedLockPassword,+ ),autofillHints: const [AutofillHints.password],),),@@ -1979,16 +2030,8 @@ class _TextInputPreviewState extends State<_TextInputPreview> {child: TextInputComponent(label: 'Recovery key',hintText: 'Enter recovery key',- alertText: 'Save this key somewhere safe before continuing.',- ),- ),- _CatalogPreviewGroup(- title: 'Read only',- child: TextInputComponent(- controller: _readOnlyController,- label: 'Owner',- readOnly: true,- suffix: const _CatalogHugeIcon(HugeIcons.strokeRoundedLock),+ message: 'Save this key somewhere safe before continuing.',+ messageType: TextInputComponentMessageType.alert,),),const _CatalogPreviewGroup(@@ -1997,7 +2040,6 @@ class _TextInputPreviewState extends State<_TextInputPreview> {label: 'Referral code',hintText: 'SUMMER2026',maxLength: 12,- counterText: '',textCapitalization: TextCapitalization.characters,),),@@ -2006,9 +2048,10 @@ class _TextInputPreviewState extends State<_TextInputPreview> {child: TextInputComponent(label: 'Description',hintText: 'Hint text',- errorText: 'This is an error',+ message: 'This is an error',+ messageType: TextInputComponentMessageType.error,maxLines: 4,- suffix: _CatalogHugeIcon(HugeIcons.strokeRoundedCopy01),+ suffix: _TextInputPreviewIcon(HugeIcons.strokeRoundedCopy01),),),const _CatalogPreviewGroup(@@ -2017,7 +2060,7 @@ class _TextInputPreviewState extends State<_TextInputPreview> {label: 'Description',hintText: 'Hint text',maxLines: 4,- suffix: _CatalogHugeIcon(HugeIcons.strokeRoundedCopy01),+ suffix: _TextInputPreviewIcon(HugeIcons.strokeRoundedCopy01),),),const _CatalogPreviewGroup(@@ -2033,15 +2076,12 @@ class _TextInputPreviewState extends State<_TextInputPreview> {child: TextInputComponent(hintText: 'Hint text',maxLines: 4,- suffix: _CatalogHugeIcon(HugeIcons.strokeRoundedCopy01),+ suffix: _TextInputPreviewIcon(HugeIcons.strokeRoundedCopy01),),),const _CatalogPreviewGroup(title: 'Multiline: no label',- child: TextInputComponent(- hintText: 'Hint text',- maxLines: 4,- ),+ child: TextInputComponent(hintText: 'Hint text', maxLines: 4),),const _CatalogPreviewGroup(title: 'Multiline: focused',@@ -2049,8 +2089,7 @@ class _TextInputPreviewState extends State<_TextInputPreview> {label: 'Description',hintText: 'Hint text',maxLines: 4,- isFocused: true,- suffix: _CatalogHugeIcon(HugeIcons.strokeRoundedCopy01),+ suffix: _TextInputPreviewIcon(HugeIcons.strokeRoundedCopy01),),),const _CatalogPreviewGroup(@@ -2059,7 +2098,8 @@ class _TextInputPreviewState extends State<_TextInputPreview> {label: 'Description',hintText: 'Hint text',maxLines: 4,- errorText: 'This is an error',+ message: 'This is an error',+ messageType: TextInputComponentMessageType.error,),),const _CatalogPreviewGroup(@@ -2068,7 +2108,8 @@ class _TextInputPreviewState extends State<_TextInputPreview> {label: 'Description',hintText: 'Hint text',maxLines: 4,- successText: 'Saved',+ message: 'Saved',+ messageType: TextInputComponentMessageType.success,),),const _CatalogPreviewGroup(@@ -2077,8 +2118,8 @@ class _TextInputPreviewState extends State<_TextInputPreview> {label: 'Description',hintText: 'Hint text',maxLines: 4,- enabled: false,- suffix: _CatalogHugeIcon(HugeIcons.strokeRoundedCopy01),+ isDisabled: true,+ suffix: _TextInputPreviewIcon(HugeIcons.strokeRoundedCopy01),),),],@@ -2086,6 +2127,17 @@ class _TextInputPreviewState extends State<_TextInputPreview> {}}+class _TextInputPreviewIcon extends StatelessWidget {+ const _TextInputPreviewIcon(this.icon);++ final HugeIconData icon;++ @override+ Widget build(BuildContext context) {+ return _CatalogHugeIcon(icon, color: context.componentColors.textLighter);+ }+}+class TitleBarPreview extends StatelessWidget {const TitleBarPreview({super.key});@@ -2203,11 +2255,13 @@ class _TitleBarSample extends StatelessWidget {TitleBarComponentVariant.partiallyPreserved ||TitleBarComponentVariant.preserved ||TitleBarComponentVariant.syncing ||- TitleBarComponentVariant.videoProcessing =>- const _CatalogHugeIcon(HugeIcons.strokeRoundedMoreHorizontal),+ TitleBarComponentVariant.videoProcessing => const _CatalogHugeIcon(+ HugeIcons.strokeRoundedMoreHorizontal,+ ),TitleBarComponentVariant.settings ||- TitleBarComponentVariant.titleTopbar =>- const _CatalogHugeIcon(HugeIcons.strokeRoundedSearch01),+ TitleBarComponentVariant.titleTopbar => const _CatalogHugeIcon(+ HugeIcons.strokeRoundedSearch01,+ ),_ => null,};}@@ -2216,14 +2270,15 @@ class _TitleBarSample extends StatelessWidget {return switch (variant) {TitleBarComponentVariant.preserving ||TitleBarComponentVariant.partiallyPreserved ||- TitleBarComponentVariant.preserved =>- const _CatalogHugeIcon(HugeIcons.strokeRoundedCheckmarkCircle01),+ TitleBarComponentVariant.preserved => const _CatalogHugeIcon(+ HugeIcons.strokeRoundedCheckmarkCircle01,+ ),TitleBarComponentVariant.syncing => const _CatalogHugeIcon(- HugeIcons.strokeRoundedRefresh,- ),+ HugeIcons.strokeRoundedRefresh,+ ),TitleBarComponentVariant.videoProcessing => const _CatalogHugeIcon(- HugeIcons.strokeRoundedVideo01,- ),+ HugeIcons.strokeRoundedVideo01,+ ),_ => null,};}@@ -2238,10 +2293,7 @@ class _HeaderPreview extends StatelessWidget {children: [_CatalogPreviewGroup(title: 'Title + subtitle + two actions',- child: _HeaderSample(- subtitle: true,- actionCount: 2,- ),+ child: _HeaderSample(subtitle: true, actionCount: 2),),_CatalogPreviewGroup(title: 'Title + two actions',@@ -2255,45 +2307,26 @@ class _HeaderPreview extends StatelessWidget {title: 'Title + subtitle',child: _HeaderSample(subtitle: true),),- _CatalogPreviewGroup(- title: 'Title only',- child: _HeaderSample(),- ),+ _CatalogPreviewGroup(title: 'Title only', child: _HeaderSample()),_CatalogPreviewGroup(title: 'Title + subtitle + one action',- child: _HeaderSample(- subtitle: true,- actionCount: 1,- ),+ child: _HeaderSample(subtitle: true, actionCount: 1),),_CatalogPreviewGroup(title: 'Image + subtitle + two actions',- child: _HeaderSample(- image: true,- subtitle: true,- actionCount: 2,- ),+ child: _HeaderSample(image: true, subtitle: true, actionCount: 2),),_CatalogPreviewGroup(title: 'Image + two actions',- child: _HeaderSample(- image: true,- actionCount: 2,- ),+ child: _HeaderSample(image: true, actionCount: 2),),_CatalogPreviewGroup(title: 'Image + one action',- child: _HeaderSample(- image: true,- actionCount: 1,- ),+ child: _HeaderSample(image: true, actionCount: 1),),_CatalogPreviewGroup(title: 'Image + subtitle',- child: _HeaderSample(- image: true,- subtitle: true,- ),+ child: _HeaderSample(image: true, subtitle: true),),_CatalogPreviewGroup(title: 'Image only',@@ -2301,11 +2334,7 @@ class _HeaderPreview extends StatelessWidget {),_CatalogPreviewGroup(title: 'Image + subtitle + one action',- child: _HeaderSample(- image: true,- subtitle: true,- actionCount: 1,- ),+ child: _HeaderSample(image: true, subtitle: true, actionCount: 1),),],);@@ -2335,7 +2364,7 @@ class _HeaderSample extends StatelessWidget {tooltip: index == 0 ? 'Add' : 'Create',variant: IconButtonComponentVariant.primary,icon: const _CatalogHugeIcon(HugeIcons.strokeRoundedAdd01),- onPressed: () {},+ onTap: () {},),],);@@ -2428,8 +2457,10 @@ class _SelectionPreviewState extends State<_SelectionPreview> {label: 'Selected radio',),LabeledControlComponent(- control:- ToggleSwitchComponent(selected: false, onChanged: null),+ control: ToggleSwitchComponent(+ selected: false,+ onChanged: null,+ ),label: 'Off switch',),],@@ -2469,11 +2500,7 @@ class _SelectionPreviewState extends State<_SelectionPreview> {}}-enum _MenuItemTrailingKind {- icon,- toggle,- none,-}+enum _MenuItemTrailingKind { icon, toggle, none }class _MenuItemPreview extends StatefulWidget {const _MenuItemPreview();@@ -2505,16 +2532,8 @@ class _MenuItemPreviewState extends State<_MenuItemPreview> {),),const _CatalogPreviewGroup(- title: 'Loading',- child: _MenuItemLoadingPreview(),- ),- const _CatalogPreviewGroup(- title: 'Success',- child: _MenuItemSuccessPreview(),- ),- const _CatalogPreviewGroup(- title: 'Loading only',- child: _MenuItemLoadingOnlyPreview(),+ title: 'Interaction states',+ child: _MenuItemInteractionStatesPreview(),),_CatalogPreviewGroup(title: 'Display only',@@ -2524,29 +2543,18 @@ class _MenuItemPreviewState extends State<_MenuItemPreview> {return MenuComponent(title: 'Storage plan',subtitle: 'Gestures disabled for read-only rows',- leading:- const _CatalogHugeIcon(HugeIcons.strokeRoundedDatabase),+ leading: const _CatalogHugeIcon(+ HugeIcons.strokeRoundedDatabase,+ ),trailing: Text('2 TB',style: TextStyles.body.copyWith(color: colors.textLight),),- gesturesEnabled: false,+ isDisabled: true,);},),),- const _CatalogPreviewGroup(- title: 'Async state',- child: MenuComponent(- title: 'Check for updates',- subtitle: 'Shows loading and success states',- leading: _CatalogHugeIcon(HugeIcons.strokeRoundedRefresh),- trailing: _CatalogTrailingIcon(HugeIcons.strokeRoundedArrowRight01),- surfaceExecutionStates: true,- alwaysShowSuccessState: true,- onTap: _completeAfterDelay,- ),- ),_CatalogPreviewGroup(title: 'Destructive',child: Builder(@@ -2555,8 +2563,9 @@ class _MenuItemPreviewState extends State<_MenuItemPreview> {return MenuComponent(title: 'Delete account',subtitle: 'Warning color title and icon',- leading:- const _CatalogHugeIcon(HugeIcons.strokeRoundedDelete02),+ leading: const _CatalogHugeIcon(+ HugeIcons.strokeRoundedDelete02,+ ),trailing: const _CatalogTrailingIcon(HugeIcons.strokeRoundedArrowRight01,),@@ -2592,50 +2601,84 @@ Future<void> _completeAfterDelay() {return Future<void>.delayed(const Duration(milliseconds: 650));}-class _MenuItemLoadingPreview extends StatelessWidget {- const _MenuItemLoadingPreview();-- @override- Widget build(BuildContext context) {- return const MenuComponent(- title: 'Updating backup',- subtitle: 'Tap to see the trailing loading state',- leading: _CatalogHugeIcon(HugeIcons.strokeRoundedCloudUpload),- trailing: _CatalogTrailingIcon(HugeIcons.strokeRoundedArrowRight01),- surfaceExecutionStates: true,- onTap: _completeAfterDelay,- );- }+Future<void> _completeSlowly() {+ return Future<void>.delayed(const Duration(milliseconds: 900));}-class _MenuItemLoadingOnlyPreview extends StatelessWidget {- const _MenuItemLoadingOnlyPreview();+Future<void> _completeQuickly() {+ return Future<void>.delayed(const Duration(milliseconds: 120));+}- @override- Widget build(BuildContext context) {- return const MenuComponent(- title: 'Opening sessions',- subtitle: 'Loading-only execution state',- leading: _CatalogHugeIcon(HugeIcons.strokeRoundedUserGroup),- trailing: _CatalogTrailingIcon(HugeIcons.strokeRoundedArrowRight01),- showOnlyLoadingState: true,- onTap: _completeAfterDelay,- );+Future<void> _failAfterDelay(BuildContext context) async {+ await Future<void>.delayed(const Duration(milliseconds: 900));+ if (context.mounted) {+ ScaffoldMessenger.of(+ context,+ ).showSnackBar(const SnackBar(content: Text('Something went wrong')));}+ throw StateError('Preview action failed');}-class _MenuItemSuccessPreview extends StatelessWidget {- const _MenuItemSuccessPreview();+class _MenuItemInteractionStatesPreview extends StatelessWidget {+ const _MenuItemInteractionStatesPreview();@overrideWidget build(BuildContext context) {- return const MenuComponent(- title: 'Copied recovery key',- subtitle: 'Tap to see completion replace trailing slot',- leading: _CatalogHugeIcon(HugeIcons.strokeRoundedCopy01),- trailing: _CatalogTrailingIcon(HugeIcons.strokeRoundedArrowRight01),- alwaysShowSuccessState: true,- onTap: _completeAfterDelay,+ return Column(+ children: [+ MenuComponent(+ title: 'Open storage plan',+ subtitle: 'Tap only, no execution UI',+ leading: const _CatalogHugeIcon(HugeIcons.strokeRoundedDatabase),+ trailing: const _CatalogTrailingIcon(+ HugeIcons.strokeRoundedArrowRight01,+ ),+ shouldSurfaceExecutionStates: false,+ onTap: () {+ ScaffoldMessenger.of(+ context,+ ).showSnackBar(const SnackBar(content: Text('Opened')));+ },+ ),+ const SizedBox(height: Spacing.md),+ const MenuComponent(+ title: 'Updating backup',+ subtitle: 'Execution loading, then success',+ leading: _CatalogHugeIcon(HugeIcons.strokeRoundedCloudUpload),+ trailing: _CatalogTrailingIcon(HugeIcons.strokeRoundedArrowRight01),+ onTap: _completeSlowly,+ ),+ const SizedBox(height: Spacing.md),+ const MenuComponent(+ title: 'Copied recovery key',+ subtitle: 'Fast success confirmation',+ leading: _CatalogHugeIcon(HugeIcons.strokeRoundedCopy01),+ trailing: _CatalogTrailingIcon(HugeIcons.strokeRoundedArrowRight01),+ shouldShowSuccessConfirmation: true,+ onTap: _completeQuickly,+ ),+ const SizedBox(height: Spacing.md),+ MenuComponent(+ title: 'Sync backup',+ subtitle: 'Error resets to idle',+ leading: const _CatalogHugeIcon(HugeIcons.strokeRoundedRefresh),+ trailing: const _CatalogTrailingIcon(+ HugeIcons.strokeRoundedArrowRight01,+ ),+ titleColor: context.componentColors.warning,+ iconColor: context.componentColors.warning,+ onTap: () => _failAfterDelay(context),+ ),+ const SizedBox(height: Spacing.md),+ const MenuComponent(+ title: 'Opening sessions',+ subtitle: 'Loading only, no success tick',+ leading: _CatalogHugeIcon(HugeIcons.strokeRoundedUserGroup),+ trailing: _CatalogTrailingIcon(HugeIcons.strokeRoundedArrowRight01),+ showOnlyLoadingState: true,+ onTap: _completeSlowly,+ ),+ ],);}}@@ -2718,12 +2761,12 @@ class _MenuItemExample extends StatelessWidget {}return switch (trailingKind) {_MenuItemTrailingKind.icon => const _CatalogTrailingIcon(- HugeIcons.strokeRoundedMoreVertical,- ),+ HugeIcons.strokeRoundedMoreVertical,+ ),_MenuItemTrailingKind.toggle => ToggleSwitchComponent(- selected: toggleSelected,- onChanged: onToggleChanged,- ),+ selected: toggleSelected,+ onChanged: onToggleChanged,+ ),_MenuItemTrailingKind.none => null,};}diff --git a/mobile/packages/ente_components/lib/components/buttons/button_component.dart b/mobile/packages/ente_components/lib/components/buttons/button_component.dartindex a6210ba475..139853abc2 100644--- a/mobile/packages/ente_components/lib/components/buttons/button_component.dart+++ b/mobile/packages/ente_components/lib/components/buttons/button_component.dart@@ -1,5 +1,7 @@import 'dart:async';+import 'package:ente_components/models/component_execution_state.dart';+import 'package:ente_components/theme/colors.dart';import 'package:ente_components/theme/motion.dart';import 'package:ente_components/theme/radii.dart';import 'package:ente_components/theme/spacing.dart';@@ -7,7 +9,6 @@ import 'package:ente_components/theme/text_styles.dart';import 'package:ente_components/theme/theme.dart';import 'package:flutter/foundation.dart';import 'package:flutter/material.dart';-import 'package:flutter/scheduler.dart';import 'package:hugeicons/hugeicons.dart';enum ButtonComponentVariant {@@ -19,26 +20,11 @@ enum ButtonComponentVariant {link,}-enum ButtonComponentSize {- small,- large,-}--enum _ButtonVisualState {- normal,- hover,- pressed,-}--enum _ButtonExecutionState {- idle,- inProgress,- successful,-}+enum ButtonComponentSize { small, large }/// Figma: https://www.figma.com/design/BuBNPPytxlVnqfmCUW0mgz/Ente-Visual-Design?node-id=2207-41578&m=dev/// Section: Buttons / Button Small-/// Specs: 52px height, 20px radius, 24px horizontal padding, 8px icon gap.+/// Specs: 52px height, 20px radius, 24px horizontal padding./// States: default, hover, pressed, disabled, loading, success.class ButtonComponent extends StatefulWidget {const ButtonComponent({@@ -46,29 +32,21 @@ class ButtonComponent extends StatefulWidget {required this.label,this.onTap,this.variant = ButtonComponentVariant.primary,- this.size = ButtonComponentSize.small,- this.leading,- this.trailing,+ this.size = ButtonComponentSize.large,this.isDisabled = false,this.shouldSurfaceExecutionStates = true,this.shouldShowSuccessConfirmation = false,this.progressStatus,- this.iconColor,- this.width,});final String label;final FutureOr<void> Function()? onTap;final ButtonComponentVariant variant;final ButtonComponentSize size;- final Widget? leading;- final Widget? trailing;final bool isDisabled;final bool shouldSurfaceExecutionStates;final bool shouldShowSuccessConfirmation;final ValueListenable<String>? progressStatus;- final Color? iconColor;- final double? width;@overrideState<ButtonComponent> createState() => _ButtonComponentState();@@ -80,7 +58,7 @@ class _ButtonComponentState extends State<ButtonComponent>static const double _contentMinHeight = 24;static const double _verticalPadding = 14;static const Duration _loadingDelay = Duration(milliseconds: 300);- static const Duration _successDisplayDuration = Duration(seconds: 2);+ static const Duration _successDisplayDuration = Duration(seconds: 1);static const Duration _minimumPressDuration = Duration(milliseconds: 120);late final AnimationController _loadingController;@@ -88,12 +66,11 @@ class _ButtonComponentState extends State<ButtonComponent>bool _isPressed = false;int _pressToken = 0;DateTime? _tapDownTime;- double? _idleWidth;Timer? _loadingTimer;Timer? _successResetTimer;Timer? _pressReleaseTimer;- _ButtonExecutionState _executionState = _ButtonExecutionState.idle;bool _loadingVisible = false;+ ComponentExecutionState _executionState = ComponentExecutionState.idle;@overridevoid initState() {@@ -108,14 +85,6 @@ class _ButtonComponentState extends State<ButtonComponent>@overridevoid didUpdateWidget(covariant ButtonComponent oldWidget) {super.didUpdateWidget(oldWidget);- final idleContentChanged = widget.variant != oldWidget.variant ||- widget.label != oldWidget.label ||- widget.leading != oldWidget.leading ||- widget.trailing != oldWidget.trailing;- if (widget.size != oldWidget.size ||- (widget.size == ButtonComponentSize.small && idleContentChanged)) {- _idleWidth = null;- }if (widget.isDisabled && !oldWidget.isDisabled) {_isPressed = false;}@@ -133,12 +102,12 @@ class _ButtonComponentState extends State<ButtonComponent>@overrideWidget build(BuildContext context) {- final isInlineLink = widget.variant == ButtonComponentVariant.link &&+ final isInlineLink =+ widget.variant == ButtonComponentVariant.link &&widget.size == ButtonComponentSize.small;final resolvedColors = _colors(context);final enabled = _canHandleGestures;final verticalPadding = isInlineLink ? Spacing.xs : _buttonVerticalPadding;- _captureIdleWidth();return MouseRegion(cursor: enabled ? SystemMouseCursors.click : SystemMouseCursors.forbidden,@@ -157,17 +126,14 @@ class _ButtonComponentState extends State<ButtonComponent>child: AnimatedContainer(duration: Motion.standard,curve: Curves.easeInOutCubic,- width: widget.width ??- (widget.size == ButtonComponentSize.large- ? double.infinity- : _executionWidth),+ width: widget.size == ButtonComponentSize.large+ ? double.infinity+ : null,decoration: BoxDecoration(color: resolvedColors.background,- borderRadius:- BorderRadius.circular(isInlineLink ? 0 : Radii.button),- border: resolvedColors.border == null- ? null- : Border.all(color: resolvedColors.border!),+ borderRadius: BorderRadius.circular(+ isInlineLink ? 0 : Radii.button,+ ),),child: Padding(padding: EdgeInsets.symmetric(@@ -182,20 +148,7 @@ class _ButtonComponentState extends State<ButtonComponent>duration: Motion.quick,switchInCurve: Curves.easeOutCubic,switchOutCurve: Curves.easeInCubic,- transitionBuilder: (child, animation) {- return FadeTransition(- opacity: animation,- child: ScaleTransition(- scale: Tween<double>(begin: 0.92, end: 1).animate(- CurvedAnimation(- parent: animation,- curve: Curves.easeOutCubic,- ),- ),- child: child,- ),- );- },+ transitionBuilder: _contentTransition,child: _content(context, resolvedColors.foreground),),),@@ -206,12 +159,6 @@ class _ButtonComponentState extends State<ButtonComponent>);}- _ButtonVisualState get _effectiveVisualState {- if (_isPressed) return _ButtonVisualState.pressed;- if (_isHovered) return _ButtonVisualState.hover;- return _ButtonVisualState.normal;- }-void _setHovered(bool value) {if (!_canHandleGestures || _isHovered == value) {return;@@ -259,58 +206,28 @@ class _ButtonComponentState extends State<ButtonComponent>Widget _content(BuildContext context, Color foreground) {if (_showLoading) {- final spinner = SizedBox(- width: _executionIconSize,- height: _executionIconSize,- child: Center(- child: RotationTransition(- turns: _loadingController,- child: HugeIcon(- icon: HugeIcons.strokeRoundedLoading03,- color: _iconForeground(foreground),- size: _executionIconSize,- ),- ),- ),- );- if (widget.progressStatus == null) {- return KeyedSubtree(- key: const ValueKey('loading'),- child: spinner,- );- }- return Row(+ return _executionContent(key: const ValueKey('loading'),- mainAxisAlignment: MainAxisAlignment.center,- mainAxisSize: MainAxisSize.min,- children: [- ValueListenableBuilder<String>(- valueListenable: widget.progressStatus!,- builder: (context, value, _) {- if (value.isEmpty) return const SizedBox.shrink();- return Padding(- padding: const EdgeInsets.only(right: Spacing.sm),- child: Text(- value,- style: TextStyles.mini.copyWith(color: foreground),- ),- );- },- ),- spinner,- ],+ child: _loadingContent(foreground),);}if (_showSuccess) {- return HugeIcon(+ return _executionContent(key: const ValueKey('success'),- icon: HugeIcons.strokeRoundedTick02,- size: _executionIconSize,- color: _iconForeground(foreground),+ child: HugeIcon(+ icon: HugeIcons.strokeRoundedTick02,+ size: _executionIconSize,+ color: foreground,+ ),);}- final underlined = widget.variant == ButtonComponentVariant.link ||+ return _idleContent(foreground);+ }++ Widget _idleContent(Color foreground) {+ final underlined =+ widget.variant == ButtonComponentVariant.link ||widget.variant == ButtonComponentVariant.tertiaryCritical;final label = Text(widget.label,@@ -322,40 +239,86 @@ class _ButtonComponentState extends State<ButtonComponent>decorationColor: underlined ? foreground : null,),);- final children = <Widget>[- if (widget.leading != null) ...[- IconTheme.merge(- data: IconThemeData(size: 20, color: _iconForeground(foreground)),- child: widget.leading!,- ),- const SizedBox(width: Spacing.sm),- ],- if (widget.size == ButtonComponentSize.large)- Flexible(child: label)- else- label,- if (widget.trailing != null) ...[- const SizedBox(width: Spacing.md),- IconTheme.merge(- data: IconThemeData(size: 20, color: _iconForeground(foreground)),- child: widget.trailing!,- ),- ],- ];-return Row(key: const ValueKey('content'),mainAxisSize: widget.size == ButtonComponentSize.large? MainAxisSize.max: MainAxisSize.min,- mainAxisAlignment: widget.trailing == null- ? MainAxisAlignment.center- : MainAxisAlignment.spaceBetween,- children: children,+ mainAxisAlignment: MainAxisAlignment.center,+ children: [+ if (widget.variant != ButtonComponentVariant.link)+ Flexible(child: label)+ else+ label,+ ],+ );+ }++ Widget _executionContent({required Key key, required Widget child}) {+ return Stack(+ key: key,+ alignment: Alignment.center,+ children: [+ Visibility(+ visible: false,+ maintainAnimation: true,+ maintainSize: true,+ maintainState: true,+ child: _idleContent(Colors.transparent),+ ),+ child,+ ],+ );+ }++ Widget _contentTransition(Widget child, Animation<double> animation) {+ return FadeTransition(+ opacity: animation,+ child: ScaleTransition(+ scale: Tween<double>(begin: 0.92, end: 1).animate(+ CurvedAnimation(parent: animation, curve: Curves.easeOutCubic),+ ),+ child: child,+ ),);}- Color _iconForeground(Color foreground) => widget.iconColor ?? foreground;+ Widget _loadingContent(Color foreground) {+ return Row(+ mainAxisAlignment: MainAxisAlignment.center,+ mainAxisSize: MainAxisSize.min,+ children: [+ if (widget.progressStatus != null)+ ValueListenableBuilder<String>(+ valueListenable: widget.progressStatus!,+ builder: (context, value, _) {+ if (value.isEmpty) return const SizedBox.shrink();+ return Padding(+ padding: const EdgeInsets.only(right: Spacing.sm),+ child: Text(+ value,+ style: TextStyles.mini.copyWith(color: foreground),+ ),+ );+ },+ ),+ SizedBox(+ width: _executionIconSize,+ height: _executionIconSize,+ child: Center(+ child: RotationTransition(+ turns: _loadingController,+ child: HugeIcon(+ icon: HugeIcons.strokeRoundedLoading03,+ color: foreground,+ size: _executionIconSize,+ ),+ ),+ ),+ ),+ ],+ );+ }double get _buttonVerticalPadding {return _verticalPadding;@@ -365,23 +328,23 @@ class _ButtonComponentState extends State<ButtonComponent>if (widget.isDisabled || widget.onTap == null) {return _ResolvedButtonColors(background: _disabledBackground(context),- foreground: context.componentColors.textLighter,- border: null,+ foreground: _componentColors(context).textLighter,);}- final visualState =- _showLoading ? _ButtonVisualState.pressed : _effectiveVisualState;+ final isPressed = !_showLoading && !_showSuccess && _isPressed;+ final isHovered = !_showLoading && !_showSuccess && _isHovered;return _ResolvedButtonColors(- background: switch (visualState) {- _ButtonVisualState.pressed when !_showSuccess =>- _pressedBackground(context),- _ButtonVisualState.hover when !_showSuccess =>- _hoverBackground(context),- _ => _background(context),- },- foreground: _foreground(context, visualState),- border: _borderColor(),+ background: isPressed+ ? _pressedBackground(context)+ : isHovered+ ? _hoverBackground(context)+ : _background(context),+ foreground: _foreground(+ context,+ isPressed: isPressed,+ isHovered: isHovered,+ ),);}@@ -402,24 +365,19 @@ class _ButtonComponentState extends State<ButtonComponent>bool get _canHandleGestures =>!widget.isDisabled &&widget.onTap != null &&- _executionState == _ButtonExecutionState.idle;+ !_isExecuting &&+ !_isSuccessful;++ bool get _isExecuting =>+ _executionState == ComponentExecutionState.inProgress;++ bool get _isSuccessful =>+ _executionState == ComponentExecutionState.successful;bool get _showLoading =>- widget.shouldSurfaceExecutionStates &&- _executionState == _ButtonExecutionState.inProgress &&- _loadingVisible;-- bool get _showSuccess =>- widget.shouldSurfaceExecutionStates &&- _executionState == _ButtonExecutionState.successful;-- double? get _executionWidth {- if (widget.size != ButtonComponentSize.small ||- (!_showLoading && !_showSuccess)) {- return null;- }- return _idleWidth;- }+ widget.shouldSurfaceExecutionStates && _isExecuting && _loadingVisible;++ bool get _showSuccess => widget.shouldSurfaceExecutionStates && _isSuccessful;Future<void> _handleTap() async {final callback = widget.onTap;@@ -429,7 +387,7 @@ class _ButtonComponentState extends State<ButtonComponent>var loadingSurfaced = false;_loadingTimer?.cancel();setState(() {- _executionState = _ButtonExecutionState.inProgress;+ _executionState = ComponentExecutionState.inProgress;_loadingVisible = false;});_loadingTimer = Timer(_loadingDelay, () {@@ -450,7 +408,8 @@ class _ButtonComponentState extends State<ButtonComponent>_loadingTimer?.cancel();_loadingTimer = null;- final shouldShowSuccess = widget.shouldSurfaceExecutionStates &&+ final shouldShowSuccess =+ widget.shouldSurfaceExecutionStates &&(loadingSurfaced ||(loadingPending && widget.shouldShowSuccessConfirmation));@@ -458,7 +417,7 @@ class _ButtonComponentState extends State<ButtonComponent>_showSuccessForDuration();} else {setState(() {- _executionState = _ButtonExecutionState.idle;+ _executionState = ComponentExecutionState.idle;_loadingVisible = false;_isPressed = false;});@@ -467,19 +426,20 @@ class _ButtonComponentState extends State<ButtonComponent>} catch (_) {_loadingTimer?.cancel();_loadingTimer = null;- if (!mounted) return;- setState(() {- _executionState = _ButtonExecutionState.idle;- _loadingVisible = false;- _isPressed = false;- });- _syncLoadingController();+ if (mounted) {+ setState(() {+ _executionState = ComponentExecutionState.idle;+ _loadingVisible = false;+ _isPressed = false;+ });+ _syncLoadingController();+ }}}void _showSuccessForDuration() {setState(() {- _executionState = _ButtonExecutionState.successful;+ _executionState = ComponentExecutionState.successful;_loadingVisible = false;_isPressed = false;});@@ -488,37 +448,18 @@ class _ButtonComponentState extends State<ButtonComponent>_successResetTimer = Timer(_successDisplayDuration, () {if (!mounted) return;setState(() {- _executionState = _ButtonExecutionState.idle;+ _executionState = ComponentExecutionState.idle;_loadingVisible = false;});_syncLoadingController();});}- void _captureIdleWidth() {- if (widget.size != ButtonComponentSize.small ||- _showLoading ||- _showSuccess) {- return;- }- SchedulerBinding.instance.addPostFrameCallback((_) {- if (!mounted || widget.size != ButtonComponentSize.small) return;- final box = context.findRenderObject() as RenderBox?;- if (box == null || !box.hasSize) return;- final width = box.size.width;- if (_idleWidth != null && (_idleWidth! - width).abs() < 0.5) return;- setState(() => _idleWidth = width);- });- }-Color _background(BuildContext context) {- final colors = context.componentColors;+ final colors = _componentColors(context);return switch (widget.variant) {ButtonComponentVariant.primary => colors.primary,- ButtonComponentVariant.secondary- when widget.size == ButtonComponentSize.large =>- colors.primaryLight,- ButtonComponentVariant.secondary => colors.fillDark,+ ButtonComponentVariant.secondary => colors.primaryLight,ButtonComponentVariant.neutral => colors.fillBase,ButtonComponentVariant.critical => colors.warning,ButtonComponentVariant.tertiaryCritical => Colors.transparent,@@ -527,10 +468,10 @@ class _ButtonComponentState extends State<ButtonComponent>}Color _hoverBackground(BuildContext context) {- final colors = context.componentColors;+ final colors = _componentColors(context);return switch (widget.variant) {ButtonComponentVariant.primary => colors.primaryDark,- ButtonComponentVariant.secondary => colors.fillDarker,+ ButtonComponentVariant.secondary => colors.primaryLightHover,ButtonComponentVariant.neutral => colors.fillBase,ButtonComponentVariant.critical => colors.warningDark,ButtonComponentVariant.tertiaryCritical => Colors.transparent,@@ -539,10 +480,10 @@ class _ButtonComponentState extends State<ButtonComponent>}Color _pressedBackground(BuildContext context) {- final colors = context.componentColors;+ final colors = _componentColors(context);return switch (widget.variant) {ButtonComponentVariant.primary => colors.primaryDarker,- ButtonComponentVariant.secondary => colors.fillDarkest,+ ButtonComponentVariant.secondary => colors.primaryLightPressed,ButtonComponentVariant.neutral => colors.fillBase,ButtonComponentVariant.critical => colors.warningDarker,ButtonComponentVariant.tertiaryCritical => Colors.transparent,@@ -551,7 +492,7 @@ class _ButtonComponentState extends State<ButtonComponent>}Color _disabledBackground(BuildContext context) {- final colors = context.componentColors;+ final colors = _componentColors(context);return switch (widget.variant) {ButtonComponentVariant.tertiaryCritical => Colors.transparent,ButtonComponentVariant.link => Colors.transparent,@@ -559,34 +500,35 @@ class _ButtonComponentState extends State<ButtonComponent>};}- Color _foreground(BuildContext context, _ButtonVisualState visualState) {- final colors = context.componentColors;+ Color _foreground(+ BuildContext context, {+ required bool isPressed,+ required bool isHovered,+ }) {+ final colors = _componentColors(context);return switch (widget.variant) {ButtonComponentVariant.primary => colors.specialWhite,- ButtonComponentVariant.secondary- when widget.size == ButtonComponentSize.large =>- switch (visualState) {- _ButtonVisualState.normal => colors.primary,- _ => colors.textBase,- },- ButtonComponentVariant.secondary => colors.textBase,+ ButtonComponentVariant.secondary =>+ isPressed ? colors.primaryDarker : colors.primaryDark,ButtonComponentVariant.neutral => colors.textReverse,ButtonComponentVariant.critical => colors.specialWhite,- ButtonComponentVariant.tertiaryCritical => switch (visualState) {- _ButtonVisualState.pressed => colors.warningDarker,- _ButtonVisualState.hover => colors.warningDark,- _ButtonVisualState.normal => colors.warning,- },- ButtonComponentVariant.link => switch (visualState) {- _ButtonVisualState.pressed => colors.primaryDarker,- _ButtonVisualState.hover => colors.primaryDark,- _ButtonVisualState.normal => colors.primary,- },+ ButtonComponentVariant.tertiaryCritical =>+ isPressed+ ? colors.warningDarker+ : isHovered+ ? colors.warningDark+ : colors.warning,+ ButtonComponentVariant.link =>+ isPressed+ ? colors.primaryDarker+ : isHovered+ ? colors.primaryDark+ : colors.primary,};}- Color? _borderColor() {- return null;+ ColorTokens _componentColors(BuildContext context) {+ return context.componentColors;}}@@ -594,10 +536,8 @@ class _ResolvedButtonColors {const _ResolvedButtonColors({required this.background,required this.foreground,- required this.border,});final Color background;final Color foreground;- final Color? border;}diff --git a/mobile/packages/ente_components/lib/components/buttons/icon_button_component.dart b/mobile/packages/ente_components/lib/components/buttons/icon_button_component.dartindex be92c8a37b..817e2f045c 100644--- a/mobile/packages/ente_components/lib/components/buttons/icon_button_component.dart+++ b/mobile/packages/ente_components/lib/components/buttons/icon_button_component.dart@@ -1,8 +1,12 @@+import 'dart:async';++import 'package:ente_components/models/component_execution_state.dart';import 'package:ente_components/theme/motion.dart';import 'package:ente_components/theme/radii.dart';import 'package:ente_components/theme/spacing.dart';import 'package:ente_components/theme/theme.dart';import 'package:flutter/material.dart';+import 'package:hugeicons/hugeicons.dart';enum IconButtonComponentVariant {primary,@@ -13,50 +17,73 @@ enum IconButtonComponentVariant {circular,}-enum IconButtonComponentState {- normal,- hover,- pressed,-}-/// Figma: https://www.figma.com/design/BuBNPPytxlVnqfmCUW0mgz/Ente-Visual-Design?node-id=2207-42075&m=dev/// Section: Buttons / Icon Button-/// Specs: 38px square, compact icon affordance with default, hover, pressed, disabled, loading, success states.+/// Specs: 36px square, compact icon affordance with default, hover, pressed,+/// disabled, loading, and success states.class IconButtonComponent extends StatefulWidget {const IconButtonComponent({super.key,required this.icon,- required this.onPressed,+ required this.onTap,this.variant = IconButtonComponentVariant.secondary,- this.state,- this.isLoading = false,- this.isSuccess = false,+ this.shouldSurfaceExecutionStates = true,+ this.shouldShowSuccessConfirmation = false,this.tooltip,});final Widget icon;- final VoidCallback? onPressed;+ final FutureOr<void> Function()? onTap;final IconButtonComponentVariant variant;- final IconButtonComponentState? state;- final bool isLoading;- final bool isSuccess;+ final bool shouldSurfaceExecutionStates;+ final bool shouldShowSuccessConfirmation;final String? tooltip;@overrideState<IconButtonComponent> createState() => _IconButtonComponentState();}-class _IconButtonComponentState extends State<IconButtonComponent> {+class _IconButtonComponentState extends State<IconButtonComponent>+ with SingleTickerProviderStateMixin {+ static const Duration _loadingDelay = Duration(milliseconds: 300);+ static const Duration _successDisplayDuration = Duration(seconds: 1);++ late final AnimationController _loadingController;bool _isHovered = false;bool _isPressed = false;+ Timer? _loadingTimer;+ Timer? _successResetTimer;+ bool _loadingVisible = false;+ ComponentExecutionState _executionState = ComponentExecutionState.idle;++ @override+ void initState() {+ super.initState();+ _loadingController = AnimationController(+ vsync: this,+ duration: const Duration(milliseconds: 800),+ );+ _syncLoadingController();+ }++ @override+ void didUpdateWidget(covariant IconButtonComponent oldWidget) {+ super.didUpdateWidget(oldWidget);+ _syncLoadingController();+ }++ @override+ void dispose() {+ _loadingTimer?.cancel();+ _successResetTimer?.cancel();+ _loadingController.dispose();+ super.dispose();+ }@overrideWidget build(BuildContext context) {- final enabled =- widget.onPressed != null && !widget.isLoading && !widget.isSuccess;- final visualState = _visualState(enabled);- final foreground = _foreground(context, visualState);- final background = _background(context, visualState);+ final enabled = _canHandleGestures;+ final colors = _colors(context);final radius = widget.variant == IconButtonComponentVariant.circular? BorderRadius.circular(35): BorderRadius.circular(Radii.md);@@ -66,31 +93,37 @@ class _IconButtonComponentState extends State<IconButtonComponent> {height: _buttonSize,child: MouseRegion(cursor: enabled ? SystemMouseCursors.click : SystemMouseCursors.basic,- onEnter: enabled ? (_) => _setHovered(true) : null,- onExit: enabled ? (_) => _setHovered(false) : null,+ onEnter: (_) => _setHovered(true),+ onExit: (_) => _setHovered(false),child: GestureDetector(behavior: HitTestBehavior.opaque,- onTap: enabled ? widget.onPressed : null,+ onTap: enabled ? _handleTap : null,onTapDown: enabled ? (_) => _setPressed(true) : null,onTapUp: enabled ? (_) => _setPressed(false) : null,onTapCancel: enabled ? () => _setPressed(false) : null,- child: AnimatedContainer(- key: const ValueKey('icon-button-surface'),- duration: Motion.quick,- curve: Curves.easeInOutCubic,- width: _buttonSize,- height: _buttonSize,- padding: EdgeInsets.all(_outerPadding(visualState)),- alignment: Alignment.center,- decoration: BoxDecoration(- color: background,- borderRadius: radius,- ),- child: Padding(- padding: const EdgeInsets.all(Spacing.sm),- child: AnimatedSwitcher(- duration: Motion.quick,- child: _content(context, foreground),+ child: AnimatedScale(+ scale: enabled && _isPressed ? 0.98 : 1,+ duration: const Duration(milliseconds: 120),+ curve: Curves.easeOutCubic,+ child: AnimatedContainer(+ key: const ValueKey('icon-button-surface'),+ duration: Motion.quick,+ curve: Curves.easeInOutCubic,+ width: _buttonSize,+ height: _buttonSize,+ alignment: Alignment.center,+ decoration: BoxDecoration(+ color: colors.background,+ borderRadius: radius,+ ),+ child: Padding(+ padding: const EdgeInsets.all(Spacing.sm),+ child: AnimatedSwitcher(+ duration: Motion.quick,+ switchInCurve: Curves.easeOutCubic,+ switchOutCurve: Curves.easeInCubic,+ child: _content(colors.foreground),+ ),),),),@@ -102,69 +135,39 @@ class _IconButtonComponentState extends State<IconButtonComponent> {button = Tooltip(message: widget.tooltip!, child: button);}- return Semantics(- button: true,- enabled: enabled,- label: widget.tooltip,- child: button,- );- }-- _ResolvedIconButtonState _visualState(bool enabled) {- if (widget.isLoading) {- return _ResolvedIconButtonState.loading;- }- if (widget.isSuccess) {- return _ResolvedIconButtonState.success;- }- if (!enabled) {- return _ResolvedIconButtonState.disabled;- }-- final forcedState = widget.state;- if (forcedState != null) {- return switch (forcedState) {- IconButtonComponentState.normal => _ResolvedIconButtonState.normal,- IconButtonComponentState.hover => _ResolvedIconButtonState.hover,- IconButtonComponentState.pressed => _ResolvedIconButtonState.pressed,- };- }-- if (_isPressed) {- return _ResolvedIconButtonState.pressed;- }- if (_isHovered) {- return _ResolvedIconButtonState.hover;- }- return _ResolvedIconButtonState.normal;+ return button;}void _setHovered(bool value) {- if (widget.onPressed == null || _isHovered == value) return;+ if (!_canHandleGestures || _isHovered == value) {+ return;+ }setState(() => _isHovered = value);}void _setPressed(bool value) {- if (widget.onPressed == null || _isPressed == value) return;+ if (!_canHandleGestures || _isPressed == value) {+ return;+ }setState(() => _isPressed = value);}- Widget _content(BuildContext context, Color foreground) {- if (widget.isLoading) {- return SizedBox(+ Widget _content(Color foreground) {+ if (_showLoading) {+ return RotationTransition(key: const ValueKey('loading'),- width: _iconSize,- height: _iconSize,- child: CircularProgressIndicator(- strokeWidth: 2,- valueColor: AlwaysStoppedAnimation(foreground),+ turns: _loadingController,+ child: HugeIcon(+ icon: HugeIcons.strokeRoundedLoading03,+ size: _iconSize,+ color: foreground,),);}- if (widget.isSuccess) {- return Icon(+ if (_showSuccess) {+ return HugeIcon(key: const ValueKey('success'),- Icons.check_circle_rounded,+ icon: HugeIcons.strokeRoundedTick02,size: _iconSize,color: foreground,);@@ -176,61 +179,233 @@ class _IconButtonComponentState extends State<IconButtonComponent> {);}- double _outerPadding(_ResolvedIconButtonState state) {+ bool get _canHandleGestures {+ return widget.onTap != null && !_isExecuting && !_isSuccessful;+ }++ bool get _isExecuting =>+ _executionState == ComponentExecutionState.inProgress;++ bool get _isSuccessful =>+ _executionState == ComponentExecutionState.successful;++ bool get _showLoading {+ return widget.shouldSurfaceExecutionStates &&+ _isExecuting &&+ _loadingVisible;+ }++ bool get _showSuccess {+ return widget.shouldSurfaceExecutionStates && _isSuccessful;+ }++ void _syncLoadingController() {+ if (_showLoading) {+ if (!_loadingController.isAnimating) {+ _loadingController.repeat();+ }+ return;+ }++ if (_loadingController.isAnimating || _loadingController.value != 0) {+ _loadingController.stop();+ _loadingController.reset();+ }+ }++ Future<void> _handleTap() async {+ final callback = widget.onTap;+ if (callback == null) return;++ _successResetTimer?.cancel();+ _successResetTimer = null;+ _cancelLoadingTimer();+ setState(() {+ _executionState = ComponentExecutionState.inProgress;+ _loadingVisible = false;+ _isPressed = false;+ });+ _loadingTimer = Timer(_loadingDelay, () {+ if (!mounted) return;+ setState(() {+ _loadingVisible = true;+ _isPressed = false;+ });+ _syncLoadingController();+ });++ try {+ await Future.sync(callback);+ if (!mounted) {+ return;+ }++ final loadingPending = _loadingTimer?.isActive ?? false;+ final shouldShowSuccess =+ widget.shouldSurfaceExecutionStates &&+ (_loadingVisible ||+ (loadingPending && widget.shouldShowSuccessConfirmation));++ _cancelLoadingTimer();++ if (shouldShowSuccess) {+ _showSuccessForDuration();+ } else {+ _clearExecutionState();+ }+ } catch (_) {+ if (mounted) {+ _cancelLoadingTimer();+ _clearExecutionState();+ }+ }+ }++ void _cancelLoadingTimer() {+ _loadingTimer?.cancel();+ _loadingTimer = null;+ }++ void _clearExecutionState() {+ setState(() {+ _executionState = ComponentExecutionState.idle;+ _loadingVisible = false;+ _isPressed = false;+ });+ _syncLoadingController();+ }++ void _showSuccessForDuration() {+ setState(() {+ _executionState = ComponentExecutionState.successful;+ _loadingVisible = false;+ _isPressed = false;+ });+ _syncLoadingController();+ _successResetTimer?.cancel();+ _successResetTimer = Timer(_successDisplayDuration, () {+ if (!mounted) return;+ setState(() {+ _executionState = ComponentExecutionState.idle;+ _loadingVisible = false;+ });+ _syncLoadingController();+ });+ }++ _ResolvedIconButtonColors _colors(BuildContext context) {+ if (_showLoading) {+ return _ResolvedIconButtonColors(+ background: _executionBackground(context),+ foreground: _foreground(context),+ );+ }+ if (_showSuccess) {+ return _ResolvedIconButtonColors(+ background: _executionBackground(context),+ foreground: _foreground(context, isSuccess: true),+ );+ }+ if (widget.onTap == null) {+ return _ResolvedIconButtonColors(+ background: _disabledBackground(context),+ foreground: _foreground(context, isDisabled: true),+ );+ }++ return _ResolvedIconButtonColors(+ background: _isPressed+ ? _pressedBackground(context)+ : _isHovered+ ? _hoverBackground(context)+ : _background(context),+ foreground: _foreground(context),+ );+ }++ Color _background(BuildContext context) {+ final colors = context.componentColors;+ final transparent = colors.specialScrim.withAlpha(0);++ return switch (widget.variant) {+ IconButtonComponentVariant.unfilled ||+ IconButtonComponentVariant.secondary => transparent,+ IconButtonComponentVariant.primary => colors.fillLight,+ IconButtonComponentVariant.critical => colors.fillDark,+ IconButtonComponentVariant.green => colors.primary,+ IconButtonComponentVariant.circular => colors.fillLight,+ };+ }++ Color _hoverBackground(BuildContext context) {+ final colors = context.componentColors;+ final transparent = colors.specialScrim.withAlpha(0);++ return switch (widget.variant) {+ IconButtonComponentVariant.unfilled ||+ IconButtonComponentVariant.secondary => transparent,+ IconButtonComponentVariant.primary => colors.fillDark,+ IconButtonComponentVariant.critical => colors.fillDarker,+ IconButtonComponentVariant.green => colors.primaryDark,+ IconButtonComponentVariant.circular => colors.fillDark,+ };+ }++ Color _pressedBackground(BuildContext context) {+ final colors = context.componentColors;+ final transparent = colors.specialScrim.withAlpha(0);++ return switch (widget.variant) {+ IconButtonComponentVariant.unfilled ||+ IconButtonComponentVariant.secondary => transparent,+ IconButtonComponentVariant.primary => colors.fillDarker,+ IconButtonComponentVariant.critical => colors.fillDarkest,+ IconButtonComponentVariant.green => colors.primaryDarker,+ IconButtonComponentVariant.circular => colors.fillDarker,+ };+ }++ Color _disabledBackground(BuildContext context) {+ final colors = context.componentColors;+ final transparent = colors.specialScrim.withAlpha(0);+return switch (widget.variant) {IconButtonComponentVariant.unfilled ||- IconButtonComponentVariant.secondary =>- 0,- _ => 2,+ IconButtonComponentVariant.secondary => transparent,+ IconButtonComponentVariant.primary ||+ IconButtonComponentVariant.critical ||+ IconButtonComponentVariant.green ||+ IconButtonComponentVariant.circular => colors.fillDark,};}- Color _background(BuildContext context, _ResolvedIconButtonState state) {+ Color _executionBackground(BuildContext context) {final colors = context.componentColors;final transparent = colors.specialScrim.withAlpha(0);return switch (widget.variant) {IconButtonComponentVariant.unfilled ||- IconButtonComponentVariant.secondary =>- transparent,- IconButtonComponentVariant.primary => switch (state) {- _ResolvedIconButtonState.normal => colors.fillLight,- _ResolvedIconButtonState.hover ||- _ResolvedIconButtonState.disabled ||- _ResolvedIconButtonState.loading ||- _ResolvedIconButtonState.success =>- colors.fillDark,- _ResolvedIconButtonState.pressed => colors.fillDarker,- },- IconButtonComponentVariant.critical => switch (state) {- _ResolvedIconButtonState.hover => colors.fillDarker,- _ResolvedIconButtonState.pressed => colors.fillDarkest,- _ => colors.fillDark,- },- IconButtonComponentVariant.green => switch (state) {- _ResolvedIconButtonState.hover => colors.primaryDark,- _ResolvedIconButtonState.pressed => colors.primaryDarker,- _ResolvedIconButtonState.disabled => colors.fillDark,- _ => colors.primary,- },- IconButtonComponentVariant.circular => switch (state) {- _ResolvedIconButtonState.hover ||- _ResolvedIconButtonState.disabled =>- colors.fillDark,- _ResolvedIconButtonState.pressed => colors.fillDarker,- _ => colors.fillLight,- },+ IconButtonComponentVariant.secondary => transparent,+ IconButtonComponentVariant.primary ||+ IconButtonComponentVariant.critical => colors.fillDark,+ IconButtonComponentVariant.green => colors.primary,+ IconButtonComponentVariant.circular => colors.fillLight,};}- Color _foreground(BuildContext context, _ResolvedIconButtonState state) {+ Color _foreground(+ BuildContext context, {+ bool isSuccess = false,+ bool isDisabled = false,+ }) {final colors = context.componentColors;- if (state == _ResolvedIconButtonState.success &&- widget.variant != IconButtonComponentVariant.green) {+ if (isDisabled) {+ return colors.textLighter;+ }+ if (isSuccess && widget.variant != IconButtonComponentVariant.green) {return colors.primary;}- if (widget.variant == IconButtonComponentVariant.green &&- state != _ResolvedIconButtonState.disabled) {+ if (widget.variant == IconButtonComponentVariant.green && !isDisabled) {return colors.specialWhite;}if (widget.variant == IconButtonComponentVariant.unfilled ||@@ -241,14 +416,15 @@ class _IconButtonComponentState extends State<IconButtonComponent> {}}-const double _buttonSize = 38;+const double _buttonSize = 36;const double _iconSize = 18;-enum _ResolvedIconButtonState {- normal,- hover,- pressed,- disabled,- loading,- success,+class _ResolvedIconButtonColors {+ const _ResolvedIconButtonColors({+ required this.background,+ required this.foreground,+ });++ final Color background;+ final Color foreground;}diff --git a/mobile/packages/ente_components/lib/components/menu_component.dart b/mobile/packages/ente_components/lib/components/menu_component.dartindex f176c9c2bb..0cd2f2fe43 100644--- a/mobile/packages/ente_components/lib/components/menu_component.dart+++ b/mobile/packages/ente_components/lib/components/menu_component.dart@@ -1,5 +1,6 @@import 'dart:async';+import 'package:ente_components/models/component_execution_state.dart';import 'package:ente_components/theme/colors.dart';import 'package:ente_components/theme/motion.dart';import 'package:ente_components/theme/radii.dart';@@ -11,6 +12,8 @@ import 'package:flutter/material.dart';const double _menuItemVerticalPadding = 9;const double _leadingSlotSize = 36;const double _trailingSlotSize = 36;+const Duration _loadingDelay = Duration(milliseconds: 300);+const Duration _successDisplayDuration = Duration(seconds: 1);/// Figma: https://www.figma.com/design/BuBNPPytxlVnqfmCUW0mgz/Ente-Visual-Design?node-id=4055-18734&m=dev/// Section: List items / Menu Item@@ -24,10 +27,10 @@ class MenuComponent extends StatefulWidget {this.trailing,this.selected = false,this.onTap,- this.gesturesEnabled = true,+ this.isDisabled = false,this.showOnlyLoadingState = false,- this.surfaceExecutionStates = true,- this.alwaysShowSuccessState = false,+ this.shouldSurfaceExecutionStates = true,+ this.shouldShowSuccessConfirmation = false,this.titleMaxLines = 2,this.subtitleMaxLines = 1,this.titleColor,@@ -40,10 +43,10 @@ class MenuComponent extends StatefulWidget {final Widget? trailing;final bool selected;final FutureOr<void> Function()? onTap;- final bool gesturesEnabled;+ final bool isDisabled;final bool showOnlyLoadingState;- final bool surfaceExecutionStates;- final bool alwaysShowSuccessState;+ final bool shouldSurfaceExecutionStates;+ final bool shouldShowSuccessConfirmation;final int titleMaxLines;final int subtitleMaxLines;final Color? titleColor;@@ -56,16 +59,16 @@ class MenuComponent extends StatefulWidget {class _MenuComponentState extends State<MenuComponent> {bool _isHovered = false;bool _isPressed = false;- bool _isBusy = false;- bool _showsLoading = false;- bool _showsSuccess = false;+ bool _loadingVisible = false;Timer? _loadingTimer;+ ComponentExecutionState _executionState = ComponentExecutionState.idle;@overrideWidget build(BuildContext context) {final colors = context.componentColors;final enabled = _canHandleGestures;final trailing = _trailing(colors);+ final shouldReserveTrailingSlot = _shouldReserveTrailingSlot;return UnconstrainedBox(alignment: Alignment.topLeft,constrainedAxis: Axis.horizontal,@@ -144,14 +147,25 @@ class _MenuComponentState extends State<MenuComponent> {],),),- if (trailing != null) ...[+ if (shouldReserveTrailingSlot) ...[const SizedBox(width: Spacing.md),ConstrainedBox(constraints: const BoxConstraints(minWidth: _trailingSlotSize,minHeight: _trailingSlotSize,),- child: Center(child: trailing),+ child: Center(+ child: AnimatedSwitcher(+ duration: Motion.quick,+ switchInCurve: Curves.easeOutCubic,+ switchOutCurve: Curves.easeInCubic,+ child:+ trailing ??+ const SizedBox.shrink(+ key: ValueKey('menu-item-empty-trailing'),+ ),+ ),+ ),),],],@@ -172,13 +186,26 @@ class _MenuComponentState extends State<MenuComponent> {}bool get _canHandleGestures {- return widget.gesturesEnabled && widget.onTap != null && !_isBusy;+ return !widget.isDisabled && widget.onTap != null && !_isBusy;}+ bool get _isBusy => _executionState == ComponentExecutionState.inProgress;++ bool get _showsLoading =>+ _executionState == ComponentExecutionState.inProgress && _loadingVisible;++ bool get _showsSuccess =>+ _executionState == ComponentExecutionState.successful;+bool get _shouldSurfaceExecutionState {- return widget.surfaceExecutionStates ||- widget.showOnlyLoadingState ||- widget.alwaysShowSuccessState;+ return widget.shouldSurfaceExecutionStates || widget.showOnlyLoadingState;+ }++ bool get _shouldReserveTrailingSlot {+ return widget.trailing != null ||+ (!widget.isDisabled &&+ widget.onTap != null &&+ _shouldSurfaceExecutionState);}Color _backgroundColor(ColorTokens colors, bool enabled) {@@ -202,9 +229,7 @@ class _MenuComponentState extends State<MenuComponent> {),);}- if (_showsSuccess &&- _shouldSurfaceExecutionState &&- !widget.showOnlyLoadingState) {+ if (_showsSuccess && _shouldShowSuccess) {return Icon(key: const ValueKey('menu-item-success'),Icons.check_rounded,@@ -215,6 +240,10 @@ class _MenuComponentState extends State<MenuComponent> {return widget.trailing;}+ bool get _shouldShowSuccess {+ return widget.shouldSurfaceExecutionStates && !widget.showOnlyLoadingState;+ }+double _minimumHeight() {final textHeight =_lineHeight(TextStyles.body) +@@ -251,34 +280,35 @@ class _MenuComponentState extends State<MenuComponent> {return;}- _isBusy = true;var loadingWasShown = false;- _loadingTimer = Timer(const Duration(milliseconds: 300), () {+ _loadingTimer?.cancel();+ setState(() {+ _executionState = ComponentExecutionState.inProgress;+ _loadingVisible = false;+ });+ _loadingTimer = Timer(_loadingDelay, () {if (!mounted || !_isBusy) {return;}loadingWasShown = true;- setState(() => _showsLoading = true);+ setState(() => _loadingVisible = true);});try {await widget.onTap?.call();- _loadingTimer?.cancel();if (!mounted) {return;}- if (widget.alwaysShowSuccessState) {- await _showSuccessThenReset();- return;- }-- if (widget.showOnlyLoadingState) {- _resetExecutionState();- return;- }+ final loadingPending = _loadingTimer?.isActive ?? false;+ _loadingTimer?.cancel();+ _loadingTimer = null;- if (widget.surfaceExecutionStates && loadingWasShown) {+ final shouldShowSuccess =+ _shouldShowSuccess &&+ (loadingWasShown ||+ (loadingPending && widget.shouldShowSuccessConfirmation));+ if (shouldShowSuccess) {await _showSuccessThenReset();return;}@@ -286,6 +316,7 @@ class _MenuComponentState extends State<MenuComponent> {_resetExecutionState();} catch (_) {_loadingTimer?.cancel();+ _loadingTimer = null;if (mounted) {_resetExecutionState();}@@ -297,10 +328,10 @@ class _MenuComponentState extends State<MenuComponent> {return;}setState(() {- _showsLoading = false;- _showsSuccess = true;+ _executionState = ComponentExecutionState.successful;+ _loadingVisible = false;});- await Future<void>.delayed(const Duration(seconds: 2));+ await Future<void>.delayed(_successDisplayDuration);if (mounted) {_resetExecutionState();}@@ -309,10 +340,9 @@ class _MenuComponentState extends State<MenuComponent> {void _resetExecutionState() {_loadingTimer?.cancel();setState(() {- _isBusy = false;+ _executionState = ComponentExecutionState.idle;_isPressed = false;- _showsLoading = false;- _showsSuccess = false;+ _loadingVisible = false;});}}diff --git a/mobile/packages/ente_components/lib/components/text_input_component.dart b/mobile/packages/ente_components/lib/components/text_input_component.dartindex 01cf46d5ee..021025da85 100644--- a/mobile/packages/ente_components/lib/components/text_input_component.dart+++ b/mobile/packages/ente_components/lib/components/text_input_component.dart@@ -1,3 +1,5 @@+import 'dart:async';+import 'package:ente_components/theme/colors.dart';import 'package:ente_components/theme/radii.dart';import 'package:ente_components/theme/spacing.dart';@@ -6,12 +8,7 @@ import 'package:ente_components/theme/theme.dart';import 'package:flutter/material.dart';import 'package:flutter/services.dart';-enum TextInputComponentMessageType {- helper,- error,- alert,- success,-}+enum TextInputComponentMessageType { helper, error, alert, success }/// Figma: https://www.figma.com/design/BuBNPPytxlVnqfmCUW0mgz/Ente-Visual-Design?node-id=2275-11526&m=dev/// Section: Textfield / Text Input@@ -20,101 +17,106 @@ enum TextInputComponentMessageType {////// Multiline variant:/// https://www.figma.com/design/BuBNPPytxlVnqfmCUW0mgz/Ente-Visual-Design?node-id=2275-11746&m=dev+class TextInputComponent extends StatefulWidget {const TextInputComponent({super.key,this.controller,this.focusNode,this.label,+ this.message,this.hintText,- this.helperText,- this.alertText,- this.errorText,- this.successText,- this.isFocused = false,- this.prefix,- this.suffix,- this.messageIcon,- this.isRequired = false,- this.enabled = true,- this.readOnly = false,+ this.initialValue,this.autofocus = false,- this.obscureText = false,- this.showPasswordToggle = false,- this.isClearable = false,- this.maxLines = 1,- this.minLines,this.maxLength,- this.keyboardType,- this.textInputAction,+ this.submitNotifier,+ this.cancelNotifier,+ this.onSubmit,+ this.onChanged,+ this.onCancel,+ this.popNavAfterSubmission = false,this.textCapitalization = TextCapitalization.none,+ this.isPasswordInput = false,+ this.isClearable = false,+ this.shouldUnfocusOnClearOrSubmit = false,+ this.isEmptyNotifier,this.inputFormatters,- this.autofillHints,+ this.keyboardType,+ this.enableFillColor = true,this.autocorrect = true,- this.enableSuggestions = true,- this.enableInteractiveSelection,- this.showCursor,- this.obscuringCharacter = 'β’',- this.textAlign = TextAlign.start,- this.textAlignVertical,- this.scrollController,- this.expands = false,- this.counterText,- this.onChanged,- this.onSubmitted,- this.onEditingComplete,+ this.isRequired = false,+ this.prefix,+ this.suffix,+ this.messageType = TextInputComponentMessageType.helper,+ this.messageIcon,+ this.isDisabled = false,+ this.autofillHints,+ this.maxLines,+ this.minLines,+ this.finishAutofillContextOnEditingComplete = false,});final TextEditingController? controller;final FocusNode? focusNode;final String? label;+ final String? message;final String? hintText;- final String? helperText;- final String? alertText;- final String? errorText;- final String? successText;- final bool isFocused;- final Widget? prefix;- final Widget? suffix;- final IconData? messageIcon;- final bool isRequired;- final bool enabled;- final bool readOnly;+ final String? initialValue;final bool autofocus;- final bool obscureText;- final bool showPasswordToggle;- final bool isClearable;- final int maxLines;- final int? minLines;final int? maxLength;- final TextInputType? keyboardType;- final TextInputAction? textInputAction;++ /// Executes [onSubmit] when the notifier changes. Duplicate submissions are+ /// ignored while a submit is in flight.+ final ValueNotifier<dynamic>? submitNotifier;++ /// Clears and unfocuses the field when the notifier changes, unless [onCancel]+ /// is provided.+ final ValueNotifier<dynamic>? cancelNotifier;++ /// Called by [submitNotifier] or the platform editing-complete action.+ final FutureOr<void> Function(String value)? onSubmit;+ final ValueChanged<String>? onChanged;+ final VoidCallback? onCancel;+ final bool popNavAfterSubmission;final TextCapitalization textCapitalization;+ final bool isPasswordInput;+ final bool isClearable;+ final bool shouldUnfocusOnClearOrSubmit;+ final ValueNotifier<bool>? isEmptyNotifier;final List<TextInputFormatter>? inputFormatters;- final Iterable<String>? autofillHints;+ final TextInputType? keyboardType;+ final bool enableFillColor;final bool autocorrect;- final bool enableSuggestions;- final bool? enableInteractiveSelection;- final bool? showCursor;- final String obscuringCharacter;- final TextAlign textAlign;- final TextAlignVertical? textAlignVertical;- final ScrollController? scrollController;- final bool expands;- final String? counterText;- final ValueChanged<String>? onChanged;- final ValueChanged<String>? onSubmitted;- final VoidCallback? onEditingComplete;+ final bool isRequired;++ /// Caller-owned leading widget. Pass explicit color and size when needed.+ final Widget? prefix;++ /// Caller-owned trailing widget. Multiline fields pin this slot to the top.+ final Widget? suffix;+ final TextInputComponentMessageType messageType;+ final IconData? messageIcon;+ final bool isDisabled;+ final Iterable<String>? autofillHints;+ final int? maxLines;+ final int? minLines;+ final bool finishAutofillContextOnEditingComplete;@overrideState<TextInputComponent> createState() => _TextInputComponentState();}class _TextInputComponentState extends State<TextInputComponent> {+ static const _kHeight = 52.0;+ static const _kIconContainerSize = 24.0;+TextEditingController? _internalController;FocusNode? _internalFocusNode;+ Timer? _wrongPasswordResetTimer;late bool _obscureText;bool _hasText = false;+ bool _incorrectPassword = false;+ bool _isSubmitting = false;TextEditingController get _controller =>widget.controller ?? _internalController!;@@ -124,11 +126,16 @@ class _TextInputComponentState extends State<TextInputComponent> {@overridevoid initState() {super.initState();- _internalController =- widget.controller == null ? TextEditingController() : null;+ widget.submitNotifier?.addListener(_handleSubmitRequested);+ widget.cancelNotifier?.addListener(_handleCancel);+ _internalController = widget.controller == null+ ? TextEditingController()+ : null;_internalFocusNode = widget.focusNode == null ? FocusNode() : null;- _obscureText = widget.obscureText;+ _obscureText = widget.isPasswordInput;+ _setInitialValue();_hasText = _controller.text.isNotEmpty;+ widget.isEmptyNotifier?.value = !_hasText;_controller.addListener(_handleControllerChanged);_focusNode.addListener(_handleFocusChanged);}@@ -136,16 +143,29 @@ class _TextInputComponentState extends State<TextInputComponent> {@overridevoid didUpdateWidget(covariant TextInputComponent oldWidget) {super.didUpdateWidget(oldWidget);+ if (oldWidget.submitNotifier != widget.submitNotifier) {+ oldWidget.submitNotifier?.removeListener(_handleSubmitRequested);+ widget.submitNotifier?.addListener(_handleSubmitRequested);+ }+ if (oldWidget.cancelNotifier != widget.cancelNotifier) {+ oldWidget.cancelNotifier?.removeListener(_handleCancel);+ widget.cancelNotifier?.addListener(_handleCancel);+ }if (oldWidget.controller != widget.controller) {oldWidget.controller?.removeListener(_handleControllerChanged);_internalController?.removeListener(_handleControllerChanged);if (oldWidget.controller == null) {_internalController?.dispose();}- _internalController =- widget.controller == null ? TextEditingController() : null;+ _internalController = widget.controller == null+ ? TextEditingController()+ : null;+ _setInitialValue();_controller.addListener(_handleControllerChanged);_hasText = _controller.text.isNotEmpty;+ widget.isEmptyNotifier?.value = !_hasText;+ } else if (oldWidget.initialValue != widget.initialValue) {+ _setInitialValue();}if (oldWidget.focusNode != widget.focusNode) {oldWidget.focusNode?.removeListener(_handleFocusChanged);@@ -156,13 +176,16 @@ class _TextInputComponentState extends State<TextInputComponent> {_internalFocusNode = widget.focusNode == null ? FocusNode() : null;_focusNode.addListener(_handleFocusChanged);}- if (oldWidget.obscureText != widget.obscureText) {- _obscureText = widget.obscureText;+ if (oldWidget.isPasswordInput != widget.isPasswordInput) {+ _obscureText = widget.isPasswordInput;}}@overridevoid dispose() {+ widget.submitNotifier?.removeListener(_handleSubmitRequested);+ widget.cancelNotifier?.removeListener(_handleCancel);+ _wrongPasswordResetTimer?.cancel();_controller.removeListener(_handleControllerChanged);_focusNode.removeListener(_handleFocusChanged);_internalController?.dispose();@@ -173,210 +196,281 @@ class _TextInputComponentState extends State<TextInputComponent> {@overrideWidget build(BuildContext context) {final colors = context.componentColors;- final message = _message;- final messageType = _messageType;- final messageColor = switch (messageType) {- TextInputComponentMessageType.error ||- TextInputComponentMessageType.alert =>- colors.warning,- TextInputComponentMessageType.success => colors.primary,- TextInputComponentMessageType.helper => colors.textLight,- };- final suffix = _effectiveSuffix();- final effectiveObscureText = _obscureText;-- return Opacity(- opacity: widget.enabled ? 1 : 0.38,- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- mainAxisSize: MainAxisSize.min,- children: [- if (widget.label != null) ...[- Text.rich(- TextSpan(- text: widget.label,- children: [- if (widget.isRequired)- TextSpan(- text: ' *',- style: TextStyles.body.copyWith(- color: colors.warning,- ),- ),- ],+ final message = widget.message;+ final messageColor = _messageColor(colors);+ final prefix = _buildPrefix();+ final suffix = _buildSuffix(colors);++ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ if (widget.label != null) ...[+ Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(+ widget.label!,+ style: TextStyles.bodyBold.copyWith(color: _labelColor(colors)),),- style: TextStyles.body.copyWith(color: colors.textBase),+ if (widget.isRequired) ...[+ const SizedBox(width: 2),+ Text(+ '*',+ style: TextStyles.bodyBold.copyWith(color: colors.warning),+ ),+ ],+ ],+ ),+ const SizedBox(height: Spacing.sm),+ ],+ GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: widget.isDisabled ? null : _focusNode.requestFocus,+ child: Container(+ height: _isMultiline ? null : _kHeight,+ constraints: _isMultiline+ ? const BoxConstraints(minHeight: _kHeight)+ : null,+ padding: EdgeInsets.symmetric(+ horizontal: Spacing.lg,+ vertical: _isMultiline ? Spacing.lg : 0,),- const SizedBox(height: Spacing.sm),- ],- TextField(- controller: _controller,- focusNode: _focusNode,- enabled: widget.enabled,- readOnly: widget.readOnly,- autofocus: widget.autofocus,- obscureText: effectiveObscureText,- obscuringCharacter: widget.obscuringCharacter,- maxLines: widget.expands- ? null- : effectiveObscureText- ? 1- : widget.maxLines,- minLines:- widget.expands || effectiveObscureText ? null : widget.minLines,- expands: widget.expands,- maxLength: widget.maxLength,- keyboardType: widget.keyboardType,- textInputAction: widget.textInputAction,- textCapitalization: widget.textCapitalization,- inputFormatters: widget.inputFormatters,- autofillHints: widget.autofillHints,- autocorrect: widget.autocorrect && !effectiveObscureText,- enableSuggestions:- widget.enableSuggestions && !effectiveObscureText,- enableInteractiveSelection: widget.enableInteractiveSelection,- showCursor: widget.showCursor,- textAlign: widget.textAlign,- textAlignVertical: widget.textAlignVertical ??- (_isMultiline- ? TextAlignVertical.top- : TextAlignVertical.center),- scrollController: widget.scrollController,- onChanged: _handleChanged,- onSubmitted: widget.onSubmitted,- onEditingComplete: widget.onEditingComplete,- style: TextStyles.body.copyWith(color: colors.textBase),- decoration: InputDecoration(- hintText: widget.hintText,- hintStyle: TextStyles.body.copyWith(color: colors.textLighter),- filled: true,- fillColor: colors.fillLight,- prefixIcon:- widget.prefix == null ? null : _slot(widget.prefix!, colors),- suffixIcon: suffix == null ? null : _slot(suffix, colors),- prefixIconConstraints: const BoxConstraints.tightFor(- width: 2 + Spacing.lg,- height: 2 + Spacing.lg,- ),- suffixIconConstraints: const BoxConstraints.tightFor(- width: 2 + Spacing.lg,- height: 2 + Spacing.lg,- ),- contentPadding: const EdgeInsets.symmetric(- horizontal: Spacing.lg,- vertical: Spacing.lg,- ),- counterText: widget.counterText,- border: _border(colors),- enabledBorder: _border(colors),- focusedBorder: _border(colors, focused: true),- disabledBorder: _border(colors),+ decoration: BoxDecoration(+ color: _backgroundColor(colors),+ borderRadius: BorderRadius.circular(Radii.lg),+ border: Border.all(color: _borderColor(colors)),),- ),- if (message != null) ...[- const SizedBox(height: Spacing.xs),- Row(- crossAxisAlignment: CrossAxisAlignment.start,+ child: Row(+ crossAxisAlignment: _isMultiline+ ? CrossAxisAlignment.start+ : CrossAxisAlignment.center,children: [- if (_messageIcon(messageType) != null) ...[- Icon(- _messageIcon(messageType),- size: 14,- color: messageColor,- ),- const SizedBox(width: Spacing.xs),+ if (prefix != null) ...[+ prefix,+ const SizedBox(width: Spacing.sm),],Expanded(- child: Text(- message,- style: TextStyles.tiny.copyWith(color: messageColor),+ child: TextField(+ controller: _controller,+ focusNode: _focusNode,+ enabled: !widget.isDisabled,+ autofocus: widget.autofocus,+ obscureText: _obscureText,+ maxLines: widget.isPasswordInput+ ? 1+ : widget.maxLines ?? (_isMultiline ? null : 1),+ minLines: widget.isPasswordInput ? null : widget.minLines,+ keyboardType: widget.keyboardType,+ textCapitalization: widget.textCapitalization,+ inputFormatters: _inputFormatters,+ autofillHints:+ widget.autofillHints ??+ (widget.isPasswordInput+ ? const [AutofillHints.password]+ : const []),+ autocorrect: widget.autocorrect && !widget.isPasswordInput,+ enableSuggestions: !widget.isPasswordInput,+ textAlignVertical: _isMultiline+ ? TextAlignVertical.top+ : TextAlignVertical.center,+ onEditingComplete: _handleEditingComplete,+ style: TextStyles.body.copyWith(color: _textColor(colors)),+ decoration: InputDecoration(+ hintText: widget.hintText,+ hintStyle: TextStyles.body.copyWith(+ color: _hintColor(colors),+ ),+ border: InputBorder.none,+ focusedBorder: InputBorder.none,+ enabledBorder: InputBorder.none,+ disabledBorder: InputBorder.none,+ isDense: true,+ contentPadding: EdgeInsets.zero,+ ),),),+ if (suffix != null) ...[+ const SizedBox(width: Spacing.sm),+ suffix,+ ],],),- ],+ ),+ ),+ if (message != null) ...[+ const SizedBox(height: Spacing.sm),+ Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ if (_messageIcon(messageColor) != null) ...[+ _messageIcon(messageColor)!,+ const SizedBox(width: Spacing.sm),+ ],+ Expanded(+ child: Text(+ message,+ style: TextStyles.mini.copyWith(color: messageColor),+ ),+ ),+ ],+ ),],- ),+ ],);}- bool get _isMultiline {- return !_obscureText &&- (widget.maxLines > 1 ||- (widget.minLines != null && widget.minLines! > 1));- }+ bool get _isMultiline =>+ !widget.isPasswordInput &&+ ((widget.maxLines != null && widget.maxLines! > 1) ||+ (widget.minLines != null && widget.minLines! > 1));++ bool get _isError =>+ _incorrectPassword ||+ widget.messageType == TextInputComponentMessageType.error ||+ widget.messageType == TextInputComponentMessageType.alert;- String? get _message =>- widget.errorText ??- widget.alertText ??- widget.successText ??- widget.helperText;+ bool get _hasSuccess =>+ widget.messageType == TextInputComponentMessageType.success;- TextInputComponentMessageType get _messageType {- if (widget.errorText != null) {- return TextInputComponentMessageType.error;+ List<TextInputFormatter>? get _inputFormatters {+ if (widget.inputFormatters != null) {+ return widget.inputFormatters;}- if (widget.alertText != null) {- return TextInputComponentMessageType.alert;+ if (widget.maxLength != null) {+ return [LengthLimitingTextInputFormatter(widget.maxLength)];}- if (widget.successText != null) {- return TextInputComponentMessageType.success;+ return null;+ }++ Color _backgroundColor(ColorTokens colors) {+ if (!widget.enableFillColor) {+ return Colors.transparent;}- return TextInputComponentMessageType.helper;+ if (widget.isDisabled) {+ return colors.fillDark;+ }+ return colors.fillLight;}- IconData? _messageIcon(TextInputComponentMessageType messageType) {- if (widget.messageIcon != null) {- return widget.messageIcon;+ Color _borderColor(ColorTokens colors) {+ if (_isError) {+ return colors.warning;}- return switch (messageType) {- TextInputComponentMessageType.alert => Icons.warning_amber_rounded,- TextInputComponentMessageType.success =>- Icons.check_circle_outline_rounded,+ if (_hasSuccess || _focusNode.hasFocus) {+ return colors.primary;+ }+ return colors.strokeFaint;+ }++ Color _textColor(ColorTokens colors) {+ return widget.isDisabled ? colors.textLightest : colors.textBase;+ }++ Color _hintColor(ColorTokens colors) {+ return widget.isDisabled ? colors.textLightest : colors.textLighter;+ }++ Color _labelColor(ColorTokens colors) {+ return widget.isDisabled ? colors.textLightest : colors.textBase;+ }++ Color _messageColor(ColorTokens colors) {+ return switch (widget.messageType) {TextInputComponentMessageType.error ||- TextInputComponentMessageType.helper =>- null,+ TextInputComponentMessageType.alert => colors.warning,+ TextInputComponentMessageType.success => colors.primary,+ TextInputComponentMessageType.helper => colors.textLight,};}- Widget? _effectiveSuffix() {- if (widget.showPasswordToggle) {- return GestureDetector(+ Widget? _buildPrefix() {+ if (widget.prefix == null) return null;+ return _slot(widget.prefix!);+ }++ Widget? _buildSuffix(ColorTokens colors) {+ final Widget child;+ if (widget.isPasswordInput) {+ child = GestureDetector(key: const ValueKey('text-field-password-toggle'),behavior: HitTestBehavior.opaque,- onTap: widget.enabled- ? () => setState(() => _obscureText = !_obscureText)- : null,+ onTap: widget.isDisabled+ ? null+ : () => setState(() => _obscureText = !_obscureText),child: Icon(_obscureText? Icons.visibility_off_outlined: Icons.visibility_outlined,size: 20,+ color: colors.textLighter,),);- }- if (widget.isClearable && _hasText) {- return GestureDetector(+ } else if (widget.isClearable && _hasText) {+ child = GestureDetector(key: const ValueKey('text-field-clear'),behavior: HitTestBehavior.opaque,- onTap: widget.enabled && !widget.readOnly- ? () {+ onTap: widget.isDisabled+ ? null+ : () {_controller.clear();- widget.onChanged?.call('');- }- : null,- child: const Icon(Icons.close_rounded, size: 20),+ if (widget.shouldUnfocusOnClearOrSubmit) {+ FocusScope.of(context).unfocus();+ }+ },+ child: Icon(Icons.close_rounded, size: 20, color: colors.textLighter),);+ } else if (widget.suffix != null) {+ child = widget.suffix!;+ } else {+ return null;}- return widget.suffix;++ return _slot(child);+ }++ Widget? _messageIcon(Color color) {+ if (widget.messageIcon != null) {+ return Icon(widget.messageIcon, size: 18, color: color);+ }+ return switch (widget.messageType) {+ TextInputComponentMessageType.alert => Icon(+ Icons.warning_amber_rounded,+ size: 18,+ color: color,+ ),+ TextInputComponentMessageType.success => Icon(+ Icons.check_circle_outline_rounded,+ size: 18,+ color: color,+ ),+ TextInputComponentMessageType.error ||+ TextInputComponentMessageType.helper => null,+ };}- void _handleChanged(String value) {- widget.onChanged?.call(value);+ Widget _slot(Widget child) {+ return SizedBox.square(+ dimension: _kIconContainerSize,+ child: Center(child: child),+ );}void _handleControllerChanged() {+ widget.onChanged?.call(_controller.text);+final hasText = _controller.text.isNotEmpty;+ if (widget.isEmptyNotifier != null &&+ widget.isEmptyNotifier!.value == hasText) {+ widget.isEmptyNotifier!.value = !hasText;+ }+ if (_incorrectPassword && hasText) {+ setState(() {+ _incorrectPassword = false;+ _hasText = hasText;+ });+ return;+ }if (_hasText != hasText && mounted) {setState(() => _hasText = hasText);}@@ -388,45 +482,117 @@ class _TextInputComponentState extends State<TextInputComponent> {}}- Widget _slot(Widget child, ColorTokens colors) {- return IconTheme.merge(- data: IconThemeData(color: colors.textLighter, size: 24),- child: Center(- widthFactor: 1,- child: SizedBox.square(- dimension: 24,- child: Center(child: child),- ),- ),- );+ void _handleEditingComplete() {+ if (widget.finishAutofillContextOnEditingComplete) {+ TextInput.finishAutofillContext();+ }+ if (widget.onSubmit == null) {+ if (widget.shouldUnfocusOnClearOrSubmit) {+ FocusScope.of(context).unfocus();+ }+ return;+ }+ _handleSubmitRequested();}- bool get _hasError => widget.errorText != null || widget.alertText != null;+ void _handleSubmitRequested() {+ unawaited(_handleSubmit());+ }- bool get _hasSuccess => widget.successText != null;+ Future<void> _handleSubmit() async {+ if (widget.onSubmit == null || widget.isDisabled || _isSubmitting) {+ return;+ }- bool get _hasFocus => widget.isFocused || _focusNode.hasFocus;+ setState(() {+ _isSubmitting = true;+ });- OutlineInputBorder _border(ColorTokens colors, {bool focused = false}) {- final Color color;- final double width;- if (_hasError) {- color = colors.warning;- width = 1.5;- } else if (_hasSuccess) {- color = colors.primary;- width = 1.5;- } else if (focused || _hasFocus) {- color = colors.primary;- width = 2;- } else {- color = colors.strokeFaint.withAlpha(0);- width = 0;+ if (widget.shouldUnfocusOnClearOrSubmit) {+ FocusScope.of(context).unfocus();+ }++ try {+ await widget.onSubmit!.call(_controller.text);+ } catch (error) {+ if (error.toString().contains('Incorrect password')) {+ _surfaceWrongPasswordState();+ }+ if (mounted) {+ setState(() => _isSubmitting = false);+ }+ if (widget.popNavAfterSubmission) {+ _popNavigatorStack(+ context,+ e: error is Exception ? error : Exception(error.toString()),+ );+ } else {+ rethrow;+ }+ return;}- return OutlineInputBorder(- borderRadius: BorderRadius.circular(Radii.lg),- borderSide: BorderSide(color: color, width: width),+ if (!mounted) return;+ setState(() => _isSubmitting = false);+ if (widget.popNavAfterSubmission) _popNavigatorStack(context);+ }++ void _handleCancel() {+ if (widget.onCancel != null) {+ widget.onCancel!();+ return;+ }+ _controller.clear();+ FocusScope.of(context).unfocus();+ }++ void _popNavigatorStack(BuildContext context, {Exception? e}) {+ if (Navigator.of(context).canPop()) {+ Navigator.of(context).pop(e);+ }+ }++ void _setInitialValue() {+ if (widget.initialValue == null) return;++ final formattedInitialValue = _formatInitialValue(+ widget.initialValue!,+ widget.inputFormatters,);+ _controller.value = TextEditingValue(+ text: formattedInitialValue,+ selection: TextSelection.collapsed(offset: formattedInitialValue.length),+ );+ }++ String _formatInitialValue(+ String initialValue,+ List<TextInputFormatter>? formatters,+ ) {+ if (formatters == null || formatters.isEmpty) return initialValue;++ var formattedValue = initialValue;+ for (final formatter in formatters) {+ formattedValue = formatter+ .formatEditUpdate(+ TextEditingValue.empty,+ TextEditingValue(text: formattedValue),+ )+ .text;+ }+ return formattedValue;+ }++ void _surfaceWrongPasswordState() {+ setState(() {+ _incorrectPassword = true;+ HapticFeedback.vibrate();+ });+ _wrongPasswordResetTimer?.cancel();+ _wrongPasswordResetTimer = Timer(const Duration(seconds: 1), () {+ if (mounted) {+ setState(() => _incorrectPassword = false);+ }+ });}}diff --git a/mobile/packages/ente_components/lib/ente_components.dart b/mobile/packages/ente_components/lib/ente_components.dartindex 917095ecdb..b2e752bc77 100644--- a/mobile/packages/ente_components/lib/ente_components.dart+++ b/mobile/packages/ente_components/lib/ente_components.dart@@ -9,6 +9,7 @@ export 'components/selection_control_components.dart';export 'components/slider_component.dart';export 'components/stepper_component.dart';export 'components/text_input_component.dart';+export 'models/component_execution_state.dart';export 'theme/colors.dart';export 'theme/motion.dart';export 'theme/radii.dart';diff --git a/mobile/packages/ente_components/lib/models/component_execution_state.dart b/mobile/packages/ente_components/lib/models/component_execution_state.dartnew file mode 100644index 0000000000..65e3c27370--- /dev/null+++ b/mobile/packages/ente_components/lib/models/component_execution_state.dart@@ -0,0 +1 @@+enum ComponentExecutionState { idle, inProgress, error, successful }diff --git a/mobile/packages/ente_components/test/components/app_surface_widgets_test.dart b/mobile/packages/ente_components/test/components/app_surface_widgets_test.dartindex a136905a7d..54367eeac8 100644--- a/mobile/packages/ente_components/test/components/app_surface_widgets_test.dart+++ b/mobile/packages/ente_components/test/components/app_surface_widgets_test.dart@@ -28,8 +28,9 @@ Future<void> pumpComponent(}void main() {- testWidgets('MenuComponent renders slots, states, and handles taps',- (tester) async {+ testWidgets('MenuComponent renders slots, states, and handles taps', (+ tester,+ ) async {var tapped = false;await pumpComponent(@@ -67,8 +68,9 @@ void main() {ColorTokens.light.warning,);expect(- IconTheme.of(tester.element(find.byIcon(Icons.cloud_upload_outlined)))- .color,+ IconTheme.of(+ tester.element(find.byIcon(Icons.cloud_upload_outlined)),+ ).color,ColorTokens.light.primary,);expect(@@ -82,44 +84,48 @@ void main() {});testWidgets(- 'MenuComponent delays loading, blocks repeat taps, and shows success',- (tester) async {- final completer = Completer<void>();- var tapCount = 0;-- await pumpComponent(- tester,- MenuComponent(- title: 'Sync now',- trailing: const Icon(Icons.chevron_right),- onTap: () {- tapCount += 1;- return completer.future;- },- ),- );-- await tester.tap(find.text('Sync now'));- await tester.pump(const Duration(milliseconds: 299));- expect(find.byKey(const ValueKey('menu-item-loading')), findsNothing);-- await tester.tap(find.text('Sync now'));- await tester.pump(const Duration(milliseconds: 1));- expect(tapCount, 1);- expect(find.byKey(const ValueKey('menu-item-loading')), findsOneWidget);- expect(find.byIcon(Icons.chevron_right), findsNothing);-- completer.complete();- await tester.pump();- expect(find.byKey(const ValueKey('menu-item-success')), findsOneWidget);- expect(find.byKey(const ValueKey('menu-item-loading')), findsNothing);-- await tester.pump(const Duration(seconds: 2));- expect(find.byIcon(Icons.chevron_right), findsOneWidget);- });+ 'MenuComponent delays loading, blocks repeat taps, and shows success',+ (tester) async {+ final completer = Completer<void>();+ var tapCount = 0;++ await pumpComponent(+ tester,+ MenuComponent(+ title: 'Sync now',+ trailing: const Icon(Icons.chevron_right),+ onTap: () {+ tapCount += 1;+ return completer.future;+ },+ ),+ );++ await tester.tap(find.text('Sync now'));+ await tester.pump(const Duration(milliseconds: 299));+ expect(find.byKey(const ValueKey('menu-item-loading')), findsNothing);++ await tester.tap(find.text('Sync now'));+ await tester.pump(const Duration(milliseconds: 1));+ expect(tapCount, 1);+ expect(find.byKey(const ValueKey('menu-item-loading')), findsOneWidget);+ await tester.pump(const Duration(milliseconds: 200));+ expect(find.byIcon(Icons.chevron_right), findsNothing);++ completer.complete();+ await tester.pump();+ expect(find.byKey(const ValueKey('menu-item-success')), findsOneWidget);+ await tester.pump(const Duration(milliseconds: 200));+ expect(find.byKey(const ValueKey('menu-item-loading')), findsNothing);++ await tester.pump(const Duration(seconds: 1));+ expect(find.byIcon(Icons.chevron_right), findsOneWidget);+ },+ );- testWidgets('MenuComponent can show only loading without success',- (tester) async {+ testWidgets('MenuComponent can show only loading without success', (+ tester,+ ) async {final completer = Completer<void>();await pumpComponent(@@ -141,13 +147,14 @@ void main() {expect(find.byKey(const ValueKey('menu-item-loading')), findsNothing);});- testWidgets('MenuComponent can force success for fast actions',- (tester) async {+ testWidgets('MenuComponent can force success for fast actions', (+ tester,+ ) async {await pumpComponent(tester,MenuComponent(title: 'Copy',- alwaysShowSuccessState: true,+ shouldShowSuccessConfirmation: true,onTap: () async {},),);@@ -156,19 +163,49 @@ void main() {await tester.pump();expect(find.byKey(const ValueKey('menu-item-success')), findsOneWidget);- await tester.pump(const Duration(seconds: 2));+ await tester.pump(const Duration(seconds: 1));+ await tester.pump(const Duration(milliseconds: 200));+ expect(find.byKey(const ValueKey('menu-item-success')), findsNothing);+ });++ testWidgets('MenuComponent resets to idle after async errors', (+ tester,+ ) async {+ await pumpComponent(+ tester,+ MenuComponent(+ title: 'Fail',+ trailing: const Icon(Icons.chevron_right),+ onTap: () async {+ await Future<void>.delayed(const Duration(milliseconds: 400));+ throw StateError('failed');+ },+ ),+ );++ await tester.tap(find.text('Fail'));+ await tester.pump(const Duration(milliseconds: 300));+ expect(find.byKey(const ValueKey('menu-item-loading')), findsOneWidget);++ await tester.pump(const Duration(milliseconds: 100));+ await tester.pump(const Duration(milliseconds: 200));++ expect(find.text('Fail'), findsOneWidget);+ expect(find.byIcon(Icons.chevron_right), findsOneWidget);+ expect(find.byKey(const ValueKey('menu-item-loading')), findsNothing);expect(find.byKey(const ValueKey('menu-item-success')), findsNothing);});- testWidgets('MenuComponent can disable gestures for display-only rows',- (tester) async {+ testWidgets('MenuComponent can disable gestures for display-only rows', (+ tester,+ ) async {var tapCount = 0;await pumpComponent(tester,MenuComponent(title: 'Storage plan',- gesturesEnabled: false,+ isDisabled: true,onTap: () {tapCount += 1;},@@ -204,7 +241,7 @@ void main() {MenuComponent(title: 'Success row',trailing: const Icon(Icons.chevron_right),- alwaysShowSuccessState: true,+ shouldShowSuccessConfirmation: true,onTap: () async {},),],@@ -218,6 +255,7 @@ void main() {await tester.pump(const Duration(milliseconds: 300));await tester.tap(find.text('Success row'));await tester.pump();+ await tester.pump(const Duration(milliseconds: 200));final surfaces = tester.widgetList<AnimatedContainer>(find.byKey(const ValueKey('menu-item-surface')),@@ -230,11 +268,11 @@ void main() {expect(tapCount, 0);loadingCompleter.complete();await tester.pump();- await tester.pump(const Duration(seconds: 2));+ await tester.pump(const Duration(seconds: 1));+ await tester.pump(const Duration(milliseconds: 200));});- testWidgets(- 'MenuComponent long text uses two title lines and one subtitle line', (+ testWidgets('MenuComponent long text uses two title lines and one subtitle line', (tester,) async {await pumpComponent(@@ -273,8 +311,9 @@ void main() {expect(tester.getSize(find.byType(MenuComponent)).height, greaterThan(60));});- testWidgets('TitleBarComponent renders heading and status variants',- (tester) async {+ testWidgets('TitleBarComponent renders heading and status variants', (+ tester,+ ) async {await pumpComponent(tester,const TitleBarComponent(@@ -319,36 +358,33 @@ void main() {});testWidgets(- 'TitleBarComponent keeps title centered with multiple trailing actions', (- tester,- ) async {- await pumpComponent(- tester,- const TitleBarComponent(- variant: TitleBarComponentVariant.titleTopbar,- title: 'Buttons',- leadingWidth: 44,- trailingWidth: 88,- leading: Icon(Icons.arrow_back),- trailing: Row(- mainAxisSize: MainAxisSize.min,- children: [- Icon(Icons.text_fields),- Icon(Icons.dark_mode),- ],+ 'TitleBarComponent keeps title centered with multiple trailing actions',+ (tester) async {+ await pumpComponent(+ tester,+ const TitleBarComponent(+ variant: TitleBarComponentVariant.titleTopbar,+ title: 'Buttons',+ leadingWidth: 44,+ trailingWidth: 88,+ leading: Icon(Icons.arrow_back),+ trailing: Row(+ mainAxisSize: MainAxisSize.min,+ children: [Icon(Icons.text_fields), Icon(Icons.dark_mode)],+ ),),- ),- width: 327,- height: 42,- );+ width: 327,+ height: 42,+ );- final titleCenter = tester.getCenter(find.text('Buttons')).dx;- final barCenter = tester.getCenter(find.byType(TitleBarComponent)).dx;+ final titleCenter = tester.getCenter(find.text('Buttons')).dx;+ final barCenter = tester.getCenter(find.byType(TitleBarComponent)).dx;- expect((titleCenter - barCenter).abs(), lessThan(1));- expect(find.byIcon(Icons.text_fields), findsOneWidget);- expect(find.byIcon(Icons.dark_mode), findsOneWidget);- });+ expect((titleCenter - barCenter).abs(), lessThan(1));+ expect(find.byIcon(Icons.text_fields), findsOneWidget);+ expect(find.byIcon(Icons.dark_mode), findsOneWidget);+ },+ );testWidgets('HeaderComponent renders image, subtitle, and multiple actions', (tester,@@ -358,14 +394,8 @@ void main() {const HeaderComponent(title: 'Title',subtitle: 'Subtitle',- leading: ColoredBox(- key: ValueKey('header-image'),- color: Colors.blue,- ),- actions: [- Icon(Icons.add),- Icon(Icons.more_horiz),- ],+ leading: ColoredBox(key: ValueKey('header-image'), color: Colors.blue),+ actions: [Icon(Icons.add), Icon(Icons.more_horiz)],),width: 327,);@@ -376,8 +406,9 @@ void main() {expect(find.byIcon(Icons.add), findsOneWidget);expect(find.byIcon(Icons.more_horiz), findsOneWidget);- final imageSize =- tester.getSize(find.byKey(const ValueKey('header-image')));+ final imageSize = tester.getSize(+ find.byKey(const ValueKey('header-image')),+ );expect(imageSize, const Size(36, 36));});}diff --git a/mobile/packages/ente_components/test/components/button_test.dart b/mobile/packages/ente_components/test/components/button_test.dartindex b4a95a38f2..3be9ea30c0 100644--- a/mobile/packages/ente_components/test/components/button_test.dart+++ b/mobile/packages/ente_components/test/components/button_test.dart@@ -6,23 +6,14 @@ import "package:flutter_test/flutter_test.dart";import "package:hugeicons/hugeicons.dart";void main() {- testWidgets("ButtonComponent renders label, icons, and expected size", (+ testWidgets("ButtonComponent renders label and expected size", (tester,) async {await tester.pumpWidget(- _wrap(- ButtonComponent(- label: "Continue",- leading: const Icon(Icons.arrow_back_rounded),- trailing: const Icon(Icons.arrow_forward_rounded),- onTap: () {},- ),- ),+ _wrap(ButtonComponent(label: "Continue", onTap: () {})),);expect(find.text("Continue"), findsOneWidget);- expect(find.byIcon(Icons.arrow_back_rounded), findsOneWidget);- expect(find.byIcon(Icons.arrow_forward_rounded), findsOneWidget);expect(tester.getSize(find.byType(AnimatedContainer)).height, 52);});@@ -30,12 +21,7 @@ void main() {var tapCount = 0;await tester.pumpWidget(- _wrap(- ButtonComponent(- label: "Save",- onTap: () => tapCount += 1,- ),- ),+ _wrap(ButtonComponent(label: "Save", onTap: () => tapCount += 1)),);await tester.tap(find.text("Save"));@@ -45,192 +31,249 @@ void main() {});testWidgets(- "Small ButtonComponent shrink-wraps content without a minimum width", (- tester,- ) async {- await tester.pumpWidget(- _wrap(- ButtonComponent(- label: "OK",- onTap: () {},+ "Small ButtonComponent shrink-wraps content without a minimum width",+ (tester) async {+ await tester.pumpWidget(+ _wrap(+ ButtonComponent(+ label: "OK",+ size: ButtonComponentSize.small,+ onTap: () {},+ ),),- ),- );+ );- final size = tester.getSize(find.byType(AnimatedContainer));- expect(size.height, 52);- expect(size.width, lessThan(100));- });+ final size = tester.getSize(find.byType(AnimatedContainer));+ expect(size.height, 52);+ expect(size.width, lessThan(100));+ },+ );testWidgets(- "ButtonComponent surfaces loading after debounce and blocks repeat taps",- (- tester,- ) async {- var tapCount = 0;- final completer = Completer<void>();-- await tester.pumpWidget(- _wrap(- ButtonComponent(- label: "Uploading",- onTap: () {- tapCount += 1;- return completer.future;- },+ "ButtonComponent surfaces loading after debounce and blocks repeat taps",+ (tester) async {+ var tapCount = 0;+ final completer = Completer<void>();++ await tester.pumpWidget(+ _wrap(+ ButtonComponent(+ label: "Uploading",+ onTap: () {+ tapCount += 1;+ return completer.future;+ },+ ),),- ),- );+ );- await tester.tap(find.text("Uploading"));- await tester.pump();+ await tester.tap(find.text("Uploading"));+ await tester.pump();- expect(tapCount, 1);- expect(find.byKey(const ValueKey('loading')), findsNothing);+ expect(tapCount, 1);+ expect(find.byKey(const ValueKey('loading')), findsNothing);- await tester.tap(find.text("Uploading"));- await tester.pump();+ await tester.tap(find.text("Uploading"));+ await tester.pump();- expect(tapCount, 1);+ expect(tapCount, 1);- await tester.pump(const Duration(milliseconds: 299));- expect(find.byKey(const ValueKey('loading')), findsNothing);+ await tester.pump(const Duration(milliseconds: 299));+ expect(find.byKey(const ValueKey('loading')), findsNothing);- await tester.pump(const Duration(milliseconds: 1));+ await tester.pump(const Duration(milliseconds: 1));- final loadingFinder = find.byKey(const ValueKey('loading'));- expect(loadingFinder, findsOneWidget);- expect(- find.descendant(- of: loadingFinder,- matching: find.byType(RotationTransition),- ),- findsOneWidget,- );- expect(- find.descendant(of: loadingFinder, matching: find.byType(HugeIcon)),- findsOneWidget,- );- expect(find.byType(CircularProgressIndicator), findsNothing);- expect(find.text("Uploading"), findsNothing);- expect(tester.getSize(find.byType(AnimatedContainer)).height, 52);-- completer.complete();- await tester.pump();- await tester.pump(const Duration(milliseconds: 100));-- expect(find.byKey(const ValueKey('success')), findsOneWidget);- });+ final loadingFinder = find.byKey(const ValueKey('loading'));+ expect(loadingFinder, findsOneWidget);+ expect(+ find.descendant(+ of: loadingFinder,+ matching: find.byType(RotationTransition),+ ),+ findsOneWidget,+ );+ expect(+ find.descendant(of: loadingFinder, matching: find.byType(HugeIcon)),+ findsOneWidget,+ );+ expect(find.byType(CircularProgressIndicator), findsNothing);+ await tester.pump(const Duration(milliseconds: 200));+ expect(find.text("Uploading"), findsOneWidget);+ expect(tester.getSize(find.byType(AnimatedContainer)).height, 52);++ completer.complete();+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 100));++ expect(find.byKey(const ValueKey('success')), findsOneWidget);+ },+ );testWidgets(- "ButtonComponent shows success confirmation for fast actions when enabled",- (- tester,- ) async {- var tapCount = 0;+ "Small ButtonComponent keeps idle width when parent rebuilds during loading",+ (tester) async {+ final completer = Completer<void>();+ var rebuildToken = 0;++ Widget buildButton() {+ return _wrap(+ Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ Text("Parent rebuild $rebuildToken"),+ ButtonComponent(+ label: "Uploading",+ size: ButtonComponentSize.small,+ onTap: () => completer.future,+ ),+ ],+ ),+ );+ }++ await tester.pumpWidget(buildButton());+ await tester.pump();++ final idleWidth = tester.getSize(find.byType(AnimatedContainer)).width;++ await tester.tap(find.text("Uploading"));+ await tester.pump(const Duration(milliseconds: 300));+ await tester.pump(const Duration(milliseconds: 200));++ rebuildToken += 1;+ await tester.pumpWidget(buildButton());+ await tester.pump();++ expect(find.byKey(const ValueKey('loading')), findsOneWidget);+ expect(find.text("Uploading"), findsOneWidget);+ expect(tester.getSize(find.byType(AnimatedContainer)).width, idleWidth);++ completer.complete();+ },+ );- await tester.pumpWidget(- _wrap(- ButtonComponent(- label: "Saved",- shouldShowSuccessConfirmation: true,- onTap: () => tapCount += 1,+ testWidgets(+ "ButtonComponent shows success confirmation for fast actions when enabled",+ (tester) async {+ var tapCount = 0;++ await tester.pumpWidget(+ _wrap(+ ButtonComponent(+ label: "Saved",+ shouldShowSuccessConfirmation: true,+ onTap: () => tapCount += 1,+ ),),- ),- );+ );- await tester.tap(find.text("Saved"));- await tester.pump();+ await tester.tap(find.text("Saved"));+ await tester.pump();- expect(tapCount, 1);- expect(find.byType(HugeIcon), findsOneWidget);- expect(find.text("Saved"), findsNothing);- expect(tester.getSize(find.byType(AnimatedContainer)).height, 52);+ expect(tapCount, 1);+ expect(find.byType(HugeIcon), findsOneWidget);+ await tester.pump(const Duration(milliseconds: 200));+ expect(find.text("Saved"), findsOneWidget);+ expect(tester.getSize(find.byType(AnimatedContainer)).height, 52);- await tester.pump(const Duration(seconds: 2));- await tester.pump();+ await tester.pump(const Duration(seconds: 1));+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 200));- expect(find.text("Saved"), findsOneWidget);- });+ expect(find.text("Saved"), findsOneWidget);+ },+ );testWidgets(- "ButtonComponent can hide execution visuals while still blocking taps", (- tester,- ) async {- var tapCount = 0;- final completer = Completer<void>();-- await tester.pumpWidget(- _wrap(- ButtonComponent(- label: "Silent",- shouldSurfaceExecutionStates: false,- onTap: () {- tapCount += 1;- return completer.future;- },+ "ButtonComponent can hide execution visuals while still blocking taps",+ (tester) async {+ var tapCount = 0;+ final completer = Completer<void>();++ await tester.pumpWidget(+ _wrap(+ ButtonComponent(+ label: "Silent",+ shouldSurfaceExecutionStates: false,+ onTap: () {+ tapCount += 1;+ return completer.future;+ },+ ),),- ),- );+ );- await tester.tap(find.text("Silent"));- await tester.pump(const Duration(milliseconds: 400));+ await tester.tap(find.text("Silent"));+ await tester.pump(const Duration(milliseconds: 400));- expect(tapCount, 1);- expect(find.byKey(const ValueKey('loading')), findsNothing);- expect(find.text("Silent"), findsOneWidget);+ expect(tapCount, 1);+ expect(find.byKey(const ValueKey('loading')), findsNothing);+ expect(find.text("Silent"), findsOneWidget);- await tester.tap(find.text("Silent"));- await tester.pump();+ await tester.tap(find.text("Silent"));+ await tester.pump();- expect(tapCount, 1);+ expect(tapCount, 1);- completer.complete();- await tester.pump();- });+ completer.complete();+ await tester.pump();+ },+ );- testWidgets("ButtonComponent remains disabled when onTap is null or disabled",- (+ testWidgets("ButtonComponent resets state after async errors", (tester,) async {- var tapCount = 0;-await tester.pumpWidget(_wrap(- Column(- children: [- const ButtonComponent(- label: "No callback",- onTap: null,- ),- ButtonComponent(- label: "Disabled",- isDisabled: true,- onTap: () => tapCount += 1,- ),- ],+ ButtonComponent(+ label: "Fail",+ onTap: () async => throw StateError("failed"),),),);- expect(find.text("No callback"), findsOneWidget);- expect(find.text("Disabled"), findsOneWidget);- await tester.tap(find.text("Disabled"));+ await tester.tap(find.text("Fail"));await tester.pump();- expect(tapCount, 0);+ expect(find.text("Fail"), findsOneWidget);+ expect(find.byKey(const ValueKey('loading')), findsNothing);+ expect(find.byKey(const ValueKey('success')), findsNothing);});+ testWidgets(+ "ButtonComponent remains disabled when onTap is null or disabled",+ (tester) async {+ var tapCount = 0;++ await tester.pumpWidget(+ _wrap(+ Column(+ children: [+ const ButtonComponent(label: "No callback", onTap: null),+ ButtonComponent(+ label: "Disabled",+ isDisabled: true,+ onTap: () => tapCount += 1,+ ),+ ],+ ),+ ),+ );++ expect(find.text("No callback"), findsOneWidget);+ expect(find.text("Disabled"), findsOneWidget);+ await tester.tap(find.text("Disabled"));+ await tester.pump();++ expect(tapCount, 0);+ },+ );+testWidgets("ButtonComponent renders pressed visual state from gesture", (tester,) async {await tester.pumpWidget(- _wrap(- ButtonComponent(- label: "Continue",- onTap: () {},- ),- ),+ _wrap(ButtonComponent(label: "Continue", onTap: () {})),);expect(_containerColor(tester), const Color(0xFF08C225));@@ -262,7 +305,7 @@ void main() {),);- expect(_containerColor(tester), const Color(0xFFDDEEDF));+ expect(_containerColor(tester), ColorTokens.light.primaryLight);expect(tester.getSize(find.byType(AnimatedContainer)).height, 52);await tester.pumpWidget(@@ -279,8 +322,7 @@ void main() {expect(tester.getSize(find.byType(AnimatedContainer)).height, 52);});- testWidgets("IconButtonComponent renders Figma size and token-backed states",- (+ testWidgets("IconButtonComponent renders Figma size and pressed state", (tester,) async {await tester.pumpWidget(@@ -288,8 +330,7 @@ void main() {IconButtonComponent(icon: const Icon(Icons.add),variant: IconButtonComponentVariant.primary,- state: IconButtonComponentState.pressed,- onPressed: () {},+ onTap: () {},),),);@@ -298,59 +339,103 @@ void main() {final surface = tester.widget<AnimatedContainer>(surfaceFinder);final decoration = surface.decoration! as BoxDecoration;- expect(tester.getSize(surfaceFinder), const Size(38, 38));- expect(decoration.color, ColorTokens.light.fillDarker);+ expect(tester.getSize(surfaceFinder), const Size(36, 36));+ expect(decoration.color, ColorTokens.light.fillLight);++ final gesture = await tester.startGesture(tester.getCenter(surfaceFinder));+ await tester.pump(const Duration(milliseconds: 200));++ final pressedSurface = tester.widget<AnimatedContainer>(surfaceFinder);+ final pressedDecoration = pressedSurface.decoration! as BoxDecoration;+ expect(pressedDecoration.color, ColorTokens.light.fillDarker);++ await gesture.up();});- testWidgets(- "IconButtonComponent maps loading and success to designed affordances", (+ testWidgets("IconButtonComponent default variant is secondary", (+ tester,+ ) async {+ await tester.pumpWidget(+ _wrap(IconButtonComponent(icon: const Icon(Icons.add), onTap: () {})),+ );++ expect(_iconButtonColor(tester), Colors.transparent);+ });++ testWidgets("IconButtonComponent calls taps only when enabled", (tester,) async {+ var tapCount = 0;+await tester.pumpWidget(_wrap(IconButtonComponent(icon: const Icon(Icons.add),- variant: IconButtonComponentVariant.green,- isSuccess: true,- onPressed: () {},+ onTap: () => tapCount += 1,),),);- final surface = tester.widget<AnimatedContainer>(- find.byKey(const ValueKey('icon-button-surface')),- );- final decoration = surface.decoration! as BoxDecoration;- final successIcon = tester.widget<Icon>(- find.byIcon(Icons.check_circle_rounded),+ await tester.tap(find.byType(GestureDetector));+ await tester.pump();++ expect(tapCount, 1);+ });++ testWidgets("IconButtonComponent mutes disabled foreground", (tester) async {+ await tester.pumpWidget(+ _wrap(+ const IconButtonComponent(+ icon: Icon(Icons.add),+ variant: IconButtonComponentVariant.primary,+ onTap: null,+ ),+ ),);- expect(decoration.color, ColorTokens.light.primary);- expect(successIcon.color, ColorTokens.light.specialWhite);+ final iconTheme = tester.widget<IconTheme>(+ find.descendant(+ of: find.byKey(const ValueKey('icon-button-surface')),+ matching: find.byType(IconTheme),+ ),+ );+ expect(iconTheme.data.color, ColorTokens.light.textLighter);+ });+ testWidgets("IconButtonComponent resets state after async errors", (+ tester,+ ) async {await tester.pumpWidget(_wrap(IconButtonComponent(icon: const Icon(Icons.add),- isLoading: true,- onPressed: () {},+ onTap: () async => throw StateError("failed"),),),);- expect(find.byType(CircularProgressIndicator), findsOneWidget);- expect(find.byIcon(Icons.add), findsNothing);+ await tester.tap(find.byType(GestureDetector));+ await tester.pump();++ expect(find.byIcon(Icons.add), findsOneWidget);+ expect(find.byKey(const ValueKey('loading')), findsNothing);+ expect(find.byKey(const ValueKey('success')), findsNothing);});- testWidgets("IconButtonComponent calls taps only when enabled",- (tester) async {+ testWidgets("IconButtonComponent surfaces async execution states", (+ tester,+ ) async {var tapCount = 0;+ final completer = Completer<void>();await tester.pumpWidget(_wrap(IconButtonComponent(icon: const Icon(Icons.add),- onPressed: () => tapCount += 1,+ onTap: () {+ tapCount += 1;+ return completer.future;+ },),),);@@ -358,14 +443,38 @@ void main() {await tester.tap(find.byType(GestureDetector));await tester.pump();+ expect(tapCount, 1);+ expect(find.byKey(const ValueKey('loading')), findsNothing);++ await tester.tap(find.byType(GestureDetector));+ await tester.pump();+expect(tapCount, 1);+ await tester.pump(const Duration(milliseconds: 300));++ expect(find.byKey(const ValueKey('loading')), findsOneWidget);+ await tester.pump(const Duration(milliseconds: 200));+ expect(find.byIcon(Icons.add), findsNothing);++ completer.complete();+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 100));++ expect(find.byKey(const ValueKey('success')), findsOneWidget);+ });++ testWidgets("IconButtonComponent can show success for fast actions", (+ tester,+ ) async {+ var tapCount = 0;+await tester.pumpWidget(_wrap(IconButtonComponent(icon: const Icon(Icons.add),- isLoading: true,- onPressed: () => tapCount += 1,+ shouldShowSuccessConfirmation: true,+ onTap: () => tapCount += 1,),),);@@ -374,15 +483,16 @@ void main() {await tester.pump();expect(tapCount, 1);+ expect(find.byKey(const ValueKey('success')), findsOneWidget);+ await tester.pump(const Duration(milliseconds: 200));+ expect(find.byIcon(Icons.add), findsNothing);});}Widget _wrap(Widget child) {return MaterialApp(theme: ComponentTheme.lightTheme(),- home: Scaffold(- body: Center(child: child),- ),+ home: Scaffold(body: Center(child: child)),);}@@ -392,3 +502,10 @@ Color _containerColor(WidgetTester tester) {);return (container.decoration! as BoxDecoration).color!;}++Color _iconButtonColor(WidgetTester tester) {+ final container = tester.widget<AnimatedContainer>(+ find.byKey(const ValueKey('icon-button-surface')),+ );+ return (container.decoration! as BoxDecoration).color!;+}diff --git a/mobile/packages/ente_components/test/components/text_input_component_test.dart b/mobile/packages/ente_components/test/components/text_input_component_test.dartindex b21d641860..84e3872c5d 100644--- a/mobile/packages/ente_components/test/components/text_input_component_test.dart+++ b/mobile/packages/ente_components/test/components/text_input_component_test.dart@@ -1,3 +1,5 @@+import "dart:async";+import "package:ente_components/ente_components.dart";import "package:flutter/material.dart";import "package:flutter/services.dart";@@ -5,180 +7,185 @@ import "package:flutter_test/flutter_test.dart";void main() {testWidgets(- "TextInputComponent renders label, required mark, and helper text", (- tester,- ) async {- await tester.pumpWidget(- _wrap(- const TextInputComponent(- label: "Email",- hintText: "[email protected]",- helperText: "Use your account email",- isRequired: true,+ "TextInputComponent renders label, required mark, and helper message",+ (tester) async {+ await tester.pumpWidget(+ _wrap(+ const TextInputComponent(+ label: "Email",+ hintText: "[email protected]",+ message: "Use your account email",+ isRequired: true,+ ),),- ),- );-- expect(_richText("Email *"), findsOneWidget);- expect(find.text("Use your account email"), findsOneWidget);- expect(- tester.widget<Text>(find.text("Use your account email")).style?.color,- ColorTokens.light.textLight,- );- expect(- tester- .widget<TextField>(- find.byType(TextField),- )- .decoration- ?.hintText,- "[email protected]",- );- });+ );++ expect(_richText("Email *"), findsNothing);+ expect(find.text("Email"), findsOneWidget);+ expect(find.text("*"), findsOneWidget);+ expect(find.text("Use your account email"), findsOneWidget);+ expect(+ tester.widget<Text>(find.text("Use your account email")).style?.color,+ ColorTokens.light.textLight,+ );+ expect(+ tester.widget<TextField>(find.byType(TextField)).decoration?.hintText,+ "[email protected]",+ );+ },+ );- testWidgets("TextInputComponent gives error text priority over helper text", (+ testWidgets("TextInputComponent renders error message visuals", (tester,) async {await tester.pumpWidget(_wrap(const TextInputComponent(label: "Password",- helperText: "At least 8 characters",- errorText: "Password is required",+ message: "Password is required",+ messageType: TextInputComponentMessageType.error,),),);expect(find.text("Password is required"), findsOneWidget);- expect(find.text("At least 8 characters"), findsNothing);expect(tester.widget<Text>(find.text("Password is required")).style?.color,ColorTokens.light.warning,);+ expect(+ _fieldDecoration(tester).border?.top.color,+ ColorTokens.light.warning,+ );});- testWidgets("TextInputComponent renders success text when valid",- (tester) async {+ testWidgets("TextInputComponent renders success message visuals", (+ tester,+ ) async {await tester.pumpWidget(_wrap(const TextInputComponent(label: "Code",- successText: "Looks good",+ message: "Looks good",+ messageType: TextInputComponentMessageType.success,),),);expect(find.text("Looks good"), findsOneWidget);+ expect(find.byIcon(Icons.check_circle_outline_rounded), findsOneWidget);expect(tester.widget<Text>(find.text("Looks good")).style?.color,ColorTokens.light.primary,);+ expect(+ _fieldDecoration(tester).border?.top.color,+ ColorTokens.light.primary,+ );});- testWidgets("TextInputComponent supports explicit focused visual state", (+ testWidgets("TextInputComponent maps actual focus to the focused border", (tester,) async {- await tester.pumpWidget(- _wrap(- const TextInputComponent(- label: "Email",- isFocused: true,- ),- ),- );+ await tester.pumpWidget(_wrap(const TextInputComponent(label: "Email")));++ await tester.tap(find.byType(TextField));+ await tester.pump();- final input = tester.widget<TextField>(- find.byType(TextField),+ expect(+ _fieldDecoration(tester).border?.top.color,+ ColorTokens.light.primary,);- final border = input.decoration?.enabledBorder as OutlineInputBorder?;- expect(border?.borderSide.color, ColorTokens.light.primary);- expect(border?.borderSide.width, 2);});- testWidgets(- "TextInputComponent maps error and success states to Figma borders", (+ testWidgets("TextInputComponent maps error and success states to borders", (tester,) async {await tester.pumpWidget(_wrap(const Column(children: [- TextInputComponent(label: "Error", errorText: "This is an error"),- TextInputComponent(label: "Success", successText: "Saved"),+ TextInputComponent(+ label: "Error",+ message: "This is an error",+ messageType: TextInputComponentMessageType.error,+ ),+ TextInputComponent(+ label: "Success",+ message: "Saved",+ messageType: TextInputComponentMessageType.success,+ ),],),),);- final inputs = tester.widgetList<TextField>(- find.byType(TextField),- );- final errorBorder =- inputs.first.decoration?.enabledBorder as OutlineInputBorder?;- final successBorder =- inputs.last.decoration?.enabledBorder as OutlineInputBorder?;-- expect(errorBorder?.borderSide.color, ColorTokens.light.warning);- expect(errorBorder?.borderSide.width, 1.5);- expect(successBorder?.borderSide.color, ColorTokens.light.primary);- expect(successBorder?.borderSide.width, 1.5);+ final borders = tester+ .widgetList<Container>(_fieldContainers())+ .map((container) => container.decoration! as BoxDecoration)+ .map((decoration) => decoration.border! as Border)+ .toList();++ expect(borders.first.top.color, ColorTokens.light.warning);+ expect(borders.first.top.width, 1);+ expect(borders.last.top.color, ColorTokens.light.primary);+ expect(borders.last.top.width, 1);});testWidgets(- "TextInputComponent forwards disabled state to the platform field", (+ "TextInputComponent forwards disabled state to the platform field",+ (tester) async {+ await tester.pumpWidget(+ _wrap(const TextInputComponent(label: "Email", isDisabled: true)),+ );++ final input = tester.widget<TextField>(find.byType(TextField));+ expect(input.enabled, isFalse);+ expect(_fieldDecoration(tester).color, ColorTokens.light.fillDark);+ expect(+ _fieldDecoration(tester).border?.top.color,+ ColorTokens.light.strokeFaint,+ );+ },+ );++ testWidgets("TextInputComponent supports the multiline layout", (tester,) async {- await tester.pumpWidget(- _wrap(- const TextInputComponent(- label: "Email",- enabled: false,- ),- ),- );-- final input = tester.widget<TextField>(- find.byType(TextField),- );- expect(input.enabled, isFalse);- expect(input.decoration?.fillColor, ColorTokens.light.fillLight);- expect(tester.widget<Opacity>(find.byType(Opacity).first).opacity, 0.38);- });-- testWidgets("TextInputComponent supports the Figma multiline layout",- (tester) async {await tester.pumpWidget(_wrap(const TextInputComponent(label: "Notes",hintText: "Hint text",- errorText: "This is an error",+ message: "This is an error",+ messageType: TextInputComponentMessageType.error,maxLines: 4,suffix: Icon(Icons.copy, key: ValueKey("copy-icon")),),),);- final input = tester.widget<TextField>(- find.byType(TextField),- );- final border = input.decoration?.enabledBorder as OutlineInputBorder?;+ final input = tester.widget<TextField>(find.byType(TextField));+ final container = tester.widget<Container>(_fieldContainers().first);expect(input.maxLines, 4);expect(- input.decoration?.contentPadding,- const EdgeInsets.symmetric(- horizontal: 16,- vertical: 16,- ),+ container.padding,+ const EdgeInsets.symmetric(horizontal: 16, vertical: 16),+ );+ expect(_fieldDecoration(tester).borderRadius, BorderRadius.circular(16));+ expect(+ _fieldDecoration(tester).border?.top.color,+ ColorTokens.light.warning,);- expect(border?.borderRadius, BorderRadius.circular(16));- expect(border?.borderSide.color, ColorTokens.light.warning);- expect(border?.borderSide.width, 1.5);expect(find.byKey(const ValueKey("copy-icon")), findsOneWidget);+ expect(+ tester.getTopLeft(find.byKey(const ValueKey("copy-icon"))).dy,+ tester.getTopLeft(find.byType(TextField)).dy,+ );expect(tester.widget<Text>(find.text("This is an error")).style?.fontSize,- TextStyles.tiny.fontSize,+ TextStyles.mini.fontSize,);});@@ -199,7 +206,7 @@ void main() {),);- await tester.enterText(find.byType(TextInputComponent), "Ada Lovelace");+ await tester.enterText(find.byType(TextField), "Ada Lovelace");await tester.pump();expect(controller.text, "Ada Lovelace");@@ -212,135 +219,203 @@ void main() {) async {final controller = TextEditingController();final focusNode = FocusNode();- final scrollController = ScrollController();+ final isEmptyNotifier = ValueNotifier<bool>(false);var submitted = "";- var editingComplete = false;addTearDown(controller.dispose);addTearDown(focusNode.dispose);- addTearDown(scrollController.dispose);+ addTearDown(isEmptyNotifier.dispose);await tester.pumpWidget(_wrap(TextInputComponent(controller: controller,focusNode: focusNode,+ isEmptyNotifier: isEmptyNotifier,label: "Invite email",autofocus: true,- readOnly: true,- showCursor: false,- enableInteractiveSelection: false,textCapitalization: TextCapitalization.words,- textInputAction: TextInputAction.done,inputFormatters: [FilteringTextInputFormatter.allow(RegExp("[a-z@.]")),],maxLength: 48,- counterText: "",keyboardType: TextInputType.emailAddress,autofillHints: const [AutofillHints.email],autocorrect: false,- enableSuggestions: false,- textAlign: TextAlign.center,- textAlignVertical: TextAlignVertical.top,- scrollController: scrollController,- onSubmitted: (value) => submitted = value,- onEditingComplete: () => editingComplete = true,+ onSubmit: (value) => submitted = value,),),);- final input = tester.widget<TextField>(- find.byType(TextField),- );+ final input = tester.widget<TextField>(find.byType(TextField));expect(input.focusNode, focusNode);expect(input.autofocus, isTrue);- expect(input.readOnly, isTrue);- expect(input.showCursor, isFalse);- expect(input.enableInteractiveSelection, isFalse);expect(input.textCapitalization, TextCapitalization.words);- expect(input.textInputAction, TextInputAction.done);- expect(input.maxLength, 48);- expect(input.decoration?.counterText, "");+ expect(input.maxLength, isNull);expect(input.keyboardType, TextInputType.emailAddress);expect(input.autofillHints, const [AutofillHints.email]);expect(input.autocorrect, isFalse);- expect(input.enableSuggestions, isFalse);- expect(input.textAlign, TextAlign.center);- expect(input.textAlignVertical, TextAlignVertical.top);- expect(input.scrollController, scrollController);- input.onSubmitted?.call("[email protected]");- input.onEditingComplete?.call();+ await tester.enterText(find.byType(TextField), "[email protected]");+ await tester.testTextInput.receiveAction(TextInputAction.done);+ await tester.pump();+expect(submitted, "[email protected]");- expect(editingComplete, isTrue);+ expect(isEmptyNotifier.value, isFalse);});testWidgets(- "TextInputComponent supports clear and password visibility affordances", (+ "TextInputComponent supports clear and password visibility affordances",+ (tester) async {+ final clearController = TextEditingController(text: "search");+ final passwordController = TextEditingController(text: "secret");+ addTearDown(clearController.dispose);+ addTearDown(passwordController.dispose);++ await tester.pumpWidget(+ _wrap(+ Column(+ children: [+ TextInputComponent(+ controller: clearController,+ label: "Search",+ isClearable: true,+ ),+ TextInputComponent(+ controller: passwordController,+ label: "Password",+ isPasswordInput: true,+ ),+ ],+ ),+ ),+ );++ expect(find.byKey(const ValueKey("text-field-clear")), findsOneWidget);+ await tester.tap(find.byKey(const ValueKey("text-field-clear")));+ await tester.pump();+ expect(clearController.text, "");+ expect(find.byKey(const ValueKey("text-field-clear")), findsNothing);++ var inputs = tester.widgetList<TextField>(find.byType(TextField));+ expect(inputs.last.obscureText, isTrue);++ await tester.tap(+ find.byKey(const ValueKey("text-field-password-toggle")),+ );+ await tester.pump();+ inputs = tester.widgetList<TextField>(find.byType(TextField));+ expect(inputs.last.obscureText, isFalse);+ },+ );++ testWidgets("TextInputComponent renders alert message visuals", (+ tester,+ ) async {+ await tester.pumpWidget(+ _wrap(+ const TextInputComponent(+ label: "Recovery key",+ message: "Save this somewhere safe.",+ messageType: TextInputComponentMessageType.alert,+ ),+ ),+ );++ expect(find.text("Save this somewhere safe."), findsOneWidget);+ expect(find.byIcon(Icons.warning_amber_rounded), findsOneWidget);+ expect(+ tester.widget<Text>(find.text("Save this somewhere safe.")).style?.color,+ ColorTokens.light.warning,+ );+ });++ testWidgets("TextInputComponent submits without surfacing execution UI", (tester,) async {- final clearController = TextEditingController(text: "search");- final passwordController = TextEditingController(text: "secret");- addTearDown(clearController.dispose);- addTearDown(passwordController.dispose);+ final submitNotifier = ValueNotifier<int>(0);+ final submitCompleter = Completer<void>();+ var submitCount = 0;+ addTearDown(submitNotifier.dispose);await tester.pumpWidget(_wrap(- Column(- children: [- TextInputComponent(- controller: clearController,- label: "Search",- isClearable: true,- ),- TextInputComponent(- controller: passwordController,- label: "Password",- obscureText: true,- showPasswordToggle: true,- ),- ],+ TextInputComponent(+ initialValue: "album",+ submitNotifier: submitNotifier,+ onSubmit: (_) {+ submitCount += 1;+ return submitCompleter.future;+ },),),);- expect(find.byKey(const ValueKey("text-field-clear")), findsOneWidget);- await tester.tap(find.byKey(const ValueKey("text-field-clear")));+ submitNotifier.value++;+ await tester.pump();+ submitNotifier.value++;await tester.pump();- expect(clearController.text, "");- expect(find.byKey(const ValueKey("text-field-clear")), findsNothing);- var inputs = tester.widgetList<TextField>(- find.byType(TextField),- );- expect(inputs.last.obscureText, isTrue);+ expect(submitCount, 1);+ expect(find.byType(CircularProgressIndicator), findsNothing);+ expect(find.byIcon(Icons.check_rounded), findsNothing);- await tester.tap(find.byKey(const ValueKey("text-field-password-toggle")));+ submitCompleter.complete();await tester.pump();- inputs = tester.widgetList<TextField>(- find.byType(TextField),- );- expect(inputs.last.obscureText, isFalse);+ submitNotifier.value++;+ await tester.pump();++ expect(submitCount, 2);+ expect(find.byIcon(Icons.check_rounded), findsNothing);});- testWidgets("TextInputComponent renders alert message visuals",- (tester) async {+ testWidgets("TextInputComponent surfaces wrong password as an error border", (+ tester,+ ) async {+ final submitNotifier = ValueNotifier<int>(0);+ addTearDown(submitNotifier.dispose);+await tester.pumpWidget(_wrap(- const TextInputComponent(- label: "Recovery key",- alertText: "Save this somewhere safe.",+ TextInputComponent(+ initialValue: "secret",+ submitNotifier: submitNotifier,+ popNavAfterSubmission: true,+ onSubmit: (_) => throw Exception("Incorrect password"),),),);- expect(find.text("Save this somewhere safe."), findsOneWidget);- expect(find.byIcon(Icons.warning_amber_rounded), findsOneWidget);+ submitNotifier.value++;+ await tester.pump();+expect(- tester.widget<Text>(find.text("Save this somewhere safe.")).style?.color,+ _fieldDecoration(tester).border?.top.color,ColorTokens.light.warning,);});++ testWidgets("TextInputComponent listens for cancel notifications", (+ tester,+ ) async {+ final cancelNotifier = ValueNotifier<int>(0);+ final controller = TextEditingController(text: "draft");+ addTearDown(cancelNotifier.dispose);+ addTearDown(controller.dispose);++ await tester.pumpWidget(+ _wrap(+ TextInputComponent(+ controller: controller,+ cancelNotifier: cancelNotifier,+ ),+ ),+ );++ cancelNotifier.value++;+ await tester.pump();++ expect(controller.text, "");+ });}Finder _richText(String value) {@@ -349,14 +424,27 @@ Finder _richText(String value) {);}+Finder _fieldContainers() {+ return find.byWidgetPredicate((widget) {+ if (widget is! Container || widget.decoration is! BoxDecoration) {+ return false;+ }+ final decoration = widget.decoration! as BoxDecoration;+ return decoration.borderRadius == BorderRadius.circular(16) &&+ decoration.border is Border;+ });+}++BoxDecoration _fieldDecoration(WidgetTester tester) {+ return tester.widget<Container>(_fieldContainers().first).decoration!+ as BoxDecoration;+}+Widget _wrap(Widget child) {return MaterialApp(theme: ComponentTheme.lightTheme(),home: Scaffold(- body: Padding(- padding: const EdgeInsets.all(24),- child: child,- ),+ body: Padding(padding: const EdgeInsets.all(24), child: child),),);}