diff --git a/lib/core/theme.dart b/lib/core/theme.dart index abafc19..26e0a42 100644 --- a/lib/core/theme.dart +++ b/lib/core/theme.dart @@ -24,12 +24,30 @@ class AppTheme { margin: EdgeInsets.zero, ), textTheme: const TextTheme( - headlineLarge: TextStyle(fontSize: 32, fontWeight: FontWeight.bold, letterSpacing: -0.5, color: Color(0xFF1A1A1A)), - headlineMedium: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, letterSpacing: -0.5, color: Color(0xFF1A1A1A)), - titleLarge: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: Color(0xFF1A1A1A)), + headlineLarge: TextStyle( + fontSize: 32, + fontWeight: FontWeight.bold, + letterSpacing: -0.5, + color: Color(0xFF1A1A1A), + ), + headlineMedium: TextStyle( + fontSize: 24, + fontWeight: FontWeight.bold, + letterSpacing: -0.5, + color: Color(0xFF1A1A1A), + ), + titleLarge: TextStyle( + fontSize: 18, + fontWeight: FontWeight.w600, + color: Color(0xFF1A1A1A), + ), bodyLarge: TextStyle(fontSize: 16, color: Color(0xFF2C2C2C)), bodyMedium: TextStyle(fontSize: 14, color: Color(0xFF4A4A4A)), - labelLarge: TextStyle(fontSize: 14, fontWeight: FontWeight.bold, color: Color(0xFF1A1A1A)), + labelLarge: TextStyle( + fontSize: 14, + fontWeight: FontWeight.bold, + color: Color(0xFF1A1A1A), + ), ), appBarTheme: const AppBarTheme( backgroundColor: Colors.white, @@ -68,12 +86,30 @@ class AppTheme { margin: EdgeInsets.zero, ), textTheme: const TextTheme( - headlineLarge: TextStyle(fontSize: 32, fontWeight: FontWeight.bold, letterSpacing: -0.5, color: Colors.white), - headlineMedium: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, letterSpacing: -0.5, color: Colors.white), - titleLarge: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: Colors.white), + headlineLarge: TextStyle( + fontSize: 32, + fontWeight: FontWeight.bold, + letterSpacing: -0.5, + color: Colors.white, + ), + headlineMedium: TextStyle( + fontSize: 24, + fontWeight: FontWeight.bold, + letterSpacing: -0.5, + color: Colors.white, + ), + titleLarge: TextStyle( + fontSize: 18, + fontWeight: FontWeight.w600, + color: Colors.white, + ), bodyLarge: TextStyle(fontSize: 16, color: Color(0xFFE0E0E0)), bodyMedium: TextStyle(fontSize: 14, color: Color(0xFFA0A0A0)), - labelLarge: TextStyle(fontSize: 14, fontWeight: FontWeight.bold, color: Colors.white), + labelLarge: TextStyle( + fontSize: 14, + fontWeight: FontWeight.bold, + color: Colors.white, + ), ), appBarTheme: const AppBarTheme( backgroundColor: Color(0xFF121212), diff --git a/lib/features/about/about_screen.dart b/lib/features/about/about_screen.dart index cdf193f..0bc6b4d 100644 --- a/lib/features/about/about_screen.dart +++ b/lib/features/about/about_screen.dart @@ -15,20 +15,18 @@ class AboutScreen extends ConsumerWidget { final String versionText = packageInfoAsync.when( data: (info) => info.version, - loading: () => '1.1.0', - error: (err, stack) => '1.1.0', + loading: () => '1.0.2', + error: (err, stack) => '1.0.2', ); final String buildText = packageInfoAsync.when( data: (info) => info.buildNumber, - loading: () => '2', - error: (err, stack) => '2', + loading: () => '3', + error: (err, stack) => '3', ); return Scaffold( - appBar: AppBar( - title: const Text('About PlayMate'), - ), + appBar: AppBar(title: const Text('About PlayMate')), body: SafeArea( child: ResponsiveLayout( mobile: SingleChildScrollView( @@ -48,7 +46,9 @@ class AboutScreen extends ConsumerWidget { Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( - color: theme.colorScheme.primary.withValues(alpha: 0.1), + color: theme.colorScheme.primary.withValues( + alpha: 0.1, + ), borderRadius: BorderRadius.circular(12), ), child: Icon( @@ -64,17 +64,19 @@ class AboutScreen extends ConsumerWidget { children: [ Text( 'PlayMate', - style: theme.textTheme.headlineLarge?.copyWith( - fontWeight: FontWeight.w900, - letterSpacing: -0.5, - ), + style: theme.textTheme.headlineLarge + ?.copyWith( + fontWeight: FontWeight.w900, + letterSpacing: -0.5, + ), ), Text( 'Everything you need for offline games.', - style: theme.textTheme.titleMedium?.copyWith( - color: theme.colorScheme.secondary, - fontWeight: FontWeight.w500, - ), + style: theme.textTheme.titleMedium + ?.copyWith( + color: theme.colorScheme.secondary, + fontWeight: FontWeight.w500, + ), ), ], ), @@ -151,7 +153,8 @@ class AboutScreen extends ConsumerWidget { title: const Text('Official Website'), subtitle: const Text('sundramdotdev.xyz'), trailing: const Icon(Icons.open_in_new, size: 18), - onTap: () => ExternalLinks.openUrl(ExternalLinks.websiteUrl), + onTap: () => + ExternalLinks.openUrl(ExternalLinks.websiteUrl), ), const Divider(height: 1), ListTile( @@ -160,7 +163,8 @@ class AboutScreen extends ConsumerWidget { title: const Text('GitHub'), subtitle: const Text('github.com/sundramdotdev'), trailing: const Icon(Icons.open_in_new, size: 18), - onTap: () => ExternalLinks.openUrl(ExternalLinks.githubUrl), + onTap: () => + ExternalLinks.openUrl(ExternalLinks.githubUrl), ), const Divider(height: 1), ListTile( @@ -169,16 +173,21 @@ class AboutScreen extends ConsumerWidget { title: const Text('LinkedIn'), subtitle: const Text('linkedin.com/in/sundramdotdev'), trailing: const Icon(Icons.open_in_new, size: 18), - onTap: () => ExternalLinks.openUrl(ExternalLinks.linkedinUrl), + onTap: () => + ExternalLinks.openUrl(ExternalLinks.linkedinUrl), ), const Divider(height: 1), ListTile( contentPadding: EdgeInsets.zero, leading: const Icon(Icons.folder_zip_outlined), title: const Text('PlayMate Repository'), - subtitle: const Text('github.com/sundramdotdev/playmate'), + subtitle: const Text( + 'github.com/sundramdotdev/playmate', + ), trailing: const Icon(Icons.open_in_new, size: 18), - onTap: () => ExternalLinks.openUrl(ExternalLinks.repositoryUrl), + onTap: () => ExternalLinks.openUrl( + ExternalLinks.repositoryUrl, + ), ), const Divider(height: 1), ListTile( @@ -187,7 +196,8 @@ class AboutScreen extends ConsumerWidget { title: const Text('Instagram'), subtitle: const Text('@devsundram_'), trailing: const Icon(Icons.open_in_new, size: 18), - onTap: () => ExternalLinks.openUrl(ExternalLinks.instagramUrl), + onTap: () => + ExternalLinks.openUrl(ExternalLinks.instagramUrl), ), ], ), @@ -201,7 +211,7 @@ class AboutScreen extends ConsumerWidget { children: [ ListTile( leading: const Icon(Icons.new_releases_outlined), - title: const Text('What\'s New in 1.1.0'), + title: const Text('What\'s New in 1.0.2'), trailing: const Icon(Icons.chevron_right), onTap: () => context.push('/changelog'), ), diff --git a/lib/features/about/changelog_screen.dart b/lib/features/about/changelog_screen.dart index 174954b..62477fd 100644 --- a/lib/features/about/changelog_screen.dart +++ b/lib/features/about/changelog_screen.dart @@ -10,7 +10,7 @@ class ChangelogScreen extends StatelessWidget { final releases = [ { - 'version': 'v1.1.0', + 'version': 'v1.0.2', 'date': 'October 2026', 'isLatest': true, 'highlights': [ @@ -34,7 +34,7 @@ class ChangelogScreen extends StatelessWidget { '3D Coin Toss with multi-coin flipping and streak tracking.', 'Smart Team Generator with random and skill-balanced modes.', 'Universal Score Tracker with round-by-round history and undo.', - + 'Gully & Club Cricket Scorer with legal delivery counting and run rate.', 'Custom Spin Wheel with angular velocity physics and elimination mode.', 'Tournament Generator for 4 to 32 team elimination brackets.', @@ -76,9 +76,7 @@ class ChangelogScreen extends StatelessWidget { ]; return Scaffold( - appBar: AppBar( - title: const Text('What\'s New'), - ), + appBar: AppBar(title: const Text('What\'s New')), body: SafeArea( child: ResponsiveLayout( mobile: ListView.builder( diff --git a/lib/features/about/link_launcher.dart b/lib/features/about/link_launcher.dart index 4f148cf..dcc1411 100644 --- a/lib/features/about/link_launcher.dart +++ b/lib/features/about/link_launcher.dart @@ -9,11 +9,14 @@ class ExternalLinks { static const String githubUrl = 'https://github.com/sundramdotdev'; static const String linkedinUrl = 'https://linkedin.com/in/sundramdotdev'; static const String websiteUrl = 'https://www.sundramdotdev.xyz'; - static const String portfolioFallbackUrl = 'https://sundramdotdev-portfolio.vercel.app'; - static const String instagramUrl = 'https://www.instagram.com/devsundram_?stkn=dXBva2IwMzZxbHY1'; + static const String portfolioFallbackUrl = + 'https://sundramdotdev-portfolio.vercel.app'; + static const String instagramUrl = + 'https://www.instagram.com/devsundram_?stkn=dXBva2IwMzZxbHY1'; // Project Repositories & Resources - static const String repositoryUrl = 'https://github.com/sundramdotdev/playmate'; + static const String repositoryUrl = + 'https://github.com/sundramdotdev/playmate'; static const String supportEmail = 'support@playmateapp.com'; /// Launches a verified external URL in the default system browser or native application. @@ -26,10 +29,7 @@ class ExternalLinks { ); if (launched) return true; - return await launchUrl( - uri, - mode: LaunchMode.platformDefault, - ); + return await launchUrl(uri, mode: LaunchMode.platformDefault); } catch (e) { debugPrint('Failed to open external link: $urlString ($e)'); try { diff --git a/lib/features/about/privacy_policy_screen.dart b/lib/features/about/privacy_policy_screen.dart index 0351668..e81053a 100644 --- a/lib/features/about/privacy_policy_screen.dart +++ b/lib/features/about/privacy_policy_screen.dart @@ -11,9 +11,7 @@ class PrivacyPolicyScreen extends StatelessWidget { final theme = Theme.of(context); return Scaffold( - appBar: AppBar( - title: const Text('Privacy Policy'), - ), + appBar: AppBar(title: const Text('Privacy Policy')), body: SafeArea( child: ResponsiveLayout( mobile: SingleChildScrollView( @@ -21,10 +19,7 @@ class PrivacyPolicyScreen extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text( - 'Privacy Policy', - style: theme.textTheme.headlineMedium, - ), + Text('Privacy Policy', style: theme.textTheme.headlineMedium), const SizedBox(height: AppSpacing.xs), Text( 'Last Updated: October 2026', @@ -113,9 +108,7 @@ class PrivacyPolicyScreen extends StatelessWidget { Linkify( onOpen: (link) => openExternalUrl(link.url), text: body, - style: theme.textTheme.bodyLarge?.copyWith( - height: 1.5, - ), + style: theme.textTheme.bodyLarge?.copyWith(height: 1.5), linkStyle: TextStyle( color: theme.colorScheme.primary, fontWeight: FontWeight.bold, diff --git a/lib/features/about/terms_screen.dart b/lib/features/about/terms_screen.dart index 147c02d..16dc7e9 100644 --- a/lib/features/about/terms_screen.dart +++ b/lib/features/about/terms_screen.dart @@ -11,9 +11,7 @@ class TermsScreen extends StatelessWidget { final theme = Theme.of(context); return Scaffold( - appBar: AppBar( - title: const Text('Terms & Conditions'), - ), + appBar: AppBar(title: const Text('Terms & Conditions')), body: SafeArea( child: ResponsiveLayout( mobile: SingleChildScrollView( @@ -98,9 +96,7 @@ class TermsScreen extends StatelessWidget { Linkify( onOpen: (link) => openExternalUrl(link.url), text: body, - style: theme.textTheme.bodyLarge?.copyWith( - height: 1.5, - ), + style: theme.textTheme.bodyLarge?.copyWith(height: 1.5), linkStyle: TextStyle( color: theme.colorScheme.primary, fontWeight: FontWeight.bold, diff --git a/lib/features/coin/coin_face.dart b/lib/features/coin/coin_face.dart index 3781441..1def5c2 100644 --- a/lib/features/coin/coin_face.dart +++ b/lib/features/coin/coin_face.dart @@ -115,9 +115,8 @@ class _CoinFacePainter extends CustomPainter { void _drawEngravedRims(Canvas canvas, Offset center, double radius) { // Outer engraved trench rim final outerRingPaint = Paint() - ..color = (isDarkMode ? Colors.black : const Color(0xFFC8C4B8)).withValues( - alpha: (isDarkMode ? 0.7 : 0.5) * lightIntensity, - ) + ..color = (isDarkMode ? Colors.black : const Color(0xFFC8C4B8)) + .withValues(alpha: (isDarkMode ? 0.7 : 0.5) * lightIntensity) ..style = PaintingStyle.stroke ..strokeWidth = radius * 0.035; canvas.drawCircle(center, radius * 0.90, outerRingPaint); @@ -150,10 +149,12 @@ class _CoinFacePainter extends CustomPainter { final double innerAngle = outerAngle + (math.pi / 4); final ox = center.dx + starRadius * math.cos(outerAngle); - final oy = center.dy - (radius * 0.04) + starRadius * math.sin(outerAngle); + final oy = + center.dy - (radius * 0.04) + starRadius * math.sin(outerAngle); final ix = center.dx + innerRadius * math.cos(innerAngle); - final iy = center.dy - (radius * 0.04) + innerRadius * math.sin(innerAngle); + final iy = + center.dy - (radius * 0.04) + innerRadius * math.sin(innerAngle); if (i == 0) { starPath.moveTo(ox, oy); @@ -187,7 +188,12 @@ class _CoinFacePainter extends CustomPainter { ); // Micro text label "HEADS" - _drawMicroLabel(canvas, 'HEADS', Offset(center.dx, center.dy + radius * 0.48), radius * 0.125); + _drawMicroLabel( + canvas, + 'HEADS', + Offset(center.dx, center.dy + radius * 0.48), + radius * 0.125, + ); } void _drawTailsBranding(Canvas canvas, Offset center, double radius) { @@ -204,10 +210,12 @@ class _CoinFacePainter extends CustomPainter { final loopRadius = monogramWidth - stemWidth; // Vertical stem - path.addRRect(RRect.fromRectAndRadius( - Rect.fromLTWH(topLeft.dx, topLeft.dy, stemWidth, monogramHeight), - Radius.circular(stemWidth * 0.4), - )); + path.addRRect( + RRect.fromRectAndRadius( + Rect.fromLTWH(topLeft.dx, topLeft.dy, stemWidth, monogramHeight), + Radius.circular(stemWidth * 0.4), + ), + ); // Upper semi-circle loop final loopRect = Rect.fromLTWH( @@ -216,7 +224,10 @@ class _CoinFacePainter extends CustomPainter { monogramWidth, monogramHeight * 0.58, ); - final loopRRect = RRect.fromRectAndRadius(loopRect, Radius.circular(loopRadius * 0.7)); + final loopRRect = RRect.fromRectAndRadius( + loopRect, + Radius.circular(loopRadius * 0.7), + ); final innerLoopRRect = RRect.fromRectAndRadius( Rect.fromLTWH( topLeft.dx + stemWidth, @@ -251,16 +262,29 @@ class _CoinFacePainter extends CustomPainter { ..color = accentColor ..style = PaintingStyle.fill; canvas.drawCircle( - Offset(topLeft.dx + stemWidth + loopRadius * 0.45, topLeft.dy + monogramHeight * 0.29), + Offset( + topLeft.dx + stemWidth + loopRadius * 0.45, + topLeft.dy + monogramHeight * 0.29, + ), radius * 0.05, bronzeSparkPaint, ); // Micro text label "TAILS" - _drawMicroLabel(canvas, 'TAILS', Offset(center.dx, center.dy + radius * 0.48), radius * 0.125); + _drawMicroLabel( + canvas, + 'TAILS', + Offset(center.dx, center.dy + radius * 0.48), + radius * 0.125, + ); } - void _drawMicroLabel(Canvas canvas, String text, Offset position, double fontSize) { + void _drawMicroLabel( + Canvas canvas, + String text, + Offset position, + double fontSize, + ) { final textSpan = TextSpan( text: text, style: TextStyle( @@ -278,7 +302,10 @@ class _CoinFacePainter extends CustomPainter { textPainter.layout(); textPainter.paint( canvas, - Offset(position.dx - textPainter.width / 2, position.dy - textPainter.height / 2), + Offset( + position.dx - textPainter.width / 2, + position.dy - textPainter.height / 2, + ), ); } diff --git a/lib/features/coin/coin_provider.dart b/lib/features/coin/coin_provider.dart index 6ffa131..975fd35 100644 --- a/lib/features/coin/coin_provider.dart +++ b/lib/features/coin/coin_provider.dart @@ -40,11 +40,13 @@ class CoinNotifier extends StateNotifier { final Random _random = Random(); CoinNotifier() - : super(CoinState( + : super( + CoinState( lastResult: CoinSide.heads, isFlipping: false, tossHistory: [], - )) { + ), + ) { _loadHistory(); } @@ -54,10 +56,12 @@ class CoinNotifier extends StateNotifier { final List? historyRaw = box.get('coin_history'); if (historyRaw != null) { final history = historyRaw - .map((e) => CoinSide.values.firstWhere( - (element) => element.name == e, - orElse: () => CoinSide.heads, - )) + .map( + (e) => CoinSide.values.firstWhere( + (element) => element.name == e, + orElse: () => CoinSide.heads, + ), + ) .toList(); state = state.copyWith(tossHistory: history); } @@ -80,27 +84,24 @@ class CoinNotifier extends StateNotifier { if (state.isFlipping) return; // 1. Generate authoritative logical result first - final CoinSide result = _random.nextBool() ? CoinSide.heads : CoinSide.tails; + final CoinSide result = _random.nextBool() + ? CoinSide.heads + : CoinSide.tails; // 2. Publish target result immediately so visual renderer computes target orientation - state = state.copyWith( - lastResult: result, - isFlipping: true, - ); + state = state.copyWith(lastResult: result, isFlipping: true); // 3. Await duration matching physical 3D animation timeline await Future.delayed(CoinMotionConfig.flipDuration); // 4. Update history upon settling - final updatedHistory = List.from(state.tossHistory)..insert(0, result); + final updatedHistory = List.from(state.tossHistory) + ..insert(0, result); if (updatedHistory.length > 50) { updatedHistory.removeLast(); } - state = state.copyWith( - isFlipping: false, - tossHistory: updatedHistory, - ); + state = state.copyWith(isFlipping: false, tossHistory: updatedHistory); // Save history & statistics in storage if (StorageService.isBoxOpen(StorageService.statsBoxName)) { diff --git a/lib/features/coin/coin_screen.dart b/lib/features/coin/coin_screen.dart index f161528..d2bca8b 100644 --- a/lib/features/coin/coin_screen.dart +++ b/lib/features/coin/coin_screen.dart @@ -68,7 +68,9 @@ class _CoinScreenState extends ConsumerState { LayoutBuilder( builder: (context, constraints) { final double availableWidth = constraints.maxWidth; - final double coinSize = _calculateResponsiveCoinSize(availableWidth); + final double coinSize = _calculateResponsiveCoinSize( + availableWidth, + ); return Center( child: PlayMateCoin( @@ -93,7 +95,11 @@ class _CoinScreenState extends ConsumerState { _buildStatsSummary(coinState, theme, isDarkMode), const SizedBox(height: 14), // Compact recent toss history - _buildRecentHistorySection(coinState, theme, isDarkMode), + _buildRecentHistorySection( + coinState, + theme, + isDarkMode, + ), ], ], ), @@ -179,7 +185,11 @@ class _CoinScreenState extends ConsumerState { ); } - Widget _buildStatsSummary(CoinState coinState, ThemeData theme, bool isDarkMode) { + Widget _buildStatsSummary( + CoinState coinState, + ThemeData theme, + bool isDarkMode, + ) { return Container( padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8), decoration: BoxDecoration( @@ -246,11 +256,7 @@ class _CoinScreenState extends ConsumerState { Row( mainAxisAlignment: MainAxisAlignment.center, children: [ - Icon( - Icons.history, - size: 15, - color: theme.colorScheme.secondary, - ), + Icon(Icons.history, size: 15, color: theme.colorScheme.secondary), const SizedBox(width: 6), Text( 'Recent Tosses', @@ -276,16 +282,25 @@ class _CoinScreenState extends ConsumerState { return Padding( padding: const EdgeInsets.only(right: 6.0), child: Container( - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), + padding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 5, + ), decoration: BoxDecoration( color: isLatest - ? (isDarkMode ? const Color(0xFF2C2C2E) : const Color(0xFFEBEBEB)) - : (isDarkMode ? const Color(0xFF1E1E1E) : const Color(0xFFF5F5F5)), + ? (isDarkMode + ? const Color(0xFF2C2C2E) + : const Color(0xFFEBEBEB)) + : (isDarkMode + ? const Color(0xFF1E1E1E) + : const Color(0xFFF5F5F5)), borderRadius: BorderRadius.circular(10), border: Border.all( color: isLatest ? const Color(0xFFC18A42).withValues(alpha: 0.4) - : (isDarkMode ? const Color(0xFF2C2C2C) : const Color(0xFFE0E0E0)), + : (isDarkMode + ? const Color(0xFF2C2C2C) + : const Color(0xFFE0E0E0)), width: 1.0, ), ), @@ -307,9 +322,13 @@ class _CoinScreenState extends ConsumerState { side == CoinSide.heads ? 'H' : 'T', style: TextStyle( fontSize: 12, - fontWeight: isLatest ? FontWeight.bold : FontWeight.w600, + fontWeight: isLatest + ? FontWeight.bold + : FontWeight.w600, color: isLatest - ? (isDarkMode ? Colors.white : const Color(0xFF1A1A1A)) + ? (isDarkMode + ? Colors.white + : const Color(0xFF1A1A1A)) : theme.colorScheme.secondary, ), ), @@ -329,9 +348,7 @@ class _CoinScreenState extends ConsumerState { padding: const EdgeInsets.all(AppSpacing.m), decoration: BoxDecoration( color: theme.colorScheme.surface, - border: Border( - top: BorderSide(color: theme.dividerColor, width: 1), - ), + border: Border(top: BorderSide(color: theme.dividerColor, width: 1)), ), child: SafeArea( top: false, @@ -342,7 +359,9 @@ class _CoinScreenState extends ConsumerState { style: ElevatedButton.styleFrom( backgroundColor: theme.colorScheme.primary, foregroundColor: theme.colorScheme.onPrimary, - disabledBackgroundColor: theme.colorScheme.primary.withValues(alpha: 0.5), + disabledBackgroundColor: theme.colorScheme.primary.withValues( + alpha: 0.5, + ), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(14), ), diff --git a/lib/features/coin/playmate_coin.dart b/lib/features/coin/playmate_coin.dart index d6b0f9c..a16debb 100644 --- a/lib/features/coin/playmate_coin.dart +++ b/lib/features/coin/playmate_coin.dart @@ -40,7 +40,8 @@ class PlayMateCoin extends StatefulWidget { State createState() => _PlayMateCoinState(); } -class _PlayMateCoinState extends State with TickerProviderStateMixin { +class _PlayMateCoinState extends State + with TickerProviderStateMixin { late AnimationController _flipController; late AnimationController _idleController; late AnimationController _pressController; @@ -76,7 +77,8 @@ class _PlayMateCoinState extends State with TickerProviderStateMix ); // Only loop idle animation in production to prevent pumpAndSettle test timeouts - final isTesting = !kIsWeb && Platform.environment.containsKey('FLUTTER_TEST'); + final isTesting = + !kIsWeb && Platform.environment.containsKey('FLUTTER_TEST'); if (!isTesting) { _idleController.repeat(); } @@ -98,7 +100,9 @@ class _PlayMateCoinState extends State with TickerProviderStateMix void didUpdateWidget(covariant PlayMateCoin oldWidget) { super.didUpdateWidget(oldWidget); - if (widget.side != oldWidget.side && !widget.isFlipping && !_flipController.isAnimating) { + if (widget.side != oldWidget.side && + !widget.isFlipping && + !_flipController.isAnimating) { setState(() { _currentRx = CoinOrientation.getBaseAngleForSide(widget.side); _fromRx = _currentRx; @@ -106,7 +110,9 @@ class _PlayMateCoinState extends State with TickerProviderStateMix }); } - if (widget.isFlipping && !oldWidget.isFlipping && !_flipController.isAnimating) { + if (widget.isFlipping && + !oldWidget.isFlipping && + !_flipController.isAnimating) { _startFlipSequence(); } } @@ -173,7 +179,8 @@ class _PlayMateCoinState extends State with TickerProviderStateMix return -0.01 * CoinMotionConfig.anticipationCurve.transform(subT); } else { // Fast acceleration into smooth natural deceleration - final subT = (t - CoinMotionConfig.anticipationEnd) / + final subT = + (t - CoinMotionConfig.anticipationEnd) / (1.0 - CoinMotionConfig.anticipationEnd); return Curves.easeOutCubic.transform(subT.clamp(0.0, 1.0)); } @@ -221,7 +228,8 @@ class _PlayMateCoinState extends State with TickerProviderStateMix Widget build(BuildContext context) { final theme = Theme.of(context); final isDarkMode = theme.brightness == Brightness.dark; - final reducedMotion = MediaQuery.maybeOf(context)?.disableAnimations ?? false; + final reducedMotion = + MediaQuery.maybeOf(context)?.disableAnimations ?? false; return Semantics( label: widget.isFlipping @@ -234,7 +242,11 @@ class _PlayMateCoinState extends State with TickerProviderStateMix onTapUp: _onTapUp, onTapCancel: _onTapCancel, child: AnimatedBuilder( - animation: Listenable.merge([_flipController, _idleController, _pressController]), + animation: Listenable.merge([ + _flipController, + _idleController, + _pressController, + ]), builder: (context, _) { final double flipT = _flipController.value; final double pressT = _pressController.value; @@ -246,21 +258,31 @@ class _PlayMateCoinState extends State with TickerProviderStateMix final subT = flipT / CoinMotionConfig.anticipationEnd; scale = 1.0 - (subT * (1.0 - CoinMotionConfig.pressScale)); } else if (flipT < CoinMotionConfig.launchEnd) { - final subT = (flipT - CoinMotionConfig.anticipationEnd) / - (CoinMotionConfig.launchEnd - CoinMotionConfig.anticipationEnd); - scale = CoinMotionConfig.pressScale + - subT * (CoinMotionConfig.launchScale - CoinMotionConfig.pressScale); + final subT = + (flipT - CoinMotionConfig.anticipationEnd) / + (CoinMotionConfig.launchEnd - + CoinMotionConfig.anticipationEnd); + scale = + CoinMotionConfig.pressScale + + subT * + (CoinMotionConfig.launchScale - + CoinMotionConfig.pressScale); } else if (flipT < CoinMotionConfig.flipEnd) { - final subT = (flipT - CoinMotionConfig.launchEnd) / + final subT = + (flipT - CoinMotionConfig.launchEnd) / (CoinMotionConfig.flipEnd - CoinMotionConfig.launchEnd); - scale = CoinMotionConfig.launchScale - subT * (CoinMotionConfig.launchScale - 1.0); + scale = + CoinMotionConfig.launchScale - + subT * (CoinMotionConfig.launchScale - 1.0); } else if (flipT < CoinMotionConfig.landingEnd) { - final subT = (flipT - CoinMotionConfig.flipEnd) / + final subT = + (flipT - CoinMotionConfig.flipEnd) / (CoinMotionConfig.landingEnd - CoinMotionConfig.flipEnd); final bouncePhase = math.sin(subT * math.pi * 2); scale = 1.0 + (bouncePhase * 0.025); } else { - final subT = (flipT - CoinMotionConfig.landingEnd) / + final subT = + (flipT - CoinMotionConfig.landingEnd) / (CoinMotionConfig.settleEnd - CoinMotionConfig.landingEnd); final settlePhase = math.sin(subT * math.pi * 2); scale = 1.0 + (settlePhase * 0.008); @@ -271,26 +293,37 @@ class _PlayMateCoinState extends State with TickerProviderStateMix double translateY = pressT * CoinMotionConfig.pressTranslateY; if (!reducedMotion && _flipController.isAnimating) { if (flipT < CoinMotionConfig.anticipationEnd) { - translateY = CoinMotionConfig.pressTranslateY * (flipT / CoinMotionConfig.anticipationEnd); + translateY = + CoinMotionConfig.pressTranslateY * + (flipT / CoinMotionConfig.anticipationEnd); } else if (flipT < CoinMotionConfig.launchEnd) { - final subT = (flipT - CoinMotionConfig.anticipationEnd) / - (CoinMotionConfig.launchEnd - CoinMotionConfig.anticipationEnd); - translateY = CoinMotionConfig.pressTranslateY + + final subT = + (flipT - CoinMotionConfig.anticipationEnd) / + (CoinMotionConfig.launchEnd - + CoinMotionConfig.anticipationEnd); + translateY = + CoinMotionConfig.pressTranslateY + Curves.easeOutQuad.transform(subT) * - (CoinMotionConfig.launchPeakElevationY - CoinMotionConfig.pressTranslateY); + (CoinMotionConfig.launchPeakElevationY - + CoinMotionConfig.pressTranslateY); } else if (flipT < CoinMotionConfig.flipEnd) { - final subT = (flipT - CoinMotionConfig.launchEnd) / + final subT = + (flipT - CoinMotionConfig.launchEnd) / (CoinMotionConfig.flipEnd - CoinMotionConfig.launchEnd); - translateY = CoinMotionConfig.launchPeakElevationY * + translateY = + CoinMotionConfig.launchPeakElevationY * (1.0 - Curves.easeInQuad.transform(subT)); } else if (flipT < CoinMotionConfig.landingEnd) { - final subT = (flipT - CoinMotionConfig.flipEnd) / + final subT = + (flipT - CoinMotionConfig.flipEnd) / (CoinMotionConfig.landingEnd - CoinMotionConfig.flipEnd); translateY = -4.0 * math.sin(subT * math.pi); } else { translateY = 0.0; } - } else if (!reducedMotion && !_flipController.isAnimating && pressT == 0) { + } else if (!reducedMotion && + !_flipController.isAnimating && + pressT == 0) { // Idle subtle breathing drift (~1.5px) final idlePhase = math.sin(_idleController.value * math.pi * 2); translateY = -1.5 * idlePhase; @@ -304,27 +337,50 @@ class _PlayMateCoinState extends State with TickerProviderStateMix if (!reducedMotion && _flipController.isAnimating) { if (flipT < CoinMotionConfig.launchEnd) { - final subT = (flipT / CoinMotionConfig.launchEnd).clamp(0.0, 1.0); - shadowScale = CoinMotionConfig.shadowIdleScale + - subT * (CoinMotionConfig.shadowLaunchScale - CoinMotionConfig.shadowIdleScale); - shadowOpacity = shadowOpacity + - subT * (CoinMotionConfig.shadowLaunchOpacity - shadowOpacity); + final subT = (flipT / CoinMotionConfig.launchEnd).clamp( + 0.0, + 1.0, + ); + shadowScale = + CoinMotionConfig.shadowIdleScale + + subT * + (CoinMotionConfig.shadowLaunchScale - + CoinMotionConfig.shadowIdleScale); + shadowOpacity = + shadowOpacity + + subT * + (CoinMotionConfig.shadowLaunchOpacity - shadowOpacity); } else if (flipT < CoinMotionConfig.flipEnd) { - final subT = ((flipT - CoinMotionConfig.launchEnd) / - (CoinMotionConfig.flipEnd - CoinMotionConfig.launchEnd)) - .clamp(0.0, 1.0); - shadowScale = CoinMotionConfig.shadowLaunchScale + - subT * (CoinMotionConfig.shadowLandingScale - CoinMotionConfig.shadowLaunchScale); - shadowOpacity = CoinMotionConfig.shadowLaunchOpacity + - subT * (CoinMotionConfig.shadowLandingOpacity - CoinMotionConfig.shadowLaunchOpacity); + final subT = + ((flipT - CoinMotionConfig.launchEnd) / + (CoinMotionConfig.flipEnd - + CoinMotionConfig.launchEnd)) + .clamp(0.0, 1.0); + shadowScale = + CoinMotionConfig.shadowLaunchScale + + subT * + (CoinMotionConfig.shadowLandingScale - + CoinMotionConfig.shadowLaunchScale); + shadowOpacity = + CoinMotionConfig.shadowLaunchOpacity + + subT * + (CoinMotionConfig.shadowLandingOpacity - + CoinMotionConfig.shadowLaunchOpacity); } else { - final subT = ((flipT - CoinMotionConfig.flipEnd) / - (1.0 - CoinMotionConfig.flipEnd)) - .clamp(0.0, 1.0); - shadowScale = CoinMotionConfig.shadowLandingScale + - subT * (CoinMotionConfig.shadowIdleScale - CoinMotionConfig.shadowLandingScale); - shadowOpacity = CoinMotionConfig.shadowLandingOpacity + - subT * (CoinMotionConfig.shadowIdleOpacity - CoinMotionConfig.shadowLandingOpacity); + final subT = + ((flipT - CoinMotionConfig.flipEnd) / + (1.0 - CoinMotionConfig.flipEnd)) + .clamp(0.0, 1.0); + shadowScale = + CoinMotionConfig.shadowLandingScale + + subT * + (CoinMotionConfig.shadowIdleScale - + CoinMotionConfig.shadowLandingScale); + shadowOpacity = + CoinMotionConfig.shadowLandingOpacity + + subT * + (CoinMotionConfig.shadowIdleOpacity - + CoinMotionConfig.shadowLandingOpacity); } } @@ -333,10 +389,12 @@ class _PlayMateCoinState extends State with TickerProviderStateMix // Secondary rotations during tumbling final double secondaryY = _flipController.isAnimating - ? CoinOrientation.restingTiltY + math.sin(flipT * math.pi) * _secondaryDriftY + ? CoinOrientation.restingTiltY + + math.sin(flipT * math.pi) * _secondaryDriftY : CoinOrientation.restingTiltY; final double secondaryZ = _flipController.isAnimating - ? CoinOrientation.restingTiltZ + math.sin(flipT * math.pi * 2) * _secondaryWobbleZ + ? CoinOrientation.restingTiltZ + + math.sin(flipT * math.pi * 2) * _secondaryWobbleZ : CoinOrientation.restingTiltZ; return RepaintBoundary( @@ -359,7 +417,11 @@ class _PlayMateCoinState extends State with TickerProviderStateMix height: coinSize * 0.24, decoration: BoxDecoration( borderRadius: BorderRadius.all( - Radius.elliptical(coinSize * 0.42, coinSize * 0.12)), + Radius.elliptical( + coinSize * 0.42, + coinSize * 0.12, + ), + ), gradient: RadialGradient( colors: [ Colors.black.withValues(alpha: 0.65), @@ -416,8 +478,14 @@ class _PlayMateCoinState extends State with TickerProviderStateMix final bool isHeadsFacing = cosRx >= 0.0; // Directional lighting based on orientation relative to light (-0.35, -0.65, -0.67) - final double lightFront = (0.78 + (0.22 * math.max(0.0, cosRx))).clamp(0.0, 1.0); - final double lightBack = (0.78 + (0.22 * math.max(0.0, -cosRx))).clamp(0.0, 1.0); + final double lightFront = (0.78 + (0.22 * math.max(0.0, cosRx))).clamp( + 0.0, + 1.0, + ); + final double lightBack = (0.78 + (0.22 * math.max(0.0, -cosRx))).clamp( + 0.0, + 1.0, + ); // 3D rotation transform for the coin container final coinTransform = Matrix4.identity() @@ -428,7 +496,9 @@ class _PlayMateCoinState extends State with TickerProviderStateMix // Number of cylindrical edge slices const int edgeSliceCount = 8; - final edgeColor = isDarkMode ? const Color(0xFF1E1F23) : const Color(0xFF2B2C31); + final edgeColor = isDarkMode + ? const Color(0xFF1E1F23) + : const Color(0xFF2B2C31); // Edge slices ordered along Z from -halfThickness to +halfThickness final List children = []; @@ -476,8 +546,8 @@ class _PlayMateCoinState extends State with TickerProviderStateMix // Cylindrical edge slices along Z creating continuous solid cylindrical thickness for (int i = 0; i < edgeSliceCount; i++) { - final double zSlice = -halfThickness + - (thickness * (i + 0.5) / edgeSliceCount); + final double zSlice = + -halfThickness + (thickness * (i + 0.5) / edgeSliceCount); children.add( Transform( diff --git a/lib/features/cricket/cricket_provider.dart b/lib/features/cricket/cricket_provider.dart index dd086e7..ddcd55d 100644 --- a/lib/features/cricket/cricket_provider.dart +++ b/lib/features/cricket/cricket_provider.dart @@ -57,7 +57,9 @@ class CricketNotifier extends StateNotifier { maxOvers: overs, target: target, isInningsCompleted: false, - statusMessage: target == null ? '1st Innings: Batting' : '2nd Innings: Chasing $target', + statusMessage: target == null + ? '1st Innings: Batting' + : '2nd Innings: Chasing $target', ); AnalyticsService.trackCricketMatchCreated(); } @@ -66,7 +68,8 @@ class CricketNotifier extends StateNotifier { if (state == null || state!.isInningsCompleted) return; final newRuns = state!.runs + runsToAdd; - final newBalls = state!.balls + 1; // Standard delivery increments ball count + final newBalls = + state!.balls + 1; // Standard delivery increments ball count _checkMatchProgress(newRuns, state!.wickets, newBalls); } @@ -105,7 +108,8 @@ class CricketNotifier extends StateNotifier { status = 'Match Lost! Target not reached.'; _saveToHistory(runs, wickets, balls, false); } else { - status = 'Chasing ${state!.target!}: Need ${state!.target! - runs} runs from ${maxBalls - balls} balls'; + status = + 'Chasing ${state!.target!}: Need ${state!.target! - runs} runs from ${maxBalls - balls} balls'; } } else { // 1st innings logic @@ -113,7 +117,8 @@ class CricketNotifier extends StateNotifier { isCompleted = true; status = '1st Innings Over! Target: ${runs + 1}'; } else { - status = '1st Innings: Batting. Overs remaining: ${((maxBalls - balls) / 6).toStringAsFixed(1)}'; + status = + '1st Innings: Batting. Overs remaining: ${((maxBalls - balls) / 6).toStringAsFixed(1)}'; } } @@ -126,10 +131,16 @@ class CricketNotifier extends StateNotifier { ); } - Future _saveToHistory(int runs, int wickets, int balls, bool won) async { + Future _saveToHistory( + int runs, + int wickets, + int balls, + bool won, + ) async { final box = StorageService.getMatchBox(); - final List history = box.get('cricket_matches', defaultValue: []) as List; - + final List history = + box.get('cricket_matches', defaultValue: []) as List; + final match = { 'date': DateTime.now().toIso8601String(), 'type': 'Cricket Scorer', @@ -148,6 +159,7 @@ class CricketNotifier extends StateNotifier { } } -final cricketProvider = StateNotifierProvider((ref) { - return CricketNotifier(); -}); +final cricketProvider = + StateNotifierProvider((ref) { + return CricketNotifier(); + }); diff --git a/lib/features/cricket/cricket_screen.dart b/lib/features/cricket/cricket_screen.dart index e81d03c..5173e20 100644 --- a/lib/features/cricket/cricket_screen.dart +++ b/lib/features/cricket/cricket_screen.dart @@ -237,7 +237,8 @@ class _CricketScreenState extends ConsumerState { backgroundColor: theme.colorScheme.errorContainer, foregroundColor: theme.colorScheme.onErrorContainer, ), - onPressed: () => ref.read(cricketProvider.notifier).addWicket(), + onPressed: () => + ref.read(cricketProvider.notifier).addWicket(), icon: const Icon(Icons.outbox), label: const Text('WICKET'), ), diff --git a/lib/features/dice/dice_face.dart b/lib/features/dice/dice_face.dart index 3a16eb5..ebbb7b2 100644 --- a/lib/features/dice/dice_face.dart +++ b/lib/features/dice/dice_face.dart @@ -84,13 +84,17 @@ class DiceFace extends StatelessWidget { boxShadow: [ // Subtle inner face bevel and chamfer rim BoxShadow( - color: style.highlightColor.withValues(alpha: 0.35 * lightIntensity), + color: style.highlightColor.withValues( + alpha: 0.35 * lightIntensity, + ), offset: const Offset(-1.2, -1.2), blurRadius: 1.5, spreadRadius: 0.0, ), BoxShadow( - color: style.shadowEdgeColor.withValues(alpha: 0.25 * lightIntensity), + color: style.shadowEdgeColor.withValues( + alpha: 0.25 * lightIntensity, + ), offset: const Offset(1.5, 1.5), blurRadius: 2.0, spreadRadius: 0.0, diff --git a/lib/features/dice/dice_orientation.dart b/lib/features/dice/dice_orientation.dart index 8a49c6e..d9205f3 100644 --- a/lib/features/dice/dice_orientation.dart +++ b/lib/features/dice/dice_orientation.dart @@ -69,8 +69,11 @@ class DiceFaceOrientation { static const DiceVec3 restingTilt = DiceVec3(-0.24, 0.28, 0.0); /// Normalized ambient light vector coming from the top-left-front. - static final DiceVec3 lightDirection = - const DiceVec3(-0.35, -0.65, -0.67).normalized(); + static final DiceVec3 lightDirection = const DiceVec3( + -0.35, + -0.65, + -0.67, + ).normalized(); /// Canonical 6-face definitions on a unit cube with half-extent 1.0. /// Opposite faces sum to 7: @@ -225,12 +228,14 @@ class DiceFaceOrientation { fullMatrix.multiply(rotMatrix); fullMatrix.multiply(localMatrix); - visible.add(VisibleDiceFace( - value: face.value, - depthZ: worldCenterZ, - lightIntensity: lightIntensity, - transform: fullMatrix, - )); + visible.add( + VisibleDiceFace( + value: face.value, + depthZ: worldCenterZ, + lightIntensity: lightIntensity, + transform: fullMatrix, + ), + ); } // Sort by depth for painter's algorithm: diff --git a/lib/features/dice/dice_pips.dart b/lib/features/dice/dice_pips.dart index e8995fd..059a84f 100644 --- a/lib/features/dice/dice_pips.dart +++ b/lib/features/dice/dice_pips.dart @@ -102,14 +102,23 @@ class _DicePipsPainter extends CustomPainter { } } - void _drawRecessedPip(Canvas canvas, Offset center, double radius, bool isOnePip) { + void _drawRecessedPip( + Canvas canvas, + Offset center, + double radius, + bool isOnePip, + ) { // 1. Recessed inner shadow (top-left rim) final innerShadowPaint = Paint() ..color = isDarkMode ? Colors.black.withValues(alpha: 0.6) : Colors.black.withValues(alpha: 0.25) ..style = PaintingStyle.fill; - canvas.drawCircle(center + const Offset(0.4, 0.6), radius + 0.5, innerShadowPaint); + canvas.drawCircle( + center + const Offset(0.4, 0.6), + radius + 0.5, + innerShadowPaint, + ); // 2. Subtle light reflection on bottom-right rim final rimHighlightPaint = Paint() @@ -125,14 +134,8 @@ class _DicePipsPainter extends CustomPainter { center: const Alignment(-0.25, -0.25), radius: 0.9, colors: isDarkMode - ? [ - pipColor, - pipColor.withValues(alpha: 0.88), - ] - : [ - pipColor.withValues(alpha: 0.92), - pipColor, - ], + ? [pipColor, pipColor.withValues(alpha: 0.88)] + : [pipColor.withValues(alpha: 0.92), pipColor], ); final pipPaint = Paint() diff --git a/lib/features/dice/dice_provider.dart b/lib/features/dice/dice_provider.dart index 4cabb4b..b646ecf 100644 --- a/lib/features/dice/dice_provider.dart +++ b/lib/features/dice/dice_provider.dart @@ -9,13 +9,15 @@ class DiceNotifier extends StateNotifier { final Random _random = Random(); DiceNotifier() - : super(DiceRollState( + : super( + DiceRollState( currentRolls: [6], diceType: DiceType.d6, diceCount: 1, isRolling: false, rollHistory: [], - )) { + ), + ) { _loadHistory(); } @@ -70,30 +72,26 @@ class DiceNotifier extends StateNotifier { ); // 2. Publish target result immediately so visual renderer computes target orientation - state = state.copyWith( - currentRolls: finalRolls, - isRolling: true, - ); + state = state.copyWith(currentRolls: finalRolls, isRolling: true); // 3. Await duration matching physical 3D animation timeline await Future.delayed(DiceMotionConfig.rollDuration); // 4. Update history upon settling - final updatedHistory = List>.from(state.rollHistory)..insert(0, finalRolls); + final updatedHistory = List>.from(state.rollHistory) + ..insert(0, finalRolls); if (updatedHistory.length > 50) { updatedHistory.removeLast(); } - state = state.copyWith( - isRolling: false, - rollHistory: updatedHistory, - ); + state = state.copyWith(isRolling: false, rollHistory: updatedHistory); // Persist history & statistics if (StorageService.isBoxOpen(StorageService.statsBoxName)) { final box = StorageService.getStatsBox(); await box.put('dice_history', updatedHistory); - final int totalRolls = box.get('total_dice_rolls', defaultValue: 0) as int; + final int totalRolls = + box.get('total_dice_rolls', defaultValue: 0) as int; await box.put('total_dice_rolls', totalRolls + state.diceCount); } diff --git a/lib/features/dice/dice_screen.dart b/lib/features/dice/dice_screen.dart index fdd08ec..b79bcf4 100644 --- a/lib/features/dice/dice_screen.dart +++ b/lib/features/dice/dice_screen.dart @@ -33,7 +33,8 @@ class _DiceScreenState extends ConsumerState { event.x * event.x + event.y * event.y + event.z * event.z; if (acceleration > 190) { final now = DateTime.now(); - if (now.difference(_lastShakeTime) > const Duration(milliseconds: 1100)) { + if (now.difference(_lastShakeTime) > + const Duration(milliseconds: 1100)) { _lastShakeTime = now; _triggerRoll(); } @@ -232,11 +233,7 @@ class _DiceScreenState extends ConsumerState { Row( mainAxisAlignment: MainAxisAlignment.center, children: [ - Icon( - Icons.history, - size: 15, - color: theme.colorScheme.secondary, - ), + Icon(Icons.history, size: 15, color: theme.colorScheme.secondary), const SizedBox(width: 6), Text( 'Recent Rolls', @@ -260,21 +257,32 @@ class _DiceScreenState extends ConsumerState { final sum = roll.fold(0, (prev, element) => prev + element); final isLatest = index == 0; - final label = roll.length == 1 ? '$sum' : '$sum (${roll.join('+')})'; + final label = roll.length == 1 + ? '$sum' + : '$sum (${roll.join('+')})'; return Padding( padding: const EdgeInsets.only(right: 6.0), child: Container( - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), + padding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 5, + ), decoration: BoxDecoration( color: isLatest - ? (isDarkMode ? const Color(0xFF2C2C2E) : const Color(0xFFEBEBEB)) - : (isDarkMode ? const Color(0xFF1E1E1E) : const Color(0xFFF5F5F5)), + ? (isDarkMode + ? const Color(0xFF2C2C2E) + : const Color(0xFFEBEBEB)) + : (isDarkMode + ? const Color(0xFF1E1E1E) + : const Color(0xFFF5F5F5)), borderRadius: BorderRadius.circular(10), border: Border.all( color: isLatest ? const Color(0xFFC18A42).withValues(alpha: 0.4) - : (isDarkMode ? const Color(0xFF2C2C2C) : const Color(0xFFE0E0E0)), + : (isDarkMode + ? const Color(0xFF2C2C2C) + : const Color(0xFFE0E0E0)), width: 1.0, ), ), @@ -284,7 +292,9 @@ class _DiceScreenState extends ConsumerState { fontSize: 12, fontWeight: isLatest ? FontWeight.bold : FontWeight.w500, color: isLatest - ? (isDarkMode ? Colors.white : const Color(0xFF1A1A1A)) + ? (isDarkMode + ? Colors.white + : const Color(0xFF1A1A1A)) : theme.colorScheme.secondary, ), ), @@ -302,9 +312,7 @@ class _DiceScreenState extends ConsumerState { padding: const EdgeInsets.all(AppSpacing.m), decoration: BoxDecoration( color: theme.colorScheme.surface, - border: Border( - top: BorderSide(color: theme.dividerColor, width: 1), - ), + border: Border(top: BorderSide(color: theme.dividerColor, width: 1)), ), child: Column( mainAxisSize: MainAxisSize.min, @@ -333,11 +341,17 @@ class _DiceScreenState extends ConsumerState { children: [ IconButton( icon: const Icon(Icons.remove, size: 18), - constraints: const BoxConstraints(minWidth: 32, minHeight: 32), + constraints: const BoxConstraints( + minWidth: 32, + minHeight: 32, + ), padding: EdgeInsets.zero, visualDensity: VisualDensity.compact, - onPressed: (!diceState.isRolling && diceState.diceCount > 1) - ? () => ref.read(diceProvider.notifier).setDiceCount(diceState.diceCount - 1) + onPressed: + (!diceState.isRolling && diceState.diceCount > 1) + ? () => ref + .read(diceProvider.notifier) + .setDiceCount(diceState.diceCount - 1) : null, ), Padding( @@ -351,11 +365,17 @@ class _DiceScreenState extends ConsumerState { ), IconButton( icon: const Icon(Icons.add, size: 18), - constraints: const BoxConstraints(minWidth: 32, minHeight: 32), + constraints: const BoxConstraints( + minWidth: 32, + minHeight: 32, + ), padding: EdgeInsets.zero, visualDensity: VisualDensity.compact, - onPressed: (!diceState.isRolling && diceState.diceCount < 6) - ? () => ref.read(diceProvider.notifier).setDiceCount(diceState.diceCount + 1) + onPressed: + (!diceState.isRolling && diceState.diceCount < 6) + ? () => ref + .read(diceProvider.notifier) + .setDiceCount(diceState.diceCount + 1) : null, ), ], @@ -401,7 +421,9 @@ class _DiceScreenState extends ConsumerState { style: ElevatedButton.styleFrom( backgroundColor: theme.colorScheme.primary, foregroundColor: theme.colorScheme.onPrimary, - disabledBackgroundColor: theme.colorScheme.primary.withValues(alpha: 0.5), + disabledBackgroundColor: theme.colorScheme.primary.withValues( + alpha: 0.5, + ), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(14), ), diff --git a/lib/features/dice/dice_state.dart b/lib/features/dice/dice_state.dart index 78b1d11..3a3ad36 100644 --- a/lib/features/dice/dice_state.dart +++ b/lib/features/dice/dice_state.dart @@ -1,4 +1,3 @@ - enum DiceType { d4(4), d6(6), diff --git a/lib/features/dice/playmate_dice.dart b/lib/features/dice/playmate_dice.dart index cf22fc5..bb361be 100644 --- a/lib/features/dice/playmate_dice.dart +++ b/lib/features/dice/playmate_dice.dart @@ -49,7 +49,8 @@ class PlayMateDice extends StatefulWidget { State createState() => _PlayMateDiceState(); } -class _PlayMateDiceState extends State with TickerProviderStateMixin { +class _PlayMateDiceState extends State + with TickerProviderStateMixin { late AnimationController _rollController; late AnimationController _idleController; late AnimationController _pressController; @@ -66,7 +67,9 @@ class _PlayMateDiceState extends State with TickerProviderStateMix @override void initState() { super.initState(); - _currentRotation = DiceFaceOrientation.getRestingEulerForValue(widget.value); + _currentRotation = DiceFaceOrientation.getRestingEulerForValue( + widget.value, + ); _fromRotation = _currentRotation; _targetRotation = _currentRotation; @@ -80,7 +83,8 @@ class _PlayMateDiceState extends State with TickerProviderStateMix duration: DiceMotionConfig.idleCycleDuration, ); // Do not continuously loop idle animation in tests to prevent pumpAndSettle timeout - final isTesting = !kIsWeb && Platform.environment.containsKey('FLUTTER_TEST'); + final isTesting = + !kIsWeb && Platform.environment.containsKey('FLUTTER_TEST'); if (!isTesting) { _idleController.repeat(); } @@ -102,15 +106,21 @@ class _PlayMateDiceState extends State with TickerProviderStateMix void didUpdateWidget(covariant PlayMateDice oldWidget) { super.didUpdateWidget(oldWidget); - if (widget.value != oldWidget.value && !widget.isRolling && !_rollController.isAnimating) { + if (widget.value != oldWidget.value && + !widget.isRolling && + !_rollController.isAnimating) { setState(() { - _currentRotation = DiceFaceOrientation.getRestingEulerForValue(widget.value); + _currentRotation = DiceFaceOrientation.getRestingEulerForValue( + widget.value, + ); _fromRotation = _currentRotation; _targetRotation = _currentRotation; }); } - if (widget.isRolling && !oldWidget.isRolling && !_rollController.isAnimating) { + if (widget.isRolling && + !oldWidget.isRolling && + !_rollController.isAnimating) { _startRollSequence(); } } @@ -118,7 +128,9 @@ class _PlayMateDiceState extends State with TickerProviderStateMix void _startRollSequence() { _fromRotation = _currentRotation; - final baseTarget = DiceFaceOrientation.getRestingEulerForValue(widget.value); + final baseTarget = DiceFaceOrientation.getRestingEulerForValue( + widget.value, + ); final int revCountX = 2 + (widget.diceIndex % 2); final int revCountY = 3 + ((widget.diceIndex + 1) % 2); @@ -190,7 +202,8 @@ class _PlayMateDiceState extends State with TickerProviderStateMix final subT = t / DiceMotionConfig.anticipationEnd; return -0.015 * DiceMotionConfig.anticipationCurve.transform(subT); } else { - final subT = (t - DiceMotionConfig.anticipationEnd) / + final subT = + (t - DiceMotionConfig.anticipationEnd) / (1.0 - DiceMotionConfig.anticipationEnd); return Curves.easeOutCubic.transform(subT.clamp(0.0, 1.0)); } @@ -198,7 +211,9 @@ class _PlayMateDiceState extends State with TickerProviderStateMix void _handleRollStatus(AnimationStatus status) { if (status == AnimationStatus.completed) { - final baseTarget = DiceFaceOrientation.getRestingEulerForValue(widget.value); + final baseTarget = DiceFaceOrientation.getRestingEulerForValue( + widget.value, + ); setState(() { _currentRotation = baseTarget; _fromRotation = baseTarget; @@ -237,8 +252,10 @@ class _PlayMateDiceState extends State with TickerProviderStateMix Widget build(BuildContext context) { final theme = Theme.of(context); final isDarkMode = theme.brightness == Brightness.dark; - final effectiveStyle = widget.style ?? DiceStyle.fromBrightness(theme.brightness); - final reducedMotion = MediaQuery.maybeOf(context)?.disableAnimations ?? false; + final effectiveStyle = + widget.style ?? DiceStyle.fromBrightness(theme.brightness); + final reducedMotion = + MediaQuery.maybeOf(context)?.disableAnimations ?? false; return Semantics( label: widget.isRolling @@ -251,7 +268,11 @@ class _PlayMateDiceState extends State with TickerProviderStateMix onTapUp: _onTapUp, onTapCancel: _onTapCancel, child: AnimatedBuilder( - animation: Listenable.merge([_rollController, _idleController, _pressController]), + animation: Listenable.merge([ + _rollController, + _idleController, + _pressController, + ]), builder: (context, _) { final double rollT = _rollController.value; final double pressT = _pressController.value; @@ -263,20 +284,29 @@ class _PlayMateDiceState extends State with TickerProviderStateMix final subT = rollT / DiceMotionConfig.anticipationEnd; scale = _lerpDouble(1.0, DiceMotionConfig.pressScale, subT); } else if (rollT < DiceMotionConfig.launchEnd) { - final subT = (rollT - DiceMotionConfig.anticipationEnd) / - (DiceMotionConfig.launchEnd - DiceMotionConfig.anticipationEnd); - scale = _lerpDouble(DiceMotionConfig.pressScale, DiceMotionConfig.launchScale, subT); + final subT = + (rollT - DiceMotionConfig.anticipationEnd) / + (DiceMotionConfig.launchEnd - + DiceMotionConfig.anticipationEnd); + scale = _lerpDouble( + DiceMotionConfig.pressScale, + DiceMotionConfig.launchScale, + subT, + ); } else if (rollT < DiceMotionConfig.tumbleEnd) { - final subT = (rollT - DiceMotionConfig.launchEnd) / + final subT = + (rollT - DiceMotionConfig.launchEnd) / (DiceMotionConfig.tumbleEnd - DiceMotionConfig.launchEnd); scale = _lerpDouble(DiceMotionConfig.launchScale, 1.0, subT); } else if (rollT < DiceMotionConfig.landingEnd) { - final subT = (rollT - DiceMotionConfig.tumbleEnd) / + final subT = + (rollT - DiceMotionConfig.tumbleEnd) / (DiceMotionConfig.landingEnd - DiceMotionConfig.tumbleEnd); final bouncePhase = math.sin(subT * math.pi * 2); scale = 1.0 + (bouncePhase * 0.035); } else { - final subT = (rollT - DiceMotionConfig.landingEnd) / + final subT = + (rollT - DiceMotionConfig.landingEnd) / (DiceMotionConfig.settleEnd - DiceMotionConfig.landingEnd); final settlePhase = math.sin(subT * math.pi * 2); scale = 1.0 + (settlePhase * 0.012); @@ -287,17 +317,22 @@ class _PlayMateDiceState extends State with TickerProviderStateMix double translateY = pressT * DiceMotionConfig.pressTranslateY; if (!reducedMotion && _rollController.isAnimating) { if (rollT < DiceMotionConfig.anticipationEnd) { - translateY = DiceMotionConfig.pressTranslateY * (rollT / DiceMotionConfig.anticipationEnd); + translateY = + DiceMotionConfig.pressTranslateY * + (rollT / DiceMotionConfig.anticipationEnd); } else if (rollT < DiceMotionConfig.launchEnd) { - final subT = (rollT - DiceMotionConfig.anticipationEnd) / - (DiceMotionConfig.launchEnd - DiceMotionConfig.anticipationEnd); + final subT = + (rollT - DiceMotionConfig.anticipationEnd) / + (DiceMotionConfig.launchEnd - + DiceMotionConfig.anticipationEnd); translateY = _lerpDouble( DiceMotionConfig.pressTranslateY, DiceMotionConfig.launchPeakElevationY, Curves.easeOutQuad.transform(subT), ); } else if (rollT < DiceMotionConfig.tumbleEnd) { - final subT = (rollT - DiceMotionConfig.launchEnd) / + final subT = + (rollT - DiceMotionConfig.launchEnd) / (DiceMotionConfig.tumbleEnd - DiceMotionConfig.launchEnd); translateY = _lerpDouble( DiceMotionConfig.launchPeakElevationY, @@ -305,13 +340,16 @@ class _PlayMateDiceState extends State with TickerProviderStateMix Curves.easeInQuad.transform(subT), ); } else if (rollT < DiceMotionConfig.landingEnd) { - final subT = (rollT - DiceMotionConfig.tumbleEnd) / + final subT = + (rollT - DiceMotionConfig.tumbleEnd) / (DiceMotionConfig.landingEnd - DiceMotionConfig.tumbleEnd); translateY = -5.0 * math.sin(subT * math.pi); } else { translateY = 0.0; } - } else if (!reducedMotion && !_rollController.isAnimating && pressT == 0) { + } else if (!reducedMotion && + !_rollController.isAnimating && + pressT == 0) { final idlePhase = math.sin(_idleController.value * math.pi * 2); translateY = -1.8 * idlePhase; } @@ -324,21 +362,51 @@ class _PlayMateDiceState extends State with TickerProviderStateMix if (!reducedMotion && _rollController.isAnimating) { if (rollT < DiceMotionConfig.launchEnd) { - final subT = (rollT / DiceMotionConfig.launchEnd).clamp(0.0, 1.0); - shadowScale = _lerpDouble(DiceMotionConfig.shadowIdleScale, DiceMotionConfig.shadowLaunchScale, subT); - shadowOpacity = _lerpDouble(shadowOpacity, DiceMotionConfig.shadowLaunchOpacity, subT); + final subT = (rollT / DiceMotionConfig.launchEnd).clamp( + 0.0, + 1.0, + ); + shadowScale = _lerpDouble( + DiceMotionConfig.shadowIdleScale, + DiceMotionConfig.shadowLaunchScale, + subT, + ); + shadowOpacity = _lerpDouble( + shadowOpacity, + DiceMotionConfig.shadowLaunchOpacity, + subT, + ); } else if (rollT < DiceMotionConfig.tumbleEnd) { - final subT = ((rollT - DiceMotionConfig.launchEnd) / - (DiceMotionConfig.tumbleEnd - DiceMotionConfig.launchEnd)) - .clamp(0.0, 1.0); - shadowScale = _lerpDouble(DiceMotionConfig.shadowLaunchScale, DiceMotionConfig.shadowLandingScale, subT); - shadowOpacity = _lerpDouble(DiceMotionConfig.shadowLaunchOpacity, DiceMotionConfig.shadowLandingOpacity, subT); + final subT = + ((rollT - DiceMotionConfig.launchEnd) / + (DiceMotionConfig.tumbleEnd - + DiceMotionConfig.launchEnd)) + .clamp(0.0, 1.0); + shadowScale = _lerpDouble( + DiceMotionConfig.shadowLaunchScale, + DiceMotionConfig.shadowLandingScale, + subT, + ); + shadowOpacity = _lerpDouble( + DiceMotionConfig.shadowLaunchOpacity, + DiceMotionConfig.shadowLandingOpacity, + subT, + ); } else { - final subT = ((rollT - DiceMotionConfig.tumbleEnd) / - (1.0 - DiceMotionConfig.tumbleEnd)) - .clamp(0.0, 1.0); - shadowScale = _lerpDouble(DiceMotionConfig.shadowLandingScale, DiceMotionConfig.shadowIdleScale, subT); - shadowOpacity = _lerpDouble(DiceMotionConfig.shadowLandingOpacity, DiceMotionConfig.shadowIdleOpacity, subT); + final subT = + ((rollT - DiceMotionConfig.tumbleEnd) / + (1.0 - DiceMotionConfig.tumbleEnd)) + .clamp(0.0, 1.0); + shadowScale = _lerpDouble( + DiceMotionConfig.shadowLandingScale, + DiceMotionConfig.shadowIdleScale, + subT, + ); + shadowOpacity = _lerpDouble( + DiceMotionConfig.shadowLandingOpacity, + DiceMotionConfig.shadowIdleOpacity, + subT, + ); } } @@ -365,7 +433,11 @@ class _PlayMateDiceState extends State with TickerProviderStateMix height: dieSize * 0.28, decoration: BoxDecoration( borderRadius: BorderRadius.all( - Radius.elliptical(dieSize * 0.44, dieSize * 0.14)), + Radius.elliptical( + dieSize * 0.44, + dieSize * 0.14, + ), + ), gradient: RadialGradient( colors: [ Colors.black.withValues(alpha: 0.65), @@ -386,8 +458,17 @@ class _PlayMateDiceState extends State with TickerProviderStateMix child: Transform.scale( scale: scale, child: widget.diceType == DiceType.d6 - ? _build3DCube(dieSize, halfExtent, effectiveStyle, isDarkMode) - : _buildPolyhedralDie(dieSize, effectiveStyle, isDarkMode), + ? _build3DCube( + dieSize, + halfExtent, + effectiveStyle, + isDarkMode, + ) + : _buildPolyhedralDie( + dieSize, + effectiveStyle, + isDarkMode, + ), ), ), ], @@ -435,11 +516,7 @@ class _PlayMateDiceState extends State with TickerProviderStateMix ); } - Widget _buildPolyhedralDie( - double dieSize, - DiceStyle style, - bool isDarkMode, - ) { + Widget _buildPolyhedralDie(double dieSize, DiceStyle style, bool isDarkMode) { final double radius = dieSize * 0.22; return Container( width: dieSize, diff --git a/lib/features/home/home_screen.dart b/lib/features/home/home_screen.dart index 738c97f..96b8fa0 100644 --- a/lib/features/home/home_screen.dart +++ b/lib/features/home/home_screen.dart @@ -127,7 +127,9 @@ class _HomeScreenState extends State { ), ]; - final favoriteTools = allTools.where((t) => _favoriteToolIds.contains(t.id)).toList(); + final favoriteTools = allTools + .where((t) => _favoriteToolIds.contains(t.id)) + .toList(); return Scaffold( appBar: AppBar( @@ -148,10 +150,7 @@ class _HomeScreenState extends State { const SizedBox(width: AppSpacing.s), const Text( 'PLAYMATE', - style: TextStyle( - fontWeight: FontWeight.w900, - letterSpacing: 0.5, - ), + style: TextStyle(fontWeight: FontWeight.w900, letterSpacing: 0.5), ), ], ), @@ -204,10 +203,16 @@ class _HomeScreenState extends State { child: ListView.separated( scrollDirection: Axis.horizontal, itemCount: favoriteTools.length, - separatorBuilder: (_, _) => const SizedBox(width: AppSpacing.s), + separatorBuilder: (_, _) => + const SizedBox(width: AppSpacing.s), itemBuilder: (context, index) { final tool = favoriteTools[index]; - return _buildQuickAccessChip(context, tool, theme, isDark); + return _buildQuickAccessChip( + context, + tool, + theme, + isDark, + ); }, ), ), @@ -250,7 +255,13 @@ class _HomeScreenState extends State { itemBuilder: (context, index) { final tool = allTools[index]; final isFavorite = _favoriteToolIds.contains(tool.id); - return _buildToolCard(context, tool, isFavorite, theme, isDark); + return _buildToolCard( + context, + tool, + isFavorite, + theme, + isDark, + ); }, ), const SizedBox(height: AppSpacing.xl), @@ -262,7 +273,11 @@ class _HomeScreenState extends State { ); } - Widget _buildQuickPlayBar(BuildContext context, ThemeData theme, bool isDark) { + Widget _buildQuickPlayBar( + BuildContext context, + ThemeData theme, + bool isDark, + ) { return Container( padding: const EdgeInsets.all(AppSpacing.m), decoration: BoxDecoration( @@ -277,11 +292,7 @@ class _HomeScreenState extends State { children: [ Row( children: [ - Icon( - Icons.bolt, - size: 18, - color: theme.colorScheme.primary, - ), + Icon(Icons.bolt, size: 18, color: theme.colorScheme.primary), const SizedBox(width: AppSpacing.xs), Text( 'QUICK START', @@ -368,11 +379,7 @@ class _HomeScreenState extends State { children: [ Row( children: [ - Icon( - tool.icon, - size: 22, - color: theme.colorScheme.primary, - ), + Icon(tool.icon, size: 22, color: theme.colorScheme.primary), const Spacer(), Icon( Icons.arrow_forward_ios, @@ -443,9 +450,13 @@ class _HomeScreenState extends State { constraints: const BoxConstraints(), icon: Icon( isFavorite ? Icons.star : Icons.star_border, - color: isFavorite ? Colors.amber[700] : theme.colorScheme.secondary, + color: isFavorite + ? Colors.amber[700] + : theme.colorScheme.secondary, ), - tooltip: isFavorite ? 'Unpin from quick access' : 'Pin to quick access', + tooltip: isFavorite + ? 'Unpin from quick access' + : 'Pin to quick access', onPressed: () => _toggleFavorite(tool.id), ), ], @@ -463,7 +474,9 @@ class _HomeScreenState extends State { Text( tool.desc, style: theme.textTheme.bodySmall?.copyWith( - color: isDark ? const Color(0xFFA0A0A0) : const Color(0xFF666666), + color: isDark + ? const Color(0xFFA0A0A0) + : const Color(0xFF666666), height: 1.3, ), maxLines: 2, diff --git a/lib/features/onboarding/onboarding_screen.dart b/lib/features/onboarding/onboarding_screen.dart new file mode 100644 index 0000000..07fa04c --- /dev/null +++ b/lib/features/onboarding/onboarding_screen.dart @@ -0,0 +1,328 @@ +import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; +import '../../services/storage_service.dart'; +import '../../shared/responsive_layout.dart'; +import 'widgets/dice_onboarding_visual.dart'; +import 'widgets/essentials_onboarding_visual.dart'; +import 'widgets/onboarding_page.dart'; +import 'widgets/onboarding_page_indicator.dart'; +import 'widgets/welcome_onboarding_visual.dart'; + +/// Production-ready, premium first-time onboarding experience for PlayMate. +/// +/// Features: +/// - Three distinct, carefully calibrated introduction pages +/// - Native tactile Flutter animations (floating dice, essentials cluster, welcome composition) +/// - Rapid-tap prevention and graceful lifecycle handling +/// - Persistent local completion state via [StorageService] +/// - Full accessibility semantics and reduced-motion support +/// - Zero-overflow responsive layout across 320px–1024px screens +class OnboardingScreen extends StatefulWidget { + final VoidCallback? onFinish; + + const OnboardingScreen({super.key, this.onFinish}); + + @override + State createState() => _OnboardingScreenState(); +} + +class _OnboardingScreenState extends State { + final PageController _pageController = PageController(); + int _currentPage = 0; + bool _isNavigating = false; + + @override + void dispose() { + _pageController.dispose(); + super.dispose(); + } + + void _onPageChanged(int index) { + setState(() { + _currentPage = index; + }); + } + + void _nextPage() { + if (_isNavigating) return; + if (_currentPage < 2) { + _pageController.nextPage( + duration: const Duration(milliseconds: 350), + curve: Curves.easeOutCubic, + ); + } + } + + void _previousPage() { + if (_isNavigating) return; + if (_currentPage > 0) { + _pageController.previousPage( + duration: const Duration(milliseconds: 350), + curve: Curves.easeOutCubic, + ); + } else { + // If replaying from settings on page 0, allow popping back + if (context.canPop()) { + context.pop(); + } + } + } + + Future _completeOnboarding() async { + if (_isNavigating) return; + _isNavigating = true; + + try { + await StorageService.setCompletedOnboarding(true); + } catch (_) { + // Storage error safeguard + } + + if (widget.onFinish != null) { + widget.onFinish!(); + return; + } + + if (mounted) { + if (Navigator.of(context).canPop()) { + Navigator.of(context).pop(); + } else { + try { + context.go('/'); + } catch (_) { + // Fallback when standalone without GoRouter + } + } + } + } + + Future _skipOnboarding() async { + await _completeOnboarding(); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final size = MediaQuery.of(context).size; + final isCompact = size.height < 680; + + return Scaffold( + backgroundColor: theme.scaffoldBackgroundColor, + body: SafeArea( + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 560), + child: Column( + children: [ + // Top Navigation Bar + Padding( + padding: EdgeInsets.symmetric( + horizontal: AppSpacing.m, + vertical: isCompact ? AppSpacing.xs : AppSpacing.s, + ), + child: SizedBox( + height: 48, + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + // Left: Back button or discrete brand marker + _currentPage > 0 + ? TextButton.icon( + onPressed: _previousPage, + icon: const Icon(Icons.arrow_back, size: 18), + label: const Text('Back'), + style: TextButton.styleFrom( + foregroundColor: theme.colorScheme.secondary, + ), + ) + : Container( + padding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 4, + ), + decoration: BoxDecoration( + color: theme.colorScheme.primary.withValues( + alpha: 0.08, + ), + borderRadius: BorderRadius.circular(8), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.sports_esports, + size: 16, + color: theme.colorScheme.primary, + ), + const SizedBox(width: 6), + Text( + 'PLAYMATE', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w900, + letterSpacing: 0.8, + color: theme.colorScheme.primary, + ), + ), + ], + ), + ), + + // Right: Skip button (visible on pages 0 and 1) + if (_currentPage < 2) + Semantics( + button: true, + label: 'Skip onboarding', + child: TextButton( + onPressed: _isNavigating ? null : _skipOnboarding, + style: TextButton.styleFrom( + foregroundColor: theme.colorScheme.secondary, + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.m, + vertical: AppSpacing.s, + ), + ), + child: const Text( + 'Skip', + style: TextStyle( + fontWeight: FontWeight.w600, + fontSize: 14, + ), + ), + ), + ) + else + const SizedBox(width: 48), + ], + ), + ), + ), + + // Main PageView Content + Expanded( + child: PageView( + controller: _pageController, + onPageChanged: _onPageChanged, + children: const [ + // Screen 01: Introduction + OnboardingPage( + headline: 'Make every moment a game.', + supportingText: + 'From spontaneous decisions to unforgettable game nights, everything you need to play is right here.', + visual: DiceOnboardingVisual(), + ), + + // Screen 02: Features + OnboardingPage( + headline: 'All your game-night essentials.', + supportingText: + 'Roll, flip, spin, keep score, build teams, and manage every moment without switching between apps.', + visual: EssentialsOnboardingVisual(), + ), + + // Screen 03: Final Welcome + OnboardingPage( + headline: 'Less setup. More playing.', + supportingText: + 'Your next game night starts here. Pick a tool, bring everyone together, and let the fun begin.', + visual: WelcomeOnboardingVisual(), + ), + ], + ), + ), + + // Bottom Controls & Page Indicator + Padding( + padding: EdgeInsets.only( + left: AppSpacing.l, + right: AppSpacing.l, + top: AppSpacing.s, + bottom: isCompact ? AppSpacing.s : AppSpacing.m, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + // Page Indicators + OnboardingPageIndicator( + currentPage: _currentPage, + pageCount: 3, + onDotTapped: (index) { + _pageController.animateToPage( + index, + duration: const Duration(milliseconds: 350), + curve: Curves.easeOutCubic, + ); + }, + ), + + SizedBox(height: isCompact ? AppSpacing.s : AppSpacing.m), + + // Navigation Action Button + if (_currentPage < 2) + SizedBox( + width: double.infinity, + height: 52, + child: FilledButton( + style: FilledButton.styleFrom( + backgroundColor: theme.colorScheme.primary, + foregroundColor: theme.colorScheme.onPrimary, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(14), + ), + elevation: 0, + ), + onPressed: _nextPage, + child: const Text( + 'Continue', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + letterSpacing: 0.2, + ), + ), + ), + ) + else + SizedBox( + width: double.infinity, + height: 52, + child: FilledButton( + style: FilledButton.styleFrom( + backgroundColor: theme.colorScheme.primary, + foregroundColor: theme.colorScheme.onPrimary, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(14), + ), + elevation: 0, + ), + onPressed: _isNavigating + ? null + : _completeOnboarding, + child: const Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + "Let's Play", + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + letterSpacing: 0.2, + ), + ), + SizedBox(width: 8), + Icon(Icons.arrow_forward, size: 18), + ], + ), + ), + ), + ], + ), + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/features/onboarding/widgets/dice_onboarding_visual.dart b/lib/features/onboarding/widgets/dice_onboarding_visual.dart new file mode 100644 index 0000000..ad3d26c --- /dev/null +++ b/lib/features/onboarding/widgets/dice_onboarding_visual.dart @@ -0,0 +1,176 @@ +import 'dart:io' show Platform; +import 'dart:math' as math; +import 'package:flutter/foundation.dart' show kIsWeb; +import 'package:flutter/material.dart'; +import '../../dice/dice_face.dart'; + +/// Screen 1 custom dice illustration. +/// +/// Features: +/// - Reuses PlayMate's authentic dice face rendering (chamfer, realistic pips, embossed shadows) +/// - Paired physical dice composition (primary die + companion accent die) +/// - Subtle, organic floating levitation with dynamic contact shadow +/// - Full reduced-motion awareness and lifecycle disposal +class DiceOnboardingVisual extends StatefulWidget { + final double size; + + const DiceOnboardingVisual({super.key, this.size = 220.0}); + + @override + State createState() => _DiceOnboardingVisualState(); +} + +class _DiceOnboardingVisualState extends State + with SingleTickerProviderStateMixin { + late AnimationController _floatController; + + @override + void initState() { + super.initState(); + _floatController = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 3200), + ); + + final isTesting = + !kIsWeb && Platform.environment.containsKey('FLUTTER_TEST'); + if (!isTesting) { + _floatController.repeat(reverse: true); + } + } + + @override + void dispose() { + _floatController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final isDark = theme.brightness == Brightness.dark; + final diceStyle = DiceStyle.fromBrightness(theme.brightness); + final reduceMotion = MediaQuery.of(context).disableAnimations; + + final primaryDiceSize = widget.size * 0.52; + final secondaryDiceSize = widget.size * 0.38; + + return Semantics( + label: 'PlayMate 3D Tabletop Dice Illustration', + child: AnimatedBuilder( + animation: _floatController, + builder: (context, child) { + final double t = reduceMotion ? 0.5 : _floatController.value; + final double floatOffset = math.sin(t * math.pi) * 8.0; + final double shadowScale = 1.0 - (floatOffset / 40.0).clamp(0.0, 0.3); + + return SizedBox( + width: widget.size, + height: widget.size, + child: Stack( + alignment: Alignment.center, + children: [ + // Ground Ambient Contact Shadow + Positioned( + bottom: widget.size * 0.12, + child: Container( + width: widget.size * 0.72 * shadowScale, + height: 18.0 * shadowScale, + decoration: BoxDecoration( + borderRadius: BorderRadius.all( + Radius.elliptical(widget.size * 0.72, 18.0), + ), + boxShadow: [ + BoxShadow( + color: + (isDark ? Colors.black : const Color(0xFF1A1A1A)) + .withValues(alpha: isDark ? 0.45 : 0.12), + blurRadius: 18.0, + spreadRadius: 2.0, + ), + ], + ), + ), + ), + + // Secondary Companion Die (Tilted in background) + Positioned( + right: widget.size * 0.12, + top: widget.size * 0.22 - (floatOffset * 0.7), + child: Transform( + alignment: Alignment.center, + transform: Matrix4.identity() + ..setEntry(3, 2, 0.002) + ..rotateZ(0.22) + ..rotateX(-0.15) + ..rotateY(0.20), + child: Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular( + secondaryDiceSize * 0.20, + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues( + alpha: isDark ? 0.50 : 0.16, + ), + blurRadius: 12.0, + offset: const Offset(4, 6), + ), + ], + ), + child: DiceFace( + value: 5, + size: secondaryDiceSize, + style: diceStyle, + lightIntensity: 0.92, + isDarkMode: isDark, + ), + ), + ), + ), + + // Primary Hero Die (Foreground with signature 6) + Positioned( + left: widget.size * 0.14, + bottom: widget.size * 0.20 + floatOffset, + child: Transform( + alignment: Alignment.center, + transform: Matrix4.identity() + ..setEntry(3, 2, 0.002) + ..rotateZ(-0.10) + ..rotateX(0.12) + ..rotateY(-0.16), + child: Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular( + primaryDiceSize * 0.20, + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues( + alpha: isDark ? 0.60 : 0.20, + ), + blurRadius: 16.0, + offset: const Offset(4, 8), + ), + ], + ), + child: DiceFace( + value: 6, + size: primaryDiceSize, + style: diceStyle, + lightIntensity: 1.0, + isDarkMode: isDark, + ), + ), + ), + ), + ], + ), + ); + }, + ), + ); + } +} diff --git a/lib/features/onboarding/widgets/essentials_onboarding_visual.dart b/lib/features/onboarding/widgets/essentials_onboarding_visual.dart new file mode 100644 index 0000000..61a849a --- /dev/null +++ b/lib/features/onboarding/widgets/essentials_onboarding_visual.dart @@ -0,0 +1,288 @@ +import 'package:flutter/material.dart'; +import '../../../shared/responsive_layout.dart'; +import '../../coin/coin_face.dart'; +import '../../coin/coin_orientation.dart'; +import '../../dice/dice_face.dart'; + +/// Screen 2 visual composition showcasing PlayMate's essential game-night toolkit. +/// +/// Highlights four representative tools in a tactile focal cluster with +/// surrounding pill labels representing the full collection. +class EssentialsOnboardingVisual extends StatefulWidget { + final double size; + + const EssentialsOnboardingVisual({super.key, this.size = 230.0}); + + @override + State createState() => + _EssentialsOnboardingVisualState(); +} + +class _EssentialsOnboardingVisualState extends State + with SingleTickerProviderStateMixin { + late AnimationController _animController; + late Animation _scaleAnimation; + late Animation _fadeAnimation; + + @override + void initState() { + super.initState(); + _animController = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 900), + ); + + _scaleAnimation = CurvedAnimation( + parent: _animController, + curve: Curves.easeOutBack, + ); + + _fadeAnimation = CurvedAnimation( + parent: _animController, + curve: Curves.easeOut, + ); + + _animController.forward(); + } + + @override + void dispose() { + _animController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final isDark = theme.brightness == Brightness.dark; + final reduceMotion = MediaQuery.of(context).disableAnimations; + + final diceStyle = DiceStyle.fromBrightness(theme.brightness); + + final content = SizedBox( + width: widget.size * 1.15, + height: widget.size, + child: Center( + child: FittedBox( + fit: BoxFit.scaleDown, + child: SizedBox( + width: 320, + child: Column( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + // Central Tactile Toolkit Cluster + Container( + padding: const EdgeInsets.all(AppSpacing.m), + decoration: BoxDecoration( + color: isDark + ? const Color(0xFF1E1E1E) + : const Color(0xFFF7F7F7), + borderRadius: BorderRadius.circular(20), + border: Border.all( + color: isDark + ? const Color(0xFF2E2E2E) + : const Color(0xFFE2E2E2), + width: 1.2, + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues( + alpha: isDark ? 0.35 : 0.08, + ), + blurRadius: 16.0, + offset: const Offset(0, 6), + ), + ], + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + // Dice preview + _ToolClusterItem( + label: 'Dice', + child: DiceFace( + value: 6, + size: 42, + style: diceStyle, + lightIntensity: 1.0, + isDarkMode: isDark, + ), + ), + const SizedBox(width: AppSpacing.m), + + // Coin preview + const _ToolClusterItem( + label: 'Coin', + child: CoinFace( + side: CoinSide.heads, + size: 42, + lightIntensity: 1.0, + ), + ), + const SizedBox(width: AppSpacing.m), + + // Spin Wheel preview + _ToolClusterItem( + label: 'Wheel', + child: Container( + width: 42, + height: 42, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: isDark + ? const Color(0xFF262626) + : const Color(0xFFEFEFEF), + border: Border.all( + color: const Color(0xFFC18A42), + width: 2, + ), + ), + child: const Icon( + Icons.track_changes, + size: 24, + color: Color(0xFFC18A42), + ), + ), + ), + const SizedBox(width: AppSpacing.m), + + // Timers preview + _ToolClusterItem( + label: 'Timers', + child: Container( + width: 42, + height: 42, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: theme.colorScheme.primary.withValues( + alpha: 0.1, + ), + ), + child: Icon( + Icons.timer_outlined, + size: 24, + color: theme.colorScheme.primary, + ), + ), + ), + ], + ), + ), + + const SizedBox(height: AppSpacing.m), + + // Secondary Tools Capsule Badges + Wrap( + spacing: AppSpacing.s, + runSpacing: AppSpacing.xs + 2, + alignment: WrapAlignment.center, + children: const [ + _FeaturePill( + icon: Icons.groups_outlined, + label: 'Team Gen', + ), + _FeaturePill( + icon: Icons.scoreboard_outlined, + label: 'Score Tracker', + ), + _FeaturePill( + icon: Icons.sports_cricket_outlined, + label: 'Cricket Scorer', + ), + _FeaturePill( + icon: Icons.emoji_events_outlined, + label: 'Tournament', + ), + _FeaturePill(icon: Icons.timer, label: 'Chess Clock'), + ], + ), + ], + ), + ), + ), + ), + ); + + if (reduceMotion) { + return Semantics( + label: 'PlayMate essentials toolkit preview', + child: content, + ); + } + + return Semantics( + label: 'PlayMate essentials toolkit preview', + child: FadeTransition( + opacity: _fadeAnimation, + child: ScaleTransition(scale: _scaleAnimation, child: content), + ), + ); + } +} + +class _ToolClusterItem extends StatelessWidget { + final Widget child; + final String label; + + const _ToolClusterItem({required this.child, required this.label}); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + child, + const SizedBox(height: 6), + Text( + label, + style: theme.textTheme.bodySmall?.copyWith( + fontWeight: FontWeight.w600, + fontSize: 11, + ), + ), + ], + ); + } +} + +class _FeaturePill extends StatelessWidget { + final IconData icon; + final String label; + + const _FeaturePill({required this.icon, required this.label}); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final isDark = theme.brightness == Brightness.dark; + + return Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), + decoration: BoxDecoration( + color: isDark ? const Color(0xFF1E1E1E) : const Color(0xFFF1F1F1), + borderRadius: BorderRadius.circular(16), + border: Border.all( + color: isDark ? const Color(0xFF2C2C2C) : const Color(0xFFE2E2E2), + width: 0.8, + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 14, color: theme.colorScheme.secondary), + const SizedBox(width: 4), + Text( + label, + style: theme.textTheme.bodySmall?.copyWith( + fontSize: 11, + fontWeight: FontWeight.w500, + color: isDark ? const Color(0xFFCCCCCC) : const Color(0xFF555555), + ), + ), + ], + ), + ); + } +} diff --git a/lib/features/onboarding/widgets/onboarding_page.dart b/lib/features/onboarding/widgets/onboarding_page.dart new file mode 100644 index 0000000..6b37c82 --- /dev/null +++ b/lib/features/onboarding/widgets/onboarding_page.dart @@ -0,0 +1,102 @@ +import 'package:flutter/material.dart'; +import '../../../shared/responsive_layout.dart'; + +/// Reusable layout for an onboarding screen. +/// +/// Features: +/// - Prominent headline with strong typographical hierarchy +/// - Refined supporting body copy with restrained contrast +/// - Proportional visual area that scales safely across all form factors +/// - Built-in overflow protection and semantic accessibility labels +class OnboardingPage extends StatelessWidget { + final String headline; + final String supportingText; + final Widget visual; + final Widget? badge; + + const OnboardingPage({ + super.key, + required this.headline, + required this.supportingText, + required this.visual, + this.badge, + }); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final size = MediaQuery.of(context).size; + final isCompact = size.height < 680; + + return LayoutBuilder( + builder: (context, constraints) { + return SingleChildScrollView( + physics: const ClampingScrollPhysics(), + padding: EdgeInsets.symmetric( + horizontal: constraints.maxWidth > 600 + ? AppSpacing.xl + : AppSpacing.l, + vertical: isCompact ? AppSpacing.s : AppSpacing.m, + ), + child: ConstrainedBox( + constraints: BoxConstraints( + minHeight: + (constraints.maxHeight - + (isCompact ? AppSpacing.m : AppSpacing.l * 2)) + .clamp(0.0, double.infinity), + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + if (badge != null) ...[ + badge!, + const SizedBox(height: AppSpacing.s), + ], + + // Central Visual Area + Center( + child: Padding( + padding: EdgeInsets.symmetric( + vertical: isCompact ? AppSpacing.s : AppSpacing.m, + ), + child: visual, + ), + ), + + const SizedBox(height: AppSpacing.m), + + // Text Content Area + Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + headline, + textAlign: TextAlign.center, + style: theme.textTheme.headlineMedium?.copyWith( + fontWeight: FontWeight.w800, + letterSpacing: -0.5, + fontSize: isCompact ? 22 : 26, + height: 1.25, + ), + ), + const SizedBox(height: AppSpacing.s + 2), + Text( + supportingText, + textAlign: TextAlign.center, + style: theme.textTheme.bodyMedium?.copyWith( + color: theme.colorScheme.secondary, + height: 1.45, + fontSize: isCompact ? 13 : 15, + ), + ), + SizedBox(height: isCompact ? AppSpacing.s : AppSpacing.l), + ], + ), + ], + ), + ), + ); + }, + ); + } +} diff --git a/lib/features/onboarding/widgets/onboarding_page_indicator.dart b/lib/features/onboarding/widgets/onboarding_page_indicator.dart new file mode 100644 index 0000000..b046d55 --- /dev/null +++ b/lib/features/onboarding/widgets/onboarding_page_indicator.dart @@ -0,0 +1,47 @@ +import 'package:flutter/material.dart'; + +/// Accessible, animated page indicator with smooth width transitions and theme awareness. +class OnboardingPageIndicator extends StatelessWidget { + final int currentPage; + final int pageCount; + final ValueChanged? onDotTapped; + + const OnboardingPageIndicator({ + super.key, + required this.currentPage, + this.pageCount = 3, + this.onDotTapped, + }); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final isDark = theme.brightness == Brightness.dark; + + return Semantics( + label: 'Page ${currentPage + 1} of $pageCount', + child: Row( + mainAxisSize: MainAxisSize.min, + children: List.generate(pageCount, (index) { + final bool isActive = index == currentPage; + return GestureDetector( + onTap: onDotTapped != null ? () => onDotTapped!(index) : null, + child: AnimatedContainer( + duration: const Duration(milliseconds: 280), + curve: Curves.easeOutCubic, + margin: const EdgeInsets.symmetric(horizontal: 4.0), + height: 8.0, + width: isActive ? 26.0 : 8.0, + decoration: BoxDecoration( + color: isActive + ? theme.colorScheme.primary + : (isDark ? Colors.white24 : Colors.black12), + borderRadius: BorderRadius.circular(4.0), + ), + ), + ); + }), + ), + ); + } +} diff --git a/lib/features/onboarding/widgets/welcome_onboarding_visual.dart b/lib/features/onboarding/widgets/welcome_onboarding_visual.dart new file mode 100644 index 0000000..d7f3220 --- /dev/null +++ b/lib/features/onboarding/widgets/welcome_onboarding_visual.dart @@ -0,0 +1,277 @@ +import 'dart:io' show Platform; +import 'dart:math' as math; +import 'package:flutter/foundation.dart' show kIsWeb; +import 'package:flutter/material.dart'; +import '../../coin/coin_face.dart'; +import '../../coin/coin_orientation.dart'; +import '../../dice/dice_face.dart'; + +/// Screen 3 memorable visual composition uniting PlayMate's signature tactile gaming assets. +/// +/// Features: +/// - Embossed 3D PlayMate coin alongside a 3D tilted die +/// - Subtle concentric game-night energy arcs +/// - Gentle floating & breathing animation +/// - Full reduced-motion support and lifecycle management +class WelcomeOnboardingVisual extends StatefulWidget { + final double size; + + const WelcomeOnboardingVisual({super.key, this.size = 230.0}); + + @override + State createState() => + _WelcomeOnboardingVisualState(); +} + +class _WelcomeOnboardingVisualState extends State + with SingleTickerProviderStateMixin { + late AnimationController _pulseController; + + @override + void initState() { + super.initState(); + _pulseController = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 2800), + ); + + final isTesting = + !kIsWeb && Platform.environment.containsKey('FLUTTER_TEST'); + if (!isTesting) { + _pulseController.repeat(reverse: true); + } + } + + @override + void dispose() { + _pulseController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final isDark = theme.brightness == Brightness.dark; + final diceStyle = DiceStyle.fromBrightness(theme.brightness); + final reduceMotion = MediaQuery.of(context).disableAnimations; + + return Semantics( + label: 'PlayMate Game Night Welcome Composition', + child: AnimatedBuilder( + animation: _pulseController, + builder: (context, child) { + final double t = reduceMotion ? 0.5 : _pulseController.value; + final double floatOffset = math.sin(t * math.pi) * 6.0; + + return SizedBox( + width: widget.size, + height: widget.size, + child: Stack( + alignment: Alignment.center, + children: [ + // Concentric Energy Arc Background + CustomPaint( + size: Size(widget.size, widget.size), + painter: _EnergyArcPainter( + arcColor: theme.colorScheme.primary.withValues( + alpha: isDark ? 0.12 : 0.07, + ), + accentColor: const Color( + 0xFFC18A42, + ).withValues(alpha: isDark ? 0.22 : 0.15), + phase: reduceMotion ? 0.0 : _pulseController.value, + ), + ), + + // Ground Contact Shadows + Positioned( + bottom: widget.size * 0.14, + child: Container( + width: widget.size * 0.65, + height: 14.0, + decoration: BoxDecoration( + borderRadius: BorderRadius.all( + Radius.elliptical(widget.size * 0.65, 14.0), + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues( + alpha: isDark ? 0.40 : 0.12, + ), + blurRadius: 16.0, + spreadRadius: 2.0, + ), + ], + ), + ), + ), + + // PlayMate Minted 3D Coin (Left-anchored) + Positioned( + left: widget.size * 0.12, + top: widget.size * 0.24 + floatOffset, + child: Transform( + alignment: Alignment.center, + transform: Matrix4.identity() + ..setEntry(3, 2, 0.002) + ..rotateZ(-0.08) + ..rotateY(-0.18), + child: Container( + decoration: BoxDecoration( + shape: BoxShape.circle, + boxShadow: [ + BoxShadow( + color: Colors.black.withValues( + alpha: isDark ? 0.55 : 0.18, + ), + blurRadius: 14.0, + offset: const Offset(2, 6), + ), + ], + ), + child: const CoinFace( + side: CoinSide.heads, + size: 88, + lightIntensity: 1.0, + ), + ), + ), + ), + + // PlayMate Tactile Die (Right-anchored) + Positioned( + right: widget.size * 0.12, + bottom: widget.size * 0.18 - floatOffset, + child: Transform( + alignment: Alignment.center, + transform: Matrix4.identity() + ..setEntry(3, 2, 0.002) + ..rotateZ(0.12) + ..rotateX(0.14) + ..rotateY(0.12), + child: Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(74 * 0.20), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues( + alpha: isDark ? 0.55 : 0.18, + ), + blurRadius: 16.0, + offset: const Offset(4, 8), + ), + ], + ), + child: DiceFace( + value: 6, + size: 74, + style: diceStyle, + lightIntensity: 1.0, + isDarkMode: isDark, + ), + ), + ), + ), + + // Subtle Top Accent Badge + Positioned( + top: widget.size * 0.08, + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 4, + ), + decoration: BoxDecoration( + color: const Color(0xFFC18A42).withValues(alpha: 0.15), + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: const Color(0xFFC18A42).withValues(alpha: 0.35), + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon( + Icons.sports_esports, + size: 14, + color: Color(0xFFC18A42), + ), + const SizedBox(width: 4), + Text( + 'READY TO PLAY', + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w700, + letterSpacing: 0.8, + color: isDark + ? const Color(0xFFE4AA5A) + : const Color(0xFF9E6822), + ), + ), + ], + ), + ), + ), + ], + ), + ); + }, + ), + ); + } +} + +class _EnergyArcPainter extends CustomPainter { + final Color arcColor; + final Color accentColor; + final double phase; + + _EnergyArcPainter({ + required this.arcColor, + required this.accentColor, + required this.phase, + }); + + @override + void paint(Canvas canvas, Size size) { + final center = Offset(size.width / 2, size.height / 2); + final paint1 = Paint() + ..color = arcColor + ..style = PaintingStyle.stroke + ..strokeWidth = 1.2; + + final paint2 = Paint() + ..color = accentColor + ..style = PaintingStyle.stroke + ..strokeWidth = 1.6 + ..strokeCap = StrokeCap.round; + + final double radius1 = size.width * 0.44; + final double radius2 = size.width * 0.38; + + canvas.drawCircle(center, radius1, paint1); + + // Accent partial arcs + canvas.drawArc( + Rect.fromCircle(center: center, radius: radius2), + -math.pi / 4 + (phase * 0.1), + math.pi / 3, + false, + paint2, + ); + canvas.drawArc( + Rect.fromCircle(center: center, radius: radius2), + 3 * math.pi / 4 + (phase * 0.1), + math.pi / 4, + false, + paint2, + ); + } + + @override + bool shouldRepaint(covariant _EnergyArcPainter oldDelegate) { + return oldDelegate.phase != phase || + oldDelegate.arcColor != arcColor || + oldDelegate.accentColor != accentColor; + } +} diff --git a/lib/features/score_tracker/score_provider.dart b/lib/features/score_tracker/score_provider.dart index 1e8d48a..c1b743f 100644 --- a/lib/features/score_tracker/score_provider.dart +++ b/lib/features/score_tracker/score_provider.dart @@ -96,10 +96,13 @@ class ScoreTrackerNotifier extends StateNotifier { } void undoLastAction() { - if (state == null || state!.scoreHistory.isEmpty || state!.isCompleted) return; + if (state == null || state!.scoreHistory.isEmpty || state!.isCompleted) { + return; + } final previousScores = state!.scoreHistory.last; - final updatedHistory = List>.from(state!.scoreHistory)..removeLast(); + final updatedHistory = List>.from(state!.scoreHistory) + ..removeLast(); state = state!.copyWith( teamAScore: previousScores[0], @@ -114,8 +117,9 @@ class ScoreTrackerNotifier extends StateNotifier { // Save to matches history final box = StorageService.getMatchBox(); - final List history = box.get('score_matches', defaultValue: []) as List; - + final List history = + box.get('score_matches', defaultValue: []) as List; + final match = { 'date': DateTime.now().toIso8601String(), 'type': 'Score Tracker', @@ -124,8 +128,8 @@ class ScoreTrackerNotifier extends StateNotifier { 'teamB': state!.teamBName, 'scoreA': state!.teamAScore, 'scoreB': state!.teamBScore, - 'winner': state!.teamAScore > state!.teamBScore - ? state!.teamAName + 'winner': state!.teamAScore > state!.teamBScore + ? state!.teamAName : (state!.teamAScore < state!.teamBScore ? state!.teamBName : 'Tie'), }; @@ -137,6 +141,7 @@ class ScoreTrackerNotifier extends StateNotifier { } } -final scoreTrackerProvider = StateNotifierProvider((ref) { - return ScoreTrackerNotifier(); -}); +final scoreTrackerProvider = + StateNotifierProvider((ref) { + return ScoreTrackerNotifier(); + }); diff --git a/lib/features/score_tracker/score_screen.dart b/lib/features/score_tracker/score_screen.dart index 48ef215..125d0ed 100644 --- a/lib/features/score_tracker/score_screen.dart +++ b/lib/features/score_tracker/score_screen.dart @@ -16,7 +16,9 @@ class _ScoreTrackerScreenState extends ConsumerState { final TextEditingController _teamBController = TextEditingController(); void _startMatch() { - ref.read(scoreTrackerProvider.notifier).startNewMatch( + ref + .read(scoreTrackerProvider.notifier) + .startNewMatch( _matchNameController.text, _teamAController.text, _teamBController.text, @@ -44,7 +46,9 @@ class _ScoreTrackerScreenState extends ConsumerState { IconButton( icon: const Icon(Icons.undo), onPressed: match.scoreHistory.isNotEmpty - ? () => ref.read(scoreTrackerProvider.notifier).undoLastAction() + ? () => ref + .read(scoreTrackerProvider.notifier) + .undoLastAction() : null, tooltip: 'Undo Last Score', ), @@ -100,10 +104,15 @@ class _ScoreTrackerScreenState extends ConsumerState { style: ElevatedButton.styleFrom( backgroundColor: theme.colorScheme.primary, foregroundColor: theme.colorScheme.onPrimary, - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), ), onPressed: _startMatch, - child: const Text('START MATCH', style: TextStyle(fontWeight: FontWeight.bold)), + child: const Text( + 'START MATCH', + style: TextStyle(fontWeight: FontWeight.bold), + ), ), ), ], @@ -118,7 +127,9 @@ class _ScoreTrackerScreenState extends ConsumerState { padding: const EdgeInsets.symmetric(vertical: AppSpacing.m), child: Text( match.matchName, - style: theme.textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold), + style: theme.textTheme.titleLarge?.copyWith( + fontWeight: FontWeight.bold, + ), ), ), Expanded( @@ -129,8 +140,12 @@ class _ScoreTrackerScreenState extends ConsumerState { child: _buildTeamScoreButton( name: match.teamAName, score: match.teamAScore, - onTap: () => ref.read(scoreTrackerProvider.notifier).incrementScore(true), - onLongPress: () => ref.read(scoreTrackerProvider.notifier).decrementScore(true), + onTap: () => ref + .read(scoreTrackerProvider.notifier) + .incrementScore(true), + onLongPress: () => ref + .read(scoreTrackerProvider.notifier) + .decrementScore(true), theme: theme, isTeamA: true, ), @@ -141,8 +156,12 @@ class _ScoreTrackerScreenState extends ConsumerState { child: _buildTeamScoreButton( name: match.teamBName, score: match.teamBScore, - onTap: () => ref.read(scoreTrackerProvider.notifier).incrementScore(false), - onLongPress: () => ref.read(scoreTrackerProvider.notifier).decrementScore(false), + onTap: () => ref + .read(scoreTrackerProvider.notifier) + .incrementScore(false), + onLongPress: () => ref + .read(scoreTrackerProvider.notifier) + .decrementScore(false), theme: theme, isTeamA: false, ), @@ -157,7 +176,8 @@ class _ScoreTrackerScreenState extends ConsumerState { children: [ Expanded( child: OutlinedButton( - onPressed: () => ref.read(scoreTrackerProvider.notifier).reset(), + onPressed: () => + ref.read(scoreTrackerProvider.notifier).reset(), child: const Text('CANCEL'), ), ), @@ -169,10 +189,14 @@ class _ScoreTrackerScreenState extends ConsumerState { foregroundColor: theme.colorScheme.onPrimary, ), onPressed: () async { - await ref.read(scoreTrackerProvider.notifier).endAndSaveMatch(); + await ref + .read(scoreTrackerProvider.notifier) + .endAndSaveMatch(); if (!mounted) return; ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Match saved successfully!')), + const SnackBar( + content: Text('Match saved successfully!'), + ), ); ref.read(scoreTrackerProvider.notifier).reset(); }, diff --git a/lib/features/settings/settings_screen.dart b/lib/features/settings/settings_screen.dart index 554a595..330e59c 100644 --- a/lib/features/settings/settings_screen.dart +++ b/lib/features/settings/settings_screen.dart @@ -20,9 +20,7 @@ class SettingsScreen extends ConsumerWidget { final theme = Theme.of(context); return Scaffold( - appBar: AppBar( - title: const Text('Settings'), - ), + appBar: AppBar(title: const Text('Settings')), body: SafeArea( child: ResponsiveLayout( mobile: ListView( @@ -36,8 +34,9 @@ class SettingsScreen extends ConsumerWidget { subtitle: const Text('Use clean Notion dark theme'), value: themeMode == ThemeMode.dark, onChanged: (value) async { - ref.read(themeModeProvider.notifier).state = - value ? ThemeMode.dark : ThemeMode.light; + ref.read(themeModeProvider.notifier).state = value + ? ThemeMode.dark + : ThemeMode.light; await StorageService.setDarkMode(value); }, ), @@ -49,12 +48,20 @@ class SettingsScreen extends ConsumerWidget { child: Column( children: [ ListTile( - leading: Icon(Icons.delete_sweep, color: theme.colorScheme.error), + leading: Icon( + Icons.delete_sweep, + color: theme.colorScheme.error, + ), title: Text( 'Clear Match History', - style: TextStyle(color: theme.colorScheme.error, fontWeight: FontWeight.bold), + style: TextStyle( + color: theme.colorScheme.error, + fontWeight: FontWeight.bold, + ), + ), + subtitle: const Text( + 'Deletes all local matches and dice histories', ), - subtitle: const Text('Deletes all local matches and dice histories'), onTap: () async { final confirmed = await showDialog( context: context, @@ -84,7 +91,9 @@ class SettingsScreen extends ConsumerWidget { final messenger = ScaffoldMessenger.of(context); await StorageService.clearAllData(); messenger.showSnackBar( - const SnackBar(content: Text('All data cleared successfully!')), + const SnackBar( + content: Text('All data cleared successfully!'), + ), ); } }, @@ -99,7 +108,9 @@ class SettingsScreen extends ConsumerWidget { ListTile( leading: const Icon(Icons.info_outline), title: const Text('About PlayMate'), - subtitle: const Text('Utilities, developer information & version'), + subtitle: const Text( + 'Utilities, developer information & version', + ), trailing: const Icon(Icons.chevron_right), onTap: () => context.push('/about'), ), @@ -133,14 +144,17 @@ class SettingsScreen extends ConsumerWidget { builder: (context, ref, _) { final packageInfoAsync = ref.watch(packageInfoProvider); final version = packageInfoAsync.when( - data: (info) => 'v${info.version} (Build ${info.buildNumber})', - loading: () => 'v1.0.0', - error: (err, stack) => 'v1.0.0', + data: (info) => 'v${info.version}', + loading: () => 'v1.0.2', + error: (err, stack) => 'v1.0.2', ); return Text( 'PLAYMATE $version\nEverything you need for offline games.\nDeveloped by Sundramdotdev', textAlign: TextAlign.center, - style: TextStyle(color: theme.colorScheme.secondary, height: 1.5), + style: TextStyle( + color: theme.colorScheme.secondary, + height: 1.5, + ), ); }, ), diff --git a/lib/features/spin_wheel/playmate_spin_wheel.dart b/lib/features/spin_wheel/playmate_spin_wheel.dart index 2714d28..bdcb99b 100644 --- a/lib/features/spin_wheel/playmate_spin_wheel.dart +++ b/lib/features/spin_wheel/playmate_spin_wheel.dart @@ -71,7 +71,8 @@ class _PlayMateSpinWheelState extends State ); // Guard idle animation loop during automated testing to avoid pumpAndSettle timeout - final isTesting = !kIsWeb && Platform.environment.containsKey('FLUTTER_TEST'); + final isTesting = + !kIsWeb && Platform.environment.containsKey('FLUTTER_TEST'); if (!isTesting) { _idleController.repeat(); } @@ -93,7 +94,9 @@ class _PlayMateSpinWheelState extends State void didUpdateWidget(covariant PlayMateSpinWheel oldWidget) { super.didUpdateWidget(oldWidget); - if (widget.isSpinning && !oldWidget.isSpinning && !_spinController.isAnimating) { + if (widget.isSpinning && + !oldWidget.isSpinning && + !_spinController.isAnimating) { _startSpinSequence(); } } @@ -107,7 +110,9 @@ class _PlayMateSpinWheelState extends State // Determine target index int winningIndex = 0; if (widget.targetWinner != null) { - final found = widget.options.indexWhere((o) => o.id == widget.targetWinner!.id); + final found = widget.options.indexWhere( + (o) => o.id == widget.targetWinner!.id, + ); winningIndex = found >= 0 ? found : 0; } @@ -129,7 +134,8 @@ class _PlayMateSpinWheelState extends State final double t = _spinController.value; final double curvedT = SpinWheelMotionConfig.spinCurve.transform(t); - final double rotation = _startRotation + (_targetRotation - _startRotation) * curvedT; + final double rotation = + _startRotation + (_targetRotation - _startRotation) * curvedT; final int count = widget.options.length; if (count > 0) { @@ -150,7 +156,8 @@ class _PlayMateSpinWheelState extends State // Pointer deflection: deflects in rotation direction when near peg boundary (fraction < 0.25) if (pegFraction < 0.25) { final double factor = math.sin((pegFraction / 0.25) * math.pi); - _pointerDeflection = factor * SpinWheelMotionConfig.pointerMaxDeflection; + _pointerDeflection = + factor * SpinWheelMotionConfig.pointerMaxDeflection; } else { _pointerDeflection = 0.0; } @@ -203,13 +210,14 @@ class _PlayMateSpinWheelState extends State Widget build(BuildContext context) { final theme = Theme.of(context); final isDarkMode = theme.brightness == Brightness.dark; - final reducedMotion = MediaQuery.maybeOf(context)?.disableAnimations ?? false; + final reducedMotion = + MediaQuery.maybeOf(context)?.disableAnimations ?? false; final String semanticsLabel = widget.isSpinning ? 'Spin wheel is spinning' : widget.targetWinner != null - ? 'Spin wheel winner is ${widget.targetWinner!.label}. Tap to spin again' - : 'Spin wheel ready with ${widget.options.length} options. Tap to spin'; + ? 'Spin wheel winner is ${widget.targetWinner!.label}. Tap to spin again' + : 'Spin wheel ready with ${widget.options.length} options. Tap to spin'; return Semantics( label: semanticsLabel, @@ -220,19 +228,25 @@ class _PlayMateSpinWheelState extends State onTapUp: _onTapUp, onTapCancel: _onTapCancel, child: AnimatedBuilder( - animation: Listenable.merge([_spinController, _idleController, _pressController]), + animation: Listenable.merge([ + _spinController, + _idleController, + _pressController, + ]), builder: (context, _) { final double pressT = _pressController.value; final double spinT = _spinController.value; // Physical tactile scale: compression on press, gentle breathing during spin - double scale = 1.0 - (pressT * (1.0 - SpinWheelMotionConfig.pressScale)); + double scale = + 1.0 - (pressT * (1.0 - SpinWheelMotionConfig.pressScale)); if (!reducedMotion && _spinController.isAnimating) { if (spinT < SpinWheelMotionConfig.accelerationEnd) { final subT = spinT / SpinWheelMotionConfig.accelerationEnd; scale = 1.0 + (subT * 0.02); } else if (spinT > SpinWheelMotionConfig.decelerationEnd) { - final subT = (spinT - SpinWheelMotionConfig.decelerationEnd) / + final subT = + (spinT - SpinWheelMotionConfig.decelerationEnd) / (1.0 - SpinWheelMotionConfig.decelerationEnd); scale = 1.02 - (subT * 0.02); } else { @@ -252,7 +266,9 @@ class _PlayMateSpinWheelState extends State scale: scale, child: SizedBox( width: wheelSize, - height: wheelSize + 24.0, // extra clearance for top pointer & contact shadow + height: + wheelSize + + 24.0, // extra clearance for top pointer & contact shadow child: Stack( clipBehavior: Clip.none, alignment: Alignment.center, @@ -261,20 +277,31 @@ class _PlayMateSpinWheelState extends State Positioned( bottom: 4.0, child: Container( - width: wheelSize * SpinWheelMotionConfig.shadowIdleScale, + width: + wheelSize * SpinWheelMotionConfig.shadowIdleScale, height: wheelSize * 0.14, decoration: BoxDecoration( shape: BoxShape.rectangle, - borderRadius: BorderRadius.all(Radius.elliptical(wheelSize * 0.5, wheelSize * 0.07)), + borderRadius: BorderRadius.all( + Radius.elliptical( + wheelSize * 0.5, + wheelSize * 0.07, + ), + ), boxShadow: [ BoxShadow( color: Colors.black.withValues( alpha: isDarkMode - ? SpinWheelMotionConfig.shadowIdleOpacity * 1.6 + ? SpinWheelMotionConfig.shadowIdleOpacity * + 1.6 : SpinWheelMotionConfig.shadowIdleOpacity, ), - blurRadius: _spinController.isAnimating ? 18.0 : 12.0, - spreadRadius: _spinController.isAnimating ? 4.0 : 2.0, + blurRadius: _spinController.isAnimating + ? 18.0 + : 12.0, + spreadRadius: _spinController.isAnimating + ? 4.0 + : 2.0, ), ], ), @@ -318,4 +345,3 @@ class _PlayMateSpinWheelState extends State ); } } - diff --git a/lib/features/spin_wheel/spin_wheel_math.dart b/lib/features/spin_wheel/spin_wheel_math.dart index 714b30b..e356ffe 100644 --- a/lib/features/spin_wheel/spin_wheel_math.dart +++ b/lib/features/spin_wheel/spin_wheel_math.dart @@ -41,7 +41,9 @@ class SpinWheelMath { // To bring sector center ((index + 0.5) * sweep) to the pointer: // centerAngle + finalRotation = pointerAngle (mod 2pi) // finalRotation = - (winningIndex + 0.5) * sweep (mod 2pi) - final double targetBase = (2 * math.pi - ((winningIndex + 0.5) * sweep) % (2 * math.pi)) % (2 * math.pi); + final double targetBase = + (2 * math.pi - ((winningIndex + 0.5) * sweep) % (2 * math.pi)) % + (2 * math.pi); final double normalizedCurrent = currentRotation % (2 * math.pi); double delta = targetBase - normalizedCurrent; @@ -60,7 +62,8 @@ class SpinWheelMath { if (count <= 0) return 0; final double sweep = getSweepAngle(count); // Effective angle on the unrotated wheel that corresponds to pointerAngle - final double effectiveAngle = (2 * math.pi - (rotation % (2 * math.pi))) % (2 * math.pi); + final double effectiveAngle = + (2 * math.pi - (rotation % (2 * math.pi))) % (2 * math.pi); final int index = (effectiveAngle / sweep).floor() % count; return index; } @@ -111,4 +114,3 @@ class SpinWheelMath { } } } - diff --git a/lib/features/spin_wheel/spin_wheel_models.dart b/lib/features/spin_wheel/spin_wheel_models.dart index 6d1f084..c658c72 100644 --- a/lib/features/spin_wheel/spin_wheel_models.dart +++ b/lib/features/spin_wheel/spin_wheel_models.dart @@ -6,17 +6,9 @@ class WheelOption { final String label; final Color? customColor; - const WheelOption({ - required this.id, - required this.label, - this.customColor, - }); + const WheelOption({required this.id, required this.label, this.customColor}); - WheelOption copyWith({ - String? id, - String? label, - Color? customColor, - }) { + WheelOption copyWith({String? id, String? label, Color? customColor}) { return WheelOption( id: id ?? this.id, label: label ?? this.label, @@ -25,10 +17,10 @@ class WheelOption { } Map toJson() => { - 'id': id, - 'label': label, - if (customColor != null) 'color': customColor!.toARGB32(), - }; + 'id': id, + 'label': label, + if (customColor != null) 'color': customColor!.toARGB32(), + }; factory WheelOption.fromJson(Map json) { return WheelOption( @@ -105,15 +97,12 @@ class SpinWheelRecord { final String winnerLabel; final DateTime timestamp; - const SpinWheelRecord({ - required this.winnerLabel, - required this.timestamp, - }); + const SpinWheelRecord({required this.winnerLabel, required this.timestamp}); Map toJson() => { - 'winner': winnerLabel, - 'time': timestamp.millisecondsSinceEpoch, - }; + 'winner': winnerLabel, + 'time': timestamp.millisecondsSinceEpoch, + }; factory SpinWheelRecord.fromJson(Map json) { return SpinWheelRecord( @@ -122,4 +111,3 @@ class SpinWheelRecord { ); } } - diff --git a/lib/features/spin_wheel/spin_wheel_motion_config.dart b/lib/features/spin_wheel/spin_wheel_motion_config.dart index eebc7bc..16df9e6 100644 --- a/lib/features/spin_wheel/spin_wheel_motion_config.dart +++ b/lib/features/spin_wheel/spin_wheel_motion_config.dart @@ -57,4 +57,3 @@ class SpinWheelMotionConfig { static const Curve spinCurve = Curves.easeOutCubic; static const Curve reducedMotionCurve = Curves.easeOutQuad; } - diff --git a/lib/features/spin_wheel/spin_wheel_provider.dart b/lib/features/spin_wheel/spin_wheel_provider.dart index cb91e2c..6b7c234 100644 --- a/lib/features/spin_wheel/spin_wheel_provider.dart +++ b/lib/features/spin_wheel/spin_wheel_provider.dart @@ -30,7 +30,9 @@ class SpinWheelState { }) { return SpinWheelState( options: options ?? this.options, - selectedWinner: clearWinner ? null : (selectedWinner ?? this.selectedWinner), + selectedWinner: clearWinner + ? null + : (selectedWinner ?? this.selectedWinner), isSpinning: isSpinning ?? this.isSpinning, history: history ?? this.history, activePresetId: activePresetId ?? this.activePresetId, @@ -48,12 +50,14 @@ class SpinWheelNotifier extends StateNotifier { final Random _random = Random(); SpinWheelNotifier() - : super(SpinWheelState( + : super( + SpinWheelState( options: SpinWheelPreset.builtInPresets.first.toOptions(), isSpinning: false, history: const [], activePresetId: 'truth_or_dare', - )) { + ), + ) { _loadPersistedData(); } @@ -67,7 +71,9 @@ class SpinWheelNotifier extends StateNotifier { if (savedOptionsRaw != null && savedOptionsRaw.isNotEmpty) { try { loadedOptions = savedOptionsRaw - .map((e) => WheelOption.fromJson(Map.from(e as Map))) + .map( + (e) => WheelOption.fromJson(Map.from(e as Map)), + ) .toList(); } catch (_) { loadedOptions = null; @@ -80,7 +86,10 @@ class SpinWheelNotifier extends StateNotifier { if (savedHistoryRaw != null) { try { loadedHistory = savedHistoryRaw - .map((e) => SpinWheelRecord.fromJson(Map.from(e as Map))) + .map( + (e) => + SpinWheelRecord.fromJson(Map.from(e as Map)), + ) .toList(); } catch (_) { loadedHistory = []; @@ -88,7 +97,8 @@ class SpinWheelNotifier extends StateNotifier { } final String savedPresetId = - box.get('spin_wheel_active_preset', defaultValue: 'truth_or_dare') as String; + box.get('spin_wheel_active_preset', defaultValue: 'truth_or_dare') + as String; if (loadedOptions != null && loadedOptions.length >= 2) { state = state.copyWith( @@ -105,7 +115,9 @@ class SpinWheelNotifier extends StateNotifier { } Future _persistOptions() async { - if (!mounted || !StorageService.isBoxOpen(StorageService.statsBoxName)) return; + if (!mounted || !StorageService.isBoxOpen(StorageService.statsBoxName)) { + return; + } final box = StorageService.getStatsBox(); await box.put( 'spin_wheel_options', @@ -116,7 +128,9 @@ class SpinWheelNotifier extends StateNotifier { } Future _persistHistory() async { - if (!mounted || !StorageService.isBoxOpen(StorageService.statsBoxName)) return; + if (!mounted || !StorageService.isBoxOpen(StorageService.statsBoxName)) { + return; + } final box = StorageService.getStatsBox(); await box.put( 'spin_wheel_history', @@ -130,7 +144,9 @@ class SpinWheelNotifier extends StateNotifier { void addOption(String label) { final trimmed = label.trim(); if (trimmed.isEmpty) return; - if (state.options.length >= 16) return; // Prevent unreasonable segment squeeze + if (state.options.length >= 16) { + return; // Prevent unreasonable segment squeeze + } final newOption = WheelOption( id: 'opt_${DateTime.now().microsecondsSinceEpoch}', @@ -156,10 +172,7 @@ class SpinWheelNotifier extends StateNotifier { return opt; }).toList(); - state = state.copyWith( - options: updated, - activePresetId: 'custom', - ); + state = state.copyWith(options: updated, activePresetId: 'custom'); _persistOptions(); } @@ -216,10 +229,7 @@ class SpinWheelNotifier extends StateNotifier { final WheelOption chosenWinner = state.options[winnerIndex]; // 2. Publish target winner immediately so the renderer targets this sector - state = state.copyWith( - isSpinning: true, - selectedWinner: chosenWinner, - ); + state = state.copyWith(isSpinning: true, selectedWinner: chosenWinner); // 3. Await duration matching the physical spin timeline await Future.delayed(SpinWheelMotionConfig.spinDuration); @@ -230,7 +240,8 @@ class SpinWheelNotifier extends StateNotifier { timestamp: DateTime.now(), ); - final updatedHistory = List.from(state.history)..insert(0, record); + final updatedHistory = List.from(state.history) + ..insert(0, record); if (updatedHistory.length > 50) { updatedHistory.removeLast(); } @@ -261,5 +272,5 @@ class SpinWheelNotifier extends StateNotifier { final spinWheelProvider = StateNotifierProvider((ref) { - return SpinWheelNotifier(); -}); + return SpinWheelNotifier(); + }); diff --git a/lib/features/spin_wheel/spin_wheel_screen.dart b/lib/features/spin_wheel/spin_wheel_screen.dart index daabd20..fa5f0d7 100644 --- a/lib/features/spin_wheel/spin_wheel_screen.dart +++ b/lib/features/spin_wheel/spin_wheel_screen.dart @@ -58,7 +58,9 @@ class _SpinWheelScreenState extends ConsumerState { FilledButton( onPressed: () { if (_optionController.text.trim().isNotEmpty) { - ref.read(spinWheelProvider.notifier).addOption(_optionController.text); + ref + .read(spinWheelProvider.notifier) + .addOption(_optionController.text); Navigator.pop(ctx); } }, @@ -93,7 +95,10 @@ class _SpinWheelScreenState extends ConsumerState { children: [ const Text( 'Wheel Presets', - style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + ), ), IconButton( icon: const Icon(Icons.close), @@ -109,7 +114,9 @@ class _SpinWheelScreenState extends ConsumerState { title: Text( preset.name, style: TextStyle( - fontWeight: isSelected ? FontWeight.bold : FontWeight.w500, + fontWeight: isSelected + ? FontWeight.bold + : FontWeight.w500, color: isSelected ? const Color(0xFFC18A42) : null, ), ), @@ -120,7 +127,10 @@ class _SpinWheelScreenState extends ConsumerState { style: const TextStyle(fontSize: 12), ), trailing: isSelected - ? const Icon(Icons.check_circle, color: Color(0xFFC18A42)) + ? const Icon( + Icons.check_circle, + color: Color(0xFFC18A42), + ) : null, onTap: () { ref.read(spinWheelProvider.notifier).applyPreset(preset); @@ -163,12 +173,16 @@ class _SpinWheelScreenState extends ConsumerState { children: [ Text( 'Edit Options (${wheelState.options.length})', - style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + ), ), Row( children: [ TextButton.icon( - onPressed: () => _showAddOptionDialog(context), + onPressed: () => + _showAddOptionDialog(context), icon: const Icon(Icons.add, size: 18), label: const Text('Add'), ), @@ -192,7 +206,9 @@ class _SpinWheelScreenState extends ConsumerState { return ListTile( leading: CircleAvatar( radius: 14, - backgroundColor: const Color(0xFFC18A42).withValues(alpha: 0.2), + backgroundColor: const Color( + 0xFFC18A42, + ).withValues(alpha: 0.2), child: Text( '${index + 1}', style: const TextStyle( @@ -206,14 +222,18 @@ class _SpinWheelScreenState extends ConsumerState { trailing: IconButton( icon: Icon( Icons.delete_outline, - color: canDelete ? Colors.red.shade400 : Colors.grey, + color: canDelete + ? Colors.red.shade400 + : Colors.grey, ), onPressed: canDelete ? () => ref - .read(spinWheelProvider.notifier) - .removeOptionById(option.id) + .read(spinWheelProvider.notifier) + .removeOptionById(option.id) : null, - tooltip: canDelete ? 'Delete option' : 'Minimum 2 options required', + tooltip: canDelete + ? 'Delete option' + : 'Minimum 2 options required', ), ); }, @@ -242,7 +262,9 @@ class _SpinWheelScreenState extends ConsumerState { actions: [ IconButton( icon: const Icon(Icons.list_alt), - onPressed: wheelState.isSpinning ? null : () => _showEditOptionsSheet(context), + onPressed: wheelState.isSpinning + ? null + : () => _showEditOptionsSheet(context), tooltip: 'Options', ), PopupMenuButton( @@ -303,7 +325,10 @@ class _SpinWheelScreenState extends ConsumerState { // Responsive Hero Physical Spin Wheel LayoutBuilder( builder: (context, constraints) { - final double wheelSize = _calculateResponsiveWheelSize(constraints.maxWidth); + final double wheelSize = + _calculateResponsiveWheelSize( + constraints.maxWidth, + ); return Center( child: PlayMateSpinWheel( options: wheelState.options, @@ -325,7 +350,11 @@ class _SpinWheelScreenState extends ConsumerState { // Compact Recent History if (wheelState.history.isNotEmpty) ...[ - _buildRecentHistorySection(wheelState, theme, isDarkMode), + _buildRecentHistorySection( + wheelState, + theme, + isDarkMode, + ), ], ], ), @@ -353,7 +382,11 @@ class _SpinWheelScreenState extends ConsumerState { } } - Widget _buildPresetIndicator(SpinWheelState wheelState, ThemeData theme, bool isDarkMode) { + Widget _buildPresetIndicator( + SpinWheelState wheelState, + ThemeData theme, + bool isDarkMode, + ) { final presetName = SpinWheelPreset.builtInPresets .firstWhere( (p) => p.id == wheelState.activePresetId, @@ -371,12 +404,16 @@ class _SpinWheelScreenState extends ConsumerState { runSpacing: 6.0, children: [ InkWell( - onTap: wheelState.isSpinning ? null : () => _showPresetsBottomSheet(context), + onTap: wheelState.isSpinning + ? null + : () => _showPresetsBottomSheet(context), borderRadius: BorderRadius.circular(16), child: Container( padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), decoration: BoxDecoration( - color: isDarkMode ? const Color(0xFF1E1E1E) : const Color(0xFFF5F5F5), + color: isDarkMode + ? const Color(0xFF1E1E1E) + : const Color(0xFFF5F5F5), borderRadius: BorderRadius.circular(16), border: Border.all( color: const Color(0xFFC18A42).withValues(alpha: 0.35), @@ -397,28 +434,42 @@ class _SpinWheelScreenState extends ConsumerState { ), ), const SizedBox(width: 4), - const Icon(Icons.arrow_drop_down, size: 16, color: Color(0xFFC18A42)), + const Icon( + Icons.arrow_drop_down, + size: 16, + color: Color(0xFFC18A42), + ), ], ), ), ), InkWell( - onTap: wheelState.isSpinning ? null : () => _showEditOptionsSheet(context), + onTap: wheelState.isSpinning + ? null + : () => _showEditOptionsSheet(context), borderRadius: BorderRadius.circular(16), child: Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), decoration: BoxDecoration( - color: isDarkMode ? const Color(0xFF1E1E1E) : const Color(0xFFF5F5F5), + color: isDarkMode + ? const Color(0xFF1E1E1E) + : const Color(0xFFF5F5F5), borderRadius: BorderRadius.circular(16), border: Border.all( - color: isDarkMode ? const Color(0xFF2C2C2C) : const Color(0xFFE0E0E0), + color: isDarkMode + ? const Color(0xFF2C2C2C) + : const Color(0xFFE0E0E0), width: 1.0, ), ), child: Row( mainAxisSize: MainAxisSize.min, children: [ - Icon(Icons.pie_chart_outline, size: 13, color: theme.colorScheme.secondary), + Icon( + Icons.pie_chart_outline, + size: 13, + color: theme.colorScheme.secondary, + ), const SizedBox(width: 5), Text( '${wheelState.options.length} options', @@ -543,23 +594,39 @@ class _SpinWheelScreenState extends ConsumerState { style: OutlinedButton.styleFrom( visualDensity: VisualDensity.compact, side: BorderSide( - color: isDarkMode ? const Color(0xFF383838) : const Color(0xFFD0D0D0), + color: isDarkMode + ? const Color(0xFF383838) + : const Color(0xFFD0D0D0), + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), ), - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), ), onPressed: _triggerSpin, icon: const Icon(Icons.replay, size: 16), - label: const Text('SPIN AGAIN', style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold)), + label: const Text( + 'SPIN AGAIN', + style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold), + ), ), if (canRemoveWinner) FilledButton.tonalIcon( style: FilledButton.styleFrom( visualDensity: VisualDensity.compact, - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + ), ), - onPressed: () => ref.read(spinWheelProvider.notifier).removeWinner(), + onPressed: () => + ref.read(spinWheelProvider.notifier).removeWinner(), icon: const Icon(Icons.remove_circle_outline, size: 16), - label: const Text('REMOVE WINNER', style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold)), + label: const Text( + 'REMOVE WINNER', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + ), + ), ), ], ), @@ -597,7 +664,8 @@ class _SpinWheelScreenState extends ConsumerState { icon: const Icon(Icons.delete_outline, size: 16), visualDensity: VisualDensity.compact, tooltip: 'Clear history', - onPressed: () => ref.read(spinWheelProvider.notifier).clearHistory(), + onPressed: () => + ref.read(spinWheelProvider.notifier).clearHistory(), ), ], ), @@ -615,16 +683,25 @@ class _SpinWheelScreenState extends ConsumerState { return Padding( padding: const EdgeInsets.only(right: 6.0), child: Container( - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), + padding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 5, + ), decoration: BoxDecoration( color: isLatest - ? (isDarkMode ? const Color(0xFF2C2C2E) : const Color(0xFFEBEBEB)) - : (isDarkMode ? const Color(0xFF1E1E1E) : const Color(0xFFF5F5F5)), + ? (isDarkMode + ? const Color(0xFF2C2C2E) + : const Color(0xFFEBEBEB)) + : (isDarkMode + ? const Color(0xFF1E1E1E) + : const Color(0xFFF5F5F5)), borderRadius: BorderRadius.circular(10), border: Border.all( color: isLatest ? const Color(0xFFC18A42).withValues(alpha: 0.4) - : (isDarkMode ? const Color(0xFF2C2C2C) : const Color(0xFFE0E0E0)), + : (isDarkMode + ? const Color(0xFF2C2C2C) + : const Color(0xFFE0E0E0)), width: 1.0, ), ), @@ -646,9 +723,13 @@ class _SpinWheelScreenState extends ConsumerState { record.winnerLabel, style: TextStyle( fontSize: 12, - fontWeight: isLatest ? FontWeight.bold : FontWeight.w600, + fontWeight: isLatest + ? FontWeight.bold + : FontWeight.w600, color: isLatest - ? (isDarkMode ? Colors.white : const Color(0xFF1A1A1A)) + ? (isDarkMode + ? Colors.white + : const Color(0xFF1A1A1A)) : theme.colorScheme.secondary, ), ), @@ -668,9 +749,7 @@ class _SpinWheelScreenState extends ConsumerState { padding: const EdgeInsets.all(AppSpacing.m), decoration: BoxDecoration( color: theme.colorScheme.surface, - border: Border( - top: BorderSide(color: theme.dividerColor, width: 1), - ), + border: Border(top: BorderSide(color: theme.dividerColor, width: 1)), ), child: SafeArea( top: false, @@ -681,7 +760,9 @@ class _SpinWheelScreenState extends ConsumerState { style: ElevatedButton.styleFrom( backgroundColor: theme.colorScheme.primary, foregroundColor: theme.colorScheme.onPrimary, - disabledBackgroundColor: theme.colorScheme.primary.withValues(alpha: 0.5), + disabledBackgroundColor: theme.colorScheme.primary.withValues( + alpha: 0.5, + ), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(14), ), diff --git a/lib/features/spin_wheel/wheel_painter.dart b/lib/features/spin_wheel/wheel_painter.dart index 267103c..aa455a1 100644 --- a/lib/features/spin_wheel/wheel_painter.dart +++ b/lib/features/spin_wheel/wheel_painter.dart @@ -10,10 +10,7 @@ class WheelPainter extends CustomPainter { final List options; final bool isDarkMode; - const WheelPainter({ - required this.options, - required this.isDarkMode, - }); + const WheelPainter({required this.options, required this.isDarkMode}); @override void paint(Canvas canvas, Size size) { @@ -32,7 +29,8 @@ class WheelPainter extends CustomPainter { // 1. Draw Sector Bodies for (int i = 0; i < count; i++) { final double startAngle = SpinWheelMath.getSectorStartAngle(i, count); - final Color sectorColor = options[i].customColor ?? + final Color sectorColor = + options[i].customColor ?? SpinWheelMath.getSegmentColor(i, count, isDarkMode); final Paint sectorPaint = Paint() @@ -81,18 +79,22 @@ class WheelPainter extends CustomPainter { final double fontSize = count <= 4 ? 14.0 : count <= 8 - ? 12.0 - : count <= 12 - ? 10.5 - : 9.0; + ? 12.0 + : count <= 12 + ? 10.5 + : 9.0; final double maxLabelWidth = innerRadius * 0.48; for (int i = 0; i < count; i++) { final double centerAngle = SpinWheelMath.getSectorCenterAngle(i, count); - final Color sectorColor = options[i].customColor ?? + final Color sectorColor = + options[i].customColor ?? SpinWheelMath.getSegmentColor(i, count, isDarkMode); - final Color textColor = SpinWheelMath.getTextColorForSegment(sectorColor, isDarkMode); + final Color textColor = SpinWheelMath.getTextColorForSegment( + sectorColor, + isDarkMode, + ); canvas.save(); canvas.translate(center.dx, center.dy); @@ -121,18 +123,22 @@ class WheelPainter extends CustomPainter { // Position text along the radial arm (between center hub and outer rim) final double radialOffset = innerRadius * 0.42; - textPainter.paint( - canvas, - Offset(radialOffset, -textPainter.height / 2), - ); + textPainter.paint(canvas, Offset(radialOffset, -textPainter.height / 2)); canvas.restore(); } } - void _drawOuterRim(Canvas canvas, Offset center, double radius, double innerRadius) { + void _drawOuterRim( + Canvas canvas, + Offset center, + double radius, + double innerRadius, + ) { // Rim background stroke - final rimColor = isDarkMode ? const Color(0xFF1E1F24) : const Color(0xFF2C2D33); + final rimColor = isDarkMode + ? const Color(0xFF1E1F24) + : const Color(0xFF2C2D33); final Paint rimPaint = Paint() ..color = rimColor ..style = PaintingStyle.stroke @@ -142,7 +148,9 @@ class WheelPainter extends CustomPainter { // Subtle outer highlight ring final Paint highlightPaint = Paint() - ..color = (isDarkMode ? Colors.white : Colors.white).withValues(alpha: isDarkMode ? 0.12 : 0.35) + ..color = (isDarkMode ? Colors.white : Colors.white).withValues( + alpha: isDarkMode ? 0.12 : 0.35, + ) ..style = PaintingStyle.stroke ..strokeWidth = 1.0; canvas.drawCircle(center, radius - 0.5, highlightPaint); @@ -166,7 +174,8 @@ class WheelPainter extends CustomPainter { final double pegDistance = (radius + innerRadius) / 2; final Paint pegBodyPaint = Paint() - ..color = const Color(0xFFC18A42) // Warm bronze stud + ..color = + const Color(0xFFC18A42) // Warm bronze stud ..style = PaintingStyle.fill; final Paint pegHighlightPaint = Paint() @@ -201,7 +210,9 @@ class WheelPainter extends CustomPainter { canvas.drawCircle(center + const Offset(0, 2), hubRadius, shadowPaint); // 2. Hub Metallic Body - final hubBodyColor = isDarkMode ? const Color(0xFF22242A) : const Color(0xFFF3F0E8); + final hubBodyColor = isDarkMode + ? const Color(0xFF22242A) + : const Color(0xFFF3F0E8); final Paint hubPaint = Paint() ..color = hubBodyColor ..style = PaintingStyle.fill; @@ -209,14 +220,18 @@ class WheelPainter extends CustomPainter { // 3. Hub Concentric Engraved Ring final Paint engravedRingPaint = Paint() - ..color = (isDarkMode ? Colors.white : Colors.black).withValues(alpha: 0.15) + ..color = (isDarkMode ? Colors.white : Colors.black).withValues( + alpha: 0.15, + ) ..style = PaintingStyle.stroke ..strokeWidth = 1.2; canvas.drawCircle(center, hubRadius * 0.85, engravedRingPaint); // 4. Hub Outer Chamfer Rim final Paint bevelPaint = Paint() - ..color = (isDarkMode ? Colors.white : Colors.white).withValues(alpha: isDarkMode ? 0.15 : 0.6) + ..color = (isDarkMode ? Colors.white : Colors.white).withValues( + alpha: isDarkMode ? 0.15 : 0.6, + ) ..style = PaintingStyle.stroke ..strokeWidth = 1.5; canvas.drawCircle(center, hubRadius - 0.75, bevelPaint); @@ -249,7 +264,8 @@ class WheelPainter extends CustomPainter { path.close(); final Paint markPaint = Paint() - ..color = const Color(0xFFC18A42) // Warm Bronze Accent + ..color = + const Color(0xFFC18A42) // Warm Bronze Accent ..style = PaintingStyle.fill; canvas.drawPath(path, markPaint); @@ -272,4 +288,3 @@ class WheelPainter extends CustomPainter { return false; } } - diff --git a/lib/features/spin_wheel/wheel_pointer.dart b/lib/features/spin_wheel/wheel_pointer.dart index 61aad7c..7c3f013 100644 --- a/lib/features/spin_wheel/wheel_pointer.dart +++ b/lib/features/spin_wheel/wheel_pointer.dart @@ -61,7 +61,9 @@ class _PointerPainter extends CustomPainter { canvas.drawPath(path.shift(const Offset(0, 2)), shadowPaint); // 2. Base metallic body - final Color bodyColor = isDarkMode ? const Color(0xFF2E3036) : const Color(0xFFF3F0E8); + final Color bodyColor = isDarkMode + ? const Color(0xFF2E3036) + : const Color(0xFFF3F0E8); final Paint bodyPaint = Paint() ..color = bodyColor ..style = PaintingStyle.fill; @@ -76,7 +78,9 @@ class _PointerPainter extends CustomPainter { // 4. Center indicator ridge line final Paint ridgePaint = Paint() - ..color = isDarkMode ? Colors.white.withValues(alpha: 0.25) : Colors.black.withValues(alpha: 0.2) + ..color = isDarkMode + ? Colors.white.withValues(alpha: 0.25) + : Colors.black.withValues(alpha: 0.2) ..style = PaintingStyle.stroke ..strokeWidth = 1.0; canvas.drawLine(Offset(w * 0.5, 0), Offset(w * 0.5, h * 0.9), ridgePaint); @@ -90,7 +94,11 @@ class _PointerPainter extends CustomPainter { final Paint studDotPaint = Paint() ..color = Colors.white.withValues(alpha: 0.8) ..style = PaintingStyle.fill; - canvas.drawCircle(Offset(w * 0.5 - 0.5, h * 0.16 - 0.5), w * 0.04, studDotPaint); + canvas.drawCircle( + Offset(w * 0.5 - 0.5, h * 0.16 - 0.5), + w * 0.04, + studDotPaint, + ); } @override @@ -98,4 +106,3 @@ class _PointerPainter extends CustomPainter { return oldDelegate.isDarkMode != isDarkMode; } } - diff --git a/lib/features/team_generator/team_provider.dart b/lib/features/team_generator/team_provider.dart index a4108a2..00e106a 100644 --- a/lib/features/team_generator/team_provider.dart +++ b/lib/features/team_generator/team_provider.dart @@ -34,12 +34,15 @@ class TeamGeneratorState { class TeamNotifier extends StateNotifier { final Random _random = Random(); - TeamNotifier() : super(TeamGeneratorState( - players: [], - generatedTeams: [], - numberOfTeams: 2, - balanceRandomization: true, - )) { + TeamNotifier() + : super( + TeamGeneratorState( + players: [], + generatedTeams: [], + numberOfTeams: 2, + balanceRandomization: true, + ), + ) { _loadPlayers(); } @@ -75,7 +78,7 @@ class TeamNotifier extends StateNotifier { void generateTeams() { if (state.players.isEmpty) return; - + final shuffled = List.from(state.players)..shuffle(_random); final teams = List.generate(state.numberOfTeams, (_) => []); @@ -84,10 +87,11 @@ class TeamNotifier extends StateNotifier { } state = state.copyWith(generatedTeams: teams); - + // Save to matches history final box = StorageService.getMatchBox(); - final List history = box.get('team_matches', defaultValue: []) as List; + final List history = + box.get('team_matches', defaultValue: []) as List; final match = { 'date': DateTime.now().toIso8601String(), 'type': 'Team Generator', @@ -97,7 +101,10 @@ class TeamNotifier extends StateNotifier { box.put('team_matches', [...history, match]); // Analytics - AnalyticsService.trackTeamGenerated(state.numberOfTeams, state.players.length); + AnalyticsService.trackTeamGenerated( + state.numberOfTeams, + state.players.length, + ); } void clearAll() { @@ -106,6 +113,8 @@ class TeamNotifier extends StateNotifier { } } -final teamProvider = StateNotifierProvider((ref) { +final teamProvider = StateNotifierProvider(( + ref, +) { return TeamNotifier(); }); diff --git a/lib/features/team_generator/team_screen.dart b/lib/features/team_generator/team_screen.dart index 3ccb21d..53cc35d 100644 --- a/lib/features/team_generator/team_screen.dart +++ b/lib/features/team_generator/team_screen.dart @@ -7,7 +7,8 @@ class TeamGeneratorScreen extends ConsumerStatefulWidget { const TeamGeneratorScreen({super.key}); @override - ConsumerState createState() => _TeamGeneratorScreenState(); + ConsumerState createState() => + _TeamGeneratorScreenState(); } class _TeamGeneratorScreenState extends ConsumerState { @@ -97,7 +98,10 @@ class _TeamGeneratorScreenState extends ConsumerState { children: [ Padding( padding: const EdgeInsets.symmetric(horizontal: AppSpacing.m), - child: Text('Players (${players.length})', style: theme.textTheme.titleLarge), + child: Text( + 'Players (${players.length})', + style: theme.textTheme.titleLarge, + ), ), Expanded( child: ListView.builder( @@ -111,7 +115,8 @@ class _TeamGeneratorScreenState extends ConsumerState { title: Text(player), trailing: IconButton( icon: const Icon(Icons.remove_circle_outline), - onPressed: () => ref.read(teamProvider.notifier).removePlayer(player), + onPressed: () => + ref.read(teamProvider.notifier).removePlayer(player), ), ), ); @@ -133,7 +138,8 @@ class _TeamGeneratorScreenState extends ConsumerState { children: [ Text('Generated Teams', style: theme.textTheme.titleLarge), TextButton( - onPressed: () => ref.read(teamProvider.notifier).generateTeams(), + onPressed: () => + ref.read(teamProvider.notifier).generateTeams(), child: const Text('Shuffle Again'), ), ], @@ -154,13 +160,19 @@ class _TeamGeneratorScreenState extends ConsumerState { children: [ Text( 'Team ${index + 1}', - style: theme.textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold), + style: theme.textTheme.titleLarge?.copyWith( + fontWeight: FontWeight.bold, + ), ), const Divider(), - ...team.map((player) => Padding( - padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs), - child: Text(player, style: theme.textTheme.bodyLarge), - )), + ...team.map( + (player) => Padding( + padding: const EdgeInsets.symmetric( + vertical: AppSpacing.xs, + ), + child: Text(player, style: theme.textTheme.bodyLarge), + ), + ), ], ), ), @@ -210,12 +222,17 @@ class _TeamGeneratorScreenState extends ConsumerState { style: ElevatedButton.styleFrom( backgroundColor: theme.colorScheme.primary, foregroundColor: theme.colorScheme.onPrimary, - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), ), onPressed: teamState.players.length >= teamState.numberOfTeams ? () => ref.read(teamProvider.notifier).generateTeams() : null, - child: const Text('GENERATE TEAMS', style: TextStyle(fontWeight: FontWeight.bold)), + child: const Text( + 'GENERATE TEAMS', + style: TextStyle(fontWeight: FontWeight.bold), + ), ), ), ], diff --git a/lib/features/timer/domain/time_formatter.dart b/lib/features/timer/domain/time_formatter.dart index 030c4ae..5474516 100644 --- a/lib/features/timer/domain/time_formatter.dart +++ b/lib/features/timer/domain/time_formatter.dart @@ -19,7 +19,10 @@ class TimeFormatter { final hours = d.inHours; final minutes = (d.inMinutes % 60).toString().padLeft(2, '0'); final seconds = (d.inSeconds % 60).toString().padLeft(2, '0'); - final centiseconds = ((d.inMilliseconds % 1000) ~/ 10).toString().padLeft(2, '0'); + final centiseconds = ((d.inMilliseconds % 1000) ~/ 10).toString().padLeft( + 2, + '0', + ); if (hours > 0) { return '$hours:$minutes:$seconds.$centiseconds'; @@ -37,4 +40,3 @@ class TimeFormatter { return formatMmSs(d); } } - diff --git a/lib/features/timer/domain/timer_models.dart b/lib/features/timer/domain/timer_models.dart index 319ac62..475fcba 100644 --- a/lib/features/timer/domain/timer_models.dart +++ b/lib/features/timer/domain/timer_models.dart @@ -1,13 +1,7 @@ import 'package:flutter/foundation.dart'; /// Supported timing modes in PlayMate -enum TimerMode { - countdown, - timer, - stopwatch, - turn, - chess, -} +enum TimerMode { countdown, timer, stopwatch, turn, chess } extension TimerModeDetails on TimerMode { String get displayName { @@ -55,24 +49,20 @@ class StopwatchLap { }); Map toJson() => { - 'lapNumber': lapNumber, - 'splitTimeMs': splitTime.inMilliseconds, - 'totalTimeMs': totalTime.inMilliseconds, - }; + 'lapNumber': lapNumber, + 'splitTimeMs': splitTime.inMilliseconds, + 'totalTimeMs': totalTime.inMilliseconds, + }; factory StopwatchLap.fromJson(Map json) => StopwatchLap( - lapNumber: json['lapNumber'] as int, - splitTime: Duration(milliseconds: json['splitTimeMs'] as int), - totalTime: Duration(milliseconds: json['totalTimeMs'] as int), - ); + lapNumber: json['lapNumber'] as int, + splitTime: Duration(milliseconds: json['splitTimeMs'] as int), + totalTime: Duration(milliseconds: json['totalTimeMs'] as int), + ); } /// Interval phase for General / Round Timer. -enum IntervalPhase { - work, - rest, - complete, -} +enum IntervalPhase { work, rest, complete } /// Config for Round / Interval Timer. @immutable @@ -106,19 +96,10 @@ class TurnPlayer { final String id; final String name; - const TurnPlayer({ - required this.id, - required this.name, - }); + const TurnPlayer({required this.id, required this.name}); - TurnPlayer copyWith({ - String? id, - String? name, - }) { - return TurnPlayer( - id: id ?? this.id, - name: name ?? this.name, - ); + TurnPlayer copyWith({String? id, String? name}) { + return TurnPlayer(id: id ?? this.id, name: name ?? this.name); } } @@ -170,4 +151,3 @@ class ChessTimeControlPreset { ), ]; } - diff --git a/lib/features/timer/timer_provider.dart b/lib/features/timer/timer_provider.dart index a78c1cb..25324b2 100644 --- a/lib/features/timer/timer_provider.dart +++ b/lib/features/timer/timer_provider.dart @@ -35,8 +35,8 @@ class TimerNotifier extends StateNotifier { bool _hasFiredChessFlag = false; TimerNotifier({TimeSource? timeSource}) - : _timeSource = timeSource ?? const SystemTimeSource(), - super(TimerState.initial()) { + : _timeSource = timeSource ?? const SystemTimeSource(), + super(TimerState.initial()) { _loadPersistedSettings(); } @@ -44,10 +44,14 @@ class TimerNotifier extends StateNotifier { if (!StorageService.isBoxOpen(StorageService.settingsBoxName)) return; final box = StorageService.getSettingsBox(); - final countdownSec = box.get('timer_countdown_seconds', defaultValue: 300) as int; - final chessBaseSec = box.get('timer_chess_base_seconds', defaultValue: 300) as int; - final chessIncSec = box.get('timer_chess_inc_seconds', defaultValue: 0) as int; - final chessPreset = box.get('timer_chess_preset', defaultValue: 'blitz_5_0') as String; + final countdownSec = + box.get('timer_countdown_seconds', defaultValue: 300) as int; + final chessBaseSec = + box.get('timer_chess_base_seconds', defaultValue: 300) as int; + final chessIncSec = + box.get('timer_chess_inc_seconds', defaultValue: 0) as int; + final chessPreset = + box.get('timer_chess_preset', defaultValue: 'blitz_5_0') as String; state = state.copyWith( countdownInitial: Duration(seconds: countdownSec), @@ -61,7 +65,9 @@ class TimerNotifier extends StateNotifier { } Future _persistSettings() async { - if (!mounted || !StorageService.isBoxOpen(StorageService.settingsBoxName)) return; + if (!mounted || !StorageService.isBoxOpen(StorageService.settingsBoxName)) { + return; + } final box = StorageService.getSettingsBox(); await box.put('timer_countdown_seconds', state.countdownInitial.inSeconds); if (!mounted) return; @@ -154,7 +160,9 @@ class TimerNotifier extends StateNotifier { void removeTurnPlayer(int index) { if (state.turnPlayers.length <= 2) return; // Need at least 2 players final updated = List.from(state.turnPlayers)..removeAt(index); - final newActiveIndex = state.activePlayerIndex >= updated.length ? 0 : state.activePlayerIndex; + final newActiveIndex = state.activePlayerIndex >= updated.length + ? 0 + : state.activePlayerIndex; state = state.copyWith( turnPlayers: updated, activePlayerIndex: newActiveIndex, @@ -206,7 +214,10 @@ class TimerNotifier extends StateNotifier { // Guard against starting an already expired state without reset if (state.mode == TimerMode.countdown && state.countdownFinished) return; if (state.mode == TimerMode.timer && state.roundFinished) return; - if (state.mode == TimerMode.chess && (state.chessPlayerAFlagged || state.chessPlayerBFlagged)) return; + if (state.mode == TimerMode.chess && + (state.chessPlayerAFlagged || state.chessPlayerBFlagged)) { + return; + } _intervalStartUs = _timeSource.nowMicroseconds; state = state.copyWith(isRunning: true); @@ -231,7 +242,9 @@ class TimerNotifier extends StateNotifier { // Freeze monotonic delta into accumulated counters final int nowUs = _timeSource.nowMicroseconds; - final Duration intervalDelta = Duration(microseconds: nowUs - _intervalStartUs); + final Duration intervalDelta = Duration( + microseconds: nowUs - _intervalStartUs, + ); _commitIntervalDelta(intervalDelta); @@ -244,30 +257,43 @@ class TimerNotifier extends StateNotifier { switch (state.mode) { case TimerMode.countdown: - updatedCountdownRemaining = state.countdownInitial - _accumulatedCountdownElapsed; - if (updatedCountdownRemaining < Duration.zero) updatedCountdownRemaining = Duration.zero; + updatedCountdownRemaining = + state.countdownInitial - _accumulatedCountdownElapsed; + if (updatedCountdownRemaining < Duration.zero) { + updatedCountdownRemaining = Duration.zero; + } break; case TimerMode.timer: final target = state.intervalPhase == IntervalPhase.work ? state.roundConfig.workDuration : state.roundConfig.restDuration; updatedRoundRemaining = target - _accumulatedRoundElapsed; - if (updatedRoundRemaining < Duration.zero) updatedRoundRemaining = Duration.zero; + if (updatedRoundRemaining < Duration.zero) { + updatedRoundRemaining = Duration.zero; + } break; case TimerMode.stopwatch: updatedStopwatchElapsed = _accumulatedStopwatchElapsed; break; case TimerMode.turn: updatedTurnRemaining = state.turnDuration - _accumulatedTurnElapsed; - if (updatedTurnRemaining < Duration.zero) updatedTurnRemaining = Duration.zero; + if (updatedTurnRemaining < Duration.zero) { + updatedTurnRemaining = Duration.zero; + } break; case TimerMode.chess: if (state.isPlayerATurn) { - updatedChessPlayerARemaining = state.chessBaseTime - _accumulatedChessPlayerAElapsed; - if (updatedChessPlayerARemaining < Duration.zero) updatedChessPlayerARemaining = Duration.zero; + updatedChessPlayerARemaining = + state.chessBaseTime - _accumulatedChessPlayerAElapsed; + if (updatedChessPlayerARemaining < Duration.zero) { + updatedChessPlayerARemaining = Duration.zero; + } } else { - updatedChessPlayerBRemaining = state.chessBaseTime - _accumulatedChessPlayerBElapsed; - if (updatedChessPlayerBRemaining < Duration.zero) updatedChessPlayerBRemaining = Duration.zero; + updatedChessPlayerBRemaining = + state.chessBaseTime - _accumulatedChessPlayerBElapsed; + if (updatedChessPlayerBRemaining < Duration.zero) { + updatedChessPlayerBRemaining = Duration.zero; + } } break; } @@ -355,8 +381,11 @@ class TimerNotifier extends StateNotifier { if (state.mode != TimerMode.stopwatch || !state.isRunning) return; final int nowUs = _timeSource.nowMicroseconds; - final Duration currentIntervalDelta = Duration(microseconds: nowUs - _intervalStartUs); - final Duration currentTotal = _accumulatedStopwatchElapsed + currentIntervalDelta; + final Duration currentIntervalDelta = Duration( + microseconds: nowUs - _intervalStartUs, + ); + final Duration currentTotal = + _accumulatedStopwatchElapsed + currentIntervalDelta; final Duration split = currentTotal - _lastLapTotalTime; _lastLapTotalTime = currentTotal; @@ -391,7 +420,9 @@ class TimerNotifier extends StateNotifier { activePlayerIndex: nextIndex, turnRemaining: state.turnDuration, turnExpired: false, - currentTurnRound: isNewRound ? state.currentTurnRound + 1 : state.currentTurnRound, + currentTurnRound: isNewRound + ? state.currentTurnRound + 1 + : state.currentTurnRound, ); } @@ -410,24 +441,36 @@ class TimerNotifier extends StateNotifier { if (state.isPlayerATurn) { _accumulatedChessPlayerAElapsed += delta; // Apply increment to Player A who just finished move - final remaining = (state.chessBaseTime - _accumulatedChessPlayerAElapsed + state.chessIncrement); + final remaining = + (state.chessBaseTime - + _accumulatedChessPlayerAElapsed + + state.chessIncrement); state = state.copyWith( isPlayerATurn: false, - chessPlayerARemaining: remaining > Duration.zero ? remaining : Duration.zero, + chessPlayerARemaining: remaining > Duration.zero + ? remaining + : Duration.zero, chessPlayerAMoves: state.chessPlayerAMoves + 1, ); // Adjust accumulated so future ticks calculate from the incremented value - _accumulatedChessPlayerAElapsed = state.chessBaseTime - state.chessPlayerARemaining; + _accumulatedChessPlayerAElapsed = + state.chessBaseTime - state.chessPlayerARemaining; } else { _accumulatedChessPlayerBElapsed += delta; // Apply increment to Player B who just finished move - final remaining = (state.chessBaseTime - _accumulatedChessPlayerBElapsed + state.chessIncrement); + final remaining = + (state.chessBaseTime - + _accumulatedChessPlayerBElapsed + + state.chessIncrement); state = state.copyWith( isPlayerATurn: true, - chessPlayerBRemaining: remaining > Duration.zero ? remaining : Duration.zero, + chessPlayerBRemaining: remaining > Duration.zero + ? remaining + : Duration.zero, chessPlayerBMoves: state.chessPlayerBMoves + 1, ); - _accumulatedChessPlayerBElapsed = state.chessBaseTime - state.chessPlayerBRemaining; + _accumulatedChessPlayerBElapsed = + state.chessBaseTime - state.chessPlayerBRemaining; } } @@ -439,11 +482,14 @@ class TimerNotifier extends StateNotifier { if (!state.isRunning) return; final int nowUs = _timeSource.nowMicroseconds; - final Duration currentIntervalDelta = Duration(microseconds: nowUs - _intervalStartUs); + final Duration currentIntervalDelta = Duration( + microseconds: nowUs - _intervalStartUs, + ); switch (state.mode) { case TimerMode.countdown: - final totalElapsed = _accumulatedCountdownElapsed + currentIntervalDelta; + final totalElapsed = + _accumulatedCountdownElapsed + currentIntervalDelta; final remaining = state.countdownInitial - totalElapsed; if (remaining <= Duration.zero) { @@ -467,7 +513,8 @@ class TimerNotifier extends StateNotifier { break; case TimerMode.stopwatch: - final totalElapsed = _accumulatedStopwatchElapsed + currentIntervalDelta; + final totalElapsed = + _accumulatedStopwatchElapsed + currentIntervalDelta; state = state.copyWith(stopwatchElapsed: totalElapsed); break; @@ -551,7 +598,8 @@ class TimerNotifier extends StateNotifier { void _handleChessTick(Duration currentIntervalDelta) { if (state.isPlayerATurn) { - final totalElapsed = _accumulatedChessPlayerAElapsed + currentIntervalDelta; + final totalElapsed = + _accumulatedChessPlayerAElapsed + currentIntervalDelta; final remaining = state.chessBaseTime - totalElapsed; if (remaining <= Duration.zero) { @@ -569,7 +617,8 @@ class TimerNotifier extends StateNotifier { state = state.copyWith(chessPlayerARemaining: remaining); } } else { - final totalElapsed = _accumulatedChessPlayerBElapsed + currentIntervalDelta; + final totalElapsed = + _accumulatedChessPlayerBElapsed + currentIntervalDelta; final remaining = state.chessBaseTime - totalElapsed; if (remaining <= Duration.zero) { diff --git a/lib/features/timer/timer_screen.dart b/lib/features/timer/timer_screen.dart index 8e0d122..32d77ca 100644 --- a/lib/features/timer/timer_screen.dart +++ b/lib/features/timer/timer_screen.dart @@ -19,13 +19,23 @@ class TimerScreen extends ConsumerStatefulWidget { class _TimerScreenState extends ConsumerState { // Custom duration controllers - final TextEditingController _customMinutesController = TextEditingController(text: '5'); - final TextEditingController _customSecondsController = TextEditingController(text: '0'); + final TextEditingController _customMinutesController = TextEditingController( + text: '5', + ); + final TextEditingController _customSecondsController = TextEditingController( + text: '0', + ); // Round timer controllers - final TextEditingController _workMinController = TextEditingController(text: '3'); - final TextEditingController _restSecController = TextEditingController(text: '30'); - final TextEditingController _roundsController = TextEditingController(text: '3'); + final TextEditingController _workMinController = TextEditingController( + text: '3', + ); + final TextEditingController _restSecController = TextEditingController( + text: '30', + ); + final TextEditingController _roundsController = TextEditingController( + text: '3', + ); // Player name controller for turn timer final TextEditingController _newPlayerController = TextEditingController(); @@ -78,7 +88,10 @@ class _TimerScreenState extends ConsumerState { children: [ const Text( 'Countdown Presets', - style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + ), ), IconButton( icon: const Icon(Icons.close), @@ -94,10 +107,13 @@ class _TimerScreenState extends ConsumerState { final label = duration.inMinutes == 0 ? '${duration.inSeconds}s' : duration.inHours == 0 - ? '${duration.inMinutes}m' - : '${duration.inHours}h'; + ? '${duration.inMinutes}m' + : '${duration.inHours}h'; return ActionChip( - label: Text(label, style: const TextStyle(fontWeight: FontWeight.bold)), + label: Text( + label, + style: const TextStyle(fontWeight: FontWeight.bold), + ), onPressed: () { notifier.configureCountdown(duration); Navigator.pop(ctx); @@ -137,8 +153,10 @@ class _TimerScreenState extends ConsumerState { const SizedBox(width: 8), FilledButton( onPressed: () { - final mins = int.tryParse(_customMinutesController.text) ?? 0; - final secs = int.tryParse(_customSecondsController.text) ?? 0; + final mins = + int.tryParse(_customMinutesController.text) ?? 0; + final secs = + int.tryParse(_customSecondsController.text) ?? 0; final total = Duration(minutes: mins, seconds: secs); if (total > Duration.zero) { notifier.configureCountdown(total); @@ -181,7 +199,10 @@ class _TimerScreenState extends ConsumerState { children: [ const Text( 'Chess Time Controls', - style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + ), ), IconButton( icon: const Icon(Icons.close), @@ -200,13 +221,18 @@ class _TimerScreenState extends ConsumerState { title: Text( preset.name, style: TextStyle( - fontWeight: isSelected ? FontWeight.bold : FontWeight.w500, + fontWeight: isSelected + ? FontWeight.bold + : FontWeight.w500, color: isSelected ? const Color(0xFFC18A42) : null, ), ), subtitle: Text('${preset.baseTime.inMinutes} mins$incText'), trailing: isSelected - ? const Icon(Icons.check_circle, color: Color(0xFFC18A42)) + ? const Icon( + Icons.check_circle, + color: Color(0xFFC18A42), + ) : null, onTap: () { notifier.applyChessPreset(preset); @@ -249,7 +275,10 @@ class _TimerScreenState extends ConsumerState { children: [ Text( 'Players (${timerState.turnPlayers.length})', - style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + ), ), IconButton( icon: const Icon(Icons.close), @@ -259,7 +288,10 @@ class _TimerScreenState extends ConsumerState { ), ), Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 8, + ), child: Row( children: [ Expanded( @@ -273,7 +305,9 @@ class _TimerScreenState extends ConsumerState { ), onSubmitted: (val) { if (val.trim().isNotEmpty) { - ref.read(timerProvider.notifier).addTurnPlayer(val); + ref + .read(timerProvider.notifier) + .addTurnPlayer(val); _newPlayerController.clear(); } }, @@ -282,7 +316,9 @@ class _TimerScreenState extends ConsumerState { const SizedBox(width: 8), FilledButton( onPressed: () { - if (_newPlayerController.text.trim().isNotEmpty) { + if (_newPlayerController.text + .trim() + .isNotEmpty) { ref .read(timerProvider.notifier) .addTurnPlayer(_newPlayerController.text); @@ -306,7 +342,9 @@ class _TimerScreenState extends ConsumerState { return ListTile( leading: CircleAvatar( radius: 14, - backgroundColor: const Color(0xFFC18A42).withValues(alpha: 0.2), + backgroundColor: const Color( + 0xFFC18A42, + ).withValues(alpha: 0.2), child: Text( '${index + 1}', style: const TextStyle( @@ -320,12 +358,18 @@ class _TimerScreenState extends ConsumerState { trailing: IconButton( icon: Icon( Icons.delete_outline, - color: canDelete ? Colors.red.shade400 : Colors.grey, + color: canDelete + ? Colors.red.shade400 + : Colors.grey, ), onPressed: canDelete - ? () => ref.read(timerProvider.notifier).removeTurnPlayer(index) + ? () => ref + .read(timerProvider.notifier) + .removeTurnPlayer(index) : null, - tooltip: canDelete ? 'Remove player' : 'Minimum 2 players required', + tooltip: canDelete + ? 'Remove player' + : 'Minimum 2 players required', ), ); }, @@ -369,7 +413,10 @@ class _TimerScreenState extends ConsumerState { children: [ const Text( 'Configure Round Timer', - style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + ), ), IconButton( icon: const Icon(Icons.close), @@ -419,15 +466,19 @@ class _TimerScreenState extends ConsumerState { width: double.infinity, child: FilledButton( onPressed: () { - final workMins = int.tryParse(_workMinController.text) ?? 3; - final restSecs = int.tryParse(_restSecController.text) ?? 30; + final workMins = + int.tryParse(_workMinController.text) ?? 3; + final restSecs = + int.tryParse(_restSecController.text) ?? 30; final rounds = int.tryParse(_roundsController.text) ?? 3; - notifier.configureRoundTimer(RoundTimerConfig( - workDuration: Duration(minutes: workMins), - restDuration: Duration(seconds: restSecs), - totalRounds: rounds, - )); + notifier.configureRoundTimer( + RoundTimerConfig( + workDuration: Duration(minutes: workMins), + restDuration: Duration(seconds: restSecs), + totalRounds: rounds, + ), + ); Navigator.pop(ctx); }, child: const Text('APPLY SETTINGS'), @@ -458,25 +509,33 @@ class _TimerScreenState extends ConsumerState { if (timerState.mode == TimerMode.countdown) IconButton( icon: const Icon(Icons.tune), - onPressed: timerState.isRunning ? null : () => _showCountdownPresetsSheet(context), + onPressed: timerState.isRunning + ? null + : () => _showCountdownPresetsSheet(context), tooltip: 'Presets & Duration', ), if (timerState.mode == TimerMode.timer) IconButton( icon: const Icon(Icons.settings), - onPressed: timerState.isRunning ? null : () => _showRoundConfigSheet(context), + onPressed: timerState.isRunning + ? null + : () => _showRoundConfigSheet(context), tooltip: 'Round Settings', ), if (timerState.mode == TimerMode.turn) IconButton( icon: const Icon(Icons.group), - onPressed: timerState.isRunning ? null : () => _showTurnPlayersSheet(context), + onPressed: timerState.isRunning + ? null + : () => _showTurnPlayersSheet(context), tooltip: 'Manage Players', ), if (timerState.mode == TimerMode.chess) IconButton( icon: const Icon(Icons.tune), - onPressed: timerState.isRunning ? null : () => _showChessPresetsSheet(context), + onPressed: timerState.isRunning + ? null + : () => _showChessPresetsSheet(context), tooltip: 'Time Controls', ), IconButton( @@ -493,7 +552,8 @@ class _TimerScreenState extends ConsumerState { // 1. Top Mode Selector Chip Row TimerModeSelector( selectedMode: timerState.mode, - onModeChanged: (mode) => ref.read(timerProvider.notifier).setMode(mode), + onModeChanged: (mode) => + ref.read(timerProvider.notifier).setMode(mode), ), // 2. Mode Content Body @@ -501,7 +561,9 @@ class _TimerScreenState extends ConsumerState { child: Center( child: SingleChildScrollView( physics: const BouncingScrollPhysics(), - padding: const EdgeInsets.symmetric(horizontal: AppSpacing.m), + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.m, + ), child: _buildActiveModeContent(timerState, theme, isDark), ), ), @@ -517,7 +579,11 @@ class _TimerScreenState extends ConsumerState { ); } - Widget _buildActiveModeContent(TimerState timerState, ThemeData theme, bool isDark) { + Widget _buildActiveModeContent( + TimerState timerState, + ThemeData theme, + bool isDark, + ) { switch (timerState.mode) { case TimerMode.countdown: return _buildCountdownView(timerState, theme); @@ -541,8 +607,8 @@ class _TimerScreenState extends ConsumerState { final subtitle = timerState.countdownFinished ? 'COMPLETED!' : timerState.isRunning - ? 'Counting down' - : 'Paused / Ready'; + ? 'Counting down' + : 'Paused / Ready'; return Column( mainAxisAlignment: MainAxisAlignment.center, @@ -555,26 +621,41 @@ class _TimerScreenState extends ConsumerState { ), const SizedBox(height: 16), InkWell( - onTap: timerState.isRunning ? null : () => _showCountdownPresetsSheet(context), + onTap: timerState.isRunning + ? null + : () => _showCountdownPresetsSheet(context), borderRadius: BorderRadius.circular(14), child: Container( padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8), decoration: BoxDecoration( color: theme.colorScheme.surface, borderRadius: BorderRadius.circular(14), - border: Border.all(color: const Color(0xFFC18A42).withValues(alpha: 0.3)), + border: Border.all( + color: const Color(0xFFC18A42).withValues(alpha: 0.3), + ), ), child: Row( mainAxisSize: MainAxisSize.min, children: [ - const Icon(Icons.timer_outlined, size: 16, color: Color(0xFFC18A42)), + const Icon( + Icons.timer_outlined, + size: 16, + color: Color(0xFFC18A42), + ), const SizedBox(width: 6), Text( 'Initial: ${TimeFormatter.formatMmSs(timerState.countdownInitial)}', - style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 13), + style: const TextStyle( + fontWeight: FontWeight.bold, + fontSize: 13, + ), ), const SizedBox(width: 4), - const Icon(Icons.arrow_drop_down, size: 16, color: Color(0xFFC18A42)), + const Icon( + Icons.arrow_drop_down, + size: 16, + color: Color(0xFFC18A42), + ), ], ), ), @@ -583,7 +664,11 @@ class _TimerScreenState extends ConsumerState { ); } - Widget _buildRoundTimerView(TimerState timerState, ThemeData theme, bool isDark) { + Widget _buildRoundTimerView( + TimerState timerState, + ThemeData theme, + bool isDark, + ) { final formatted = TimeFormatter.formatMmSs(timerState.roundRemaining); final isWork = timerState.intervalPhase == IntervalPhase.work; final isDone = timerState.roundFinished; @@ -591,8 +676,8 @@ class _TimerScreenState extends ConsumerState { final badgeColor = isDone ? Colors.grey : isWork - ? (isDark ? const Color(0xFFC18A42) : const Color(0xFF1A1A1A)) - : Colors.blueAccent; + ? (isDark ? const Color(0xFFC18A42) : const Color(0xFF1A1A1A)) + : Colors.blueAccent; return Column( mainAxisAlignment: MainAxisAlignment.center, @@ -622,8 +707,8 @@ class _TimerScreenState extends ConsumerState { subtitle: isDone ? 'Great effort!' : timerState.isRunning - ? 'Stay focused' - : 'Paused', + ? 'Stay focused' + : 'Paused', fontSize: 84, isFlagged: isDone, ), @@ -632,7 +717,9 @@ class _TimerScreenState extends ConsumerState { } Widget _buildStopwatchView(TimerState timerState, ThemeData theme) { - final formatted = TimeFormatter.formatStopwatch(timerState.stopwatchElapsed); + final formatted = TimeFormatter.formatStopwatch( + timerState.stopwatchElapsed, + ); return Column( mainAxisAlignment: MainAxisAlignment.center, @@ -648,9 +735,14 @@ class _TimerScreenState extends ConsumerState { ); } - Widget _buildTurnTimerView(TimerState timerState, ThemeData theme, bool isDark) { + Widget _buildTurnTimerView( + TimerState timerState, + ThemeData theme, + bool isDark, + ) { final activePlayer = timerState.turnPlayers[timerState.activePlayerIndex]; - final nextPlayerIndex = (timerState.activePlayerIndex + 1) % timerState.turnPlayers.length; + final nextPlayerIndex = + (timerState.activePlayerIndex + 1) % timerState.turnPlayers.length; final nextPlayer = timerState.turnPlayers[nextPlayerIndex]; final formatted = TimeFormatter.formatMmSs(timerState.turnRemaining); @@ -669,12 +761,19 @@ class _TimerScreenState extends ConsumerState { children: [ Text( 'ROUND ${timerState.currentTurnRound}', - style: const TextStyle(fontSize: 11, fontWeight: FontWeight.bold, letterSpacing: 0.8), + style: const TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + letterSpacing: 0.8, + ), ), const SizedBox(height: 2), Text( activePlayer.name.toUpperCase(), - style: const TextStyle(fontSize: 22, fontWeight: FontWeight.w900), + style: const TextStyle( + fontSize: 22, + fontWeight: FontWeight.w900, + ), ), ], ), @@ -692,7 +791,11 @@ class _TimerScreenState extends ConsumerState { ); } - Widget _buildChessClockView(TimerState timerState, ThemeData theme, bool isDark) { + Widget _buildChessClockView( + TimerState timerState, + ThemeData theme, + bool isDark, + ) { return Column( children: [ // Player B (Top) - Rotated 180 degrees for face-to-face play @@ -731,7 +834,9 @@ class _TimerScreenState extends ConsumerState { style: ElevatedButton.styleFrom( backgroundColor: theme.colorScheme.primary, foregroundColor: theme.colorScheme.onPrimary, - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), ), onPressed: () { if (timerState.isRunning) { @@ -740,12 +845,17 @@ class _TimerScreenState extends ConsumerState { ref.read(timerProvider.notifier).start(); } }, - icon: Icon(timerState.isRunning ? Icons.pause : Icons.play_arrow, size: 18), + icon: Icon( + timerState.isRunning ? Icons.pause : Icons.play_arrow, + size: 18, + ), label: Text(timerState.isRunning ? 'PAUSE' : 'START'), ), IconButton( icon: const Icon(Icons.tune), - onPressed: timerState.isRunning ? null : () => _showChessPresetsSheet(context), + onPressed: timerState.isRunning + ? null + : () => _showChessPresetsSheet(context), tooltip: 'Time Controls', ), ], @@ -784,10 +894,10 @@ class _TimerScreenState extends ConsumerState { final bgColor = isFlagged ? Colors.red.withValues(alpha: 0.2) : isActive - ? (isDark - ? const Color(0xFFC18A42).withValues(alpha: 0.2) - : const Color(0xFF1A1A1A).withValues(alpha: 0.08)) - : Colors.transparent; + ? (isDark + ? const Color(0xFFC18A42).withValues(alpha: 0.2) + : const Color(0xFF1A1A1A).withValues(alpha: 0.08)) + : Colors.transparent; final borderColor = isActive ? const Color(0xFFC18A42) : Colors.transparent; @@ -813,14 +923,19 @@ class _TimerScreenState extends ConsumerState { fontSize: 14, fontWeight: FontWeight.bold, letterSpacing: 1.0, - color: isActive ? const Color(0xFFC18A42) : theme.colorScheme.secondary, + color: isActive + ? const Color(0xFFC18A42) + : theme.colorScheme.secondary, ), ), if (moves > 0) ...[ const SizedBox(width: 8), Text( '($moves moves)', - style: TextStyle(fontSize: 12, color: theme.colorScheme.secondary), + style: TextStyle( + fontSize: 12, + color: theme.colorScheme.secondary, + ), ), ], ], @@ -836,7 +951,11 @@ class _TimerScreenState extends ConsumerState { padding: EdgeInsets.only(top: 8.0), child: Text( 'TAP TO END MOVE', - style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12, letterSpacing: 0.5), + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 12, + letterSpacing: 0.5, + ), ), ), ], diff --git a/lib/features/timer/timer_state.dart b/lib/features/timer/timer_state.dart index 9e1ee0f..6c8c747 100644 --- a/lib/features/timer/timer_state.dart +++ b/lib/features/timer/timer_state.dart @@ -163,8 +163,10 @@ class TimerState { return TimerState( mode: mode ?? this.mode, isRunning: isRunning ?? this.isRunning, - countdownRemaining: countdownRemaining ?? remaining ?? this.countdownRemaining, - countdownInitial: countdownInitial ?? initialDuration ?? this.countdownInitial, + countdownRemaining: + countdownRemaining ?? remaining ?? this.countdownRemaining, + countdownInitial: + countdownInitial ?? initialDuration ?? this.countdownInitial, countdownFinished: countdownFinished ?? this.countdownFinished, roundConfig: roundConfig ?? this.roundConfig, currentRound: currentRound ?? this.currentRound, @@ -179,8 +181,10 @@ class TimerState { turnRemaining: turnRemaining ?? this.turnRemaining, currentTurnRound: currentTurnRound ?? this.currentTurnRound, turnExpired: turnExpired ?? this.turnExpired, - chessPlayerARemaining: chessPlayerARemaining ?? this.chessPlayerARemaining, - chessPlayerBRemaining: chessPlayerBRemaining ?? this.chessPlayerBRemaining, + chessPlayerARemaining: + chessPlayerARemaining ?? this.chessPlayerARemaining, + chessPlayerBRemaining: + chessPlayerBRemaining ?? this.chessPlayerBRemaining, chessBaseTime: chessBaseTime ?? this.chessBaseTime, chessIncrement: chessIncrement ?? this.chessIncrement, isPlayerATurn: isPlayerATurn ?? this.isPlayerATurn, diff --git a/lib/features/timer/widgets/lap_list.dart b/lib/features/timer/widgets/lap_list.dart index 3684e1e..388a964 100644 --- a/lib/features/timer/widgets/lap_list.dart +++ b/lib/features/timer/widgets/lap_list.dart @@ -5,10 +5,7 @@ import '../domain/timer_models.dart'; class LapList extends StatelessWidget { final List laps; - const LapList({ - super.key, - required this.laps, - }); + const LapList({super.key, required this.laps}); String _formatLapTime(Duration d) { final minutes = (d.inMinutes % 60).toString().padLeft(2, '0'); @@ -101,7 +98,10 @@ class LapList extends StatelessWidget { if (isSlowest) splitColor = Colors.orangeAccent.shade400; return Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 8, + ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ diff --git a/lib/features/timer/widgets/time_display.dart b/lib/features/timer/widgets/time_display.dart index 09d45fa..cdea5df 100644 --- a/lib/features/timer/widgets/time_display.dart +++ b/lib/features/timer/widgets/time_display.dart @@ -38,9 +38,7 @@ class TimeDisplay extends StatelessWidget { fontFamily: 'monospace', letterSpacing: -1.5, color: displayColor, - fontFeatures: const [ - FontFeature.tabularFigures(), - ], + fontFeatures: const [FontFeature.tabularFigures()], ), ), ), @@ -59,4 +57,3 @@ class TimeDisplay extends StatelessWidget { ); } } - diff --git a/lib/features/timer/widgets/timer_controls.dart b/lib/features/timer/widgets/timer_controls.dart index 85c14a4..e8608ee 100644 --- a/lib/features/timer/widgets/timer_controls.dart +++ b/lib/features/timer/widgets/timer_controls.dart @@ -28,7 +28,10 @@ class TimerControls extends StatelessWidget { final isDark = theme.brightness == Brightness.dark; return Container( - padding: const EdgeInsets.symmetric(horizontal: AppSpacing.m, vertical: 12), + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.m, + vertical: 12, + ), decoration: BoxDecoration( color: theme.colorScheme.surface, border: Border( @@ -49,14 +52,21 @@ class TimerControls extends StatelessWidget { style: OutlinedButton.styleFrom( minimumSize: const Size(0, 50), side: BorderSide( - color: isDark ? const Color(0xFF383838) : const Color(0xFFD0D0D0), + color: isDark + ? const Color(0xFF383838) + : const Color(0xFFD0D0D0), + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), ), - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), ), onPressed: onReset, child: const Text( 'RESET', - style: TextStyle(fontWeight: FontWeight.bold, letterSpacing: 0.5), + style: TextStyle( + fontWeight: FontWeight.bold, + letterSpacing: 0.5, + ), ), ), ), @@ -69,7 +79,9 @@ class TimerControls extends StatelessWidget { child: FilledButton.tonal( style: FilledButton.styleFrom( minimumSize: const Size(0, 50), - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), ), onPressed: isRunning ? onSecondaryAction : null, child: Row( @@ -84,7 +96,10 @@ class TimerControls extends StatelessWidget { secondaryActionLabel!, maxLines: 1, overflow: TextOverflow.ellipsis, - style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 13), + style: const TextStyle( + fontWeight: FontWeight.bold, + fontSize: 13, + ), ), ), ], @@ -103,7 +118,9 @@ class TimerControls extends StatelessWidget { foregroundColor: theme.colorScheme.onPrimary, minimumSize: const Size(0, 50), elevation: 0, - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), ), onPressed: isRunning ? onPause : onStart, child: Row( @@ -113,7 +130,10 @@ class TimerControls extends StatelessWidget { const SizedBox(width: 6), Text( isRunning ? 'PAUSE' : 'START', - style: const TextStyle(fontWeight: FontWeight.bold, letterSpacing: 0.8), + style: const TextStyle( + fontWeight: FontWeight.bold, + letterSpacing: 0.8, + ), ), ], ), diff --git a/lib/features/timer/widgets/timer_mode_selector.dart b/lib/features/timer/widgets/timer_mode_selector.dart index 6e4ac4f..29d4649 100644 --- a/lib/features/timer/widgets/timer_mode_selector.dart +++ b/lib/features/timer/widgets/timer_mode_selector.dart @@ -21,7 +21,10 @@ class TimerModeSelector extends StatelessWidget { return SingleChildScrollView( scrollDirection: Axis.horizontal, physics: const BouncingScrollPhysics(), - padding: const EdgeInsets.symmetric(horizontal: AppSpacing.m, vertical: 8.0), + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.m, + vertical: 8.0, + ), child: Row( mainAxisSize: MainAxisSize.min, children: TimerMode.values.map((mode) { @@ -40,16 +43,26 @@ class TimerModeSelector extends StatelessWidget { : (isDark ? Colors.white70 : Colors.black87), ), ), - selectedColor: isDark ? const Color(0xFFC18A42) : const Color(0xFF1A1A1A), - backgroundColor: isDark ? const Color(0xFF1E1E1E) : const Color(0xFFF0F0F0), + selectedColor: isDark + ? const Color(0xFFC18A42) + : const Color(0xFF1A1A1A), + backgroundColor: isDark + ? const Color(0xFF1E1E1E) + : const Color(0xFFF0F0F0), showCheckmark: false, side: BorderSide( color: isSelected - ? (isDark ? const Color(0xFFC18A42) : const Color(0xFF1A1A1A)) - : (isDark ? const Color(0xFF2C2C2C) : const Color(0xFFE0E0E0)), + ? (isDark + ? const Color(0xFFC18A42) + : const Color(0xFF1A1A1A)) + : (isDark + ? const Color(0xFF2C2C2C) + : const Color(0xFFE0E0E0)), width: 1.0, ), - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2), onSelected: (_) => onModeChanged(mode), ), diff --git a/lib/features/tournament/tournament_provider.dart b/lib/features/tournament/tournament_provider.dart index 4982010..04cbfa3 100644 --- a/lib/features/tournament/tournament_provider.dart +++ b/lib/features/tournament/tournament_provider.dart @@ -38,11 +38,8 @@ class TournamentState { } class TournamentNotifier extends StateNotifier { - TournamentNotifier() : super(TournamentState( - teams: [], - rounds: [], - isGenerated: false, - )); + TournamentNotifier() + : super(TournamentState(teams: [], rounds: [], isGenerated: false)); void addTeam(String name) { final cleaned = name.trim(); @@ -61,7 +58,12 @@ class TournamentNotifier extends StateNotifier { void generateBrackets() { final teamCount = state.teams.length; - if (teamCount != 4 && teamCount != 8 && teamCount != 16 && teamCount != 32) return; + if (teamCount != 4 && + teamCount != 8 && + teamCount != 16 && + teamCount != 32) { + return; + } final shuffled = List.from(state.teams)..shuffle(); final List rounds = []; @@ -72,26 +74,26 @@ class TournamentNotifier extends StateNotifier { round1Matches.add('${shuffled[i]} vs ${shuffled[i + 1]}'); } - rounds.add(TournamentRound( - matches: round1Matches, - winners: List.filled(round1Matches.length, ''), - )); + rounds.add( + TournamentRound( + matches: round1Matches, + winners: List.filled(round1Matches.length, ''), + ), + ); // Fill remaining rounds with empty placeholders int nextRoundMatchesCount = round1Matches.length ~/ 2; while (nextRoundMatchesCount > 0) { - rounds.add(TournamentRound( - matches: List.filled(nextRoundMatchesCount, 'TBD vs TBD'), - winners: List.filled(nextRoundMatchesCount, ''), - )); + rounds.add( + TournamentRound( + matches: List.filled(nextRoundMatchesCount, 'TBD vs TBD'), + winners: List.filled(nextRoundMatchesCount, ''), + ), + ); nextRoundMatchesCount ~/= 2; } - state = state.copyWith( - rounds: rounds, - isGenerated: true, - champion: null, - ); + state = state.copyWith(rounds: rounds, isGenerated: true, champion: null); AnalyticsService.trackTournamentCreated(teamCount); } @@ -125,7 +127,8 @@ class TournamentNotifier extends StateNotifier { if (matchIndex % 2 == 0) { // First slot in next match - nextMatches[nextMatchIndex] = '$winner vs ${teamsInNextMatch.length > 1 ? teamsInNextMatch[1] : 'TBD'}'; + nextMatches[nextMatchIndex] = + '$winner vs ${teamsInNextMatch.length > 1 ? teamsInNextMatch[1] : 'TBD'}'; } else { // Second slot in next match nextMatches[nextMatchIndex] = '${teamsInNextMatch[0]} vs $winner'; @@ -141,7 +144,8 @@ class TournamentNotifier extends StateNotifier { Future _saveTournament(String champion) async { final box = StorageService.getMatchBox(); - final List history = box.get('tournament_matches', defaultValue: []) as List; + final List history = + box.get('tournament_matches', defaultValue: []) as List; final match = { 'date': DateTime.now().toIso8601String(), @@ -163,6 +167,7 @@ class TournamentNotifier extends StateNotifier { } } -final tournamentProvider = StateNotifierProvider((ref) { - return TournamentNotifier(); -}); +final tournamentProvider = + StateNotifierProvider((ref) { + return TournamentNotifier(); + }); diff --git a/lib/features/tournament/tournament_screen.dart b/lib/features/tournament/tournament_screen.dart index e199007..5952e70 100644 --- a/lib/features/tournament/tournament_screen.dart +++ b/lib/features/tournament/tournament_screen.dart @@ -55,7 +55,11 @@ class _TournamentScreenState extends ConsumerState { final allowedCounts = [4, 8, 16, 32]; final remaining = allowedCounts.contains(tourState.teams.length) ? 0 - : allowedCounts.firstWhere((e) => e > tourState.teams.length, orElse: () => 32) - tourState.teams.length; + : allowedCounts.firstWhere( + (e) => e > tourState.teams.length, + orElse: () => 32, + ) - + tourState.teams.length; return Column( children: [ @@ -86,7 +90,9 @@ class _TournamentScreenState extends ConsumerState { padding: const EdgeInsets.symmetric(horizontal: AppSpacing.m), child: Text( 'Add $remaining more team(s) to hit the next valid bracket (4, 8, 16, or 32)', - style: theme.textTheme.bodyMedium?.copyWith(color: theme.colorScheme.secondary), + style: theme.textTheme.bodyMedium?.copyWith( + color: theme.colorScheme.secondary, + ), ), ), Expanded( @@ -99,7 +105,8 @@ class _TournamentScreenState extends ConsumerState { title: Text(team), trailing: IconButton( icon: const Icon(Icons.delete_outline), - onPressed: () => ref.read(tournamentProvider.notifier).removeTeam(team), + onPressed: () => + ref.read(tournamentProvider.notifier).removeTeam(team), ), ); }, @@ -114,12 +121,18 @@ class _TournamentScreenState extends ConsumerState { style: ElevatedButton.styleFrom( backgroundColor: theme.colorScheme.primary, foregroundColor: theme.colorScheme.onPrimary, - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), ), onPressed: remaining == 0 && tourState.teams.isNotEmpty - ? () => ref.read(tournamentProvider.notifier).generateBrackets() + ? () => + ref.read(tournamentProvider.notifier).generateBrackets() : null, - child: const Text('GENERATE BRACKET', style: TextStyle(fontWeight: FontWeight.bold)), + child: const Text( + 'GENERATE BRACKET', + style: TextStyle(fontWeight: FontWeight.bold), + ), ), ), ), @@ -140,7 +153,9 @@ class _TournamentScreenState extends ConsumerState { Text('CHAMPION!', style: theme.textTheme.headlineMedium), Text( tourState.champion!, - style: theme.textTheme.headlineLarge?.copyWith(fontWeight: FontWeight.bold), + style: theme.textTheme.headlineLarge?.copyWith( + fontWeight: FontWeight.bold, + ), ), const SizedBox(height: AppSpacing.l), ElevatedButton( @@ -165,7 +180,9 @@ class _TournamentScreenState extends ConsumerState { padding: const EdgeInsets.symmetric(vertical: AppSpacing.s), child: Text( 'Round ${roundIndex + 1}', - style: theme.textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold), + style: theme.textTheme.titleLarge?.copyWith( + fontWeight: FontWeight.bold, + ), ), ), ...List.generate(round.matches.length, (matchIndex) { @@ -185,16 +202,30 @@ class _TournamentScreenState extends ConsumerState { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - _buildTeamAdvanceRow(teamA, winner, roundIndex, matchIndex, theme), + _buildTeamAdvanceRow( + teamA, + winner, + roundIndex, + matchIndex, + theme, + ), const SizedBox(height: AppSpacing.s), - _buildTeamAdvanceRow(teamB, winner, roundIndex, matchIndex, theme), + _buildTeamAdvanceRow( + teamB, + winner, + roundIndex, + matchIndex, + theme, + ), ], ), if (winner.isEmpty && teamA != 'TBD' && teamB != 'TBD') Text( 'Select winner', - style: theme.textTheme.bodySmall?.copyWith(color: theme.colorScheme.secondary), - ) + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.secondary, + ), + ), ], ), ), @@ -219,10 +250,15 @@ class _TournamentScreenState extends ConsumerState { return InkWell( onTap: isClickable - ? () => ref.read(tournamentProvider.notifier).advanceWinner(roundIndex, matchIndex, team) + ? () => ref + .read(tournamentProvider.notifier) + .advanceWinner(roundIndex, matchIndex, team) : null, child: Padding( - padding: const EdgeInsets.symmetric(horizontal: AppSpacing.s, vertical: AppSpacing.xs), + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.s, + vertical: AppSpacing.xs, + ), child: Row( children: [ Icon( @@ -235,7 +271,9 @@ class _TournamentScreenState extends ConsumerState { team, style: theme.textTheme.bodyLarge?.copyWith( fontWeight: isWinner ? FontWeight.bold : FontWeight.normal, - decoration: winner.isNotEmpty && !isWinner ? TextDecoration.lineThrough : null, + decoration: winner.isNotEmpty && !isWinner + ? TextDecoration.lineThrough + : null, ), ), ], diff --git a/lib/main.dart b/lib/main.dart index 074583f..7e9f615 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -9,18 +9,14 @@ import 'services/storage_service.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); - + // Fast storage bootstrap for instantaneous frame rendering await StorageService.initialize(); // Asynchronous background telemetry initialization (non-blocking for splash) unawaited(FirebaseService.initialize()); - runApp( - const ProviderScope( - child: PlaymateApp(), - ), - ); + runApp(const ProviderScope(child: PlaymateApp())); } class PlaymateApp extends ConsumerWidget { diff --git a/lib/routes/router.dart b/lib/routes/router.dart index 2d80d0d..ba4e795 100644 --- a/lib/routes/router.dart +++ b/lib/routes/router.dart @@ -1,5 +1,8 @@ +import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; +import '../services/storage_service.dart'; import '../features/home/home_screen.dart'; +import '../features/onboarding/onboarding_screen.dart'; import '../features/dice/dice_screen.dart'; import '../features/coin/coin_screen.dart'; import '../features/team_generator/team_screen.dart'; @@ -14,64 +17,67 @@ import '../features/about/privacy_policy_screen.dart'; import '../features/about/terms_screen.dart'; import '../features/about/changelog_screen.dart'; -final GoRouter appRouter = GoRouter( - initialLocation: '/', - routes: [ - GoRoute( - path: '/', - builder: (context, state) => const HomeScreen(), - ), - GoRoute( - path: '/dice', - builder: (context, state) => const DiceScreen(), - ), - GoRoute( - path: '/coin', - builder: (context, state) => const CoinScreen(), - ), - GoRoute( - path: '/teams', - builder: (context, state) => const TeamGeneratorScreen(), - ), - GoRoute( - path: '/scores', - builder: (context, state) => const ScoreTrackerScreen(), - ), - GoRoute( - path: '/cricket', - builder: (context, state) => const CricketScreen(), - ), - GoRoute( - path: '/spin', - builder: (context, state) => const SpinWheelScreen(), - ), - GoRoute( - path: '/tournament', - builder: (context, state) => const TournamentScreen(), - ), - GoRoute( - path: '/timers', - builder: (context, state) => const TimerScreen(), - ), - GoRoute( - path: '/settings', - builder: (context, state) => const SettingsScreen(), - ), - GoRoute( - path: '/about', - builder: (context, state) => const AboutScreen(), - ), - GoRoute( - path: '/privacy', - builder: (context, state) => const PrivacyPolicyScreen(), - ), - GoRoute( - path: '/terms', - builder: (context, state) => const TermsScreen(), - ), - GoRoute( - path: '/changelog', - builder: (context, state) => const ChangelogScreen(), - ), - ], -); +GoRouter createAppRouter({String? initialLocation}) { + return GoRouter( + initialLocation: + initialLocation ?? + (StorageService.hasCompletedOnboarding() ? '/' : '/onboarding'), + redirect: (BuildContext context, GoRouterState state) { + final bool completed = StorageService.hasCompletedOnboarding(); + final bool isOnboarding = state.matchedLocation == '/onboarding'; + if (!completed && !isOnboarding) { + return '/onboarding'; + } + return null; + }, + routes: [ + GoRoute( + path: '/onboarding', + builder: (context, state) => const OnboardingScreen(), + ), + GoRoute(path: '/', builder: (context, state) => const HomeScreen()), + GoRoute(path: '/dice', builder: (context, state) => const DiceScreen()), + GoRoute(path: '/coin', builder: (context, state) => const CoinScreen()), + GoRoute( + path: '/teams', + builder: (context, state) => const TeamGeneratorScreen(), + ), + GoRoute( + path: '/scores', + builder: (context, state) => const ScoreTrackerScreen(), + ), + GoRoute( + path: '/cricket', + builder: (context, state) => const CricketScreen(), + ), + GoRoute( + path: '/spin', + builder: (context, state) => const SpinWheelScreen(), + ), + GoRoute( + path: '/tournament', + builder: (context, state) => const TournamentScreen(), + ), + GoRoute( + path: '/timers', + builder: (context, state) => const TimerScreen(), + ), + GoRoute( + path: '/settings', + builder: (context, state) => const SettingsScreen(), + ), + GoRoute(path: '/about', builder: (context, state) => const AboutScreen()), + GoRoute( + path: '/privacy', + builder: (context, state) => const PrivacyPolicyScreen(), + ), + GoRoute(path: '/terms', builder: (context, state) => const TermsScreen()), + GoRoute( + path: '/changelog', + builder: (context, state) => const ChangelogScreen(), + ), + ], + ); +} + +final GoRouter appRouter = createAppRouter(); diff --git a/lib/services/storage_service.dart b/lib/services/storage_service.dart index a737db0..8e2929f 100644 --- a/lib/services/storage_service.dart +++ b/lib/services/storage_service.dart @@ -8,7 +8,7 @@ class StorageService { static Future initialize() async { await Hive.initFlutter(); - + // Open all necessary boxes concurrently to minimize splash startup delay await Future.wait([ Hive.openBox(settingsBoxName), @@ -24,7 +24,20 @@ class StorageService { static Box getStatsBox() => Hive.box(statsBoxName); static bool isBoxOpen(String name) => Hive.isBoxOpen(name); + static const String hasCompletedOnboardingKey = 'hasCompletedOnboarding'; + // Helper getters/setters for simple state + static bool hasCompletedOnboarding() { + if (!isBoxOpen(settingsBoxName)) return false; + return getSettingsBox().get(hasCompletedOnboardingKey, defaultValue: false) + as bool; + } + + static Future setCompletedOnboarding(bool value) async { + if (!isBoxOpen(settingsBoxName)) return; + await getSettingsBox().put(hasCompletedOnboardingKey, value); + } + static bool isDarkMode() { return getSettingsBox().get('dark_mode', defaultValue: false) as bool; } diff --git a/lib/shared/responsive_layout.dart b/lib/shared/responsive_layout.dart index a5952b4..9bd073d 100644 --- a/lib/shared/responsive_layout.dart +++ b/lib/shared/responsive_layout.dart @@ -4,11 +4,7 @@ class ResponsiveLayout extends StatelessWidget { final Widget mobile; final Widget? tablet; - const ResponsiveLayout({ - super.key, - required this.mobile, - this.tablet, - }); + const ResponsiveLayout({super.key, required this.mobile, this.tablet}); static bool isMobile(BuildContext context) => MediaQuery.of(context).size.width < 600; diff --git a/pubspec.yaml b/pubspec.yaml index b435db7..badc9cf 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # In Windows, build-name is used as the major, minor, and patch parts # of the product and file versions while build-number is used as the build suffix. -version: 1.1.0+2 +version: 1.0.2+3 environment: sdk: ^3.11.4 diff --git a/test/about_flow_test.dart b/test/about_flow_test.dart index 69fd185..8973a15 100644 --- a/test/about_flow_test.dart +++ b/test/about_flow_test.dart @@ -24,56 +24,61 @@ void main() { await Hive.close(); }); - testWidgets('AboutScreen renders dynamic package info and developer details', (WidgetTester tester) async { - PackageInfo.setMockInitialValues( - appName: 'PlayMate', - packageName: 'com.sundramdotdev.playmate', - version: '1.0.0', - buildNumber: '1', - buildSignature: '', - ); - - await tester.pumpWidget( - ProviderScope( - overrides: [ - packageInfoProvider.overrideWith( - (ref) => PackageInfo( - appName: 'PlayMate', - packageName: 'com.sundramdotdev.playmate', - version: '1.0.0', - buildNumber: '1', - buildSignature: '', + testWidgets( + 'AboutScreen renders dynamic package info and developer details', + (WidgetTester tester) async { + PackageInfo.setMockInitialValues( + appName: 'PlayMate', + packageName: 'com.sundramdotdev.playmate', + version: '1.0.0', + buildNumber: '1', + buildSignature: '', + ); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + packageInfoProvider.overrideWith( + (ref) => PackageInfo( + appName: 'PlayMate', + packageName: 'com.sundramdotdev.playmate', + version: '1.0.0', + buildNumber: '1', + buildSignature: '', + ), ), + ], + child: MaterialApp( + theme: AppTheme.lightTheme, + home: const AboutScreen(), ), - ], - child: MaterialApp( - theme: AppTheme.lightTheme, - home: const AboutScreen(), ), - ), - ); - - await tester.pumpAndSettle(); - - expect(find.text('PlayMate'), findsWidgets); - expect(find.text('Everything you need for offline games.'), findsOneWidget); - expect(find.text('Sundramdotdev'), findsOneWidget); - expect(find.text('Official Website'), findsOneWidget); - expect(find.text('GitHub'), findsOneWidget); - expect(find.text('LinkedIn'), findsOneWidget); - expect(find.text('PlayMate Repository'), findsOneWidget); - expect(find.text('Instagram'), findsOneWidget); - expect(find.text('Privacy Policy'), findsOneWidget); - expect(find.text('Terms & Conditions'), findsOneWidget); - expect(find.text('What\'s New in 1.1.0'), findsOneWidget); - }); - - testWidgets('PrivacyPolicyScreen renders and scrolls without error', (WidgetTester tester) async { + ); + + await tester.pumpAndSettle(); + + expect(find.text('PlayMate'), findsWidgets); + expect( + find.text('Everything you need for offline games.'), + findsOneWidget, + ); + expect(find.text('Sundramdotdev'), findsOneWidget); + expect(find.text('Official Website'), findsOneWidget); + expect(find.text('GitHub'), findsOneWidget); + expect(find.text('LinkedIn'), findsOneWidget); + expect(find.text('PlayMate Repository'), findsOneWidget); + expect(find.text('Instagram'), findsOneWidget); + expect(find.text('Privacy Policy'), findsOneWidget); + expect(find.text('Terms & Conditions'), findsOneWidget); + expect(find.text('What\'s New in 1.0.2'), findsOneWidget); + }, + ); + + testWidgets('PrivacyPolicyScreen renders and scrolls without error', ( + WidgetTester tester, + ) async { await tester.pumpWidget( - MaterialApp( - theme: AppTheme.darkTheme, - home: const PrivacyPolicyScreen(), - ), + MaterialApp(theme: AppTheme.darkTheme, home: const PrivacyPolicyScreen()), ); await tester.pumpAndSettle(); @@ -85,10 +90,7 @@ void main() { testWidgets('TermsScreen renders correctly', (WidgetTester tester) async { await tester.pumpWidget( - MaterialApp( - theme: AppTheme.lightTheme, - home: const TermsScreen(), - ), + MaterialApp(theme: AppTheme.lightTheme, home: const TermsScreen()), ); await tester.pumpAndSettle(); @@ -97,12 +99,11 @@ void main() { expect(find.text('1. Acceptance of Terms'), findsOneWidget); }); - testWidgets('ChangelogScreen renders release milestones', (WidgetTester tester) async { + testWidgets('ChangelogScreen renders release milestones', ( + WidgetTester tester, + ) async { await tester.pumpWidget( - MaterialApp( - theme: AppTheme.darkTheme, - home: const ChangelogScreen(), - ), + MaterialApp(theme: AppTheme.darkTheme, home: const ChangelogScreen()), ); await tester.pumpAndSettle(); diff --git a/test/coin_system_test.dart b/test/coin_system_test.dart index 5ed5bb1..f99dad0 100644 --- a/test/coin_system_test.dart +++ b/test/coin_system_test.dart @@ -40,31 +40,45 @@ void main() { expect(CoinOrientation.isHeadsFacing(tailsAngle), isFalse); }); - test('calculateTargetFlipAngle lands deterministically on target side for any cycle count', () { - for (final targetSide in CoinSide.values) { - for (int cycles = 3; cycles <= 8; cycles++) { - final targetAngle = CoinOrientation.calculateTargetFlipAngle( - currentRx: 0.0, - targetSide: targetSide, - fullCycles: cycles, - ); - - // Verify cosine matches target side - final double cosVal = math.cos(targetAngle); - if (targetSide == CoinSide.heads) { - expect(cosVal, closeTo(1.0, 0.001), reason: 'Heads targetAngle must have cos=1'); - expect(CoinOrientation.isHeadsFacing(targetAngle), isTrue); - } else { - expect(cosVal, closeTo(-1.0, 0.001), reason: 'Tails targetAngle must have cos=-1'); - expect(CoinOrientation.isHeadsFacing(targetAngle), isFalse); + test( + 'calculateTargetFlipAngle lands deterministically on target side for any cycle count', + () { + for (final targetSide in CoinSide.values) { + for (int cycles = 3; cycles <= 8; cycles++) { + final targetAngle = CoinOrientation.calculateTargetFlipAngle( + currentRx: 0.0, + targetSide: targetSide, + fullCycles: cycles, + ); + + // Verify cosine matches target side + final double cosVal = math.cos(targetAngle); + if (targetSide == CoinSide.heads) { + expect( + cosVal, + closeTo(1.0, 0.001), + reason: 'Heads targetAngle must have cos=1', + ); + expect(CoinOrientation.isHeadsFacing(targetAngle), isTrue); + } else { + expect( + cosVal, + closeTo(-1.0, 0.001), + reason: 'Tails targetAngle must have cos=-1', + ); + expect(CoinOrientation.isHeadsFacing(targetAngle), isFalse); + } } } - } - }); + }, + ); test('Edge visibility reaches 1.0 when edge-on at 90 degrees', () { expect(CoinOrientation.getEdgeVisibility(0.0), closeTo(0.0, 0.001)); - expect(CoinOrientation.getEdgeVisibility(math.pi / 2), closeTo(1.0, 0.001)); + expect( + CoinOrientation.getEdgeVisibility(math.pi / 2), + closeTo(1.0, 0.001), + ); expect(CoinOrientation.getEdgeVisibility(math.pi), closeTo(0.0, 0.001)); }); }); @@ -90,35 +104,38 @@ void main() { expect(state.lastResult, equals(CoinSide.heads)); }); - test('Toss updates state to target side and records history after completion', () async { - final container = ProviderContainer(); - final future = container.read(coinProvider.notifier).toss(); - - // Immediately becomes isFlipping: true with non-null target result - final flippingState = container.read(coinProvider); - expect(flippingState.isFlipping, isTrue); - expect(flippingState.lastResult, isNotNull); - - // Duplicate toss while flipping is rejected - await container.read(coinProvider.notifier).toss(); - - // Await toss completion - await future; - - final settledState = container.read(coinProvider); - expect(settledState.isFlipping, isFalse); - expect(settledState.tossHistory.length, equals(1)); - expect(settledState.totalTosses, equals(1)); - expect(settledState.tossHistory.first, equals(settledState.lastResult)); - - if (settledState.lastResult == CoinSide.heads) { - expect(settledState.headsCount, equals(1)); - expect(settledState.tailsCount, equals(0)); - } else { - expect(settledState.headsCount, equals(0)); - expect(settledState.tailsCount, equals(1)); - } - }); + test( + 'Toss updates state to target side and records history after completion', + () async { + final container = ProviderContainer(); + final future = container.read(coinProvider.notifier).toss(); + + // Immediately becomes isFlipping: true with non-null target result + final flippingState = container.read(coinProvider); + expect(flippingState.isFlipping, isTrue); + expect(flippingState.lastResult, isNotNull); + + // Duplicate toss while flipping is rejected + await container.read(coinProvider.notifier).toss(); + + // Await toss completion + await future; + + final settledState = container.read(coinProvider); + expect(settledState.isFlipping, isFalse); + expect(settledState.tossHistory.length, equals(1)); + expect(settledState.totalTosses, equals(1)); + expect(settledState.tossHistory.first, equals(settledState.lastResult)); + + if (settledState.lastResult == CoinSide.heads) { + expect(settledState.headsCount, equals(1)); + expect(settledState.tailsCount, equals(0)); + } else { + expect(settledState.headsCount, equals(0)); + expect(settledState.tailsCount, equals(1)); + } + }, + ); test('Clear history clears toss history and resets counts', () { final container = ProviderContainer(); @@ -131,27 +148,28 @@ void main() { }); group('Coin UI Widgets & Semantics', () { - testWidgets('CoinFace renders both HEADS and TAILS with PlayMate branding', (tester) async { - for (final side in CoinSide.values) { - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: Center( - child: CoinFace( - side: side, - size: 150, - isDarkMode: false, + testWidgets( + 'CoinFace renders both HEADS and TAILS with PlayMate branding', + (tester) async { + for (final side in CoinSide.values) { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Center( + child: CoinFace(side: side, size: 150, isDarkMode: false), ), ), ), - ), - ); + ); - expect(find.byType(CoinFace), findsOneWidget); - } - }); + expect(find.byType(CoinFace), findsOneWidget); + } + }, + ); - testWidgets('PlayMateCoin renders tactile 3D coin with semantics', (tester) async { + testWidgets('PlayMateCoin renders tactile 3D coin with semantics', ( + tester, + ) async { bool tossRequested = false; await tester.pumpWidget( @@ -183,7 +201,9 @@ void main() { final testWidths = [320.0, 360.0, 390.0, 412.0, 768.0, 1024.0]; for (final width in testWidths) { - testWidgets('CoinScreen renders without overflow at ${width}px width', (tester) async { + testWidgets('CoinScreen renders without overflow at ${width}px width', ( + tester, + ) async { tester.view.physicalSize = Size(width, 800); tester.view.devicePixelRatio = 1.0; addTearDown(tester.view.resetPhysicalSize); diff --git a/test/dice_system_test.dart b/test/dice_system_test.dart index 1291fc9..8d7dbd4 100644 --- a/test/dice_system_test.dart +++ b/test/dice_system_test.dart @@ -51,50 +51,69 @@ void main() { expect(f4.localNormal.x, equals(-1.0)); }); - test('For every value 1 to 6, base rotation points the face normal at camera (0, 0, -1)', () { - for (int val = 1; val <= 6; val++) { - final rot = DiceFaceOrientation.getBaseEulerForValue(val); - final rotMatrix = Matrix4.identity() - ..rotateX(rot.x) - ..rotateY(rot.y) - ..rotateZ(rot.z); - - final targetFace = - DiceFaceOrientation.canonicalFaces.firstWhere((f) => f.value == val); - final s = rotMatrix.storage; - final nx = targetFace.localNormal.x; - final ny = targetFace.localNormal.y; - final nz = targetFace.localNormal.z; - - final worldZ = s[2] * nx + s[6] * ny + s[10] * nz; - final worldX = s[0] * nx + s[4] * ny + s[8] * nz; - final worldY = s[1] * nx + s[5] * ny + s[9] * nz; - - // Facing camera directly means normal Z is close to -1.0, X and Y close to 0.0 - expect(worldZ, closeTo(-1.0, 0.001), reason: 'Value $val must face camera'); - expect(worldX, closeTo(0.0, 0.001), reason: 'Value $val must have worldX=0'); - expect(worldY, closeTo(0.0, 0.001), reason: 'Value $val must have worldY=0'); - } - }); - - test('computeVisibleFaces returns at most 3 visible faces in depth order', () { - for (int val = 1; val <= 6; val++) { - final restingEuler = DiceFaceOrientation.getRestingEulerForValue(val); - final visible = DiceFaceOrientation.computeVisibleFaces( - cubeRotation: restingEuler, - halfExtent: 50.0, - ); - - expect(visible.length, inInclusiveRange(1, 3)); - // The winning face must always be in the visible set - expect(visible.any((f) => f.value == val), isTrue); - - // Painter's algorithm verification: elements sorted from greatest depthZ to least - for (int i = 0; i < visible.length - 1; i++) { - expect(visible[i].depthZ >= visible[i + 1].depthZ, isTrue); + test( + 'For every value 1 to 6, base rotation points the face normal at camera (0, 0, -1)', + () { + for (int val = 1; val <= 6; val++) { + final rot = DiceFaceOrientation.getBaseEulerForValue(val); + final rotMatrix = Matrix4.identity() + ..rotateX(rot.x) + ..rotateY(rot.y) + ..rotateZ(rot.z); + + final targetFace = DiceFaceOrientation.canonicalFaces.firstWhere( + (f) => f.value == val, + ); + final s = rotMatrix.storage; + final nx = targetFace.localNormal.x; + final ny = targetFace.localNormal.y; + final nz = targetFace.localNormal.z; + + final worldZ = s[2] * nx + s[6] * ny + s[10] * nz; + final worldX = s[0] * nx + s[4] * ny + s[8] * nz; + final worldY = s[1] * nx + s[5] * ny + s[9] * nz; + + // Facing camera directly means normal Z is close to -1.0, X and Y close to 0.0 + expect( + worldZ, + closeTo(-1.0, 0.001), + reason: 'Value $val must face camera', + ); + expect( + worldX, + closeTo(0.0, 0.001), + reason: 'Value $val must have worldX=0', + ); + expect( + worldY, + closeTo(0.0, 0.001), + reason: 'Value $val must have worldY=0', + ); } - } - }); + }, + ); + + test( + 'computeVisibleFaces returns at most 3 visible faces in depth order', + () { + for (int val = 1; val <= 6; val++) { + final restingEuler = DiceFaceOrientation.getRestingEulerForValue(val); + final visible = DiceFaceOrientation.computeVisibleFaces( + cubeRotation: restingEuler, + halfExtent: 50.0, + ); + + expect(visible.length, inInclusiveRange(1, 3)); + // The winning face must always be in the visible set + expect(visible.any((f) => f.value == val), isTrue); + + // Painter's algorithm verification: elements sorted from greatest depthZ to least + for (int i = 0; i < visible.length - 1; i++) { + expect(visible[i].depthZ >= visible[i + 1].depthZ, isTrue); + } + } + }, + ); }); group('Dice Logic & Riverpod Notifier', () { @@ -129,31 +148,39 @@ void main() { expect(state.totalSum, equals(12)); }); - test('Roll updates state to target rolls and records history after completion', () async { - final container = ProviderContainer(); - final future = container.read(diceProvider.notifier).roll(); - - // Immediately becomes isRolling: true with valid target rolls 1..6 - final rollingState = container.read(diceProvider); - expect(rollingState.isRolling, isTrue); - expect(rollingState.currentRolls.length, equals(1)); - expect(rollingState.currentRolls.first, inInclusiveRange(1, 6)); - - // Duplicate roll while rolling is rejected - await container.read(diceProvider.notifier).roll(); - - // Await roll completion - await future; - - final settledState = container.read(diceProvider); - expect(settledState.isRolling, isFalse); - expect(settledState.rollHistory.isNotEmpty, isTrue); - expect(settledState.rollHistory.first, equals(settledState.currentRolls)); - }); + test( + 'Roll updates state to target rolls and records history after completion', + () async { + final container = ProviderContainer(); + final future = container.read(diceProvider.notifier).roll(); + + // Immediately becomes isRolling: true with valid target rolls 1..6 + final rollingState = container.read(diceProvider); + expect(rollingState.isRolling, isTrue); + expect(rollingState.currentRolls.length, equals(1)); + expect(rollingState.currentRolls.first, inInclusiveRange(1, 6)); + + // Duplicate roll while rolling is rejected + await container.read(diceProvider.notifier).roll(); + + // Await roll completion + await future; + + final settledState = container.read(diceProvider); + expect(settledState.isRolling, isFalse); + expect(settledState.rollHistory.isNotEmpty, isTrue); + expect( + settledState.rollHistory.first, + equals(settledState.currentRolls), + ); + }, + ); }); group('Dice UI Widgets & Semantics', () { - testWidgets('DicePips renders correct pip counts and PlayMate brand mark', (tester) async { + testWidgets('DicePips renders correct pip counts and PlayMate brand mark', ( + tester, + ) async { for (int val = 1; val <= 6; val++) { await tester.pumpWidget( MaterialApp( @@ -170,11 +197,16 @@ void main() { ); expect(find.byType(DicePips), findsOneWidget); - expect(DicePips.normalizedPipOffsets[val]!.length, equals(val == 1 ? 1 : val)); + expect( + DicePips.normalizedPipOffsets[val]!.length, + equals(val == 1 ? 1 : val), + ); } }); - testWidgets('PlayMateDice renders tactile 3D die with semantics', (tester) async { + testWidgets('PlayMateDice renders tactile 3D die with semantics', ( + tester, + ) async { bool rollRequested = false; await tester.pumpWidget( @@ -202,7 +234,9 @@ void main() { expect(rollRequested, isTrue); }); - testWidgets('DiceRollerView coordinates multi-dice layout (4 dice)', (tester) async { + testWidgets('DiceRollerView coordinates multi-dice layout (4 dice)', ( + tester, + ) async { await tester.pumpWidget( MaterialApp( home: Scaffold( @@ -230,7 +264,9 @@ void main() { final testWidths = [320.0, 360.0, 390.0, 412.0, 768.0]; for (final width in testWidths) { - testWidgets('DiceScreen renders without overflow at ${width}px width', (tester) async { + testWidgets('DiceScreen renders without overflow at ${width}px width', ( + tester, + ) async { tester.view.physicalSize = Size(width, 800); tester.view.devicePixelRatio = 1.0; addTearDown(tester.view.resetPhysicalSize); diff --git a/test/onboarding_test.dart b/test/onboarding_test.dart new file mode 100644 index 0000000..21219ce --- /dev/null +++ b/test/onboarding_test.dart @@ -0,0 +1,400 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive_flutter/hive_flutter.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:playmate/core/theme.dart'; +import 'package:playmate/features/about/package_info_provider.dart'; +import 'package:playmate/features/onboarding/onboarding_screen.dart'; +import 'package:playmate/features/onboarding/widgets/dice_onboarding_visual.dart'; +import 'package:playmate/features/onboarding/widgets/essentials_onboarding_visual.dart'; +import 'package:playmate/features/onboarding/widgets/onboarding_page_indicator.dart'; +import 'package:playmate/features/onboarding/widgets/welcome_onboarding_visual.dart'; +import 'package:playmate/features/settings/settings_screen.dart'; +import 'package:playmate/routes/router.dart'; +import 'package:playmate/services/storage_service.dart'; + +void main() { + setUpAll(() async { + PackageInfo.setMockInitialValues( + appName: 'PlayMate', + packageName: 'com.sundramdotdev.playmate', + version: '1.0.2', + buildNumber: '3', + buildSignature: '', + ); + Hive.init('test_hive_onboarding'); + await Hive.openBox(StorageService.settingsBoxName); + await Hive.openBox(StorageService.matchBoxName); + await Hive.openBox(StorageService.achievementsBoxName); + await Hive.openBox(StorageService.statsBoxName); + }); + + tearDownAll(() async { + await Hive.close(); + }); + + setUp(() async { + final box = StorageService.getSettingsBox(); + await box.delete(StorageService.hasCompletedOnboardingKey); + }); + + group('Onboarding Persistence & Unit Tests', () { + test('Initial onboarding status is false on fresh install', () { + expect(StorageService.hasCompletedOnboarding(), isFalse); + }); + + test('Completing onboarding persists true in settings box', () async { + await StorageService.setCompletedOnboarding(true); + expect(StorageService.hasCompletedOnboarding(), isTrue); + }); + + test('Skipping onboarding persists true in settings box', () async { + await StorageService.setCompletedOnboarding(true); + expect(StorageService.hasCompletedOnboarding(), isTrue); + }); + + test( + 'Replay does not delete or alter match and user preferences', + () async { + await StorageService.setCompletedOnboarding(true); + await StorageService.setDarkMode(true); + await StorageService.getSettingsBox().put( + 'timer_countdown_seconds', + 180, + ); + + expect(StorageService.hasCompletedOnboarding(), isTrue); + expect(StorageService.isDarkMode(), isTrue); + expect( + StorageService.getSettingsBox().get('timer_countdown_seconds'), + equals(180), + ); + + // Replay preserves data + expect(StorageService.hasCompletedOnboarding(), isTrue); + expect(StorageService.isDarkMode(), isTrue); + }, + ); + }); + + group('Onboarding UI & Widget Rendering Tests', () { + testWidgets( + 'OnboardingPageIndicator renders correct dot counts and active state', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + theme: AppTheme.lightTheme, + home: const Scaffold( + body: Center( + child: OnboardingPageIndicator(currentPage: 0, pageCount: 3), + ), + ), + ), + ); + + expect(find.byType(OnboardingPageIndicator), findsOneWidget); + expect(find.byType(AnimatedContainer), findsNWidgets(3)); + expect(find.bySemanticsLabel('Page 1 of 3'), findsOneWidget); + }, + ); + + testWidgets('Visual components render without errors', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + MaterialApp( + theme: AppTheme.lightTheme, + home: const Scaffold( + body: SingleChildScrollView( + child: Column( + children: [ + DiceOnboardingVisual(size: 150), + EssentialsOnboardingVisual(size: 150), + WelcomeOnboardingVisual(size: 150), + ], + ), + ), + ), + ), + ); + + await tester.pump(const Duration(milliseconds: 100)); + expect(find.byType(DiceOnboardingVisual), findsOneWidget); + expect(find.byType(EssentialsOnboardingVisual), findsOneWidget); + expect(find.byType(WelcomeOnboardingVisual), findsOneWidget); + }); + + testWidgets( + 'OnboardingScreen displays 3 pages with approved copy and transitions', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + theme: AppTheme.lightTheme, + home: const OnboardingScreen(), + ), + ); + + await tester.pumpAndSettle(); + + // Page 1: Introduction verification + expect(find.text('Make every moment a game.'), findsOneWidget); + expect( + find.text( + 'From spontaneous decisions to unforgettable game nights, everything you need to play is right here.', + ), + findsOneWidget, + ); + expect(find.text('Continue'), findsOneWidget); + expect(find.text('Skip'), findsOneWidget); + + // Advance to Page 2: Features + await tester.tap(find.text('Continue')); + await tester.pumpAndSettle(); + + expect(find.text('All your game-night essentials.'), findsOneWidget); + expect( + find.text( + 'Roll, flip, spin, keep score, build teams, and manage every moment without switching between apps.', + ), + findsOneWidget, + ); + expect(find.text('Back'), findsOneWidget); + expect(find.text('Continue'), findsOneWidget); + expect(find.text('Skip'), findsOneWidget); + + // Test Back navigation to Page 1 + await tester.tap(find.text('Back')); + await tester.pumpAndSettle(); + expect(find.text('Make every moment a game.'), findsOneWidget); + + // Re-advance to Page 2 then Page 3 + await tester.tap(find.text('Continue')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Continue')); + await tester.pumpAndSettle(); + + // Page 3: Final Welcome verification + expect(find.text('Less setup. More playing.'), findsOneWidget); + expect( + find.text( + 'Your next game night starts here. Pick a tool, bring everyone together, and let the fun begin.', + ), + findsOneWidget, + ); + expect(find.text("Let's Play"), findsOneWidget); + expect(find.text('Back'), findsOneWidget); + // Skip should be hidden on final welcome page + expect(find.text('Skip'), findsNothing); + }, + ); + }); + + group('Onboarding Navigation & Routing Integration Tests', () { + testWidgets( + 'Tapping Skip completes onboarding and persists completion state', + (WidgetTester tester) async { + await tester.runAsync(() async { + await StorageService.setCompletedOnboarding(false); + }); + bool completed = false; + + await tester.pumpWidget( + MaterialApp( + theme: AppTheme.lightTheme, + home: OnboardingScreen(onFinish: () => completed = true), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('Skip'), findsOneWidget); + await tester.runAsync(() async { + await tester.tap(find.text('Skip')); + await Future.delayed(const Duration(milliseconds: 50)); + }); + await tester.pumpAndSettle(); + + expect(StorageService.hasCompletedOnboarding(), isTrue); + expect(completed, isTrue); + }, + ); + + testWidgets( + "Tapping Let's Play on page 3 completes onboarding and persists state", + (WidgetTester tester) async { + await tester.runAsync(() async { + await StorageService.setCompletedOnboarding(false); + }); + bool completed = false; + + await tester.pumpWidget( + MaterialApp( + theme: AppTheme.lightTheme, + home: OnboardingScreen(onFinish: () => completed = true), + ), + ); + await tester.pumpAndSettle(); + + // Navigate to Page 2 + await tester.tap(find.text('Continue')); + await tester.pumpAndSettle(); + + // Navigate to Page 3 + await tester.tap(find.text('Continue')); + await tester.pumpAndSettle(); + + // Tap Let's Play + expect(find.text("Let's Play"), findsOneWidget); + await tester.runAsync(() async { + await tester.tap(find.text("Let's Play")); + await Future.delayed(const Duration(milliseconds: 50)); + }); + await tester.pumpAndSettle(); + + // Verify completion persisted + expect(StorageService.hasCompletedOnboarding(), isTrue); + expect(completed, isTrue); + }, + ); + + test( + 'Router redirect policy routes first-time user to /onboarding', + () async { + await StorageService.setCompletedOnboarding(false); + final router = createAppRouter(); + expect(StorageService.hasCompletedOnboarding(), isFalse); + expect( + router.routeInformationProvider.value.uri.path, + equals('/onboarding'), + ); + }, + ); + + test( + 'Router redirect policy routes returning user directly to /', + () async { + await StorageService.setCompletedOnboarding(true); + final router = createAppRouter(); + expect(StorageService.hasCompletedOnboarding(), isTrue); + expect(router.routeInformationProvider.value.uri.path, equals('/')); + }, + ); + + testWidgets( + 'Settings screen renders cleanly without Replay Onboarding and preserves user data', + (WidgetTester tester) async { + await tester.runAsync( + () async => StorageService.setCompletedOnboarding(true), + ); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + packageInfoProvider.overrideWith( + (ref) => PackageInfo( + appName: 'PlayMate', + packageName: 'com.sundramdotdev.playmate', + version: '1.0.2', + buildNumber: '3', + buildSignature: '', + ), + ), + ], + child: MaterialApp( + theme: AppTheme.lightTheme, + home: const Scaffold(body: SettingsScreen()), + ), + ), + ); + await tester.pumpAndSettle(); + + // Verify Settings does not contain Replay Onboarding tile + expect(find.text('Replay Onboarding'), findsNothing); + expect( + find.text( + 'PLAYMATE v1.0.2\nEverything you need for offline games.\nDeveloped by Sundramdotdev', + ), + findsOneWidget, + ); + + // Verify onboarding completion is still true + expect(StorageService.hasCompletedOnboarding(), isTrue); + }, + ); + }); + + group('Responsive Layout Tests Across Widths', () { + final testWidths = [ + 320.0, + 360.0, + 375.0, + 390.0, + 412.0, + 600.0, + 768.0, + 1024.0, + ]; + + for (final width in testWidths) { + testWidgets( + 'OnboardingScreen renders with zero overflow at ${width}px width', + (WidgetTester tester) async { + tester.view.physicalSize = Size(width * 2, 800 * 2); + tester.view.devicePixelRatio = 2.0; + addTearDown(() { + tester.view.resetPhysicalSize(); + tester.view.resetDevicePixelRatio(); + }); + + await tester.pumpWidget( + MaterialApp( + theme: AppTheme.lightTheme, + home: const OnboardingScreen(), + ), + ); + + await tester.pumpAndSettle(); + + expect(find.text('Make every moment a game.'), findsOneWidget); + expect(tester.takeException(), isNull); + + // Test next page + await tester.tap(find.text('Continue')); + await tester.pumpAndSettle(); + expect(find.text('All your game-night essentials.'), findsOneWidget); + expect(tester.takeException(), isNull); + + // Test page 3 + await tester.tap(find.text('Continue')); + await tester.pumpAndSettle(); + expect(find.text('Less setup. More playing.'), findsOneWidget); + expect(tester.takeException(), isNull); + }, + ); + } + + testWidgets( + 'OnboardingScreen renders with zero overflow on short device (320x568)', + (WidgetTester tester) async { + tester.view.physicalSize = const Size(320 * 2, 568 * 2); + tester.view.devicePixelRatio = 2.0; + addTearDown(() { + tester.view.resetPhysicalSize(); + tester.view.resetDevicePixelRatio(); + }); + + await tester.pumpWidget( + MaterialApp( + theme: AppTheme.darkTheme, + home: const OnboardingScreen(), + ), + ); + + await tester.pumpAndSettle(); + + expect(find.text('Make every moment a game.'), findsOneWidget); + expect(tester.takeException(), isNull); + }, + ); + }); +} diff --git a/test/spin_wheel_system_test.dart b/test/spin_wheel_system_test.dart index 8df275a..739c310 100644 --- a/test/spin_wheel_system_test.dart +++ b/test/spin_wheel_system_test.dart @@ -31,112 +31,156 @@ void main() { expect(SpinWheelMath.getSweepAngle(8), closeTo(math.pi / 4, 0.0001)); }); - test('calculateTargetRotation places winning sector center exactly at Top pointer for all N', () { - for (int count = 2; count <= 12; count++) { - for (int winningIndex = 0; winningIndex < count; winningIndex++) { - final target = SpinWheelMath.calculateTargetRotation( + test( + 'calculateTargetRotation places winning sector center exactly at Top pointer for all N', + () { + for (int count = 2; count <= 12; count++) { + for (int winningIndex = 0; winningIndex < count; winningIndex++) { + final target = SpinWheelMath.calculateTargetRotation( + currentRotation: 0.0, + winningIndex: winningIndex, + count: count, + revolutions: 6, + ); + + // Sector center angle on unrotated wheel: -pi/2 + (winningIndex + 0.5) * sweep + // When rotated by target, the position of that sector center in screen space is: + // centerAngle + target + final sweep = SpinWheelMath.getSweepAngle(count); + final centerAngle = -math.pi / 2 + (winningIndex + 0.5) * sweep; + final finalScreenAngle = (centerAngle + target) % (2 * math.pi); + + // Pointer is at -pi/2, which is 3*pi/2 mod 2pi + final expectedPointer = (-math.pi / 2) % (2 * math.pi); + final diff = + (finalScreenAngle - expectedPointer).abs() % (2 * math.pi); + final shortestDist = math.min(diff, 2 * math.pi - diff); + + expect( + shortestDist, + lessThan(0.0001), + reason: 'Failed for count=$count, winningIndex=$winningIndex', + ); + } + } + }, + ); + + test( + 'getIndexUnderPointer accurately retrieves sector under pointer for any rotation', + () { + const count = 4; + for (int i = 0; i < count; i++) { + final rot = SpinWheelMath.calculateTargetRotation( currentRotation: 0.0, - winningIndex: winningIndex, + winningIndex: i, count: count, - revolutions: 6, + revolutions: 5, ); - - // Sector center angle on unrotated wheel: -pi/2 + (winningIndex + 0.5) * sweep - // When rotated by target, the position of that sector center in screen space is: - // centerAngle + target - final sweep = SpinWheelMath.getSweepAngle(count); - final centerAngle = -math.pi / 2 + (winningIndex + 0.5) * sweep; - final finalScreenAngle = (centerAngle + target) % (2 * math.pi); - - // Pointer is at -pi/2, which is 3*pi/2 mod 2pi - final expectedPointer = (-math.pi / 2) % (2 * math.pi); - final diff = (finalScreenAngle - expectedPointer).abs() % (2 * math.pi); - final shortestDist = math.min(diff, 2 * math.pi - diff); - - expect( - shortestDist, - lessThan(0.0001), - reason: 'Failed for count=$count, winningIndex=$winningIndex', + final detected = SpinWheelMath.getIndexUnderPointer( + rotation: rot, + count: count, ); + expect(detected, equals(i)); } - } - }); - - test('getIndexUnderPointer accurately retrieves sector under pointer for any rotation', () { - const count = 4; - for (int i = 0; i < count; i++) { - final rot = SpinWheelMath.calculateTargetRotation( - currentRotation: 0.0, - winningIndex: i, - count: count, - revolutions: 5, - ); - final detected = SpinWheelMath.getIndexUnderPointer(rotation: rot, count: count); - expect(detected, equals(i)); - } - }); - - test('Curated palettes guarantee contrast for odd and even segment counts', () { - for (int count = 2; count <= 10; count++) { - for (int i = 0; i < count; i++) { - final lightColor = SpinWheelMath.getSegmentColor(i, count, false); - final darkColor = SpinWheelMath.getSegmentColor(i, count, true); - expect(lightColor, isNotNull); - expect(darkColor, isNotNull); - - final lightTextColor = SpinWheelMath.getTextColorForSegment(lightColor, false); - final darkTextColor = SpinWheelMath.getTextColorForSegment(darkColor, true); - expect(lightTextColor, isNotNull); - expect(darkTextColor, isNotNull); + }, + ); + + test( + 'Curated palettes guarantee contrast for odd and even segment counts', + () { + for (int count = 2; count <= 10; count++) { + for (int i = 0; i < count; i++) { + final lightColor = SpinWheelMath.getSegmentColor(i, count, false); + final darkColor = SpinWheelMath.getSegmentColor(i, count, true); + expect(lightColor, isNotNull); + expect(darkColor, isNotNull); + + final lightTextColor = SpinWheelMath.getTextColorForSegment( + lightColor, + false, + ); + final darkTextColor = SpinWheelMath.getTextColorForSegment( + darkColor, + true, + ); + expect(lightTextColor, isNotNull); + expect(darkTextColor, isNotNull); + } } - } - }); + }, + ); }); group('Spin Wheel Riverpod Notifier & State', () { - test('Initial state loads Truth or Dare preset with at least 4 options', () { - final container = ProviderContainer(); - addTearDown(container.dispose); - - final state = container.read(spinWheelProvider); - expect(state.options.length, greaterThanOrEqualTo(4)); - expect(state.isSpinning, isFalse); - expect(state.selectedWinner, isNull); - }); + test( + 'Initial state loads Truth or Dare preset with at least 4 options', + () { + final container = ProviderContainer(); + addTearDown(container.dispose); + + final state = container.read(spinWheelProvider); + expect(state.options.length, greaterThanOrEqualTo(4)); + expect(state.isSpinning, isFalse); + expect(state.selectedWinner, isNull); + }, + ); + + test( + 'Add, update, and remove options maintain minimum 2 options constraint', + () { + final container = ProviderContainer(); + addTearDown(container.dispose); + + final notifier = container.read(spinWheelProvider.notifier); + + // Add option + notifier.addOption('New Option'); + expect( + container + .read(spinWheelProvider) + .options + .any((o) => o.label == 'New Option'), + isTrue, + ); - test('Add, update, and remove options maintain minimum 2 options constraint', () { - final container = ProviderContainer(); - addTearDown(container.dispose); + // Update option + final opt = container + .read(spinWheelProvider) + .options + .firstWhere((o) => o.label == 'New Option'); + notifier.updateOption(opt.id, 'Updated Option'); + expect( + container + .read(spinWheelProvider) + .options + .any((o) => o.label == 'Updated Option'), + isTrue, + ); - final notifier = container.read(spinWheelProvider.notifier); + // Attempt to remove down to below 2 options + while (container.read(spinWheelProvider).options.length > 2) { + notifier.removeOptionById( + container.read(spinWheelProvider).options.first.id, + ); + } + expect(container.read(spinWheelProvider).options.length, equals(2)); - // Add option - notifier.addOption('New Option'); - expect(container.read(spinWheelProvider).options.any((o) => o.label == 'New Option'), isTrue); - - // Update option - final opt = container.read(spinWheelProvider).options.firstWhere((o) => o.label == 'New Option'); - notifier.updateOption(opt.id, 'Updated Option'); - expect(container.read(spinWheelProvider).options.any((o) => o.label == 'Updated Option'), isTrue); - - // Attempt to remove down to below 2 options - while (container.read(spinWheelProvider).options.length > 2) { - notifier.removeOptionById(container.read(spinWheelProvider).options.first.id); - } - expect(container.read(spinWheelProvider).options.length, equals(2)); - - // Cannot remove below 2 - final remainingId = container.read(spinWheelProvider).options.first.id; - notifier.removeOptionById(remainingId); - expect(container.read(spinWheelProvider).options.length, equals(2)); - }); + // Cannot remove below 2 + final remainingId = container.read(spinWheelProvider).options.first.id; + notifier.removeOptionById(remainingId); + expect(container.read(spinWheelProvider).options.length, equals(2)); + }, + ); test('Apply preset switches options and resets winner', () { final container = ProviderContainer(); addTearDown(container.dispose); final notifier = container.read(spinWheelProvider.notifier); - final foodPreset = SpinWheelPreset.builtInPresets.firstWhere((p) => p.id == 'food_picker'); + final foodPreset = SpinWheelPreset.builtInPresets.firstWhere( + (p) => p.id == 'food_picker', + ); notifier.applyPreset(foodPreset); final state = container.read(spinWheelProvider); @@ -163,30 +207,38 @@ void main() { expect(settledState.isSpinning, isFalse); expect(settledState.selectedWinner, isNotNull); expect(settledState.history.length, equals(1)); - expect(settledState.history.first.winnerLabel, equals(settledState.selectedWinner!.label)); + expect( + settledState.history.first.winnerLabel, + equals(settledState.selectedWinner!.label), + ); }); - test('Remove winner eliminates current winner and clears winner selection', () async { - final container = ProviderContainer(); - addTearDown(container.dispose); + test( + 'Remove winner eliminates current winner and clears winner selection', + () async { + final container = ProviderContainer(); + addTearDown(container.dispose); - final notifier = container.read(spinWheelProvider.notifier); - await notifier.spin(); + final notifier = container.read(spinWheelProvider.notifier); + await notifier.spin(); - final winner = container.read(spinWheelProvider).selectedWinner!; - final initialCount = container.read(spinWheelProvider).options.length; + final winner = container.read(spinWheelProvider).selectedWinner!; + final initialCount = container.read(spinWheelProvider).options.length; - notifier.removeWinner(); + notifier.removeWinner(); - final state = container.read(spinWheelProvider); - expect(state.options.length, equals(initialCount - 1)); - expect(state.options.any((o) => o.id == winner.id), isFalse); - expect(state.selectedWinner, isNull); - }); + final state = container.read(spinWheelProvider); + expect(state.options.length, equals(initialCount - 1)); + expect(state.options.any((o) => o.id == winner.id), isFalse); + expect(state.selectedWinner, isNull); + }, + ); }); group('Spin Wheel UI Components & Painting', () { - testWidgets('WheelPointer renders without errors in light and dark mode', (tester) async { + testWidgets('WheelPointer renders without errors in light and dark mode', ( + tester, + ) async { await tester.pumpWidget( const MaterialApp( home: Scaffold( @@ -210,58 +262,35 @@ void main() { expect(find.byType(WheelPointer), findsOneWidget); }); - testWidgets('PlayMateSpinWheel renders hero wheel with custom painter and pointer', (tester) async { - final options = [ - const WheelOption(id: '1', label: 'One'), - const WheelOption(id: '2', label: 'Two'), - const WheelOption(id: '3', label: 'Three'), - ]; + testWidgets( + 'PlayMateSpinWheel renders hero wheel with custom painter and pointer', + (tester) async { + final options = [ + const WheelOption(id: '1', label: 'One'), + const WheelOption(id: '2', label: 'Two'), + const WheelOption(id: '3', label: 'Three'), + ]; - await tester.pumpWidget( - MaterialApp( - theme: AppTheme.lightTheme, - home: Scaffold( - body: Center( - child: PlayMateSpinWheel( - options: options, - size: 260.0, + await tester.pumpWidget( + MaterialApp( + theme: AppTheme.lightTheme, + home: Scaffold( + body: Center( + child: PlayMateSpinWheel(options: options, size: 260.0), ), ), ), - ), - ); - - expect(find.byType(PlayMateSpinWheel), findsOneWidget); - expect(find.byType(WheelPointer), findsOneWidget); - expect(find.byType(CustomPaint), findsWidgets); - }); - - testWidgets('SpinWheelScreen renders full interface with controls and zero overflow', (tester) async { - await tester.pumpWidget( - ProviderScope( - child: MaterialApp( - theme: AppTheme.lightTheme, - home: const SpinWheelScreen(), - ), - ), - ); - - expect(find.text('Spin Wheel'), findsOneWidget); - expect(find.text('SPIN WHEEL'), findsOneWidget); - expect(find.byType(PlayMateSpinWheel), findsOneWidget); - }); - }); - - group('Responsive Layout Testing Across Screen Widths', () { - final testWidths = [320.0, 360.0, 390.0, 412.0, 768.0, 1024.0]; - - for (final width in testWidths) { - testWidgets('SpinWheelScreen renders without overflow at ${width}px width', (tester) async { - tester.view.physicalSize = Size(width, 800); - tester.view.devicePixelRatio = 1.0; - addTearDown(tester.view.resetPhysicalSize); - addTearDown(tester.view.resetDevicePixelRatio); + ); + expect(find.byType(PlayMateSpinWheel), findsOneWidget); + expect(find.byType(WheelPointer), findsOneWidget); + expect(find.byType(CustomPaint), findsWidgets); + }, + ); + + testWidgets( + 'SpinWheelScreen renders full interface with controls and zero overflow', + (tester) async { await tester.pumpWidget( ProviderScope( child: MaterialApp( @@ -271,11 +300,44 @@ void main() { ), ); - await tester.pump(); - expect(tester.takeException(), isNull, reason: 'No exception or overflow at width $width'); expect(find.text('Spin Wheel'), findsOneWidget); + expect(find.text('SPIN WHEEL'), findsOneWidget); expect(find.byType(PlayMateSpinWheel), findsOneWidget); - }); + }, + ); + }); + + group('Responsive Layout Testing Across Screen Widths', () { + final testWidths = [320.0, 360.0, 390.0, 412.0, 768.0, 1024.0]; + + for (final width in testWidths) { + testWidgets( + 'SpinWheelScreen renders without overflow at ${width}px width', + (tester) async { + tester.view.physicalSize = Size(width, 800); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + theme: AppTheme.lightTheme, + home: const SpinWheelScreen(), + ), + ), + ); + + await tester.pump(); + expect( + tester.takeException(), + isNull, + reason: 'No exception or overflow at width $width', + ); + expect(find.text('Spin Wheel'), findsOneWidget); + expect(find.byType(PlayMateSpinWheel), findsOneWidget); + }, + ); } }); } diff --git a/test/timer_system_test.dart b/test/timer_system_test.dart index 3ab138c..2a44808 100644 --- a/test/timer_system_test.dart +++ b/test/timer_system_test.dart @@ -30,21 +30,36 @@ void main() { group('TimeFormatter Unit Tests', () { test('formatMmSs formats MM:SS and HH:MM:SS accurately', () { expect(TimeFormatter.formatMmSs(Duration.zero), equals('00:00')); - expect(TimeFormatter.formatMmSs(const Duration(seconds: 45)), equals('00:45')); - expect(TimeFormatter.formatMmSs(const Duration(minutes: 5, seconds: 9)), equals('05:09')); - expect(TimeFormatter.formatMmSs(const Duration(hours: 1, minutes: 2, seconds: 3)), equals('1:02:03')); + expect( + TimeFormatter.formatMmSs(const Duration(seconds: 45)), + equals('00:45'), + ); + expect( + TimeFormatter.formatMmSs(const Duration(minutes: 5, seconds: 9)), + equals('05:09'), + ); + expect( + TimeFormatter.formatMmSs( + const Duration(hours: 1, minutes: 2, seconds: 3), + ), + equals('1:02:03'), + ); }); test('formatStopwatch includes centiseconds', () { expect( - TimeFormatter.formatStopwatch(const Duration(minutes: 1, seconds: 23, milliseconds: 450)), + TimeFormatter.formatStopwatch( + const Duration(minutes: 1, seconds: 23, milliseconds: 450), + ), equals('01:23.45'), ); }); test('formatChess shows tenths when under 10 seconds', () { expect( - TimeFormatter.formatChess(const Duration(seconds: 7, milliseconds: 400)), + TimeFormatter.formatChess( + const Duration(seconds: 7, milliseconds: 400), + ), equals('7.4s'), ); expect( @@ -75,7 +90,10 @@ void main() { test('Initial mode is Countdown at 5 minutes', () { expect(notifier.state.mode, equals(TimerMode.countdown)); - expect(notifier.state.countdownRemaining, equals(const Duration(minutes: 5))); + expect( + notifier.state.countdownRemaining, + equals(const Duration(minutes: 5)), + ); expect(notifier.state.isRunning, isFalse); }); @@ -89,14 +107,20 @@ void main() { notifier.stop(); expect(notifier.state.isRunning, isFalse); - expect(notifier.state.countdownRemaining, equals(const Duration(seconds: 45))); + expect( + notifier.state.countdownRemaining, + equals(const Duration(seconds: 45)), + ); // Resume and advance another 10 seconds notifier.start(); timeSource.advance(const Duration(seconds: 10)); notifier.stop(); - expect(notifier.state.countdownRemaining, equals(const Duration(seconds: 35))); + expect( + notifier.state.countdownRemaining, + equals(const Duration(seconds: 35)), + ); }); test('Countdown: Reset restores initial duration', () { @@ -105,9 +129,15 @@ void main() { timeSource.advance(const Duration(seconds: 30)); notifier.stop(); - expect(notifier.state.countdownRemaining, equals(const Duration(seconds: 90))); + expect( + notifier.state.countdownRemaining, + equals(const Duration(seconds: 90)), + ); notifier.reset(); - expect(notifier.state.countdownRemaining, equals(const Duration(minutes: 2))); + expect( + notifier.state.countdownRemaining, + equals(const Duration(minutes: 2)), + ); }); test('Stopwatch: Elapsed time accumulation and lap recording', () { @@ -116,7 +146,10 @@ void main() { timeSource.advance(const Duration(seconds: 10, milliseconds: 500)); notifier.stop(); - expect(notifier.state.stopwatchElapsed, equals(const Duration(seconds: 10, milliseconds: 500))); + expect( + notifier.state.stopwatchElapsed, + equals(const Duration(seconds: 10, milliseconds: 500)), + ); // Record lap while running notifier.start(); @@ -125,15 +158,24 @@ void main() { expect(notifier.state.stopwatchLaps.length, equals(1)); expect(notifier.state.stopwatchLaps.first.lapNumber, equals(1)); - expect(notifier.state.stopwatchLaps.first.totalTime, equals(const Duration(seconds: 15, milliseconds: 500))); - expect(notifier.state.stopwatchLaps.first.splitTime, equals(const Duration(seconds: 15, milliseconds: 500))); + expect( + notifier.state.stopwatchLaps.first.totalTime, + equals(const Duration(seconds: 15, milliseconds: 500)), + ); + expect( + notifier.state.stopwatchLaps.first.splitTime, + equals(const Duration(seconds: 15, milliseconds: 500)), + ); timeSource.advance(const Duration(seconds: 4)); notifier.recordStopwatchLap(); expect(notifier.state.stopwatchLaps.length, equals(2)); expect(notifier.state.stopwatchLaps.first.lapNumber, equals(2)); - expect(notifier.state.stopwatchLaps.first.splitTime, equals(const Duration(seconds: 4))); + expect( + notifier.state.stopwatchLaps.first.splitTime, + equals(const Duration(seconds: 4)), + ); }); test('Turn Timer: Advances players and increments round on loop', () { @@ -146,17 +188,26 @@ void main() { ], ); - expect(notifier.state.turnPlayers[notifier.state.activePlayerIndex].name, equals('Alice')); + expect( + notifier.state.turnPlayers[notifier.state.activePlayerIndex].name, + equals('Alice'), + ); expect(notifier.state.currentTurnRound, equals(1)); // Advance turn to Bob notifier.advanceTurn(); - expect(notifier.state.turnPlayers[notifier.state.activePlayerIndex].name, equals('Bob')); + expect( + notifier.state.turnPlayers[notifier.state.activePlayerIndex].name, + equals('Bob'), + ); expect(notifier.state.currentTurnRound, equals(1)); // Advance turn back to Alice (New round) notifier.advanceTurn(); - expect(notifier.state.turnPlayers[notifier.state.activePlayerIndex].name, equals('Alice')); + expect( + notifier.state.turnPlayers[notifier.state.activePlayerIndex].name, + equals('Alice'), + ); expect(notifier.state.currentTurnRound, equals(2)); }); @@ -177,7 +228,10 @@ void main() { expect(notifier.state.isPlayerATurn, isFalse); expect(notifier.state.chessPlayerAMoves, equals(1)); // Remaining = 3m - 10s + 2s inc = 2m 52s = 172s - expect(notifier.state.chessPlayerARemaining, equals(const Duration(seconds: 172))); + expect( + notifier.state.chessPlayerARemaining, + equals(const Duration(seconds: 172)), + ); // Player B thinks for 5 seconds and moves timeSource.advance(const Duration(seconds: 5)); @@ -186,16 +240,21 @@ void main() { expect(notifier.state.isPlayerATurn, isTrue); expect(notifier.state.chessPlayerBMoves, equals(1)); // Remaining = 3m - 5s + 2s inc = 2m 57s = 177s - expect(notifier.state.chessPlayerBRemaining, equals(const Duration(seconds: 177))); + expect( + notifier.state.chessPlayerBRemaining, + equals(const Duration(seconds: 177)), + ); }); test('Round Timer: Work and rest transitions', () { notifier.setMode(TimerMode.timer); - notifier.configureRoundTimer(const RoundTimerConfig( - workDuration: Duration(minutes: 1), - restDuration: Duration(seconds: 15), - totalRounds: 2, - )); + notifier.configureRoundTimer( + const RoundTimerConfig( + workDuration: Duration(minutes: 1), + restDuration: Duration(seconds: 15), + totalRounds: 2, + ), + ); expect(notifier.state.currentRound, equals(1)); expect(notifier.state.intervalPhase, equals(IntervalPhase.work)); @@ -229,14 +288,13 @@ void main() { expect(selected, equals(TimerMode.stopwatch)); }); - testWidgets('TimeDisplay renders tabular digits without error', (tester) async { + testWidgets('TimeDisplay renders tabular digits without error', ( + tester, + ) async { await tester.pumpWidget( const MaterialApp( home: Scaffold( - body: TimeDisplay( - formattedTime: '05:00', - subtitle: 'Ready', - ), + body: TimeDisplay(formattedTime: '05:00', subtitle: 'Ready'), ), ), ); @@ -245,17 +303,25 @@ void main() { expect(find.text('Ready'), findsOneWidget); }); - testWidgets('LapList renders list of laps with split calculations', (tester) async { + testWidgets('LapList renders list of laps with split calculations', ( + tester, + ) async { const laps = [ - StopwatchLap(lapNumber: 2, splitTime: Duration(seconds: 4), totalTime: Duration(seconds: 14)), - StopwatchLap(lapNumber: 1, splitTime: Duration(seconds: 10), totalTime: Duration(seconds: 10)), + StopwatchLap( + lapNumber: 2, + splitTime: Duration(seconds: 4), + totalTime: Duration(seconds: 14), + ), + StopwatchLap( + lapNumber: 1, + splitTime: Duration(seconds: 10), + totalTime: Duration(seconds: 10), + ), ]; await tester.pumpWidget( const MaterialApp( - home: Scaffold( - body: LapList(laps: laps), - ), + home: Scaffold(body: LapList(laps: laps)), ), ); @@ -263,7 +329,9 @@ void main() { expect(find.text('Lap 01'), findsOneWidget); }); - testWidgets('TimerControls renders Start, Pause, and Reset', (tester) async { + testWidgets('TimerControls renders Start, Pause, and Reset', ( + tester, + ) async { bool resetPressed = false; bool startPressed = false; @@ -295,7 +363,9 @@ void main() { final testWidths = [320.0, 360.0, 390.0, 412.0, 768.0, 1024.0]; for (final width in testWidths) { - testWidgets('TimerScreen renders without overflow at ${width}px width', (tester) async { + testWidgets('TimerScreen renders without overflow at ${width}px width', ( + tester, + ) async { tester.view.physicalSize = Size(width, 800); tester.view.devicePixelRatio = 1.0; addTearDown(tester.view.resetPhysicalSize); @@ -311,13 +381,19 @@ void main() { ); await tester.pump(); - expect(tester.takeException(), isNull, reason: 'No exception or overflow at width $width'); + expect( + tester.takeException(), + isNull, + reason: 'No exception or overflow at width $width', + ); expect(find.text('Timers'), findsOneWidget); expect(find.byType(TimerModeSelector), findsOneWidget); }); } - testWidgets('TimerScreen switches between all 5 modes without error', (tester) async { + testWidgets('TimerScreen switches between all 5 modes without error', ( + tester, + ) async { await tester.pumpWidget( ProviderScope( child: MaterialApp( diff --git a/test/widget_test.dart b/test/widget_test.dart index b9ba935..8af1bbc 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -6,6 +6,8 @@ import 'package:hive_flutter/hive_flutter.dart'; import 'package:playmate/core/theme.dart'; import 'package:playmate/routes/router.dart'; +import 'package:playmate/services/storage_service.dart'; + void main() { setUpAll(() async { // Initialize Hive for testing with an in-memory path @@ -14,6 +16,7 @@ void main() { await Hive.openBox('matches'); await Hive.openBox('achievements'); await Hive.openBox('statistics'); + await StorageService.setCompletedOnboarding(true); }); tearDownAll(() async { @@ -44,7 +47,9 @@ void main() { expect(find.text('Score Tracker'), findsWidgets); }); - testWidgets('Dice Roller screen navigates correctly', (WidgetTester tester) async { + testWidgets('Dice Roller screen navigates correctly', ( + WidgetTester tester, + ) async { await tester.pumpWidget( ProviderScope( child: MaterialApp.router(