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(web): disable the save button when creating a new item with invalid metadata #1327

Merged
merged 3 commits into from
Dec 5, 2024

Conversation

caichi-t
Copy link
Contributor

@caichi-t caichi-t commented Nov 27, 2024

Overview

This PR fixes to disable the save button when creating a new item with invalid metadata.

Summary by CodeRabbit

  • New Features
    • Enhanced form handling for text metadata with improved validation and state management.
  • Bug Fixes
    • Improved assertions and interactions in end-to-end tests for text metadata creation and editing, ensuring correct visibility and values.
  • Refactor
    • Introduced a new method for managing meta form value changes, improving clarity and separation of concerns in the ContentForm component.

@caichi-t caichi-t requested a review from nourbalaha as a code owner November 27, 2024 03:46
Copy link
Contributor

coderabbitai bot commented Nov 27, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The changes in this pull request involve enhancements to the end-to-end test cases for text metadata creation and editing, specifically in the text.spec.ts file. New assertions and interactions have been added to improve test coverage. Additionally, a new method handleMetaValuesChange has been introduced in the ContentForm component to handle changes in the meta form values, improving validation and state management without altering existing functionality.

Changes

File Path Change Summary
web/e2e/project/item/metadata/text.spec.ts Enhanced end-to-end tests for text metadata creation and editing with new assertions and interactions.
web/src/components/molecules/Content/Form/index.tsx Added handleMetaValuesChange method for meta form validation and updated onValuesChange prop.

Possibly related PRs

Suggested reviewers

  • nourbalaha

🐇 In the meadow, where the text does play,
New tests are hopping, brightening the day.
With forms that validate, and values that shine,
The metadata dances, all perfectly aligned!
Let's celebrate changes, with joy and delight,
For every new feature makes our code just right! 🌼


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 96ddded and 104b406.

📒 Files selected for processing (2)
  • web/e2e/project/item/metadata/text.spec.ts (1 hunks)
  • web/src/components/molecules/Content/Form/index.tsx (2 hunks)

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.

@github-actions github-actions bot added the web label Nov 27, 2024
Copy link

netlify bot commented Nov 27, 2024

Deploy Preview for reearth-cms ready!

Name Link
🔨 Latest commit 104b406
🔍 Latest deploy log https://app.netlify.com/sites/reearth-cms/deploys/67510bd7f7ff44000862f6df
😎 Deploy Preview https://deploy-preview-1327--reearth-cms.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

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 (4)
web/e2e/project/item/metadata/text.spec.ts (2)

134-137: Test case successfully validates the save button disable functionality.

The test case effectively verifies the PR objective by checking that the save button is disabled when the input exceeds the maximum length. However, consider these improvements for better test reliability and clarity:

   await page.getByLabel("new text1(unique)").click();
   await page.getByLabel("new text1(unique)").fill("text22");
+  // Verify button is disabled due to exceeding max length of 5
   await expect(page.getByRole("button", { name: "Save" })).toBeDisabled();
   await page.getByLabel("new text1(unique)").fill("text2");
+  // Verify button becomes enabled after fixing the value
+  await expect(page.getByRole("button", { name: "Save" })).toBeEnabled();

Additionally, consider adding more test cases to verify other invalid metadata scenarios, such as:

  • Empty required field
  • Duplicate value for unique field

Line range hint 177-178: Replace hardcoded waits with explicit wait conditions.

The test uses multiple waitForTimeout(100) calls which can make the test flaky. Instead, wait for specific conditions using Playwright's built-in wait methods.

Replace the hardcoded waits with appropriate wait conditions. For example:

-  // eslint-disable-next-line playwright/no-wait-for-timeout
-  await page.waitForTimeout(100);
+  // Wait for the textbox value to be updated
+  await expect(page.getByRole('textbox')).toHaveValue('text2');

-  // eslint-disable-next-line playwright/no-wait-for-timeout
-  await page.waitForTimeout(100);
+  // Wait for the arrow buttons to be clickable
+  await expect(page.getByRole('button', { name: 'arrow-down' })).toBeEnabled();

This will make the tests more reliable and faster by only waiting as long as necessary.

Also applies to: 182-183, 187-188, 192-193

web/src/components/molecules/Content/Form/index.tsx (2)

443-454: Implementation looks good, but consider adding error logging

The new handleMetaValuesChange method correctly implements the validation logic for metadata fields when creating new items. However, consider adding error logging to help with debugging validation failures.

  const handleMetaValuesChange = useCallback(async () => {
    if (itemId) return;
    try {
      await metaForm.validateFields();
    } catch (e) {
      if ((e as ValidateErrorEntity).errorFields.length > 0) {
        setIsDisabled(true);
+       console.error('Metadata validation failed:', e);
        return;
      }
    }
    setIsDisabled(false);
  }, [itemId, metaForm]);

443-454: Consider adding a debounce to validation

The validation runs on every change which might be expensive for complex metadata forms. Consider adding a debounce to improve performance.

+ import { debounce } from 'lodash';

  const handleMetaValuesChange = useCallback(
+   debounce(
      async () => {
        if (itemId) return;
        try {
          await metaForm.validateFields();
        } catch (e) {
          if ((e as ValidateErrorEntity).errorFields.length > 0) {
            setIsDisabled(true);
            return;
          }
        }
        setIsDisabled(false);
      },
+     300
+   ),
    [itemId, metaForm]
  );
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6d13978 and 96ddded.

📒 Files selected for processing (2)
  • web/e2e/project/item/metadata/text.spec.ts (1 hunks)
  • web/src/components/molecules/Content/Form/index.tsx (2 hunks)
🔇 Additional comments (3)
web/e2e/project/item/metadata/text.spec.ts (1)

Line range hint 6-14: Well-structured test setup and teardown.

The test file follows good practices with proper test isolation using beforeEach and afterEach hooks for setup and cleanup.

web/src/components/molecules/Content/Form/index.tsx (2)

672-676: LGTM! Form implementation correctly uses the new handler

The metadata form is properly configured to use the new handleMetaValuesChange method for validation.


443-454: Verify the save button behavior

Let's verify that the save button is properly disabled when metadata is invalid during item creation.

Also applies to: 672-676

✅ Verification successful

Based on the code analysis, I can now provide a final response regarding the save button behavior verification:

Save button correctly implements disabled state for invalid metadata

The implementation properly handles the save button's disabled state during item creation:

  • The button's disabled state is controlled by isDisabled state: <Button disabled={isDisabled}>
  • handleMetaValuesChange callback correctly sets isDisabled to:
    • true when metadata validation fails
    • false when validation passes
  • The validation is triggered appropriately through metaForm.validateFields()
  • Initial state is properly set with useState(!!itemId)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for tests that verify the save button's disabled state
rg -A 5 "save.*button.*disabled" "**/*.{test,spec}.{ts,tsx}"

# Search for related test files
fd -g "*content*.test.{ts,tsx}" -g "*form*.test.{ts,tsx}"

Length of output: 296


Script:

#!/bin/bash
# Search for tests related to the Form component
fd "test|spec" web/src/components/molecules/Content/Form/

# Search for save button disabled state tests with proper context
rg -A 5 "save.*button.*disabled"

# Search for test files containing "form" or "content" in their name
fd "form.*\.(test|spec)\." 
fd "content.*\.(test|spec)\."

# Look for form validation tests
rg -A 5 "validateFields|setIsDisabled" "web/src/components/molecules/Content/Form/"

Length of output: 6439


Script:

#!/bin/bash
# Search for the save button implementation and its disabled state
rg -A 5 "Button.*disabled={isDisabled}" web/src/components/molecules/Content/Form/

# Look for the form submission handler to understand the save flow
rg -A 10 "const handleSubmit" web/src/components/molecules/Content/Form/

# Search for the meta form initialization
rg -B 5 "metaForm = Form.useForm" web/src/components/molecules/Content/Form/

Length of output: 1479


Script:

#!/bin/bash
# Search for the save button with proper regex
rg -A 5 "Button.*disabled=\{isDisabled\}" web/src/components/molecules/Content/Form/

# Look for the form render section with the save button
rg -A 10 "return \(" web/src/components/molecules/Content/Form/

# Search for any button component with disabled prop
rg -A 5 "<Button.*disabled" web/src/components/molecules/Content/Form/

Length of output: 30253

@caichi-t caichi-t merged commit 4204334 into main Dec 5, 2024
19 checks passed
@caichi-t caichi-t deleted the fix-web/handle-invalid-metadata branch December 5, 2024 02:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants