Skip to content

The open alternative to Salesforce, designed for AI.

2.0 KB
Raw Blame
import { type CommandMenuItemDefinition } from '@/command-menu-item/types/CommandMenuItemDefinition';
import { isDefined } from 'twenty-shared/utils';
import { EngineComponentKey } from '~/generated-metadata/graphql';

export const mergeGlobalRecordCreationCommandMenuItems = ({
  commandMenuItems,
  globalRecordCreationCommandMenuItems,
  shouldDisplayGlobalRecordCreationCommands,
  contextObjectMetadataId,
}: {
  commandMenuItems: CommandMenuItemDefinition[];
  globalRecordCreationCommandMenuItems: CommandMenuItemDefinition[];
  shouldDisplayGlobalRecordCreationCommands: boolean;
  contextObjectMetadataId?: string;
}): CommandMenuItemDefinition[] => {
  const sortedCommandMenuItems = [...commandMenuItems].sort(
    (firstItem, secondItem) => firstItem.position - secondItem.position,
  );

  if (!shouldDisplayGlobalRecordCreationCommands) {
    return sortedCommandMenuItems;
  }

  const hasCurrentObjectCreationCommand =
    isDefined(contextObjectMetadataId) &&
    globalRecordCreationCommandMenuItems.some(
      (item) => item.creationTargetObjectMetadataId === contextObjectMetadataId,
    );

  const isPinnedContextualCreationCommand = (item: CommandMenuItemDefinition) =>
    hasCurrentObjectCreationCommand &&
    item.engineComponentKey === EngineComponentKey.CREATE_NEW_RECORD &&
    item.isPinned;

  const hasPinnedContextualCreationCommand = sortedCommandMenuItems.some(
    isPinnedContextualCreationCommand,
  );

  return [
    ...sortedCommandMenuItems.filter(
      (item) =>
        isPinnedContextualCreationCommand(item) ||
        (item.engineComponentKey !== EngineComponentKey.CREATE_NEW_RECORD &&
          item.engineComponentKey !== EngineComponentKey.NAVIGATION),
    ),
    ...globalRecordCreationCommandMenuItems.filter(
      (item) =>
        !hasPinnedContextualCreationCommand ||
        item.creationTargetObjectMetadataId !== contextObjectMetadataId,
    ),
    ...sortedCommandMenuItems.filter(
      (item) => item.engineComponentKey === EngineComponentKey.NAVIGATION,
    ),
  ];
};