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

feat: Subform table - enable editing of column title #14318

Merged
merged 23 commits into from
Jan 14, 2025

Conversation

lassopicasso
Copy link
Contributor

@lassopicasso lassopicasso commented Dec 19, 2024

Description

This PR enables users to write their custom title for the column in the subform table. This title will be a new text key solely used in the table form, so it won't influence the label of the component itself.
If the column is deleted, then this text key will also be deleted.

The cell content is now displayed as per the Figma design, and is not editable for now.

A simple validation has been added, where the save button is disabled until a component is selected. If the user removes the title completely, the save button will also be disabled.

subform-table-edit-title.mp4

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

    • Enhanced subform table column configuration with new language strings for Norwegian.
    • Introduced a new component for editing column content and titles.
    • Added new utility functions for managing subform table components.
  • Improvements

    • Updated component props for better clarity and consistency.
    • Refined UI for column editing with improved spacing and layout.
  • Localization

    • Added Norwegian translations for subform table column management.

@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 Dec 19, 2024
@lassopicasso lassopicasso changed the title Subform table manually editing column name feat: Subform table enable editing of column title Dec 19, 2024
@lassopicasso lassopicasso changed the title feat: Subform table enable editing of column title feat: Subform table - enable editing of column title Dec 19, 2024
@lassopicasso lassopicasso added the skip-releasenotes Issues that do not make sense to list in our release notes label Dec 19, 2024
Copy link

codecov bot commented Dec 19, 2024

Codecov Report

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

Project coverage is 95.66%. Comparing base (a514966) to head (403ce43).
Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
...TableColumns/utils/editSubformTableColumnsUtils.ts 95.45% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14318   +/-   ##
=======================================
  Coverage   95.66%   95.66%           
=======================================
  Files        1879     1880    +1     
  Lines       24405    24446   +41     
  Branches     2807     2810    +3     
=======================================
+ Hits        23346    23386   +40     
- Misses        799      800    +1     
  Partials      260      260           

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

@lassopicasso lassopicasso marked this pull request as ready for review December 19, 2024 15:16
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! I tested it locally to see how it works and noticed a little issue:
In edit mode, when we delete the column, the text resource of the component is also deleted:

deleted-text-resource.mov

Copy link
Contributor

coderabbitai bot commented Jan 13, 2025

📝 Walkthrough

Walkthrough

This pull request introduces enhancements to the subform table columns configuration in the UX editor. The changes primarily involve updating language resources, modifying component props from layoutSetName to subformLayout, and adding new utility functions for managing subform table components. The modifications span multiple files across the frontend packages, focusing on improving the user interface for editing subform table column properties and their associated text resources.

Changes

File Change Summary
frontend/language/src/nb.json Added Norwegian language keys for subform table column configuration
frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/... Renamed layoutSetName prop to subformLayout across multiple components
frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/ColumnElement/EditColumnElementContent.tsx New component for editing column titles and displaying cell content
frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/ColumnElement/EditColumnElementContent.module.css Added new CSS classes for component styling
frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/utils/editSubformTableColumnsUtils.ts Added utility functions for managing subform table components and titles

Possibly related PRs

Suggested labels

area/text-editor, area/dashboard, area/content-library, quality/testing, skip-documentation, added-to-sprint

Suggested reviewers

  • ErlingHauan
  • TomasEng
  • Konrad-Simso

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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

🔭 Outside diff range comments (1)
frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/ColumnElement/ColumnElement.test.tsx (1)

Line range hint 42-84: Add test cases for error scenarios

The test suite should include cases for:

  • Failed text resource mutations
  • Missing text resources
  • Network errors
♻️ Duplicate comments (1)
frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/utils/editSubformTableColumnsUtils.ts (1)

47-50: 🛠️ Refactor suggestion

Enhance uniqueness of generated title IDs

As noted in a previous review, there's a risk of key collisions. Consider incorporating additional uniqueness factors.

 export const getTitleIdForColumn = (titleId: string): string => {
   const prefixTitleId = 'subform_table_column_title_';
-  return titleId.startsWith(prefixTitleId) ? titleId : prefixTitleId + getRandNumber();
+  return titleId.startsWith(prefixTitleId) 
+    ? titleId 
+    : `${prefixTitleId}${Date.now()}_${getRandNumber()}`;
 };
🧹 Nitpick comments (7)
frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/ColumnElement/EditColumnElement/EditColumnElementContent.tsx (2)

26-33: Add aria-label to improve accessibility

The StudioTextfield should have an aria-label for better screen reader support.

 <StudioTextfield
   label={t('ux_editor.properties_panel.subform_table_columns.column_title_edit')}
   size='sm'
   value={title}
   autoFocus={true}
+  aria-label={t('ux_editor.properties_panel.subform_table_columns.column_title_edit')}
   onChange={(e) => setTitle(e.target.value)}
   error={!title?.trim() && errorMessage}
 />

30-32: Consider debouncing the onChange handler

For better performance, consider debouncing the onChange handler to reduce the number of state updates when typing.

+import { debounce } from 'lodash';
+
+const debouncedSetTitle = debounce((value: string) => setTitle(value), 300);
+
 <StudioTextfield
   // ...other props
-  onChange={(e) => setTitle(e.target.value)}
+  onChange={(e) => debouncedSetTitle(e.target.value)}
   // ...other props
 />
frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/ColumnElement/ColumnElement.tsx (1)

Line range hint 41-48: Handle cleanup when unmounting during edit mode

When the component unmounts while in edit mode, we should ensure proper cleanup to prevent any potential memory leaks or unexpected behavior.

+import { useEffect } from 'react';

+useEffect(() => {
+  return () => {
+    if (editing) {
+      onEdit(tableColumn);
+    }
+  };
+}, [editing, onEdit, tableColumn]);
frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/EditSubformTableColumns.tsx (1)

Line range hint 64-71: Add error boundary for column rendering

Consider wrapping the ColumnElement rendering in an error boundary to gracefully handle any rendering errors.

+import { ErrorBoundary } from 'react-error-boundary';

+const ColumnElementErrorFallback = ({ error, resetErrorBoundary }) => (
+  <div>
+    {t('ux_editor.properties_panel.subform_table_columns.error_rendering_column')}
+    <button onClick={resetErrorBoundary}>Try again</button>
+  </div>
+);

 {tableColumns.map((tableColumn: TableColumn, index: number) => (
+  <ErrorBoundary
+    FallbackComponent={ColumnElementErrorFallback}
+    onReset={() => {
+      // Reset the error state
+    }}
+  >
     <ColumnElement
       subformLayout={component.layoutSet}
       key={getUniqueKey(index)}
       // ... other props
     />
+  </ErrorBoundary>
 ))}
frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/utils/editSubformTableColumnsUtils.test.ts (2)

30-52: Consider extracting mock data to a separate file

The formLayouts mock data structure is quite complex and could be reused across other test files. Consider moving it to a shared mock file to improve maintainability.


149-159: Add edge case test for getTitleIdForColumn

While basic functionality is covered, consider adding a test case for empty string input to ensure robust error handling.

frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/EditSubformTableColumns.test.tsx (1)

94-94: Add comment explaining the title format requirement

The assertion checks for 'subform_table_column_title_' prefix, but it's not immediately clear why this format is required. Consider adding a comment explaining the business rule.

+    // Column titles must follow the format 'subform_table_column_title_<number>' for proper text resource management
     expect(columnTitleKey).toEqual(expect.stringContaining('subform_table_column_title_'));
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between aa46b72 and 17b7c05.

📒 Files selected for processing (10)
  • frontend/language/src/nb.json (1 hunks)
  • frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/ColumnElement/ColumnElement.test.tsx (3 hunks)
  • frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/ColumnElement/ColumnElement.tsx (3 hunks)
  • frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/ColumnElement/EditColumnElement/EditColumnElement.tsx (2 hunks)
  • frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/ColumnElement/EditColumnElement/EditColumnElementContent.module.css (1 hunks)
  • frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/ColumnElement/EditColumnElement/EditColumnElementContent.tsx (1 hunks)
  • frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/EditSubformTableColumns.test.tsx (1 hunks)
  • frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/EditSubformTableColumns.tsx (1 hunks)
  • frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/utils/editSubformTableColumnsUtils.test.ts (3 hunks)
  • frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/utils/editSubformTableColumnsUtils.ts (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/ColumnElement/EditColumnElement/EditColumnElementContent.module.css
⏰ 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/Properties/EditSubformTableColumns/utils/editSubformTableColumnsUtils.test.ts (1)

123-147: LGTM! Comprehensive test coverage for component filtering

The test cases effectively verify both successful filtering and empty result scenarios for getComponentsForSubformTable.

frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/ColumnElement/EditColumnElement/EditColumnElement.tsx (2)

79-80: LGTM! Good validation for save button

The save button disable logic effectively prevents invalid states.


46-48: Consider adding error handling for missing text resources

The getValueOfTitleId call could potentially return undefined if text resources are not loaded. Consider adding a fallback value or loading state.

frontend/language/src/nb.json (1)

1839-1843: LGTM! The translations are well-structured and consistent.

The added Norwegian translations for subform table column configurations align well with the PR objectives and maintain consistency with existing translations.

Let's verify the consistency of these translations with other related keys:

✅ Verification successful

Translations are consistent and complete

The new translations follow the established patterns in terms of:

  • Key naming convention
  • Norwegian terminology for columns ("kolonne")
  • Label formatting and punctuation
  • Error message style
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any inconsistencies in translation keys related to subform table columns
# Look for related translation keys to ensure naming consistency
rg -A 2 "subform_table_columns" frontend/language/src/

Length of output: 2186

@lassopicasso lassopicasso requested a review from mlqn January 14, 2025 08:51
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! 🚀

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/Properties/EditSubformTableColumns/utils/editSubformTableColumnsUtils.ts (3)

27-38: Enhance type safety and add JSDoc documentation.

While the implementation is good, we can improve it further:

+/**
+ * Retrieves all form components that have both a title and a simple binding
+ * @param formLayouts - The form layouts to extract components from
+ * @returns Array of form items that match the criteria
+ */
 export const getComponentsForSubformTable = (formLayouts: IFormLayouts): FormItem[] => {
-  const components = Object.values(formLayouts ?? {}).flatMap((layout: IInternalLayout) =>
+  const components = Object.values(formLayouts ?? {}).flatMap((layout) =>
     getAllLayoutComponents(layout),
   );
   return componentsWithLabelAndDataModel(components);
 };

+/**
+ * Filters components that have both a title text resource binding and a simple data model binding
+ */
 const componentsWithLabelAndDataModel = (components: FormItem[]): FormItem[] => {

40-42: Add error handling for missing text resources.

The function should handle cases where the text resource or value is not found.

 export const getValueOfTitleId = (titleId: string, textResources: ITextResources): string => {
-  return textResourceByLanguageAndIdSelector('nb', titleId)(textResources)?.value;
+  const value = textResourceByLanguageAndIdSelector('nb', titleId)(textResources)?.value;
+  if (!value) {
+    console.warn(`Text resource not found for titleId: ${titleId}`);
+  }
+  return value ?? '';
 };

50-70: Add safety check for infinite loop scenario.

While the implementation correctly uses subformId and ensures uniqueness, the while loop could potentially run indefinitely in an edge case where all possible IDs are taken.

 export const getTitleIdForColumn = ({
   titleId,
   subformId,
   textResources,
 }: TitleIdForColumn): string => {
   const prefixTitleId = 'subform_table_column_title_';
+  const MAX_ATTEMPTS = 1000; // Prevent infinite loop
+  let attempts = 0;

   if (titleId.startsWith(prefixTitleId)) {
     return titleId;
   }

   const resourcesArray = Object.values(textResources).flat();
   const isUnique = (id: string): boolean => !resourcesArray.some((resource) => resource.id === id);

   let uniqueTitleId = prefixTitleId + subformId;
-  while (!isUnique(uniqueTitleId)) {
+  while (!isUnique(uniqueTitleId) && attempts < MAX_ATTEMPTS) {
     uniqueTitleId = prefixTitleId + subformId + getRandNumber();
+    attempts++;
   }
+  
+  if (attempts === MAX_ATTEMPTS) {
+    throw new Error('Failed to generate unique title ID after maximum attempts');
+  }

   return uniqueTitleId;
 };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 010b76f and 403ce43.

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

4-8: LGTM! Well-organized imports.

The new imports are properly organized and typed, providing clear dependencies for the added functionality.

Copy link
Contributor

@JamalAlabdullah JamalAlabdullah left a comment

Choose a reason for hiding this comment

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

Tested ok in dev

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-releasenotes Issues that do not make sense to list in our release notes solution/studio/designer Issues related to the Altinn Studio Designer solution.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

UX: Manual editing of the fields in Table columns config (subform)
3 participants