Skip to content

feat(dashboard): URL state synchronization for /settings/root-keys/new route#2218

Merged
chronark merged 7 commits intounkeyed:mainfrom
unrenamed:feat/url-sync-on-new-root-key-route
Oct 7, 2024
Merged

feat(dashboard): URL state synchronization for /settings/root-keys/new route#2218
chronark merged 7 commits intounkeyed:mainfrom
unrenamed:feat/url-sync-on-new-root-key-route

Conversation

@unrenamed
Copy link
Contributor

@unrenamed unrenamed commented Oct 5, 2024

What does this PR do?

Utilizes nuqs to establish two-way synchronization between URL query parameters and the page for creating a new root key. The permissions query parameter value corresponds to both workspace permissions and any scoped permissions for existing APIs, if available.

Fixes #2147

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

How should this be tested?

  • Test A
    • Navigate to the dashboard's /settings/root-keys/new page.
    • Select permissions from either or both the "Workspace Permissions" and "API-Specific Permissions" sections.
    • Verify that the selected permissions are reflected in the URL as query parameters.
  • Test B
    • Copy the URL generated in Test A.
    • Open a new browser tab and paste the URL.
    • Ensure that the /settings/root-keys/new page loads with the permissions from the URL query parameters automatically selected in the permissions tree.

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

  • New Features

    • Enhanced permissions handling with improved state management across navigation.
    • Introduced a new parser for unkeyed permissions to ensure safe query value parsing.
  • Improvements

    • Updated rendering logic for permissions selection to reflect the new state structure.
    • Modified TooltipTrigger component for better tooltip trigger area structure.
    • Optimized performance with a more efficient state initialization approach.

…w route

Utilize `nuqs` to establish two-way synchronization between URL query parameters and the page for creating a new root key. The `permissions` query parameter value corresponds to both workspace permissions and any scoped permissions for existing APIs, if available.
…page

Addresses a hydration error caused by a `<button>` element being a descendant of another `<button>`. The solution implements the `asChild` prop for Radix UI components, allowing the default rendered element to be replaced with the specified child while merging their props and behaviors.
@changeset-bot
Copy link

changeset-bot bot commented Oct 5, 2024

⚠️ No Changeset found

Latest commit: c5bb53c

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

@vercel
Copy link

vercel bot commented Oct 5, 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 Oct 7, 2024 10:40am
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 7, 2024 10:40am
play ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 7, 2024 10:40am
workflows ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 7, 2024 10:40am
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 7, 2024 10:40am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 5, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request focus on the Client component within client.tsx. A new parser function, parseAsUnkeyPermission, has been introduced to enhance query value parsing. The state management for selectedPermissions has transitioned from local state to useQueryState, ensuring state persistence across navigation. The rendering logic for permissions has been updated accordingly. Additionally, the TooltipTrigger component has been modified to improve its structure. Import statements have been updated to reflect these changes, indicating a shift towards improved data handling.

Changes

Files Change Summary
apps/dashboard/app/(app)/settings/root-keys/new/client.tsx Added parseAsUnkeyPermission parser function; replaced local state with useQueryState for selectedPermissions; updated rendering logic for permissions; modified TooltipTrigger component structure; updated import statements.

Assessment against linked issues

Objective Addressed Explanation
Automatically select required permissions from query params (#2147)
Maintain state consistency across navigations (#2147)

Possibly related PRs

Suggested labels

Bug, Good first issue, :joystick: 150 points

Suggested reviewers

  • mcstepp
  • chronark
  • perkinsjr

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.

@vercel
Copy link

vercel bot commented Oct 5, 2024

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

A member of the Team first needs to authorize it.

@github-actions github-actions bot added 🕹️ 300 points Feature New feature or request labels Oct 5, 2024
@github-actions
Copy link
Contributor

github-actions bot commented Oct 5, 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 (1)
apps/dashboard/app/(app)/settings/root-keys/new/client.tsx (1)

Line range hint 77-80: Prevent duplicate permissions in selectedPermissions

When adding permissions, the current implementation may introduce duplicates if the same permission is added multiple times. To ensure selectedPermissions contains unique permissions, consider checking if the permission already exists before adding it.

Apply this diff to prevent duplicates:

if (checked) {
-   return [...prevPermissions, permission];
+   return prevPermissions.includes(permission)
+     ? prevPermissions
+     : [...prevPermissions, permission];
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 34a1533 and cb3f8f2.

📒 Files selected for processing (1)
  • apps/dashboard/app/(app)/settings/root-keys/new/client.tsx (2 hunks)

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 (1)
apps/dashboard/app/(app)/settings/root-keys/new/client.tsx (1)

51-58: LGTM: Effective implementation of URL state synchronization

The switch from useState to useQueryState for selectedPermissions successfully implements URL state synchronization. The configuration with parseAsArrayOf(parseAsUnkeyPermission) ensures proper handling of permission arrays in the URL.

Consider extracting the useQueryState options into a separate constant for improved readability:

const queryStateOptions = {
  history: "push",
  shallow: false,
  clearOnDefault: true,
};

const [selectedPermissions, setSelectedPermissions] = useQueryState(
  "permissions",
  parseAsArrayOf(parseAsUnkeyPermission).withDefault([]).withOptions(queryStateOptions)
);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between cb3f8f2 and e32482f.

📒 Files selected for processing (1)
  • apps/dashboard/app/(app)/settings/root-keys/new/client.tsx (2 hunks)
🔇 Additional comments (3)
apps/dashboard/app/(app)/settings/root-keys/new/client.tsx (3)

25-45: LGTM: New imports and parser function align with PR objectives

The added imports and the new parseAsUnkeyPermission function are well-implemented to support URL state synchronization for permissions. This change directly addresses the PR objective of enabling two-way synchronization between URL query parameters and the page state.


330-340: LGTM: Improved PermissionToggle structure and accessibility

The changes to the PermissionToggle component enhance both its structure and accessibility:

  1. Wrapping the TooltipTrigger children in a div improves the layout and potential styling of the tooltip trigger area.
  2. Changing the Checkbox component's prop from onClick to onCheckedChange addresses the accessibility concern raised in the past review comments.

These modifications contribute to a more robust and user-friendly interface.


Line range hint 1-353: LGTM: Successful implementation of URL state synchronization for permissions

This PR successfully implements the URL state synchronization for the /settings/root-keys/new route, addressing the objectives outlined in the PR summary and the linked issue #2147. Key achievements include:

  1. Implementation of two-way synchronization between URL query parameters and the page state for permissions.
  2. Utilization of the nuqs library for efficient query state management.
  3. Maintenance of the existing component structure while introducing the new functionality.
  4. Improved user experience by allowing permissions to be reflected in and loaded from the URL.

The changes are well-implemented and do not introduce any new issues or inconsistencies. This feature will significantly enhance the usability of the root key creation process, allowing users to easily share and reproduce permission configurations.

Copy link
Collaborator

@chronark chronark left a comment

Choose a reason for hiding this comment

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

Works great, the only issue is that it's very easy to miss if an api scoped permission was checked cause the card doesn't expand by default

Could you expand all api cards if there's at least one checked permission?

https://share.cleanshot.com/mmKQRjTG

@unrenamed
Copy link
Contributor Author

While working on this PR, I noticed other places causing rehydration issues, likely due to HTML semantics violations or incorrect use of the Radix UI API (e.g., a inside a ; see TooltipTrigger API). The fix is to use the asChild prop for Radix components triggering these errors. I've fixed this in one place in this PR.

But, it might be worth opening a separate issue for this, though it's not critical right now. WDYT, @chronark?

@unrenamed
Copy link
Contributor Author

Works great, the only issue is that it's very easy to miss if an api scoped permission was checked cause the card doesn't expand by default

Could you expand all api cards if there's at least one checked permission?

https://share.cleanshot.com/mmKQRjTG

Good catch! Sure, I'll look into this.

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)
apps/dashboard/app/(app)/settings/root-keys/new/client.tsx (2)

51-58: LGTM: URL state synchronization for selectedPermissions

The implementation of useQueryState for selectedPermissions successfully achieves the two-way synchronization between URL query parameters and the page state. This aligns well with the PR objectives.

However, consider the implications of the clearOnDefault: true option. This might clear the URL when no permissions are selected, which could be confusing for users. Consider setting it to false to maintain the URL state even when the default value (empty array) is selected.


97-115: LGTM with suggestion: Efficient initialization of cardStatesMap

The new useEffect hook efficiently initializes cardStatesMap based on selected permissions. The use of a Set for O(1) membership checks is a great optimization, reducing the overall complexity to O(n + m) for large data sets.

However, the empty dependency array [] means this effect will only run once on component mount. Consider adding selectedPermissions and apis to the dependency array to ensure cardStatesMap is updated if these values change:

useEffect(() => {
  // ... existing code ...
}, [selectedPermissions, apis]);

This will ensure that cardStatesMap stays in sync with the latest permissions and API list.

🧰 Tools
🪛 Biome

[error] 101-101: Block statements are preferred in this position.

Unsafe fix: Wrap the statement with a JsBlockStatement

(lint/style/useBlockStatements)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e32482f and c5bb53c.

📒 Files selected for processing (1)
  • apps/dashboard/app/(app)/settings/root-keys/new/client.tsx (4 hunks)
🧰 Additional context used
🪛 Biome
apps/dashboard/app/(app)/settings/root-keys/new/client.tsx

[error] 101-101: Block statements are preferred in this position.

Unsafe fix: Wrap the statement with a JsBlockStatement

(lint/style/useBlockStatements)

🔇 Additional comments (4)
apps/dashboard/app/(app)/settings/root-keys/new/client.tsx (4)

25-25: LGTM: New imports and parser function for URL state synchronization

The new imports and the parseAsUnkeyPermission function are well-implemented to support the URL state synchronization feature. The use of unkeyPermissionValidation ensures safe parsing of query values, which aligns with the PR objectives.

Also applies to: 28-31, 39-46


Line range hint 80-87: LGTM: Updated handleSetChecked function

The handleSetChecked function has been correctly updated to work with the new state management using useQueryState. It maintains the expected behavior of adding or removing permissions from the selectedPermissions array.


342-352: LGTM: Improved accessibility in PermissionToggle component

The PermissionToggle component has been updated to use onCheckedChange instead of onClick for the Checkbox component. This change improves accessibility and addresses the issue mentioned in the past review comments. The implementation is correct and aligns with best practices for form controls.


Line range hint 1-364: Overall assessment: Well-implemented URL state synchronization feature

The changes in this PR successfully implement the URL state synchronization for the /settings/root-keys/new route, meeting the objectives outlined in the PR summary and linked issue #2147. The implementation uses the nuqs library effectively, handles permissions correctly, and includes performance optimizations.

Key improvements:

  1. Efficient state management using useQueryState
  2. Optimized initialization of cardStatesMap
  3. Enhanced accessibility in the PermissionToggle component

Minor suggestions have been made to further improve the code, including:

  1. Reconsidering the clearOnDefault option in useQueryState
  2. Updating the dependency array in the useEffect hook

Overall, this is a solid implementation that enhances user experience and addresses the feature request effectively.

@chronark
Copy link
Collaborator

chronark commented Oct 7, 2024

While working on this PR, I noticed other places causing rehydration issues, likely due to HTML semantics violations or incorrect use of the Radix UI API (e.g., a inside a ; see TooltipTrigger API). The fix is to use the asChild prop for Radix components triggering these errors. I've fixed this in one place in this PR.

But, it might be worth opening a separate issue for this, though it's not critical right now. WDYT, @chronark?

Huh I didn't see this before
Could you create an issue for this, @unrenamed ?
I was never able to figure out what we did wrong and ignored it :/

@chronark
Copy link
Collaborator

chronark commented Oct 7, 2024

The O(1) optimization is probably overkill, outside of some testing workspaces, nobody has more than a handful of apis, but it doesn't hurt I suppose.

@chronark chronark added this pull request to the merge queue Oct 7, 2024
Merged via the queue into unkeyed:main with commit eaa94bb Oct 7, 2024
@oss-gg
Copy link

oss-gg bot commented Oct 7, 2024

Awarding unrenamed: 300 points 🕹️ Well done! Check out your new contribution on oss.gg/unrenamed

@unrenamed
Copy link
Contributor Author

The O(1) optimization is probably overkill, outside of some testing workspaces, nobody has more than a handful of apis, but it doesn't hurt I suppose.

If a malicious user repeats permissions in the URL, the m * n solution could show its downside with exponential growth. The current solution, using a Set for uniqueness, should perform better in such cases.

You are right. I seem to be pulling things out of thin air though 😅. If anyone experiences a performance downgrade, it would be the malicious user themselves 😄

@unrenamed
Copy link
Contributor Author

While working on this PR, I noticed other places causing rehydration issues, likely due to HTML semantics violations or incorrect use of the Radix UI API (e.g., a inside a ; see TooltipTrigger API). The fix is to use the asChild prop for Radix components triggering these errors. I've fixed this in one place in this PR.
But, it might be worth opening a separate issue for this, though it's not critical right now. WDYT, @chronark?

Huh I didn't see this before Could you create an issue for this, @unrenamed ? I was never able to figure out what we did wrong and ignored it :/

yep, will do

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Feature New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Linking permissions when creating root keys

2 participants