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): ensure the argument of runes function are string #1340

Merged
merged 3 commits into from
Dec 13, 2024

Conversation

caichi-t
Copy link
Contributor

@caichi-t caichi-t commented Dec 5, 2024

Overview

This PR fixes to ensure the argument of runes function are string.

Memo

A fatal bug occurs when the argument of rune function is not string.

Summary by CodeRabbit

  • New Features

    • Enhanced type safety in input components by ensuring that only string values are validated against maximum length constraints.
  • Bug Fixes

    • Improved error handling in validation logic to prevent runtime errors when non-string values are encountered.
  • Refactor

    • Updated validation logic across multiple components to include type checks for better robustness and reliability.

@caichi-t caichi-t requested a review from nourbalaha as a code owner December 5, 2024 10:41
Copy link
Contributor

coderabbitai bot commented Dec 5, 2024

Walkthrough

The pull request introduces modifications across several components to enhance type safety and validation logic. Specifically, the value property has been removed from the Props type in the Input and MarkdownInput components, while type checks have been added to ensure that the value is a string before applying any length checks in various components. These changes aim to prevent runtime errors and improve the robustness of the validation process throughout the application.

Changes

File Path Change Summary
web/src/components/atoms/Input/index.tsx Removed optional value property from Props. Updated status logic to include type checks for maxLength.
web/src/components/atoms/Markdown/index.tsx Removed optional value property from Props. Enhanced isError state with type checks for maxLength. Updated rendering logic to handle non-string values.
web/src/components/atoms/TextArea/index.tsx Made value optional in Props. Added type checks for maxLength validation.
web/src/components/molecules/Content/Form/fields/FieldComponents/DefaultField.tsx Enhanced validation logic to check if values are strings before applying maxLength checks.
web/src/components/molecules/Content/Form/fields/FieldComponents/MarkdownField.tsx Improved validation logic to ensure only string values are checked against maxLength.
web/src/components/molecules/Content/Form/fields/FieldComponents/TextareaField.tsx Updated validation logic to check types before length comparisons for value.
web/src/components/molecules/Schema/FieldModal/FieldDefaultInputs/Markdown/index.tsx Enhanced validation logic to ensure only string values are considered for length checks.
web/src/components/molecules/Schema/FieldModal/FieldDefaultInputs/TextArea/index.tsx Improved validation logic with type checks for defaultValue length comparisons.
web/src/components/molecules/Schema/FieldModal/FieldDefaultInputs/TextField/index.tsx Updated validation logic to ensure value is a string before applying maxLength checks.

Possibly related PRs

Suggested labels

web

Suggested reviewers

  • nourbalaha

🐇 In the code we hop and play,
With types and checks, we pave the way.
No more errors, just safe and sound,
In every input, joy is found!
So let’s celebrate, with a cheer,
For type safety brings us near! 🎉


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 Dec 5, 2024
Copy link

netlify bot commented Dec 5, 2024

Deploy Preview for reearth-cms ready!

Name Link
🔨 Latest commit 28133d0
🔍 Latest deploy log https://app.netlify.com/sites/reearth-cms/deploys/675be833327f3700089cae54
😎 Deploy Preview https://deploy-preview-1340--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: 3

🧹 Outside diff range and nitpick comments (6)
web/src/components/atoms/TextArea/index.tsx (1)

15-15: Optimize the type check condition

The condition has a redundant check. Since an empty string is still a string, the value && check after the type check is unnecessary.

-(maxLength && typeof value === "string" && value && runes(value).length > maxLength)
+(maxLength && typeof value === "string" && runes(value).length > maxLength)
web/src/components/molecules/Schema/FieldModal/FieldDefaultInputs/Markdown/index.tsx (1)

27-30: LGTM! Consider adding descriptive error messages.

The type checks properly ensure string arguments for the runes function. However, the empty error message (message: "") might not be user-friendly.

Consider adding descriptive error messages for validation failures:

 rules={[
   {
     validator: (_, value) => {
       if (value && maxLength) {
         if (Array.isArray(value)) {
           if (value.some(v => typeof v === "string" && maxLength < runes(v).length)) {
-            return Promise.reject();
+            return Promise.reject(new Error(t("Input exceeds maximum length")));
           }
         } else if (typeof value === "string" && maxLength < runes(value).length) {
-          return Promise.reject();
+          return Promise.reject(new Error(t("Input exceeds maximum length")));
         }
       }
       return Promise.resolve();
     },
-    message: "",
   },
 ]}
web/src/components/molecules/Schema/FieldModal/FieldDefaultInputs/TextArea/index.tsx (1)

26-29: Consider extracting shared validation logic.

The validation logic is identical to the MarkdownField component. Consider extracting this into a shared utility function to maintain DRY principles and ensure consistent validation across components.

Example implementation:

// utils/validation.ts
export const validateStringLength = (value: unknown, maxLength: number) => {
  if (!value || !maxLength) return Promise.resolve();
  
  if (Array.isArray(value)) {
    if (value.some(v => typeof v === "string" && maxLength < runes(v).length)) {
      return Promise.reject(new Error(t("Input exceeds maximum length")));
    }
  } else if (typeof value === "string" && maxLength < runes(value).length) {
    return Promise.reject(new Error(t("Input exceeds maximum length")));
  }
  return Promise.resolve();
};

Then use it in both components:

rules={[
  {
    validator: (_, value) => validateStringLength(value, maxLength),
  },
]}
web/src/components/molecules/Content/Form/fields/FieldComponents/TextareaField.tsx (1)

39-42: Consider extracting shared validation logic

The same validation logic appears in multiple components (TextareaField, DefaultField). Consider extracting it into a shared utility function.

Create a new utility function in utils.ts:

export const validateMaxLength = (value: unknown, maxLength?: number) => {
  if (!value || !maxLength) return true;
  
  if (Array.isArray(value)) {
    return !value.some(v => typeof v === "string" && maxLength < runes(v).length);
  }
  return !(typeof value === "string" && maxLength < runes(value).length);
};

Then use it in the components:

          validator: (_, value) => {
-           if (value && maxLength) {
-             if (Array.isArray(value)) {
-               if (value.some(v => typeof v === "string" && maxLength < runes(v).length)) {
-                 return Promise.reject();
-               }
-             } else if (typeof value === "string" && maxLength < runes(value).length) {
-               return Promise.reject();
-             }
-           }
-           return Promise.resolve();
+           return validateMaxLength(value, maxLength) 
+             ? Promise.resolve()
+             : Promise.reject(t("Text length cannot exceed {maxLength} characters", { maxLength }));
          },
web/src/components/atoms/Markdown/index.tsx (2)

19-22: Simplify the type check condition

The current condition can be simplified while maintaining type safety.

-   } else if (props.maxLength && typeof value === "string" && value) {
+   } else if (props.maxLength && typeof value === "string" && value.length > 0) {
      return runes(value).length > props.maxLength;

54-54: Use empty string as fallback for non-string values

Using undefined as fallback might cause ReactMarkdown to use its default fallback. It's more explicit to use an empty string.

-        <ReactMarkdown>{typeof value === "string" ? value : undefined}</ReactMarkdown>
+        <ReactMarkdown>{typeof value === "string" ? value : ""}</ReactMarkdown>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7fd205a and be7fffb.

📒 Files selected for processing (9)
  • web/src/components/atoms/Input/index.tsx (1 hunks)
  • web/src/components/atoms/Markdown/index.tsx (2 hunks)
  • web/src/components/atoms/TextArea/index.tsx (1 hunks)
  • web/src/components/molecules/Content/Form/fields/FieldComponents/DefaultField.tsx (1 hunks)
  • web/src/components/molecules/Content/Form/fields/FieldComponents/MarkdownField.tsx (1 hunks)
  • web/src/components/molecules/Content/Form/fields/FieldComponents/TextareaField.tsx (1 hunks)
  • web/src/components/molecules/Schema/FieldModal/FieldDefaultInputs/Markdown/index.tsx (1 hunks)
  • web/src/components/molecules/Schema/FieldModal/FieldDefaultInputs/TextArea/index.tsx (1 hunks)
  • web/src/components/molecules/Schema/FieldModal/FieldDefaultInputs/TextField/index.tsx (1 hunks)
🔇 Additional comments (4)
web/src/components/molecules/Schema/FieldModal/FieldDefaultInputs/TextField/index.tsx (1)

27-31: Verify all usages of runes function across the codebase

Let's ensure all usages of the runes function have proper type checks.

✅ Verification successful

All usages of runes function have proper type checks

After reviewing all occurrences of the runes function across the codebase, every usage is properly guarded with type checks:

  • Input/TextArea components check typeof value === "string" before using runes
  • Form field components check both array elements and direct values with typeof v === "string" or typeof value === "string"
  • Markdown component includes type check typeof value === "string"
  • All implementations consistently validate string type before applying runes
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for all usages of runes function
echo "Searching for runes function calls without type checks..."
rg "runes\(" --type typescript -C 2 | grep -v "typeof.*===.*string.*&&.*runes"

Length of output: 240


Script:

#!/bin/bash
# Search for all usages of runes function with proper context
echo "Searching for runes function calls..."
rg "runes\(" -t ts -t tsx -C 2

Length of output: 145


Script:

#!/bin/bash
# Search for all usages of runes function with proper context
echo "Searching for runes function calls..."
rg "runes\(" --type-add 'ts:*.{ts,tsx}' -t ts -C 2

Length of output: 8325

web/src/components/molecules/Content/Form/fields/FieldComponents/MarkdownField.tsx (1)

39-42: Verify validation behavior with itemGroupId.

The type checking changes look good but are duplicated across components. Additionally, since this component handles grouped items differently, let's verify the validation behavior.

Strongly recommend extracting the validation logic into a shared utility as it's now duplicated in three components. This will:

  1. Reduce code duplication
  2. Ensure consistent validation behavior
  3. Make future updates easier to maintain
  4. Centralize error message handling

See the previous review comment for the suggested implementation of validateStringLength.

✅ Verification successful

Let me gather more information about the validation behavior in grouped items.


Let me try a different approach to check the validation handling.


Let me try one final verification to check the validation implementation.


Based on the verification results, I can now provide the final response:

Validation behavior with itemGroupId is correctly implemented

The validation logic in MarkdownField works correctly with itemGroupId as it:

  • Uses Form.Item's standard name composition [field.id, itemGroupId]
  • Leverages MultiValueField component which properly handles array values and validation
  • Maintains validation state independently for each field in the group

The suggestion to extract validation logic remains valid as the string length validation is still duplicated, but the itemGroupId handling itself is properly implemented.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any special handling of validation in grouped items
# Look for other uses of itemGroupId with validation rules

rg -A 5 "itemGroupId.*validation" .
rg -A 5 "\[field\.id,\s*itemGroupId\]" .

Length of output: 9988


Script:

#!/bin/bash
# Check MultiValueField implementation and validation handling
ast-grep --pattern 'const MultiValueField = $_' 

# Check for any validation-related code in MultiValueField
rg -A 5 "validation|validator|rules" ./web/src/components/molecules/Common/MultiValueField/

Length of output: 143


Script:

#!/bin/bash
# Check MultiValueField component implementation
rg -A 10 "export.*MultiValueField" ./web/src/components/molecules/Common/MultiValueField/

# Check how validation is handled in the component
ast-grep --pattern 'function $_($$$) {
  $$$
  maxLength
  $$$
}'

# Look for validation rules in form items
rg -A 5 "rules=\{" ./web/src/components/molecules/Common/MultiValueField/

Length of output: 1126


Script:

#!/bin/bash
# Check the implementation of MultiValueField component
cat ./web/src/components/molecules/Common/MultiValueField/index.tsx

# Look for validation handling in the parent Form component
rg -A 10 "Form.Item.*rules" ./web/src/components/molecules/Content/Form/fields/FieldComponents/MarkdownField.tsx

Length of output: 4228

web/src/components/molecules/Content/Form/fields/FieldComponents/DefaultField.tsx (1)

45-48: Same issues as in TextareaField component

The validation logic has the same issues as identified in TextareaField:

  1. Empty validation message
  2. Duplicated validation logic

Please refer to the suggestions made for TextareaField component regarding:

  • Adding descriptive validation messages
  • Extracting shared validation logic
web/src/components/atoms/Markdown/index.tsx (1)

Line range hint 8-11: Verify the removal of value from Props type

The removal of value from Props type needs verification to ensure it doesn't break existing usage.

✅ Verification successful

Removal of value prop is safe to proceed

Based on the search results, the value prop is not being used directly in any <Markdown> component instances across the codebase. The component is used in several places (FieldDefaultInputs, MarkdownField.tsx) but they don't pass the value prop explicitly. Instead, they use form context or other mechanisms to handle the value state.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for direct usage of value prop in Markdown components
rg -l "value.*props" --type typescript | xargs ast-grep --pattern 'value={$_}'

# Search for spread operator usage with Markdown
rg -l "\.\.\..*props" --type typescript | xargs ast-grep --pattern '<MarkdownInput {...$_}/>'

Length of output: 246


Script:

#!/bin/bash
# Search for direct usage of value prop in Markdown components
rg -l "value.*props" --type ts --type tsx | xargs ast-grep --pattern 'value={$_}'

# Search for spread operator usage with Markdown components
rg -l "\.\.\..*props" --type ts --type tsx | xargs ast-grep --pattern '<Markdown {...$_}/>'

# Search for direct value prop usage in Markdown components
rg -l "Markdown" --type ts --type tsx | xargs ast-grep --pattern '<Markdown value={$_}/>'

# Search for any Markdown component usage
rg -l "Markdown" --type ts --type tsx | xargs ast-grep --pattern '<Markdown$$$>'

Length of output: 460


Script:

#!/bin/bash
# Search for any usage of Markdown component
rg -l "Markdown" 

# Then search for specific usages in those files
rg -A 5 "<Markdown" 

# Search for any spread operator usage with components
rg -A 5 "<Markdown.*\.\.\."

# Look for value prop usage
rg -A 5 "<Markdown.*value="

Length of output: 4800

@caichi-t caichi-t enabled auto-merge (squash) December 13, 2024 07:54
@caichi-t caichi-t merged commit 12445a9 into main Dec 13, 2024
19 checks passed
@caichi-t caichi-t deleted the fix-web/rune-type-bug branch December 13, 2024 07:58
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