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.

Click to Ad: an End card switch with a live preview; the card is drawn in the browser

Claude5d7b401a2079
diff --git a/src/components/ads/layout.ts b/src/components/ads/layout.ts
index 6ff558e3..e4d85ee3 100644
--- a/src/components/ads/layout.ts
+++ b/src/components/ads/layout.ts
@@ -213,7 +213,7 @@ export function fitText(text: string, width: number, maxLines: number, family: s
}
}
-const textBox = (t: { size: number; lines: string[] }, x: number, y: number, family: string, weight: number, color: string, align: "left" | "center", width: number, lh = 1.12): TextBox => ({
+export const textBox = (t: { size: number; lines: string[] }, x: number, y: number, family: string, weight: number, color: string, align: "left" | "center", width: number, lh = 1.12): TextBox => ({
lines: t.lines,
x,
y,
diff --git a/src/components/marketing/click-to-ad.tsx b/src/components/marketing/click-to-ad.tsx
index 27b74534..a7067164 100644
--- a/src/components/marketing/click-to-ad.tsx
+++ b/src/components/marketing/click-to-ad.tsx
@@ -5,14 +5,18 @@ import { Check, Clapperboard, Loader2, MousePointerClick, PenLine, RefreshCw, Sp
import { useEffect, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
+import { Switch } from "@/components/ui/switch";
+import { themeFrom } from "@/components/ads/layout";
import { LogoField } from "@/components/brand/brand-kit-form";
import { areaCls, ColorList, inputCls } from "@/components/brand/fields";
import { ImageList } from "@/components/brand/image-list";
import { AddFromLink, priceText, ProductThumb, UploadProductButton } from "@/components/brand/products";
import type { SlotValue } from "@/components/studio/media-slot";
-import { AD_STYLES, KIT_LABELS, type BrandKit, type MarketingRun, type Product, type RunEstimate } from "@/lib/catalog/marketing";
+import { uploadFile } from "@/lib/api";
+import { AD_STYLES, END_CARD, KIT_LABELS, type BrandKit, type MarketingRun, type Product, type RunEstimate } from "@/lib/catalog/marketing";
import { formatCost } from "@/lib/format";
import { cn } from "@/lib/utils";
+import { endCardPng, renderEndCard, siteLabel, type EndCardInput } from "./end-card";
import { addRuns, send, useBrand, useEstimate, useProductActions, useProducts, useReadingProduct, useUpdateBrand } from "./hooks";
import type { ModelInfo } from "./model-info";
import { AvatarSlot, VoiceControl } from "./pickers";
@@ -59,6 +63,17 @@ function KitProgress() {
const styleScene = (presenter: boolean, dark?: boolean) => (presenter ? "selfie" : dark ? "noir" : "orbit");
+/** The end card as the ad will end on it, drawn small (the same drawing as the full-size PNG). */
+function EndCardPreview({ input, className }: { input: EndCardInput; className?: string }) {
+ const ref = useRef<HTMLCanvasElement>(null);
+ const key = JSON.stringify(input);
+ useEffect(() => {
+ if (ref.current) void renderEndCard(ref.current, JSON.parse(key) as EndCardInput, 0.3);
+ }, [key]);
+ const words = [input.content.brand, input.content.product, input.content.cta].filter(Boolean).join(", ");
+ return <canvas ref={ref} role="img" aria-label={`End card preview: ${words}`} className={cn("aspect-[9/16] rounded-lg border bg-muted", className)} />;
+}
+
/**
* The product kit's logo and colours, kept in the product's brand kit (made from the page when the link
* was read) so they stay after a reload and reach the video prompts. Edits save to that kit.
@@ -137,6 +152,29 @@ export function ClickToAd({ models }: { models: Record<string, ModelInfo> }) {
const withPresenter = presenter ?? style.presenter;
const [name, setName] = useState("");
const [desc, setDesc] = useState("");
+ // The logo end card: on by default when the kit has a logo (null = follow that), with its call to action.
+ const [endCardOn, setEndCardOn] = useState<boolean | null>(null);
+ const [cta, setCta] = useState<string>(END_CARD.cta);
+ const logo = brand?.logo || brandBits?.logo || null;
+ const withEndCard = endCardOn ?? !!logo;
+ const card = useMemo<EndCardInput>(
+ () => ({
+ theme: themeFrom(brand ?? (brandBits ? { colors: brandBits.colors } : null)),
+ content: { brand: brand?.name ?? "", product: name.trim() || product?.name || "", cta: cta.trim() || undefined, website: siteLabel(brand?.website ?? product?.url) },
+ logo,
+ }),
+ [brand, brandBits, name, product, cta, logo],
+ );
+ // The drawn card is uploaded once per look (a second Generate with the same card reuses it).
+ const uploadedCard = useRef<{ key: string; url: string } | null>(null);
+ const cardUrl = async () => {
+ const key = JSON.stringify(card);
+ if (uploadedCard.current?.key === key) return uploadedCard.current.url;
+ const blob = await endCardPng(card);
+ const { url } = await uploadFile(new File([blob], "end-card.png", { type: "image/png" }));
+ uploadedCard.current = { key, url };
+ return url;
+ };
const choose = (p: Product, bits?: { logo?: string; colors: string[] }) => {
setProductId(p.id);
@@ -166,9 +204,11 @@ export function ClickToAd({ models }: { models: Record<string, ModelInfo> }) {
voice,
voiceSample: sample?.ref,
avatar: withPresenter ? avatar?.ref : undefined,
+ // Priced with a stand-in; the card itself is drawn and uploaded when you generate.
+ endCard: withEndCard ? { image: "/api/files/placeholder.png" } : undefined,
}
: null,
- [engine, productId, styleId, picked, withPresenter, script, mode, instructions, quality, voice, sample, avatar],
+ [engine, productId, styleId, picked, withPresenter, script, mode, instructions, quality, voice, sample, avatar, withEndCard],
);
const est = useEstimate<RunEstimate>("/api/marketing/click-to-ad/estimate", body);
const blocker = !product ? "Select a product or enter a product URL" : !product.images.length ? `${product.name} has no images` : !desc.trim() ? "Add a description" : est.data?.blocker;
@@ -191,7 +231,8 @@ export function ClickToAd({ models }: { models: Record<string, ModelInfo> }) {
if (blocker) return void toast(blocker, { id: "c2a-blocker" });
setBusy(true);
try {
- const r = await send<{ run: MarketingRun; script: string }>("/api/marketing/click-to-ad", "POST", body);
+ const endCard = withEndCard ? { image: await cardUrl() } : undefined;
+ const r = await send<{ run: MarketingRun; script: string }>("/api/marketing/click-to-ad", "POST", { ...body, endCard });
addRuns(qc, "click-to-ad", [r.run]);
setScript(r.script);
toast.success("Creating your video", { duration: 1600 });
@@ -329,6 +370,22 @@ export function ClickToAd({ models }: { models: Record<string, ModelInfo> }) {
{withPresenter && <AvatarSlot value={avatar} onChange={setAvatar} />}
<VoiceControl engine={engine} models={models} voice={voice} sample={sample} onVoice={setVoice} onSample={setSample} />
</div>
+ <div className="flex items-start gap-3 rounded-xl border p-3">
+ <EndCardPreview input={card} className={cn("w-[72px] shrink-0 transition-opacity", !withEndCard && "opacity-40")} />
+ <div className="min-w-0 flex-1 space-y-2">
+ <div className="flex items-center justify-between gap-2">
+ <label htmlFor="c2a-end-card" className="text-[13px] font-medium">
+ End card
+ </label>
+ <Switch id="c2a-end-card" checked={withEndCard} onCheckedChange={setEndCardOn} />
+ </div>
+ <p className="text-[12px] text-muted-foreground">
+ {withEndCard ? `The ad ends on your ${logo ? "logo" : "brand name"} for ${END_CARD.seconds} s, in your brand colours.` : "The ad ends on its last shot."}
+ {!logo && " Add a logo in the product kit to show it."}
+ </p>
+ {withEndCard && <input value={cta} onChange={(e) => setCta(e.target.value.slice(0, 30))} className={inputCls} aria-label="Call to action on the end card" placeholder="Call to action, e.g. Shop now" />}
+ </div>
+ </div>
<div>
<p className="mb-1.5 text-[12px] font-medium text-muted-foreground">Video quality</p>
<div role="radiogroup" aria-label="Video quality" className="inline-flex rounded-full bg-muted p-0.5">
@@ -364,7 +421,10 @@ export function ClickToAd({ models }: { models: Record<string, ModelInfo> }) {
</div>
</div>
<div className="mt-6 flex flex-wrap items-center justify-end gap-3 border-t pt-4">
- <p className="mr-auto text-[12px] text-muted-foreground">9:16 · up to 12 s · voiceover and captions{est.data?.steps.length ? ` · ${est.data.steps.length} steps` : ""}</p>
+ <p className="mr-auto text-[12px] text-muted-foreground">
+ 9:16 · up to 12 s · voiceover and captions{withEndCard ? ` · ${END_CARD.seconds} s end card` : ""}
+ {est.data?.steps.length ? ` · ${est.data.steps.length} steps` : ""}
+ </p>
{cost && <span className="font-mono text-[13px] text-muted-foreground">{cost}</span>}
<Button size="lg" onClick={() => void generate()} aria-disabled={!!blocker || busy} className={cn(blocker && "bg-muted text-muted-foreground hover:bg-muted")} title={blocker}>
{busy ? <Loader2 className="animate-spin" /> : <Wand2 />} Generate video
diff --git a/src/components/marketing/end-card.ts b/src/components/marketing/end-card.ts
new file mode 100644
index 00000000..b56a0e5b
--- /dev/null
+++ b/src/components/marketing/end-card.ts
@@ -0,0 +1,109 @@
+import { END_CARD } from "@/lib/catalog/marketing";
+import { containIn, contrast, fitText, fontString, readableOn, textBox, type AdPlan, type AdTheme, type Measure, type Rect, type TextBox } from "../ads/layout";
+import { drawPlan, ensureFont, loadImage, measureText } from "../ads/render";
+
+/**
+ * Click to Ad's logo end card: the brand colour, the logo (or the brand's name), the product name and a
+ * call-to-action pill, centred on a 9:16 card. Laid out here (pure, tested) and drawn with the Ads Studio
+ * compositor's drawPlan, so the preview on the page and the PNG the ad ends on are the same picture.
+ */
+
+export interface EndCardContent {
+ /** Shown when the kit has no logo. */
+ brand: string;
+ product: string;
+ cta?: string;
+ /** A small line at the bottom (the shop's address). */
+ website?: string;
+}
+
+export interface EndCardLayoutInput {
+ theme: AdTheme;
+ content: EndCardContent;
+ /** The logo's pixel size (null: none, or it didn't load). */
+ logo?: { w: number; h: number } | null;
+ measure: Measure;
+ size?: { w: number; h: number };
+}
+
+/** "yourshop.com" from "https://www.yourshop.com/products/x". */
+export function siteLabel(url: string | undefined): string | undefined {
+ if (!url?.trim()) return undefined;
+ try {
+ return new URL(/^https?:\/\//i.test(url) ? url : `https://${url}`).hostname.replace(/^www\./, "");
+ } catch {
+ return undefined;
+ }
+}
+
+/** Where everything goes on the card: one centred block (logo or name, product, CTA), the address at the foot. */
+export function planEndCard(p: EndCardLayoutInput): AdPlan {
+ const { w: W, h: H } = p.size ?? END_CARD.size;
+ const t = p.theme;
+ const m = Math.round(W * 0.1);
+ const inner = W - 2 * m;
+ const ink = t.onAccent;
+ const gap = H * 0.04;
+ // Measure the block first, then centre it a little above the middle.
+ const logoH = H * 0.15;
+ const name = !p.logo && p.content.brand.trim() ? fitText(p.content.brand.trim().toUpperCase(), inner, 2, t.heading, 800, W * 0.1, W * 0.06, p.measure) : null;
+ const head = fitText(p.content.product.trim() || " ", inner, 2, t.heading, 700, W * 0.068, W * 0.045, p.measure);
+ const ctaSize = W * 0.045;
+ const label = p.content.cta?.trim() ? fitText(p.content.cta.trim(), inner - ctaSize * 2.4, 1, t.body, 700, ctaSize, W * 0.03, p.measure) : null;
+ const ctaH = label ? label.size * 2.3 : 0;
+ const top = p.logo ? logoH : name ? name.lines.length * name.size * 1.05 : 0;
+ const headH = head.lines.length * head.size * 1.12;
+ const total = top + (top ? gap : 0) + headH + (label ? gap * 1.4 + ctaH : 0);
+ let y = Math.max(m, (H - total) / 2 - H * 0.03);
+
+ let logo: Rect | undefined;
+ let brand: TextBox | undefined;
+ if (p.logo) {
+ logo = containIn(p.logo.w, p.logo.h, { x: m, y, w: inner, h: logoH }, "center");
+ y += logoH + gap;
+ } else if (name) {
+ brand = textBox(name, W / 2, y, t.heading, 800, ink, "center", inner, 1.05);
+ y += top + gap;
+ }
+ const headline = textBox(head, W / 2, y, t.heading, 700, ink, "center", inner);
+ y += headH;
+ let cta: AdPlan["cta"];
+ if (label) {
+ y += gap * 1.4;
+ const tw = p.measure(label.lines[0], fontString(t.body, label.size, 700));
+ const bw = Math.min(inner, tw + label.size * 2.4);
+ const bx = (W - bw) / 2;
+ // The pill is the text colour; its words the brand colour, or whatever reads on the pill.
+ const onPill = contrast(t.accent, ink) >= 3 ? t.accent : readableOn(ink);
+ cta = { x: bx, y, w: bw, h: ctaH, radius: ctaH / 2, color: ink, text: textBox(label, bx + bw / 2, y + (ctaH - label.size * 1.12) / 2, t.body, 700, onPill, "center", bw) };
+ }
+ const site = p.content.website?.trim() ? fitText(p.content.website.trim(), inner, 1, t.body, 500, W * 0.032, W * 0.024, p.measure) : null;
+ const body = site ? textBox(site, W / 2, H - m - site.size * 1.12, t.body, 500, ink, "center", inner) : undefined;
+ return { w: W, h: H, bg: t.accent, image: null, logo, brand, headline, body, cta };
+}
+
+export interface EndCardInput {
+ theme: AdTheme;
+ content: EndCardContent;
+ logo?: string | null;
+}
+
+/** Draw the card on `canvas` at `scale` (1 = the full 720 × 1280 card). */
+export async function renderEndCard(canvas: HTMLCanvasElement, input: EndCardInput, scale = 1): Promise<void> {
+ const [logo] = await Promise.all([input.logo ? loadImage(input.logo).catch(() => null) : null, ensureFont(input.theme.heading), ensureFont(input.theme.body)]);
+ const { w, h } = END_CARD.size;
+ canvas.width = Math.round(w * scale);
+ canvas.height = Math.round(h * scale);
+ const ctx = canvas.getContext("2d");
+ if (!ctx) return;
+ ctx.setTransform(scale, 0, 0, scale, 0, 0);
+ const plan = planEndCard({ theme: input.theme, content: input.content, logo: logo ? { w: logo.naturalWidth || 400, h: logo.naturalHeight || 120 } : null, measure: measureText });
+ drawPlan(ctx, plan, null, logo);
+}
+
+/** The full-size card as a PNG, ready to upload. */
+export async function endCardPng(input: EndCardInput): Promise<Blob> {
+ const canvas = document.createElement("canvas");
+ await renderEndCard(canvas, input, 1);
+ return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("Couldn't draw the end card"))), "image/png"));
+}
diff --git a/tests/marketing-endcard.test.ts b/tests/marketing-endcard.test.ts
index 9dc32f60..95854b23 100644
--- a/tests/marketing-endcard.test.ts
+++ b/tests/marketing-endcard.test.ts
@@ -25,6 +25,8 @@ const { saveFile } = await import("@/server/storage");
const { prepareWorkflow } = await import("@/server/providers/comfyui");
const { getModel } = await import("@/lib/catalog");
const { END_CARD, END_CARD_MODELS, endCardSteps } = await import("@/lib/catalog/marketing");
+const { planEndCard, siteLabel } = await import("@/components/marketing/end-card");
+const { themeFrom } = await import("@/components/ads/layout");
beforeAll(() => setSetting("demoMode", "auto"));
afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
@@ -188,3 +190,49 @@ describe("the open end-card workflows through the ComfyUI provider", () => {
expect(h / w).toBeCloseTo(16 / 9, 1);
});
});
+
+describe("the end card the page draws", () => {
+ // A stand-in for canvas text metrics: half the font size per character.
+ const measure = (text: string, font: string) => text.length * Number(/(\d+)px/.exec(font)![1]) * 0.5;
+ const theme = themeFrom({ colors: ["#c1121f", "#fdf0d5"], fonts: { heading: "Playfair Display" } });
+ const inside = (r: { x: number; y: number; w?: number; h?: number }, W = END_CARD.size.w, H = END_CARD.size.h) => {
+ expect(r.x).toBeGreaterThanOrEqual(0);
+ expect(r.y).toBeGreaterThanOrEqual(0);
+ expect(r.x + (r.w ?? 0)).toBeLessThanOrEqual(W);
+ expect(r.y + (r.h ?? 0)).toBeLessThanOrEqual(H);
+ };
+
+ it("centres the logo, the product name and the CTA pill on the brand colour, the address at the foot", () => {
+ const plan = planEndCard({ theme, content: { brand: "Dermaco", product: "Barrier Cream", cta: "Shop now", website: "dermaco.com" }, logo: { w: 800, h: 200 }, measure });
+ expect(plan).toMatchObject({ w: 720, h: 1280, bg: "#c1121f", image: null });
+ expect(plan.brand).toBeUndefined();
+ const { logo, headline, cta, body } = plan;
+ expect(logo!.x + logo!.w / 2).toBeCloseTo(360, 0);
+ expect(logo!.w / logo!.h).toBeCloseTo(4, 1);
+ expect(headline).toMatchObject({ lines: ["Barrier Cream"], align: "center", x: 360, color: theme.onAccent });
+ expect(headline.y).toBeGreaterThan(logo!.y + logo!.h);
+ expect(cta!.x + cta!.w / 2).toBeCloseTo(360, 0);
+ expect(cta!.y).toBeGreaterThan(headline.y + headline.lineHeight);
+ expect(cta!.color).toBe(theme.onAccent);
+ expect(cta!.text.lines).toEqual(["Shop now"]);
+ expect(body!.lines).toEqual(["dermaco.com"]);
+ expect(body!.y).toBeGreaterThan(cta!.y + cta!.h);
+ for (const r of [logo!, cta!, { x: 0, y: body!.y, h: body!.lineHeight }]) inside(r);
+ });
+
+ it("writes the brand's name when there is no logo, and leaves out a CTA nobody wrote", () => {
+ const plan = planEndCard({ theme, content: { brand: "Dermaco", product: "A very long product name that keeps going and going for a while" }, logo: null, measure });
+ expect(plan.logo).toBeUndefined();
+ expect(plan.brand!.lines).toEqual(["DERMACO"]);
+ expect(plan.cta).toBeUndefined();
+ expect(plan.headline.lines.length).toBeLessThanOrEqual(2);
+ for (const l of plan.headline.lines) expect(measure(l, plan.headline.font)).toBeLessThanOrEqual(720 - 144 + 1);
+ });
+
+ it("names the shop by its address", () => {
+ expect(siteLabel("https://www.dermaco.com/products/cream")).toBe("dermaco.com");
+ expect(siteLabel("shop.example.org")).toBe("shop.example.org");
+ expect(siteLabel(undefined)).toBeUndefined();
+ expect(siteLabel("not a url at all")).toBeUndefined();
+ });
+});