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

chore(IDataModelBindings): Fix typing of data model bindings #14659

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

Conversation

lassopicasso
Copy link
Contributor

@lassopicasso lassopicasso commented Feb 13, 2025

Description

This PR fixes the type logic for the union type IDataModelBindings that contains old and new datamodel format (string and { dataType: string, field: string }. Also separate it more clearer to have a IDataModelBindingsKeyValue as well.

  • IDataModelBindings: is used for types with specific keys/props, such as address:
type DataModelBindingsForAddress = {
  address: IDataModelBindings;
  zipCode: IDataModelBindings;
  postPlace: IDataModelBindings;
  careOf?: IDataModelBindings;
  houseNumber?: IDataModelBindings;
};
  • IDataModelBindingsKeyValue: is used for more "generic/unknown" keys/props, such as DataModelBindingsForCustom:
Before:
type DataModelBindingsForCustom = {
  [id: string]: string;
};

After:
type DataModelBindingsForCustom = IDataModelBindingsKeyValue;
  • Also refactored convertDataBindingToInternalFormat with type guards so that the types is correctly. Before dataModelBindings always ended up as a string according to typescript.

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

  • Refactor
    • Enhanced the internal data binding structures to improve stability and reliability in form configuration.
    • Streamlined error handling and data conversion processes for consistent behavior across related features.
  • Tests
    • Updated test cases to align with the new binding logic, ensuring robust validation of form interactions.
  • Chore
    • Optimized internal utilities and standardized imports to improve overall maintainability and performance.

Copy link
Contributor

coderabbitai bot commented Feb 13, 2025

📝 Walkthrough

Walkthrough

This pull request refactors the data model binding types throughout the codebase. String-based definitions have been replaced with more structured types, such as IDataModelBindingsKeyValue and ExplicitDataModelBinding, across multiple modules. Components, tests, and utility functions have been updated to use these new types, with modifications to property declarations and conversion logic (via convertDataBindingToInternalFormat). The changes also include improved handling of undefined values and the removal of temporary type assertions, ensuring consistent and stricter type safety across component configurations.

Changes

File(s) Summary
frontend/.../ComponentSpecificConfig.ts, frontend/.../FormLayoutsResponse.ts, frontend/.../FormComponent.ts, frontend/.../FormContainer.ts, frontend/.../global.ts Updated type definitions and interfaces to replace string-based data bindings with structured types (IDataModelBindingsKeyValue, ExplicitDataModelBinding), redefining binding properties.
frontend/.../EditSubformTableColumns/..., frontend/.../EditDataModelBinding/... Modified component props and internal logic to utilize the new binding types; updated data access patterns with optional chaining and conversion functions.
frontend/.../EditColumnElement.test.tsx, frontend/.../useUpdateFormComponentMutation.test.ts Revised test cases to incorporate new binding conversion methods and to remove outdated type assertions.
frontend/.../dataModelUtils.ts, frontend/.../dataModelUtils.test.ts Refactored utility function convertDataBindingToInternalFormat to improve type safety, simplify parameter handling, and remove deprecated types.

Possibly related PRs

Suggested labels

quality/code, skip-manual-testing, skip-releasenotes

Suggested reviewers

  • mlqn
  • Jondyr
✨ 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 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 13, 2025
@lassopicasso lassopicasso changed the title Fix typing of data model bindings chore(dataModelBindings): Fix typing of data model bindings Feb 13, 2025
@lassopicasso lassopicasso changed the title chore(dataModelBindings): Fix typing of data model bindings chore(IDataModelBindings): Fix typing of data model bindings Feb 14, 2025
@lassopicasso lassopicasso marked this pull request as ready for review February 14, 2025 11:04
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/types/global.ts (1)

19-28: LGTM! Well-structured type definitions.

The new type definitions provide a clear separation between implicit and explicit bindings while maintaining backward compatibility. The union types are well-designed to handle both cases.

Consider adding JSDoc comments to document the purpose and usage of each type, especially explaining when to use ImplicitDataModelBinding vs ExplicitDataModelBinding. Example:

+/**
+ * Represents a simple string-based data model binding (legacy format)
+ */
 export type ImplicitDataModelBinding = string;
+
+/**
+ * Represents a structured data model binding with explicit dataType and field
+ */
 export type ExplicitDataModelBinding = {
   dataType: string;
   field: string;
 };
frontend/packages/ux-editor/src/components/config/editModal/EditDataModelBinding/EditBinding/SelectDataModelBinding.tsx (1)

35-41: Consider initializing field with null or undefined.

The empty string initialization for the field property might not accurately represent an unset state. Consider using null or undefined to be more explicit about the field not being selected yet.

 const handleDataModelChange = (newDataModel: string) => {
   const dataModelBinding = {
-    field: '',
+    field: undefined,
     dataType: newDataModel,
   };
   handleBindingChange(dataModelBinding);
 };
frontend/packages/ux-editor/src/components/config/editModal/EditDataModelBinding/EditBinding/SelectDataFieldBinding.tsx (1)

31-33: Add type guard for internalBindingFormat properties.

Consider adding type guards to ensure type safety when destructuring internalBindingFormat.

-  const { dataType: currentDataModel, field: currentDataModelField } = internalBindingFormat;
+  const currentDataModel = internalBindingFormat?.dataType ?? '';
+  const currentDataModelField = internalBindingFormat?.field ?? '';
frontend/packages/ux-editor/src/utils/dataModelUtils.ts (1)

105-114: Consider adding validation for empty strings.

While the conversion logic is correct, consider validating empty strings in the field and dataType properties.

 return {
-  field: binding || '',
+  field: binding && binding.trim() ? binding : '',
   dataType: '',
 };
frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/ColumnElement/EditColumnElement/EditColumnElement.test.tsx (1)

336-338: Consider using exact matching instead of RegExp.

Using RegExp for matching the field value might be fragile if the field contains special characters. Consider using exact matching:

-        name: new RegExp(postPlaceDataField),
+        name: postPlaceDataField,
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 502c440 and f6ad050.

📒 Files selected for processing (21)
  • frontend/packages/shared/src/types/ComponentSpecificConfig.ts (1 hunks)
  • frontend/packages/shared/src/types/api/FormLayoutsResponse.ts (2 hunks)
  • frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/ColumnElement/ColumnElement.test.tsx (2 hunks)
  • frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/ColumnElement/EditColumnElement/DataModelBindingsCombobox.tsx (2 hunks)
  • frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/ColumnElement/EditColumnElement/EditColumnElement.test.tsx (7 hunks)
  • frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/ColumnElement/EditColumnElement/EditColumnElement.tsx (3 hunks)
  • frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/utils/editSubformTableColumnsUtils.test.ts (1 hunks)
  • frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/utils/editSubformTableColumnsUtils.ts (1 hunks)
  • frontend/packages/ux-editor/src/components/config/editModal/EditDataModelBinding/DefinedBinding/DefinedBinding.tsx (1 hunks)
  • frontend/packages/ux-editor/src/components/config/editModal/EditDataModelBinding/EditBinding/EditBinding.test.tsx (2 hunks)
  • frontend/packages/ux-editor/src/components/config/editModal/EditDataModelBinding/EditBinding/EditBinding.tsx (2 hunks)
  • frontend/packages/ux-editor/src/components/config/editModal/EditDataModelBinding/EditBinding/EditBindingButtons.tsx (1 hunks)
  • frontend/packages/ux-editor/src/components/config/editModal/EditDataModelBinding/EditBinding/SelectDataFieldBinding.tsx (1 hunks)
  • frontend/packages/ux-editor/src/components/config/editModal/EditDataModelBinding/EditBinding/SelectDataModelBinding.tsx (1 hunks)
  • frontend/packages/ux-editor/src/components/config/editModal/EditDataModelBinding/EditDataModelBinding.tsx (1 hunks)
  • frontend/packages/ux-editor/src/hooks/mutations/useUpdateFormComponentMutation.test.ts (2 hunks)
  • frontend/packages/ux-editor/src/types/FormComponent.ts (2 hunks)
  • frontend/packages/ux-editor/src/types/FormContainer.ts (2 hunks)
  • frontend/packages/ux-editor/src/types/global.ts (1 hunks)
  • frontend/packages/ux-editor/src/utils/dataModelUtils.test.ts (1 hunks)
  • frontend/packages/ux-editor/src/utils/dataModelUtils.ts (2 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 (34)
frontend/packages/ux-editor/src/components/config/editModal/EditDataModelBinding/EditDataModelBinding.tsx (2)

28-28: LGTM!

The fallback logic for bindingKey is clear and appropriate.


29-31: LGTM! Improved type safety and specificity.

The changes correctly target a specific binding using bindingKey and safely handle undefined values through optional chaining. This aligns well with the PR's objective of improving type safety in data model bindings.

frontend/packages/shared/src/types/ComponentSpecificConfig.ts (9)

10-13: Good import for unified data model bindings.
By importing IDataModelBindings and IDataModelBindingsKeyValue from a single source, you ensure consistency across the codebase.


16-20: Consistent use of IDataModelBindings for address fields.
Switching to IDataModelBindings for each field clarifies the expected structure and enforces type safety.


23-23: Adopting IDataModelBindingsKeyValue for custom bindings.
This is a logical approach for flexible data fields, providing a more structured type than plain strings.


26-26: Refining group field to IDataModelBindings.
Using IDataModelBindings for the group property further aligns it with the new typed approach.


29-29: Aligning list bindings with IDataModelBindingsKeyValue.
This update provides clarity for list-based data structures while maintaining flexibility.


32-33: Likert fields switching to IDataModelBindings.
Defining both answer and questions as IDataModelBindings is consistent and ensures a uniform contract.


37-37: Applying IDataModelBindings for list usage.
This maintains a standardized approach for handling data model bindings across similar components.


41-42: Added typed metadata in DataModelBindingsOptionsSimple.
Including an optional metadata field typed as IDataModelBindings provides structured extensibility.


46-46: Simplifying DataModelBindingsSimple with typed field.
Converting simpleBinding to IDataModelBindings promotes consistency with other binding structures.

frontend/packages/ux-editor/src/types/FormContainer.ts (2)

1-1: New import aligns with key-value style bindings.
Importing IDataModelBindingsKeyValue sets the stage for more structured container references.


13-13: Using IDataModelBindingsKeyValue in the container base.
Replacing the old approach with dataModelBindings?: IDataModelBindingsKeyValue ensures typed mappings at the container level.

frontend/packages/shared/src/types/api/FormLayoutsResponse.ts (2)

5-5: Introducing IDataModelBindingsKeyValue import.
Pulling in the new type underlines the shift from string-based definitions to robust key-value mappings.


24-24: Switching external components to IDataModelBindingsKeyValue.
Replacing KeyValuePairs<string> ensures a clearer and more enforceable structure for external layout bindings.

frontend/packages/ux-editor/src/components/config/editModal/EditDataModelBinding/EditBinding/EditBindingButtons.tsx (1)

6-6:

❓ Verification inconclusive

LGTM! Type changes align with the PR objectives.

The change from InternalBindingFormat to ExplicitDataModelBinding improves type safety and clarity.

Let's verify that all usages of handleBindingChange are updated consistently:

Also applies to: 9-9


🏁 Script executed:

#!/bin/bash
# Search for handleBindingChange function calls
ast-grep --pattern 'handleBindingChange($$$)'

Length of output: 762


Action Required: Verify Consistency of handleBindingChange Usage

LGTM overall—the change from InternalBindingFormat to ExplicitDataModelBinding improves type safety and clarity as intended. Our search confirms that in the config edit modal components (in EditBindingButtons.tsx, SelectDataFieldBinding.tsx, and SelectDataModelBinding.tsx), the updated single-parameter usage (or undefined for deletion) is applied correctly.

However, note that in
frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/ColumnElement/EditColumnElement/EditColumnElement.tsx
the function is invoked with two arguments. Please verify that this dual-parameter call is meant to use an overloaded version (or remains unaffected by this PR’s type change) so that it doesn’t conflict with the updated signature.

frontend/packages/ux-editor/src/components/config/editModal/EditDataModelBinding/DefinedBinding/DefinedBinding.tsx (1)

12-12: LGTM! Type changes maintain consistency.

The change to ExplicitDataModelBinding aligns with the type system improvements and maintains type safety when destructuring field and dataType.

Also applies to: 17-17

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

4-4: LGTM! Type change improves specificity.

The change to IDataModelBindingsKeyValue better represents the key-value structure of the bindings.

Also applies to: 9-9

frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/utils/editSubformTableColumnsUtils.ts (1)

44-44: LGTM! Improved null safety with optional chaining.

The addition of optional chaining when accessing dataModelBindings[binding] prevents potential runtime errors.

frontend/packages/ux-editor/src/types/FormComponent.ts (1)

2-2: LGTM! Type update aligns with new binding system.

The change from IDataModelBindings to IDataModelBindingsKeyValue in FormComponentBase interface correctly implements the new typing system while maintaining backward compatibility.

Also applies to: 17-17

frontend/packages/ux-editor/src/components/config/editModal/EditDataModelBinding/EditBinding/SelectDataFieldBinding.tsx (1)

42-48: LGTM! Proper handling of field updates.

The handleDataModelFieldChange function correctly maintains the data model binding structure when updating fields.

frontend/packages/ux-editor/src/components/config/editModal/EditDataModelBinding/EditBinding/EditBinding.tsx (1)

19-19: LGTM! Type safety improvements look good.

The changes enhance type safety by:

  1. Using ExplicitDataModelBinding instead of InternalBindingFormat
  2. Consistently applying the type across props and handlers

Also applies to: 27-27, 44-44

frontend/packages/ux-editor/src/utils/dataModelUtils.ts (1)

100-103: LGTM! Well-implemented type guard.

The type guard correctly checks for both dataType and field properties, ensuring type safety.

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

14-14: LGTM! Test updates properly reflect the new typing system.

The changes correctly use the conversion function to handle data model bindings in tests.

Also applies to: 20-22, 54-54

frontend/packages/ux-editor/src/components/Properties/EditSubformTableColumns/utils/editSubformTableColumnsUtils.test.ts (1)

50-50: LGTM! Improved type safety by removing type assertion.

The change properly types the simpleBinding object without relying on type assertions.

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

24-24: LGTM! Type import aligns with PR objectives.

The change from IDataModelBindings to IDataModelBindingsKeyValue improves type safety by using a more specific type for key-value data model bindings.


58-60: LGTM! Safe handling of optional values.

The use of optional chaining (?.) in accessing dataModelBindings ensures safe handling of potentially undefined values.


69-73: LGTM! Consistent use of new binding format.

The handleBindingChange function correctly uses the new IDataModelBindingsKeyValue type and properly extracts the field using convertDataBindingToInternalFormat.

frontend/packages/ux-editor/src/hooks/mutations/useUpdateFormComponentMutation.test.ts (1)

19-19: LGTM! Test data updated to use new type.

The test data correctly uses the new IDataModelBindingsKeyValue type for data model bindings, maintaining consistency with the type system changes.

Also applies to: 33-35

frontend/packages/ux-editor/src/utils/dataModelUtils.test.ts (1)

158-160: LGTM! Comprehensive test coverage for binding format conversion.

The test cases thoroughly cover:

  1. Internal format preservation
  2. Old format conversion
  3. Undefined value handling

The changes improve type safety while maintaining backward compatibility.

Also applies to: 166-168, 173-174

frontend/packages/ux-editor/src/components/config/editModal/EditDataModelBinding/EditBinding/EditBinding.test.tsx (2)

15-16: LGTM! Appropriate type imports.

The imports correctly include both ExplicitDataModelBinding type and the convertDataBindingToInternalFormat utility function.


40-42: LGTM! State management updated for new binding format.

The component correctly:

  1. Uses ExplicitDataModelBinding for state type
  2. Utilizes convertDataBindingToInternalFormat for binding conversion
  3. Updates state with the extracted field value

Also applies to: 47-49, 52-52

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

13-13: LGTM! Well-structured data binding conversion.

The extraction of data fields using convertDataBindingToInternalFormat at the top level promotes reusability and aligns with the PR's goal of improving typing.

Also applies to: 27-32


138-138: LGTM! Consistent usage of converted data fields.

The test cases have been consistently updated to use the converted data fields while maintaining the original test behavior.

Also applies to: 164-164, 275-275, 313-313

Copy link

codecov bot commented Feb 14, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 95.76%. Comparing base (502c440) to head (f6ad050).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14659   +/-   ##
=======================================
  Coverage   95.76%   95.76%           
=======================================
  Files        1914     1914           
  Lines       24961    24961           
  Branches     2858     2858           
=======================================
  Hits        23904    23904           
  Misses        799      799           
  Partials      258      258           

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

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.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Ensure proper handling of both old (string) and new (object) formats in the global IDataModelBindings type
1 participant