355 lines
14 KiB
TypeScript
355 lines
14 KiB
TypeScript
"use client";
|
|
/* eslint-disable @next/next/no-img-element -- generated image URLs, not optimisable */
|
|
import { withBase } from "@/lib/base-path";
|
|
|
|
import { useState, useEffect } from "react";
|
|
import Link from "next/link";
|
|
import { Icon } from "./Icon";
|
|
import { Notice } from "./ui";
|
|
import { IMAGE_PROMPT_MAX, IMAGE_SIZES, type ImageSizeKey } from "@/lib/ai/image-shared";
|
|
// (server-only helpers live in lib/ai/image.ts — never import that file here)
|
|
|
|
type OverlayPos = "top" | "center" | "bottom";
|
|
|
|
let sarabunFontPromise: Promise<FontFace> | null = null;
|
|
|
|
function loadSarabunFont() {
|
|
if (!sarabunFontPromise) {
|
|
const font = new FontFace("Sarabun", `url(${withBase("/fonts/sarabun/Sarabun-Bold.ttf")})`, { weight: "700" });
|
|
sarabunFontPromise = font.load().then((loaded) => {
|
|
document.fonts.add(loaded);
|
|
return loaded;
|
|
});
|
|
}
|
|
return sarabunFontPromise;
|
|
}
|
|
|
|
function wrapText(ctx: CanvasRenderingContext2D, text: string, maxWidth: number): string[] {
|
|
const lines: string[] = [];
|
|
const paragraphs = text.split("\n");
|
|
for (const para of paragraphs) {
|
|
const words = para.split(" ");
|
|
let current = "";
|
|
for (const w of words) {
|
|
const test = current ? `${current} ${w}` : w;
|
|
if (ctx.measureText(test).width > maxWidth && current) {
|
|
lines.push(current);
|
|
current = w;
|
|
} else {
|
|
current = test;
|
|
}
|
|
}
|
|
if (current) lines.push(current);
|
|
}
|
|
return lines;
|
|
}
|
|
|
|
function buildComposite(imgUrl: string, text: string, pos: OverlayPos): Promise<string> {
|
|
return new Promise((resolve, reject) => {
|
|
const img = new Image();
|
|
img.onload = async () => {
|
|
try { await loadSarabunFont(); } catch { /* Canvas will use the Thai fallback font. */ }
|
|
const canvas = document.createElement("canvas");
|
|
canvas.width = img.naturalWidth;
|
|
canvas.height = img.naturalHeight;
|
|
const ctx = canvas.getContext("2d");
|
|
if (!ctx) { reject(new Error("no canvas context")); return; }
|
|
ctx.drawImage(img, 0, 0);
|
|
|
|
const fontSize = Math.max(28, Math.round(img.naturalHeight * 0.065));
|
|
ctx.font = `bold ${fontSize}px 'Sarabun', 'Noto Sans Thai', 'Prompt', sans-serif`;
|
|
const maxW = img.naturalWidth * 0.84;
|
|
const lines = wrapText(ctx, text.trim(), maxW);
|
|
const lineH = fontSize * 1.55;
|
|
const pad = fontSize * 1.1;
|
|
const zoneH = lines.length * lineH + pad * 2;
|
|
|
|
let zoneY: number;
|
|
if (pos === "top") zoneY = 0;
|
|
else if (pos === "bottom") zoneY = img.naturalHeight - zoneH;
|
|
else zoneY = (img.naturalHeight - zoneH) / 2;
|
|
|
|
const grad = ctx.createLinearGradient(0, zoneY, 0, zoneY + zoneH);
|
|
if (pos === "top") {
|
|
grad.addColorStop(0, "rgba(0,0,0,0.48)");
|
|
grad.addColorStop(1, "rgba(0,0,0,0)");
|
|
} else if (pos === "bottom") {
|
|
grad.addColorStop(0, "rgba(0,0,0,0)");
|
|
grad.addColorStop(1, "rgba(0,0,0,0.48)");
|
|
} else {
|
|
grad.addColorStop(0, "rgba(0,0,0,0)");
|
|
grad.addColorStop(0.15, "rgba(0,0,0,0.42)");
|
|
grad.addColorStop(0.85, "rgba(0,0,0,0.42)");
|
|
grad.addColorStop(1, "rgba(0,0,0,0)");
|
|
}
|
|
ctx.fillStyle = grad;
|
|
ctx.fillRect(0, zoneY, img.naturalWidth, zoneH);
|
|
|
|
ctx.fillStyle = "#ffffff";
|
|
ctx.textAlign = "center";
|
|
ctx.shadowColor = "rgba(0,0,0,0.35)";
|
|
ctx.shadowBlur = fontSize * 0.28;
|
|
ctx.shadowOffsetY = 2;
|
|
|
|
const textStartY = pos === "top" ? pad + fontSize : zoneY + pad + fontSize;
|
|
lines.forEach((line, i) => {
|
|
ctx.fillText(line, img.naturalWidth / 2, textStartY + i * lineH);
|
|
});
|
|
|
|
canvas.toBlob(
|
|
(blob) => {
|
|
if (!blob) { reject(new Error("toBlob failed")); return; }
|
|
resolve(URL.createObjectURL(blob));
|
|
},
|
|
"image/jpeg",
|
|
0.93,
|
|
);
|
|
};
|
|
img.onerror = reject;
|
|
img.src = imgUrl;
|
|
});
|
|
}
|
|
|
|
async function post(body: Record<string, unknown>): Promise<{ ok: true; data: Record<string, unknown> } | { ok: false; error: string }> {
|
|
const res = await fetch(withBase("/api/ai/image"), {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify(body),
|
|
}).catch(() => null);
|
|
const data = res ? await res.json().catch(() => ({})) : {};
|
|
if (!res?.ok) return { ok: false, error: (data.error as string) ?? "AI ทำงานไม่สำเร็จ ลองใหม่อีกครั้ง" };
|
|
return { ok: true, data };
|
|
}
|
|
|
|
/**
|
|
* Two explicit steps: AI drafts an image prompt the user can edit, then a
|
|
* second press makes the image. The chosen image only fills the editor —
|
|
* saving and approval stay exactly as for an uploaded picture.
|
|
*/
|
|
export function ImageAssistant({
|
|
pageId,
|
|
initialIdea,
|
|
hasImage,
|
|
onUse,
|
|
}: {
|
|
pageId: string;
|
|
initialIdea: string;
|
|
hasImage: boolean;
|
|
onUse: (url: string) => void;
|
|
}) {
|
|
const [hasPrompt, setHasPrompt] = useState(false);
|
|
const [open, setOpen] = useState(false);
|
|
const [idea, setIdea] = useState("");
|
|
const [prompt, setPrompt] = useState("");
|
|
const [size, setSize] = useState<ImageSizeKey>("square");
|
|
const [result, setResult] = useState<string | null>(null);
|
|
const [busy, setBusy] = useState<"prompt" | "generate" | "overlay" | null>(null);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [profileMissing, setProfileMissing] = useState(false);
|
|
const [overlayText, setOverlayText] = useState("");
|
|
const [overlayPos, setOverlayPos] = useState<OverlayPos>("bottom");
|
|
const [overlayPreview, setOverlayPreview] = useState<string | null>(null);
|
|
|
|
async function draftPrompt() {
|
|
setBusy("prompt");
|
|
setError(null);
|
|
const r = await post({ action: "prompt", pageId, description: idea });
|
|
setBusy(null);
|
|
if (!r.ok) return setError(r.error);
|
|
setPrompt(String(r.data.prompt ?? ""));
|
|
setHasPrompt(true);
|
|
setProfileMissing(Boolean(r.data.profileMissing));
|
|
}
|
|
|
|
async function makeImage() {
|
|
setBusy("generate");
|
|
setError(null);
|
|
const r = await post({ action: "generate", pageId, prompt, size });
|
|
setBusy(null);
|
|
if (!r.ok) return setError(r.error);
|
|
setOverlayText("");
|
|
setOverlayPreview(null);
|
|
setResult(String(r.data.url ?? ""));
|
|
}
|
|
|
|
useEffect(() => {
|
|
if (!result || !overlayText.trim()) return;
|
|
let cancelled = false;
|
|
buildComposite(result, overlayText, overlayPos)
|
|
.then((url) => {
|
|
if (!cancelled) setOverlayPreview((prev) => { if (prev) URL.revokeObjectURL(prev); return url; });
|
|
})
|
|
.catch(() => {});
|
|
return () => { cancelled = true; };
|
|
}, [result, overlayText, overlayPos]);
|
|
|
|
async function handleUse() {
|
|
if (!result) return;
|
|
if (hasImage && !window.confirm("แทนที่รูปเดิมของโพสต์ด้วยรูปนี้?")) return;
|
|
|
|
if (!overlayText.trim()) {
|
|
onUse(result);
|
|
setResult(null);
|
|
setOpen(false);
|
|
return;
|
|
}
|
|
|
|
setBusy("overlay");
|
|
setError(null);
|
|
try {
|
|
const compositeUrl = overlayPreview ?? await buildComposite(result, overlayText, overlayPos);
|
|
const resp = await fetch(compositeUrl);
|
|
const blob = await resp.blob();
|
|
const file = new File([blob], "ai-image-overlay.jpg", { type: "image/jpeg" });
|
|
const form = new FormData();
|
|
form.append("pageId", pageId);
|
|
form.append("file", file);
|
|
const uploadRes = await fetch(withBase("/api/upload"), { method: "POST", body: form });
|
|
const data: Record<string, unknown> = await uploadRes.json().catch(() => ({}));
|
|
if (!uploadRes.ok) throw new Error(typeof data.error === "string" ? data.error : "อัปโหลดไม่สำเร็จ");
|
|
onUse(String(data.url));
|
|
setResult(null);
|
|
setOpen(false);
|
|
} catch (e) {
|
|
setError(e instanceof Error ? e.message : "เพิ่มข้อความบนรูปไม่สำเร็จ ลองใหม่");
|
|
} finally {
|
|
setBusy(null);
|
|
}
|
|
}
|
|
|
|
if (!open) {
|
|
return (
|
|
<button
|
|
aria-expanded={false}
|
|
type="button"
|
|
className="btn btn-ghost btn-sm self-start"
|
|
onClick={() => {
|
|
setIdea((cur) => cur || initialIdea.slice(0, 1000));
|
|
setOpen(true);
|
|
}}
|
|
>
|
|
<Icon name="sparkle" size={15} /> ให้ AI สร้างรูป
|
|
</button>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<section aria-busy={busy !== null} className="rounded-[12px] border border-line bg-board p-3.5 flex flex-col gap-3" aria-label="ผู้ช่วยสร้างรูป">
|
|
<div className="flex items-center gap-2">
|
|
<Icon name="sparkle" size={16} />
|
|
<b className="text-[14px]">ให้ AI สร้างรูป</b>
|
|
<button type="button" className="btn btn-ghost btn-sm ml-auto" disabled={busy !== null} onClick={() => setOpen(false)} aria-label="ปิดผู้ช่วยสร้างรูป">
|
|
<Icon name="x" size={14} />
|
|
</button>
|
|
</div>
|
|
|
|
<label className="field">
|
|
<span>อยากได้รูปแบบไหน</span>
|
|
<textarea
|
|
className="textarea"
|
|
rows={2}
|
|
autoFocus
|
|
disabled={busy !== null}
|
|
maxLength={1000}
|
|
value={idea}
|
|
onChange={(e) => setIdea(e.target.value)}
|
|
placeholder="เช่น เค้กช็อกโกแลตบนโต๊ะไม้ แสงธรรมชาติจากหน้าต่าง โทนอบอุ่น"
|
|
/>
|
|
</label>
|
|
<div>
|
|
<button type="button" className="btn btn-primary btn-sm" disabled={busy !== null || !idea.trim()} onClick={draftPrompt}>
|
|
<Icon name="sparkle" size={14} /> {busy === "prompt" ? "AI กำลังร่างพรอมต์…" : prompt ? "ร่างพรอมต์ใหม่" : "ร่างพรอมต์ให้"}
|
|
</button>
|
|
</div>
|
|
|
|
{hasPrompt && (
|
|
<>
|
|
<label className="field">
|
|
<span className="flex">
|
|
พรอมต์สร้างรูป (แก้ได้) <span className="ml-auto num text-ink-4">{prompt.length.toLocaleString("th-TH")}</span>
|
|
</span>
|
|
<textarea className="textarea" disabled={busy !== null} rows={6} maxLength={IMAGE_PROMPT_MAX} value={prompt} onChange={(e) => setPrompt(e.target.value)} />
|
|
</label>
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
{(Object.keys(IMAGE_SIZES) as ImageSizeKey[]).map((k) => (
|
|
<button key={k} type="button" className="chip" aria-pressed={size === k} disabled={busy !== null} onClick={() => setSize(k)}>
|
|
{IMAGE_SIZES[k].label}
|
|
</button>
|
|
))}
|
|
<button type="button" className="btn btn-primary btn-sm ml-auto" disabled={busy !== null || !prompt.trim()} onClick={makeImage}>
|
|
<Icon name="image" size={14} /> {busy === "generate" ? "กำลังสร้างรูป… (ราว 30–60 วินาที)" : result ? "สร้างใหม่" : "สร้างรูป"}
|
|
</button>
|
|
</div>
|
|
</>
|
|
)}
|
|
|
|
{busy && <p role="status" className="text-[12px] text-ink-3">{busy === "prompt" ? "กำลังร่างพรอมต์…" : "กำลังสร้างรูป กรุณารอสักครู่…"}</p>}
|
|
{error && <div role="alert"><Notice tone="red">{error}</Notice></div>}
|
|
{profileMissing && (
|
|
<p className="text-[12px] text-ink-3">
|
|
ยังไม่มีโปรไฟล์ร้าน — <Link href="/profile" className="underline">ตั้งไว้</Link> แล้วพรอมต์จะตรงกับร้านมากขึ้น
|
|
</p>
|
|
)}
|
|
|
|
{result && (
|
|
<div className="rounded-[10px] border border-line bg-paper p-2 flex flex-col gap-2">
|
|
<img
|
|
src={(overlayText.trim() && overlayPreview) ? overlayPreview : result ?? undefined}
|
|
alt="รูปที่ AI สร้าง"
|
|
className="w-full max-h-[320px] object-contain rounded-[6px] bg-board"
|
|
/>
|
|
|
|
{/* text overlay controls */}
|
|
<div className="flex flex-col gap-2 pt-1">
|
|
<label className="field">
|
|
<span className="text-[12px]">ข้อความบนภาพ <span className="text-ink-4">(ไม่บังคับ)</span></span>
|
|
<textarea
|
|
className="textarea text-[13px]"
|
|
rows={2}
|
|
maxLength={120}
|
|
disabled={busy !== null}
|
|
placeholder="เช่น โปรพิเศษวันนี้เท่านั้น!"
|
|
value={overlayText}
|
|
onChange={(e) => setOverlayText(e.target.value)}
|
|
/>
|
|
</label>
|
|
{overlayText.trim() && (
|
|
<div className="flex gap-1.5 flex-wrap">
|
|
<span className="text-[12px] text-ink-3 self-center">ตำแหน่ง:</span>
|
|
{(["top", "center", "bottom"] as OverlayPos[]).map((p) => (
|
|
<button
|
|
key={p}
|
|
type="button"
|
|
className="chip"
|
|
aria-pressed={overlayPos === p}
|
|
disabled={busy !== null}
|
|
onClick={() => setOverlayPos(p)}
|
|
>
|
|
{p === "top" ? "บน" : p === "center" ? "กลาง" : "ล่าง"}
|
|
</button>
|
|
))}
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
<div className="flex items-center gap-2">
|
|
<button
|
|
type="button"
|
|
className="btn btn-primary btn-sm"
|
|
disabled={busy !== null}
|
|
onClick={handleUse}
|
|
>
|
|
<Icon name="check" size={14} />
|
|
{busy === "overlay" ? "กำลังบันทึก…" : "ใช้รูปนี้"}
|
|
</button>
|
|
<button type="button" className="btn btn-ghost btn-sm" disabled={busy !== null} onClick={() => { setResult(null); setOverlayPreview(null); setOverlayText(""); }}>
|
|
ทิ้ง
|
|
</button>
|
|
</div>
|
|
</div>
|
|
)}
|
|
<p className="text-[11px] text-ink-4">รูปจาก AI — ตรวจให้ตรงกับสินค้าจริงก่อนส่งอนุมัติ · พรอมต์จะถูกส่งไปสร้างรูปผ่านเว็บ ChatGPT บนเครื่อง worker</p>
|
|
</section>
|
|
);
|
|
}
|