Skip to content

Comments

[WEB-2610] fix: workspace redirection from admin app#6122

Merged
pushya22 merged 1 commit intopreviewfrom
fix/admin-workspace-redirection
Nov 29, 2024
Merged

[WEB-2610] fix: workspace redirection from admin app#6122
pushya22 merged 1 commit intopreviewfrom
fix/admin-workspace-redirection

Conversation

@prateekshourya29
Copy link
Member

@prateekshourya29 prateekshourya29 commented Nov 29, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a derived value for the workspace URL, enhancing how the workspace's URL is displayed.
    • Improved slug validation in the workspace creation form.
  • Bug Fixes

    • Streamlined error handling for workspace creation, ensuring accurate error messaging.
  • Refactor

    • Updated the navigation method in the WorkspaceListItem component, replacing the Link component with a standard anchor tag for external links.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 29, 2024

Walkthrough

This pull request introduces changes to two components: WorkspaceCreateForm and WorkspaceListItem. In WorkspaceCreateForm, a new derived value workspaceBaseURL is added to streamline URL handling, and the slug input's validation logic is enhanced. In WorkspaceListItem, the navigation method is updated by replacing the Link component with a standard anchor element, maintaining the existing functionality while modifying how external links are handled.

Changes

File Path Change Summary
admin/app/workspace/create/form.tsx Added workspaceBaseURL for URL handling; modified slug input validation; streamlined error handling.
admin/core/components/workspace/list-item.tsx Replaced Link component with <a> element for navigation, retaining target="_blank" for new tab opening.

Possibly related PRs

  • minor improvements for workspace management #6099: This PR modifies the href attribute in the WorkspaceListItem component to use template literals and encodeURIComponent, which relates to the changes made in the main PR where workspaceBaseURL is introduced for handling the workspace URL.

Suggested labels

🌐frontend, 🧹chore

Suggested reviewers

  • SatishGandham
  • sriramveeraghanta

🐰 In the workspace, we hop and play,
With URLs that guide the way.
Slugs are checked, and links are bright,
Navigating smoothly, day and night!
Join us now, don’t delay,
In our cozy code ballet! 🌟


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

@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 (2)
admin/core/components/workspace/list-item.tsx (1)

Line range hint 74-78: Enhance accessibility for external link indicator

The external link icon should have an aria-label to improve accessibility.

 <div className="flex-shrink-0">
   <ExternalLink 
     size={14} 
+    aria-label="Opens in new tab"
     className="text-custom-text-400 group-hover:text-custom-text-200" 
   />
 </div>
admin/app/workspace/create/form.tsx (1)

Line range hint 129-156: Improve slug validation consistency and user feedback

The current slug validation implementation has several areas for improvement:

  1. Validation logic is duplicated between the name field rules and slug onChange
  2. Multiple validation states (invalidSlug, slugError, form validation) might lead to confusing user feedback
  3. No immediate validation against RESTRICTED_URLS

Consider this improved implementation:

 const WorkspaceCreateForm = () => {
+  const SLUG_REGEX = /^[a-zA-Z0-9_-]+$/;
+  const validateSlug = (value: string) => {
+    if (!SLUG_REGEX.test(value)) return "URLs can contain only (-), (_) and alphanumeric characters.";
+    if (RESTRICTED_URLS.includes(value)) return "This URL is reserved. Try something else.";
+    return true;
+  };

   // ... existing code ...

   <Controller
     control={control}
     name="slug"
     rules={{
       required: "The URL is a required field.",
       maxLength: {
         value: 48,
         message: "Limit your URL to 48 characters.",
       },
+      validate: validateSlug
     }}
     render={({ field: { onChange, value, ref } }) => (
       <Input
         id="workspaceUrl"
         type="text"
         value={value.toLocaleLowerCase().trim().replace(/ /g, "-")}
         onChange={(e) => {
-          if (/^[a-zA-Z0-9_-]+$/.test(e.target.value)) setInvalidSlug(false);
-          else setInvalidSlug(true);
           onChange(e.target.value.toLowerCase());
         }}
         ref={ref}
         hasError={Boolean(errors.slug)}
         placeholder="workspace-name"
         className="block w-full rounded-md border-none bg-transparent !px-0 py-2 text-sm"
       />
     )}
   />

This refactor:

  • Centralizes validation logic
  • Removes redundant state
  • Provides immediate feedback for reserved URLs
  • Makes the validation rules more maintainable
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7725b20 and 2a9805d.

📒 Files selected for processing (2)
  • admin/app/workspace/create/form.tsx (2 hunks)
  • admin/core/components/workspace/list-item.tsx (2 hunks)
🔇 Additional comments (2)
admin/core/components/workspace/list-item.tsx (1)

Line range hint 22-79: Verify workspace URL construction

The component uses WEB_BASE_URL for constructing workspace URLs. Let's verify this matches the expected behavior across the application.

✅ Verification successful

Workspace URL construction is consistent with application configuration

The verification shows that:

  1. WEB_BASE_URL is consistently defined across all common helper files using the environment variable NEXT_PUBLIC_WEB_BASE_URL
  2. The workspace URL construction in list-item.tsx follows the application's standard pattern
  3. The environment variable is properly configured in all Dockerfile configurations
  4. No inconsistent workspace URL construction patterns were found
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent usage of WEB_BASE_URL in workspace URL construction

# Search for other instances of workspace URL construction
echo "Searching for workspace URL construction patterns..."
rg -A 2 "WEB_BASE_URL.*workspace\.slug" --type typescript

# Check if WEB_BASE_URL is consistently imported
echo "Checking WEB_BASE_URL imports..."
rg "import.*WEB_BASE_URL.*from.*helpers/common\.helper" --type typescript

Length of output: 395


Script:

#!/bin/bash
# Let's try without typescript file type restriction and search for WEB_BASE_URL usage

# Search for workspace URL construction patterns
echo "Searching for workspace URL construction patterns..."
rg -A 2 "WEB_BASE_URL.*workspace\.slug"

# Check WEB_BASE_URL imports and definitions
echo -e "\nChecking WEB_BASE_URL imports and definitions..."
rg "WEB_BASE_URL"

# Look for the common helper file that might define WEB_BASE_URL
echo -e "\nLooking for common helper file..."
fd "common.helper" --type f

Length of output: 2837


Script:

#!/bin/bash
# Let's check the content of common helper files to verify WEB_BASE_URL definition consistency

echo "Checking common helper files content..."
cat admin/helpers/common.helper.ts
echo -e "\n---\n"
cat space/helpers/common.helper.ts
echo -e "\n---\n"
cat web/helpers/common.helper.ts

# Let's also check for any other workspace URL construction patterns that might not use WEB_BASE_URL
echo -e "\nChecking for other workspace URL patterns..."
rg -A 2 "workspace\.slug.*href" 

Length of output: 3522

admin/app/workspace/create/form.tsx (1)

Line range hint 44-71: Verify workspace creation error handling

The workspace creation flow should be tested to ensure proper error handling with the new URL validation.

✅ Verification successful

Workspace creation flow validation is properly implemented

The error handling in the workspace creation flow is correctly implemented with proper URL validation:

  1. The RESTRICTED_URLS constant contains a list of reserved slugs that cannot be used for workspaces
  2. The workspaceSlugCheck service validates the slug against both the API and the restricted URLs list
  3. The error handling flow includes:
    • Slug validation before creation
    • API-level error handling with proper error responses
    • UI feedback through toast messages for both success and failure cases
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other components that might be affected by the workspace URL changes
rg -l "createWorkspace|workspaceSlugCheck" --type typescript

# Check for any existing workspace URL validation patterns
ast-grep --pattern 'const $_ = /^[a-zA-Z0-9_-]+$/'

# Look for other uses of WEB_BASE_URL
rg "WEB_BASE_URL" --type typescript

Length of output: 221


Script:

#!/bin/bash
# Search for other components that might be affected by the workspace URL changes
rg -l "createWorkspace|workspaceSlugCheck"

# Check for any existing workspace URL validation patterns
rg "RESTRICTED_URLS" -A 2

# Look for workspace-related validation or URL handling
rg "workspaceSlug" -A 2

Length of output: 120224


Script:

#!/bin/bash
# Check for workspace slug validation patterns and restricted URLs
rg -A 5 "RESTRICTED_URLS" packages/constants/workspace.ts

# Look for workspace creation and slug check implementations
rg -A 10 "workspaceSlugCheck" web/core/services/workspace.service.ts admin/core/services/workspace.service.ts

Length of output: 1810

Comment on lines +22 to 25
<a
key={workspaceId}
href={`${WEB_BASE_URL}/${encodeURIComponent(workspace.slug)}`}
target="_blank"
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

Add security attributes for external link

The external link should include security attributes to protect against potential security vulnerabilities.

 <a
   key={workspaceId}
   href={`${WEB_BASE_URL}/${encodeURIComponent(workspace.slug)}`}
   target="_blank"
+  rel="noopener noreferrer"
   className="group flex items-center justify-between p-4 gap-2.5 truncate border border-custom-border-200/70 hover:border-custom-border-200 hover:bg-custom-background-90 rounded-md"
📝 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
<a
key={workspaceId}
href={`${WEB_BASE_URL}/${encodeURIComponent(workspace.slug)}`}
target="_blank"
<a
key={workspaceId}
href={`${WEB_BASE_URL}/${encodeURIComponent(workspace.slug)}`}
target="_blank"
rel="noopener noreferrer"
className="group flex items-center justify-between p-4 gap-2.5 truncate border border-custom-border-200/70 hover:border-custom-border-200 hover:bg-custom-background-90 rounded-md"

Comment on lines +41 to +42
// derived values
const workspaceBaseURL = encodeURI(WEB_BASE_URL || window.location.origin + "/");
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider improving URL handling robustness

The current implementation has several potential issues:

  1. The fallback to window.location.origin won't work during SSR
  2. No handling of trailing slashes could lead to double slashes in the final URL
  3. encodeURI might be unnecessary for the base URL and could cause issues with special characters

Consider this improved implementation:

- const workspaceBaseURL = encodeURI(WEB_BASE_URL || window.location.origin + "/");
+ const workspaceBaseURL = (WEB_BASE_URL || (typeof window !== 'undefined' ? window.location.origin : '')).replace(/\/?$/, '/');
📝 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
// derived values
const workspaceBaseURL = encodeURI(WEB_BASE_URL || window.location.origin + "/");
// derived values
const workspaceBaseURL = (WEB_BASE_URL || (typeof window !== 'undefined' ? window.location.origin : '')).replace(/\/?$/, '/');

@pushya22 pushya22 merged commit 5aeedd1 into preview Nov 29, 2024
@pushya22 pushya22 deleted the fix/admin-workspace-redirection branch November 29, 2024 13:32
@coderabbitai coderabbitai bot mentioned this pull request Dec 20, 2024
1 task
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