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: Show warning when previewing a subform #14486

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

Conversation

Jondyr
Copy link
Member

@Jondyr Jondyr commented Jan 22, 2025

Description

image
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)

Documentation

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

Summary by CodeRabbit

Release Notes

  • New Features

    • Added warning for unsupported subform previews in the UI.
  • Bug Fixes

    • Improved error handling in layout set retrieval to prevent potential runtime errors.
  • Localization

    • Added Norwegian translation for subform preview warning.

These updates enhance user communication regarding layout compatibility and improve the overall stability of the application.

@Jondyr Jondyr added text/content used for issues that need som text improvements, often by ux team/studio-domain2 labels Jan 22, 2025
@Jondyr Jondyr requested a review from Ildest January 22, 2025 11:41
Copy link
Contributor

coderabbitai bot commented Jan 22, 2025

📝 Walkthrough

Walkthrough

This pull request introduces changes to handle unsupported subform previews across multiple frontend components. Modifications include the addition of a StudioAlert component for displaying warnings in the LandingPage and Preview components, an update to the Norwegian language translations for unsupported subform previews, and the implementation of optional chaining in a hook to enhance error handling. The primary goal is to provide clear user feedback when attempting to preview subforms that are not yet fully supported in the application.

Changes

File Change Summary
frontend/app-preview/src/views/LandingPage.tsx Added StudioAlert import and conditional rendering for subform warning
frontend/language/src/nb.json Added Norwegian translation for subform preview unsupported warning
frontend/packages/ux-editor/src/components/Preview/Preview.tsx Integrated useGetLayoutSetByName hook and added StudioAlert for subform warning
frontend/packages/ux-editor/src/hooks/useGetLayoutSetByName.ts Implemented optional chaining in hook return statement
frontend/packages/ux-editor/src/components/Preview/Preview.test.tsx Added test for warning message when subform layout is unsupported
frontend/app-preview/src/views/LandingPage.test.tsx Updated import statement to type-only and added test for subform warning message

Possibly related PRs

Suggested labels

quality/testing, skip-releasenotes, team/studio-domain1, skip-documentation

Suggested reviewers

  • mlqn
  • 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 linked an issue Jan 22, 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. area/app-preview Area: Related to test and preview of apps that are developed in Altinn Studio. solution/studio/designer Issues related to the Altinn Studio Designer solution. frontend labels Jan 22, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
frontend/packages/ux-editor/src/hooks/useGetLayoutSetByName.ts (1)

16-16: LGTM! Consider adding type assertion for better type safety.

The optional chaining operator improves error handling. For additional type safety, consider adding a non-null assertion for the sets property since it's guaranteed by the API type.

-  return layoutSetsResponse?.sets.find((set) => set.id === name);
+  return layoutSetsResponse?.sets!.find((set) => set.id === name);
frontend/packages/ux-editor/src/components/Preview/Preview.tsx (1)

6-6: Consider organizing imports by category.

Group related imports together for better maintainability:

  • React and hooks
  • Components
  • Types
  • Utilities
import React, { useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import cn from 'classnames';
+
+import { useAppContext, useGetLayoutSetByName } from '../../hooks';
+import { useChecksum } from '../../hooks/useChecksum.ts';
+import { useStudioEnvironmentParams } from 'app-shared/hooks/useStudioEnvironmentParams';
+import { useSelectedTaskId } from 'app-shared/hooks/useSelectedTaskId';
+import { useCreatePreviewInstanceMutation } from 'app-shared/hooks/mutations/useCreatePreviewInstanceMutation';
+import { useUserQuery } from 'app-shared/hooks/queries';
+
+import { Paragraph } from '@digdir/designsystemet-react';
+import {
+  StudioAlert,
+  StudioButton,
+  StudioCenter,
+  StudioErrorMessage,
+  StudioSpinner,
+} from '@studio/components';
+import { ShrinkIcon } from '@studio/icons';
+
+import type { SupportedView } from './ViewToggler/ViewToggler';
+import { ViewToggler } from './ViewToggler/ViewToggler';
+import { PreviewLimitationsInfo } from 'app-shared/components/PreviewLimitationsInfo/PreviewLimitationsInfo';
+
+import { previewPage } from 'app-shared/api/paths';
+import classes from './Preview.module.css';
-// Remove existing imports

Also applies to: 10-16

frontend/app-preview/src/views/LandingPage.tsx (1)

50-51: Consider extracting duplicated layout set detection logic into a shared hook.

The layout set detection logic is duplicated between LandingPage and Preview components. Consider creating a shared hook:

// hooks/useIsSubform.ts
export const useIsSubform = (layoutSetName: string) => {
  const { org, app } = useStudioEnvironmentParams();
  const { data: layoutSets } = useLayoutSetsQuery(org, app);
  const currentLayoutSet = layoutSets?.sets?.find((set) => set.id === layoutSetName);
  return currentLayoutSet?.type === 'subform';
};

Then use it in both components:

const isSubform = useIsSubform(selectedFormLayoutSetName);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3d752ba and 3481562.

📒 Files selected for processing (4)
  • frontend/app-preview/src/views/LandingPage.tsx (3 hunks)
  • frontend/language/src/nb.json (1 hunks)
  • frontend/packages/ux-editor/src/components/Preview/Preview.tsx (3 hunks)
  • frontend/packages/ux-editor/src/hooks/useGetLayoutSetByName.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • frontend/language/src/nb.json
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build environment and run e2e test
  • GitHub Check: Testing
🔇 Additional comments (4)
frontend/packages/ux-editor/src/components/Preview/Preview.tsx (2)

107-108: LGTM! Layout set detection is implemented correctly.

The implementation properly uses the hook to detect subform layouts, maintaining consistency with the LandingPage component.


143-147: LGTM! Warning alert implementation is clean and user-friendly.

The warning alert is properly placed and uses translations for internationalization support.

frontend/app-preview/src/views/LandingPage.tsx (2)

11-16: Consider organizing imports by category.

Similar to Preview.tsx, group related imports together for better maintainability.


101-105: LGTM! Warning alert implementation maintains consistency.

The warning alert implementation is consistent with the Preview component and properly placed within the header.

Copy link

codecov bot commented Jan 22, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 95.69%. Comparing base (3d752ba) to head (169fce5).
Report is 3 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14486   +/-   ##
=======================================
  Coverage   95.68%   95.69%           
=======================================
  Files        1888     1888           
  Lines       24568    24574    +6     
  Branches     2820     2822    +2     
=======================================
+ Hits        23509    23515    +6     
  Misses        799      799           
  Partials      260      260           

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

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

137-145: Enhance test coverage and cleanup.

While the test correctly verifies the presence of the warning, consider these improvements:

  1. Use exact text matching instead of regex to ensure the precise warning message.
  2. Reset appContextMock.selectedFormLayoutSetName after the test to prevent side effects.
  3. Verify the warning's styling/type using the appropriate test-id or role.
   it('should show a warning that subform is unsupported in preview', async () => {
     appContextMock.selectedFormLayoutSetName = subformLayoutMock.layoutSetName;
     render();
     await waitForElementToBeRemoved(() =>
       screen.queryByTitle(textMock('preview.loading_preview_controller')),
     );
 
-    expect(screen.getByText(/ux_editor.preview.subform_unsupported_warning/i)).toBeInTheDocument();
+    const warning = screen.getByText(textMock('ux_editor.preview.subform_unsupported_warning'));
+    expect(warning).toBeInTheDocument();
+    expect(warning.closest('[role="alert"]')).toHaveClass('warning');
+  });
+
+  afterEach(() => {
+    appContextMock.selectedFormLayoutSetName = undefined;
   });

155-159: Improve mock implementation flexibility.

The current mock implementation is hardcoded to always return a subform type. Consider:

  1. Making the mock response configurable through options.
  2. Ensuring the mock response structure matches the actual API.
  3. Adding test cases for error scenarios.
       getLayoutSets: jest
         .fn()
-        .mockImplementation(() =>
-          Promise.resolve({ sets: [{ id: subformLayoutMock.layoutSetName, type: 'subform' }] }),
+        .mockImplementation(() => {
+          const layoutSet = options.layoutSet ?? {
+            id: subformLayoutMock.layoutSetName,
+            type: 'subform',
+            // Add other required fields to match API response
+          };
+          return Promise.resolve({ sets: [layoutSet] });
+        }),

Then add a test case for error handling:

it('should handle layout set fetch error gracefully', async () => {
  const errorMessage = 'Failed to fetch layout sets';
  render({
    queries: {
      getLayoutSets: jest.fn().mockRejectedValue(new Error(errorMessage))
    }
  });
  
  await waitForElementToBeRemoved(() =>
    screen.queryByTitle(textMock('preview.loading_preview_controller'))
  );
  
  expect(screen.getByText(textMock('ux_editor.preview.error'))).toBeInTheDocument();
});
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3481562 and 50d12bf.

📒 Files selected for processing (1)
  • frontend/packages/ux-editor/src/components/Preview/Preview.test.tsx (3 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 (1)
frontend/packages/ux-editor/src/components/Preview/Preview.test.tsx (1)

12-12: LGTM!

The import is correctly placed and properly utilized in the test implementation.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
frontend/app-preview/src/views/LandingPage.test.tsx (1)

93-105: Consider expanding test coverage.

The test effectively verifies the basic warning message display. Consider adding the following test scenarios:

  1. Verify iframe behavior when a subform is detected
  2. Test handling of multiple layout sets
  3. Verify the exact content and styling of the warning message

Example test case for iframe behavior:

it('should handle iframe correctly when previewing a subform', async () => {
  renderLandingPage({
    getLayoutSets: jest
      .fn()
      .mockImplementation(() => Promise.resolve({ sets: [{ id: '', type: 'subform' }] })),
  });

  await waitForElementToBeRemoved(screen.queryByTitle(textMock('preview.loading_page')));

  // Verify iframe presence/absence or any specific attributes
  const iframe = screen.queryByTitle(textMock('preview.title'));
  expect(iframe).toBeInTheDocument(); // or not.toBeInTheDocument() based on requirements
});
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 50d12bf and 169fce5.

📒 Files selected for processing (1)
  • frontend/app-preview/src/views/LandingPage.test.tsx (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 (1)
frontend/app-preview/src/views/LandingPage.test.tsx (1)

9-9: LGTM! Good TypeScript practice.

The change to a type-only import is appropriate since ServicesContextProps is only used as a type annotation in the test file.

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.

LGTM 🥳

Copy link
Contributor

@JamalAlabdullah JamalAlabdullah Jan 23, 2025

Choose a reason for hiding this comment

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

It works fine. As we discussed, the position of the warning message should be reviewed with the UX team. I believe we should consider changing the width of the warning message and possibly its placement as well. You can check how we used StudioPageError for reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area/app-preview Area: Related to test and preview of apps that are developed in Altinn Studio. 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 text/content used for issues that need som text improvements, often by ux
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Subform preview: show a temporary not-supported warning message
3 participants