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: Add text resources to app content library #14722

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

TomasEng
Copy link
Contributor

@TomasEng TomasEng commented Feb 19, 2025

Description

This pull request adds text resources and text resource mutations to AppContentLibrary and applies them to the code list editor.

This pull request might look quite large, but test data alone accounts for more than 150 of the added lines.

image

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)

Summary by CodeRabbit

  • New Features

    • The content library now offers enhanced support for localized text resources alongside existing content. Users will experience improved display and seamless updating of text elements for a more robust and intuitive interface.
    • New option lists have been added, providing users with additional items and descriptions for better content selection.
  • Bug Fixes

    • Improvements in test coverage ensure more reliable functionality and handling of loading states and error messages.

Copy link
Contributor

coderabbitai bot commented Feb 19, 2025

📝 Walkthrough

Walkthrough

This PR updates the AppContentLibrary feature to incorporate enhanced support for text resources. Changes include the introduction of new type definitions, query and mutation hooks for text resources, updated component and test implementations, and modifications to data setups. Tests are refactored to use a consolidated rendering function and additional scenarios validate text resource handling. Utility functions for converting text resources to mutation arguments and associated tests are also added.

Changes

File(s) Change Summary
frontend/app-development/features/appContentLibrary/AppContentLibrary.test.tsx Updated test cases for the AppContentLibrary component; added new type imports and text resource test data, refactored rendering with renderAppContentLibraryWithData, and renamed the query client creation function.
frontend/app-development/features/appContentLibrary/AppContentLibrary.tsx Enhanced component functionality to handle text resources; integrated useTextResourcesQuery and useUpsertTextResourceMutation, updated prop types, and linked the new onUpdateTextResource handler.
frontend/app-development/features/appContentLibrary/test-data/optionListDataList.ts Introduced new option list constants and the exported aggregated optionListDataList with updated structure.
frontend/app-development/features/appContentLibrary/test-data/textResources.ts Added numerous text resource identifiers and localized strings for Norwegian and English; exported structured text resources for localization.
frontend/app-development/features/appContentLibrary/utils/convertTextResourceToMutationArgs.* Added a utility function to convert text resource objects for mutation operations along with corresponding unit tests.

Possibly related PRs

Suggested labels

skip-manual-testing

Suggested reviewers

  • github-actions
  • mlqn
✨ 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.

@github-actions github-actions bot added solution/studio/designer Issues related to the Altinn Studio Designer solution. frontend labels Feb 19, 2025
Copy link

codecov bot commented Feb 19, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 95.77%. Comparing base (0df8045) to head (acbcaf0).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14722   +/-   ##
=======================================
  Coverage   95.76%   95.77%           
=======================================
  Files        1916     1919    +3     
  Lines       24988    25043   +55     
  Branches     2859     2859           
=======================================
+ Hits        23930    23985   +55     
  Misses        799      799           
  Partials      259      259           

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

@TomasEng TomasEng force-pushed the add-text-resources-to-app-content-library branch from 2e51047 to 69e3490 Compare February 19, 2025 11:56
@TomasEng TomasEng force-pushed the add-text-resources-to-app-content-library branch from 69e3490 to 15368c3 Compare February 19, 2025 12:07
@TomasEng TomasEng added team/studio-domain1 area/content-library Area: Related to library for shared resources skip-documentation Issues where updating documentation is not relevant skip-releasenotes Issues that do not make sense to list in our release notes labels Feb 19, 2025
@TomasEng TomasEng marked this pull request as ready for review February 19, 2025 12:41
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 (8)
frontend/app-development/features/appContentLibrary/utils/convertTextResourceToMutationArgs.test.ts (1)

4-14: Consider adding more test cases for better coverage.

While the happy path is well tested, consider adding test cases for:

  • Empty string values
  • Missing optional fields
  • Validation of required fields
frontend/app-development/features/appContentLibrary/test-data/optionListDataList.ts (2)

52-55: Fix inconsistent naming.

The variable name codeList2Data is inconsistent with the pattern used in optionList1Data. Consider renaming to maintain consistency:

-export const codeList2Data: OptionListData = {
+export const optionList2Data: OptionListData = {
   title: optionList2Name,
   data: optionList2,
 };

15-34: Add type annotations for intermediate constants.

Consider adding explicit type annotations for the intermediate constants:

-const optionList1: OptionList = [
+const optionList1: OptionList = [

-const optionList2: OptionList = [
+const optionList2: OptionList = [

Also applies to: 41-50

frontend/app-development/features/appContentLibrary/test-data/textResources.ts (2)

3-38: Consider using a more maintainable data structure.

The current implementation has a large number of individual constants. Consider using a more structured approach:

-const label1Id = 'label1';
-const description1Id = 'description1';
// ... more constants ...

+const resourceIds = {
+  labels: {
+    label1: 'label1',
+    label2: 'label2',
+    label3: 'label3',
+    label4: 'label4',
+  },
+  descriptions: {
+    description1: 'description1',
+    // ... more descriptions
+  },
+  helpTexts: {
+    helpText1: 'helpText1',
+    // ... more help texts
+  },
+} as const;

40-63: Simplify resource creation using a factory function.

The creation of text resources follows a repetitive pattern. Consider using a factory function:

const createTextResource = (id: string, value: string): ITextResource => ({ id, value });

export const resources = {
  nb: {
    labels: {
      label1: createTextResource(resourceIds.labels.label1, 'Ledetekst 1'),
      // ... more labels
    },
    // ... more categories
  },
  en: {
    // ... similar structure for English
  },
} as const;
frontend/app-development/features/appContentLibrary/AppContentLibrary.tsx (2)

38-71: Consider adding error handling for text resources query.

While the implementation looks good, consider adding specific error handling for text resources query failures to provide more detailed feedback to users.

 switch (status) {
   case 'pending':
     return <StudioPageSpinner spinnerTitle={t('general.loading')} />;
   case 'error':
-    return <StudioPageError message={t('app_content_library.fetch_error')} />;
+    const errorMessage = textResourcesStatus === 'error'
+      ? t('app_content_library.text_resources_fetch_error')
+      : t('app_content_library.fetch_error');
+    return <StudioPageError message={errorMessage} />;
   case 'success':
     return (

111-135: Consider adding loading state for mutation operations.

While the implementation is correct, consider adding loading states during text resource updates to provide better user feedback.

 const handleUpdateTextResource = useCallback(
   (textResourceWithLanguage: TextResourceWithLanguage): void => {
+    toast.info(t('app_content_library.updating_text_resource'));
     const mutationArgs = convertTextResourceToMutationArgs(textResourceWithLanguage);
-    updateTextResource(mutationArgs);
+    updateTextResource(mutationArgs, {
+      onSuccess: () => toast.success(t('app_content_library.text_resource_updated')),
+      onError: () => toast.error(t('app_content_library.text_resource_update_failed')),
+    });
   },
   [updateTextResource],
 );
frontend/app-development/features/appContentLibrary/AppContentLibrary.test.tsx (1)

148-167: Consider adding error case test for text resource updates.

While the success case is well tested, consider adding a test for the error case to ensure proper error handling.

it('Handles errors when updating text resources', async () => {
  const upsertTextResources = jest.fn().mockRejectedValue(new Error('Update failed'));
  const language = 'nb';
  const textResource = label1ResourceNb;
  const textResourceWithLanguage: TextResourceWithLanguage = { language, textResource };
  renderAppContentLibraryWithData({ queries: { upsertTextResources } });

  retrieveConfig().codeList.props.onUpdateTextResource(textResourceWithLanguage);
  await waitFor(expect(upsertTextResources).toHaveBeenCalled);

  expect(upsertTextResources).toHaveBeenCalledTimes(1);
  // Add expectations for error handling once implemented
});
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f2104d9 and 15368c3.

📒 Files selected for processing (6)
  • frontend/app-development/features/appContentLibrary/AppContentLibrary.test.tsx (7 hunks)
  • frontend/app-development/features/appContentLibrary/AppContentLibrary.tsx (7 hunks)
  • frontend/app-development/features/appContentLibrary/test-data/optionListDataList.ts (1 hunks)
  • frontend/app-development/features/appContentLibrary/test-data/textResources.ts (1 hunks)
  • frontend/app-development/features/appContentLibrary/utils/convertTextResourceToMutationArgs.test.ts (1 hunks)
  • frontend/app-development/features/appContentLibrary/utils/convertTextResourceToMutationArgs.ts (1 hunks)
🔇 Additional comments (8)
frontend/app-development/features/appContentLibrary/utils/convertTextResourceToMutationArgs.ts (1)

4-13: LGTM! Clean and well-typed implementation.

The function effectively maps text resource data to mutation arguments with proper TypeScript types.

frontend/app-development/features/appContentLibrary/test-data/optionListDataList.ts (1)

15-39: LGTM! Well-structured test data.

Good separation of concerns and clear organization of option list data.

frontend/app-development/features/appContentLibrary/test-data/textResources.ts (1)

65-93: LGTM! Well-organized language-specific arrays.

The organization of resources into language-specific arrays is clean and maintainable.

frontend/app-development/features/appContentLibrary/AppContentLibrary.tsx (2)

1-37: LGTM! Clean and well-organized imports.

The imports are logically grouped and the new text resource related imports are correctly placed.


103-109: LGTM! Well-implemented text resource update handler.

The handleUpdateTextResource callback is correctly memoized with useCallback and has proper dependency tracking.

frontend/app-development/features/appContentLibrary/AppContentLibrary.test.tsx (3)

37-40: LGTM! Clear and simple mock implementation.

The mock implementation is straightforward and uses a testid for easy querying.


71-75: LGTM! Good test coverage for text resources.

The test verifies that text resources are correctly passed to the component.


189-195: LGTM! Well-structured test data setup.

The createQueryClientWithData function properly initializes all required query data.

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 (6)
frontend/app-development/features/appContentLibrary/test-data/optionListDataList.ts (3)

15-39: Add JSDoc documentation for better maintainability.

Consider adding JSDoc documentation to describe the purpose and structure of the option list data. This will improve maintainability and help other developers understand the test data's purpose.

+/**
+ * Test data for the first option list.
+ * Contains three items with full text resource references (label, description, and help text).
+ */
 const optionList1: OptionList = [

41-55: Document the intentional differences between option lists.

The second option list has a different structure (missing description and helpText). If this is intentional for testing different scenarios, please document this.

+/**
+ * Test data for the second option list.
+ * Intentionally contains minimal item properties (only value and label)
+ * to test handling of incomplete option list items.
+ */
 const optionList2: OptionList = [

57-57: Add type annotation for better clarity.

Consider adding a type annotation to the exported array for better code clarity.

-export const optionListDataList = [optionList1Data, optionList2Data];
+export const optionListDataList: OptionListData[] = [optionList1Data, optionList2Data];
frontend/app-development/features/appContentLibrary/test-data/textResources.ts (3)

3-14: Consider grouping related constants using an object or enum.

The ID constants could be better organized to reduce repetition and improve maintainability.

Consider this alternative structure:

-const label1Id = 'label1';
-const description1Id = 'description1';
-const helpText1Id = 'helpText1';
-const label2Id = 'label2';
-const description2Id = 'description2';
-const helpText2Id = 'helpText2';
-const label3Id = 'label3';
-const description3Id = 'description3';
-const helpText3Id = 'helpText3';
-const label4Id = 'label4';
-const description4Id = 'description4';
-const helpText4Id = 'helpText4';
+const TEXT_RESOURCE_IDS = {
+  1: {
+    label: 'label1',
+    description: 'description1',
+    helpText: 'helpText1',
+  },
+  2: {
+    label: 'label2',
+    description: 'description2',
+    helpText: 'helpText2',
+  },
+  3: {
+    label: 'label3',
+    description: 'description3',
+    helpText: 'helpText3',
+  },
+  4: {
+    label: 'label4',
+    description: 'description4',
+    helpText: 'helpText4',
+  },
+} as const;

16-39: Consider using a factory function to generate text resources.

The current implementation is repetitive and could be simplified using a factory function approach.

Consider this alternative structure:

const createTextResource = (id: string, translations: { nb: string; en: string }): { nb: ITextResource; en: ITextResource } => ({
  nb: { id, value: translations.nb },
  en: { id, value: translations.en },
});

const resources = {
  label1: createTextResource('label1', { nb: 'Ledetekst 1', en: 'Label 1' }),
  description1: createTextResource('description1', { nb: 'Beskrivelse 1', en: 'Description 1' }),
  helpText1: createTextResource('helpText1', { nb: 'Hjelpetekst 1', en: 'Help text 1' }),
  // ... repeat for other resources
};

export const {
  label1: { nb: label1ResourceNb, en: label1ResourceEn },
  description1: { nb: description1ResourceNb, en: description1ResourceEn },
  // ... repeat for other exports
} = resources;

41-69: Consider adding validation for resource completeness.

The current implementation doesn't ensure that all required resources are present for each language.

Consider adding runtime validation:

const validateResources = (resources: ITextResource[], expectedIds: string[]) => {
  const missingIds = expectedIds.filter(id => !resources.find(r => r.id === id));
  if (missingIds.length > 0) {
    throw new Error(`Missing text resources for ids: ${missingIds.join(', ')}`);
  }
};

const expectedIds = [label1Id, description1Id, helpText1Id, /* ... */];
validateResources(textResourcesNb, expectedIds);
validateResources(textResourcesEn, expectedIds);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 15368c3 and 33d971d.

📒 Files selected for processing (2)
  • frontend/app-development/features/appContentLibrary/test-data/optionListDataList.ts (1 hunks)
  • frontend/app-development/features/appContentLibrary/test-data/textResources.ts (1 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/app-development/features/appContentLibrary/test-data/optionListDataList.ts (1)

1-14: LGTM! Well-organized imports.

The imports are properly organized and use TypeScript's recommended 'type' import syntax for type definitions.

frontend/app-development/features/appContentLibrary/test-data/textResources.ts (1)

71-74: LGTM!

The final export structure is clean and properly typed.

@wrt95 wrt95 self-assigned this Feb 20, 2025
Copy link
Contributor

@wrt95 wrt95 left a comment

Choose a reason for hiding this comment

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

🥳

@wrt95 wrt95 removed their assignment Feb 20, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area/content-library Area: Related to library for shared resources frontend skip-documentation Issues where updating documentation is not relevant 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. team/studio-domain1
Projects
Status: 🧪 Test
Development

Successfully merging this pull request may close these issues.

2 participants