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

Fix/bracket viewer #224

Merged
merged 2 commits into from
Jan 6, 2025
Merged

Fix/bracket viewer #224

merged 2 commits into from
Jan 6, 2025

Conversation

thornxyz
Copy link
Contributor

@thornxyz thornxyz commented Jan 6, 2025

added bye logic, now can generate bracket for any number of teams

Summary by CodeRabbit

  • New Features

    • Simplified bracket creation process with a single input for the number of teams
    • Added input validation to ensure a minimum of 4 teams are selected
  • Bug Fixes

    • Improved error handling for team number input
    • Streamlined team generation logic
  • User Interface

    • Replaced detailed team name entry with a more straightforward number of teams input

Copy link

vercel bot commented Jan 6, 2025

@thornxyz is attempting to deploy a commit to the blaze's projects Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Jan 6, 2025

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

app/createBracket/page.jsx

Oops! Something went wrong! :(

ESLint: 9.17.0

ESLint couldn't find an eslint.config.(js|mjs|cjs) file.

From ESLint v9.0.0, the default configuration file is now eslint.config.js.
If you are using a .eslintrc.* file, please follow the migration guide
to update your configuration file to the new format:

https://eslint.org/docs/latest/use/configure/migration-guide

If you still have problems after following the migration guide, please stop by
https://eslint.org/chat/help to chat with the team.

Walkthrough

The pull request modifies the createBracket/page.jsx component to simplify the bracket creation process. Instead of manually entering team names, users now input the total number of teams. The changes streamline the team submission logic by replacing the complex team name entry with a single numeric input. The component now validates the number of teams, generates team names automatically, and prepares the bracket creation with a more straightforward approach.

Changes

File Change Summary
app/createBracket/page.jsx - Removed teamSchema and teamForm
- Added teams state for number of teams
- Added error state for input validation
- Implemented handleInputChange for team number input
- Added handleSubmit to validate team count
- Modified onTeamSubmit to generate teams based on input number

Sequence Diagram

sequenceDiagram
    participant User
    participant CreateBracketPage
    participant BracketSystem

    User->>CreateBracketPage: Enter number of teams
    CreateBracketPage->>CreateBracketPage: Validate input
    alt Valid Input
        CreateBracketPage->>BracketSystem: Submit team count
        BracketSystem->>BracketSystem: Generate team names
        BracketSystem-->>CreateBracketPage: Prepare bracket
    else Invalid Input
        CreateBracketPage->>User: Display error message
    end
Loading

Possibly related PRs

Suggested labels

backend, frontend

Suggested reviewers

  • dinxsh

Poem

🐰 Brackets bloom with numbers neat,
Teams generated, a digital feat!
No more typing names galore,
Just count and click, then explore!
A tournament's birth, simple and bright 🏆


🪧 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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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
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: 3

🧹 Nitpick comments (2)
app/createBracket/page.jsx (2)

49-50: Consider using number type for teams state

Using string type for numeric input can lead to type coercion issues. Consider using number type and handling the conversion explicitly.

- const [teams, setTeams] = useState("");
+ const [teams, setTeams] = useState(0);

106-115: Optimize power of 2 calculation and improve image handling

Consider these optimizations:

  1. Use bitwise operations for power of 2 calculations
  2. Make participant image URL configurable
  3. Add error handling for image loading
-  const nearestPowerOf2 = Math.pow(2, Math.ceil(Math.log2(len)));
+  const nearestPowerOf2 = 1 << Math.ceil(Math.log2(len));

Consider extracting the participant image URL to a configuration file and adding error handling for image loading failures.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4cdd305 and 10a38ca.

📒 Files selected for processing (1)
  • app/createBracket/page.jsx (5 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
app/createBracket/page.jsx

[error] 60-60: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

Comment on lines +323 to +342
<form onSubmit={handleSubmit} className="lg:w-1/2 mx-auto">
<h2 className="text-2xl font-bold mb-2">Enter Number of Teams</h2>
<Input
type="text"
id="number"
value={teams}
onChange={handleInputChange}
placeholder="Enter Number of Teams"
/>
{error && <p style={{ color: "red" }}>{error}</p>}
<div className="flex justify-center mt-4">
<Button
type="button"
variant="outline"
onClick={() =>
teamForm.setValue("teams", [...teamForm.watch("teams"), ""])
}
arial-label="add-another-team-btn"
type="submit"
disabled={showBrackets}
arial-label="submit-team-btn"
>
Add Another Team
Submit
</Button>
<div className="flex justify-center">
<Button
type="submit"
disabled={teamForm.formState.isSubmitting || showBrackets}
arial-label="submit-team-btn"
>
Submit Teams
</Button>
</div>
</form>
</Form>
</div>
</form>
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix input semantics and accessibility issues

Several UI improvements are needed:

  1. Use number input type for semantic HTML
  2. Fix misspelled aria-label attribute
  3. Move inline styles to CSS
 <Input
-  type="text"
+  type="number"
+  min="4"
+  max="64"
   id="number"
   value={teams}
   onChange={handleInputChange}
   placeholder="Enter Number of Teams"
 />
- {error && <p style={{ color: "red" }}>{error}</p>}
+ {error && <p className="text-red-500 mt-2">{error}</p>}
 <div className="flex justify-center mt-4">
   <Button
     type="submit"
     disabled={showBrackets}
-    arial-label="submit-team-btn"
+    aria-label="submit-team-btn"
   >
     Submit
   </Button>
 </div>
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<form onSubmit={handleSubmit} className="lg:w-1/2 mx-auto">
<h2 className="text-2xl font-bold mb-2">Enter Number of Teams</h2>
<Input
type="text"
id="number"
value={teams}
onChange={handleInputChange}
placeholder="Enter Number of Teams"
/>
{error && <p style={{ color: "red" }}>{error}</p>}
<div className="flex justify-center mt-4">
<Button
type="button"
variant="outline"
onClick={() =>
teamForm.setValue("teams", [...teamForm.watch("teams"), ""])
}
arial-label="add-another-team-btn"
type="submit"
disabled={showBrackets}
arial-label="submit-team-btn"
>
Add Another Team
Submit
</Button>
<div className="flex justify-center">
<Button
type="submit"
disabled={teamForm.formState.isSubmitting || showBrackets}
arial-label="submit-team-btn"
>
Submit Teams
</Button>
</div>
</form>
</Form>
</div>
</form>
<form onSubmit={handleSubmit} className="lg:w-1/2 mx-auto">
<h2 className="text-2xl font-bold mb-2">Enter Number of Teams</h2>
<Input
type="number"
min="4"
max="64"
id="number"
value={teams}
onChange={handleInputChange}
placeholder="Enter Number of Teams"
/>
{error && <p className="text-red-500 mt-2">{error}</p>}
<div className="flex justify-center mt-4">
<Button
type="submit"
disabled={showBrackets}
aria-label="submit-team-btn"
>
Submit
</Button>
</div>
</form>

Comment on lines +84 to +91
if (values < 4) {
toast.error("Number of teams must be greater than 4");
return;
}

const uniqueTeams = new Set(values.teams);
if (uniqueTeams.size !== values.teams.length) {
toast.error("Team names must be unique.");
return;
}
const teams = Array.from({ length: values }, (_, i) => `Team${i + 1}`);

const res = { ...bracketInfo, ...values };
const res = { ...bracketInfo, teams };
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

Enhance team generation and validation

The team submission logic could be improved in several ways:

  1. Add maximum team validation
  2. Improve team name generation
  3. Move success toast after successful bracket creation
 function onTeamSubmit(values) {
-  if (values < 4) {
+  if (values < 4 || values > 64) {
-    toast.error("Number of teams must be greater than 4");
+    toast.error("Number of teams must be between 4 and 64");
     return;
   }

-  const teams = Array.from({ length: values }, (_, i) => `Team${i + 1}`);
+  const teams = Array.from(
+    { length: values },
+    (_, i) => `Team ${String(i + 1).padStart(2, '0')}`
+  );

   const res = { ...bracketInfo, teams };
   setInfo(res);

   console.log("Bracket Info", JSON.stringify(info, null, 2));

   if (!showBrackets) {
     setShowBrackets(true);
   }

-  toast.success("Bracket created successfully");
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (values < 4) {
toast.error("Number of teams must be greater than 4");
return;
}
const uniqueTeams = new Set(values.teams);
if (uniqueTeams.size !== values.teams.length) {
toast.error("Team names must be unique.");
return;
}
const teams = Array.from({ length: values }, (_, i) => `Team${i + 1}`);
const res = { ...bracketInfo, ...values };
const res = { ...bracketInfo, teams };
if (values < 4 || values > 64) {
toast.error("Number of teams must be between 4 and 64");
return;
}
const teams = Array.from(
{ length: values },
(_, i) => `Team ${String(i + 1).padStart(2, '0')}`
);
const res = { ...bracketInfo, teams };

Comment on lines +52 to +66
const handleInputChange = (e) => {
setTeams(e.target.value);
setError("");
};

const handleSubmit = (e) => {
e.preventDefault();

if (isNaN(teams) || teams === "") {
setError("Please enter a valid number.");
} else {
onTeamSubmit(teams);
setTeams("");
}
};
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve input validation and safety

The current validation has several issues:

  1. Using isNaN is unsafe due to type coercion
  2. Missing validation for negative numbers and decimals
  3. No maximum limit for number of teams

Apply these improvements:

 const handleInputChange = (e) => {
-  setTeams(e.target.value);
+  const value = e.target.value.trim();
+  setTeams(value);
   setError("");
 };

 const handleSubmit = (e) => {
   e.preventDefault();
+  const numTeams = Number(teams);
 
-  if (isNaN(teams) || teams === "") {
+  if (Number.isNaN(numTeams) || teams === "" || !Number.isInteger(numTeams) || numTeams <= 0) {
     setError("Please enter a valid number.");
+  } else if (numTeams > 64) {
+    setError("Maximum 64 teams allowed.");
   } else {
-    onTeamSubmit(teams);
+    onTeamSubmit(numTeams);
     setTeams("");
   }
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const handleInputChange = (e) => {
setTeams(e.target.value);
setError("");
};
const handleSubmit = (e) => {
e.preventDefault();
if (isNaN(teams) || teams === "") {
setError("Please enter a valid number.");
} else {
onTeamSubmit(teams);
setTeams("");
}
};
const handleInputChange = (e) => {
const value = e.target.value.trim();
setTeams(value);
setError("");
};
const handleSubmit = (e) => {
e.preventDefault();
const numTeams = Number(teams);
if (Number.isNaN(numTeams) || teams === "" || !Number.isInteger(numTeams) || numTeams <= 0) {
setError("Please enter a valid number.");
} else if (numTeams > 64) {
setError("Maximum 64 teams allowed.");
} else {
onTeamSubmit(numTeams);
setTeams("");
}
};
🧰 Tools
🪛 Biome (1.9.4)

[error] 60-60: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

@dinxsh dinxsh merged commit 536fa02 into dinxsh:master Jan 6, 2025
7 of 8 checks passed
This was referenced Jan 8, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants