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(monitoring): preserves scroll position on a data table (BAL-3248) #2962

Merged
merged 7 commits into from
Jan 16, 2025

Conversation

r4zendev
Copy link
Collaborator

@r4zendev r4zendev commented Jan 14, 2025

Screen.Recording.2025-01-14.at.21.09.54.mov

This PR includes:

  • fix: tailwind loading twice / overriding styles
  • fix: dynamic height of the main element based on viewport size to prevent user from scrolling out of the main shell (with back button etc.)
  • fix: navbar now remembers last state of a merchant monitoring tab to route the user correctly
  • feat: scroll state is persisted for tables

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced a new usePersistentScroll hook to maintain scroll position across page reloads.
    • Enhanced DataTable and ScrollArea components with improved scroll event handling and ref management.
    • Added a new constant for dynamic navigation parameters in the "Merchant Monitoring" section.
  • Refactor

    • Updated ScrollArea component type parameters and props structure.
    • Simplified DataTable component with forward ref implementation.
    • Modified MerchantMonitoringSearchSchema to ensure default date values for search parameters.
  • Bug Fixes

    • Adjusted the height of the ScrollArea component in the MerchantMonitoringBusinessReport for better layout.

@r4zendev r4zendev self-assigned this Jan 14, 2025
Copy link

changeset-bot bot commented Jan 14, 2025

⚠️ No Changeset found

Latest commit: 2e4b149

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Jan 14, 2025

Walkthrough

This pull request introduces several enhancements across multiple components and files, focusing on improving scroll management, data table functionality, and navigation logic. The changes include adding a new usePersistentScroll hook, modifying the DataTable and ScrollArea components to support scroll references, updating the merchant monitoring page's date range handling, and making minor UI adjustments. The modifications aim to provide a more consistent and user-friendly experience in the backoffice application.

Changes

File Change Summary
apps/backoffice-v2/src/common/components/organisms/UrlDataTable/UrlDataTable.tsx Added usePersistentScroll hook integration
apps/backoffice-v2/src/common/hooks/usePersistentScroll/usePersistentScroll.tsx New custom hook for managing scroll position using session storage
packages/ui/src/components/atoms/ScrollArea/ScrollArea.tsx Simplified props interface and updated type parameters
packages/ui/src/components/organisms/DataTable/DataTable.tsx Added scroll ref and scroll event handling
apps/backoffice-v2/src/common/components/organisms/Header/hooks/useNavbarLogic/useNavbarLogic.tsx Added dynamic merchant monitoring navigation params
apps/backoffice-v2/src/pages/MerchantMonitoring/constants.ts Added MERCHANT_MONITORING_QUERY_PARAMS_KEY constant
apps/backoffice-v2/src/pages/MerchantMonitoring/hooks/useMerchantMonitoringLogic/useMerchantMonitoringLogic.tsx Removed useDefaultDateRange function
apps/backoffice-v2/src/pages/MerchantMonitoring/schemas.ts Updated date range schema with default values
apps/backoffice-v2/src/pages/MerchantMonitoringBusinessReport/MerchantMonitoringBusinessReport.page.tsx Adjusted ScrollArea height
apps/backoffice-v2/tailwind.config.cjs Added new content path for Tailwind CSS scanning

Sequence Diagram

sequenceDiagram
    participant User
    participant Component
    participant usePersistentScroll
    participant SessionStorage

    User->>Component: Scrolls
    Component->>usePersistentScroll: Trigger handleScroll
    usePersistentScroll->>SessionStorage: Save scroll position
    
    User->>Component: Reloads/Navigates back
    Component->>usePersistentScroll: Mount component
    usePersistentScroll->>SessionStorage: Retrieve scroll position
    usePersistentScroll->>Component: Restore scroll position
Loading

Possibly related PRs

Suggested reviewers

  • MatanYadaev
  • Omri-Levy

Poem

🐰 Scrolling tales of code so bright,
Persistent memory takes flight,
Sessions saved with gentle care,
Components dance without a scare,
A rabbit's scroll, a tech delight! 📜✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 76d085d and 2e4b149.

📒 Files selected for processing (1)
  • apps/backoffice-v2/src/pages/MerchantMonitoringBusinessReport/MerchantMonitoringBusinessReport.page.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/backoffice-v2/src/pages/MerchantMonitoringBusinessReport/MerchantMonitoringBusinessReport.page.tsx
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build (windows-latest)
  • GitHub Check: test_windows
  • GitHub Check: test_linux
  • GitHub Check: build (ubuntu-latest)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: lint

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 (3)
packages/ui/src/components/atoms/ScrollArea/ScrollArea.tsx (1)

7-10: Consider adding scroll position persistence props.

Since this component is used for preserving scroll position in data tables (per PR objective), consider adding props to support this functionality directly:

  React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root> & {
    orientation: 'vertical' | 'horizontal' | 'both';
+   persistScrollPosition?: boolean;
+   onScrollPositionChange?: (position: { x: number; y: number }) => void;
  }
packages/ui/src/components/organisms/DataTable/DataTable.tsx (2)

76-78: Add JSDoc comments for the new props

Consider adding documentation for the new scroll-related props to improve maintainability.

+  /**
+   * Reference to the scrollable area DOM element
+   */
   scrollRef?: React.RefObject<HTMLDivElement>;
+  /**
+   * Callback fired when the scrollable area is scrolled
+   */
   handleScroll?: (event: React.UIEvent<HTMLDivElement>) => void;

338-341: Improve type safety of the forwardRef wrapper

The current type assertion is too permissive. Consider using a more specific type.

-const forward = React.forwardRef as <T, P = NonNullable<unknown>>(
-  render: (props: P, ref: React.Ref<T>) => React.ReactNode,
-) => (props: P & React.RefAttributes<T>) => React.ReactNode;
-export const DataTable = forward(DataTableBase);
+const DataTable = React.forwardRef<HTMLDivElement, IDataTableProps<any, any>>(DataTableBase);
+export { DataTable };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 01c2c7b and 79a48ef.

📒 Files selected for processing (5)
  • apps/backoffice-v2/src/common/components/organisms/UrlDataTable/UrlDataTable.tsx (1 hunks)
  • apps/backoffice-v2/src/common/hooks/usePersistentScroll/usePersistentScroll.tsx (1 hunks)
  • packages/ui/src/components/atoms/ScrollArea/ScrollArea.tsx (1 hunks)
  • packages/ui/src/components/organisms/DataTable/DataTable.tsx (3 hunks)
  • services/workflows-service/prisma/data-migrations (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • services/workflows-service/prisma/data-migrations
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (3)
packages/ui/src/components/atoms/ScrollArea/ScrollArea.tsx (2)

7-10: Type definitions improved for better type safety.

The change from using React.FC<Props> to React.ElementRef<typeof ScrollAreaPrimitive.Root> provides better type safety and more accurate TypeScript definitions by directly referencing the Radix UI primitive types.


Line range hint 13-15: Verify scroll position preservation on viewport ref updates.

The viewport ref is crucial for scroll position management. Ensure that scroll position is maintained when the ref's content updates.

✅ Verification successful

Scroll position management implementation verified ✓

The ScrollArea component correctly implements scroll position management through Radix UI's primitive component, with proper ref forwarding. The codebase demonstrates appropriate scroll position handling patterns.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for places where ScrollArea's ref is used for scroll position management
ast-grep --pattern 'const $_ = useRef<$_>($$$)' | rg -A 5 'scroll|position'

# Look for scroll position related state management
rg -g '*.{ts,tsx}' -A 5 'scrollTop|scrollLeft|scrollTo'

Length of output: 3259

apps/backoffice-v2/src/common/components/organisms/UrlDataTable/UrlDataTable.tsx (1)

15-21: LGTM! Clean integration of the scroll persistence feature

The hook integration is implemented correctly, with proper prop forwarding to the DataTable component.

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 (2)
apps/backoffice-v2/src/common/components/organisms/Header/hooks/useNavbarLogic/useNavbarLogic.tsx (1)

25-25: Add error handling and type safety for sessionStorage access.

Consider adding error handling and type safety:

- const merchantMonitoringParams = sessionStorage.getItem(MERCHANT_MONITORING_QUERY_PARAMS_KEY);
+ const merchantMonitoringParams = (() => {
+   try {
+     const params = sessionStorage.getItem(MERCHANT_MONITORING_QUERY_PARAMS_KEY);
+     return params && JSON.parse(params) as Record<string, string>;
+   } catch (error) {
+     console.error('Failed to parse merchant monitoring params:', error);
+     return null;
+   }
+ })();
apps/backoffice-v2/src/pages/MerchantMonitoring/hooks/useMerchantMonitoringLogic/useMerchantMonitoringLogic.tsx (1)

49-52: Consider using a custom hook for search persistence.

The search persistence logic could be reused across different components. Consider extracting it into a custom hook like usePersistentSearchParams.

// Create a new hook:
const usePersistentSearchParams = (storageKey: string) => {
  const { search } = useLocation();
  
  useEffect(() => {
    sessionStorage.setItem(storageKey, search);
  }, [search, storageKey]);
};

// Usage in component:
usePersistentSearchParams(MERCHANT_MONITORING_QUERY_PARAMS_KEY);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 79a48ef and b05ccc7.

📒 Files selected for processing (8)
  • apps/backoffice-v2/src/common/components/organisms/Header/hooks/useNavbarLogic/useNavbarLogic.tsx (3 hunks)
  • apps/backoffice-v2/src/common/hooks/usePersistentScroll/usePersistentScroll.tsx (1 hunks)
  • apps/backoffice-v2/src/pages/MerchantMonitoring/constants.ts (1 hunks)
  • apps/backoffice-v2/src/pages/MerchantMonitoring/hooks/useMerchantMonitoringLogic/useMerchantMonitoringLogic.tsx (2 hunks)
  • apps/backoffice-v2/src/pages/MerchantMonitoring/schemas.ts (2 hunks)
  • apps/backoffice-v2/src/pages/MerchantMonitoringBusinessReport/MerchantMonitoringBusinessReport.page.tsx (1 hunks)
  • apps/backoffice-v2/tailwind.config.cjs (1 hunks)
  • services/workflows-service/prisma/data-migrations (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • apps/backoffice-v2/src/pages/MerchantMonitoring/constants.ts
  • apps/backoffice-v2/src/pages/MerchantMonitoringBusinessReport/MerchantMonitoringBusinessReport.page.tsx
🚧 Files skipped from review as they are similar to previous changes (2)
  • services/workflows-service/prisma/data-migrations
  • apps/backoffice-v2/src/common/hooks/usePersistentScroll/usePersistentScroll.tsx
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build (windows-latest)
  • GitHub Check: build (ubuntu-latest)
  • GitHub Check: test_windows
  • GitHub Check: test_linux
  • GitHub Check: Analyze (javascript)
  • GitHub Check: lint
🔇 Additional comments (6)
apps/backoffice-v2/src/common/components/organisms/Header/hooks/useNavbarLogic/useNavbarLogic.tsx (2)

9-9: LGTM! New import is correctly placed.


25-25: Verify the relationship between query parameters and scroll position.

The changes preserve query parameters in session storage, but it's unclear how this relates to scroll position preservation. Let's verify the connection:

Also applies to: 39-39

apps/backoffice-v2/src/pages/MerchantMonitoring/schemas.ts (2)

5-5: LGTM: dayjs import added for date manipulation.

The import is necessary for the new default date range functionality.


129-130: Verify date range default values across timezones.

The default values for date range now use dayjs() which uses the local timezone. This could lead to inconsistencies across different timezones when querying the backend.

Consider explicitly setting the timezone or using UTC:

-  from: z.string().date().default(dayjs().subtract(30, 'day').format('YYYY-MM-DD')),
-  to: z.string().date().default(dayjs().format('YYYY-MM-DD')),
+  from: z.string().date().default(dayjs().utc().subtract(30, 'day').format('YYYY-MM-DD')),
+  to: z.string().date().default(dayjs().utc().format('YYYY-MM-DD')),
apps/backoffice-v2/src/pages/MerchantMonitoring/hooks/useMerchantMonitoringLogic/useMerchantMonitoringLogic.tsx (2)

3-24: LGTM: Clean import organization and proper separation of concerns.

The reorganization of imports and removal of useDefaultDateRange in favor of schema defaults improves code maintainability.


Line range hint 71-72: Verify date handling in API query.

The code adds one day to the 'to' date for the API query. This might lead to timezone-related issues when combined with the default values from the schema.

@r4zendev r4zendev enabled auto-merge (squash) January 16, 2025 09:40
@r4zendev r4zendev merged commit e8630d3 into dev Jan 16, 2025
18 checks passed
@r4zendev r4zendev deleted the bal3248 branch January 16, 2025 11:11
Omri-Levy added a commit that referenced this pull request Jan 21, 2025
* feat: updated styles for link elements (#2959)

* feat: added csv document rendering (#2958)

* fix(monitoring): changes the block ordering in website credibility view (#2963)

* feat(monitoring): adds loading state for a single merchant record (BAL-3359) (#2960)

* feat(monitoring): adjusts merchant risk summary text (BAL-3373) (#2961)

* refactor(websiteCredibility): fix CardContent height for no data (#2966)

* refactor(websiteCredibility): fix CardContent height for no data

- Remove unused Tooltip import from recharts
- Update CardContent class to ensure full height

(your code is like a tidy room: looks clean but still has hidden messes)

* empty

* fix: UI fixes for statistics and merchant monitoring report pages (#2965)

* feat(monitoring): adds exhaustive check for action before deboarding a merchant (BAL-3343) (#2964)

* feat(monitoring): preserves scroll position on a data table (BAL-3248) (#2962)

* fix: chart graph cut off (BAL-3395) (#2969)

* fix: corrected home page merchants metrics source of truth (BAL-3396, BAL-3397) (#2968)

* chore(*): updated packages (#2971)

* fix(backoffice-v2): reverted default logic for from and to (#2973)

* refactor(entities): streamline form data context creation (#2974)

- Remove unnecessary context object creation
- Simplify the return statement by directly returning the new context

(your code is like a magic trick that turns objects into empty space)

* fix: remove monitoring params logic from navbar (#2975)

Co-authored-by: Omri Levy <[email protected]>

* fix: fixed popup flickering in date picker & bump (#2977)

* feat: add a report note when monitoring status is toggled (BAL-3398) (#2979)

* feat: add a report note when monitoring status is toggled

* chore: remove storing reason in metadata

* fix: dmt and dsta rules (#2970)

Co-authored-by: Lior Zamir <[email protected]>
Co-authored-by: Alon Peretz <[email protected]>

---------

Co-authored-by: Illia Rudniev <[email protected]>
Co-authored-by: Sasha <[email protected]>
Co-authored-by: Shane <[email protected]>
Co-authored-by: Tomer Shvadron <[email protected]>
Co-authored-by: liorzam <[email protected]>
Co-authored-by: Lior Zamir <[email protected]>
Co-authored-by: Alon Peretz <[email protected]>
@Omri-Levy Omri-Levy mentioned this pull request Jan 21, 2025
Omri-Levy added a commit that referenced this pull request Jan 21, 2025
* feat: updated styles for link elements (#2959)

* feat: added csv document rendering (#2958)

* fix(monitoring): changes the block ordering in website credibility view (#2963)

* feat(monitoring): adds loading state for a single merchant record (BAL-3359) (#2960)

* feat(monitoring): adjusts merchant risk summary text (BAL-3373) (#2961)

* refactor(websiteCredibility): fix CardContent height for no data (#2966)

* refactor(websiteCredibility): fix CardContent height for no data

- Remove unused Tooltip import from recharts
- Update CardContent class to ensure full height

(your code is like a tidy room: looks clean but still has hidden messes)

* empty

* fix: UI fixes for statistics and merchant monitoring report pages (#2965)

* feat(monitoring): adds exhaustive check for action before deboarding a merchant (BAL-3343) (#2964)

* feat(monitoring): preserves scroll position on a data table (BAL-3248) (#2962)

* fix: chart graph cut off (BAL-3395) (#2969)

* fix: corrected home page merchants metrics source of truth (BAL-3396, BAL-3397) (#2968)

* chore(*): updated packages (#2971)

* fix(backoffice-v2): reverted default logic for from and to (#2973)

* refactor(entities): streamline form data context creation (#2974)

- Remove unnecessary context object creation
- Simplify the return statement by directly returning the new context

(your code is like a magic trick that turns objects into empty space)

* fix: remove monitoring params logic from navbar (#2975)



* fix: fixed popup flickering in date picker & bump (#2977)

* feat: add a report note when monitoring status is toggled (BAL-3398) (#2979)

* feat: add a report note when monitoring status is toggled

* chore: remove storing reason in metadata

* fix: dmt and dsta rules (#2970)




---------

Co-authored-by: Illia Rudniev <[email protected]>
Co-authored-by: Sasha <[email protected]>
Co-authored-by: Shane <[email protected]>
Co-authored-by: Tomer Shvadron <[email protected]>
Co-authored-by: liorzam <[email protected]>
Co-authored-by: Lior Zamir <[email protected]>
Co-authored-by: Alon Peretz <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants