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: 14472 should show the value of selector in properties config #14686

Merged

Conversation

JamalAlabdullah
Copy link
Contributor

@JamalAlabdullah JamalAlabdullah commented Feb 17, 2025

Description

In the config panel, we add all selectors inside the + button, but we missed displaying the selected value when the user chooses an option from the selector. This has been fixed in this PR.

Changes:

  • Added a new reusable component called SelectPropertyEditor.
  • Added tests for it.
  • Removed the CollapsiblePropertyEditor folder and replaced it with the new component.

Related Issue(s)

Verification

  • Your code builds clean without any errors or warnings
  • Manual testing done (required)
  • Relevant automated test added (if you find this hard, leave it and we'll help out)

Documentation

  • User documentation is updated with a separate linked PR in altinn-studio-docs. (if applicable)

Summary by CodeRabbit

  • New Features

    • Added a new selection-based editor for configuring component properties.
    • Introduced enhanced language support for validation type labels.
  • Style

    • Improved spacing and layout adjustments for configuration buttons and grid elements.
    • Added new styles for the SelectPropertyEditor component.
  • Refactor

    • Replaced the previous collapsible interface with a streamlined, more intuitive property editor.
    • Updated rendering logic to utilize the new SelectPropertyEditor for managing property displays.
  • Bug Fixes

    • Corrected rendering behavior for property text in the FormComponentConfig tests.
  • Chores

    • Removed outdated styles and tests associated with the previous collapsible property editor.
    • Cleaned up obsolete exports related to the CollapsiblePropertyEditor.

@JamalAlabdullah JamalAlabdullah linked an issue Feb 17, 2025 that may be closed by this pull request
@github-actions github-actions bot added area/ui-editor Area: Related to the designer tool for assembling app UI in Altinn Studio. solution/studio/designer Issues related to the Altinn Studio Designer solution. frontend labels Feb 17, 2025
Copy link
Contributor

coderabbitai bot commented Feb 17, 2025

📝 Walkthrough

Walkthrough

The pull request introduces several changes, including the modification of a key-value pair in nb.json, the removal of the outdated CollapsiblePropertyEditor component along with its styles and tests, and updates to the FormComponentConfig component to utilize a new hook and the SelectPropertyEditor. Additionally, new CSS styles, tests, and an export for the SelectPropertyEditor have been added, while related test descriptions in FormComponentConfig have been adjusted.

Changes

File(s) Change Summary
frontend/language/src/nb.json Updated the key-value pair for "ux_editor.component_properties.showValidations" from "Vis valideringstyper" to "Valideringstyper".
frontend/packages/ux-editor/src/components/config/CollapsiblePropertyEditor/... Removed the CollapsiblePropertyEditor component, its associated test file, CSS module, and export statement.
frontend/packages/ux-editor/src/components/config/FormComponentConfig.module.css Added a new .gridButton rule (margin-bottom: var(--fds-spacing-0)) and updated the .button margin from var(--fds-spacing-1) to var(--fds-spacing-2).
frontend/packages/ux-editor/src/components/config/FormComponentConfig.test.tsx Updated test descriptions to reflect rendering property text instead of the CollapsiblePropertyEditor, and added new tests for array properties.
frontend/packages/ux-editor/src/components/config/FormComponentConfig.tsx Modified component logic to use useComponentPropertyEnumValue and replaced CollapsiblePropertyEditor with SelectPropertyEditor, updating several method signatures.
frontend/packages/ux-editor/src/components/config/SelectPropertyEditor/... Introduced the new SelectPropertyEditor component with its CSS module, tests, and added export in the index file.

Possibly related PRs

Suggested labels

team/studio-domain1

Suggested reviewers

  • Jondyr

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

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: 1

🧹 Nitpick comments (5)
frontend/packages/ux-editor/src/components/config/FormComponentConfig.module.css (1)

5-8: Duplicate Declaration for .button
There are two separate declarations for the .button class—with the first (lines 5–8) setting margin: var(--fds-spacing-1) and the later one (lines 34–36) updating it to var(--fds-spacing-2). Please confirm if this intentional dual declaration is desired for handling different contexts or if it might be beneficial to consolidate these styles into a single definition to improve maintainability and reduce potential specificity conflicts.

Also applies to: 34-36

frontend/packages/ux-editor/src/components/config/SelectPropertyEditor/SelectPropertyEditor.tsx (1)

15-47: Consider adding error boundaries and loading states.

The component implementation is clean and follows React best practices. However, consider these improvements:

  1. Add error boundaries to handle potential rendering errors
  2. Add loading states for async operations
  3. Consider memoizing the callbacks to prevent unnecessary re-renders
 export const SelectPropertyEditor = ({
   children,
   value,
   property,
   title,
 }: SelectPropertyEditorProps) => {
   const { t } = useTranslation();
   const [dataTypeSelectVisible, setDataTypeSelectVisible] = useState(false);
+  const handleClose = useCallback(() => setDataTypeSelectVisible(false), []);
+  const handleOpen = useCallback(() => setDataTypeSelectVisible(true), []);
 
   return (
     <div className={cn(dataTypeSelectVisible ? classes.container : classes.viewMode)}>
       {dataTypeSelectVisible ? (
         <div className={classes.editSelectProperty}>
           <div className={classes.selectProperty}>{children}</div>
           <StudioButton
             icon={<XMarkIcon />}
-            onClick={() => setDataTypeSelectVisible(false)}
+            onClick={handleClose}
             title={t('general.close')}
             variant='secondary'
           />
         </div>
       ) : (
         <StudioProperty.Button
-          onClick={() => setDataTypeSelectVisible(true)}
+          onClick={handleOpen}
           property={property}
           title={title}
           value={value}
           className={classes.viewSelectProperty}
         />
       )}
     </div>
   );
 };
frontend/packages/ux-editor/src/components/config/SelectPropertyEditor/SelectPropertyEditor.test.tsx (2)

12-38: Add more test coverage for edge cases.

The test suite covers basic functionality well. Consider adding tests for:

  1. Error scenarios
  2. Empty/null values
  3. Long text overflow handling
  4. Keyboard navigation
  5. Accessibility (ARIA attributes)

46-48: Consider improving test helper function.

The renderSelectPropertyEditor helper could be enhanced:

 const renderSelectPropertyEditor = (props: Partial<SelectPropertyEditorProps> = {}) => {
-  renderWithProviders()(<SelectPropertyEditor {...defaultProps} {...props} />);
+  const result = renderWithProviders()(<SelectPropertyEditor {...defaultProps} {...props} />);
+  return {
+    ...result,
+    rerender: (newProps: Partial<SelectPropertyEditorProps> = {}) =>
+      result.rerender(<SelectPropertyEditor {...defaultProps} {...newProps} />),
+  };
 };
frontend/packages/ux-editor/src/components/config/FormComponentConfig.tsx (1)

227-251: Consider extracting string property rendering logic.

The string property handling logic is becoming complex. Consider extracting it into a separate component for better maintainability.

+const StringPropertyEditor = ({ propertyKey, component, handleComponentUpdate }) => {
+  const componentPropertyLabel = useComponentPropertyLabel();
+  const selectedDataType = useComponentPropertyEnumValue();
+
+  const selectedStringPropertiesDisplay = () => {
+    const value = component[propertyKey];
+    if (Array.isArray(value)) return value.map((dataType) => selectedDataType(dataType));
+    if (value) return selectedDataType(value);
+    return undefined;
+  };
+
+  return (
+    <SelectPropertyEditor
+      key={propertyKey}
+      property={componentPropertyLabel(propertyKey)}
+      title={componentPropertyLabel(propertyKey)}
+      value={selectedStringPropertiesDisplay()}
+    >
+      <EditStringValue
+        key={propertyKey}
+        component={component}
+        handleComponentChange={handleComponentUpdate}
+        propertyKey={propertyKey}
+        enumValues={properties[propertyKey]?.enum || properties[propertyKey]?.examples}
+      />
+    </SelectPropertyEditor>
+  );
+};
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 38138e4 and 8f90bef.

📒 Files selected for processing (12)
  • frontend/language/src/nb.json (1 hunks)
  • frontend/packages/ux-editor/src/components/config/CollapsiblePropertyEditor/CollapsiblePropertyEditor.module.css (0 hunks)
  • frontend/packages/ux-editor/src/components/config/CollapsiblePropertyEditor/CollapsiblePropertyEditor.test.tsx (0 hunks)
  • frontend/packages/ux-editor/src/components/config/CollapsiblePropertyEditor/CollapsiblePropertyEditor.tsx (0 hunks)
  • frontend/packages/ux-editor/src/components/config/CollapsiblePropertyEditor/index.ts (0 hunks)
  • frontend/packages/ux-editor/src/components/config/FormComponentConfig.module.css (1 hunks)
  • frontend/packages/ux-editor/src/components/config/FormComponentConfig.test.tsx (3 hunks)
  • frontend/packages/ux-editor/src/components/config/FormComponentConfig.tsx (4 hunks)
  • frontend/packages/ux-editor/src/components/config/SelectPropertyEditor/SelectPropertyEditor.module.css (1 hunks)
  • frontend/packages/ux-editor/src/components/config/SelectPropertyEditor/SelectPropertyEditor.test.tsx (1 hunks)
  • frontend/packages/ux-editor/src/components/config/SelectPropertyEditor/SelectPropertyEditor.tsx (1 hunks)
  • frontend/packages/ux-editor/src/components/config/SelectPropertyEditor/index.ts (1 hunks)
💤 Files with no reviewable changes (4)
  • frontend/packages/ux-editor/src/components/config/CollapsiblePropertyEditor/index.ts
  • frontend/packages/ux-editor/src/components/config/CollapsiblePropertyEditor/CollapsiblePropertyEditor.module.css
  • frontend/packages/ux-editor/src/components/config/CollapsiblePropertyEditor/CollapsiblePropertyEditor.tsx
  • frontend/packages/ux-editor/src/components/config/CollapsiblePropertyEditor/CollapsiblePropertyEditor.test.tsx
✅ Files skipped from review due to trivial changes (3)
  • frontend/packages/ux-editor/src/components/config/SelectPropertyEditor/index.ts
  • frontend/packages/ux-editor/src/components/config/SelectPropertyEditor/SelectPropertyEditor.module.css
  • frontend/language/src/nb.json
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Build environment and run e2e test
  • GitHub Check: Testing
  • GitHub Check: CodeQL
🔇 Additional comments (5)
frontend/packages/ux-editor/src/components/config/FormComponentConfig.module.css (2)

15-18: New Style Addition for .gridButton
A new rule with margin-bottom: var(--fds-spacing-0); has been added to the .gridButton block. This update appears intended to adjust the vertical spacing of grid-based buttons as per the new design specifications. Please verify that the chosen spacing is consistent with the overall UI guidelines.


34-36: Updated .button Spacing
The declaration for the .button class has been modified to use margin: var(--fds-spacing-2);. This change updates the spacing of button elements to align with new design requirements.

frontend/packages/ux-editor/src/components/config/SelectPropertyEditor/SelectPropertyEditor.tsx (1)

8-13: LGTM! Props interface is well-defined.

The SelectPropertyEditorProps interface is clean and properly typed with optional properties.

frontend/packages/ux-editor/src/components/config/FormComponentConfig.tsx (1)

21-22: LGTM! Good use of custom hooks.

The addition of useComponentPropertyEnumValue hook and state management is well-implemented.

frontend/packages/ux-editor/src/components/config/FormComponentConfig.test.tsx (1)

163-242: LGTM! Test descriptions updated correctly.

The test descriptions have been properly updated to reflect the new component structure, maintaining good test coverage.

Copy link

codecov bot commented Feb 17, 2025

Codecov Report

Attention: Patch coverage is 96.42857% with 1 line in your changes missing coverage. Please review.

Project coverage is 95.76%. Comparing base (41c86ad) to head (38bf71a).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...itor/src/components/config/FormComponentConfig.tsx 93.33% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #14686      +/-   ##
==========================================
- Coverage   95.76%   95.76%   -0.01%     
==========================================
  Files        1917     1916       -1     
  Lines       24979    24988       +9     
  Branches     2860     2859       -1     
==========================================
+ Hits        23922    23930       +8     
- Misses        798      799       +1     
  Partials      259      259              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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

🧹 Nitpick comments (1)
frontend/packages/ux-editor/src/components/config/FormComponentConfig.test.tsx (1)

1-582: Consider adding more test cases for SelectPropertyEditor.

While the current test coverage is good, consider adding these additional test cases for the SelectPropertyEditor:

  1. Test for handling invalid/empty selections
  2. Test for proper state updates after selection
  3. Test for keyboard navigation

Example test case:

it('should handle keyboard navigation in SelectPropertyEditor', async () => {
  const user = userEvent.setup();
  render({
    props: {
      schema: {
        properties: {
          [selectedDataType]: {
            type: 'string',
            enum: ['option1', 'option2'],
          },
        },
      },
    },
  });
  
  const button = screen.getByRole('button', {
    name: textMock(`ux_editor.component_properties.${selectedDataType}`),
  });
  await user.click(button);
  
  const combobox = screen.getByRole('combobox', {
    name: textMock(`ux_editor.component_properties.${selectedDataType}`),
  });
  
  // Test keyboard navigation
  await user.type(combobox, '{arrowdown}');
  await user.type(combobox, '{enter}');
  
  expect(combobox).toHaveValue('option1');
});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8f90bef and bd39b33.

📒 Files selected for processing (1)
  • frontend/packages/ux-editor/src/components/config/FormComponentConfig.test.tsx (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Build environment and run e2e test
  • GitHub Check: Testing
  • GitHub Check: CodeQL
🔇 Additional comments (4)
frontend/packages/ux-editor/src/components/config/FormComponentConfig.test.tsx (4)

9-9: LGTM!

The addition of waitFor from @testing-library/react is appropriate for handling asynchronous test assertions.


16-16: LGTM!

The constant selectedDataType is well-named and aligns with its usage in the new test case.


164-189: Test descriptions accurately reflect the new component behavior.

The test descriptions have been updated to reflect the removal of CollapsiblePropertyEditor and now correctly describe the expected behavior of rendering property text. This aligns with the PR's objective of introducing the new SelectPropertyEditor component.

Also applies to: 191-219, 221-243


285-309: Test for SelectPropertyEditor follows best practices.

The new test case:

  1. Properly sets up user events
  2. Verifies both the button and combobox rendering
  3. Uses appropriate assertions with waitFor for async operations
  4. Follows the same pattern as other similar tests in the file

This test is crucial for validating the fix for issue #14472, ensuring that selector values are properly displayed in the configuration panel.

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

🧹 Nitpick comments (1)
frontend/packages/ux-editor/src/components/config/FormComponentConfig.test.tsx (1)

497-529: Good test coverage for enum values rendering.

The test effectively verifies the rendering of enum values. Consider adding a test case for the empty state when no enum values are selected.

Add a test case for the initial state:

 it('should render array properties with enum values correctly', async () => {
   const user = userEvent.setup();
   const propertyKey = 'supportedArrayProperty';
   const enumValues = ['option1', 'option2'];
+  // First test the empty state
+  render({
+    props: {
+      schema: {
+        properties: {
+          [propertyKey]: {
+            type: 'array',
+            items: {
+              type: 'string',
+              enum: enumValues,
+            },
+          },
+        },
+      },
+      component: {
+        ...componentMocks.Input,
+      },
+    },
+  });
+  const emptyArrayPropertyButton = screen.getByRole('button', {
+    name: textMock(`ux_editor.component_properties.${propertyKey}`),
+  });
+  await user.click(emptyArrayPropertyButton);
+  expect(screen.getByRole('combobox')).toHaveValue('');
+
+  // Then test with selected values
   render({
     props: {
       schema: {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c888888 and 0134070.

📒 Files selected for processing (1)
  • frontend/packages/ux-editor/src/components/config/FormComponentConfig.test.tsx (6 hunks)
🔇 Additional comments (3)
frontend/packages/ux-editor/src/components/config/FormComponentConfig.test.tsx (3)

9-9: LGTM!

Good addition of the waitFor utility for handling asynchronous operations in tests.


284-334: Well-structured test with comprehensive coverage!

This test demonstrates several good practices:

  • Proper setup of user events
  • Clear test data preparation
  • Step-by-step verification of component behavior
  • Async/await usage for handling UI interactions
  • Verification of both UI updates and callback invocations

163-242:

✅ Verification successful

Test descriptions accurately reflect the new component structure.

The updated test descriptions align well with the PR's objective of replacing CollapsiblePropertyEditor with SelectPropertyEditor. The focus on testing functionality rather than specific component implementation is a good practice.

Let's verify the test coverage for the new SelectPropertyEditor component:


🏁 Script executed:

#!/bin/bash
# Description: Check test coverage for SelectPropertyEditor
# Look for test files related to SelectPropertyEditor
fd "SelectPropertyEditor.*test" -t f

# Look for test cases covering SelectPropertyEditor
rg -A 5 "describe.*SelectPropertyEditor" 

Length of output: 1095


Updated Test Coverage and Component Structure Verification

The test descriptions now accurately reflect the new component structure. In addition to the FormComponentConfig tests, the new tests for the SelectPropertyEditor component (in frontend/packages/ux-editor/src/components/config/SelectPropertyEditor/SelectPropertyEditor.test.tsx) confirm that the functionality is well-covered—e.g., verifying that children are rendered when the button is clicked. This aligns with the PR’s objective of replacing the CollapsiblePropertyEditor with the more focused SelectPropertyEditor, emphasizing proper functionality tests.

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: 1

🧹 Nitpick comments (3)
frontend/packages/ux-editor/src/components/config/FormComponentConfig.tsx (3)

48-59: Optimize memoization for better performance.

The current implementation of memoizedGetSelectedValuesDisplay could be optimized:

  1. Move the div creation logic outside the memoized function
  2. Consider memoizing the mapped values separately

Consider this optimization:

-const memoizedGetSelectedValuesDisplay = useMemo(
-  () => (propertyKey: string) => {
-    if (!component[propertyKey] || component[propertyKey].length === 0) return undefined;
-    return component[propertyKey].map((dataType: string) => (
-      <div key={dataType}>{selectedDataType(dataType)}</div>
-    ));
-  },
-  [component, selectedDataType],
-);
+const memoizedSelectedValues = useMemo(
+  () => (propertyKey: string) => {
+    if (!component[propertyKey] || component[propertyKey].length === 0) return undefined;
+    return component[propertyKey].map(selectedDataType);
+  },
+  [component, selectedDataType],
+);
+
+const getSelectedValuesDisplay = (propertyKey: string) => {
+  const values = memoizedSelectedValues(propertyKey);
+  return values?.map((value: string) => (
+    <div key={value}>{value}</div>
+  ));
+};

266-282: Add number formatting for better readability.

Consider formatting the number value for better user experience.

Consider this improvement:

-value={component[propertyKey]}
+value={typeof component[propertyKey] === 'number' ? 
+  component[propertyKey].toLocaleString() : 
+  component[propertyKey]}

300-307: Improve error message for better debugging.

The error handling is good, but the error message could be more descriptive.

Consider this improvement:

-console.error(error);
+console.error(
+  `Error updating component for property ${propertyKey}:`,
+  error,
+  { component: updatedComponent }
+);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0134070 and c43bc0b.

📒 Files selected for processing (1)
  • frontend/packages/ux-editor/src/components/config/FormComponentConfig.tsx (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Build environment and run e2e test
  • GitHub Check: CodeQL
  • GitHub Check: Testing
🔇 Additional comments (1)
frontend/packages/ux-editor/src/components/config/FormComponentConfig.tsx (1)

1-1: LGTM! Clean import organization.

The new imports are well-organized and follow React best practices.

Also applies to: 21-22

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

🧹 Nitpick comments (3)
frontend/packages/ux-editor/src/components/config/FormComponentConfig.tsx (3)

51-59: Add error handling to memoizedGetSelectedValuesDisplay.

The function should handle potential errors when accessing component properties or during map operations.

 const memoizedGetSelectedValuesDisplay = useMemo(
   () => (propertyKey: string) => {
-    if (!component[propertyKey] || component[propertyKey].length === 0) return undefined;
-    return component[propertyKey].map((dataType: string) => (
-      <div key={dataType}>{selectedDataType(dataType)}</div>
-    ));
+    try {
+      if (!component[propertyKey] || component[propertyKey].length === 0) return undefined;
+      return component[propertyKey].map((dataType: string) => (
+        <div key={dataType}>{selectedDataType(dataType)}</div>
+      ));
+    } catch (error) {
+      console.error('Error displaying selected values:', error);
+      return undefined;
+    }
   },
   [component, selectedDataType],
 );

253-267: Remove duplicate key prop.

The key prop is unnecessarily duplicated on both the SelectPropertyEditor and EditStringValue components.

 <SelectPropertyEditor
   key={propertyKey}
   property={componentPropertyLabel(propertyKey)}
   title={componentPropertyLabel(propertyKey)}
   value={memoizedSelectedStringPropertiesDisplay(propertyKey)}
 >
   <EditStringValue
-    key={propertyKey}
     component={component}
     handleComponentChange={handleComponentUpdate}
     propertyKey={propertyKey}
     enumValues={properties[propertyKey]?.enum || properties[propertyKey]?.examples}
   />
 </SelectPropertyEditor>

294-298: Memoize selectProperty calculation.

The selectProperty calculation should be memoized to prevent unnecessary recalculations on each render.

+const selectProperty = useMemo(
+  () =>
+    selectedValue.length > 0
+      ? t('ux_editor.component_properties.selected_validations')
+      : componentPropertyLabel(propertyKey),
+  [selectedValue.length, t, componentPropertyLabel, propertyKey]
+);
-const selectProperty =
-  selectedValue.length > 0
-    ? t('ux_editor.component_properties.selected_validations')
-    : componentPropertyLabel(propertyKey);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c43bc0b and 6b4f596.

📒 Files selected for processing (1)
  • frontend/packages/ux-editor/src/components/config/FormComponentConfig.tsx (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Build environment and run e2e test
  • GitHub Check: CodeQL
  • GitHub Check: Typechecking and linting
  • GitHub Check: Testing
🔇 Additional comments (2)
frontend/packages/ux-editor/src/components/config/FormComponentConfig.tsx (2)

273-289: Remove duplicate key prop.

The key prop is unnecessarily duplicated on both the SelectPropertyEditor and EditNumberValue components.

 <SelectPropertyEditor
   key={propertyKey}
   property={componentPropertyLabel(
     `${propertyKey}${propertyKey === 'preselectedOptionIndex' ? '_button' : ''}`,
   )}
   title={componentPropertyLabel(propertyKey)}
   value={component[propertyKey]}
 >
   <EditNumberValue
     component={component}
     handleComponentChange={handleComponentUpdate}
     propertyKey={propertyKey}
-    key={propertyKey}
     enumValues={properties[propertyKey]?.enum}
   />
 </SelectPropertyEditor>

299-317: Remove duplicate key prop.

The key prop is unnecessarily duplicated on both the SelectPropertyEditor and EditStringValue components.

 <SelectPropertyEditor
   key={propertyKey}
   property={selectProperty}
   title={componentPropertyLabel(propertyKey)}
   value={memoizedGetSelectedValuesDisplay(propertyKey)}
 >
   <EditStringValue
     component={component}
     handleComponentChange={(updatedComponent) => {
       setSelectedValue(updatedComponent[propertyKey]);
       handleComponentUpdate(updatedComponent);
     }}
     propertyKey={propertyKey}
-    key={propertyKey}
     enumValues={properties[propertyKey]?.items?.enum}
     multiple={true}
   />
 </SelectPropertyEditor>

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

🧹 Nitpick comments (2)
frontend/packages/ux-editor/src/components/config/FormComponentConfig.test.tsx (2)

336-369: Consider enhancing error handling test coverage.

While the test verifies that handleComponentUpdate is not called on error, it could be improved to:

  1. Test specific error scenarios (e.g., invalid enum values, type mismatches)
  2. Verify error messages or UI feedback
  3. Test error recovery paths

Example enhancement:

 it('should return undefined when an error occurs in memoizedSelectedStringPropertiesDisplay', async () => {
   const propertyKey = 'invalidPropertyKey';
   const handleComponentUpdateMock = jest.fn();
   const user = userEvent.setup();
+  const consoleSpy = jest.spyOn(console, 'error').mockImplementation();
   render({
     props: {
       schema: {
         properties: {
           [propertyKey]: {
             type: 'array',
             items: {
-              type: 'string',
-              enum: ['option1', 'option2'],
+              type: 'number', // Intentional type mismatch
+              enum: [1, 2],
             },
           },
         },
       },
       handleComponentUpdate: handleComponentUpdateMock,
     },
   });
   
   // ... existing test code ...
   
+  // Verify error handling
+  expect(consoleSpy).toHaveBeenCalled();
+  expect(screen.getByText(/error message/i)).toBeInTheDocument();
+  
+  // Test recovery
+  await user.click(screen.getByRole('button', { name: /close/i }));
+  expect(screen.queryByText(/error message/i)).not.toBeInTheDocument();
+  
+  consoleSpy.mockRestore();
 });

284-334: Consider adding edge cases to array property update test.

The test effectively covers the happy path, but consider adding test cases for:

  1. Multiple selections
  2. Deselection
  3. Empty array handling
  4. Maximum selection limit (if applicable)

Example additions:

 it('should call handleComponentUpdate and setSelectedValue when array property is updated', async () => {
   // ... existing test code ...
   
+  // Test multiple selections
+  const option2 = screen.getByRole('option', {
+    name: textMock('ux_editor.component_properties.enum_option2'),
+  });
+  await user.click(option2);
+  
+  await waitFor(() => {
+    expect(handleComponentUpdateMock).toHaveBeenCalledWith(
+      expect.objectContaining({
+        [propertyKey]: ['option1', 'option2'],
+      }),
+    );
+  });
+  
+  // Test deselection
+  await user.click(option1);
+  
+  await waitFor(() => {
+    expect(handleComponentUpdateMock).toHaveBeenCalledWith(
+      expect.objectContaining({
+        [propertyKey]: ['option2'],
+      }),
+    );
+  });
 });
+
+it('should handle empty array selection correctly', async () => {
+  // Add test for empty array handling
+});
+
+it('should respect maximum selection limit', async () => {
+  // Add test for maximum selection limit
+});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6b4f596 and a283811.

📒 Files selected for processing (1)
  • frontend/packages/ux-editor/src/components/config/FormComponentConfig.test.tsx (6 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Build environment and run e2e test
  • GitHub Check: CodeQL
  • GitHub Check: Testing
🔇 Additional comments (2)
frontend/packages/ux-editor/src/components/config/FormComponentConfig.test.tsx (2)

9-9: LGTM! Import of waitFor is necessary for async testing.

The addition of waitFor from @testing-library/react is appropriate for handling asynchronous operations in the new test cases.


163-242: LGTM! Test descriptions accurately reflect the new component behavior.

The updated test cases properly verify the rendering of property text instead of checking for specific component types, which aligns with the PR's objective of replacing CollapsiblePropertyEditor with SelectPropertyEditor.

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

🧹 Nitpick comments (2)
frontend/packages/ux-editor/src/components/config/FormComponentConfig.tsx (2)

51-68: Add error handling to memoized functions.

While the memoization is good for performance, consider adding error handling to gracefully handle potential undefined values or type mismatches.

 const memoizedGetSelectedValuesDisplay = useMemo(
   () => (propertyKey: string) => {
+    try {
       if (!component[propertyKey] || component[propertyKey].length === 0) return undefined;
       return component[propertyKey].map((dataType: string) => (
         <div key={dataType}>{selectedDataType(dataType)}</div>
       ));
+    } catch (error) {
+      console.error('Error displaying selected values:', error);
+      return undefined;
+    }
   },
   [component, selectedDataType],
 );

 const memoizedSelectedStringPropertiesDisplay = useMemo(
   () => (propertyKey: string) => {
+    try {
       const value = component[propertyKey];
       if (Array.isArray(value)) return value.map((dataType) => selectedDataType(dataType));
       return value ? selectedDataType(value) : undefined;
+    } catch (error) {
+      console.error('Error displaying string properties:', error);
+      return undefined;
+    }
   },
   [component, selectedDataType],
 );

288-313: Improve state management in array properties.

The state management for selected values could be improved to prevent potential race conditions.

-handleComponentChange={(updatedComponent) => {
-  setSelectedValue(updatedComponent[propertyKey]);
-  handleComponentUpdate(updatedComponent);
-}}
+handleComponentChange={useCallback((updatedComponent) => {
+  try {
+    const newValue = updatedComponent[propertyKey] || [];
+    setSelectedValue(newValue);
+    handleComponentUpdate(updatedComponent);
+  } catch (error) {
+    console.error('Error updating component:', error);
+  }
+}, [propertyKey, handleComponentUpdate])}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a283811 and 3985752.

📒 Files selected for processing (2)
  • frontend/packages/ux-editor/src/components/config/FormComponentConfig.test.tsx (6 hunks)
  • frontend/packages/ux-editor/src/components/config/FormComponentConfig.tsx (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Build environment and run e2e test
  • GitHub Check: Testing
  • GitHub Check: Typechecking and linting
  • GitHub Check: CodeQL
🔇 Additional comments (4)
frontend/packages/ux-editor/src/components/config/FormComponentConfig.tsx (3)

1-1: LGTM! Well-structured hooks and imports.

The new hooks and imports are well-organized and properly typed, supporting the PR's objective of displaying selector values.

Also applies to: 21-22, 48-49


246-263: LGTM! Clean implementation of SelectPropertyEditor.

The replacement of CollapsiblePropertyEditor with SelectPropertyEditor is well-implemented, with proper property and title props.


266-285: LGTM! Consistent implementation for number properties.

The SelectPropertyEditor implementation for number properties is consistent with string properties, with proper handling of preselectedOptionIndex.

frontend/packages/ux-editor/src/components/config/FormComponentConfig.test.tsx (1)

284-334: LGTM! Comprehensive test coverage.

The new tests thoroughly cover:

  1. Array property updates and state management
  2. Enum value rendering
  3. User interactions with the SelectPropertyEditor

The test cases are well-structured and provide good coverage of the new functionality.

Also applies to: 486-518

@mlqn mlqn self-assigned this Feb 19, 2025
@mlqn mlqn removed their assignment Feb 20, 2025
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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3985752 and 37828e6.

📒 Files selected for processing (2)
  • frontend/language/src/nb.json (1 hunks)
  • frontend/packages/ux-editor/src/components/config/FormComponentConfig.tsx (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/language/src/nb.json
🧰 Additional context used
🪛 GitHub Check: CodeQL
frontend/packages/ux-editor/src/components/config/FormComponentConfig.tsx

[notice] 49-49: Unused variable, import, function or class
Unused variable selectedValue.

🪛 GitHub Check: Typechecking and linting
frontend/packages/ux-editor/src/components/config/FormComponentConfig.tsx

[failure] 49-49:
'selectedValue' is declared but its value is never read.

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build environment and run e2e test
  • GitHub Check: Testing

@JamalAlabdullah JamalAlabdullah requested a review from mlqn February 20, 2025 15:31
Copy link
Contributor

@mlqn mlqn left a comment

Choose a reason for hiding this comment

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

Nice work! 🚀 Tested OK 💪

@mlqn mlqn added the skip-manual-testing PRs that do not need to be tested manually label Feb 20, 2025
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: 1

🧹 Nitpick comments (3)
frontend/packages/ux-editor/src/components/config/FormComponentConfig.tsx (3)

21-22: Add error handling for the enum value hook.

Consider wrapping the hook usage in a try-catch block to handle potential errors gracefully.

-  const selectedDataType = useComponentPropertyEnumValue();
+  const selectedDataType = useMemo(() => {
+    try {
+      return useComponentPropertyEnumValue();
+    } catch (error) {
+      console.error('Error getting enum value:', error);
+      return (value: string) => value;
+    }
+  }, []);

Also applies to: 48-49


247-261: Optimize property and title props in SelectPropertyEditor.

The property and title props are being set to the same value, which is redundant.

 <SelectPropertyEditor
   key={propertyKey}
   property={componentPropertyLabel(propertyKey)}
-  title={componentPropertyLabel(propertyKey)}
   value={memoizedSelectedStringPropertiesDisplay(propertyKey)}
 >

267-283: Simplify property label construction.

Consider extracting the complex property label logic into a separate memoized function.

+const getPropertyLabel = useMemo(
+  () => (propertyKey: string): string => {
+    return componentPropertyLabel(
+      `${propertyKey}${propertyKey === 'preselectedOptionIndex' ? '_button' : ''}`
+    );
+  },
+  [componentPropertyLabel]
+);

 <SelectPropertyEditor
   key={propertyKey}
-  property={componentPropertyLabel(
-    `${propertyKey}${propertyKey === 'preselectedOptionIndex' ? '_button' : ''}`,
-  )}
+  property={getPropertyLabel(propertyKey)}
   title={componentPropertyLabel(propertyKey)}
   value={component[propertyKey]}
 >
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 37828e6 and 38bf71a.

📒 Files selected for processing (1)
  • frontend/packages/ux-editor/src/components/config/FormComponentConfig.tsx (5 hunks)
🔇 Additional comments (1)
frontend/packages/ux-editor/src/components/config/FormComponentConfig.tsx (1)

289-305: LGTM! Array properties handling has been improved.

The implementation correctly handles array properties and the unused state variable has been removed as suggested in past reviews.

@mlqn mlqn merged commit 0df8045 into main Feb 20, 2025
13 checks passed
@mlqn mlqn deleted the 14472-should-show-the-value-of-selector-in-properties-config branch February 20, 2025 16:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area/ui-editor Area: Related to the designer tool for assembling app UI in Altinn Studio. frontend skip-manual-testing PRs that do not need to be tested manually solution/studio/designer Issues related to the Altinn Studio Designer solution.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

should show the value of selector in properties config
2 participants