Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(mobile): add SureButton primitive and migrate login buttons (#2358)

ghost7b6b74874f00
diff --git a/mobile/lib/screens/login_screen.dart b/mobile/lib/screens/login_screen.dart
index efff02d6f7..cee517e41f 100644
--- a/mobile/lib/screens/login_screen.dart
+++ b/mobile/lib/screens/login_screen.dart
@@ -5,6 +5,7 @@ import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_svg/flutter_svg.dart';
import '../providers/auth_provider.dart';
import '../services/api_config.dart';
+import '../widgets/sure_button.dart';
import 'backend_config_screen.dart';
class LoginScreen extends StatefulWidget {
@@ -411,17 +412,12 @@ class _LoginScreenState extends State<LoginScreen> {
// Login Button
Consumer<AuthProvider>(
builder: (context, authProvider, _) {
- return ElevatedButton(
- onPressed:
- authProvider.isLoading ? null : _handleLogin,
- child: authProvider.isLoading
- ? const SizedBox(
- height: 20,
- width: 20,
- child:
- CircularProgressIndicator(strokeWidth: 2),
- )
- : const Text('Sign In'),
+ return SureButton(
+ label: 'Sign In',
+ size: SureButtonSize.lg,
+ fullWidth: true,
+ loading: authProvider.isLoading,
+ onPressed: _handleLogin,
);
},
),
@@ -451,23 +447,20 @@ class _LoginScreenState extends State<LoginScreen> {
// Google Sign-In button
Consumer<AuthProvider>(
builder: (context, authProvider, _) {
- return OutlinedButton.icon(
- onPressed: authProvider.isLoading
- ? null
- : () =>
- authProvider.startSsoLogin('google_oauth2'),
- icon: SvgPicture.asset(
+ return SureButton(
+ label: 'Sign in with Google',
+ variant: SureButtonVariant.outline,
+ size: SureButtonSize.lg,
+ fullWidth: true,
+ leading: SvgPicture.asset(
'assets/images/google_g_logo.svg',
width: 18,
height: 18,
),
- label: const Text('Sign in with Google'),
- style: OutlinedButton.styleFrom(
- minimumSize: const Size(double.infinity, 50),
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(12),
- ),
- ),
+ onPressed: authProvider.isLoading
+ ? null
+ : () =>
+ authProvider.startSsoLogin('google_oauth2'),
);
},
),
@@ -513,10 +506,17 @@ class _LoginScreenState extends State<LoginScreen> {
const SizedBox(height: 12),
// API Key Login Button
- TextButton.icon(
- onPressed: _showApiKeyDialog,
- icon: const Icon(Icons.vpn_key_outlined, size: 18),
- label: const Text('API-Key Login'),
+ Consumer<AuthProvider>(
+ builder: (context, authProvider, _) {
+ return SureButton(
+ label: 'API-Key Login',
+ variant: SureButtonVariant.ghost,
+ onPressed:
+ authProvider.isLoading ? null : _showApiKeyDialog,
+ leading:
+ const Icon(Icons.vpn_key_outlined, size: 18),
+ );
+ },
),
],
),
diff --git a/mobile/lib/widgets/sure_button.dart b/mobile/lib/widgets/sure_button.dart
new file mode 100644
index 0000000000..0b67da858d
--- /dev/null
+++ b/mobile/lib/widgets/sure_button.dart
@@ -0,0 +1,285 @@
+import 'package:flutter/cupertino.dart' show CupertinoActivityIndicator;
+import 'package:flutter/material.dart';
+
+import '../theme/sure_colors.dart';
+import '../theme/sure_tokens.dart';
+
+/// Sure design-system button variants, mirroring the web `DS::Button`
+/// (`DS::Buttonish::VARIANTS`).
+enum SureButtonVariant { primary, secondary, destructive, outline, ghost }
+
+/// Button sizes, mirroring the web `DS::Buttonish::SIZES` (sm/md/lg ≈ 28/36/48).
+enum SureButtonSize { sm, md, lg }
+
+/// Sure design-system button — a custom, non-Material control mirroring the web
+/// `DS::Button`: tokenized variant colors, `font-medium` label, sizes, and a
+/// flat custom press feedback (no Material ripple). `onPressed: null` (or
+/// [loading]) renders a disabled button.
+///
+/// Colors resolve from the active [SureColors] palette, so the button is
+/// brightness-aware and stays in lockstep with `sure.tokens.json`.
+class SureButton extends StatefulWidget {
+ final String label;
+
+ /// Tap handler. When null the button is disabled (50% opacity, no taps).
+ final VoidCallback? onPressed;
+
+ final SureButtonVariant variant;
+ final SureButtonSize size;
+
+ /// Optional leading widget (e.g. a `SureIcon`), kept decoupled so the button
+ /// doesn't depend on any specific icon implementation.
+ final Widget? leading;
+
+ /// Stretch to the available width (mirrors `full_width`).
+ final bool fullWidth;
+
+ /// Show an adaptive spinner in place of the leading slot and disable taps.
+ final bool loading;
+
+ const SureButton({
+ super.key,
+ required this.label,
+ required this.onPressed,
+ this.variant = SureButtonVariant.primary,
+ this.size = SureButtonSize.md,
+ this.leading,
+ this.fullWidth = false,
+ this.loading = false,
+ });
+
+ @override
+ State<SureButton> createState() => _SureButtonState();
+}
+
+class _SureButtonState extends State<SureButton> {
+ bool _pressed = false;
+ bool _focused = false;
+
+ bool get _enabled => widget.onPressed != null && !widget.loading;
+
+ @override
+ void didUpdateWidget(covariant SureButton oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ // If the button is disabled mid-press, onTapUp/onTapCancel never fire — so
+ // clear the pressed state here to avoid it sticking on once re-enabled.
+ if (!_enabled) {
+ _pressed = false;
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final palette = SureColors.of(context).palette;
+ final style = _SureButtonStyle.resolve(widget.variant, palette);
+ final metrics = _SureButtonMetrics.resolve(widget.size);
+
+ final background = _pressed && _enabled ? style.pressedBackground : style.background;
+
+ final label = Text(
+ widget.label,
+ style: TextStyle(
+ color: style.foreground,
+ fontSize: metrics.fontSize,
+ fontWeight: FontWeight.w500,
+ ),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ );
+
+ // Build the spinner per-platform so the foreground tint is honored on both:
+ // CircularProgressIndicator.adaptive renders a CupertinoActivityIndicator on
+ // Apple platforms, which ignores `valueColor`, so pass `color` to it directly.
+ final platform = Theme.of(context).platform;
+ final isCupertino =
+ platform == TargetPlatform.iOS || platform == TargetPlatform.macOS;
+ final leading = widget.loading
+ ? SizedBox(
+ width: metrics.fontSize,
+ height: metrics.fontSize,
+ child: isCupertino
+ ? CupertinoActivityIndicator(
+ color: style.foreground,
+ radius: metrics.fontSize / 2,
+ )
+ : CircularProgressIndicator(
+ strokeWidth: 2,
+ valueColor: AlwaysStoppedAnimation<Color>(style.foreground),
+ ),
+ )
+ : widget.leading;
+
+ final content = Row(
+ mainAxisSize: widget.fullWidth ? MainAxisSize.max : MainAxisSize.min,
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ if (leading != null) ...[leading, const SizedBox(width: 8)],
+ // Flex only when full-width (bounded). A bare Flexible in a min-size Row
+ // asserts under unbounded horizontal constraints, so an inline button
+ // passes the self-sizing label directly.
+ if (widget.fullWidth) Flexible(child: label) else label,
+ ],
+ );
+
+ final button = AnimatedContainer(
+ duration: const Duration(milliseconds: 80),
+ constraints: BoxConstraints(minHeight: metrics.height),
+ padding: EdgeInsets.symmetric(horizontal: metrics.horizontalPadding),
+ decoration: BoxDecoration(
+ color: background,
+ borderRadius: BorderRadius.circular(metrics.radius),
+ border: style.border == null
+ ? null
+ : Border.all(color: style.border!),
+ // Keyboard/switch-control focus ring (drawn as a non-displacing ring so
+ // it doesn't shift layout). borderPrimary is brightness-aware.
+ boxShadow: _focused
+ ? [
+ BoxShadow(
+ color: palette.borderPrimary,
+ blurRadius: 0,
+ spreadRadius: 2,
+ ),
+ ]
+ : null,
+ ),
+ child: Center(widthFactor: widget.fullWidth ? null : 1.0, child: content),
+ );
+
+ return Semantics(
+ button: true,
+ enabled: _enabled,
+ label: widget.loading ? '${widget.label}, loading' : widget.label,
+ child: FocusableActionDetector(
+ enabled: _enabled,
+ mouseCursor:
+ _enabled ? SystemMouseCursors.click : SystemMouseCursors.basic,
+ onShowFocusHighlight: (value) => setState(() => _focused = value),
+ actions: <Type, Action<Intent>>{
+ ActivateIntent: CallbackAction<ActivateIntent>(
+ onInvoke: (_) {
+ if (_enabled) widget.onPressed?.call();
+ return null;
+ },
+ ),
+ },
+ child: Opacity(
+ opacity: _enabled ? 1.0 : 0.5,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ // Keep all tap callbacks present (a stable gesture arena) and gate
+ // on `_enabled` inside them. Swapping them to null when the button
+ // is disabled mid-press would dispose the recognizer during the
+ // rebuild and fire onTapCancel -> setState() during build.
+ onTapDown: (_) {
+ if (_enabled) setState(() => _pressed = true);
+ },
+ onTapUp: (_) {
+ if (_pressed) setState(() => _pressed = false);
+ },
+ onTapCancel: () {
+ if (_pressed) setState(() => _pressed = false);
+ },
+ onTap: () {
+ if (_enabled) widget.onPressed?.call();
+ },
+ child: button,
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+class _SureButtonStyle {
+ const _SureButtonStyle({
+ required this.background,
+ required this.pressedBackground,
+ required this.foreground,
+ this.border,
+ });
+
+ final Color background;
+ final Color pressedBackground;
+ final Color foreground;
+ final Color? border;
+
+ static _SureButtonStyle resolve(
+ SureButtonVariant variant,
+ SureTokenPalette p,
+ ) {
+ switch (variant) {
+ case SureButtonVariant.primary:
+ return _SureButtonStyle(
+ background: p.buttonPrimary,
+ pressedBackground: p.buttonPrimaryHover,
+ foreground: p.textInverse,
+ );
+ case SureButtonVariant.destructive:
+ return _SureButtonStyle(
+ background: p.buttonDestructive,
+ pressedBackground: p.buttonDestructiveHover,
+ foreground: p.textInverse,
+ );
+ case SureButtonVariant.secondary:
+ return _SureButtonStyle(
+ background: p.surfaceInset,
+ pressedBackground: p.surfaceInsetHover,
+ foreground: p.textPrimary,
+ );
+ case SureButtonVariant.outline:
+ return _SureButtonStyle(
+ background: const Color(0x00000000),
+ pressedBackground: p.surfaceHover,
+ foreground: p.textPrimary,
+ border: p.borderSecondary,
+ );
+ case SureButtonVariant.ghost:
+ return _SureButtonStyle(
+ background: const Color(0x00000000),
+ pressedBackground: p.surfaceHover,
+ foreground: p.textPrimary,
+ );
+ }
+ }
+}
+
+class _SureButtonMetrics {
+ const _SureButtonMetrics({
+ required this.height,
+ required this.horizontalPadding,
+ required this.fontSize,
+ required this.radius,
+ });
+
+ final double height;
+ final double horizontalPadding;
+ final double fontSize;
+ final double radius;
+
+ static _SureButtonMetrics resolve(SureButtonSize size) {
+ switch (size) {
+ case SureButtonSize.sm:
+ return const _SureButtonMetrics(
+ height: 28,
+ horizontalPadding: 12,
+ fontSize: 14,
+ radius: SureTokens.radiusMd,
+ );
+ case SureButtonSize.md:
+ return const _SureButtonMetrics(
+ height: 36,
+ horizontalPadding: 16,
+ fontSize: 14,
+ radius: SureTokens.radiusLg,
+ );
+ case SureButtonSize.lg:
+ return const _SureButtonMetrics(
+ height: 48,
+ horizontalPadding: 20,
+ fontSize: 16,
+ radius: SureTokens.radiusLg,
+ );
+ }
+ }
+}
diff --git a/mobile/test/widgets/sure_button_test.dart b/mobile/test/widgets/sure_button_test.dart
new file mode 100644
index 0000000000..df4adfc2c6
--- /dev/null
+++ b/mobile/test/widgets/sure_button_test.dart
@@ -0,0 +1,208 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:sure_mobile/theme/sure_theme.dart';
+import 'package:sure_mobile/theme/sure_tokens.dart';
+import 'package:sure_mobile/widgets/sure_button.dart';
+
+void main() {
+ Future<void> pump(WidgetTester tester, Widget child) {
+ return tester.pumpWidget(
+ MaterialApp(
+ theme: SureTheme.light,
+ home: Scaffold(body: Center(child: child)),
+ ),
+ );
+ }
+
+ BoxDecoration decoration(WidgetTester tester) =>
+ tester.widget<AnimatedContainer>(find.byType(AnimatedContainer)).decoration
+ as BoxDecoration;
+
+ testWidgets('primary uses the button-primary token + inverse label', (tester) async {
+ await pump(
+ tester,
+ SureButton(label: 'Save', onPressed: () {}),
+ );
+ expect(decoration(tester).color, SureTokens.light.buttonPrimary);
+ final label = tester.widget<Text>(find.text('Save'));
+ expect(label.style?.color, SureTokens.light.textInverse);
+ expect(label.style?.fontWeight, FontWeight.w500);
+ });
+
+ testWidgets('destructive uses the destructive token', (tester) async {
+ await pump(
+ tester,
+ SureButton(
+ label: 'Delete',
+ variant: SureButtonVariant.destructive,
+ onPressed: () {},
+ ),
+ );
+ expect(decoration(tester).color, SureTokens.light.buttonDestructive);
+ });
+
+ testWidgets('secondary uses the inset-surface token', (tester) async {
+ await pump(
+ tester,
+ SureButton(
+ label: 'More',
+ variant: SureButtonVariant.secondary,
+ onPressed: () {},
+ ),
+ );
+ expect(decoration(tester).color, SureTokens.light.surfaceInset);
+ });
+
+ testWidgets('outline is transparent with a border and primary text',
+ (tester) async {
+ await pump(
+ tester,
+ SureButton(
+ label: 'Outline',
+ variant: SureButtonVariant.outline,
+ onPressed: () {},
+ ),
+ );
+ final deco = decoration(tester);
+ expect(deco.color, const Color(0x00000000));
+ expect((deco.border as Border).top.color, SureTokens.light.borderSecondary);
+ expect(
+ tester.widget<Text>(find.text('Outline')).style?.color,
+ SureTokens.light.textPrimary,
+ );
+ });
+
+ testWidgets('ghost is transparent with no border', (tester) async {
+ await pump(
+ tester,
+ SureButton(
+ label: 'Ghost',
+ variant: SureButtonVariant.ghost,
+ onPressed: () {},
+ ),
+ );
+ final deco = decoration(tester);
+ expect(deco.color, const Color(0x00000000));
+ expect(deco.border, isNull);
+ });
+
+ testWidgets('renders in an unbounded-width Row without asserting',
+ (tester) async {
+ // Regression: a bare Flexible in the label Row used to throw under
+ // unbounded horizontal constraints; an inline (non-full-width) button must
+ // self-size instead.
+ await pump(
+ tester,
+ Row(children: [SureButton(label: 'Inline', onPressed: () {})]),
+ );
+ expect(tester.takeException(), isNull);
+ expect(find.text('Inline'), findsOneWidget);
+ });
+
+ testWidgets('clears the pressed highlight if disabled mid-press',
+ (tester) async {
+ // Regression: if disabled while pressed, onTapUp/onTapCancel never fire, so
+ // didUpdateWidget must reset _pressed (otherwise the hover bg sticks once
+ // the button is re-enabled).
+ Widget build(bool loading) => MaterialApp(
+ theme: SureTheme.light,
+ home: Scaffold(
+ body: Center(
+ child: SureButton(
+ key: const ValueKey('btn'),
+ label: 'Go',
+ loading: loading,
+ onPressed: () {},
+ ),
+ ),
+ ),
+ );
+
+ await tester.pumpWidget(build(false));
+ final gesture =
+ await tester.startGesture(tester.getCenter(find.byType(SureButton)));
+ await tester.pump(); // onTapDown -> _pressed = true
+ await tester.pumpWidget(build(true)); // disabled mid-press -> reset
+ await tester.pump();
+ await tester.pumpWidget(build(false)); // re-enabled
+ await tester.pump();
+ // Background must be the base token, not the pressed (hover) token.
+ expect(decoration(tester).color, SureTokens.light.buttonPrimary);
+ await gesture.up();
+ });
+
+ testWidgets('tap fires onPressed when enabled', (tester) async {
+ var taps = 0;
+ await pump(tester, SureButton(label: 'Go', onPressed: () => taps++));
+ await tester.tap(find.byType(SureButton));
+ expect(taps, 1);
+ });
+
+ testWidgets('null onPressed disables taps and dims the button', (tester) async {
+ await pump(
+ tester,
+ const SureButton(label: 'Disabled', onPressed: null),
+ );
+ // Tapping a disabled button must not throw, and it stays dimmed.
+ await tester.tap(find.byType(SureButton));
+ expect(tester.widget<Opacity>(find.byType(Opacity)).opacity, 0.5);
+ });
+
+ testWidgets('loading shows a spinner and blocks taps', (tester) async {
+ var taps = 0;
+ await pump(
+ tester,
+ SureButton(label: 'Saving', onPressed: () => taps++, loading: true),
+ );
+ expect(find.byType(CircularProgressIndicator), findsOneWidget);
+ await tester.tap(find.byType(SureButton));
+ expect(taps, 0);
+ });
+
+ testWidgets('activates via the keyboard (focus + Enter)', (tester) async {
+ var taps = 0;
+ await pump(tester, SureButton(label: 'Go', onPressed: () => taps++));
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(taps, 1);
+ });
+
+ testWidgets('fullWidth fills the available width', (tester) async {
+ await pump(
+ tester,
+ ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 300),
+ child: SureButton(label: 'Wide', fullWidth: true, onPressed: () {}),
+ ),
+ );
+ expect(tester.getSize(find.byType(SureButton)).width, 300);
+ });
+
+ testWidgets('non-fullWidth hugs its content', (tester) async {
+ await pump(
+ tester,
+ ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 300),
+ child: SureButton(label: 'Hi', onPressed: () {}),
+ ),
+ );
+ expect(tester.getSize(find.byType(SureButton)).width, lessThan(300));
+ });
+
+ testWidgets('size maps to the canonical min-height', (tester) async {
+ await pump(
+ tester,
+ SureButton(label: 'Big', size: SureButtonSize.lg, onPressed: () {}),
+ );
+ expect(
+ tester
+ .widget<AnimatedContainer>(find.byType(AnimatedContainer))
+ .constraints
+ ?.minHeight,
+ 48,
+ );
+ });
+}