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.

13.5 KB
Raw Blame
import type { GalleryItem, GalleryItemKey, GalleryItemRef } from '@features/gallery/core/items';
import type { GalleryThumbnailFit } from '@features/gallery/core/settings';

import { Badge, chakra } from '@chakra-ui/react';
import { useDraggable } from '@dnd-kit/core';
import { CSS } from '@dnd-kit/utilities';
import { formatGalleryVideoDuration, toGalleryItemKey, toGalleryItemRef } from '@features/gallery/core/items';
import {
  getGalleryThumbnailRevision,
  getRefreshedGalleryThumbnailUrl,
  subscribeGalleryThumbnailRevision,
} from '@features/gallery/queries';
import { IconButton } from '@platform/ui/Button';
import { StarIcon } from 'lucide-react';
import {
  useCallback,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
  useSyncExternalStore,
  type KeyboardEvent,
  type MouseEvent,
} from 'react';
import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';

import { getGalleryItemDragData, getGalleryItemDragId } from './galleryDnd';
import {
  GALLERY_TILE_MEDIA_SELECTOR,
  GalleryTileFrame,
  GalleryTileMedia,
  getGalleryTileMediaRatio,
} from './GalleryTileFrame';
import { useGalleryImageRecovery } from './useGalleryImageRecovery';

export const GALLERY_TAB_STOP_SELECTOR = 'button[data-gallery-item-key][tabindex="0"]';

/** Includes the portalled preview. */
const THUMBNAIL_DRAG_CSS = { filter: 'saturate(0)' } as const;
const THUMBNAIL_ARMED_CSS = { '&[data-drag-armed=true]': { filter: 'saturate(0)' } } as const;

/** Modified chords are app hotkeys (Mod+Enter invokes), not activation or drag; modified clicks only select. */
const isModified = (event: KeyboardEvent | MouseEvent) =>
  event.ctrlKey || event.metaKey || event.altKey || event.shiftKey;

const stopPropagation = (event: MouseEvent) => event.stopPropagation();

const PREVIEW_IMAGE_STYLE = {
  borderRadius: '0.375rem',
  boxShadow: '0 8px 24px rgb(0 0 0 / 45%)',
  filter: 'saturate(0)',
  height: '100%',
  objectFit: 'cover',
  width: '100%',
} as const;

const LABEL_MAX_WIDTH = 'calc(100% - 2.25rem)';
/** `!important` because the tile's hover reveal outranks a single-class rule. */
const LABEL_CSS = { '@starting-style': { opacity: '0 !important' } } as const;

const THUMBNAIL_BUTTON_STYLE = {
  background: 'transparent',
  border: 0,
  display: 'block',
  height: '100%',
  inset: 0,
  minWidth: 0,
  outline: 'none',
  padding: 0,
  position: 'absolute',
  width: '100%',
} as const;

const GalleryThumbnail = ({
  alwaysShowDimensions,
  compareRole,
  dragItems,
  dragScope,
  fit,
  getItemLabel,
  isPrimary,
  isSelected,
  isTabStop,
  item,
  onClick,
  onContextMenu,
  onFocusLost,
  onOpen,
  onOpenInNewTab,
  onToggleStarred,
}: {
  alwaysShowDimensions: boolean;
  compareRole: string | null;
  dragItems: GalleryItemRef[];
  dragScope: string;
  fit: GalleryThumbnailFit;
  getItemLabel: ((item: GalleryItemRef) => Promise<string | null>) | null;
  isPrimary: boolean;
  isSelected: boolean;
  /** The other thumbnails are reached with the arrow keys. */
  isTabStop: boolean;
  item: GalleryItem;
  onClick: (item: GalleryItem, event: MouseEvent) => void;
  onContextMenu: (item: GalleryItem, x: number, y: number) => void;
  /** Runs once the grid has committed what replaced the tile. */
  onFocusLost: (itemKey: GalleryItemKey) => void;
  onOpen: (item: GalleryItem) => void;
  /** Null leaves the browser's middle-click behaviour alone. */
  onOpenInNewTab: ((item: GalleryItem) => void) | null;
  onToggleStarred: (item: GalleryItem) => void;
}) => {
  const { t } = useTranslation();
  const thumbnailRevision = useSyncExternalStore(
    subscribeGalleryThumbnailRevision,
    getGalleryThumbnailRevision,
    getGalleryThumbnailRevision
  );
  const baseThumbnailUrl = item.thumbnailUrl || item.fullUrl;
  // Only image thumbnails are regenerated by maintenance; either kind recovers after an image move.
  const maintainedThumbnailUrl = useMemo(
    () =>
      item.kind === 'image' ? getRefreshedGalleryThumbnailUrl(baseThumbnailUrl, thumbnailRevision) : baseThumbnailUrl,
    [baseThumbnailUrl, item.kind, thumbnailRevision]
  );
  const { onError: handleImageError, src: thumbnailUrl } = useGalleryImageRecovery(maintainedThumbnailUrl);
  const isCompared = compareRole !== null;
  const duration = item.kind === 'video' ? formatGalleryVideoDuration(item.durationSeconds) : null;

  const { isDragging, listeners, setNodeRef, transform } = useDraggable({
    data: getGalleryItemDragData(dragItems),
    id: getGalleryItemDragId(toGalleryItemRef(item), 'gallery-grid', dragScope),
  });
  const dragListeners = useMemo(
    () =>
      listeners && {
        ...listeners,
        onKeyDown: (event: KeyboardEvent) => {
          if (!isModified(event)) {
            listeners.onKeyDown?.(event);
          }
        },
      },
    [listeners]
  );

  // Portal the preview to escape the grid's overflow clipping and transformed virtual rows.
  const tileRef = useRef<HTMLDivElement | null>(null);
  const [dragOrigin, setDragOrigin] = useState<DOMRect | null>(null);

  useLayoutEffect(() => {
    const media = tileRef.current?.querySelector(GALLERY_TILE_MEDIA_SELECTOR) ?? tileRef.current;

    setDragOrigin(isDragging ? (media?.getBoundingClientRect() ?? null) : null);
  }, [isDragging]);

  const itemKey = toGalleryItemKey(item);
  // Covers the star toggle too: a star click can move the item between sections.
  const setTileRef = useCallback(
    (node: HTMLDivElement | null) => {
      tileRef.current = node;
      setNodeRef(node);

      if (!node) {
        return;
      }

      return () => {
        if (node.contains(document.activeElement)) {
          queueMicrotask(() => onFocusLost(itemKey));
        }
        tileRef.current = null;
        setNodeRef(null);
      };
    },
    [itemKey, onFocusLost, setNodeRef]
  );

  const previewStyle = useMemo(
    () =>
      dragOrigin
        ? ({
            height: `${String(dragOrigin.height)}px`,
            left: `${String(dragOrigin.left)}px`,
            pointerEvents: 'none',
            position: 'fixed',
            top: `${String(dragOrigin.top)}px`,
            // Translate only: dnd-kit's scale factors squash the preview to whatever it hovers.
            transform: CSS.Translate.toString(transform),
            width: `${String(dragOrigin.width)}px`,
            zIndex: 1500,
          } as const)
        : null,
    [dragOrigin, transform]
  );

  const letterbox = fit === 'aspect' && getGalleryTileMediaRatio(item, fit) === null;
  const imageStyle = useMemo(
    () =>
      ({
        display: 'block',
        height: '100%',
        inset: 0,
        maxWidth: 'none',
        objectFit: letterbox ? 'contain' : 'cover',
        position: 'absolute',
        width: '100%',
      }) as const,
    [letterbox]
  );

  const handleContextMenu = useCallback(
    (event: MouseEvent) => {
      event.preventDefault();

      // A long-press that armed a touch drag is drag intent: the app menu must not open under it.
      if (!isDragging) {
        onContextMenu(item, event.clientX, event.clientY);
      }
    },
    [isDragging, item, onContextMenu]
  );

  const buttonRef = useRef<HTMLButtonElement | null>(null);
  const handleClick = useCallback(
    (event: MouseEvent) => {
      const button = buttonRef.current;

      // So the grid's focused tile, Tab stop and Enter/Space follow the item just selected.
      if (button && !button.contains(event.target as Node)) {
        button.focus({ preventScroll: true });
      }
      onClick(item, event);
    },
    [item, onClick]
  );
  const handleDoubleClick = useCallback(
    (event: MouseEvent) => {
      if (!isModified(event)) {
        onOpen(item);
      }
    },
    [item, onOpen]
  );

  // Middle button only, beside the drag sensor's mousedown; its default (autoscroll) is suppressed so auxclick fires.
  const handleMouseDown = useCallback(
    (event: MouseEvent) => {
      if (onOpenInNewTab && event.button === 1) {
        event.preventDefault();
      }
      listeners?.onMouseDown?.(event);
    },
    [listeners, onOpenInNewTab]
  );
  const handleAuxClick = useCallback(
    (event: MouseEvent) => {
      if (onOpenInNewTab && event.button === 1) {
        event.preventDefault();
        event.stopPropagation();
        onOpenInNewTab(item);
      }
    },
    [item, onOpenInNewTab]
  );

  // Enter's default would click (select) first.
  const handleActivationKeyDown = useCallback(
    (event: KeyboardEvent<HTMLButtonElement>) => {
      if (isModified(event) || (event.key !== 'Enter' && event.key !== ' ')) {
        return;
      }

      event.stopPropagation();

      if (event.key === 'Enter') {
        event.preventDefault();

        if (!event.repeat) {
          onOpen(item);
        }
      }
    },
    [item, onOpen]
  );

  // Fetched on reveal, not per tile: labels cost a request each.
  const [label, setLabel] = useState<string | null>(null);
  const handleRevealLabel = useCallback(() => {
    if (getItemLabel) {
      void getItemLabel(toGalleryItemRef(item)).then(setLabel);
    }
  }, [getItemLabel, item]);

  const handleToggleStarred = useCallback(
    (event: MouseEvent<HTMLButtonElement>) => {
      event.stopPropagation();

      onToggleStarred(item);
    },
    [item, onToggleStarred]
  );

  return (
    <GalleryTileFrame
      ref={setTileRef}
      {...dragListeners}
      alwaysShowDimensions={alwaysShowDimensions}
      css={isDragging ? THUMBNAIL_DRAG_CSS : THUMBNAIL_ARMED_CSS}
      item={item}
      opacity={isDragging ? 0.4 : undefined}
      role="listitem"
      // The hold sensor yields to scrolling and arms drag only after a sustained hold.
      touchAction="pan-y"
      // On the whole cell so its letterbox gutter selects and opens like the media.
      onAuxClick={handleAuxClick}
      onClick={handleClick}
      onContextMenu={handleContextMenu}
      onDoubleClick={handleDoubleClick}
      onFocus={handleRevealLabel}
      onMouseDown={handleMouseDown}
      onPointerEnter={handleRevealLabel}
    >
      <GalleryTileMedia fit={fit} height={item.height} isSelected={isSelected || isCompared} width={item.width}>
        <button
          aria-current={isPrimary ? 'true' : undefined}
          aria-keyshortcuts="Enter"
          aria-label={
            item.kind === 'video'
              ? t('widgets.gallery.selectVideoForPreview', { duration, name: item.name })
              : t('widgets.gallery.selectImageForPreview', { name: item.name })
          }
          aria-pressed={isSelected}
          data-gallery-item-key={itemKey}
          ref={buttonRef}
          style={THUMBNAIL_BUTTON_STYLE}
          tabIndex={isTabStop ? 0 : -1}
          type="button"
          onKeyDown={handleActivationKeyDown}
        >
          <img
            alt={item.name}
            decoding={item.kind === 'video' ? 'async' : undefined}
            draggable={false}
            src={thumbnailUrl}
            style={imageStyle}
            onError={handleImageError}
          />
        </button>
      </GalleryTileMedia>
      {/* The compare role owns this corner while comparing. */}
      {label && getItemLabel && !compareRole ? (
        <Badge
          // Heuristic: keep it out of the tile's accessible text.
          aria-hidden="true"
          className="gallery-thumb-overlay"
          css={LABEL_CSS}
          insetInlineStart="1"
          maxW={LABEL_MAX_WIDTH}
          opacity={0}
          pointerEvents="none"
          position="absolute"
          top="1"
          transition="opacity var(--wb-motion-duration-medium) ease"
          variant="solid"
          zIndex="1"
        >
          <chakra.span minW="0" truncate>
            {label}
          </chakra.span>
        </Badge>
      ) : null}
      {compareRole && (
        <Badge insetInlineStart="1" pointerEvents="none" position="absolute" top="1" variant="solid" zIndex="1">
          {compareRole}
        </Badge>
      )}
      <IconButton
        aria-label={
          item.starred
            ? t('widgets.gallery.unstarImage', { name: item.name })
            : t('widgets.gallery.starImage', { name: item.name })
        }
        className="gallery-thumb-overlay"
        colorPalette={item.starred ? 'yellow' : 'gray'}
        insetInlineEnd="1"
        opacity={item.starred ? 1 : 0}
        position="absolute"
        size="sm"
        // Pointer-only: the star hotkey toggles the selection, which keyboard focus follows.
        tabIndex={-1}
        top="1"
        transition="opacity var(--wb-motion-duration-medium) ease"
        variant="solid"
        zIndex="1"
        onAuxClick={stopPropagation}
        onClick={handleToggleStarred}
        onDoubleClick={stopPropagation}
      >
        <StarIcon fill={item.starred ? 'currentColor' : 'none'} />
      </IconButton>
      {previewStyle
        ? createPortal(
            <div aria-hidden="true" style={previewStyle}>
              <img alt="" src={thumbnailUrl} style={PREVIEW_IMAGE_STYLE} />
            </div>,
            document.body
          )
        : null}
    </GalleryTileFrame>
  );
};

/** One stable callback rather than recreated payload arrays. */
export const GalleryThumbnailCell = ({
  getDragItems,
  item,
  onClick,
  selectionPage,
  ...props
}: Omit<Parameters<typeof GalleryThumbnail>[0], 'dragItems' | 'onClick'> & {
  getDragItems: (item: GalleryItem) => GalleryItemRef[];
  onClick: (item: GalleryItem, event: MouseEvent, selectionPage?: number) => void;
  selectionPage?: number;
}) => {
  const dragItems = useMemo(() => getDragItems(item), [getDragItems, item]);
  const handleClick = useCallback(
    (clickedItem: GalleryItem, event: MouseEvent) => onClick(clickedItem, event, selectionPage),
    [onClick, selectionPage]
  );

  return <GalleryThumbnail {...props} dragItems={dragItems} item={item} onClick={handleClick} />;
};