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: Variable ui cleanup #203

Merged
merged 1 commit into from
Nov 7, 2024
Merged

fix: Variable ui cleanup #203

merged 1 commit into from
Nov 7, 2024

Conversation

adityachoudhari26
Copy link
Contributor

@adityachoudhari26 adityachoudhari26 commented Nov 7, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new EditRunbookDialog for editing runbooks with enhanced form validation and state management.
    • Added an optional exclude prop to the ConfigTypeSelector to hide specific variable types.
  • Bug Fixes

    • Removed support for "choice" type configuration in the variable creation dialog, simplifying options.
  • Improvements

    • Updated dropdown menus in RunbookRow for a more streamlined management experience of runbooks.

Copy link
Contributor

coderabbitai bot commented Nov 7, 2024

Walkthrough

The changes in this pull request primarily focus on enhancing the ConfigTypeSelector component by adding an optional exclude prop, which allows specific variable types to be hidden from the selector. Additionally, the CreateVariableDialog component has been modified to remove the handling of "choice" type configurations. A new component, EditRunbookDialog, has been introduced for editing runbooks, replacing the previous editing mechanism. The RunbookRow component has also been updated to utilize the new dialog for editing runbooks. Finally, the API router for runbooks has been adjusted to handle variable updates more robustly.

Changes

File Change Summary
apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/_components/variables/ConfigFields.tsx Added an optional exclude prop to ConfigTypeSelector for excluding variable types from display. Updated rendering logic for SelectItem components based on the exclude array.
apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/releases/CreateVariableDialog.tsx Removed handling for "choice" configuration, including the import of ChoiceConfigFields. Simplified the onChange handler for ConfigTypeSelector to exclude "choice" type. Removed JSON representation display from the dialog.
apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/runbooks/EditRunbookDialog.tsx Introduced a new component for editing runbooks, utilizing a form with validation and state management. Integrated various UI components and handled API interactions for runbook updates.
apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/runbooks/RunbookRow.tsx Replaced EditAgentConfigDialog with EditRunbookDialog. Removed job agent editing logic and updated dropdown menu options to streamline runbook management.
packages/api/src/router/runbook.ts Updated update and create mutations to include variables as an array in their input schema. Enhanced the update logic to handle transactions for updating and refreshing runbook variables in the database.

Possibly related PRs

  • fix: Edit deployment variable #164: The EditVariableDialog component introduced in this PR is related to the ConfigTypeSelector component in the main PR, as both involve managing variable data and user interactions within dialogs.
  • init target variables #166: The changes in this PR regarding the initialization of target variables are directly related to the enhancements made in the main PR, which focuses on the configurability of variable types in the ConfigTypeSelector.
  • fix: Init target variable ui #171: The CreateTargetVariableDialog component added in this PR is relevant as it also deals with the creation and management of target variables, similar to the changes made in the main PR regarding variable selection and display.
  • fix: Target variables #170: This PR introduces target variables, which aligns with the main PR's focus on enhancing the ConfigTypeSelector for better variable management.
  • Fix: Approval Usability #172: The usability improvements in the approval process may indirectly relate to the user interface changes in the main PR, particularly in how variable selections are presented and managed in dialogs.

Suggested reviewers

  • jsbroks

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.

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 (4)
apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/runbooks/RunbookRow.tsx (1)

46-53: Consider removing redundant cursor-pointer class

The cursor-pointer class might be redundant as DropdownMenuItem components typically handle cursor styling internally.

-              className="flex cursor-pointer items-center gap-2"
+              className="flex items-center gap-2"
apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/_components/variables/ConfigFields.tsx (2)

44-55: Consider type safety improvements and performance optimization

While the implementation works, there are a few areas for improvement:

  1. Type Safety: Consider using a union type for excluded types to prevent invalid strings:
type VariableType = "string" | "number" | "boolean" | "choice";
exclude?: VariableType[];
  1. Performance: For larger exclude lists, consider using a Set for O(1) lookups:
const excludeSet = new Set(exclude);
// Then use: !excludeSet.has("string")

44-55: Consider maintaining consistency with RunbookConfigTypeSelector

The RunbookConfigTypeSelector component has similar functionality but doesn't support the exclude prop. Consider either:

  1. Adding the exclude prop to RunbookConfigTypeSelector for consistency
  2. Creating a shared base component that both selectors extend

This would improve maintainability and reduce code duplication.

packages/api/src/router/runbook.ts (1)

109-129: Refactor transaction logic using async/await for better readability and consistency

Consider refactoring the transaction logic to use async/await instead of chained .then() calls. This will improve readability and make error handling more straightforward. Additionally, returning the updated runbook along with its variables, similar to the create mutation, would maintain consistency in API responses.

Apply this diff to refactor the transaction logic:

-          ctx.db.transaction((tx) =>
-            tx
-              .update(SCHEMA.runbook)
-              .set(input.data)
-              .where(eq(SCHEMA.runbook.id, input.id))
-              .returning()
-              .then(takeFirst)
-              .then((rb) =>
-                tx
-                  .delete(SCHEMA.runbookVariable)
-                  .where(eq(SCHEMA.runbookVariable.runbookId, rb.id))
-                  .then(() =>
-                    tx.insert(SCHEMA.runbookVariable).values(
-                      input.data.variables.map((v) => ({
-                        ...v,
-                        runbookId: rb.id,
-                      })),
-                    ),
-                  ),
-              ),
-          ),
+          ctx.db.transaction(async (tx) => {
+            const rb = await tx
+              .update(SCHEMA.runbook)
+              .set(input.data)
+              .where(eq(SCHEMA.runbook.id, input.id))
+              .returning()
+              .then(takeFirst);
+
+            await tx
+              .delete(SCHEMA.runbookVariable)
+              .where(eq(SCHEMA.runbookVariable.runbookId, rb.id));
+
+            const vars = await tx.insert(SCHEMA.runbookVariable).values(
+              input.data.variables.map((v) => ({
+                ...v,
+                runbookId: rb.id,
+              })),
+            ).returning();
+
+            return { ...rb, variables: vars };
+          }),
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7a4cba9 and 6cbd470.

📒 Files selected for processing (5)
  • apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/_components/variables/ConfigFields.tsx (1 hunks)
  • apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/releases/CreateVariableDialog.tsx (1 hunks)
  • apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/runbooks/EditRunbookDialog.tsx (1 hunks)
  • apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/runbooks/RunbookRow.tsx (3 hunks)
  • packages/api/src/router/runbook.ts (1 hunks)
🔇 Additional comments (8)
apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/runbooks/RunbookRow.tsx (3)

5-5: LGTM! Import changes are well-structured

The new imports are properly scoped and follow good practices.

Also applies to: 15-15


54-66: Consider adding error boundary and removing redundant class

  1. The cursor-pointer class issue mentioned above applies here as well.
  2. Consider wrapping the EditRunbookDialog in an error boundary to gracefully handle any rendering errors.
import { ErrorBoundary } from 'react-error-boundary';

// Wrap the dialog in an error boundary
<ErrorBoundary fallback={<div>Something went wrong with the runbook editor</div>}>
  <EditRunbookDialog
    runbook={runbook}
    workspace={workspace}
    jobAgents={jobAgents}
  >
    {/* ... */}
  </EditRunbookDialog>
</ErrorBoundary>

54-58: Verify EditRunbookDialog implementation

Let's ensure the new EditRunbookDialog component is properly implemented with the expected props interface.

✅ Verification successful

EditRunbookDialog integration is correctly implemented

The component exists and its props interface matches the usage perfectly:

  • Component accepts required props: workspace, jobAgents, runbook (with nested variables)
  • Props types are properly defined and match the schema types from @ctrlplane/db/schema
  • The component is correctly used in RunbookRow with all required props being passed
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify EditRunbookDialog implementation and props interface

# Check if the component file exists and contains the expected props
rg -A 10 "export.*EditRunbookDialog.*=.*{" --type typescript

# Check for proper prop types definition
rg "interface.*EditRunbookDialog.*Props" --type typescript

Length of output: 284


Script:

#!/bin/bash
# Search for EditRunbookDialog component definition
rg -l "EditRunbookDialog" 

# Find the component implementation
ast-grep --pattern 'export const EditRunbookDialog = $_'

# Find interface/type definitions for props
ast-grep --pattern 'interface EditRunbookDialogProps {
  $$$
}'

# Find type definitions using type keyword
ast-grep --pattern 'type EditRunbookDialogProps = {
  $$$
}'

Length of output: 390


Script:

#!/bin/bash
# Let's examine the EditRunbookDialog component implementation
cat "apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/runbooks/EditRunbookDialog.tsx"

# Also check the actual usage in RunbookRow
cat "apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/runbooks/RunbookRow.tsx"

Length of output: 8742

apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/releases/CreateVariableDialog.tsx (2)

117-118: LGTM! Clean and focused changes.

The changes effectively remove the "choice" type configuration by:

  1. Simplifying the onChange handler to directly update the type
  2. Explicitly excluding the "choice" type using the new exclude prop

This aligns well with the PR objective of cleaning up the variable UI.


117-118: Verify impact on existing variables.

Since we're removing support for "choice" type variables, we should verify that there are no existing variables of this type that would be affected.

apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/_components/variables/ConfigFields.tsx (2)

37-38: LGTM: Clean prop addition

The new optional exclude prop is well-typed and follows TypeScript best practices.


37-55: Verify usage of ConfigTypeSelector

Let's verify that all existing usages of ConfigTypeSelector handle the new optional prop correctly.

✅ Verification successful

The new exclude prop is safely implemented and used correctly

The verification shows that:

  • There are only two usages of ConfigTypeSelector:
    1. In CreateVariableDialog.tsx where it's used with exclude={["choice"]}, properly handling the new prop
    2. A separate RunbookConfigTypeSelector component that doesn't use the exclude prop, as it's a different component

Since the exclude prop is optional and the only existing usage already provides the prop correctly, there are no breaking changes or issues to address.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for all usages of ConfigTypeSelector
ast-grep --pattern 'ConfigTypeSelector $$$'

# Also check for any potential test files
fd -e test.tsx -e spec.tsx -x grep -l "ConfigTypeSelector"

Length of output: 104


Script:

#!/bin/bash
# Search for usages of ConfigTypeSelector with ripgrep for better context
rg "ConfigTypeSelector" -A 3 -B 3

# Also search for any imports of ConfigTypeSelector
rg "import.*ConfigTypeSelector"

Length of output: 6121

packages/api/src/router/runbook.ts (1)

103-105: The addition of 'variables' to the update input schema is appropriate

Extending data to include variables in the update mutation aligns with the handling of runbook variables and ensures they can be updated correctly.

Comment on lines +59 to +63
defaultValues: {
...runbook,
description: runbook.description ?? "",
jobAgentId: runbook.jobAgentId ?? "",
},
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

Avoid spreading runbook into defaultValues

Spreading ...runbook into defaultValues may include unexpected fields that are not defined in the form schema, potentially causing validation issues or unintended behavior. It's better to explicitly set only the fields defined in the schema.

Apply this diff to only include necessary fields:

 defaultValues: {
-  ...runbook,
-  description: runbook.description ?? "",
-  jobAgentId: runbook.jobAgentId ?? "",
+  name: runbook.name,
+  description: runbook.description ?? "",
+  variables: runbook.variables,
+  jobAgentId: runbook.jobAgentId ?? "",
+  jobAgentConfig: runbook.jobAgentConfig ?? {},
 },
📝 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
defaultValues: {
...runbook,
description: runbook.description ?? "",
jobAgentId: runbook.jobAgentId ?? "",
},
defaultValues: {
name: runbook.name,
description: runbook.description ?? "",
variables: runbook.variables,
jobAgentId: runbook.jobAgentId ?? "",
jobAgentConfig: runbook.jobAgentConfig ?? {},
},

Comment on lines +68 to +72
update
.mutateAsync({ id: runbook.id, data })
.then(() => router.refresh())
.then(() => setOpen(false)),
);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle errors in form submission

The onSubmit handler does not handle errors from the mutation or router refresh. This could lead to unhandled promise rejections and a poor user experience if the update fails.

Apply this diff to handle errors using try...catch:

-const onSubmit = form.handleSubmit(async (data) =>
-  update
-    .mutateAsync({ id: runbook.id, data })
-    .then(() => router.refresh())
-    .then(() => setOpen(false)),
-);
+const onSubmit = form.handleSubmit(async (data) => {
+  try {
+    await update.mutateAsync({ id: runbook.id, data });
+    router.refresh();
+    setOpen(false);
+  } catch (error) {
+    // Handle error, e.g., display error message to the user
+    form.setError("root", { message: "Failed to update runbook." });
+  }
+});
📝 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
update
.mutateAsync({ id: runbook.id, data })
.then(() => router.refresh())
.then(() => setOpen(false)),
);
const onSubmit = form.handleSubmit(async (data) => {
try {
await update.mutateAsync({ id: runbook.id, data });
router.refresh();
setOpen(false);
} catch (error) {
// Handle error, e.g., display error message to the user
form.setError("root", { message: "Failed to update runbook." });
}
});

@adityachoudhari26 adityachoudhari26 merged commit d526f74 into main Nov 7, 2024
6 checks passed
@adityachoudhari26 adityachoudhari26 deleted the variable-ui-cleanup branch November 7, 2024 02:45
This was referenced Nov 11, 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.

1 participant