Skip to content

The open alternative to Salesforce, designed for AI.

2.8 KB
Raw Blame
import { SIDE_PANEL_NAVIGATION_HISTORY_DROPDOWN_ID } from '@/side-panel/constants/SidePanelNavigationHistoryDropdownId';
import { useSidePanelContextChips } from '@/side-panel/hooks/useSidePanelContextChips';
import { useSidePanelHistory } from '@/side-panel/hooks/useSidePanelHistory';
import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContent';
import { DropdownRoot } from '@/ui/layout/dropdown/components/DropdownRoot';
import { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';
import { useOpenDropdown } from '@/ui/layout/dropdown/hooks/useOpenDropdown';
import { Children, useRef, type MouseEvent } from 'react';
import { isNonEmptyArray } from 'twenty-shared/utils';
import { IconButton } from 'twenty-ui/components/input';
import { Dropdown } from 'twenty-ui/components/navigation';
import { IconChevronLeft } from 'twenty-ui/icon';
import { useLingui } from '@lingui/react/macro';

export const SidePanelBackButton = () => {
  const { t } = useLingui();
  const { goBackFromSidePanel } = useSidePanelHistory();

  const { contextChips } = useSidePanelContextChips();

  const historyChips = contextChips.slice(0, -1);

  const { openDropdown } = useOpenDropdown();

  const { closeDropdown } = useCloseDropdown();

  const backButtonRef = useRef<HTMLButtonElement>(null);

  const handleBackButtonClick = () => {
    closeDropdown(SIDE_PANEL_NAVIGATION_HISTORY_DROPDOWN_ID);
    goBackFromSidePanel();
  };

  const handleBackButtonContextMenu = (
    event: MouseEvent<HTMLButtonElement>,
  ) => {
    if (!isNonEmptyArray(historyChips)) {
      return;
    }

    event.preventDefault();
    event.stopPropagation();

    openDropdown({
      dropdownComponentInstanceIdFromProps:
        SIDE_PANEL_NAVIGATION_HISTORY_DROPDOWN_ID,
    });
  };

  return (
    <DropdownRoot
      type="menu"
      dropdownId={SIDE_PANEL_NAVIGATION_HISTORY_DROPDOWN_ID}
      onInteractOutside={(event) => {
        if (backButtonRef.current?.contains(event.target)) {
          event.preventDefault();
        }
      }}
    >
      <IconButton
        ref={backButtonRef}
        size="sm"
        variant="ghost"
        onClick={handleBackButtonClick}
        onContextMenu={handleBackButtonContextMenu}
        aria-label={t`Back`}
      >
        <IconChevronLeft />
      </IconButton>
      <DropdownContent
        anchor={backButtonRef}
        aria-label={t`Navigation history`}
      >
        <Dropdown.Section>
          {historyChips.map((chip, index) => (
            <Dropdown.ActionItem
              key={index}
              startIcon={<>{Children.toArray(chip.Icons)}</>}
              onClick={chip.onClick}
            >
              {chip.text}
            </Dropdown.ActionItem>
          ))}
        </Dropdown.Section>
      </DropdownContent>
    </DropdownRoot>
  );
};