Skip to content

Open source CapCut alternative.

TypeScript
11.3 KB
Raw Blame
"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import {
  Captions,
  ChevronDown,
  Film,
  Image as ImageIcon,
  Layers,
  Music,
  Type,
} from "lucide-react";
import { RenameInput } from "@/cut/components/RenameInput";
import {
  clearAssetDrag,
  setCardDragImage,
  setTemplateDragData,
  type TemplateDrag,
} from "@/cut/lib/assetDrag";
import { MEDIA_CORS } from "@/cut/lib/mediaCors";
import {
  refFromTemplate,
  useAssetDrop,
  type AssetRef,
} from "@/cut/lib/assetRef";
import { useRefCopy } from "@/cut/lib/refCopy";
import { CardActionsMenu } from "@/cut/components/CardActionsMenu";
import { cardIconButton } from "@/cut/components/iconButton";
import { formatTime } from "@/cut/lib/time";
import {
  retimeOf,
  type SpeedNode,
} from "@donkeycut/effects-kit";
import { useLabels } from "@/i18n/labels";
import type { LibraryTemplate, TemplateMedia } from "@/cut/lib/types";
import { cn } from "@/lib/utils";
import { PICKED_RING } from "@/cut/lib/assetPick";

/** A template row card: name and parts, a "…" menu (Rename / extras / Delete)
 * and an optional "+" action, both revealed on hover. Rename swaps the name
 * into an inline input. With `drag` set the card drags like any other
 * item — onto the timeline, or onto the Media/Library rail tiles. Clicking the
 * card expands it to preview what's inside: each clip, sound, and title, plus
 * a caption count. Hovering a video/image row floats a live preview (video
 * plays muted); hovering a sound row plays it aloud with a small equalizer in
 * place of the row icon. */
export function TemplateCard({
  template: t,
  mediaSrc,
  drag,
  onAdd,
  addTitle,
  onRename,
  onDelete,
  onRefDrop,
  onDragStartExtra,
  extraMenu,
  selectId,
  selected = false,
  tile,
}: {
  template: LibraryTemplate;
  /** Resolve a template media file to a playable URL (project or library). */
  mediaSrc: (fileName: string) => string;
  /** The payload this card drags; omit to make it undraggable. */
  drag?: TemplateDrag;
  /** The menu's add action, named by `addTitle`; omit it with no open project. */
  onAdd?: () => void;
  addTitle?: string;
  /** Rename and delete; omit both on a shelf that can't be written to right
   * now — the card keeps its preview and drops the menu. */
  onRename?: (name: string) => void;
  onDelete?: () => void;
  /** When set, the card accepts media drops (cards and timeline clips) —
   * filter by `ref.scope` and append the item to the template. */
  onRefDrop?: (ref: AssetRef) => void;
  /** Extra drag payload (e.g. a folder-move id) set alongside the template drag. */
  onDragStartExtra?: (e: React.DragEvent) => void;
  /** Extra menu items rendered between Rename and Delete. */
  extraMenu?: React.ReactNode;
  /** Marks the card as sweepable by a marquee under this id, so a template
   * files into folders in the same selection as the media around it. */
  selectId?: string;
  selected?: boolean;
  /** Draw as a square file tile, the way every file is set: of this side, or
   * filling its grid cell with "fill". Absent, the card is a row. */
  tile?: number | "fill";
}) {
  const tc = useTranslations("media.templateCard");
  const shapeLabel = useLabels("shape");
  const effectLabel = useLabels("effect");
  const refDrop = useAssetDrop((r) => onRefDrop?.(r));
  // ⌘C over the card copies its mention token, so a saved arrangement can be
  // named in a prompt the same way a clip or an effect is.
  const copyRef = useRefCopy(() => [refFromTemplate(t)]);
  const [renaming, setRenaming] = useState(false);
  const [expanded, setExpanded] = useState(false);
  const [preview, setPreview] = useState<{
    media: TemplateMedia;
    top: number;
    left: number;
  } | null>(null);
  // Hovered audio row: plays aloud with the row's icon swapped for a small
  // equalizer — sound needs no floating preview.
  const [audioRow, setAudioRow] = useState<number | null>(null);

  const itemCount =
    t.layers.length + t.audio.length + t.texts.length + t.cues.length;

  // The contents, one row per item, in save order: clips and stills, sounds,
  // titles, then a caption count.
  const speedLen = (x: {
    in: number;
    out: number;
    speed?: number;
    speedCurve?: SpeedNode[];
    reverse?: boolean;
  }) => retimeOf(x).len;
  const parts: {
    icon: typeof Film;
    label: string;
    time?: number;
    media?: TemplateMedia;
  }[] = [
    ...t.layers.map((l) => ({
      icon: t.media[l.media]?.type === "image" ? ImageIcon : Film,
      label: t.media[l.media]?.name ?? tc("media"),
      time: speedLen(l),
      media: t.media[l.media],
    })),
    ...t.audio.map((a) => ({
      icon: Music,
      label: t.media[a.media]?.name ?? tc("audio"),
      time: speedLen(a),
      media: t.media[a.media],
    })),
    ...t.texts.map((o) => ({
      icon: Type,
      label:
        o.kind === "shape"
          ? shapeLabel(o.shape)
          : o.kind === "sticker"
            ? tc("sticker")
            : o.kind === "effect"
              ? effectLabel(o.effect)
              : o.text || tc("title"),
      time: o.end - o.start,
    })),
    ...(t.cues.length
      ? [
          {
            icon: Captions,
            label: tc("captions", { count: t.cues.length }),
          },
        ]
      : []),
  ];

  const nameEl = renaming ? (
    <RenameInput
      value={t.name}
      onDone={(name) => {
        setRenaming(false);
        if (name) onRename?.(name);
      }}
    />
  ) : (
    <div className="truncate text-[12px] font-medium">{t.name}</div>
  );
  const metaEl = (
    <div className="flex items-center gap-0.5 text-[10.5px] whitespace-nowrap text-muted-foreground">
      {tc("meta", { duration: formatTime(t.duration), count: itemCount })}
      <ChevronDown
        className={cn("size-3 transition-transform", expanded && "rotate-180")}
      />
    </div>
  );
  const actionsEl = (
    <CardActionsMenu
      label={tc("options")}
      // A tile floats the scrim pill in its corner; a light row takes the
      // row's own control.
      className={tile ? "absolute top-1.5 right-1.5" : cardIconButton}
      onUse={onAdd}
      useTitle={addTitle ?? tc("add")}
      onRename={onRename && (() => setRenaming(true))}
      extra={extraMenu}
      onDelete={onDelete}
    />
  );

  return (
    <div
      ref={(el) => {
        if (onRefDrop) refDrop.attachTarget(el);
        copyRef(el);
      }}
      {...(onRefDrop ? refDrop.targetProps : {})}
      data-sel-id={selectId}
      style={typeof tile === "number" ? { width: tile, height: tile } : undefined}
      className={cn(
        // A template is a file: it looks the same in both themes.
        "light group flex flex-col border bg-background bg-clip-padding text-foreground",
        tile ? "relative overflow-hidden rounded-xl p-2.5 shadow-sm" : "rounded-lg px-2.5 py-1.5",
        tile === "fill" && "aspect-square w-full",
        selected ? PICKED_RING : "border-page-border",
        drag ? "cursor-grab active:cursor-grabbing" : "cursor-pointer",
        onRefDrop && refDrop.active && "border-primary bg-primary/10",
      )}
      draggable={!!drag && !renaming}
      onDragStart={(e) => {
        if (!drag) return;
        setTemplateDragData(e, drag);
        onDragStartExtra?.(e);
        setCardDragImage(e, e.currentTarget);
      }}
      onDragEnd={clearAssetDrag}
      onClick={(e) => {
        // Buttons and the rename input own their clicks; the card body toggles.
        if ((e.target as HTMLElement).closest("button,input")) return;
        setExpanded((v) => !v);
      }}
    >
      {tile ? (
        <>
          <div className="min-w-0 pt-0.5">{nameEl}</div>
          {actionsEl}
        </>
      ) : (
        <div className="flex items-center gap-2">
          <Layers className="size-3.5 shrink-0 text-violet-500" />
          <div className="min-w-0 flex-1">
            {nameEl}
            {metaEl}
          </div>
          {actionsEl}
        </div>
      )}
      {tile && !(expanded && parts.length > 0) && (
        <div className="grid min-h-0 flex-1 place-items-center">
          <Layers className="size-[80%] text-violet-500" strokeWidth={1.5} />
        </div>
      )}
      {expanded && parts.length > 0 && (
        <div
          className={cn(
            "mt-1.5 flex flex-col gap-1 border-t border-border pt-1.5",
            tile && "min-h-0 flex-1 overflow-y-auto",
          )}
        >
          {parts.map(({ icon: Icon, label, time, media }, i) => (
            <div
              key={i}
              className={cn(
                "-mx-1 flex min-w-0 shrink-0 items-center gap-1.5 rounded-md px-1 py-0.5 text-[11px] text-muted-foreground",
                media && "hover:bg-muted/60 hover:text-foreground",
              )}
              onMouseEnter={(e) => {
                if (!media) return;
                if (media.type === "audio") {
                  setAudioRow(i);
                  return;
                }
                const r = e.currentTarget.getBoundingClientRect();
                setPreview({
                  media,
                  top: Math.max(
                    8,
                    Math.min(r.top - 8, window.innerHeight - 160),
                  ),
                  left: Math.min(r.right + 10, window.innerWidth - 200),
                });
              }}
              onMouseLeave={() => {
                setPreview(null);
                setAudioRow((v) => (v === i ? null : v));
              }}
            >
              {audioRow === i && media ? (
                <span className="flex size-3 shrink-0 items-center justify-center gap-[1.5px] text-[#0F6E56]">
                  {[0, 1, 2].map((b) => (
                    <span
                      key={b}
                      className="tpl-eq-bar w-[2px] rounded-full bg-current"
                      style={{ animationDelay: `${b * 0.13}s` }}
                    />
                  ))}
                  <audio src={mediaSrc(media.fileName)} autoPlay />
                  <style>{`@keyframes tpl-eq{0%,100%{height:25%}50%{height:85%}}.tpl-eq-bar{height:30%;animation:tpl-eq .8s ease-in-out infinite}`}</style>
                </span>
              ) : (
                <Icon className="size-3 shrink-0" />
              )}
              <span className="min-w-0 flex-1 truncate">{label}</span>
              {time != null && (
                <span className="shrink-0 font-mono text-[10px] tabular-nums">
                  {formatTime(time)}
                </span>
              )}
            </div>
          ))}
        </div>
      )}
      {tile && <div className="pt-1">{metaEl}</div>}
      {preview && (
        <div
          className="pointer-events-none fixed z-50"
          style={{ top: preview.top, left: preview.left }}
        >
          {preview.media.type === "video" ? (
            <video
              crossOrigin={MEDIA_CORS}
              src={mediaSrc(preview.media.fileName)}
              autoPlay
              muted
              loop
              playsInline
              className="w-44 rounded-lg border border-border bg-black shadow-lg"
            />
          ) : (
            // eslint-disable-next-line @next/next/no-img-element -- engine media file, not Next-optimizable
            <img
              crossOrigin={MEDIA_CORS}
              src={mediaSrc(preview.media.fileName)}
              alt={preview.media.name}
              className="w-44 rounded-lg border border-border shadow-lg"
            />
          )}
        </div>
      )}
    </div>
  );
}