All files / libs/payout-definition/plans/views/hub/rule-designer/src/lib/drawer/navigation-blocker PlanHubRuleDesignerDrawerNavigationBlocker.tsx

0% Statements 0/53
0% Branches 0/1
0% Functions 0/1
0% Lines 0/53

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54                                                                                                           
import { memo, useCallback } from 'react';
import { useBlocker } from 'react-router-dom';

import { useNativeUnsavedChanges } from '@amalia/ext/react/hooks';

import { type PlanHubRuleDesignerStepTabs } from '../../tabs/plan-hub-rule-designer-step-tabs.types';
import { useDesignerDrawerContext } from '../PlanHubRuleDesignerDrawer.context';

import { PlanHubConfirmLeaving } from './PlanHubConfirmLeaving';

interface PlanHubRuleDesignerDrawerNavigationBlockerProps {
  readonly selectedRuleDesignerTab: PlanHubRuleDesignerStepTabs;
  readonly setSelectedRuleDesignerTab: (tab: PlanHubRuleDesignerStepTabs) => void;
}
export const PlanHubRuleDesignerDrawerNavigationBlocker = memo(function PlanHubRuleDesignerDrawerNavigationBlocker({
  selectedRuleDesignerTab,
  setSelectedRuleDesignerTab,
}: PlanHubRuleDesignerDrawerNavigationBlockerProps) {
  const { dirtyTokensCount, closeCleanTokens } = useDesignerDrawerContext();

  // Prevent browser navigatio when the user is navigating away from the app (click on a bookmark, type new URL...) or tries to close the tab.
  useNativeUnsavedChanges(!!dirtyTokensCount);

  // This is for when the user wants to navigate in-app, e.g. clicks on a drawer, on the back button...
  const blocker = useBlocker(
    ({ currentLocation, nextLocation }) => dirtyTokensCount > 0 && currentLocation.pathname !== nextLocation.pathname,
  );

  const handleClickReviewUnsavedChanges = useCallback(() => {
    if (blocker.state === 'blocked') {
      blocker.reset();
    }

    // If we were on the third step, navigate to a step where
    // the drawer is displayed so we can actually see what's
    // currently being edited.
    if (selectedRuleDesignerTab === '3-configure-payment') {
      setSelectedRuleDesignerTab('2-design-commission-structure');
    }

    closeCleanTokens();
  }, [closeCleanTokens, blocker, selectedRuleDesignerTab, setSelectedRuleDesignerTab]);

  return (
    <PlanHubConfirmLeaving
      dirtyTokensCount={dirtyTokensCount}
      isOpen={blocker.state === 'blocked'}
      onClose={() => blocker.reset?.()}
      onConfirm={() => blocker.proceed?.()}
      onReviewChanges={handleClickReviewUnsavedChanges}
    />
  );
});