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: resolve 15 of 16 remaining lint warnings #2662

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

unrenamed
Copy link
Contributor

@unrenamed unrenamed commented Nov 15, 2024

What does this PR do?

Resolves all lint warnings except the final one, which is more complex and may require input from a core team member for optimal resolution, building on #2652. Progresses towards resolving #2605.

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • Chore (refactoring code, technical debt, workflow improvements)
  • Enhancement (small improvements)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

Checklist

Required

  • Filled out the "How to test" section in this PR
  • Read Contributing Guide
  • Self-reviewed my own code
  • Commented on my code in hard-to-understand areas
  • Ran pnpm build
  • Ran pnpm fmt
  • Checked for warnings, there are none
  • Removed all console.logs
  • Merged the latest changes from main onto my branch with git pull origin main
  • My changes don't cause any responsiveness issues

Appreciated

  • If a UI change was made: Added a screen recording or screenshots to this PR
  • Updated the Unkey Docs if changes were necessary

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced form handling in the CreateKey component for improved state management and submission logic.
    • Improved permission selection logic in the Client component for better performance.
    • Refined sign-in and sign-up processes with clearer flow and enhanced error handling.
  • Bug Fixes

    • Adjusted mouse tracking in the ShinyCardGroup component for more accurate interactions.

These updates aim to enhance user experience by optimizing performance and ensuring smoother interactions across the application.

Copy link

changeset-bot bot commented Nov 15, 2024

⚠️ No Changeset found

Latest commit: 6a0076b

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link

vercel bot commented Nov 15, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
dashboard ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 18, 2024 3:59pm
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 18, 2024 3:59pm
play ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 18, 2024 3:59pm
workflows ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 18, 2024 3:59pm
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 18, 2024 3:59pm

Copy link

vercel bot commented Nov 15, 2024

@unrenamed is attempting to deploy a commit to the Unkey Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Nov 15, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces several modifications across multiple components, primarily focusing on enhancing form state management and submission logic. Key changes include the addition of useEffect hooks for initializing state, refining error handling, and optimizing performance in the CreateKey, Client, EmailSignIn, and EmailSignUp components. These adjustments ensure that only relevant data is processed during form submissions and improve the clarity of the control flow, particularly in handling permissions and user interactions.

Changes

File Change Summary
apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/new/client.tsx Updated CreateKey component with a new useEffect for form initialization, refined onSubmit logic, and error handling.
apps/dashboard/app/(app)/settings/root-keys/new/client.tsx Modified Client component's useEffect for state initialization based on selected permissions, and updated handleSetChecked.
apps/dashboard/app/auth/sign-in/email-signin.tsx Adjusted EmailSignIn component's useEffect for better flow control and refined error handling in the sign-in process.
apps/dashboard/app/auth/sign-up/email-signup.tsx Enhanced EmailSignUp component with improved control flow and error handling related to sign-up logic.
apps/www/components/shiny-card.tsx Updated ShinyCardGroup component's onMouseMove dependency array and ensured recalibration of dimensions on refresh.

Possibly related PRs

Suggested labels

🕹️ oss.gg

Suggested reviewers

  • mcstepp
  • perkinsjr

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 49a860c and 6a0076b.

📒 Files selected for processing (1)
  • apps/www/components/shiny-card.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/www/components/shiny-card.tsx

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
Contributor

github-actions bot commented Nov 15, 2024

Thank you for following the naming conventions for pull request titles! 🙏

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

🧹 Outside diff range and nitpick comments (8)
apps/dashboard/app/auth/sign-in/email-signin.tsx (2)

Line range hint 24-52: Prevent memory leaks in async operations.

The async operation might continue after component unmount, potentially causing memory leaks or state updates on unmounted component.

Add cleanup logic:

 React.useEffect(() => {
+  let mounted = true;
   const signUpOrgUser = async () => {
     if (!signInLoaded) {
       return;
     }

     const ticket = new URL(window.location.href).searchParams.get(param);
     if (!ticket) {
       return;
     }
-    setIsLoading(true);
+    if (mounted) setIsLoading(true);
     await signIn
       .create({
         strategy: "ticket",
         ticket,
       })
       .then((result) => {
+        if (!mounted) return;
         if (result.status === "complete" && result.createdSessionId) {
           setActive({ session: result.createdSessionId }).then(() => {
+            if (mounted)
             router.push("/apis");
           });
         }
       })
       .catch((err) => {
-        setIsLoading(false);
+        if (mounted) setIsLoading(false);
         console.error(err);
       });
   };
   signUpOrgUser();
+  return () => {
+    mounted = false;
+  };
 }, [signInLoaded, router, signIn, setActive]);

Line range hint 54-85: Improve error handling and prevent memory leaks in signInWithCode.

The function has several areas for improvement:

  1. Potential memory leaks in async operations
  2. Error handling could be more type-safe
  3. Generic error message could be more specific

Consider these improvements:

 const signInWithCode = async (e: React.FormEvent<HTMLFormElement>) => {
+  let mounted = true;
   e.preventDefault();
   const email = new FormData(e.currentTarget).get("email");
   if (!signInLoaded || typeof email !== "string") {
     return null;
   }
-  setIsLoading(true);
+  if (mounted) setIsLoading(true);
   await signIn
     .create({
       identifier: email,
     })
     .then(async () => {
+      if (!mounted) return;
       const firstFactor = signIn.supportedFirstFactors.find((f) => f.strategy === "email_code") as
         | { emailAddressId: string }
         | undefined;

       if (firstFactor) {
         await signIn.prepareFirstFactor({
           strategy: "email_code",
           emailAddressId: firstFactor.emailAddressId,
         });

-        setIsLoading(false);
+        if (mounted) setIsLoading(false);
         props.verification(true);
       }
       setLastUsed("email");
     })
     .catch((err: { errors: Array<{ code: string; message: string }> }) => {
-      setIsLoading(false);
+      if (mounted) setIsLoading(false);
       if (err.errors[0].code === "form_identifier_not_found") {
         props.setAccountNotFound(true);
         props.email(email);
       } else {
-        props.setError("We couldn't sign you in. Please try again later");
+        props.setError(`Sign-in failed: ${err.errors[0].message || 'Please try again later'}`);
       }
     });
+  return () => {
+    mounted = false;
+  };
 };
apps/dashboard/app/auth/sign-up/email-signup.tsx (1)

Line range hint 24-77: Refactor useEffect to improve state management and error handling

The current implementation has several areas for improvement:

  1. Duplicate state reset
  2. Incomplete error handling
  3. Multiple state mutations that could lead to race conditions

Consider applying these changes:

  React.useEffect(() => {
    const signUpFromParams = async () => {
      if (!signUpLoaded) {
        return;
      }

      const ticket = new URL(window.location.href).searchParams.get("__clerk_ticket");
      const emailParam = new URL(window.location.href).searchParams.get("email");
      if (!ticket && !emailParam) {
        return;
      }

      try {
        if (ticket) {
          const result = await signUp?.create({
            strategy: "ticket",
            ticket,
          });
          
          if (result?.status === "complete" && result.createdSessionId) {
            await setActive({ session: result.createdSessionId });
            router.push("/apis");
          }
        }

        if (emailParam) {
          await signUp?.create({
            emailAddress: emailParam,
          });
          await signUp.prepareEmailAddressVerification();
          setVerification(true);
        }
-     } catch (err) {
+     } catch (err: any) {
        if (err.errors?.[0]?.code === "form_identifier_exists") {
          toast.error("It looks like you have an account. Please use sign in");
+       } else {
+         toast.error("An error occurred during sign up");
+         console.error(err);
        }
+     } finally {
+       setTransferLoading(false);
      }
    };

    signUpFromParams();
-   setTransferLoading(false);
  }, [signUpLoaded]);
apps/dashboard/app/(app)/settings/root-keys/new/client.tsx (1)

Line range hint 96-117: Consider revising the useEffect dependency handling

While the performance optimization using Set is excellent, ignoring the exhaustive dependencies warning might lead to bugs. The current implementation won't react to changes in apis or selectedPermissions.

Consider this alternative approach that properly handles dependencies while maintaining performance:

- // biome-ignore lint/correctness/useExhaustiveDependencies: effect must be called once to set initial cards state
  useEffect(() => {
    const initialSelectedApiSet = new Set<string>();
    selectedPermissions.forEach((permission) => {
      const apiId = permission.split(".")[1] ?? ""; // Extract API ID
      if (apiId.length) {
        initialSelectedApiSet.add(apiId);
      }
    });

    const initialCardStates: Record<string, boolean> = {};
    apis.forEach((api) => {
      initialCardStates[api.id] = initialSelectedApiSet.has(api.id); // O(1) check
    });

-   // We use a Set to gather unique API IDs, enabling O(1) membership checks.
-   // This avoids the O(m * n) complexity of repeatedly iterating over selectedPermissions
-   // for each API, reducing the overall complexity to O(n + m) and improving performance
-   // for large data sets.

    setCardStatesMap(initialCardStates);
- }, []); // Execute ones on the first load
+ }, [apis, selectedPermissions]);

This ensures the card states stay in sync with both the APIs and selected permissions while maintaining the O(n + m) performance characteristics.

apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/new/client.tsx (4)

Line range hint 262-267: Consider refactoring the useEffect hook to properly handle dependencies.

While the biome-ignore comment explains the intent, it's better to follow React's best practices for handling effect dependencies.

Consider this alternative implementation:

-  // biome-ignore lint/correctness/useExhaustiveDependencies: reset is only required on mount
-  useEffect(() => {
-    // React hook form + zod doesn't play nice with nested objects, so we need to reset them on load.
-    resetRateLimit();
-    resetLimited();
-  }, []);
+  useEffect(() => {
+    const initializeForm = () => {
+      resetRateLimit();
+      resetLimited();
+    };
+    initializeForm();
+  }, [resetRateLimit, resetLimited]);

Also, consider memoizing the reset functions using useCallback to prevent unnecessary re-renders:

const resetRateLimit = useCallback(() => {
  form.resetField("ratelimit.duration", undefined);
  form.resetField("ratelimit.limit", undefined);
  form.resetField("ratelimit", undefined);
}, [form]);

Line range hint 4-4: Address the TODO comment for test coverage.

This component handles complex form state and validation logic. It's crucial to have comprehensive test coverage for:

  • Form validation scenarios
  • State management
  • API integration
  • Error handling

Would you like me to help generate test cases for this component? I can create a new GitHub issue with:

  1. Unit tests for form validation
  2. Integration tests for API interactions
  3. Snapshot tests for UI states

Line range hint 262-267: Fix the refill day handling and improve object manipulation.

There are several issues in the form submission logic:

  1. The refill day assignment has a bug
  2. The values object is being mutated directly

Apply these fixes:

-    const refill = values.limit?.refill;
-    if (refill?.interval === "daily") {
-      refill?.refillDay === undefined;
-    }
-    if (refill?.interval === "monthly" && !refill.refillDay) {
-      refill.refillDay = 1;
-    }
+    const formValues = { ...values };
+    if (formValues.limit?.refill?.interval === "daily") {
+      delete formValues.limit.refill.refillDay;
+    } else if (formValues.limit?.refill?.interval === "monthly" && !formValues.limit.refill.refillDay) {
+      formValues.limit.refill.refillDay = 1;
+    }

Line range hint 32-38: Improve form error handling consistency.

The form has several areas where error handling could be improved:

  1. Duplicate error message displays
  2. Inconsistent error message placement

Consider centralizing error handling:

const ErrorMessage: React.FC<{ name: string }> = ({ name }) => {
  const error = form.formState.errors[name];
  return error ? (
    <p className="text-xs text-content-alert">{error.message}</p>
  ) : null;
};

Then replace duplicate error displays with the centralized component:

-{form.formState.errors.ratelimit && (
-  <p className="text-xs text-center text-content-alert">
-    {form.formState.errors.ratelimit.message}
-  </p>
-)}
+<ErrorMessage name="ratelimit" />

Also applies to: 262-267

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b21b1c4 and 49a860c.

📒 Files selected for processing (5)
  • apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/new/client.tsx (1 hunks)
  • apps/dashboard/app/(app)/settings/root-keys/new/client.tsx (1 hunks)
  • apps/dashboard/app/auth/sign-in/email-signin.tsx (1 hunks)
  • apps/dashboard/app/auth/sign-up/email-signup.tsx (2 hunks)
  • apps/www/components/shiny-card.tsx (1 hunks)
🔇 Additional comments (5)
apps/www/components/shiny-card.tsx (2)

63-63: LGTM! Dependency array fix addresses potential stale closure issues.

The addition of boxes to the dependency array is correct and resolves the ESLint exhaustive-deps warning.


63-63: Consider memoizing boxes array for performance optimization.

While the dependency array fix is necessary, it could cause unnecessary re-renders when boxes change. Consider memoizing the boxes array if performance becomes an issue:

- const [boxes, setBoxes] = useState<Array<HTMLElement>>([]);
+ const [boxes, setBoxes] = useState<Array<HTMLElement>>([]);
+ const memoizedBoxes = useMemo(() => boxes, []);

  useEffect(() => {
    containerRef.current &&
      setBoxes(Array.from(containerRef.current.children).map((el) => el as HTMLElement));
  }, []);

  const onMouseMove = useCallback(() => {
    // ... existing code ...
-  }, [boxes, mousePosition.x, mousePosition.y]);
+  }, [memoizedBoxes, mousePosition.x, mousePosition.y]);
apps/dashboard/app/auth/sign-up/email-signup.tsx (2)

27-29: LGTM: Good defensive programming practice

The early return when signUpLoaded is false is a good practice as it prevents unnecessary execution and follows the fail-fast principle.


Line range hint 23-77: Verify consistent error handling across auth components

Let's ensure that error handling and loading states are consistent across all authentication components.

✅ Verification successful

Error handling and loading states are consistently implemented across auth components

After analyzing the error handling patterns across authentication components:

  • All components properly manage loading states with setIsLoading/setTransferLoading
  • Error handling is consistent:
    • OAuth flows use toast notifications for generic errors
    • Email flows properly handle specific error cases (e.g., "form_identifier_exists")
    • Loading states are properly reset in both success and error cases
    • All errors are logged via console.error

The implementation in email-signup.tsx follows these same patterns and is consistent with the rest of the authentication flow.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for similar auth components and their error handling patterns
echo "Searching for auth components..."
rg -t tsx "useSignUp|useSignIn" --glob "apps/dashboard/app/auth/**"

echo "Checking error handling patterns..."
rg -t tsx "catch \(.*\) {" --glob "apps/dashboard/app/auth/**" -A 5

echo "Checking loading state usage..."
rg -t tsx "setIsLoading|setTransferLoading" --glob "apps/dashboard/app/auth/**" -A 2

Length of output: 603


Script:

#!/bin/bash
# Search for similar auth components and their error handling patterns
echo "Searching for auth components..."
rg "useSignUp|useSignIn" apps/dashboard/app/auth/

echo "Checking error handling patterns..."
rg "catch.*{" apps/dashboard/app/auth/ -A 5

echo "Checking loading state usage..."
rg "setIsLoading|setTransferLoading" apps/dashboard/app/auth/ -A 2

Length of output: 9560


Script:

#!/bin/bash
# Let's check the error handling patterns more specifically
echo "Checking error handling in sign-up components..."
rg "catch.*\(" apps/dashboard/app/auth/sign-up/ -B 2 -A 5

echo "Checking error handling in sign-in components..."
rg "catch.*\(" apps/dashboard/app/auth/sign-in/ -B 2 -A 5

echo "Checking toast error patterns..."
rg "toast\.error" apps/dashboard/app/auth/ -B 2 -A 2

Length of output: 9415

apps/dashboard/app/(app)/settings/root-keys/new/client.tsx (1)

Line range hint 1-95: LGTM! The implementation demonstrates solid practices

The code shows good attention to:

  • Error handling in TRPC mutations
  • Accessibility in UI components
  • Clean state management
  • Proper cleanup on dialog close

Also applies to: 118-324

@unrenamed
Copy link
Contributor Author

unrenamed commented Nov 15, 2024

Why use // biome-ignore?

Some hooks in the code are intended to be called only once when the component mounts. The variables used within these hooks are either stable (for example, route from next/navigation, which still lacks an ideal solution even as of 2024 — see Next.js Discussion) or pre-loaded before these hooks are invoked.

It may not be ideal in general, but this approach seems acceptable for now. Ideally, a separate review of all biome-ignore instances should be conducted to confirm that no better solutions exist.

Why disable all linting for a hook rather than ignoring a specific dependency diagnostic?

A targeted ignore like // biome-ignore lint/correctness/useExhaustiveDependencies(route): <explanation> would be ideal (see Biome useExhaustiveDependencies). However, this feature is only available in biome@1.8+, while our current version is 1.6.3. Upgrading would introduce many new errors and warnings that our existing biome.json configuration doesn’t yet cover. For details, see this Biome Discussion.

Why leave one warning unresolved?

One remaining warning looks a bit tricky and may benefit from input by a core team member for an optimal solution.

@unrenamed unrenamed changed the title fix: resolve all lint warnings but the last one fix: resolve 15 of 16 remaining lint warnings Nov 15, 2024
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