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 SelectWidget label and value handling logic #38254

Merged
merged 3 commits into from
Dec 19, 2024

Conversation

rahulbarwal
Copy link
Contributor

@rahulbarwal rahulbarwal commented Dec 19, 2024

Description

  • Updated the label extraction logic to support both static and dynamic keys from sourceData.
  • Improved value mapping to handle cases where optionValue is an array, ensuring consistency in label and value retrieval.
  • Added detailed documentation comments to clarify the expected structure of sourceData and the behavior of optionLabel and optionValue props.

Fixes #Issue Number
or
Fixes Issue URL

Warning

If no issue exists, please create an issue first, and check with the maintainers if the issue is valid.

Automation

/ok-to-test tags="@tag.Select"

🔍 Cypress test results

Tip

🟢 🟢 🟢 All cypress tests have passed! 🎉 🎉 🎉
Workflow run: https://github.com/appsmithorg/appsmith/actions/runs/12409964844
Commit: 1027f13
Cypress dashboard.
Tags: @tag.Select
Spec:


Thu, 19 Dec 2024 09:59:56 UTC

Communication

Should the DevRel and Marketing teams inform users about this change?

  • Yes
  • No

Summary by CodeRabbit

  • New Features
    • Enhanced logic for handling optionLabel and optionValue properties in the SelectWidget component, allowing for more flexible input scenarios.
    • Improved validation functions to handle cases where input values are arrays with identical elements, enabling direct parsing from source data.

- Updated the label extraction logic to support both static and dynamic keys from sourceData.
- Improved value mapping to handle cases where optionValue is an array, ensuring consistency in label and value retrieval.
- Added detailed documentation comments to clarify the expected structure of sourceData and the behavior of optionLabel and optionValue props.

This change enhances the flexibility and usability of the SelectWidget component.
Copy link
Contributor

coderabbitai bot commented Dec 19, 2024

Walkthrough

The pull request modifies the getOptions method in the SelectWidget component, introducing a new helper function processOptionArray to enhance the processing of optionLabel and optionValue arrays. This function checks for equality among array elements and their existence as keys in sourceData, allowing for more flexible option mapping. Additionally, the labelKeyValidation and valueKeyValidation functions in propertyUtils.ts are updated to handle array inputs, improving validation logic while maintaining error handling.

Changes

File Change Summary
app/client/src/widgets/SelectWidget/widget/derived.js Introduced processOptionArray helper function in getOptions for enhanced processing of optionLabel and optionValue arrays. Updated method logic while maintaining overall structure.
app/client/src/widgets/SelectWidget/widget/propertyUtils.ts Modified labelKeyValidation and valueKeyValidation functions to handle array inputs, adding checks for element equality and key existence in sourceData.

Possibly related PRs

Suggested labels

Enhancement, Widgets Product, JSON Form

Suggested reviewers

  • ApekshaBhosale
  • sagar-qa007
  • jsartisan

Poem

🌟 Dropdown magic, options refined
Arrays of labels, now intertwined
Flexible choices, dancing with grace
Select widget's logic finds its place!
Code evolves, with wisdom divine 🔮


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.

@rahulbarwal
Copy link
Contributor Author

/build-deploy-preview skip-tests=true

@github-actions github-actions bot added the Bug Something isn't working label Dec 19, 2024
Copy link

Deploying Your Preview: https://github.com/appsmithorg/appsmith/actions/runs/12409205202.
Workflow: On demand build Docker image and deploy preview.
skip-tests: true.
env: ``.
PR: 38254.
recreate: .

@rahulbarwal rahulbarwal self-assigned this Dec 19, 2024
@rahulbarwal rahulbarwal added Select Widget Select or dropdown widget Widgets & Accelerators Pod Issues related to widgets & Accelerators ok-to-test Required label for CI labels Dec 19, 2024
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

🧹 Nitpick comments (1)
app/client/src/widgets/SelectWidget/widget/derived.js (1)

8-30: Consider adding TypeScript interfaces for better type safety

The documentation clearly explains the data structure and various scenarios. To enhance type safety and developer experience, consider adding TypeScript interfaces for the sourceData structure.

interface SourceDataItem {
  [key: string]: string | number;  // For dynamic properties
}

interface SelectWidgetProps {
  sourceData: SourceDataItem[];
  optionLabel: string | string[];
  optionValue: string | string[];
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 68264f1 and 86e3c89.

📒 Files selected for processing (1)
  • app/client/src/widgets/SelectWidget/widget/derived.js (1 hunks)
🔇 Additional comments (1)
app/client/src/widgets/SelectWidget/widget/derived.js (1)

Line range hint 1-67: Verify integration with parent components

The changes to array handling logic might affect parent components that pass array-type optionLabel/optionValue props.

- Introduced a new helper function `processOptionArray` to streamline the processing of option arrays for both labels and values.
- Simplified the logic for determining if option arrays are consistent and if keys exist in the source data, enhancing code readability and maintainability.
@rahulbarwal
Copy link
Contributor Author

/build-deploy-preview skip-tests=true

Copy link

Deploying Your Preview: https://github.com/appsmithorg/appsmith/actions/runs/12409342549.
Workflow: On demand build Docker image and deploy preview.
skip-tests: true.
env: ``.
PR: 38254.
recreate: .

Copy link

Deploy-Preview-URL: https://ce-38254.dp.appsmith.com

- Added functionality to validate and parse array inputs in both labelKeyValidation and valueKeyValidation functions.
- Implemented checks to determine if all values in the array are equal, allowing for dynamic key retrieval from sourceData.
- Improved error handling and validation messages for better user feedback.

This change increases the flexibility and robustness of the SelectWidget component's input handling.
@rahulbarwal
Copy link
Contributor Author

/build-deploy-preview skip-tests=true

Copy link

Deploying Your Preview: https://github.com/appsmithorg/appsmith/actions/runs/12409972029.
Workflow: On demand build Docker image and deploy preview.
skip-tests: true.
env: ``.
PR: 38254.
recreate: .

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

🧹 Nitpick comments (1)
app/client/src/widgets/SelectWidget/widget/propertyUtils.ts (1)

141-144: Enhance documentation with examples

The comments about array validation could be more explicit. Consider adding examples to clarify the expected input and output.

Add examples like:

/**
 * Validates array inputs where equal values represent a key in sourceData
 * Example:
 * Input: ["name", "name", "name"]
 * sourceData: [{ name: "John" }, { name: "Jane" }]
 * Output: ["John", "Jane"]
 */

Also applies to: 242-245

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a93ab7d and 1027f13.

📒 Files selected for processing (1)
  • app/client/src/widgets/SelectWidget/widget/propertyUtils.ts (2 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
app/client/src/widgets/SelectWidget/widget/propertyUtils.ts

[error] 149-149: Do not access Object.prototype method 'hasOwnProperty' from target object.

It's recommended using Object.hasOwn() instead of using Object.hasOwnProperty().
See MDN web docs for more details.

(lint/suspicious/noPrototypeBuiltins)


[error] 250-250: Do not access Object.prototype method 'hasOwnProperty' from target object.

It's recommended using Object.hasOwn() instead of using Object.hasOwnProperty().
See MDN web docs for more details.

(lint/suspicious/noPrototypeBuiltins)

Comment on lines +242 to +261
/*
* Here assumption is that if evaluated array is all equal, then it is a key,
* and we can return the parsed value(from source data) as the options.
*/
const areAllValuesEqual = value.every((item, _, arr) => item === arr[0]);

if (
areAllValuesEqual &&
props.sourceData[0].hasOwnProperty(String(value[0]))
) {
const parsedValue = props.sourceData.map(
(d: Record<string, unknown>) => d[String(value[0])],
);

return {
parsed: parsedValue,
isValid: true,
messages: [],
};
}
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

Extract duplicated array validation logic

The array validation logic is duplicated from labelKeyValidation. Consider extracting this into a shared utility function.

  1. First, apply the same safety fixes:
    if (
      areAllValuesEqual &&
+     props.sourceData?.[0] &&
-     props.sourceData[0].hasOwnProperty(String(value[0]))
+     Object.hasOwn(props.sourceData[0], String(value[0]))
    ) {
  1. Then, extract the common logic:
function validateEqualArrayValues(
  value: unknown[],
  props: SelectWidgetProps
): ValidationResponse {
  const areAllValuesEqual = value.every((item, _, arr) => item === arr[0]);
  
  if (
    areAllValuesEqual &&
    props.sourceData?.[0] &&
    Object.hasOwn(props.sourceData[0], String(value[0]))
  ) {
    const parsedValue = props.sourceData.map(
      (d: Record<string, unknown>) => d[String(value[0])]
    );
    
    return {
      parsed: parsedValue,
      isValid: true,
      messages: [],
    };
  }
  
  return null;
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 250-250: Do not access Object.prototype method 'hasOwnProperty' from target object.

It's recommended using Object.hasOwn() instead of using Object.hasOwnProperty().
See MDN web docs for more details.

(lint/suspicious/noPrototypeBuiltins)

Comment on lines +141 to +160
/*
* Here assumption is that if evaluated array is all equal, then it is a key,
* and we can return the parsed value(from source data) as the options.
*/
const areAllValuesEqual = value.every((item, _, arr) => item === arr[0]);

if (
areAllValuesEqual &&
props.sourceData[0].hasOwnProperty(String(value[0]))
) {
const parsedValue = props.sourceData.map(
(d: Record<string, unknown>) => d[String(value[0])],
);

return {
parsed: parsedValue,
isValid: true,
messages: [],
};
}
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

Add safety checks and use Object.hasOwn

The array validation logic needs additional safety measures:

  1. Add null check for props.sourceData[0]
  2. Replace unsafe hasOwnProperty with Object.hasOwn

Apply this diff:

    if (
      areAllValuesEqual &&
+     props.sourceData?.[0] &&
-     props.sourceData[0].hasOwnProperty(String(value[0]))
+     Object.hasOwn(props.sourceData[0], String(value[0]))
    ) {
📝 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
/*
* Here assumption is that if evaluated array is all equal, then it is a key,
* and we can return the parsed value(from source data) as the options.
*/
const areAllValuesEqual = value.every((item, _, arr) => item === arr[0]);
if (
areAllValuesEqual &&
props.sourceData[0].hasOwnProperty(String(value[0]))
) {
const parsedValue = props.sourceData.map(
(d: Record<string, unknown>) => d[String(value[0])],
);
return {
parsed: parsedValue,
isValid: true,
messages: [],
};
}
/*
* Here assumption is that if evaluated array is all equal, then it is a key,
* and we can return the parsed value(from source data) as the options.
*/
const areAllValuesEqual = value.every((item, _, arr) => item === arr[0]);
if (
areAllValuesEqual &&
props.sourceData?.[0] &&
Object.hasOwn(props.sourceData[0], String(value[0]))
) {
const parsedValue = props.sourceData.map(
(d: Record<string, unknown>) => d[String(value[0])],
);
return {
parsed: parsedValue,
isValid: true,
messages: [],
};
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 149-149: Do not access Object.prototype method 'hasOwnProperty' from target object.

It's recommended using Object.hasOwn() instead of using Object.hasOwnProperty().
See MDN web docs for more details.

(lint/suspicious/noPrototypeBuiltins)

Copy link

Deploy-Preview-URL: https://ce-38254.dp.appsmith.com

github-actions bot pushed a commit to Zeral-Zhang/appsmith that referenced this pull request Feb 7, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Something isn't working ok-to-test Required label for CI Select Widget Select or dropdown widget Widgets & Accelerators Pod Issues related to widgets & Accelerators
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants