Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

9.2 KB
Raw Blame
import { internalDrag } from '@core/directive/internalDragState';

false && internalDrag;

import { SERVER_HOSTS } from '@core/constant/servers';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import Spinner from '@icon/system/bold/spinner-gap-bold.svg?component-solid';
import ExpandIcon from '@icon/system/regular/arrows-out-simple.svg';
import ClipboardIcon from '@icon/system/regular/clipboard.svg';
import ThreeDotsIcon from '@icon/system/regular/dots-three-vertical.svg';
import DownloadIcon from '@icon/system/regular/download-simple.svg';
import TrashIcon from '@icon/system/regular/trash.svg';
import { Dialog } from '@kobalte/core/dialog';
import { constrainImageDimensions } from '@macro-inc/lexical-core/utils/media';
import { Button, cn, Dropdown } from '@ui';
import { type Component, createSignal, For, Show } from 'solid-js';
import { copyImageToClipboard, downloadImage } from '../util/imageActions';
import { platformFetch } from '../util/platformFetch';
import { Lightbox } from './Lightbox';

type ImageData = {
  id: string;
  width?: string | number | undefined;
  height?: string | number | undefined;
};

/**
 * @deprecated Prefer the composable media primitives in `@channel/Media`.
 * Keep this only for legacy callers until they are migrated.
 */
type ImageGalleryPreviewProps = {
  images: ImageData[];
  initialIndex?: number;
  variant: 'small' | 'dynamic';
  square?: boolean;
  wrapperClass?: string;
  attachmentIds: string[];
  onDelete?: (attachmentId: string) => void;
  isContext?: boolean;
};

const THEMES = {
  small:
    'size-23 object-cover rounded-2xl border border-edge hover:opacity-80 select-none',
  dynamic:
    'min-w-[100px] max-h-[200px] object-contain w-full rounded-2xl select-none border border-edge hover:border-accent hover-transition-border',
};

/** Max dimensions for gallery image thumbnails */
const GALLERY_MAX_WIDTH = 200;
const GALLERY_MAX_HEIGHT = 200;

function GalleryImagePlaceholder(props: {
  dims: { width: number; height: number } | undefined;
}) {
  return (
    <div
      class="flex items-center justify-center border border-edge rounded-2xl bg-surface"
      style={
        props.dims
          ? {
              width: `${props.dims.width}px`,
              height: `${props.dims.height}px`,
            }
          : {
              width: '60px',
              height: '60px',
            }
      }
    >
      <Spinner class="size-4 animate-spin" />
    </div>
  );
}

/**
 * @deprecated Prefer the composable media primitives in `@channel/Media`.
 * Keep this only for legacy callers until they are migrated.
 */
export const ImageGalleryPreview: Component<ImageGalleryPreviewProps> = (
  props
) => {
  const [currentIndex, setCurrentIndex] = createSignal(props.initialIndex ?? 0);
  const [clickedIndex, setClickedIndex] = createSignal(0);

  const getImageUrl = (id: string) =>
    `${SERVER_HOSTS['static-file']}/file/${id}`;

  const currentImageUrl = () => {
    const id = props.images[currentIndex()]?.id;
    return id ? getImageUrl(id) : undefined;
  };

  const hasPrevious = () => currentIndex() > 0;
  const hasNext = () => currentIndex() < props.images.length - 1;

  const navigatePrevious = () => {
    if (hasPrevious()) setCurrentIndex((i) => i - 1);
  };
  const navigateNext = () => {
    if (hasNext()) setCurrentIndex((i) => i + 1);
  };

  // Thumbnail menu actions (operate on a specific image by ID)
  const copyToClipboardById = (id: string) => {
    const url = getImageUrl(id);
    return copyImageToClipboard(
      () => platformFetch(url).then((r) => r.blob()),
      url
    );
  };

  const downloadImageById = (id: string) =>
    downloadImage(
      () => platformFetch(getImageUrl(id)).then((r) => r.blob()),
      id
    );

  return (
    <Dialog
      modal={true}
      onOpenChange={(isOpen) => {
        if (isOpen) setCurrentIndex(clickedIndex());
        else setClickedIndex(0);
      }}
    >
      <div class={props.wrapperClass ?? 'flex flex-row flex-wrap gap-2'}>
        <For each={props.images}>
          {(image, index) => (
            <div class={props.variant === 'dynamic' ? 'max-w-50 w-fit' : ''}>
              <div class="flex group relative">
                <Show when={props.variant !== 'small'}>
                  <div class="group-hover:visible invisible absolute top-2 right-2 bg-surface rounded-2xl border border-edge flex flex-row items-center gap-1 z-10">
                    <Dialog.Trigger
                      onClick={() => setClickedIndex(index())}
                      disabled={props.isContext}
                    >
                      <Button variant="ghost" size="icon-md">
                        <ExpandIcon class="size-4 touch:size-6 shrink-0 pointer-events-none" />
                      </Button>
                    </Dialog.Trigger>
                    <Dropdown>
                      <Dropdown.Trigger
                        variant="ghost"
                        size="icon-md"
                        disabled={props.isContext}
                      >
                        <ThreeDotsIcon class="size-4 touch:size-6 shrink-0 pointer-events-none" />
                      </Dropdown.Trigger>
                      <Dropdown.Content>
                        <Dropdown.Group>
                          <Dropdown.Item
                            onSelect={() => copyToClipboardById(image.id)}
                          >
                            <ClipboardIcon class="size-4 shrink-0" />
                            <span class="flex-1 truncate">Copy image</span>
                          </Dropdown.Item>
                          <Dropdown.Item
                            onSelect={() => downloadImageById(image.id)}
                          >
                            <DownloadIcon class="size-4 shrink-0" />
                            <span class="flex-1 truncate">Download image</span>
                          </Dropdown.Item>
                        </Dropdown.Group>
                        <Show when={props.onDelete}>
                          <Dropdown.Group>
                            <Dropdown.Item
                              onSelect={() =>
                                props.onDelete?.(props.attachmentIds[index()])
                              }
                            >
                              <TrashIcon class="size-4 shrink-0" />
                              <span class="flex-1 truncate">Delete image</span>
                            </Dropdown.Item>
                          </Dropdown.Group>
                        </Show>
                      </Dropdown.Content>
                    </Dropdown>
                  </div>
                </Show>
                <Dialog.Trigger
                  class="flex"
                  onClick={() => setClickedIndex(index())}
                  disabled={props.isContext}
                >
                  {(() => {
                    const dims = constrainImageDimensions(
                      image.width,
                      image.height,
                      GALLERY_MAX_WIDTH,
                      GALLERY_MAX_HEIGHT
                    );
                    const [loaded, setLoaded] = createSignal(false);
                    return (
                      <>
                        <Show when={!loaded()}>
                          <GalleryImagePlaceholder dims={dims} />
                        </Show>
                        <img
                          class={cn(
                            THEMES[props.variant],
                            'select-none',
                            !loaded() && 'hidden'
                          )}
                          src={getImageUrl(image.id)}
                          alt="preview"
                          width={dims?.width}
                          height={dims?.height}
                          style={{
                            '-webkit-touch-callout': 'none',
                            '-webkit-user-select': 'none',
                            '-khtml-user-select': 'none',
                            '-moz-user-select': 'none',
                            '-ms-user-select': 'none',
                            'user-select': 'none',
                            ...(dims
                              ? {
                                  'aspect-ratio': `${dims.width} / ${dims.height}`,
                                  'max-width': `${dims.width}px`,
                                }
                              : {}),
                          }}
                          draggable={!isTouchDevice()}
                          onLoad={() => setLoaded(true)}
                          use:internalDrag={true}
                        />
                      </>
                    );
                  })()}
                </Dialog.Trigger>
              </div>
            </div>
          )}
        </For>
      </div>
      <Dialog.Portal>
        <Dialog.Overlay class="fixed inset-0 z-modal scrim-glass" />
        <Lightbox
          src={currentImageUrl}
          imageId={() => props.images[currentIndex()]?.id ?? ''}
          onPrevious={hasPrevious() ? navigatePrevious : undefined}
          onNext={hasNext() ? navigateNext : undefined}
          indexLabel={
            props.images.length > 1
              ? () => `${currentIndex() + 1}/${props.images.length}`
              : undefined
          }
        />
      </Dialog.Portal>
    </Dialog>
  );
};