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 contest navigation to use navigable contests and add slugPrefix getter. #2363

Merged
merged 6 commits into from
Oct 25, 2024

Conversation

rohitpaulk
Copy link
Member

@rohitpaulk rohitpaulk commented Oct 25, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new property to filter contests based on the current selection, enhancing navigation.
    • Added a computed property to modify contest slugs for better management.
  • Bug Fixes

    • Simplified logic for retrieving the next and previous contests, improving navigation accuracy.
  • Style

    • Updated hover background color for leaderboard entries in dark mode for improved visual consistency.
    • Adjusted hover effect styling for leaderboard entries not associated with the current user.
    • Modified appearance of leaderboard entries for the current user.
    • Updated CSS classes for contest navigation buttons for better visibility and usability.
  • Tests

    • Enhanced test coverage for contest navigation buttons to ensure correct URL transitions and behavior.

Copy link
Contributor

coderabbitai bot commented Oct 25, 2024

Walkthrough

The changes involve modifications to the ContestPageNavigationComponent and ContestModel classes. In ContestPageNavigationComponent, the sortedContests property is renamed to sortedNavigableContests, and a new getter, navigableContests, is introduced to filter contests based on the current contest's slug prefix. The logic for retrieving the next and previous contests has been simplified. In ContestModel, a new computed property, slugPrefix, is added to modify the slug attribute by removing trailing hyphens and digits. Additionally, visual styling changes are made to the leaderboard entry components.

Changes

File Path Change Summary
app/components/contest-page/navigation.ts - Renamed sortedContests to sortedNavigableContests.
- Added getter navigableContests.
- Updated nextContest and previousContest getters to use sortedNavigableContests.
app/models/contest.ts - Added computed property slugPrefix to modify the slug attribute by removing trailing hyphen and digits.
app/components/contest-page/leaderboard-entry.hbs - Updated hover background color for anchor element from dark:hover:bg-gray-800 to dark:hover:bg-gray-700/40.
app/components/contest-page/leaderboard-entry.ts - Modified colorClasses getter to change hover effect styling for entries not associated with the current user.
tests/acceptance/contests-test.js - Added assertions for navigation buttons to verify correct URLs when clicking "Next" for contests and prize details.
app/components/contest-page/navigation.hbs - Updated CSS classes for <LinkTo> components, including border colors and hover states, and shortened button text for previous button.

Possibly related PRs

  • add dark mode styling #2138: The changes in this PR involve updates to the styling of components, including dark mode enhancements, which may indirectly relate to the visual presentation of contest navigation elements affected by the main PR's logic changes.

Poem

In the contest realm where bunnies play,
Navigable paths now light the way.
With slugs refined and contests in line,
Hopping through choices, oh how divine!
Next and previous, a simple quest,
In this new logic, we surely are blessed! 🐇✨


🪧 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

codecov bot commented Oct 25, 2024

Bundle Report

Changes will increase total bundle size by 110 bytes (0.0%) ⬆️. This is within the configured threshold ✅

Detailed changes
Bundle name Size Change
client-array-push 35.77MB 110 bytes (0.0%) ⬆️

Copy link

github-actions bot commented Oct 25, 2024

Test Results

  1 files  ±0    1 suites  ±0   6m 24s ⏱️ -11s
582 tests ±0  542 ✅ ±0  40 💤 ±0  0 ❌ ±0 
597 runs  ±0  557 ✅ ±0  40 💤 ±0  0 ❌ ±0 

Results for commit 5131493. ± Comparison against base commit 6e30ca3.

♻️ This comment has been updated with latest results.

Copy link

codecov bot commented Oct 25, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

✅ All tests successful. No failed tests found.

Additional details and impacted files

📢 Thoughts on this report? Let us know!

Copy link
Contributor

@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 (3)
app/models/contest.ts (1)

39-41: Add unit tests for slugPrefix.

Since this property is used for navigation filtering, please add unit tests to verify:

  1. Basic case: "contest-123" → "contest"
  2. Edge cases mentioned above
  3. Integration with ContestPageNavigationComponent

Would you like me to help generate the unit test cases?

app/components/contest-page/navigation.ts (2)

30-32: Consider memoizing the navigableContests result

The implementation is clean and logical. However, since this getter might be called frequently and performs array filtering, consider memoizing the result to optimize performance, especially if allContests or the current contest changes infrequently.

+ @tracked private _navigableContests: ContestModel[] | null = null;

  get navigableContests(): ContestModel[] {
+   if (!this._navigableContests) {
+     this._navigableContests = this.args.allContests.filter(
+       (contest) => contest.slugPrefix === this.args.contest.slugPrefix
+     );
+   }
+   return this._navigableContests;
- return this.args.allContests.filter((contest) => contest.slugPrefix === this.args.contest.slugPrefix);
  }

+ // Add this method to reset cache when dependencies change
+ private resetNavigableContestsCache() {
+   this._navigableContests = null;
+ }

40-40: LGTM! Consider simplifying the previousContest getter

The update to use sortedNavigableContests is correct. However, the logic could be simplified to match the style of nextContest.

  get previousContest(): ContestModel | null {
-   if (this.currentContestIndex > 0) {
-     return this.sortedNavigableContests[this.currentContestIndex - 1] || null;
-   } else {
-     return null;
-   }
+   return this.sortedNavigableContests[this.currentContestIndex - 1] || null;
  }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 6e30ca3 and d6ce5a9.

📒 Files selected for processing (2)
  • app/components/contest-page/navigation.ts (2 hunks)
  • app/models/contest.ts (1 hunks)
🔇 Additional comments (4)
app/models/contest.ts (1)

39-41: Verify handling of edge cases in slugPrefix.

The implementation looks correct for basic cases, but please verify the behavior with these edge cases:

  • Slugs with multiple number segments (e.g., "contest-1-2")
  • Slugs ending with just a hyphen
  • Slugs without any numbers

Let's check existing slug patterns in the codebase:

✅ Verification successful

Based on the search results, I can now verify the slugPrefix implementation. The codebase shows:

  1. The slugPrefix property is used by ContestPageNavigationComponent to filter contests with the same prefix
  2. The test files show contest slugs follow a pattern of base name with numeric suffix (e.g. 'weekly-1', 'weekly-2', etc.)
  3. No edge cases were found where slugs have multiple number segments or end with just a hyphen
  4. The regex pattern -\d+$ correctly handles all the contest slug patterns found in the codebase

The slugPrefix implementation is correct and handles all existing slug patterns appropriately.

The regex pattern -\d+$ is well-suited for the contest slugs in use:

  • Matches trailing hyphen followed by digits at the end of string
  • Won't match mid-string numbers or hyphen-only endings
  • Returns the base slug prefix as expected
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all contest slug patterns to verify edge cases
# Expected: List of unique slug patterns to validate the regex

# Search for slug assignments or definitions in the codebase
rg -g '*.ts' -g '*.js' 'slug.*=.*["\'].*-\d' -A 1

Length of output: 93


Script:

#!/bin/bash
# Let's try a different approach to find slug patterns
# Search for slug-related code and patterns in the codebase

# Look for slug assignments or usage
rg -g '*.{ts,js}' 'slug.*=.*["\''].*-' -A 1

# Also search for test files that might contain slug examples
rg -g '*test*.{ts,js}' -g '*spec*.{ts,js}' 'slug.*=.*["\''].*-' -A 1

# Search for any slug property definitions
ast-grep --pattern 'slug: string'

Length of output: 322


Script:

#!/bin/bash
# Fix the regex syntax and try again with simpler patterns

# Look for slug patterns in the codebase
rg -g '*.{ts,js}' 'slug.*=' -A 1

# Look for test cases involving slugs
rg -g '*test*.{ts,js}' -g '*spec*.{ts,js}' 'slug' -A 1

# Look for slug-related function implementations
ast-grep --pattern 'slug($$$) {
  $$$
}'

Length of output: 111142

app/components/contest-page/navigation.ts (3)

19-19: LGTM! Consistent rename to sortedNavigableContests

The update maintains functionality while improving clarity by being more specific about the nature of the sorted contests being indexed.


46-47: LGTM! Clean implementation of sortedNavigableContests

The renamed getter maintains the same sorting logic while working with the filtered navigable contests. The implementation is clean and consistent with the overall refactoring.


35-35: Verify removal of date-based checks for next contest

The logic has been simplified to just return the next contest in the sorted array. Please confirm if removing the previous date-based checks (current date and one-week threshold) was intentional, as this changes the behavior of what contests are considered "next".

✅ Verification successful

Removal of date-based checks was intentional and correct

The change was part of a larger refactor that improved contest navigation. The previous date-based check (one week threshold) is no longer needed because:

  1. The navigation now only shows contests with the same slugPrefix (filtered in navigableContests getter)
  2. Contests are still properly sorted by startsAt date
  3. The removed date check was an arbitrary restriction that limited navigation between related contests

This simplification makes the code more maintainable while preserving the core functionality of navigating between related contests.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any tests or documentation that might reference the date-based navigation behavior
rg -l "nextContest|contest.*navigation.*date" --type=ts --type=test

Length of output: 98


Script:

#!/bin/bash
# Search for any tests or related files that might reference the date-based navigation behavior
rg -l "nextContest|contest.*navigation.*date" --type=ts

# Look for the previous implementation to understand what was changed
rg -B5 -A5 "nextContest" --type=ts

# Look for any test files specifically
fd "test|spec" -e ts

Length of output: 3048


Script:

#!/bin/bash
# Let's look at the git history of this file to see the previous implementation
git log -p app/components/contest-page/navigation.ts

# Also check the ContestModel to understand what properties are available
cat app/models/contest.ts

Length of output: 7246

Copy link
Contributor

@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: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1f1355f and b43ddad.

📒 Files selected for processing (1)
  • tests/acceptance/contests-test.js (2 hunks)
🔇 Additional comments (1)
tests/acceptance/contests-test.js (1)

165-177: LGTM! Comprehensive test coverage for header navigation.

The new assertions thoroughly verify the "Next" button functionality, including:

  • Navigation through multiple contests
  • Proper URL updates
  • Boundary condition when reaching the last contest

Comment on lines +201 to +207
assert.strictEqual(currentURL(), '/contests/weekly-4', 'Next button works');

await contestsPage.prizeDetailsNavigation.clickOnNextContestButton();
assert.strictEqual(currentURL(), '/contests/weekly-5', 'Next button works');

assert.strictEqual(currentURL(), '/contests/weekly-3', 'Next button is disabled when the next contest is the second contest from present');
await contestsPage.prizeDetailsNavigation.clickOnNextContestButton();
assert.strictEqual(currentURL(), '/contests/weekly-5', 'Next button is disabled when contest is last');
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider refactoring to reduce test duplication.

While the assertions are thorough, there's significant duplication between the header and prize details navigation tests. Consider extracting common navigation test logic into a shared helper function.

Example refactor:

function assertNavigationBehavior(assert, navigationComponent, description) {
  await navigationComponent.clickOnNextContestButton();
  assert.strictEqual(currentURL(), '/contests/weekly-4', `${description} Next button works`);

  await navigationComponent.clickOnNextContestButton();
  assert.strictEqual(currentURL(), '/contests/weekly-5', `${description} Next button works`);

  await navigationComponent.clickOnNextContestButton();
  assert.strictEqual(currentURL(), '/contests/weekly-5', `${description} Next button is disabled when contest is last`);
}

// Usage in tests:
test('header navigation buttons work', async function(assert) {
  // ... existing setup ...
  await assertNavigationBehavior(assert, contestsPage.headerNavigation, 'Header navigation:');
});

test('prize details navigation buttons work', async function(assert) {
  // ... existing setup ...
  await assertNavigationBehavior(assert, contestsPage.prizeDetailsNavigation, 'Prize details navigation:');
});

Copy link
Contributor

@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)
app/components/contest-page/navigation.hbs (2)

7-12: Consider accessibility implications of abbreviated text.

While "Prev" saves space, consider using aria-label="Previous" to ensure screen readers announce the full word for better accessibility.

 <LinkTo
   @route="contest"
   @model={{this.previousContest.slug}}
   @disabled={{this.isPreviousContestDisabled}}
+  aria-label="Previous"
   class="flex items-center rounded-l-md border border-r-[0.5px] border-white/15 hover:border-white/20 hover:bg-white/5 pl-1.5 pr-2 py-1.5
     {{if this.isPreviousContestDisabled 'pointer-events-none opacity-50'}}"
   data-test-previous-contest-button
 >

21-22: Consider standardizing border width values.

The use of border-[0.5px] might cause inconsistent rendering across browsers. Consider using standard Tailwind border utilities or a full pixel value.

-  class="flex items-center rounded-r-md border border-l-[0.5px] border-white/15 hover:border-white/20 hover:bg-white/5 pl-2 pr-1.5 py-1.5
+  class="flex items-center rounded-r-md border border-l border-white/15 hover:border-white/20 hover:bg-white/5 pl-2 pr-1.5 py-1.5
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b43ddad and 5131493.

📒 Files selected for processing (1)
  • app/components/contest-page/navigation.hbs (2 hunks)
🔇 Additional comments (1)
app/components/contest-page/navigation.hbs (1)

Line range hint 1-29: Overall implementation looks good!

The navigation component is well-structured with proper:

  • Semantic HTML
  • Test attributes
  • Disabled state handling
  • Consistent styling

@rohitpaulk rohitpaulk merged commit 9b6c442 into main Oct 25, 2024
9 checks passed
@rohitpaulk rohitpaulk deleted the test-contest-navigation-changesgs branch October 25, 2024 16:15
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.

1 participant