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: Enhance API Key Detail Page: Change Permissions Visualization to Tree Format #2238

Merged
merged 14 commits into from
Oct 17, 2024

Conversation

RajuGangitla
Copy link
Contributor

@RajuGangitla RajuGangitla commented Oct 6, 2024

In this one, i changed the way of showing permissions in api key detail page previously we are using chart i changed it to tree structure

Fixes #2195

screen-capture.23.mp4

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • Chore (refactoring code, technical debt, workflow improvements)
  • [ x] 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
  • Test B

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
    • Introduced the PermissionTree component for enhanced visualization of roles and permissions.
    • Added the APIKeyDetailPage component for improved API key management.
  • Improvements
    • Enhanced the layout structure and font loading behavior across multiple applications for better performance and user experience.
    • Updated the RecursivePermission component for improved usability in permission management.
    • Improved clarity and consistency in type definitions for better developer experience.

Copy link

changeset-bot bot commented Oct 6, 2024

⚠️ No Changeset found

Latest commit: eac3e14

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

@CLAassistant
Copy link

CLAassistant commented Oct 6, 2024

CLA assistant check
All committers have signed the CLA.

Copy link
Contributor

coderabbitai bot commented Oct 6, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces significant updates to the APIKeyDetailPage component, replacing the previous chart visualization with a new PermissionTree component for displaying roles and their permissions. The PermissionTree component manages permissions hierarchically, enhancing the user interface for better clarity. The RecursivePermission component is now exportable for broader use. Font configurations in several layout files are updated to improve rendering. Additionally, type definitions in the OpenAPI file are refined for clarity and consistency.

Changes

File Change Summary
apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/page.tsx Updated to use PermissionTree, added imports, and adjusted rendering logic.
apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/permission-list.tsx Introduced PermissionTree component for hierarchical permission display.
apps/dashboard/app/(app)/authorization/roles/[roleId]/tree.tsx Exported RecursivePermission component and updated its props.
apps/dashboard/app/layout.tsx Updated Inter font configuration with new properties.
apps/engineering/app/layout.tsx Updated Inter font configuration with new properties.
apps/planetfall/app/layout.tsx Updated Inter font configuration with new properties.
apps/workflows/app/layout.tsx Updated Inter font configuration with new properties.
packages/api/src/openapi.d.ts Modified type definitions and interface structures for clarity and consistency.

Assessment against linked issues

Objective Addressed Explanation
Improve the display of assigned/not assigned permissions for API keys (Issue #2195)
Replace graph visualization with a checkbox tree for better accessibility (Issue #2195)
Ensure full permission names are visible with tooltips (Issue #2195) Tooltips for full permission names are not implemented.

Possibly related PRs

Suggested labels

Feature, Dashboard, :joystick: 300 points

Suggested reviewers

  • mcstepp
  • chronark
  • perkinsjr

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 6846063 and f48eb86.

📒 Files selected for processing (3)
  • apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/page.tsx (5 hunks)
  • apps/planetfall/app/layout.tsx (1 hunks)
  • apps/workflows/app/layout.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/page.tsx
  • apps/planetfall/app/layout.tsx
  • apps/workflows/app/layout.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

vercel bot commented Oct 6, 2024

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

Name Status Preview Comments Updated (UTC)
dashboard ✅ Ready (Inspect) Visit Preview 💬 1 unresolved
✅ 5 resolved
Oct 17, 2024 0:39am
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 17, 2024 0:39am
play ✅ Ready (Inspect) Visit Preview 💬 23 unresolved
✅ 5 resolved
Oct 17, 2024 0:39am
workflows ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 17, 2024 0:39am
www ✅ Ready (Inspect) Visit Preview 💬 2 unresolved
✅ 1 resolved
Oct 17, 2024 0:39am

Copy link

vercel bot commented Oct 6, 2024

@RajuGangitla 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

github-actions bot commented Oct 6, 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: 3

🧹 Outside diff range and nitpick comments (14)
apps/workflows/app/layout.tsx (2)

4-8: Improved font configuration, consider adding preload.

The changes to the Inter font configuration are good improvements:

  1. display: 'swap' is a recommended setting that improves perceived loading performance by showing a fallback font until the custom font is loaded.
  2. adjustFontFallback: false gives you more control over the font fallback behavior.

These changes can enhance the rendering of text on the page, contributing to an improved user experience.

Consider adding the preload option to further optimize font loading:

 const inter = Inter({
   subsets: ["latin"],
   display: 'swap',
-  adjustFontFallback: false
+  adjustFontFallback: false,
+  preload: true
 });

This will preload the font files, potentially reducing the time it takes for the custom font to appear.


Permissions Tree Structure Not Found

No implementations of the permissions tree structure were detected in the identified files. Please ensure that the main objective of changing the permissions visualization to a tree format has been fully addressed.

🔗 Analysis chain

Line range hint 1-30: Note on PR objectives alignment

While the font configuration improvements in this file are beneficial for the overall user experience, they don't directly address the main objective of this PR, which is to change the permissions visualization from a chart format to a tree structure.

To ensure we're not missing any relevant changes, let's verify if there are other files that implement the tree structure for permissions:

This will help us locate the files where the core changes for the permissions visualization are implemented.


To accurately locate the relevant files, we'll adjust our search patterns:


To verify the implementation of the permissions tree structure in the identified files, please run the following scripts:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for files that might contain the new tree structure implementation
rg -i -t tsx -t ts "permission.*tree" --files-with-matches

# Search for files that might contain changes related to API key permissions
rg -i -t tsx -t ts "api.*key.*permission" --files-with-matches

Length of output: 181


Script:

#!/bin/bash
# Search for files that might contain the new tree structure implementation
rg 'permission.*tree' --glob '*.tsx' --glob '*.ts' --files-with-matches

# Search for files that might contain changes related to API key permissions
rg 'api.*key.*permission' --glob '*.tsx' --glob '*.ts' --files-with-matches

Length of output: 312


Script:

#!/bin/bash
# Search for tree structure implementation in the identified files

# Define the list of files to search
FILES=(
  "apps/dashboard/app/(app)/settings/root-keys/new/client.tsx"
  "apps/dashboard/app/(app)/settings/root-keys/[keyId]/page.tsx"
  "apps/api/src/routes/v1_keys_updateKey.ts"
)

# Define the search patterns related to tree structures
PATTERNS=(
  "permissionsTree"
  "treeView"
  "TreeComponent"
  "renderTree"
  "recursive"
)

# Iterate over each file and search for the patterns
for FILE in "${FILES[@]}"; do
  for PATTERN in "${PATTERNS[@]}"; do
    rg "$PATTERN" "$FILE" --context 2
  done
done

Length of output: 2113

apps/engineering/app/layout.tsx (1)

9-10: Consider the trade-offs of the new font configuration

The changes to the Inter font configuration aim to optimize font loading and rendering:

  1. display: 'swap' improves perceived performance by showing content quickly with a fallback font.
  2. adjustFontFallback: false gives more control over font fallback behavior.

While these changes can enhance initial content display speed, they come with potential trade-offs:

  • The font swap might be noticeable to users, potentially affecting the user experience.
  • Disabling adjustFontFallback could increase layout shift, impacting Cumulative Layout Shift (CLS) metrics.

Consider the following recommendations:

  1. Monitor CLS metrics after this change to ensure they remain within acceptable limits.
  2. If CLS increases significantly, consider using font-display: optional instead of swap to prioritize layout stability.
  3. Implement a font loading strategy using next/font's preload option to further optimize font loading.
  4. Use fontWeight and fontStyle options to load only the necessary font variants, reducing the overall font file size.

Example implementation:

const inter = Inter({
  subsets: ["latin"],
  display: 'swap',
  adjustFontFallback: false,
  preload: true,
  weight: ['400', '700'],
  style: ['normal', 'italic'],
});

These suggestions aim to balance performance improvements with user experience and web vitals metrics.

apps/dashboard/app/(app)/authorization/roles/[roleId]/tree.tsx (2)

59-61: LGTM! Consider using TypeScript's Pick utility type for props.

The export of the RecursivePermission component and the updated props align well with the PR objectives of improving consistency and enhancing the permissions visualization. This change allows for better reusability across the application.

To improve type safety and readability, consider using TypeScript's Pick utility type for the props:

export const RecursivePermission: React.FC<
  Pick<NestedPermission, 'id' | 'name' | 'permissions' | 'checked' | 'description'> & 
  { k: string; roleId: string; openAll: boolean }
> = ({ k, openAll, id, name, permissions, roleId, checked, description }) => {
  // ... component implementation
};

This approach ensures that only the necessary props from NestedPermission are included, making the component's interface more explicit and maintainable.


Line range hint 1-124: Great implementation of the tree structure for permissions visualization.

The changes successfully address the main objectives of the PR by implementing a tree structure for permissions visualization. This new structure should provide a clearer and more accessible view of permissions, especially when dealing with numerous permissions.

Consider adding a brief comment at the top of the file explaining the purpose of the Tree and RecursivePermission components. This would enhance the maintainability of the code and help other developers understand the components' roles quickly.

Example:

/**
 * This file contains components for rendering a tree structure of permissions.
 * Tree: The main component that renders the entire permissions tree.
 * RecursivePermission: A reusable component that recursively renders nested permissions.
 */
apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/permission-list.tsx (1)

74-74: Clean up unnecessary CSS selector

The CSS selector [&[data-state=open]>svg]:rotate-90 in the CollapsibleTrigger className may be unnecessary if you handle the rotation elsewhere. Simplifying it can improve readability.

Apply this diff:

-<CollapsibleTrigger className="flex items-center gap-1 transition-all [&[data-state=open]>svg]:rotate-90 ">
+<CollapsibleTrigger className="flex items-center gap-1 transition-all">
apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/page.tsx (6)

14-14: Consider removing 'Role' if it's unused

The imported 'Role' from "@/lib/db" at line 14 does not appear to be used in the code. Removing unnecessary imports can help keep the codebase clean.

Apply this diff to remove the unused import:

-import { and, db, eq, isNull, Role, schema } from "@/lib/db";
+import { and, db, eq, isNull, schema } from "@/lib/db";

28-29: Use 'import type' for type-only imports

The imports at lines 28-29 are only used as types. Using import type ensures they are removed during transpilation, avoiding unnecessary module loading.

Apply this diff to use import type:

-import RolePermissionsTree from "./permission-list";
+import type RolePermissionsTree from "./permission-list";

-import { NestedPermissions } from "@/app/(app)/authorization/roles/[roleId]/tree";
+import type { NestedPermissions } from "@/app/(app)/authorization/roles/[roleId]/tree";
🧰 Tools
🪛 Biome

[error] 28-29: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the transpilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)


163-163: Possible typo: Rename 'roleTee' to 'roleTree'

The variable roleTee at line 163 may be a typo. Renaming it to roleTree improves readability and aligns with its purpose of representing a tree structure.

Apply this diff to correct the variable name:

-const roleTee = key.workspace.roles.map((role) => {
+const roleTree = key.workspace.roles.map((role) => {

Remember to update all occurrences of roleTee to roleTree throughout the file.


170-176: Avoid reusing variable name 'p' in nested scopes to prevent confusion

At line 170, p is declared as const p = parts[i];, and within the .some() callback at line 176, p is reused as the parameter (p). While JavaScript allows variable shadowing, using different variable names enhances clarity.

Consider renaming the parameter in the .some() callback:

-checked: role.permissions.some((p) => p.permissionId === permission.id),
+checked: role.permissions.some((perm) => perm.permissionId === permission.id),

185-185: Use 'const' instead of 'let' for variables not reassigned

The variable data at line 185 is never reassigned after its initial declaration. Using const is preferred for variables that remain constant.

Apply this diff to use const:

-let data = {
+const data = {
🧰 Tools
🪛 Biome

[error] 185-185: This let declares a variable that is only assigned once.

'data' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)


352-352: Consider removing commented-out code

The commented-out code at line 352 seems to be obsolete. Removing it can help maintain a clean and focused codebase.

Apply this diff to remove the commented code:

-{/* <Chart ... /> */}
packages/api/src/openapi.d.ts (2)

Line range hint 1176-1208: Deprecation notice for ratelimit properties in updateKey

The ratelimit property within the updateKey request has deprecated fields type, refillRate, and refillInterval. Ensure that any existing implementations are updated to accommodate these changes and that deprecated fields are no longer used.

Consider updating documentation to reflect these deprecations and guide users towards the new properties.


1438-1459: Add missing failure count in getVerifications response

The verifications object includes counts for success, rateLimited, and usageExceeded, but it's missing a failure count to represent other types of failures. Including this could provide more comprehensive analytics.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 10749fe and dd0bb12.

📒 Files selected for processing (8)
  • apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/page.tsx (6 hunks)
  • apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/permission-list.tsx (1 hunks)
  • apps/dashboard/app/(app)/authorization/roles/[roleId]/tree.tsx (1 hunks)
  • apps/dashboard/app/layout.tsx (1 hunks)
  • apps/engineering/app/layout.tsx (1 hunks)
  • apps/planetfall/app/layout.tsx (1 hunks)
  • apps/workflows/app/layout.tsx (1 hunks)
  • packages/api/src/openapi.d.ts (34 hunks)
🧰 Additional context used
🪛 Biome
apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/page.tsx

[error] 28-29: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the transpilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)


[error] 185-185: This let declares a variable that is only assigned once.

'data' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)

🔇 Additional comments (8)
apps/planetfall/app/layout.tsx (1)

5-9: LGTM! Consider monitoring layout shifts.

The changes to the Inter font configuration look good and can potentially improve font loading behavior:

  1. display: 'swap' can prevent "flash of invisible text" (FOIT) and improve perceived loading performance.
  2. adjustFontFallback: false gives more control over font rendering.

However, disabling adjustFontFallback might lead to more noticeable layout shifts. Please monitor the impact of this change on the user experience. You can use the following script to check for other instances where adjustFontFallback is used in the project:

This will help ensure consistency across the project and identify any potential areas where layout shifts might occur.

✅ Verification successful

Configuration Verified!

The adjustFontFallback: false setting is consistently applied across all relevant layout files, ensuring uniform font rendering behavior throughout the project.

  • Consistency: All identified layout.tsx files have adjustFontFallback set to false, indicating a deliberate and uniform configuration.

Please continue to monitor the application's user experience to ensure that this setting does not introduce any unexpected layout shifts.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for other instances of adjustFontFallback in the project

# Search for adjustFontFallback in TypeScript and JavaScript files
rg --type-add 'web:*.{ts,tsx,js,jsx}' -t web 'adjustFontFallback'

Length of output: 300

apps/dashboard/app/layout.tsx (1)

18-19: Approved: Font configuration changes improve performance, but monitor user experience.

The additions of display: 'swap' and adjustFontFallback: false to the Inter font configuration are good optimizations:

  1. display: 'swap' improves perceived performance by showing text immediately with a fallback font.
  2. adjustFontFallback: false helps reduce layout shifts when the custom font loads.

These changes align with the overall goal of enhancing user experience. However, they may introduce a more noticeable font swap effect.

To ensure these changes don't negatively impact user experience, consider monitoring the following:

  1. Initial page load time
  2. Cumulative Layout Shift (CLS) metrics
  3. User feedback regarding any noticeable font changes during page load

You can use the following script to check for any other font configurations in the project that might need similar optimizations:

apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/permission-list.tsx (1)

85-85: Verify CopyButton prop usage

Ensure that the CopyButton component accepts a value prop and handles role.name correctly. If the prop name differs or additional configuration is required, please adjust accordingly.

packages/api/src/openapi.d.ts (5)

9-10: Improved clarity in XOR and OneOf type definitions

Adding parentheses around the conditional expressions in the XOR and OneOf type definitions ensures correct operator precedence and enhances readability.


521-521: Updated code property in V1KeysVerifyKeyResponse reflects all key statuses

The code property now includes all possible key statuses, including "VALID", providing a comprehensive representation of key verification results.


547-551: Enhanced PermissionQuery type definition for better clarity

Reformatting the PermissionQuery type definition using the OneOf helper type improves readability and maintains consistency across type definitions.


Line range hint 2536-2745: Verify the handling of deprecated properties in migration endpoints

The migration endpoints (v1.migrations.createKeys and v1.migrations.enqueueKeys) include deprecated properties like refillRate and refillInterval in their ratelimit configurations. Ensure that these endpoints are updated to use the new properties and handle deprecations appropriately.

Run the following script to identify deprecated properties in migration-related code:


596-610: Ensure all usages of V1KeysVerifyKeyRequest accommodate the new ratelimits structure

The ratelimits property in V1KeysVerifyKeyRequest has been updated from an object to an array of objects, allowing for multiple ratelimit configurations. Please verify that all consumers of V1KeysVerifyKeyRequest have been updated accordingly to prevent potential runtime errors.

Run the following script to locate usages of V1KeysVerifyKeyRequest and check for ratelimits usage:

@chronark
Copy link
Collaborator

chronark commented Oct 8, 2024

please sign the CLA and address the comments above

@RajuGangitla
Copy link
Contributor Author

RajuGangitla commented Oct 8, 2024

i addressed the comments above and signed the cla

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: 2

🧹 Outside diff range and nitpick comments (3)
apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/page.tsx (3)

6-6: LGTM! New imports enhance permission visualization.

The addition of NestedPermissions type and PermissionTree component aligns well with the PR objective of improving permission visualization. This change should lead to a more intuitive and hierarchical representation of permissions.

Consider using a more descriptive name for the imported component, such as PermissionTreeComponent, to avoid potential naming conflicts and improve code readability.

Also applies to: 27-27


160-190: LGTM! Effective transformation of permissions to hierarchical structure.

The roleTee creation logic successfully transforms the flat permission structure into a nested one, which is crucial for the new tree-based visualization. This aligns well with the PR objective of improving permission representation.

Consider extracting the nested permission creation logic into a separate function for improved readability and maintainability. For example:

function createNestedPermissions(permissions: Permission[], rolePermissions: RolePermission[]): NestedPermissions {
  const nested: NestedPermissions = {};
  for (const permission of permissions) {
    let n = nested;
    const parts = permission.name.split(".");
    for (let i = 0; i < parts.length; i++) {
      const p = parts[i];
      if (!(p in n)) {
        n[p] = {
          id: permission.id,
          name: permission.name,
          description: permission.description,
          checked: rolePermissions.some((rp) => rp.permissionId === permission.id),
          part: p,
          permissions: {},
          path: parts.slice(0, i).join("."),
        };
      }
      n = n[p].permissions;
    }
  }
  return nested;
}

// Usage
const roleTee = key.workspace.roles.map((role) => ({
  id: role.id,
  name: role.name,
  description: role.description,
  keyId: key.id,
  active: key.roles.some((keyRole) => keyRole.roleId === role.id),
  nestedPermissions: createNestedPermissions(key.workspace.permissions, role.permissions),
}));

This refactoring would improve code organization and make the roleTee creation more modular and easier to understand.


Line range hint 345-358: LGTM! Successful implementation of tree-based permission visualization.

The replacement of the Chart component with PermissionTree directly addresses the PR objective of changing the permissions visualization to a tree format. This should provide a more intuitive and hierarchical representation of permissions.

Consider removing the commented-out Chart component code if it's no longer needed. If you're keeping it temporarily for reference or easy rollback, add a TODO comment explaining why it's still there and when it can be removed. For example:

// TODO: Remove this commented code once the new PermissionTree component is fully tested and approved
// <Chart
//   apiId={props.params.apiId}
//   key={JSON.stringify(key)}
//   data={key}
//   roles={key.workspace.roles.map((r) => ({
//     ...r,
//     active: key.roles.some((keyRole) => keyRole.roleId === r.id),
//   }))}
//   permissions={key.workspace.permissions.map((p) => ({
//     ...p,
//     active: transientPermissionIds.has(p.id),
//   }))}
// />

This will help maintain clean code and provide context for other developers.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 66e39d0 and 6846063.

📒 Files selected for processing (6)
  • apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/page.tsx (6 hunks)
  • apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/permission-list.tsx (1 hunks)
  • apps/dashboard/app/layout.tsx (1 hunks)
  • apps/engineering/app/layout.tsx (1 hunks)
  • apps/planetfall/app/layout.tsx (1 hunks)
  • apps/workflows/app/layout.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • apps/dashboard/app/layout.tsx
  • apps/engineering/app/layout.tsx
  • apps/planetfall/app/layout.tsx
  • apps/workflows/app/layout.tsx
🧰 Additional context used
🔇 Additional comments (5)
apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/permission-list.tsx (4)

1-36: LGTM: Imports and type definitions are well-structured

The imports and type definitions in this section are clear, appropriate, and well-organized. They provide a solid foundation for the component's implementation.


46-57: LGTM: Card header and expand/collapse functionality

The card header is well-structured, and the expand/collapse functionality for all roles is implemented correctly. The use of the Switch component for this purpose is appropriate and user-friendly.


94-113: LGTM: Nested permissions rendering

The implementation of nested permissions rendering using the RecursivePermission component is correct and well-structured. All necessary props are passed appropriately, ensuring proper functionality of the nested permissions display.


1-113: Overall implementation aligns well with PR objectives

The PermissionTree component successfully addresses the main objectives of the PR:

  1. It replaces the previous chart format with a tree structure, improving clarity and accessibility of the permissions visualization.
  2. The collapsible structure allows for better management of numerous permissions, addressing the issue of cluttered views.
  3. The implementation is consistent with other areas of the application, using familiar UI components.

The component is well-structured, follows React best practices, and provides a user-friendly interface for managing API key permissions. The suggested optimizations, if implemented, will further improve the component's performance and readability.

Great job on implementing this enhancement!

apps/dashboard/app/(app)/apis/[apiId]/keys/[keyAuthId]/[keyId]/page.tsx (1)

Line range hint 1-424: Overall, excellent implementation of tree-based permission visualization.

The changes in this file successfully address the main objective of the PR by enhancing the API Key Detail Page with a tree-based permissions visualization. The implementation of PermissionTree and the creation of a nested permissions structure (roleTee) should significantly improve the clarity and accessibility of the permissions display.

Key improvements:

  1. Introduction of a hierarchical permission structure
  2. Replacement of the chart visualization with a tree-based component
  3. Maintained functionality for fetching and processing API key data

These changes align well with the goal of providing a more straightforward and consistent user experience, especially when dealing with numerous permissions.

To further enhance the implementation:

  1. Consider the suggested refactorings for improved code organization and readability.
  2. Clean up commented-out code or add explanatory TODO comments if temporary.
  3. Ensure thorough testing of the new PermissionTree component to validate its functionality across various permission scenarios.

Great job on improving the user experience and addressing the issues raised in #2195!

@RajuGangitla
Copy link
Contributor Author

@chronark do i need to change anything else

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.

This PR changes font rendering in 4 apps, can we revert that please?
what does this solve? How is it related to this PR?

auto-merge was automatically disabled October 13, 2024 09:16

Head branch was pushed to by a user without write access

@RajuGangitla
Copy link
Contributor Author

@chronark can you please check now

@Kartikey060105
Copy link

/assign

Copy link

oss-gg bot commented Oct 15, 2024

The /assign command can only be used on issues, not on pull requests.

@RajuGangitla
Copy link
Contributor Author

RajuGangitla commented Oct 17, 2024

finally wait is over

its merging

@chronark chronark merged commit fb848c0 into unkeyed:main Oct 17, 2024
23 checks passed
Copy link

oss-gg bot commented Oct 17, 2024

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

Flo4604 pushed a commit to Flo4604/unkey that referenced this pull request Oct 19, 2024
… Tree Format (unkeyed#2238)

* fix:changed the permission view

* fixed issue comments

* [autofix.ci] apply automated fixes

* removed font

---------

Co-authored-by: Andreas Thomas <[email protected]>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
github-merge-queue bot pushed a commit that referenced this pull request Oct 20, 2024
* fix: Missing plan check and ip whitelist parsing

* fix: adjust tests for ipwhitelist

* fix: Rename error code

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* fix: ipwhitelist via features vs enterprise plan

* fix: invert condition

* chore: add cache log

* fix: ensure workspace is loaded (#2470)

* chore: more logging and retries (#2475)

* Update 7_create_a_template.md (#2471)

* increase override limit

* Update create-new-override.tsx

* fix: Enhance API Key Detail Page: Change Permissions Visualization to Tree Format (#2238)

* fix:changed the permission view

* fixed issue comments

* [autofix.ci] apply automated fixes

* removed font

---------

Co-authored-by: Andreas Thomas <[email protected]>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>

* fix: show shallow permissions followed by nested in alphabetical order (#2273)

* fix: show shallow permissions followed by nested in alphabetical order

* fix: correct the sorting of nested permissions top level keys

* [autofix.ci] apply automated fixes

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>

* Add Template to Markdown (#2362)

Co-authored-by: Andreas Thomas <[email protected]>

* fix: retry on any error with disabled cache

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: chronark <[email protected]>
Co-authored-by: Chirag Arora <[email protected]>
Co-authored-by: RajuGangitla <[email protected]>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Anne Deepa Prasanna <[email protected]>
Co-authored-by: djnovin <[email protected]>
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.

[🕹️] API Key sub-optimal display permissions of permissions
4 participants