Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor home tournament card #141

Merged
merged 3 commits into from
Nov 19, 2024
Merged

Conversation

cp-mayank
Copy link
Collaborator

@cp-mayank cp-mayank commented Nov 19, 2024

tournament.card.webm

Summary by CodeRabbit

  • New Features

    • Enhanced visual presentation of tournament items with a new layout design.
    • Improved sizing management for tournament items using a new size property.
  • Bug Fixes

    • Simplified logic for displaying tournament items by removing the background property.
  • Refactor

    • Streamlined component structure for better clarity and maintainability.

@cp-mayank cp-mayank marked this pull request as ready for review November 19, 2024 09:39
Copy link

coderabbitai bot commented Nov 19, 2024

Walkthrough

The changes in this pull request primarily focus on the TournamentItem widget across multiple files. The background property has been replaced with a size property, altering the widget's layout and dimensions. The initState method has been simplified, and the layout structure has shifted from a column to a stack. Additionally, the TournamentItem instantiation in various components has been updated to reflect these changes, impacting how tournament items are displayed in the UI.

Changes

File Path Change Summary
khelo/lib/ui/flow/home/components/tournament_item.dart Updated TournamentItem class to replace background with size, modified layout to stack, and simplified color management.
khelo/lib/ui/flow/home/home_screen.dart Modified _tournamentList method to add size parameter to TournamentItem, setting it to Size.fromWidth(360).
khelo/lib/ui/flow/home/view_all/home_view_all_screen.dart Removed background parameter from TournamentItem instantiation in _body method, simplifying its usage.

Possibly related PRs

  • Add team in tournament #120: This PR adds a new parameter size to the TournamentItem widget instantiation, which is directly related to the changes made in the main PR where the size property was introduced in the TournamentItem class.
  • Implement tournament detail members #128: This PR implements a screen that displays tournament members, which may involve changes to the TournamentItem class as it relates to tournament management and display.
  • Show match group tag #134: This PR enhances the tournament detail overview by displaying the match group tag, which could be related to the visual presentation aspects modified in the main PR.
  • Remove group option conditionally #138: This PR includes changes to the TournamentItem widget, specifically modifying the imageProvider variable to be nullable, which aligns with the overall improvements in handling widget properties in the main PR.

Suggested reviewers

  • cp-sidhdhi-p

🐰 In the garden where tournaments bloom,
A size now guides, dispelling the gloom.
No more backgrounds to clutter the view,
Just layered stacks in colors so true.
With each little change, the layout's refined,
A hop and a skip, and clarity's aligned! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (7)
khelo/lib/ui/flow/home/components/tournament_item.dart (6)

21-28: LGTM! Consider adding documentation.

The switch from background to size property improves the widget's flexibility for different screen sizes.

Add documentation to explain the size property's usage and default behavior:

+ /// Controls the dimensions of the tournament item.
+ /// If null, defaults to the screen width with a 2:1 aspect ratio.
  final Size? size;

45-49: Add error handling for palette generation.

While the state management is good, consider handling potential errors during palette generation.

  imageProvider.createPaletteGenerator().then((palette) {
    if (mounted) {
      setState(() => this.palette = palette);
    }
- });
+ }).catchError((error) {
+   if (mounted) {
+     debugPrint('Failed to generate palette: $error');
+   }
+ });

55-93: Extract constants and improve width calculation.

The layout structure looks good, but we can improve maintainability.

+ static const double _aspectRatio = 2.0;
+ static const double _borderRadius = 16.0;
+ static const EdgeInsets _contentPadding = EdgeInsets.all(16);

+ double _calculateWidth(BuildContext context) {
+   return widget.size?.width ?? context.mediaQuerySize.width;
+ }

  @override
  Widget build(BuildContext context) {
-   final width = widget.size?.width ?? context.mediaQuerySize.width;
+   final width = _calculateWidth(context);
    final (titleColor, dateAndTypeColor) = _getTextColors();
    // ... rest of the build method

101-119: Extract gradient constants and reuse height calculation.

The gradient implementation is good but could be more maintainable.

+ static const double _gradientOpacityStart = 0.0;
+ static const double _gradientOpacityMiddle = 0.5;
+ static const double _gradientOpacityEnd = 1.0;

  Widget _gradient(BuildContext context, double width) {
+   final height = width / _aspectRatio;
    final dominant = palette?.dominantColor?.color ?? context.colorScheme.primary;
    return Align(
      alignment: Alignment.bottomCenter,
      child: Container(
-       height: width / 2,
+       height: height,
        width: width,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
-             dominant.withOpacity(0),
-             dominant.withOpacity(0.5),
-             dominant,
+             dominant.withOpacity(_gradientOpacityStart),
+             dominant.withOpacity(_gradientOpacityMiddle),
+             dominant.withOpacity(_gradientOpacityEnd),
            ],
          ),
        ),
      ),
    );
  }

124-141: Improve image handling and reuse constants.

The image handling is robust but could be more consistent with the rest of the code.

+ static const double _iconSize = 32.0;

  Widget _bannerImage(String? bannerUrl, double width) {
+   final height = width / _aspectRatio;
    return bannerUrl == null
        ? Center(
            child: SvgPicture.asset(
              Assets.images.icTournaments,
-             height: 32,
-             width: 32,
+             height: _iconSize,
+             width: _iconSize,
              colorFilter: ColorFilter.mode(
                context.colorScheme.textPrimary,
                BlendMode.srcATop,
              )),
          )
        : CachedNetworkImage(
            imageUrl: bannerUrl,
            fit: BoxFit.cover,
            width: width,
-           height: width / 2,
+           height: height,
+           errorWidget: (context, url, error) => Center(
+             child: Icon(Icons.error, size: _iconSize),
+           ),
          );
  }

199-214: Improve color management with named constants and explicit types.

The color logic is good but could be more maintainable.

+ static const double _luminanceThreshold = 0.5;
+ static const double _primaryTextOpacity = 0.8;
+ static const double _darkTextOpacity = 0.87;
+ static const double _darkSecondaryTextOpacity = 0.6;

- (Color, Color) _getTextColors() {
+ ({Color primary, Color secondary}) _getTextColors() {
    final dominant = palette?.dominantColor?.color ?? context.colorScheme.primary;

    if (dominant == context.colorScheme.primary) {
-     return (
-       context.colorScheme.onPrimary,
-       context.colorScheme.onPrimary.withOpacity(0.8)
-     );
+     return (
+       primary: context.colorScheme.onPrimary,
+       secondary: context.colorScheme.onPrimary.withOpacity(_primaryTextOpacity)
+     );
    }

-   if (dominant.computeLuminance() < 0.5) {
-     return (Colors.white, Colors.white.withOpacity(0.8));
+   if (dominant.computeLuminance() < _luminanceThreshold) {
+     return (
+       primary: Colors.white,
+       secondary: Colors.white.withOpacity(_primaryTextOpacity)
+     );
    } else {
-     return (Colors.black.withOpacity(0.87), Colors.black.withOpacity(0.6));
+     return (
+       primary: Colors.black.withOpacity(_darkTextOpacity),
+       secondary: Colors.black.withOpacity(_darkSecondaryTextOpacity)
+     );
    }
  }
khelo/lib/ui/flow/home/home_screen.dart (1)

164-166: Consider using responsive sizing instead of hardcoded width

The fixed width of 360 might not be optimal for all screen sizes. Consider making the tournament item size responsive to the screen width.

Here's a suggested implementation:

- size: Size.fromWidth(360),
+ size: Size.fromWidth(MediaQuery.of(context).size.width * 0.85),

Alternatively, you could use LayoutBuilder for more fine-grained control:

- TournamentItem(
-   tournament: tournament,
-   size: Size.fromWidth(360),
-   margin: EdgeInsets.symmetric(horizontal: 8),
- )
+ LayoutBuilder(
+   builder: (context, constraints) {
+     return TournamentItem(
+       tournament: tournament,
+       size: Size.fromWidth(constraints.maxWidth * 0.85),
+       margin: EdgeInsets.symmetric(horizontal: 8),
+     );
+   },
+ )
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a46a239 and 3bc3876.

📒 Files selected for processing (3)
  • khelo/lib/ui/flow/home/components/tournament_item.dart (3 hunks)
  • khelo/lib/ui/flow/home/home_screen.dart (1 hunks)
  • khelo/lib/ui/flow/home/view_all/home_view_all_screen.dart (1 hunks)
🔇 Additional comments (1)
khelo/lib/ui/flow/home/view_all/home_view_all_screen.dart (1)

84-84: 🛠️ Refactor suggestion

Add size parameter to TournamentItem for consistent behavior

The TournamentItem widget requires a size parameter for proper layout management, as seen in other screens. Consider adding it here to maintain consistency.

Apply this diff:

-return TournamentItem(tournament: tournament);
+return TournamentItem(
+  tournament: tournament,
+  size: Size.fromWidth(360),
+);

Let's verify the usage of TournamentItem across the codebase:

# Conflicts:
#	khelo/lib/ui/flow/home/components/tournament_item.dart
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (2)
khelo/lib/ui/flow/home/components/tournament_item.dart (2)

115-133: Consider extracting gradient colors to theme.

The gradient implementation looks good, but consider moving the opacity values and gradient stops to the theme for consistency across the app.

+ // In your theme file
+ class AppGradients {
+   static const tournamentItemOverlay = [0.0, 0.5, 1.0];
+ }

  // In this file
  decoration: BoxDecoration(
    gradient: LinearGradient(
      begin: Alignment.topCenter,
      end: Alignment.bottomCenter,
      colors: [
-       dominant.withOpacity(0),
-       dominant.withOpacity(0.5),
-       dominant,
+       dominant.withOpacity(AppGradients.tournamentItemOverlay[0]),
+       dominant.withOpacity(AppGradients.tournamentItemOverlay[1]),
+       dominant.withOpacity(AppGradients.tournamentItemOverlay[2]),
      ],
    ),
  ),

138-155: Consider extracting the aspect ratio constant.

The aspect ratio calculation (width/2) is duplicated. Consider extracting it to a constant.

+ // At the top of the class
+ static const _aspectRatio = 2.0;

  Widget _bannerImage(String? bannerUrl, double width) {
    return bannerUrl == null
        ? Center(
            child: SvgPicture.asset(
              Assets.images.icTournaments,
              height: 32,
              width: 32,
              colorFilter: ColorFilter.mode(
                context.colorScheme.textPrimary,
                BlendMode.srcATop,
              ),
            ),
          )
        : CachedNetworkImage(
            imageUrl: bannerUrl,
            fit: BoxFit.cover,
            width: width,
-           height: width / 2,
+           height: width / _aspectRatio,
          );
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3bc3876 and 5795229.

📒 Files selected for processing (1)
  • khelo/lib/ui/flow/home/components/tournament_item.dart (5 hunks)
🔇 Additional comments (4)
khelo/lib/ui/flow/home/components/tournament_item.dart (4)

48-52: LGTM! Improved palette generation logic.

The palette generation code has been simplified while maintaining proper lifecycle management with the mounted check.


69-107: LGTM! Improved layout structure with better visual hierarchy.

The Stack-based layout with proper alignment and padding provides a cleaner implementation.


213-229: LGTM! Good contrast handling in text colors.

The text color selection based on luminance ensures good readability across different background colors.


21-21: Verify the impact of API changes across the codebase.

The replacement of background with size property is a breaking change that could affect existing usages of this widget.

Also applies to: 25-25

✅ Verification successful

Based on the search results, I can now generate the final response:

API change is properly handled across the codebase

The removal of background property and addition of optional size property is safe as all existing usages have been updated:

  • In home_screen.dart: Uses the new size property correctly with Size.fromWidth(360)
  • In home_view_all_screen.dart: Uses the default behavior without size, which is valid since it's optional
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for existing TournamentItem instantiations that might need updates
rg -l "TournamentItem\(" | xargs rg -A 5 "TournamentItem\("

Length of output: 1629

@cp-mayank cp-mayank merged commit 293bd5d into main Nov 19, 2024
2 checks passed
@cp-mayank cp-mayank deleted the Mayank/Refactor-tournament-card branch November 19, 2024 10:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants