Skip to content

The open alternative to Salesforce, designed for AI.

8.1 KB
Raw Blame
import {
  autoUpdate,
  flip,
  offset,
  shift,
  useFloating,
} from '@floating-ui/react';
import { motion } from 'framer-motion';
import {
  forwardRef,
  useId,
  useImperativeHandle,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
} from 'react';

import { RootStackingContextZIndices } from '@/ui/layout/constants/RootStackingContextZIndices';
import { DropdownMenuSectionLabel } from '@/ui/layout/dropdown/components/DropdownMenuSectionLabel';
import { OverlayMenuList } from '@/ui/layout/overlay/components/OverlayMenuList';
import { OverlayMenuListSeparator } from '@/ui/layout/overlay/components/OverlayMenuListSeparator';
import { OverlayContainer } from '@/ui/layout/overlay/components/OverlayContainer';
import { SuggestionItemPreviewTooltip } from '@/ui/suggestion/components/SuggestionItemPreviewTooltip';
import { SuggestionMenuAccessibilityEffect } from '@/ui/suggestion/components/SuggestionMenuAccessibilityEffect';
import type { SuggestionMenuProps } from '@/ui/suggestion/types/SuggestionMenuProps';
import { getSuggestionMenuItemAnchorId } from '@/ui/suggestion/utils/getSuggestionMenuItemAnchorId';
import { isDefined } from 'twenty-shared/utils';
import { doNotTranslate } from 'twenty-shared/i18n';
import { useIsMobile } from 'twenty-ui/utilities';
import { useLingui } from '@lingui/react/macro';

type SuggestionMenuInnerProps<TItem> = SuggestionMenuProps<TItem>;

// forwardRef does not natively support generics, so we use a helper + cast
const SuggestionMenuInner = <TItem,>(
  props: SuggestionMenuInnerProps<TItem>,
  parentRef: React.ForwardedRef<unknown>,
) => {
  const { t } = useLingui();
  const {
    items,
    onSelect,
    editor,
    range,
    getItemKey,
    renderItem,
    selectedItemPreview,
    getItemSection,
    onKeyDown,
  } = props;

  const isMobile = useIsMobile();
  const menuId = useId();

  const [selectedIndex, setSelectedIndex] = useState(0);

  const clampedSelectedIndex =
    items.length > 0 ? Math.min(selectedIndex, items.length - 1) : 0;

  const selectedItem = items[clampedSelectedIndex];
  const activeOptionId = isDefined(selectedItem)
    ? getSuggestionMenuItemAnchorId({
        menuId,
        itemKey: getItemKey(selectedItem),
      })
    : undefined;

  const [isSelectedItemVisible, setIsSelectedItemVisible] = useState(true);

  const shouldDisplayPreview =
    !isMobile &&
    isSelectedItemVisible &&
    selectedItemPreview !== undefined &&
    selectedItem !== undefined;

  const activeItemRef = useRef<HTMLDivElement>(null);
  const listContainerRef = useRef<HTMLDivElement>(null);

  const positionReference = useMemo(
    () => ({
      getBoundingClientRect: () => {
        const start = editor.view.coordsAtPos(range.from);
        return new DOMRect(start.left, start.top, 0, start.bottom - start.top);
      },
    }),
    [editor, range],
  );

  const { refs, floatingStyles } = useFloating({
    placement: 'bottom-start',
    strategy: 'fixed',
    middleware: [offset(4), flip(), shift()],
    whileElementsMounted: (reference, floating, update) => {
      return autoUpdate(reference, floating, update, {
        animationFrame: true,
      });
    },
    elements: {
      reference: positionReference,
    },
  });

  const selectItem = (index: number) => {
    const item = items[index];
    if (!item) {
      return;
    }

    onSelect(item);
  };

  useImperativeHandle(parentRef, () => ({
    onKeyDown: ({ event }: { event: KeyboardEvent }) => {
      const customResult = onKeyDown?.(event, clampedSelectedIndex);
      if (customResult === true) {
        return true;
      }

      const navigationKeys = ['ArrowUp', 'ArrowDown', doNotTranslate('Enter')];
      if (navigationKeys.includes(event.key)) {
        switch (event.key) {
          case 'ArrowUp': {
            if (!items.length) {
              return false;
            }
            let newIndex = clampedSelectedIndex - 1;
            if (newIndex < 0) {
              newIndex = items.length - 1;
            }
            setSelectedIndex(newIndex);
            return true;
          }
          case 'ArrowDown': {
            if (!items.length) {
              return false;
            }
            let newIndex = clampedSelectedIndex + 1;
            if (newIndex >= items.length) {
              newIndex = 0;
            }
            setSelectedIndex(newIndex);
            return true;
          }
          case 'Enter':
            if (!items.length) {
              return false;
            }
            selectItem(clampedSelectedIndex);
            return true;
          default:
            return false;
        }
      }

      return false;
    },
  }));

  useLayoutEffect(() => {
    const container = listContainerRef?.current;
    const activeItemContainer = activeItemRef?.current;
    if (!container || !activeItemContainer) {
      return;
    }
    const scrollableContainer =
      container.firstElementChild as HTMLElement | null;
    if (!scrollableContainer) {
      return;
    }

    const { offsetTop, offsetHeight } = activeItemContainer;

    scrollableContainer.style.transition = 'none';
    scrollableContainer.scrollTop = offsetTop - offsetHeight;
  }, [clampedSelectedIndex]);

  // The preview is anchored to the selected row, so it would float detached once that row scrolls out
  useLayoutEffect(() => {
    const scrollableContainer =
      listContainerRef.current?.firstElementChild ?? null;
    const activeItemContainer = activeItemRef.current;

    if (
      !scrollableContainer ||
      !activeItemContainer ||
      typeof IntersectionObserver === 'undefined'
    ) {
      return;
    }

    const observer = new IntersectionObserver(
      ([entry]) => {
        setIsSelectedItemVisible(entry.isIntersecting);
      },
      { root: scrollableContainer, threshold: 0.99 },
    );

    observer.observe(activeItemContainer);

    return () => {
      observer.disconnect();
    };
  }, [clampedSelectedIndex, items]);

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      transition={{ duration: 0.1 }}
      data-suggestion-menu
    >
      <SuggestionMenuAccessibilityEffect
        editor={editor}
        menuId={menuId}
        activeOptionId={activeOptionId}
      />
      <OverlayContainer
        id={menuId}
        role="listbox"
        aria-label={t`Suggestions`}
        ref={refs.setFloating}
        style={{
          ...floatingStyles,
          zIndex: RootStackingContextZIndices.DropdownPortalAboveModal,
        }}
      >
        <OverlayMenuList ref={listContainerRef}>
          {items.map((item, index) => {
            const isSelected = index === clampedSelectedIndex;
            const section = getItemSection?.(item);
            const isFirstOfSection =
              isDefined(section) &&
              (index === 0 ||
                getItemSection?.(items[index - 1])?.key !== section.key);

            return (
              <div
                key={getItemKey(item)}
                ref={isSelected ? activeItemRef : null}
                onMouseDown={(event) => {
                  event.preventDefault();
                }}
              >
                {isFirstOfSection && index > 0 && <OverlayMenuListSeparator />}
                {isFirstOfSection && (
                  <DropdownMenuSectionLabel label={section.label} />
                )}
                {renderItem({
                  item,
                  isSelected,
                  id: getSuggestionMenuItemAnchorId({
                    menuId,
                    itemKey: getItemKey(item),
                  }),
                })}
              </div>
            );
          })}
        </OverlayMenuList>
      </OverlayContainer>
      {shouldDisplayPreview && (
        <SuggestionItemPreviewTooltip
          key={getItemKey(selectedItem)}
          anchor={activeItemRef}
          width={selectedItemPreview.width}
        >
          {selectedItemPreview.render(selectedItem)}
        </SuggestionItemPreviewTooltip>
      )}
    </motion.div>
  );
};

export const SuggestionMenu = forwardRef(SuggestionMenuInner) as <TItem>(
  props: SuggestionMenuProps<TItem> & { ref?: React.Ref<unknown> },
) => ReturnType<typeof SuggestionMenuInner>;