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: summary2 set correct layoutset as default #14473

Merged
merged 38 commits into from
Jan 28, 2025

Conversation

Jondyr
Copy link
Member

@Jondyr Jondyr commented Jan 21, 2025

Description

layoutSet target is now selected layoutSet when adding a new summary2 component. Previously it was automatically set to the first layout set created.

PR stack

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

Release Notes

  • New Features

    • Added a new search functionality to the app
    • Introduced enhanced configuration options for Summary2 components
    • Implemented improved handling of empty fields in summaries
  • Improvements

    • Updated language translations for better user experience
    • Enhanced component reference selection
    • Improved layout set management
    • Added more robust error handling and validation
  • Bug Fixes

    • Fixed issues with component visibility and override settings
    • Corrected layout set target selection logic
  • UI/UX Updates

    • Added new styling for required fields and component configurations
    • Improved internationalization support
    • Enhanced component interaction and state management

Copy link
Contributor

coderabbitai bot commented Jan 21, 2025

Warning

Rate limit exceeded

@Jondyr has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 3 minutes and 41 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 5622521 and 8e89ed4.

📒 Files selected for processing (4)
  • frontend/packages/ux-editor/src/components/Properties/PropertiesHeader/ComponentMainConfig.test.tsx (2 hunks)
  • frontend/packages/ux-editor/src/components/config/componentSpecificContent/Summary2/Summary2Component.test.tsx (1 hunks)
  • frontend/packages/ux-editor/src/components/config/componentSpecificContent/Summary2/Summary2Target/Summary2Target.tsx (3 hunks)
  • frontend/packages/ux-editor/src/components/config/componentSpecificContent/Summary2/Summary2Target/targetUtils.ts (2 hunks)
📝 Walkthrough

Walkthrough

This pull request introduces comprehensive changes to the Summary2 component in the UX editor, focusing on enhancing configuration options for component summaries. The modifications span multiple files across the frontend packages, introducing new components, utility functions, and UI elements that improve the handling of component overrides, target selection, and display settings. The changes primarily aim to provide more granular control over how summary components are rendered and configured.

Changes

File Change Summary
frontend/language/src/nb.json Added new translation keys for required fields and summary configuration
frontend/packages/shared/src/types/api/dto/LayoutSetModel.ts Made task property optional in LayoutSetModel type
frontend/packages/ux-editor/src/components/Properties/* Added new components for handling Summary2 configuration, including ComponentMainConfig, RequiredIndicator
frontend/packages/ux-editor/src/components/config/componentSpecificContent/Summary2/* Extensive updates to Summary2 component, including new override fields, target selection, and display configuration components

Possibly related issues

  • Summary 2 issues #14459: This PR addresses several issues mentioned in the related issue:
    • Improved layout set selection logic
    • Enhanced component list filtering in overrides
    • More flexible component summary configuration

Possibly related PRs

Suggested labels

area/ui-editor, solution/studio/designer, kind/bug, frontend, team/studio-domain1, skip-manual-testing, skip-documentation

Suggested reviewers

  • ErlingHauan

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.

@Jondyr Jondyr changed the base branch from main to 21-01-summary2-filter-override-components January 21, 2025 11:10
@Jondyr Jondyr linked an issue Jan 21, 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 Jan 21, 2025
@Jondyr Jondyr force-pushed the 21-01-summary2-filter-override-components branch from aee4443 to 0192d05 Compare January 21, 2025 11:19
@Jondyr Jondyr force-pushed the 21-01-summary2-set-correct-layoutset-as-default branch from 5622521 to 95135d0 Compare January 21, 2025 11:19
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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 4

🧹 Nitpick comments (13)
frontend/packages/ux-editor/src/components/config/componentSpecificContent/Summary2/Override/Summary2OverrideEntry.module.css (3)

1-9: Consider adding gap fallback for better browser compatibility.

While the styles look good, consider adding a fallback for the gap property to support older browsers.

 .card {
   margin-top: var(--fds-spacing-4);
   margin-bottom: var(--fds-spacing-4);
+  /* Fallback for browsers that don't support gap */
+  margin-bottom: calc(var(--fds-spacing-4) + var(--fds-spacing-4));
   gap: var(--fds-spacing-4);
 }

11-13: Simplify property class by removing unnecessary padding.

The --fds-spacing-0 variable likely equals 0, making this padding declaration unnecessary.

 .property {
-  padding-left: var(--fds-spacing-0);
 }

26-29: Consider adding gap fallback for button group.

While the flexbox layout is good, consider adding a fallback for the gap property to support older browsers.

 .buttongroup {
   display: flex;
+  /* Fallback for browsers that don't support gap */
+  margin-right: calc(-1 * var(--fds-spacing-4));
+  > * {
+    margin-right: var(--fds-spacing-4);
+  }
   gap: var(--fds-spacing-4);
 }
frontend/packages/ux-editor/src/components/config/componentSpecificContent/Summary2/Override/OverrideFields/ForceShowSwitch.tsx (2)

6-9: Align type name with component name for consistency.

The props type name ForceShowSwitchProps doesn't match the exported component name OverrideShowComponentSwitch. Consider renaming the type to OverrideShowComponentSwitchProps for better consistency.

-type ForceShowSwitchProps = {
+type OverrideShowComponentSwitchProps = {
   onChange: (updatedOverride: Summary2OverrideConfig) => void;
   override: Summary2OverrideConfig;
 };

-export const OverrideShowComponentSwitch = ({ onChange, override }: ForceShowSwitchProps) => {
+export const OverrideShowComponentSwitch = ({ onChange, override }: OverrideShowComponentSwitchProps) => {

Also applies to: 11-11


21-21: Remove unnecessary value prop.

The value prop on StudioSwitch appears to be unnecessary as it's not being used for any functional purpose. Consider removing it for cleaner code.

     <StudioSwitch
       position='right'
       size='sm'
       onChange={(event: React.ChangeEvent<HTMLInputElement>) =>
         onChange({ ...override, hidden: !event.target.checked })
       }
       checked={!override.hidden}
-      value={'hidden'}
     >
frontend/packages/ux-editor/src/components/config/componentSpecificContent/Summary2/Override/OverrideFields/CompactViewSwitch.tsx (1)

22-26: Consider performance and type safety improvements.

A few suggestions to enhance the code:

  1. Memoize the components array to prevent unnecessary recalculations
  2. Add null check before accessing component type
  3. Improve type safety by avoiding type assertion
+ const components = useMemo(
+   () => Object.values(formLayoutsData).flatMap((layout) =>
+     getAllLayoutComponents(layout)
+   ),
+   [formLayoutsData]
+ );
- const components = Object.values(formLayoutsData).flatMap((layout) =>
-   getAllLayoutComponents(layout),
- );
  const component = components.find((comp) => comp.id === override.componentId);
- const isGroupComponent = component?.type === (ComponentType.Group as ComponentType);
+ const isGroupComponent = component?.type === ComponentType.Group;
frontend/packages/ux-editor/src/components/config/componentSpecificContent/Summary2/Summary2Target/targetUtils.ts (1)

84-86: Add null safety checks to getLayoutSetOptions.

While the type change to LayoutSetsModel improves type safety, the function should handle potential null/undefined values more robustly.

Consider this safer implementation:

 export const getLayoutSetOptions = (layoutSets: LayoutSetsModel): LayoutSetModel[] => {
-  return layoutSets?.sets.filter((set) => set.task);
+  if (!layoutSets?.sets?.length) {
+    return [];
+  }
+  return layoutSets.sets.filter((set) => set?.task);
 };
frontend/packages/ux-editor/src/components/config/componentSpecificContent/Summary2/Override/OverrideFields/ShowEmptyFieldsSwitch.tsx (1)

17-24: Consider removing unnecessary async.

The event handler is marked as async but doesn't use any await operations.

-      onChange={async (event: React.ChangeEvent<HTMLInputElement>) => {
+      onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
frontend/packages/ux-editor/src/components/config/componentSpecificContent/Summary2/Override/OverrideFields/EmptyTextField.tsx (1)

22-40: Consider adding aria-label for better accessibility.

The StudioToggleableTextfield implementation looks good, but could benefit from accessibility improvements.

   <StudioToggleableTextfield
     inputProps={{
       icon: '',
       label: t('ux_editor.component_properties.summary.override.empty_field_text'),
+      'aria-label': t('ux_editor.component_properties.summary.override.empty_field_text'),
       size: 'sm',
       value: override.emptyFieldText ?? '',
frontend/packages/ux-editor/src/components/config/componentSpecificContent/Summary2/Override/OverrideFields/Summary2OverrideDisplayType.tsx (1)

29-35: Consider extracting the component type check to a utility function.

The component type check could be moved to a reusable utility function for better maintainability.

+const isCheckboxOrMultiselect = (componentId: string): boolean =>
+  componentId.includes(ComponentType.MultipleSelect) ||
+  componentId.includes(ComponentType.Checkboxes);

 export const Summary2OverrideDisplayType = ({
   override,
   onChange,
 }: Summary2OverrideDisplayTypeProps) => {
   const { t } = useTranslation();

-  const checkboxOrMultipleselect =
-    override.componentId.includes(ComponentType.MultipleSelect) ||
-    override.componentId.includes(ComponentType.Checkboxes);
+  const checkboxOrMultipleselect = isCheckboxOrMultiselect(override.componentId);
frontend/packages/ux-editor/src/components/Properties/PropertiesHeader/ComponentMainConfig.tsx (2)

25-26: Consider using a simpler boolean state for single accordion.

Since there's only one accordion item, using a Record for the state might be unnecessary.

-  const [accordionOpen, setAccordionOpen] = React.useState<Record<string, boolean>>({});
+  const [isAccordionOpen, setIsAccordionOpen] = React.useState(false);

51-70: Simplify accordion state management.

With the suggested boolean state, the accordion implementation can be simplified.

-            <Accordion.Item open={accordionOpen['summary2overrides'] === true}>
+            <Accordion.Item open={isAccordionOpen}>
               <Accordion.Header
-                onHeaderClick={() =>
-                  setAccordionOpen((prev) => {
-                    return { ...prev, summary2overrides: !prev['summary2overrides'] };
-                  })
-                }
+                onHeaderClick={() => setIsAccordionOpen((prev) => !prev)}
               >
frontend/packages/ux-editor/src/components/config/componentSpecificContent/Summary2/Override/Summary2Override.tsx (1)

83-108: Improve type safety of useTargetComponentOptions hook.

The hook returns any[] which loses type safety. Consider creating a proper return type for better type checking and documentation.

-const useTargetComponentOptions = (target: Summary2TargetConfig): any[] => {
+type ComponentOption = {
+  id: string;
+  title: string;
+};
+const useTargetComponentOptions = (target: Summary2TargetConfig): ComponentOption[] => {
🛑 Comments failed to post (4)
frontend/packages/ux-editor/src/components/config/componentSpecificContent/Summary2/Summary2ComponentReferenceSelector.tsx (1)

33-35: 💡 Codebase verification

Missing English translation for empty state message

The translation key ux_editor.component_properties.target_empty is only present in the Norwegian translation file (nb.json) but missing in the English translation file (en.json). This needs to be added to ensure proper internationalization support.

  • Add the translation key to frontend/language/src/en.json
🔗 Analysis chain

Verify the translation key exists.

Good addition of the empty state message using StudioCombobox.Empty. This improves user experience by providing clear feedback when no options are available.

Let's verify the translation key exists:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if the translation key exists in the translation files
# Expected result: The key 'ux_editor.component_properties.target_empty' should be present

# Search for the translation key in JSON/TS files
rg -g '*.{json,ts}' '"ux_editor\.component_properties\.target_empty"'

Length of output: 171


Script:

#!/bin/bash
# Search for translation files and then grep for our key
fd -e json -p 'language/src/.*\.json$' --exec grep -l "ux_editor.component_properties.target_empty" {} \;

Length of output: 140


Script:

#!/bin/bash
# List all translation files to confirm available languages
echo "Available language files:"
fd -e json -p 'language/src/.*\.json$'

echo -e "\nChecking en.json content for the key:"
cat frontend/language/src/en.json | grep -A 1 "ux_editor\.component_properties\.target_empty"

Length of output: 432

frontend/packages/ux-editor/src/components/config/componentSpecificContent/Summary2/Summary2Target/targetUtils.ts (1)

43-52: ⚠️ Potential issue

Add error handling for layout set resolution.

The function has potential runtime issues:

  1. The find() operation on line 49 could return undefined, leading to a runtime error when accessing .id
  2. No error handling for cases when the target task ID doesn't match any layout set

Consider this safer implementation:

 export const getTargetLayoutSetName = ({
   target,
   layoutSets,
   selectedFormLayoutSetName,
 }: getTargetLayoutSetNameProps): string => {
-  const layoutSetName = target?.taskId
-    ? layoutSets.sets.find((layoutSet) => layoutSet.task?.id === target.taskId).id
-    : selectedFormLayoutSetName;
-  return layoutSetName;
+  if (!target?.taskId) {
+    return selectedFormLayoutSetName;
+  }
+  const layoutSet = layoutSets.sets.find((set) => set.task?.id === target.taskId);
+  if (!layoutSet) {
+    console.warn(`Layout set not found for task ID: ${target.taskId}`);
+    return selectedFormLayoutSetName;
+  }
+  return layoutSet.id;
 };
📝 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.

export const getTargetLayoutSetName = ({
  target,
  layoutSets,
  selectedFormLayoutSetName,
}: getTargetLayoutSetNameProps): string => {
  if (!target?.taskId) {
    return selectedFormLayoutSetName;
  }
  const layoutSet = layoutSets.sets.find((set) => set.task?.id === target.taskId);
  if (!layoutSet) {
    console.warn(`Layout set not found for task ID: ${target.taskId}`);
    return selectedFormLayoutSetName;
  }
  return layoutSet.id;
};
frontend/packages/ux-editor/src/components/config/componentSpecificContent/Summary2/Override/Summary2OverrideEntry.tsx (1)

53-53: 🛠️ Refactor suggestion

Ensure value prop is false when componentNameType is undefined

When componentNameType is undefined, the value prop for StudioProperty.Button should be set to false to maintain consistent behavior with the StudioProperty.Button component.

Apply this diff to adjust the value prop:

-            value={componentNameType && `${componentNameType} (ID:${override.componentId})`}
+            value={componentNameType ? `${componentNameType} (ID:${override.componentId})` : false}
📝 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.

        value={componentNameType ? `${componentNameType} (ID:${override.componentId})` : false}
frontend/packages/ux-editor/src/components/Properties/PropertiesHeader/ComponentMainConfig.test.tsx (1)

59-64: ⚠️ Potential issue

Remove .only() from the test case.

The test case is currently focused using it.only(), which prevents other tests from running. This is typically used during development and should be removed before merging.

-  it.only('should call handleComponentChange when changing target', async () => {
+  it('should call handleComponentChange when changing target', async () => {
📝 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.

    it('should call handleComponentChange when changing target', async () => {
      const user = userEvent.setup();
      render(summary2Component);
      await user.selectOptions(summary2TargetLayoutSet(), layoutSet2NameMock);
      expect(handleComponentChange).toHaveBeenCalledTimes(1);
    });
🧰 Tools
🪛 Biome (1.9.4)

[error] 59-59: Don't focus the test.

The 'only' method is often used for debugging or during implementation. It should be removed before deploying to production.
Consider removing 'only' to ensure all tests are executed.
Unsafe fix: Remove focus from test.

(lint/suspicious/noFocusedTests)

Copy link

codecov bot commented Jan 21, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 95.70%. Comparing base (3958771) to head (8e89ed4).
Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14473   +/-   ##
=======================================
  Coverage   95.70%   95.70%           
=======================================
  Files        1902     1902           
  Lines       24771    24771           
  Branches     2839     2839           
=======================================
  Hits        23707    23707           
  Misses        803      803           
  Partials      261      261           

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

@mlqn mlqn removed their assignment Jan 23, 2025
@Jondyr Jondyr force-pushed the 21-01-summary2-filter-override-components branch from 31fee1d to a27a6e4 Compare January 27, 2025 09:47
@Jondyr Jondyr force-pushed the 21-01-summary2-set-correct-layoutset-as-default branch from bf55a30 to f47bdec Compare January 27, 2025 09:47
Copy link
Contributor

@lassopicasso lassopicasso left a comment

Choose a reason for hiding this comment

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

Tested in dev - works as expected 👍

@Jondyr Jondyr force-pushed the 21-01-summary2-set-correct-layoutset-as-default branch 2 times, most recently from c5def19 to 1bd1b19 Compare January 28, 2025 07:23
Base automatically changed from 21-01-summary2-filter-override-components to main January 28, 2025 07:36
@Jondyr Jondyr force-pushed the 21-01-summary2-set-correct-layoutset-as-default branch from 1bd1b19 to e9cdf5b Compare January 28, 2025 07:38
@Jondyr Jondyr force-pushed the 21-01-summary2-set-correct-layoutset-as-default branch from e9cdf5b to 8e89ed4 Compare January 28, 2025 07:39
@Jondyr Jondyr merged commit 52bb520 into main Jan 28, 2025
11 checks passed
@Jondyr Jondyr deleted the 21-01-summary2-set-correct-layoutset-as-default branch January 28, 2025 07:55
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 solution/studio/designer Issues related to the Altinn Studio Designer solution. team/studio-domain2
Projects
Status: ✅ Done
Development

Successfully merging this pull request may close these issues.

Summary 2 issues
3 participants