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.

Brand kits from product links: named after the product's brand, matched by host and port; chat list above the box

Claude6e2853ca7901
diff --git a/src/components/ads/ad-chat.tsx b/src/components/ads/ad-chat.tsx
index d8099ef4..2af63525 100644
--- a/src/components/ads/ad-chat.tsx
+++ b/src/components/ads/ad-chat.tsx
@@ -1,21 +1,64 @@
"use client";
-import { ArrowUp, AtSign, Check, Loader2, MoreHorizontal, Sparkles, Trash2, X } from "lucide-react";
-import { useEffect, useId, useRef, useState, useSyncExternalStore } from "react";
+import {
+ ArrowUp,
+ AtSign,
+ Check,
+ Loader2,
+ MoreHorizontal,
+ Sparkles,
+ Trash2,
+ X,
+} from "lucide-react";
+import {
+ useEffect,
+ useId,
+ useRef,
+ useState,
+ useSyncExternalStore,
+} from "react";
import { toast } from "sonner";
-import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
-import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
-import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import {
+ Popover,
+ PopoverAnchor,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
import type { BrandKit, Product } from "@/lib/catalog/marketing";
import { formatCost } from "@/lib/format";
import { cn } from "@/lib/utils";
-import { useBrandChat, useEstimate, type ChatMessage } from "@/components/marketing/hooks";
+import {
+ useBrandChat,
+ useEstimate,
+ type ChatMessage,
+} from "@/components/marketing/hooks";
import { insertMention, mentionMatches, mentionQuery } from "./mention";
import { RoutePicker, type AdRouteChoice } from "./new-ads";
const NAME_KEY = "fuobe:first-name";
-const CHIPS = ["A lifestyle ad with the product in everyday use", "A clean studio shot with a bold headline", "A playful, colorful ad for social media"];
-const PLACEHOLDERS = ["Generate 4 ads for my product…", "Change the background to a holiday setting for our winter sale…", "Make 4 ad variations to A/B test…", "Write 5 versions with different headlines and CTAs…", "Tag your product with @…"];
+const CHIPS = [
+ "A lifestyle ad with the product in everyday use",
+ "A clean studio shot with a bold headline",
+ "A playful, colorful ad for social media",
+];
+const PLACEHOLDERS = [
+ "Generate 4 ads for my product…",
+ "Change the background to a holiday setting for our winter sale…",
+ "Make 4 ad variations to A/B test…",
+ "Write 5 versions with different headlines and CTAs…",
+ "Tag your product with @…",
+];
const nameListeners = new Set<() => void>();
function readName() {
@@ -45,21 +88,53 @@ function useFirstName(): [string, (n: string) => void] {
];
}
-function Proposal({ msg, brand, products, engine, choice, onConfirmed }: { msg: ChatMessage; brand: BrandKit; products: Product[]; engine: "cloud" | "open"; choice: AdRouteChoice; onConfirmed: (batchId: string) => void }) {
+function Proposal({
+ msg,
+ brand,
+ products,
+ engine,
+ choice,
+ onConfirmed,
+}: {
+ msg: ChatMessage;
+ brand: BrandKit;
+ products: Product[];
+ engine: "cloud" | "open";
+ choice: AdRouteChoice;
+ onConfirmed: (batchId: string) => void;
+}) {
const { confirm } = useBrandChat(brand.id);
const p = msg.proposal!;
const total = p.items.reduce((n, i) => n + i.count, 0);
// The same route as New ads (Higgsfield's one-shot ads only when that's what's picked there).
const route = choice.route;
const ratio = route === "higgsfield" ? choice.ratio : undefined;
- const est = useEstimate<{ costUsd: number | null; demo: boolean }>("/api/ads/estimate", msg.batchId ? null : { brandId: brand.id, engine, items: p.items, direction: p.direction, route, ratio });
- const names = p.items.map((i) => products.find((x) => x.id === i.productId)?.name).filter(Boolean);
+ const est = useEstimate<{ costUsd: number | null; demo: boolean }>(
+ "/api/ads/estimate",
+ msg.batchId
+ ? null
+ : {
+ brandId: brand.id,
+ engine,
+ items: p.items,
+ direction: p.direction,
+ route,
+ ratio,
+ },
+ );
+ const names = p.items
+ .map((i) => products.find((x) => x.id === i.productId)?.name)
+ .filter(Boolean);
return (
<div className="mt-2 rounded-xl border bg-background p-3">
<p className="text-[13px] font-medium">
{total} ad{total === 1 ? "" : "s"} for {names.join(", ") || brand.name}
</p>
- {p.direction && <p className="mt-0.5 line-clamp-2 text-[12px] text-muted-foreground">{p.direction}</p>}
+ {p.direction && (
+ <p className="mt-0.5 line-clamp-2 text-[12px] text-muted-foreground">
+ {p.direction}
+ </p>
+ )}
{msg.batchId ? (
<p className="mt-2 inline-flex items-center gap-1 text-[12px] text-success">
<Check className="size-3.5" /> On their way to the grid
@@ -76,14 +151,29 @@ function Proposal({ msg, brand, products, engine, choice, onConfirmed }: { msg:
onClick={() =>
confirm.mutate(
{ messageId: msg.id, engine, route, ratio },
- { onSuccess: (r) => (toast.success(`Generating ${total} ads`, { duration: 1500 }), onConfirmed(r.batchId)), onError: (e) => toast.error((e as Error).message) },
+ {
+ onSuccess: (r) => (
+ toast.success(`Generating ${total} ads`, {
+ duration: 1500,
+ }),
+ onConfirmed(r.batchId)
+ ),
+ onError: (e) => toast.error((e as Error).message),
+ },
)
}
disabled={confirm.isPending}
className="mt-2 inline-flex h-8 items-center gap-1.5 rounded-full bg-primary px-3 text-[12px] font-medium text-primary-foreground hover:bg-primary/90"
>
- {confirm.isPending ? <Loader2 className="size-3.5 animate-spin" /> : <Sparkles className="size-3.5" />}
- Create {total} ads{est.data ? ` · ${est.data.demo ? "demo" : est.data.costUsd == null ? "" : `≈ ${formatCost(est.data.costUsd)}`}` : ""}
+ {confirm.isPending ? (
+ <Loader2 className="size-3.5 animate-spin" />
+ ) : (
+ <Sparkles className="size-3.5" />
+ )}
+ Create {total} ads
+ {est.data
+ ? ` · ${est.data.demo ? "demo" : est.data.costUsd == null ? "" : `≈ ${formatCost(est.data.costUsd)}`}`
+ : ""}
</button>
</>
)}
@@ -97,7 +187,23 @@ function Proposal({ msg, brand, products, engine, choice, onConfirmed }: { msg:
* puts "@Name" in place of what was typed. `onClose` (the phone sheet) adds a close button and moves
* "Clear chat" into a menu, so the two never sit on top of each other.
*/
-export function AdChat({ brand, products, engine, choice, onBatch, onClose, className }: { brand: BrandKit; products: Product[]; engine: "cloud" | "open"; choice: AdRouteChoice; onBatch: (batchId: string) => void; onClose?: () => void; className?: string }) {
+export function AdChat({
+ brand,
+ products,
+ engine,
+ choice,
+ onBatch,
+ onClose,
+ className,
+}: {
+ brand: BrandKit;
+ products: Product[];
+ engine: "cloud" | "open";
+ choice: AdRouteChoice;
+ onBatch: (batchId: string) => void;
+ onClose?: () => void;
+ className?: string;
+}) {
const { query, say, clear } = useBrandChat(brand.id);
const [name, setName] = useFirstName();
const [text, setText] = useState("");
@@ -111,14 +217,21 @@ export function AdChat({ brand, products, engine, choice, onBatch, onClose, clas
const messages = query.data ?? [];
const typed = menu === "typed" ? mentionQuery(text, caret) : null;
const open = menu === "button" || (menu === "typed" && !!typed);
- const matches = menu === "typed" ? mentionMatches(products, typed?.query ?? "") : products;
+ const matches =
+ menu === "typed" ? mentionMatches(products, typed?.query ?? "") : products;
const current = Math.min(active, Math.max(0, matches.length - 1));
useEffect(() => {
- const t = setInterval(() => setPh((i) => (i + 1) % PLACEHOLDERS.length), 4000);
+ const t = setInterval(
+ () => setPh((i) => (i + 1) % PLACEHOLDERS.length),
+ 4000,
+ );
return () => clearInterval(t);
}, []);
useEffect(() => {
- list.current?.scrollTo({ top: list.current.scrollHeight, behavior: "smooth" });
+ list.current?.scrollTo({
+ top: list.current.scrollHeight,
+ behavior: "smooth",
+ });
}, [messages.length, say.isPending]);
const sendText = (t: string) => {
const v = t.trim();
@@ -141,12 +254,19 @@ export function AdChat({ brand, products, engine, choice, onBatch, onClose, clas
const follow = (el: HTMLTextAreaElement) => {
const c = el.selectionStart ?? el.value.length;
setCaret(c);
- if (mentionQuery(el.value, c)) setMenu((m) => (m === "button" ? m : "typed"));
+ if (mentionQuery(el.value, c))
+ setMenu((m) => (m === "button" ? m : "typed"));
else setMenu((m) => (m === "typed" ? "closed" : m));
};
const optionId = (i: number) => `${listId}-o${i}`;
return (
- <aside className={cn("flex min-h-0 flex-col rounded-2xl border bg-background", className)} aria-label="Brand chat">
+ <aside
+ className={cn(
+ "flex min-h-0 flex-col rounded-2xl border bg-background",
+ className,
+ )}
+ aria-label="Brand chat"
+ >
<div className="flex items-center justify-between gap-2 border-b px-4 py-3">
<p className="text-[14px] font-semibold">Chat</p>
<div className="flex items-center gap-1">
@@ -154,12 +274,19 @@ export function AdChat({ brand, products, engine, choice, onBatch, onClose, clas
(onClose ? (
<DropdownMenu>
<DropdownMenuTrigger asChild>
- <button type="button" className="grid size-9 place-items-center rounded-full text-muted-foreground hover:bg-accent" aria-label="Chat options">
+ <button
+ type="button"
+ className="grid size-9 place-items-center rounded-full text-muted-foreground hover:bg-accent"
+ aria-label="Chat options"
+ >
<MoreHorizontal className="size-4" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
- <DropdownMenuItem variant="destructive" onClick={() => clear.mutate()}>
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() => clear.mutate()}
+ >
<Trash2 /> Clear chat
</DropdownMenuItem>
</DropdownMenuContent>
@@ -167,7 +294,12 @@ export function AdChat({ brand, products, engine, choice, onBatch, onClose, clas
) : (
<Tooltip>
<TooltipTrigger asChild>
- <button type="button" onClick={() => clear.mutate()} className="grid size-7 place-items-center rounded-full text-muted-foreground hover:bg-accent" aria-label="Clear chat">
+ <button
+ type="button"
+ onClick={() => clear.mutate()}
+ className="grid size-7 place-items-center rounded-full text-muted-foreground hover:bg-accent"
+ aria-label="Clear chat"
+ >
<Trash2 className="size-3.5" />
</button>
</TooltipTrigger>
@@ -175,30 +307,47 @@ export function AdChat({ brand, products, engine, choice, onBatch, onClose, clas
</Tooltip>
))}
{onClose && (
- <button type="button" onClick={onClose} className="grid size-9 place-items-center rounded-full text-muted-foreground hover:bg-accent" aria-label="Close the chat">
+ <button
+ type="button"
+ onClick={onClose}
+ className="grid size-9 place-items-center rounded-full text-muted-foreground hover:bg-accent"
+ aria-label="Close the chat"
+ >
<X className="size-4" />
</button>
)}
</div>
</div>
- <div ref={list} className="min-h-0 flex-1 space-y-3 overflow-y-auto px-4 py-4">
+ <div
+ ref={list}
+ className="min-h-0 flex-1 space-y-3 overflow-y-auto px-4 py-4"
+ >
{!messages.length && (
<div>
<p className="font-heading text-[22px] leading-tight">
- {name ? `${name}, what` : "What"} ads should we make for {brand.name}?
+ {name ? `${name}, what` : "What"} ads should we make for{" "}
+ {brand.name}?
</p>
{!name && (
<input
placeholder="Your first name (optional)"
aria-label="Your first name"
- onKeyDown={(e) => e.key === "Enter" && setName((e.target as HTMLInputElement).value)}
+ onKeyDown={(e) =>
+ e.key === "Enter" &&
+ setName((e.target as HTMLInputElement).value)
+ }
onBlur={(e) => e.target.value && setName(e.target.value)}
className="mt-2 h-8 w-full rounded-lg border bg-background px-2.5 text-[12px] outline-none focus:border-primary"
/>
)}
<div className="mt-3 flex flex-col gap-1.5">
{CHIPS.map((c) => (
- <button key={c} type="button" onClick={() => sendText(c)} className="rounded-xl bg-secondary px-3 py-2 text-left text-[13px] hover:bg-accent">
+ <button
+ key={c}
+ type="button"
+ onClick={() => sendText(c)}
+ className="rounded-xl bg-secondary px-3 py-2 text-left text-[13px] hover:bg-accent"
+ >
{c}
</button>
))}
@@ -206,111 +355,183 @@ export function AdChat({ brand, products, engine, choice, onBatch, onClose, clas
</div>
)}
{messages.map((m) => (
- <div key={m.id} className={cn("flex", m.role === "user" ? "justify-end" : "justify-start")}>
- <div className={cn("max-w-[88%] rounded-2xl px-3 py-2 text-[13px] leading-relaxed", m.role === "user" ? "bg-brand-faint text-foreground" : "bg-muted")}>
+ <div
+ key={m.id}
+ className={cn(
+ "flex",
+ m.role === "user" ? "justify-end" : "justify-start",
+ )}
+ >
+ <div
+ className={cn(
+ "max-w-[88%] rounded-2xl px-3 py-2 text-[13px] leading-relaxed",
+ m.role === "user"
+ ? "bg-brand-faint text-foreground"
+ : "bg-muted",
+ )}
+ >
<p className="whitespace-pre-wrap">{m.text}</p>
- {m.role === "assistant" && m.proposal && <Proposal msg={m} brand={brand} products={products} engine={engine} choice={choice} onConfirmed={onBatch} />}
+ {m.role === "assistant" && m.proposal && (
+ <Proposal
+ msg={m}
+ brand={brand}
+ products={products}
+ engine={engine}
+ choice={choice}
+ onConfirmed={onBatch}
+ />
+ )}
</div>
</div>
))}
{say.isPending && (
<div className="flex justify-start">
<span className="rounded-2xl bg-muted px-3 py-2 text-[13px]">
- <span className="shimmer-text animate-shimmer-text">Thinking…</span>
+ <span className="shimmer-text animate-shimmer-text">
+ Thinking…
+ </span>
</span>
</div>
)}
</div>
<div className="border-t p-2.5">
- <div className="rounded-2xl border bg-background p-1.5 focus-within:border-primary focus-within:ring-4 focus-within:ring-brand-faint">
- <textarea
- ref={box}
- value={text}
- onChange={(e) => {
- setText(e.target.value);
- setActive(0);
- follow(e.target);
- }}
- onSelect={(e) => follow(e.currentTarget)}
- onKeyDown={(e) => {
- if (open && menu === "typed" && matches.length) {
- if (e.key === "ArrowDown" || e.key === "ArrowUp") {
- e.preventDefault();
- setActive((current + (e.key === "ArrowDown" ? 1 : matches.length - 1)) % matches.length);
- return;
- }
- if ((e.key === "Enter" && !e.shiftKey) || e.key === "Tab") {
- e.preventDefault();
- insert(matches[current]);
- return;
- }
- }
- if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
- e.preventDefault();
- sendText(text);
- }
- }}
- rows={2}
- placeholder={PLACEHOLDERS[ph]}
- aria-label="Message"
- role="combobox"
- aria-autocomplete="list"
- aria-expanded={open && menu === "typed"}
- aria-controls={listId}
- aria-activedescendant={open && menu === "typed" && matches.length ? optionId(current) : undefined}
- className="w-full resize-none bg-transparent px-1.5 py-1 text-[13px] outline-none placeholder:text-subtle-foreground"
- />
- <div className="flex items-center justify-between">
- <Popover open={open} onOpenChange={(o) => setMenu(o ? "button" : "closed")}>
- <PopoverTrigger asChild>
- <button type="button" className="inline-flex h-7 items-center gap-1 rounded-full px-2 text-[12px] text-muted-foreground hover:bg-accent" aria-label="Mention a product">
- <AtSign className="size-3.5" /> Mention a product
- </button>
- </PopoverTrigger>
- <PopoverContent
- side="top"
- align="start"
- className="w-64 p-1"
- collisionPadding={12}
- // Typing "@…" keeps the focus (and the typing) in the message box.
- onOpenAutoFocus={(e) => menu === "typed" && e.preventDefault()}
- onCloseAutoFocus={(e) => {
- e.preventDefault();
- box.current?.focus();
+ {/* The product list opens above the whole box, so what's typed stays in view. */}
+ <Popover
+ open={open}
+ onOpenChange={(o) => setMenu(o ? "button" : "closed")}
+ >
+ <PopoverAnchor asChild>
+ <div className="rounded-2xl border bg-background p-1.5 focus-within:border-primary focus-within:ring-4 focus-within:ring-brand-faint">
+ <textarea
+ ref={box}
+ value={text}
+ onChange={(e) => {
+ setText(e.target.value);
+ setActive(0);
+ follow(e.target);
}}
- onInteractOutside={(e) => e.target === box.current && e.preventDefault()}
- >
- <div id={listId} role="listbox" aria-label="Products">
- {matches.length ? (
- matches.map((p, i) => (
- <button
- key={p.id}
- id={optionId(i)}
- type="button"
- role="option"
- aria-selected={menu === "typed" && i === current}
- onMouseDown={(e) => menu === "typed" && e.preventDefault()}
- onClick={() => insert(p)}
- className={cn("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[13px] hover:bg-accent", menu === "typed" && i === current && "bg-accent")}
- >
- <span className="size-6 shrink-0 overflow-hidden rounded bg-muted">
- {/* eslint-disable-next-line @next/next/no-img-element */}
- {p.images[0] && <img src={p.images[0]} alt="" className="size-full object-cover" />}
- </span>
- <span className="truncate">{p.name}</span>
- </button>
- ))
- ) : (
- <p className="p-2 text-[12px] text-muted-foreground">{products.length ? `No product matches “${typed?.query ?? ""}”.` : "No products yet."}</p>
+ onSelect={(e) => follow(e.currentTarget)}
+ onKeyDown={(e) => {
+ if (open && menu === "typed" && matches.length) {
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
+ e.preventDefault();
+ setActive(
+ (current +
+ (e.key === "ArrowDown" ? 1 : matches.length - 1)) %
+ matches.length,
+ );
+ return;
+ }
+ if ((e.key === "Enter" && !e.shiftKey) || e.key === "Tab") {
+ e.preventDefault();
+ insert(matches[current]);
+ return;
+ }
+ }
+ if (
+ e.key === "Enter" &&
+ !e.shiftKey &&
+ !e.nativeEvent.isComposing
+ ) {
+ e.preventDefault();
+ sendText(text);
+ }
+ }}
+ rows={2}
+ placeholder={PLACEHOLDERS[ph]}
+ aria-label="Message"
+ role="combobox"
+ aria-autocomplete="list"
+ aria-expanded={open && menu === "typed"}
+ aria-controls={listId}
+ aria-activedescendant={
+ open && menu === "typed" && matches.length
+ ? optionId(current)
+ : undefined
+ }
+ className="w-full resize-none bg-transparent px-1.5 py-1 text-[13px] outline-none placeholder:text-subtle-foreground"
+ />
+ <div className="flex items-center justify-between">
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ className="inline-flex h-7 items-center gap-1 rounded-full px-2 text-[12px] text-muted-foreground hover:bg-accent"
+ aria-label="Mention a product"
+ >
+ <AtSign className="size-3.5" /> Mention a product
+ </button>
+ </PopoverTrigger>
+ <button
+ type="button"
+ onClick={() => sendText(text)}
+ disabled={!text.trim() || say.isPending}
+ className={cn(
+ "grid size-8 place-items-center rounded-full",
+ text.trim()
+ ? "bg-primary text-primary-foreground"
+ : "bg-muted text-subtle-foreground",
)}
- </div>
- </PopoverContent>
- </Popover>
- <button type="button" onClick={() => sendText(text)} disabled={!text.trim() || say.isPending} className={cn("grid size-8 place-items-center rounded-full", text.trim() ? "bg-primary text-primary-foreground" : "bg-muted text-subtle-foreground")} aria-label="Send">
- <ArrowUp className="size-4" />
- </button>
- </div>
- </div>
+ aria-label="Send"
+ >
+ <ArrowUp className="size-4" />
+ </button>
+ </div>
+ </div>
+ </PopoverAnchor>
+ <PopoverContent
+ side="top"
+ align="start"
+ className="w-[var(--radix-popover-trigger-width)] min-w-56 max-w-80 p-1"
+ collisionPadding={12}
+ // Typing "@…" keeps the focus (and the typing) in the message box.
+ onOpenAutoFocus={(e) => menu === "typed" && e.preventDefault()}
+ onCloseAutoFocus={(e) => {
+ e.preventDefault();
+ box.current?.focus();
+ }}
+ onInteractOutside={(e) =>
+ e.target === box.current && e.preventDefault()
+ }
+ >
+ <div id={listId} role="listbox" aria-label="Products">
+ {matches.length ? (
+ matches.map((p, i) => (
+ <button
+ key={p.id}
+ id={optionId(i)}
+ type="button"
+ role="option"
+ aria-selected={menu === "typed" && i === current}
+ onMouseDown={(e) => menu === "typed" && e.preventDefault()}
+ onClick={() => insert(p)}
+ className={cn(
+ "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[13px] hover:bg-accent",
+ menu === "typed" && i === current && "bg-accent",
+ )}
+ >
+ <span className="size-6 shrink-0 overflow-hidden rounded bg-muted">
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ {p.images[0] && (
+ <img
+ src={p.images[0]}
+ alt=""
+ className="size-full object-cover"
+ />
+ )}
+ </span>
+ <span className="truncate">{p.name}</span>
+ </button>
+ ))
+ ) : (
+ <p className="p-2 text-[12px] text-muted-foreground">
+ {products.length
+ ? `No product matches “${typed?.query ?? ""}”.`
+ : "No products yet."}
+ </p>
+ )}
+ </div>
+ </PopoverContent>
+ </Popover>
</div>
</aside>
);
diff --git a/src/server/brand.ts b/src/server/brand.ts
index 2af945f2..538c582c 100644
--- a/src/server/brand.ts
+++ b/src/server/brand.ts
@@ -1308,7 +1308,7 @@ export interface LinkRead {
const siteHost = (url: string | undefined) => {
try {
- return url ? new URL(url).hostname.replace(/^www\./, "").toLowerCase() : "";
+ return url ? new URL(url).host.replace(/^www\./, "").toLowerCase() : "";
} catch {
return "";
}
@@ -1390,7 +1390,9 @@ export async function readProductLink(input: { url: string; brandId?: string | n
? saveFile({ data: Buffer.from(facts.svgLogo), contentType: "image/svg+xml", name: `${facts.host}-logo.svg`, source: "upload" }).url
: await firstSaved(facts.logos, { allowSvg: true, minBytes: 300 });
const f = extractFonts(page.text, css);
- brand = { name: facts.organization?.name ?? facts.name, logo: logo ?? undefined, colors: extractColors(css, facts.themeColor), fonts: { heading: f.heading, body: f.body } };
+ // A product page's title is the product ("Dew Theory Barrier Cream – 50 ml"): the product's own brand names the kit first.
+ const productBrand = drafts.find((d) => d.brand)?.brand;
+ brand = { name: facts.organization?.name ?? productBrand ?? facts.name, logo: logo ?? undefined, colors: extractColors(css, facts.themeColor), fonts: { heading: f.heading, body: f.body } };
}
// A product read with its brand (and no brand chosen) joins the kit for that site, made now if there's none,
// so the logo and colours stay with the product and reach every flow that uses it.
diff --git a/tests/marketing-api.test.ts b/tests/marketing-api.test.ts
index 8998d15e..05da88c9 100644
--- a/tests/marketing-api.test.ts
+++ b/tests/marketing-api.test.ts
@@ -210,6 +210,31 @@ describe("brand kits", () => {
expect((await productRoute.DELETE(json("DELETE"), params({ id: p.id }))).status).toBe(204);
});
+ it("reads a product link on a new site into a new brand kit named after the product's brand", async () => {
+ // A second shop (another host:port): no kit yet, so one is made from the page.
+ const other = http.createServer((req, res) => {
+ const body = req.url === "/products/barrier-cream" ? local(fx("product-page.html")) : req.url?.endsWith(".jpg") ? PNG : "";
+ res.writeHead(body ? 200 : 404, { "Content-Type": req.url?.endsWith(".jpg") ? "image/jpeg" : "text/html" });
+ res.end(body);
+ });
+ await new Promise<void>((r) => other.listen(0, "127.0.0.1", r));
+ try {
+ const url = `http://127.0.0.1:${(other.address() as AddressInfo).port}/products/barrier-cream`;
+ const r = await (await readRoute.POST(json("POST", { url, withBrand: true }))).json();
+ expect(r.products[0]).toMatchObject({ name: "Barrier Cream", brandId: r.brandId });
+ const kit = brand.getBrand(r.brandId)!;
+ expect(kit).toMatchObject({ name: "Dew Theory", status: "ready", source: "website" });
+ expect(kit.website).toBe(new URL(url).origin + "/");
+ // The same link again is a duplicate in that kit, not a second product.
+ const again = await (await readRoute.POST(json("POST", { url, withBrand: true }))).json();
+ expect(again.duplicate?.name).toBe("Barrier Cream");
+ expect(brand.listProducts(r.brandId)).toHaveLength(1);
+ brand.deleteBrand(r.brandId);
+ } finally {
+ other.close();
+ }
+ });
+
it("keeps a product page's logo and colours in the site's brand kit (made once, then matched by host)", () => {
const bits = { name: "Dew Theory", logo: upload("logo.png"), colors: ["#112233", "#445566"], fonts: { heading: "Fraunces" } };
const made = brand.kitForSite("https://www.dewtheory.example/products/barrier-cream", bits);