Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

10.7 KB
Raw Blame
import { combine } from '@atlaskit/pragmatic-drag-and-drop/combine';
import { draggable, monitorForElements } from '@atlaskit/pragmatic-drag-and-drop/element/adapter';
import type { FlexProps } from '@invoke-ai/ui-library';
import { Flex, Icon, Image } from '@invoke-ai/ui-library';
import { createSelector } from '@reduxjs/toolkit';
import type { AppDispatch, AppGetState } from 'app/store/store';
import { useAppSelector, useAppStore } from 'app/store/storeHooks';
import { useMiddleClickOpenInNewTab } from 'common/hooks/useMiddleClickOpenInNewTab';
import { uniq } from 'es-toolkit';
import { useMediaUrl } from 'features/auth/store/mediaCookieRefresh';
import { multipleImageDndSource, singleImageDndSource } from 'features/dnd/dnd';
import type { DndDragPreviewMultipleImageState } from 'features/dnd/DndDragPreviewMultipleImage';
import { createMultipleImageDragPreview, setMultipleImageDragPreview } from 'features/dnd/DndDragPreviewMultipleImage';
import type { DndDragPreviewSingleImageState } from 'features/dnd/DndDragPreviewSingleImage';
import { createSingleImageDragPreview, setSingleImageDragPreview } from 'features/dnd/DndDragPreviewSingleImage';
import { dndInputFix } from 'features/dnd/util';
import { useImageContextMenu } from 'features/gallery/components/ContextMenu/ImageContextMenu';
import { GalleryItemHoverIcons } from 'features/gallery/components/ImageGrid/GalleryItemHoverIcons';
import { selectSelectedBoardId, selectSelection } from 'features/gallery/store/gallerySelectors';
import {
  imageSelected,
  imageToCompareChanged,
  selectGallerySlice,
  selectionChanged,
} from 'features/gallery/store/gallerySlice';
import { selectCachedGalleryItemNames } from 'features/gallery/store/selectCachedGalleryItemNames';
import { isVideoName } from 'features/gallery/store/types';
import { navigationApi } from 'features/ui/layouts/navigation-api';
import { VIEWER_PANEL_ID } from 'features/ui/layouts/shared';
import type { MouseEvent, MouseEventHandler } from 'react';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { PiImageBold } from 'react-icons/pi';
import type { ImageDTO } from 'services/api/types';

import { galleryItemContainerSX } from './galleryItemContainerSX';

interface Props {
  imageDTO: ImageDTO;
}

const buildOnClick =
  (imageName: string, dispatch: AppDispatch, getState: AppGetState) => (e: MouseEvent<HTMLDivElement>) => {
    const { shiftKey, ctrlKey, metaKey, altKey } = e;
    const state = getState();
    // Read from the polymorphic getGalleryItemNames cache (the source of truth for grid order)
    // rather than the legacy image-only getImageNames cache, which is no longer populated for
    // the grid. Without this, shift- and ctrl-click would silently no-op because the legacy
    // list comes back empty.
    const itemNames = selectCachedGalleryItemNames(state);

    if (itemNames.length === 0) {
      // Without an ordered list we can still honor a plain single-click.
      if (!shiftKey && !ctrlKey && !metaKey && !altKey) {
        dispatch(imageSelected(imageName));
      }
      return;
    }

    const selection = state.gallery.selection;

    if (altKey) {
      if (state.gallery.imageToCompare === imageName) {
        dispatch(imageToCompareChanged(null));
      } else {
        dispatch(imageToCompareChanged(imageName));
      }
    } else if (shiftKey) {
      const rangeEndImageName = imageName;
      const lastSelectedImage = selection.at(-1);
      const lastClickedIndex = itemNames.findIndex((name) => name === lastSelectedImage);
      const currentClickedIndex = itemNames.findIndex((name) => name === rangeEndImageName);
      if (lastClickedIndex > -1 && currentClickedIndex > -1) {
        const start = Math.min(lastClickedIndex, currentClickedIndex);
        const end = Math.max(lastClickedIndex, currentClickedIndex);
        const imagesToSelect = itemNames.slice(start, end + 1);
        if (currentClickedIndex < lastClickedIndex) {
          imagesToSelect.reverse();
        }
        dispatch(selectionChanged(uniq(selection.concat(imagesToSelect))));
      }
    } else if (ctrlKey || metaKey) {
      if (selection.some((n) => n === imageName) && selection.length > 1) {
        dispatch(selectionChanged(uniq(selection.filter((n) => n !== imageName))));
      } else {
        dispatch(selectionChanged(uniq(selection.concat(imageName))));
      }
    } else {
      // A plain click is the user picking one item, where the modifier branches above mutate the
      // multi-selection. The distinction is load-bearing: the gallery selection source reads
      // `imageSelected` as a pick (so a repeat click on the active item reveals it over the
      // progress overlay) but deliberately does not read `selectionChanged`, whose mutations only
      // count when they move the active item.
      dispatch(imageSelected(imageName));
    }
  };

export const GalleryImage = memo(({ imageDTO }: Props) => {
  const thumbnailUrl = useMediaUrl(imageDTO.thumbnail_url);
  const store = useAppStore();
  const [isDragging, setIsDragging] = useState(false);
  const [dragPreviewState, setDragPreviewState] = useState<
    DndDragPreviewSingleImageState | DndDragPreviewMultipleImageState | null
  >(null);
  const ref = useRef<HTMLDivElement>(null);
  const selectIsSelectedForCompare = useMemo(
    () => createSelector(selectGallerySlice, (gallery) => gallery.imageToCompare === imageDTO.image_name),
    [imageDTO.image_name]
  );
  const isSelectedForCompare = useAppSelector(selectIsSelectedForCompare);
  const selectIsSelected = useMemo(
    () => createSelector(selectGallerySlice, (gallery) => gallery.selection.some((n) => n === imageDTO.image_name)),
    [imageDTO.image_name]
  );
  const isSelected = useAppSelector(selectIsSelected);

  useEffect(() => {
    const element = ref.current;
    if (!element) {
      return;
    }

    const monitorBinding = monitorForElements({
      // This is a "global" drag start event, meaning that it is called for all drag events.
      onDragStart: ({ source }) => {
        // When we start dragging multiple images, set the dragging state to true if the dragged image is part of the
        // selection. This is called for all drag events.
        if (
          multipleImageDndSource.typeGuard(source.data) &&
          source.data.payload.image_names.includes(imageDTO.image_name)
        ) {
          setIsDragging(true);
        }
      },
      onDrop: () => {
        // Always set the dragging state to false when a drop event occurs.
        setIsDragging(false);
      },
    });

    return combine(
      dndInputFix(element),
      draggable({
        element,
        getInitialData: () => {
          const selection = selectSelection(store.getState());
          const boardId = selectSelectedBoardId(store.getState());

          // When we have multiple items selected, and the dragged image is part of the
          // selection, initiate a multi-drag. Mixed selections (images + videos) ride along in
          // the same payload: the board drop handler splits them and dispatches both mutations.
          // Without filtering, video names would land in `image_names` and the image router
          // would 404 on each one.
          if (selection.length > 1 && selection.some((n) => n === imageDTO.image_name)) {
            const image_names = selection.filter((n) => !isVideoName(n));
            const video_names = selection.filter(isVideoName);
            return multipleImageDndSource.getData({
              image_names,
              video_names,
              board_id: boardId,
            });
          }

          // Otherwise, initiate a single-image drag
          return singleImageDndSource.getData({ imageDTO }, imageDTO.image_name);
        },
        // This is a "local" drag start event, meaning that it is only called when this specific image is dragged.
        onDragStart: ({ source }) => {
          // When we start dragging a single image, set the dragging state to true. This is only called when this
          // specific image is dragged.
          if (singleImageDndSource.typeGuard(source.data)) {
            setIsDragging(true);
            return;
          }
        },
        onGenerateDragPreview: (args) => {
          if (multipleImageDndSource.typeGuard(args.source.data)) {
            setMultipleImageDragPreview({
              multipleImageDndData: args.source.data,
              onGenerateDragPreviewArgs: args,
              setDragPreviewState,
            });
          } else if (singleImageDndSource.typeGuard(args.source.data)) {
            setSingleImageDragPreview({
              singleImageDndData: args.source.data,
              onGenerateDragPreviewArgs: args,
              setDragPreviewState,
            });
          }
        },
      }),
      monitorBinding
    );
  }, [imageDTO, store]);

  const [isHovered, setIsHovered] = useState(false);

  const onMouseOver = useCallback(() => {
    setIsHovered(true);
  }, []);

  const onMouseOut = useCallback(() => {
    setIsHovered(false);
  }, []);

  const onClick = useMemo(() => buildOnClick(imageDTO.image_name, store.dispatch, store.getState), [imageDTO, store]);
  useMiddleClickOpenInNewTab(ref, imageDTO.image_url, {
    requireDirectTarget: true,
  });

  const onDoubleClick = useCallback<MouseEventHandler<HTMLDivElement>>(() => {
    store.dispatch(imageToCompareChanged(null));
    navigationApi.focusPanelInActiveTab(VIEWER_PANEL_ID);
  }, [store]);

  useImageContextMenu(imageDTO, ref);

  return (
    <>
      <Flex
        ref={ref}
        sx={galleryItemContainerSX}
        data-is-dragging={isDragging}
        data-item-id={imageDTO.image_name}
        role="button"
        onMouseOver={onMouseOver}
        onMouseOut={onMouseOut}
        onClick={onClick}
        onDoubleClick={onDoubleClick}
        data-selected={isSelected}
        data-selected-for-compare={isSelectedForCompare}
      >
        <Image
          pointerEvents="none"
          src={thumbnailUrl}
          w={imageDTO.width}
          fallback={<GalleryImagePlaceholder />}
          objectFit="contain"
          maxW="full"
          maxH="full"
          borderRadius="base"
        />
        <GalleryItemHoverIcons imageDTO={imageDTO} isHovered={isHovered} />
      </Flex>
      {dragPreviewState?.type === 'multiple-image' ? createMultipleImageDragPreview(dragPreviewState) : null}
      {dragPreviewState?.type === 'single-image' ? createSingleImageDragPreview(dragPreviewState) : null}
    </>
  );
});

GalleryImage.displayName = 'GalleryImage';

export const GalleryImagePlaceholder = memo((props: FlexProps) => (
  <Flex w="full" h="full" bg="base.850" borderRadius="base" alignItems="center" justifyContent="center" {...props}>
    <Icon as={PiImageBold} boxSize={16} color="base.800" />
  </Flex>
));

GalleryImagePlaceholder.displayName = 'GalleryImagePlaceholder';