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 chat: keep the codebase's formatting in the message box block

Clauded9ed8c1eb5c6
diff --git a/src/components/ads/ad-chat.tsx b/src/components/ads/ad-chat.tsx
index 2af63525..bfdb71b3 100644
--- a/src/components/ads/ad-chat.tsx
+++ b/src/components/ads/ad-chat.tsx
@@ -1,64 +1,21 @@
"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,
- PopoverAnchor,
- 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() {
@@ -88,53 +45,21 @@ 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
@@ -151,29 +76,14 @@ function Proposal({
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>
</>
)}
@@ -187,23 +97,7 @@ function Proposal({
* 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("");
@@ -217,21 +111,14 @@ export function AdChat({
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();
@@ -254,19 +141,12 @@ export function AdChat({
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">
@@ -274,19 +154,12 @@ export function AdChat({
(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>
@@ -294,12 +167,7 @@ export function AdChat({
) : (
<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>
@@ -307,47 +175,30 @@ export function AdChat({
</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>
))}
@@ -355,51 +206,24 @@ export function AdChat({
</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">
- {/* The product list opens above the whole box, so what's typed stays in view. */}
- <Popover
- open={open}
- onOpenChange={(o) => setMenu(o ? "button" : "closed")}
- >
+ {/* The product list opens above the whole box (its anchor), 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
@@ -415,11 +239,7 @@ export function AdChat({
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,
- );
+ setActive((current + (e.key === "ArrowDown" ? 1 : matches.length - 1)) % matches.length);
return;
}
if ((e.key === "Enter" && !e.shiftKey) || e.key === "Tab") {
@@ -428,11 +248,7 @@ export function AdChat({
return;
}
}
- if (
- e.key === "Enter" &&
- !e.shiftKey &&
- !e.nativeEvent.isComposing
- ) {
+ if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
e.preventDefault();
sendText(text);
}
@@ -444,35 +260,16 @@ export function AdChat({
aria-autocomplete="list"
aria-expanded={open && menu === "typed"}
aria-controls={listId}
- aria-activedescendant={
- open && menu === "typed" && matches.length
- ? optionId(current)
- : undefined
- }
+ 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"
- >
+ <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",
- )}
- aria-label="Send"
- >
+ <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>
@@ -489,9 +286,7 @@ export function AdChat({
e.preventDefault();
box.current?.focus();
}}
- onInteractOutside={(e) =>
- e.target === box.current && e.preventDefault()
- }
+ onInteractOutside={(e) => e.target === box.current && e.preventDefault()}
>
<div id={listId} role="listbox" aria-label="Products">
{matches.length ? (
@@ -504,30 +299,17 @@ export function AdChat({
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",
- )}
+ 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"
- />
- )}
+ {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>
+ <p className="p-2 text-[12px] text-muted-foreground">{products.length ? `No product matches “${typed?.query ?? ""}”.` : "No products yet."}</p>
)}
</div>
</PopoverContent>