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: API Body format focus retention #37150

Merged
merged 1 commit into from
Nov 1, 2024
Merged

Conversation

hetunandu
Copy link
Member

@hetunandu hetunandu commented Oct 31, 2024

Description

  • Use Focus retention to store user context of the POST body format of APIs
  • Update component to use hooks instead of redux connect hoc
  • remove need of passing Action ID in form data as it is redundant for focus retention states

Fixes #36984

Automation

/ok-to-test tags="@tag.Datasource, @tag.IDE"

🔍 Cypress test results

Tip

🟢 🟢 🟢 All cypress tests have passed! 🎉 🎉 🎉
Workflow run: https://github.com/appsmithorg/appsmith/actions/runs/11609483418
Commit: a3a1a59
Cypress dashboard.
Tags: @tag.Datasource, @tag.IDE
Spec:


Thu, 31 Oct 2024 10:31:09 UTC

Communication

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

  • Yes
  • No

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a streamlined method for managing API body content types and form data.
    • Added new action creator setExtraFormData for enhanced form data handling.
  • Improvements

    • Simplified the PostBodyData component by utilizing React hooks for state management.
    • Updated selectors and reducers to support a flatter structure for form data, improving clarity and maintainability.
  • Updates

    • Enhanced focus elements configuration to better manage plugin action form data within the application.

Copy link
Contributor

coderabbitai bot commented Oct 31, 2024

Walkthrough

The pull request introduces significant changes to the PostBodyData component, transitioning from Redux's connect method to React hooks for state management. This includes the removal of certain props and a restructuring of action creators in pluginActionEditorActions.ts. Additionally, selector functions in pluginActionEditorSelectors.ts have been updated to streamline data retrieval. The reducer in pluginEditorReducer.ts has been simplified, and new methods have been added to manage form data. Overall, the changes enhance the clarity and maintainability of the codebase.

Changes

File Change Summary
app/client/src/PluginActionEditor/components/PluginActionForm/components/ApiEditor/PostBodyData.tsx Refactored to use hooks, removed displayFormat and apiId, simplified state management.
app/client/src/PluginActionEditor/store/pluginActionEditorActions.ts Updated updatePostBodyContentType to remove apiId, added setExtraFormData.
app/client/src/PluginActionEditor/store/pluginActionEditorSelectors.ts Modified getFormData and getPostBodyFormat for improved data handling.
app/client/src/PluginActionEditor/store/pluginEditorReducer.ts Simplified formData structure and adjusted SET_EXTRA_FORMDATA handler.
app/client/src/ce/navigation/FocusElements/AppIDE.ts Integrated new imports and updated AppIDEFocusElements configuration for form data handling.
app/client/src/navigation/FocusElements.ts Added PluginActionFormData to FocusElement enum.
app/client/src/sagas/ApiPaneSagas.ts Updated sagas to utilize setExtraFormData and modified function signatures for clarity.

Assessment against linked issues

Objective Addressed Explanation
Retain context of the body in APIs when switching segments (#36984)

Possibly related PRs

Suggested labels

Bug, Medium, Production, Enhancement, IDE Product, IDE Pod, ok-to-test

Suggested reviewers

  • ayushpahwa
  • albinAppsmith
  • ankitakinger

"In the code where logic flows,
Hooks replace the old, it shows.
Actions slimmed, selectors bright,
Form data shines in the new light.
A journey through the Redux maze,
Simplified in many ways!" 🎉


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.

@github-actions github-actions bot added Bug Something isn't working Entity Explorer Issues related to navigation using the entity explorer IDE Navigation Issues/feature requests related to IDE navigation, and context switching IDE Pod Issues that new developers face while exploring the IDE IDE Product Issues related to the IDE Product Integrations Product Issues related to a specific integration Medium Issues that frustrate users due to poor UX Needs Triaging Needs attention from maintainers to triage Production Query & JS Pod Issues related to the query & JS Pod Query Forms Isuses related to the query forms labels Oct 31, 2024
@hetunandu hetunandu added the ok-to-test Required label for CI label Oct 31, 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: 3

🧹 Outside diff range and nitpick comments (3)
app/client/src/navigation/FocusElements.ts (1)

6-6: Consider standardizing enum member naming pattern.

While the new member works correctly, consider establishing a consistent naming pattern for form-related focus elements. Currently we have mixed patterns: PluginActionFormData vs InputField, PropertyField.

Consider one of these approaches:

  1. Prefix pattern: Form_PluginAction
  2. Consistent suffixes: PluginActionField (matching InputField)
app/client/src/PluginActionEditor/store/pluginEditorReducer.ts (1)

150-152: Consider adding type assertion for values.

The reducer logic is correct, but consider adding a type assertion to ensure values match the expected structure.

-    const { values } = action.payload;
+    const { values }: { values: PluginActionEditorState['formData'] } = action.payload;
app/client/src/sagas/ApiPaneSagas.ts (1)

Line range hint 141-227: Consider adding error handling for invalid content types.

While the function handles the happy path well, it could benefit from proper error handling when an invalid content type is encountered.

Consider adding a try-catch block:

 function* handleUpdateBodyContentType(action: ReduxAction<{ title: string }>) {
+  try {
     const { title } = action.payload;
     const { values } = yield select(getFormData, API_EDITOR_FORM_NAME);
 
     const displayFormatValue = POST_BODY_FORMAT_OPTIONS_ARRAY.find(
       (el) => el === title,
     );
 
     if (!displayFormatValue) {
-      log.error("Display format not supported", title);
+      throw new Error(`Display format not supported: ${title}`);
       return;
     }
     // ... rest of the function
+  } catch (error) {
+    yield put({
+      type: ReduxActionErrorTypes.API_UPDATE_BODY_CONTENT_TYPE_ERROR,
+      payload: {
+        error,
+      },
+    });
+  }
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 38c9bc0 and a3a1a59.

📒 Files selected for processing (7)
  • app/client/src/PluginActionEditor/components/PluginActionForm/components/ApiEditor/PostBodyData.tsx (3 hunks)
  • app/client/src/PluginActionEditor/store/pluginActionEditorActions.ts (1 hunks)
  • app/client/src/PluginActionEditor/store/pluginActionEditorSelectors.ts (2 hunks)
  • app/client/src/PluginActionEditor/store/pluginEditorReducer.ts (2 hunks)
  • app/client/src/ce/navigation/FocusElements/AppIDE.ts (2 hunks)
  • app/client/src/navigation/FocusElements.ts (1 hunks)
  • app/client/src/sagas/ApiPaneSagas.ts (5 hunks)
🔇 Additional comments (12)
app/client/src/PluginActionEditor/store/pluginActionEditorActions.ts (2)

36-40: LGTM: Well-structured new action creator.

The new setExtraFormData action creator is well-typed and follows Redux best practices with a clear payload structure.


31-34: Verify the removal of apiId parameter impact.

The removal of apiId from the action payload aligns with the PR objective of removing redundant Action ID. However, we should verify this doesn't break existing consumers.

app/client/src/navigation/FocusElements.ts (1)

6-6: LGTM! Verify usage in related components.

The new enum member aligns well with the PR's focus retention objective.

Let's verify the usage of this new focus element:

✅ Verification successful

Implementation verified and properly integrated

The new PluginActionFormData focus element is correctly implemented in the Query entity configuration with:

  • Proper Redux integration using getFormData selector and setExtraFormData setter
  • Default value set to handle POST body format
  • Consistent placement alongside other plugin action related focus elements
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for components using the new focus element
rg "PluginActionFormData" --type ts

Length of output: 227


Script:

#!/bin/bash
# Let's check the implementation details in AppIDE.ts
cat app/client/src/ce/navigation/FocusElements/AppIDE.ts

# Also check for any other potential usages in action/plugin related files
rg "PluginActionFormData" -B 2 -A 2 --type ts

Length of output: 10443

app/client/src/PluginActionEditor/store/pluginActionEditorSelectors.ts (2)

5-5: LGTM!

The import follows the established pattern and is appropriately sourced from common constants.


44-47: LGTM!

The type definition is clear and properly defines the expected shape of the post body format.

app/client/src/PluginActionEditor/store/pluginEditorReducer.ts (1)

29-29: Verify impact of formData type change.

The simplified type structure aligns with the PR objective of removing Action ID dependency.

Let's verify all usages of this type to ensure compatibility:

app/client/src/ce/navigation/FocusElements/AppIDE.ts (2)

80-81: LGTM: Import statements are well-organized.

The new imports support form data retention functionality as intended.

Also applies to: 86-89


160-166: Verify form data persistence across navigation.

The focus element configuration looks good and aligns with the focus retention requirements. Let's verify the implementation works as expected.

app/client/src/sagas/ApiPaneSagas.ts (3)

64-67: LGTM! Clean import restructuring.

The imports are well-organized and align with the transition from Redux connect to hooks.


364-368: LGTM! Consistent state management.

The update to use setExtraFormData is consistent with the new form data management approach.


257-258: Verify type safety of getPostBodyFormat selector.

The type inference for extraFormData relies on the selector's return type. Let's verify its implementation.

app/client/src/PluginActionEditor/components/PluginActionForm/components/ApiEditor/PostBodyData.tsx (1)

Line range hint 1-192: Good work on refactoring to use React hooks

Transitioning from connect to React hooks (useSelector, useDispatch) improves the readability and maintainability of the component.

Comment on lines +41 to +42
export const getFormData = (state: AppState) =>
state.ui.pluginActionEditor.formData;
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 creating memoized selectors for specific form data fields.

Direct state access might cause unnecessary re-renders in components that only need specific parts of formData.

Consider creating specific selectors using createSelector:

export const getSpecificFormData = (key: string) =>
  createSelector([getFormData], (formData) => formData[key]);

Comment on lines +49 to +59
export const getPostBodyFormat: GetFormPostBodyFormat = (state) => {
const formData = getFormData(state);

if (id in formData) {
return formData[id][POST_BODY_FORM_DATA_KEY];
if (POST_BODY_FORM_DATA_KEY in formData) {
return formData[POST_BODY_FORM_DATA_KEY];
}

return undefined;
return {
label: POST_BODY_FORMAT_OPTIONS.NONE,
value: POST_BODY_FORMAT_OPTIONS.NONE,
};
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

Memoize the selector to prevent unnecessary recalculations.

While the implementation is correct, it should be memoized to prevent unnecessary recalculations.

Consider this implementation:

export const getPostBodyFormat: GetFormPostBodyFormat = createSelector(
  [getFormData],
  (formData) => {
    if (POST_BODY_FORM_DATA_KEY in formData) {
      return formData[POST_BODY_FORM_DATA_KEY];
    }
    return {
      label: POST_BODY_FORMAT_OPTIONS.NONE,
      value: POST_BODY_FORMAT_OPTIONS.NONE,
    };
  }
);

Comment on lines +177 to +179
defaultValue={postBodyFormat.value}
onSelect={updateBodyContentType}
value={postBodyFormat.value}
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

Remove redundant defaultValue prop in Select component

Using both defaultValue and value in a controlled component can cause confusion and potential bugs. Since value is already managing the selected option, defaultValue is unnecessary and should be removed.

Apply this diff to remove the redundant prop:

  <Select
    data-testid="t--api-body-tab-switch"
-   defaultValue={postBodyFormat.value}
    onSelect={updateBodyContentType}
    value={postBodyFormat.value}
  >
📝 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
defaultValue={postBodyFormat.value}
onSelect={updateBodyContentType}
value={postBodyFormat.value}
value={postBodyFormat.value}
onSelect={updateBodyContentType}
value={postBodyFormat.value}

@hetunandu hetunandu merged commit 9a9a7c4 into release Nov 1, 2024
47 checks passed
@hetunandu hetunandu deleted the fix/api-body-format-context branch November 1, 2024 05:54
github-actions bot pushed a commit to Zeral-Zhang/appsmith that referenced this pull request Nov 20, 2024
## Description


- Use Focus retention to store user context of the POST body format of
APIs
- Update component to use hooks instead of redux connect hoc
- remove need of passing Action ID in form data as it is redundant for
focus retention states


Fixes appsmithorg#36984

## Automation

/ok-to-test tags="@tag.Datasource, @tag.IDE"

### 🔍 Cypress test results
<!-- This is an auto-generated comment: Cypress test results  -->
> [!TIP]
> 🟢 🟢 🟢 All cypress tests have passed! 🎉 🎉 🎉
> Workflow run:
<https://github.com/appsmithorg/appsmith/actions/runs/11609483418>
> Commit: a3a1a59
> <a
href="https://internal.appsmith.com/app/cypress-dashboard/rundetails-65890b3c81d7400d08fa9ee5?branch=master&workflowId=11609483418&attempt=1"
target="_blank">Cypress dashboard</a>.
> Tags: `@tag.Datasource, @tag.IDE`
> Spec:
> <hr>Thu, 31 Oct 2024 10:31:09 UTC
<!-- end of auto-generated comment: Cypress test results  -->


## Communication
Should the DevRel and Marketing teams inform users about this change?
- [ ] Yes
- [ ] No


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

## Release Notes

- **New Features**
- Introduced a streamlined method for managing API body content types
and form data.
- Added new action creator `setExtraFormData` for enhanced form data
handling.

- **Improvements**
- Simplified the `PostBodyData` component by utilizing React hooks for
state management.
- Updated selectors and reducers to support a flatter structure for form
data, improving clarity and maintainability.

- **Updates**
- Enhanced focus elements configuration to better manage plugin action
form data within the application.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Something isn't working Entity Explorer Issues related to navigation using the entity explorer IDE Navigation Issues/feature requests related to IDE navigation, and context switching IDE Pod Issues that new developers face while exploring the IDE IDE Product Issues related to the IDE Product Integrations Product Issues related to a specific integration Medium Issues that frustrate users due to poor UX Needs Triaging Needs attention from maintainers to triage ok-to-test Required label for CI Production Query Forms Isuses related to the query forms Query & JS Pod Issues related to the query & JS Pod
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Bug]: When switching segments, the context of the body in APIs is lost
2 participants