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: 14277 studio pagination content #14278

Merged
merged 11 commits into from
Jan 19, 2025

Conversation

wrt95
Copy link
Contributor

@wrt95 wrt95 commented Dec 12, 2024

Description

Skjermopptak.2024-12-12.kl.18.02.09.mov

Related Issue(s)

  • #{issue number}

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

    • Introduced a new StudioPaginatedContent component with advanced pagination functionality.
    • Added support for dynamic page navigation with customizable content and validation rules.
    • Implemented a flexible pagination hook for managing multi-page interfaces.
  • Documentation

    • Added Storybook stories to demonstrate component usage and interactions.
    • Created comprehensive type definitions for pagination-related entities.
  • Tests

    • Developed unit tests for the pagination component and hook to ensure reliability and correct behavior.
    • Added tests for various scenarios in the usePagination hook.

@github-actions github-actions bot added solution/studio/designer Issues related to the Altinn Studio Designer solution. frontend labels Dec 12, 2024
@wrt95 wrt95 changed the title Chore 14277 studio pagination content chore: 14277 studio pagination content Dec 12, 2024
@wrt95 wrt95 marked this pull request as draft December 12, 2024 17:03
@wrt95 wrt95 linked an issue Dec 12, 2024 that may be closed by this pull request
Copy link

codecov bot commented Dec 12, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 95.66%. Comparing base (5dda0fd) to head (43b03e3).
Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14278   +/-   ##
=======================================
  Coverage   95.65%   95.66%           
=======================================
  Files        1889     1891    +2     
  Lines       24550    24581   +31     
  Branches     2817     2822    +5     
=======================================
+ Hits        23484    23515   +31     
  Misses        805      805           
  Partials      261      261           

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

@wrt95 wrt95 marked this pull request as ready for review December 20, 2024 11:02
@wrt95 wrt95 added the skip-manual-testing PRs that do not need to be tested manually label Dec 20, 2024
Copy link
Contributor

coderabbitai bot commented Jan 19, 2025

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

frontend/libs/studio-components/src/components/StudioPaginatedContent/StudioPaginatedContent.stories.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-storybook".

(The package "eslint-plugin-storybook" was not found when loaded as a Node module from the directory "/frontend/libs/studio-components".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-storybook@latest --save-dev

The plugin "eslint-plugin-storybook" was referenced from the config file in "frontend/libs/studio-components/.eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

📝 Walkthrough

Walkthrough

The pull request introduces a new StudioPaginatedContent component in the frontend library, which provides a comprehensive pagination solution. The implementation includes a React component, a custom pagination hook, type definitions, CSS styling, Storybook stories, and unit tests. The component allows for flexible page navigation with customizable content, validation rules, and visual indicators of current page status.

Changes

File Change Summary
frontend/libs/studio-components/src/components/StudioPaginatedContent/StudioPaginatedContent.module.css Added CSS classes for .wrapper, .buttonWrapper, .statusBarContainer, .statusBarPiece, .statusBarPiece.active, and .icon styling.
frontend/libs/studio-components/src/components/StudioPaginatedContent/StudioPaginatedContent.stories.tsx Created Storybook stories with dynamic content and user interaction, including components Children1, Children2, Children3, and Children4.
frontend/libs/studio-components/src/components/StudioPaginatedContent/StudioPaginatedContent.test.tsx Added comprehensive unit tests for component rendering and navigation functionality.
frontend/libs/studio-components/src/components/StudioPaginatedContent/StudioPaginatedContent.tsx Implemented main pagination component with props for navigation and rendering logic, including NavigationStepIndicator.
frontend/libs/studio-components/src/components/StudioPaginatedContent/hooks/usePagination.ts Created custom pagination hook for managing page state and navigation, including helper functions for validation and mapping items.
frontend/libs/studio-components/src/components/StudioPaginatedContent/types/StudioPaginatedItem.ts Added type definition for StudioPaginatedItem with properties for pageContent and optional validationRuleForNextButton.
frontend/libs/studio-components/src/components/StudioPaginatedContent/types/StudioPaginatedNavigation.ts Introduced type StudioPaginatedNavigation for managing pagination navigation options and methods.
frontend/libs/studio-components/src/components/StudioPaginatedContent/index.ts Exported StudioPaginatedContent component from the index file.

Possibly related PRs

Suggested labels

area/ui-editor, quality/testing, skip-releasenotes, skip-documentation, team/studio-domain1

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.

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

🧹 Nitpick comments (10)
frontend/libs/studio-components/src/components/StudioPaginatedContent/types/StudioPaginatedNavigation.ts (1)

1-6: Consider adding error handling to navigation callbacks

The navigation callbacks onNext and onPrevious could benefit from error handling by returning a Promise or Result type. This would allow handling edge cases where navigation fails (e.g., due to unsaved changes).

 export type StudioPaginatedNavigation = {
   canGoNext?: boolean;
   canGoPrevious?: boolean;
-  onNext: () => void;
-  onPrevious: () => void;
+  onNext: () => Promise<void>;
+  onPrevious: () => Promise<void>;
 };
frontend/libs/studio-components/src/components/StudioPaginatedContent/types/StudioPaginatedItem.ts (1)

3-6: Document default validation behavior

The validationRuleForNextButton is optional with an implicit default of true (as seen in usePagination.ts). Consider adding JSDoc comments to document this default behavior for better developer experience.

 export type StudioPaginatedItem = {
   pageContent: ReactNode;
+  /** 
+   * Optional validation rule for enabling the next button.
+   * @default true
+   */
   validationRuleForNextButton?: boolean;
 };
frontend/libs/studio-components/src/components/StudioPaginatedContent/hooks/usePagination.ts (1)

11-14: Optimize performance with useMemo

Consider memoizing validationRules and pages arrays to prevent unnecessary recalculations on re-renders.

+import { useMemo } from 'react';
 // ...
-  const validationRules: boolean[] = mapItemsToValidationRules(items);
-  const pages: ReactNode[] = mapItemsToPages(items);
+  const validationRules = useMemo(() => mapItemsToValidationRules(items), [items]);
+  const pages = useMemo(() => mapItemsToPages(items), [items]);
frontend/libs/studio-components/src/components/StudioPaginatedContent/StudioPaginatedContent.stories.tsx (2)

32-36: Consider adding argTypes for better story customization.

Adding argTypes would allow users to experiment with different props in Storybook. Consider adding controls for:

  • totalPages
  • buttonTexts
  • validationRules

38-72: Consider adding error handling for edge cases.

While the implementation works correctly, consider handling these edge cases:

  • Invalid input validation
  • Empty input state
  • Maximum input length
frontend/libs/studio-components/src/components/StudioPaginatedContent/StudioPaginatedContent.test.tsx (1)

26-37: Consider adding more comprehensive rendering tests.

While the basic tests are good, consider adding tests for:

  • Error states
  • Loading states
  • Empty states
frontend/libs/studio-components/src/components/StudioPaginatedContent/hooks/usePagination.test.tsx (2)

1-20: Consider adding edge case tests.

While the initial tests are good, consider adding tests for:

  • Empty items array
  • Single item array
  • Maximum page limit

55-80: Consider adding error scenario tests.

Add tests for error scenarios such as:

  • Navigation with invalid page numbers
  • Rapid navigation attempts
  • Navigation during state updates
frontend/libs/studio-components/src/components/StudioPaginatedContent/StudioPaginatedContent.module.css (2)

1-17: Consider adding responsive design styles.

The layout styles could benefit from responsive design considerations:

  • Media queries for different screen sizes
  • Flexible spacing using relative units
  • Mobile-first approach

19-34: Use CSS variables consistently for colors.

Replace hardcoded color value with a CSS variable for consistency:

-  background: #e0e0e0;
+  background: var(--fds-semantic-surface-neutral-default);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5dda0fd and ff6412f.

📒 Files selected for processing (9)
  • frontend/libs/studio-components/src/components/StudioPaginatedContent/StudioPaginatedContent.module.css (1 hunks)
  • frontend/libs/studio-components/src/components/StudioPaginatedContent/StudioPaginatedContent.stories.tsx (1 hunks)
  • frontend/libs/studio-components/src/components/StudioPaginatedContent/StudioPaginatedContent.test.tsx (1 hunks)
  • frontend/libs/studio-components/src/components/StudioPaginatedContent/StudioPaginatedContent.tsx (1 hunks)
  • frontend/libs/studio-components/src/components/StudioPaginatedContent/hooks/usePagination.test.tsx (1 hunks)
  • frontend/libs/studio-components/src/components/StudioPaginatedContent/hooks/usePagination.ts (1 hunks)
  • frontend/libs/studio-components/src/components/StudioPaginatedContent/index.ts (1 hunks)
  • frontend/libs/studio-components/src/components/StudioPaginatedContent/types/StudioPaginatedItem.ts (1 hunks)
  • frontend/libs/studio-components/src/components/StudioPaginatedContent/types/StudioPaginatedNavigation.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • frontend/libs/studio-components/src/components/StudioPaginatedContent/index.ts
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Typechecking and linting
  • GitHub Check: Build environment and run e2e test
  • GitHub Check: Testing
  • GitHub Check: CodeQL
🔇 Additional comments (7)
frontend/libs/studio-components/src/components/StudioPaginatedContent/StudioPaginatedContent.tsx (2)

45-62: Extract NavigationCircles to a separate file

Consider moving the NavigationCircles component to its own file for better code organization and maintainability. This aligns with the previous reviewer's suggestion to rename it to NavigationStepIndicator.

Additionally, enhance the accessibility by adding ARIA attributes for the progress indicator.

 const NavigationCircles = ({ totalPages, currentPageNumber }: NavigationCirclesProps) => {
   return (
-    <div className={classes.statusBarContainer}>
+    <div 
+      className={classes.statusBarContainer}
+      role="progressbar"
+      aria-valuemin={0}
+      aria-valuemax={totalPages - 1}
+      aria-valuenow={currentPageNumber}
+      aria-label={`Page ${currentPageNumber + 1} of ${totalPages}`}
+    >

7-10: Move ButtonTexts type to StudioPaginatedNavigation

Agree with the previous reviewer's suggestion to move ButtonTexts into StudioPaginatedNavigation type as it's closely related to navigation functionality.

frontend/libs/studio-components/src/components/StudioPaginatedContent/StudioPaginatedContent.stories.tsx (1)

1-28: LGTM! Well-structured story components.

The child components are well-organized with proper type definitions and clear validation logic.

frontend/libs/studio-components/src/components/StudioPaginatedContent/StudioPaginatedContent.test.tsx (3)

1-24: LGTM! Well-structured test setup.

The test setup with mocks and default props is clean and comprehensive.


71-82: Update to userEvent for better interaction testing.

As suggested in previous reviews, replace fireEvent with userEvent for more realistic user interaction testing.

-    fireEvent.click(screen.getByText('Previous'));
+    await userEvent.click(screen.getByText('Previous'));

93-95: LGTM! Well-implemented helper function.

The render helper function is clean and properly typed.

frontend/libs/studio-components/src/components/StudioPaginatedContent/hooks/usePagination.test.tsx (1)

21-53: LGTM! Comprehensive validation rule testing.

The tests thoroughly cover validation rules and state updates.

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/libs/studio-components/src/components/StudioPaginatedContent/StudioPaginatedContent.tsx (2)

45-65: Consider renaming and optimizing NavigationStepIndicator

  1. The component name could be more descriptive, e.g., NavigationStepIndicator.
  2. Consider memoizing the component to prevent unnecessary re-renders when parent updates.
-const NavigationStepIndicator = ({
+const NavigationStepIndicator = React.memo(({
   totalPages,
   currentPageNumber,
-}: NavigationCirclesProps): React.ReactElement => {
+}: NavigationCirclesProps): React.ReactElement => {
   return (
     <div className={classes.statusBarContainer}>
       {getArrayFromLength(totalPages).map((_, index) => (
         <div
           key={index}
           role='status'
           className={`${classes.statusBarPiece} ${index <= currentPageNumber ? classes.active : ''}`}
         />
       ))}
     </div>
   );
-};
+});

67-68: Consider moving utility function closer to usage

Since getArrayFromLength is only used within NavigationStepIndicator, consider moving it inside the component's scope for better code organization.

frontend/libs/studio-components/src/components/StudioPaginatedContent/StudioPaginatedContent.stories.tsx (2)

13-28: Consider more descriptive names for story components

The current names (Children1, Children2, etc.) are not descriptive of their purpose. Consider names that reflect their functionality, e.g., ValidationInputPage, InfoPage, etc.


32-36: Enhance story documentation with argTypes

Add documentation for component props using argTypes to improve the story's usefulness:

 const meta: Meta = {
   title: 'Components/StudioPaginatedContent',
   component: StudioPaginatedContent,
-  argTypes: {},
+  argTypes: {
+    totalPages: {
+      description: 'Total number of pages in the pagination',
+      control: 'number',
+    },
+    currentPageNumber: {
+      description: 'Current active page number (0-based index)',
+      control: 'number',
+    },
+    navigationButtonTexts: {
+      description: 'Custom texts for navigation buttons',
+    },
+  },
 };
frontend/libs/studio-components/src/components/StudioPaginatedContent/StudioPaginatedContent.test.tsx (1)

96-98: Consider adding cleanup to render helper

Add cleanup after each test to ensure a clean state:

 const renderStudioPaginatedContent = (props: Partial<StudioPaginatedContentProps> = {}) => {
-  return render(<StudioPaginatedContent {...defaultProps} {...props} />);
+  const result = render(<StudioPaginatedContent {...defaultProps} {...props} />);
+  return {
+    ...result,
+    cleanup: () => result.unmount(),
+  };
 };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ff6412f and 43b03e3.

📒 Files selected for processing (3)
  • frontend/libs/studio-components/src/components/StudioPaginatedContent/StudioPaginatedContent.stories.tsx (1 hunks)
  • frontend/libs/studio-components/src/components/StudioPaginatedContent/StudioPaginatedContent.test.tsx (1 hunks)
  • frontend/libs/studio-components/src/components/StudioPaginatedContent/StudioPaginatedContent.tsx (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: Testing
  • GitHub Check: Typechecking and linting
🔇 Additional comments (4)
frontend/libs/studio-components/src/components/StudioPaginatedContent/StudioPaginatedContent.tsx (2)

1-18: LGTM! Well-structured type definitions.

The type definitions are clear, comprehensive, and provide good type safety.


20-43: Enhance accessibility for navigation buttons

Add ARIA labels to navigation buttons to improve screen reader experience.

-        <StudioButton variant='tertiary' size='sm' onClick={onPrevious} disabled={!canGoPrevious}>
+        <StudioButton
+          variant='tertiary'
+          size='sm'
+          onClick={onPrevious}
+          disabled={!canGoPrevious}
+          aria-label={`Previous page. ${!canGoPrevious ? 'Disabled' : ''}`}
+        >
           <ChevronLeftIcon className={classes.icon} />
           {previousButtonText}
         </StudioButton>
         <NavigationStepIndicator totalPages={totalPages} currentPageNumber={currentPageNumber} />
-        <StudioButton variant='tertiary' size='sm' onClick={onNext} disabled={!canGoNext}>
+        <StudioButton
+          variant='tertiary'
+          size='sm'
+          onClick={onNext}
+          disabled={!canGoNext}
+          aria-label={`Next page. ${!canGoNext ? 'Disabled' : ''}`}
+        >
frontend/libs/studio-components/src/components/StudioPaginatedContent/StudioPaginatedContent.stories.tsx (1)

38-72: Add error handling for edge cases

Consider adding error handling for:

  1. Invalid input values
  2. Edge cases when pages array is empty
  3. Handling undefined currentPage
frontend/libs/studio-components/src/components/StudioPaginatedContent/StudioPaginatedContent.test.tsx (1)

1-25: LGTM! Well-structured test setup.

The test setup follows best practices with clean mocks and comprehensive default props.

@framitdavid framitdavid merged commit d747705 into main Jan 19, 2025
11 checks passed
@framitdavid framitdavid deleted the chore--14277-StudioPaginationContent branch January 19, 2025 22:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
frontend skip-manual-testing PRs that do not need to be tested manually solution/studio/designer Issues related to the Altinn Studio Designer solution.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Create a studio component for pagination with content above
2 participants