The personal finance app for everyone (by everyone)
Ruby
feat(mobile): add SureSegmentedControl primitive and migrate the transaction type selector (#2382)
ghost69f8a5b95f2d
diff --git a/mobile/lib/screens/transaction_form_screen.dart b/mobile/lib/screens/transaction_form_screen.dartindex 5198b320cf..ef54cd6e65 100644--- a/mobile/lib/screens/transaction_form_screen.dart+++ b/mobile/lib/screens/transaction_form_screen.dart@@ -9,14 +9,12 @@ import '../providers/transactions_provider.dart';import '../services/log_service.dart';import '../services/connectivity_service.dart';import '../utils/amount_parser.dart';+import '../widgets/sure_segmented_control.dart';class TransactionFormScreen extends StatefulWidget {final Account account;- const TransactionFormScreen({- super.key,- required this.account,- });+ const TransactionFormScreen({super.key, required this.account});@overrideState<TransactionFormScreen> createState() => _TransactionFormScreenState();@@ -47,7 +45,10 @@ class _TransactionFormScreenState extends State<TransactionFormScreen> {Future<void> _fetchCategories() async {final authProvider = Provider.of<AuthProvider>(context, listen: false);- final categoriesProvider = Provider.of<CategoriesProvider>(context, listen: false);+ final categoriesProvider = Provider.of<CategoriesProvider>(+ context,+ listen: false,+ );final accessToken = await authProvider.getValidAccessToken();if (accessToken != null) {categoriesProvider.fetchCategories(accessToken: accessToken);@@ -114,11 +115,17 @@ class _TransactionFormScreenState extends State<TransactionFormScreen> {try {final authProvider = Provider.of<AuthProvider>(context, listen: false);- final transactionsProvider = Provider.of<TransactionsProvider>(context, listen: false);+ final transactionsProvider = Provider.of<TransactionsProvider>(+ context,+ listen: false,+ );final accessToken = await authProvider.getValidAccessToken();if (accessToken == null) {- _log.warning('TransactionForm', 'Access token is null, session expired');+ _log.warning(+ 'TransactionForm',+ 'Access token is null, session expired',+ );if (mounted) {ScaffoldMessenger.of(context).showSnackBar(const SnackBar(@@ -139,7 +146,10 @@ class _TransactionFormScreenState extends State<TransactionFormScreen> {locale: _currentLocaleName(),);- _log.info('TransactionForm', 'Calling TransactionsProvider.createTransaction (offline-first)');+ _log.info(+ 'TransactionForm',+ 'Calling TransactionsProvider.createTransaction (offline-first)',+ );// Use TransactionsProvider for offline-first transaction creationfinal success = await transactionsProvider.createTransaction(@@ -157,18 +167,24 @@ class _TransactionFormScreenState extends State<TransactionFormScreen> {if (mounted) {if (success) {- _log.info('TransactionForm', 'Transaction created successfully (saved locally)');-+ _log.info(+ 'TransactionForm',+ 'Transaction created successfully (saved locally)',+ );+// Check current connectivity status to show appropriate message- final connectivityService = Provider.of<ConnectivityService>(context, listen: false);+ final connectivityService = Provider.of<ConnectivityService>(+ context,+ listen: false,+ );final isOnline = connectivityService.isOnline;-+ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(isOnline? 'Transaction created successfully'- : 'Transaction saved (will sync when online)'+ : 'Transaction saved (will sync when online)',),backgroundColor: Colors.green,),@@ -185,7 +201,10 @@ class _TransactionFormScreenState extends State<TransactionFormScreen> {}}} catch (e) {- _log.error('TransactionForm', 'Exception during transaction creation: $e');+ _log.error(+ 'TransactionForm',+ 'Exception during transaction creation: $e',+ );if (mounted) {ScaffoldMessenger.of(context).showSnackBar(SnackBar(@@ -235,7 +254,10 @@ class _TransactionFormScreenState extends State<TransactionFormScreen> {),// TitlePadding(- padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 8),+ padding: const EdgeInsets.symmetric(+ horizontal: 24,+ vertical: 8,+ ),child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,children: [@@ -281,20 +303,28 @@ class _TransactionFormScreenState extends State<TransactionFormScreen> {const SizedBox(width: 12),Expanded(child: Column(- crossAxisAlignment: CrossAxisAlignment.start,+ crossAxisAlignment:+ CrossAxisAlignment.start,children: [Text(widget.account.name,- style: Theme.of(context).textTheme.titleMedium?.copyWith(- fontWeight: FontWeight.bold,- ),+ style: Theme.of(context)+ .textTheme+ .titleMedium+ ?.copyWith(+ fontWeight: FontWeight.bold,+ ),),const SizedBox(height: 4),Text('${widget.account.balance} ${widget.account.currency}',- style: Theme.of(context).textTheme.bodyMedium?.copyWith(- color: colorScheme.onSurfaceVariant,- ),+ style: Theme.of(context)+ .textTheme+ .bodyMedium+ ?.copyWith(+ color:+ colorScheme.onSurfaceVariant,+ ),),],),@@ -308,37 +338,38 @@ class _TransactionFormScreenState extends State<TransactionFormScreen> {// Transaction type selectionText('Type',- style: Theme.of(context).textTheme.titleSmall?.copyWith(- fontWeight: FontWeight.w600,- ),+ style: Theme.of(context).textTheme.titleSmall+ ?.copyWith(fontWeight: FontWeight.w600),),const SizedBox(height: 8),- SegmentedButton<String>(+ SureSegmentedControl<String>(+ selected: _nature,+ onChanged: (value) {+ setState(() {+ _nature = value;+ });+ },segments: const [- ButtonSegment<String>(+ SureSegment<String>(value: 'expense',- label: Text('Expense'),+ label: 'Expense',icon: Icon(Icons.arrow_downward),),- ButtonSegment<String>(+ SureSegment<String>(value: 'income',- label: Text('Income'),+ label: 'Income',icon: Icon(Icons.arrow_upward),),],- selected: {_nature},- onSelectionChanged: (Set<String> newSelection) {- setState(() {- _nature = newSelection.first;- });- },),const SizedBox(height: 24),// Amount fieldTextFormField(controller: _amountController,- keyboardType: const TextInputType.numberWithOptions(decimal: true),+ keyboardType: const TextInputType.numberWithOptions(+ decimal: true,+ ),decoration: InputDecoration(labelText: 'Amount *',prefixIcon: const Icon(Icons.attach_money),@@ -356,7 +387,11 @@ class _TransactionFormScreenState extends State<TransactionFormScreen> {_showMoreFields = !_showMoreFields;});},- icon: Icon(_showMoreFields ? Icons.expand_less : Icons.expand_more),+ icon: Icon(+ _showMoreFields+ ? Icons.expand_less+ : Icons.expand_more,+ ),label: Text(_showMoreFields ? 'Less' : 'More'),),@@ -428,8 +463,9 @@ class _TransactionFormScreenState extends State<TransactionFormScreen> {if (value == null) {_selectedCategory = null;} else {- _selectedCategory = categories- .firstWhere((c) => c.id == value);+ _selectedCategory = categories.firstWhere(+ (c) => c.id == value,+ );}});},diff --git a/mobile/lib/widgets/sure_segmented_control.dart b/mobile/lib/widgets/sure_segmented_control.dartnew file mode 100644index 0000000000..dc943762ed--- /dev/null+++ b/mobile/lib/widgets/sure_segmented_control.dart@@ -0,0 +1,192 @@+import 'package:flutter/material.dart';++import '../theme/sure_colors.dart';+import '../theme/sure_tokens.dart';++/// One segment of a [SureSegmentedControl].+class SureSegment<T> {+ const SureSegment({required this.value, required this.label, this.icon});++ final T value;+ final String label;++ /// Optional leading icon (e.g. an [Icon] or [SureIcon]); tinted to match the+ /// segment's selected/unselected label color.+ final Widget? icon;+}++/// Sure design-system segmented control — a tokenized single-select toggle+/// mirroring the web DS `segmented-control`: an inset track holding equal-width+/// segments, where the selected segment is a raised surface (container fill ++/// the subtle DS shadow) and unselected segments are flat `textSecondary` labels.+///+/// Colors resolve from the active [SureColors] palette, so it's brightness-aware+/// and stays in lockstep with `sure.tokens.json` (and avoids the Material+/// `SegmentedButton` `secondaryContainer` look). Expects a bounded width — the+/// segments share it equally.+///+/// ```dart+/// SureSegmentedControl<String>(+/// selected: nature,+/// onChanged: (v) => setState(() => nature = v),+/// segments: const [+/// SureSegment(value: 'expense', label: 'Expense', icon: Icon(Icons.arrow_downward)),+/// SureSegment(value: 'income', label: 'Income', icon: Icon(Icons.arrow_upward)),+/// ],+/// )+/// ```+class SureSegmentedControl<T> extends StatelessWidget {+ const SureSegmentedControl({+ super.key,+ required this.segments,+ required this.selected,+ required this.onChanged,+ });++ final List<SureSegment<T>> segments;+ final T selected;+ final ValueChanged<T> onChanged;++ @override+ Widget build(BuildContext context) {+ // Selection is value-based (segment.value == selected), so duplicate values+ // would render multiple segments as selected at once. Guard in debug builds+ // (a const constructor can't host this non-constant check).+ assert(+ segments.map((s) => s.value).toSet().length == segments.length,+ 'SureSegmentedControl requires unique segment values.',+ );+ final palette = SureColors.of(context).palette;+ final theme = Theme.of(context);+ // The palette has no single "raised surface" token that reads correctly in+ // both modes, so pick the brightness-appropriate one: white-ish in light, a+ // lighter-than-track inset in dark — both sit *above* the track.+ final isLight = theme.brightness == Brightness.light;+ final selectedBg =+ isLight ? palette.container : palette.containerInsetHover;++ return Container(+ padding: const EdgeInsets.all(3),+ decoration: BoxDecoration(+ color: palette.surfaceInset,+ borderRadius: BorderRadius.circular(SureTokens.radiusLg),+ border: Border.all(color: palette.borderSecondary),+ ),+ child: Row(+ children: [+ for (final segment in segments)+ Expanded(+ child: _Segment<T>(+ segment: segment,+ selected: segment.value == selected,+ selectedBg: selectedBg,+ palette: palette,+ textStyle: theme.textTheme.labelLarge,+ onTap: () => onChanged(segment.value),+ ),+ ),+ ],+ ),+ );+ }+}++class _Segment<T> extends StatefulWidget {+ const _Segment({+ required this.segment,+ required this.selected,+ required this.selectedBg,+ required this.palette,+ required this.textStyle,+ required this.onTap,+ });++ final SureSegment<T> segment;+ final bool selected;+ final Color selectedBg;+ final SureTokenPalette palette;+ final TextStyle? textStyle;+ final VoidCallback onTap;++ @override+ State<_Segment<T>> createState() => _SegmentState<T>();+}++class _SegmentState<T> extends State<_Segment<T>> {+ bool _focused = false;++ @override+ Widget build(BuildContext context) {+ final palette = widget.palette;+ final selected = widget.selected;+ final fg = selected ? palette.textPrimary : palette.textSecondary;++ return Semantics(+ button: true,+ selected: selected,+ // FocusableActionDetector makes each segment keyboard/switch focusable and+ // Enter/Space-activatable (parity with the Material SegmentedButton it+ // replaces), mirroring SureButton — without the Material ripple.+ child: FocusableActionDetector(+ mouseCursor: SystemMouseCursors.click,+ onShowFocusHighlight: (value) => setState(() => _focused = value),+ actions: <Type, Action<Intent>>{+ ActivateIntent: CallbackAction<ActivateIntent>(+ onInvoke: (_) {+ widget.onTap();+ return null;+ },+ ),+ },+ child: GestureDetector(+ onTap: widget.onTap,+ behavior: HitTestBehavior.opaque,+ child: AnimatedContainer(+ duration: const Duration(milliseconds: 150),+ curve: Curves.easeOut,+ padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 8),+ decoration: BoxDecoration(+ color: selected ? widget.selectedBg : const Color(0x00000000),+ borderRadius: BorderRadius.circular(SureTokens.radiusMd),+ boxShadow: [+ if (selected) ...palette.shadowXs,+ // Non-displacing focus ring so it doesn't shift the layout.+ if (_focused)+ BoxShadow(+ color: palette.focusRing,+ blurRadius: 0,+ spreadRadius: 2,+ ),+ ],+ ),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ mainAxisAlignment: MainAxisAlignment.center,+ children: [+ if (widget.segment.icon != null) ...[+ IconTheme.merge(+ data: IconThemeData(color: fg, size: 18),+ child: widget.segment.icon!,+ ),+ const SizedBox(width: 6),+ ],+ Flexible(+ child: Text(+ widget.segment.label,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ textAlign: TextAlign.center,+ style: widget.textStyle?.copyWith(+ color: fg,+ fontWeight: selected ? FontWeight.w600 : FontWeight.w500,+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ );+ }+}diff --git a/mobile/test/widgets/sure_segmented_control_test.dart b/mobile/test/widgets/sure_segmented_control_test.dartnew file mode 100644index 0000000000..aaef2fe528--- /dev/null+++ b/mobile/test/widgets/sure_segmented_control_test.dart@@ -0,0 +1,150 @@+import 'package:flutter/material.dart';+import 'package:flutter/semantics.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_segmented_control.dart';++void main() {+ Future<void> pump(+ WidgetTester tester,+ Widget child, {+ Brightness brightness = Brightness.light,+ }) {+ return tester.pumpWidget(+ MaterialApp(+ theme:+ brightness == Brightness.light ? SureTheme.light : SureTheme.dark,+ home: Scaffold(body: Center(child: child)),+ ),+ );+ }++ Widget control(String selected, ValueChanged<String> onChanged) =>+ SureSegmentedControl<String>(+ selected: selected,+ onChanged: onChanged,+ segments: const [+ SureSegment(value: 'expense', label: 'Expense'),+ SureSegment(value: 'income', label: 'Income'),+ ],+ );++ // The selected segment's raised fill is the only chrome that differs by+ // brightness, so assert it resolves correctly in both.+ for (final (brightness, tokens) in [+ (Brightness.light, SureTokens.light),+ (Brightness.dark, SureTokens.dark),+ ]) {+ testWidgets(+ 'selected segment is a raised surface above the track '+ '(${brightness.name})', (tester) async {+ await pump(tester, control('expense', (_) {}), brightness: brightness);++ // Track decoration — the control's only plain Container (segments use+ // AnimatedContainer), so this is unambiguous.+ final track = tester+ .widget<Container>(find+ .descendant(+ of: find.byType(SureSegmentedControl<String>),+ matching: find.byType(Container),+ )+ .first)+ .decoration as BoxDecoration;+ expect(track.color, tokens.surfaceInset);++ // Selected segment fill = brightness-appropriate raised token + shadow.+ final selectedBg = brightness == Brightness.light+ ? tokens.container+ : tokens.containerInsetHover;+ final selectedSeg = tester+ .widget<AnimatedContainer>(+ find+ .ancestor(+ of: find.text('Expense'),+ matching: find.byType(AnimatedContainer),+ )+ .first,+ )+ .decoration as BoxDecoration;+ expect(selectedSeg.color, selectedBg);+ expect(selectedSeg.boxShadow, tokens.shadowXs);++ // Unselected segment is flat (transparent, no shadow).+ final unselectedSeg = tester+ .widget<AnimatedContainer>(+ find+ .ancestor(+ of: find.text('Income'),+ matching: find.byType(AnimatedContainer),+ )+ .first,+ )+ .decoration as BoxDecoration;+ expect(unselectedSeg.color, const Color(0x00000000));+ expect(unselectedSeg.boxShadow, isEmpty);+ });+ }++ testWidgets('selected vs unselected labels use the right tokens', (+ tester,+ ) async {+ await pump(tester, control('expense', (_) {}));+ expect(+ tester.widget<Text>(find.text('Expense')).style?.color,+ SureTokens.light.textPrimary,+ );+ expect(+ tester.widget<Text>(find.text('Income')).style?.color,+ SureTokens.light.textSecondary,+ );+ });++ testWidgets('tapping a segment reports its value', (tester) async {+ String? picked;+ await pump(tester, control('expense', (v) => picked = v));+ await tester.tap(find.text('Income'));+ expect(picked, 'income');+ });++ testWidgets('each segment is keyboard/switch focusable + activatable',+ (tester) async {+ // FocusableActionDetector per segment = keyboard/switch parity with the+ // Material SegmentedButton it replaced (regression guard for the focus gap).+ await pump(tester, control('expense', (_) {}));+ expect(find.byType(FocusableActionDetector), findsNWidgets(2));+ });++ testWidgets('a selected value matching no segment highlights nothing',+ (tester) async {+ await pump(tester, control('neither', (_) {}));+ for (final t in tester+ .widgetList<AnimatedContainer>(find.byType(AnimatedContainer))) {+ expect((t.decoration as BoxDecoration).color, const Color(0x00000000));+ }+ });++ testWidgets('each segment exposes button + selected semantics', (+ tester,+ ) async {+ final handle = tester.ensureSemantics();+ await pump(tester, control('expense', (_) {}));+ expect(+ tester+ .getSemantics(find.text('Expense'))+ .hasFlag(SemanticsFlag.isSelected),+ isTrue,+ );+ expect(+ tester+ .getSemantics(find.text('Income'))+ .hasFlag(SemanticsFlag.isSelected),+ isFalse,+ );+ expect(+ tester.getSemantics(find.text('Expense')).hasFlag(SemanticsFlag.isButton),+ isTrue,+ );+ handle.dispose();+ });+}