Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

12.0 KB
Raw Blame
"use client";

import { Loader2, Save, X, Zap } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { BrandRow, kitBrand, useStoredBrand } from "@/components/motion/brand-row";
import { EasyChips, LengthSlider, SizeChips, TypeChips } from "@/components/motion/easy-chips";
import { shortenLine, TemplateFields } from "@/components/motion/fields";
import { KINETIC_FEATURE, MadeStrip } from "@/components/motion/made-strip";
import { MotionPlayer, useMotionInputs, usePlan, useScene } from "@/components/motion/player";
import { phaseLine, useMotionSave } from "@/components/motion/save";
import { MediaSlot, type SlotValue } from "@/components/studio/media-slot";
import { preloadKineticFaces } from "@/components/motion/kinetic-fonts";
import { RunPlaceChip } from "@/components/studio/run-place-chip";
import { useIsOwner } from "@/lib/api";
import type { BrandKit, MarketingTemplate } from "@/lib/catalog/marketing";
import { sceneFamilies } from "@/lib/motion/registry";
import { SHOWCASE_PHOTOS, SHOWCASE_PRODUCT_THUMBS, SHOWCASE_PRODUCTS } from "@/lib/motion/showcase";
import type { SizePreset } from "@/lib/motion/sizes";
import { initialState, ownFiles, templateLengths, templateRecipe, templateSizes, templateWords, type TemplateBrand, type TemplateState } from "@/lib/motion/template";
import { IN_BROWSER } from "@/lib/run-place";
import { cn } from "@/lib/utils";
import { renderRecipe } from "./end-card-motion";
import { useBrands } from "./hooks";
import { ProductSlot, type ProductChoice } from "./pickers";

/**
 * A Marketing template drawn by Fuobe Kinetic Motion: the person's exact words in their brand's fonts and colours,
 * playing live as they type, in the four sizes the studio posts to. Nothing is generated by a model, so it's instant
 * and free. Saving renders the clip here and keeps it in Fuobe (the Library, or an account's own runs), where it
 * downloads; anyone can fill it in and play it, and Save asks first whoever couldn't keep it.
 */

const PREVIEW_WIDTH: Record<SizePreset, string> = {
  "9:16": "max-w-[260px] sm:max-w-[320px]",
  "4:5": "max-w-[320px] sm:max-w-[420px]",
  "1:1": "max-w-[340px] sm:max-w-[440px]",
  "16:9": "max-w-full",
};

/** Fuobe's own sample pictures, by the kind of picture a template shows (a small tile each; a piece gets the full one). */
const product = (id: keyof typeof SHOWCASE_PRODUCTS, label: string) => ({ url: SHOWCASE_PRODUCTS[id], thumb: SHOWCASE_PRODUCT_THUMBS[id], label });
const SAMPLES: Record<"product" | "photo", { url: string; thumb: string; label: string }[]> = {
  product: [
    product("perfume", "Sample: perfume bottle"),
    product("heel", "Sample: red heel"),
    product("serum", "Sample: serum bottle"),
    product("nightSerum", "Sample: night serum"),
    product("lipstick", "Sample: lipstick"),
    product("card", "Sample: metal card"),
    product("headphones", "Sample: headphones"),
  ],
  photo: [
    { url: SHOWCASE_PHOTOS.portrait, thumb: SHOWCASE_PHOTOS.portrait, label: "Sample: portrait" },
    { url: SHOWCASE_PHOTOS.gown, thumb: SHOWCASE_PHOTOS.gown, label: "Sample: gold gown" },
    { url: SHOWCASE_PHOTOS.dunes, thumb: SHOWCASE_PHOTOS.dunes, label: "Sample: red dress in the dunes" },
    { url: SHOWCASE_PHOTOS.night, thumb: SHOWCASE_PHOTOS.night, label: "Sample: evening lights" },
  ],
};

export function PicturePicker({ kind = "product", value, onChange, owner }: { kind?: "product" | "photo"; value: string | null | undefined; onChange: (url: string | null) => void; owner: boolean }) {
  const samples = SAMPLES[kind];
  const fallback = samples[0].url;
  const [own, setOwn] = useState<SlotValue | null>(null);
  const [product, setProduct] = useState<ProductChoice | null>(null);
  const tile = (on: boolean) => cn("relative size-14 shrink-0 overflow-hidden rounded-xl bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring", on && "ring-2 ring-primary ring-offset-2 ring-offset-background");
  return (
    <div className="min-w-0">
      <p className="mb-1.5 text-[12px] font-medium text-muted-foreground">Picture</p>
      <div role="group" aria-label="Picture" className="flex min-w-0 flex-wrap items-center gap-2">
        {samples.map((s) => (
          <button key={s.url} type="button" aria-pressed={value === s.url} aria-label={s.label} onClick={() => onChange(s.url)} className={tile(value === s.url)}>
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img src={s.thumb} alt="" className={cn("size-full", kind === "photo" ? "object-cover" : "object-contain p-1")} />
          </button>
        ))}
        {owner ? (
          <ProductSlot
            value={product}
            onChange={(p) => {
              setProduct(p);
              onChange(p?.images[0] ?? fallback);
            }}
          />
        ) : (
          <MediaSlot
            label="Your picture"
            kind="image"
            value={own}
            onChange={(v) => {
              setOwn(v);
              if (!v) onChange(fallback);
              else if (!v.uploading && v.ref.startsWith("/api/files/")) onChange(v.ref);
            }}
          />
        )}
        <p className="min-w-0 basis-full text-[11px] text-muted-foreground">{kind === "photo" ? "A photo fills its panel; the middle stays in view." : "A cut-out on a clear background traces best; a photo gets a frame."}</p>
      </div>
    </div>
  );
}

/** The owner's kits for the Brand row (only the owner has brand kits). */
function OwnerBrand({ value, onChange, kitId, onKit }: { value: TemplateBrand; onChange: (b: TemplateBrand) => void; kitId: string | null; onKit: (id: string | null, kit?: BrandKit) => void }) {
  const kits = useBrands().data?.filter((k) => k.status !== "researching");
  return <BrandRow value={value} onChange={onChange} kits={kits} kitId={kitId} onKit={(id) => onKit(id, kits?.find((k) => k.id === id))} />;
}

export function KineticTemplate({ template: t, onClose, kitId, onKit }: { template: MarketingTemplate; onClose: () => void; kitId: string | null; onKit: (id: string | null) => void }) {
  const owner = useIsOwner();
  const [stored, setStored] = useStoredBrand();
  const kits = useBrands();
  const kit = owner && kitId ? kits.data?.find((k) => k.id === kitId) : undefined;
  const [state, setState] = useState<TemplateState>(() => initialState(t, stored));
  // The owner's kit fills the brand once it has loaded (a value changed here afterwards is for this piece only).
  const appliedKit = useRef<string | null>(null);
  useEffect(() => {
    if (!kit || appliedKit.current === kit.id) return;
    appliedKit.current = kit.id;
    setState((s) => ({ ...s, brand: kitBrand(kit) }));
  }, [kit]);

  const recipe = useMemo(() => templateRecipe(t, state), [t, state]);
  const inputs = useMotionInputs(recipe);
  const scene = useScene(recipe.scene);
  // The template's own faces are asked for while the page renders, so the first frame already has its type.
  preloadKineticFaces(sceneFamilies(recipe.scene));
  const plan = usePlan(scene, recipe, inputs);
  const sizes = templateSizes(t);
  const lengths = templateLengths(t);
  const fields = t.fields ?? [];
  const overflow = plan?.overflow ?? [];
  const brandOver = overflow.includes("brand");

  const saver = useMotionSave();
  const line = phaseLine(saver.phase);
  const words = templateWords(t, state);
  const save = () =>
    void saver.save({ recipe, feature: KINETIC_FEATURE, title: words.title, prompt: words.prompt, images: ownFiles(recipe) }, (signal, progress) => renderRecipe(recipe, inputs, { formats: ["mp4", "webm"], signal, onProgress: progress }));

  const setBrand = (b: TemplateBrand) => {
    setState((s) => ({ ...s, brand: b }));
    // Kept in this browser so the next template opens in it (a kit's values changed for one piece aren't).
    if (!kit) setStored(b);
  };

  return (
    <section aria-labelledby="kinetic-template-title" data-kinetic-template={t.id} className="min-w-0 rounded-3xl border bg-background p-3 shadow-soft sm:p-5">
      <div className="flex min-w-0 items-start gap-3">
        <div className="min-w-0 flex-1">
          <div className="flex min-w-0 flex-wrap items-center gap-2">
            <h2 id="kinetic-template-title" className="font-heading text-[24px] leading-tight">
              {t.name}
            </h2>
            <span className="inline-flex items-center gap-1 rounded-full bg-brand-faint px-2 py-0.5 text-[11px] font-medium text-brand-text">
              <Zap className="size-3" /> Instant
            </span>
            <RunPlaceChip place={IN_BROWSER} className="h-7 px-2.5 text-[12px]" />
          </div>
          <p className="mt-1 text-[13px] text-pretty text-muted-foreground">Your exact words in your brand&apos;s colours, set in the template&apos;s type or your own fonts. It plays as you type; saving keeps the clip in Fuobe, ready to download.</p>
        </div>
        <button type="button" onClick={onClose} aria-label="Close template" className="grid size-11 shrink-0 place-items-center rounded-full text-muted-foreground outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring">
          <X className="size-4" />
        </button>
      </div>

      <div className="mt-4 grid min-w-0 gap-5 md:grid-cols-[minmax(0,1.05fr)_minmax(0,1fr)]">
        <div className="min-w-0 md:sticky md:top-40 md:self-start">
          <div className={cn("mx-auto w-full", PREVIEW_WIDTH[state.size])}>
            <MotionPlayer plan={plan} sources={inputs.sources} size={recipe.size} duration={recipe.duration} fps={recipe.fps} label={`${t.name} preview: ${words.prompt}`} />
          </div>
        </div>

        <div className="min-w-0 space-y-4">
          <TemplateFields fields={fields} values={state.fields} onChange={(key, value) => setState((s) => ({ ...s, fields: { ...s.fields, [key]: value } }))} overflow={overflow} />
          {t.picture && <PicturePicker kind={t.picture} value={state.product} onChange={(url) => setState((s) => ({ ...s, product: url }))} owner={owner} />}
          {owner ? (
            <OwnerBrand
              value={state.brand}
              onChange={setBrand}
              kitId={kitId}
              onKit={(id, k) => {
                onKit(id);
                appliedKit.current = id;
                if (k) setState((s) => ({ ...s, brand: kitBrand(k) }));
              }}
            />
          ) : (
            <BrandRow value={state.brand} onChange={setBrand} />
          )}
          {brandOver && <p className="text-[12px] text-destructive">Shorten the brand name to fit</p>}
          {!recipe.scene.startsWith("end-card/") && <TypeChips value={!!state.brandFonts} onChange={(brandFonts) => setState((s) => ({ ...s, brandFonts }))} />}
          {t.easy && <EasyChips groups={t.easy} values={state.controls} onChange={(id, c) => setState((s) => ({ ...s, controls: { ...s.controls, [id]: c } }))} />}
          <SizeChips sizes={sizes} value={state.size} onChange={(size) => setState((s) => ({ ...s, size }))} />
          <LengthSlider min={lengths.min} max={lengths.max} value={recipe.duration} onChange={(duration) => setState((s) => ({ ...s, duration }))} />

          <div className="space-y-2 pt-1">
            <Button className="h-11 w-full" onClick={save} disabled={!!line || overflow.length > 0 || !plan}>
              {line ? <Loader2 className="animate-spin" /> : <Save />} {line ?? saver.label}
            </Button>
            {overflow.length > 0 && (
              <p className="text-[12px] text-muted-foreground" aria-live="polite">
                {fields
                  .filter((f) => overflow.includes(f.key))
                  .map(shortenLine)
                  .concat(brandOver ? ["Shorten the brand name to fit"] : [])
                  .join(" · ")}
              </p>
            )}
            {line && (
              <Button variant="ghost" className="h-11 w-full" onClick={saver.cancel}>
                Stop
              </Button>
            )}
          </div>
        </div>
      </div>

      <div className="mt-5 min-w-0">
        <MadeStrip templateId={t.id} />
      </div>
    </section>
  );
}