Add automated content planning and image overlays
This commit is contained in:
@@ -5,15 +5,17 @@ import { withBase } from "@/lib/base-path";
|
||||
import { Notice } from "./ui";
|
||||
|
||||
type Settings = {
|
||||
enabled: boolean; weekdays: number[]; times: string[]; brief: string;
|
||||
enabled: boolean; scheduleMode: "FIXED" | "RANDOM"; weekdays: number[]; times: string[];
|
||||
randomPostsPerDay: number; articlePercent: number; knowledgePercent: number; salesPercent: number; brief: string;
|
||||
targets: ("FACEBOOK" | "INSTAGRAM")[];
|
||||
nextRunAt: string | null; lastQueuedAt: string | null; lastError: string | null;
|
||||
};
|
||||
const DAYS = ["อา.", "จ.", "อ.", "พ.", "พฤ.", "ศ.", "ส."];
|
||||
const formatTime = (value: string) => new Date(value).toLocaleString("th-TH", { timeZone: "Asia/Bangkok", dateStyle: "medium", timeStyle: "short" });
|
||||
const DEFAULT_SETTINGS: Settings = { enabled: false, scheduleMode: "FIXED", weekdays: [1, 2, 3, 4, 5], times: ["09:00"], randomPostsPerDay: 1, articlePercent: 40, knowledgePercent: 40, salesPercent: 20, brief: "", targets: ["FACEBOOK"], nextRunAt: null, lastQueuedAt: null, lastError: null };
|
||||
|
||||
export function ContentAutoForm({ pageId }: { pageId: string }) {
|
||||
const [settings, setSettings] = useState<Settings>({ enabled: false, weekdays: [1, 2, 3, 4, 5], times: ["09:00"], brief: "", targets: ["FACEBOOK"], nextRunAt: null, lastQueuedAt: null, lastError: null });
|
||||
const [settings, setSettings] = useState<Settings>(DEFAULT_SETTINGS);
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
@@ -25,7 +27,7 @@ export function ContentAutoForm({ pageId }: { pageId: string }) {
|
||||
const response = await fetch(withBase(`/api/ai/content-auto?pageId=${encodeURIComponent(pageId)}`), { signal: controller.signal, cache: "no-store" });
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || "โหลดการตั้งค่า auto ไม่สำเร็จ");
|
||||
if (data.automation) setSettings(data.automation);
|
||||
if (data.automation) setSettings({ ...DEFAULT_SETTINGS, ...data.automation });
|
||||
setLoaded(true);
|
||||
} catch (failure) {
|
||||
if (!controller.signal.aborted) setError(failure instanceof Error ? failure.message : "เชื่อมต่อไม่ได้");
|
||||
@@ -34,8 +36,13 @@ export function ContentAutoForm({ pageId }: { pageId: string }) {
|
||||
return () => controller.abort();
|
||||
}, [pageId]);
|
||||
|
||||
async function save() {
|
||||
const mixTotal = settings.articlePercent + settings.knowledgePercent + settings.salesPercent;
|
||||
|
||||
async function save(event: React.FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (!loaded || busy) return;
|
||||
if (mixTotal !== 100) { setError(`สัดส่วนเนื้อหารวม ${mixTotal}% ต้องปรับให้ครบ 100%`); return; }
|
||||
if (settings.weekdays.length === 0 || settings.targets.length === 0) { setError("เลือกวันและช่องทางอย่างน้อย 1 รายการ"); return; }
|
||||
setBusy(true); setError(""); setMessage("");
|
||||
try {
|
||||
const response = await fetch(withBase("/api/ai/content-auto"), { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pageId, ...settings }) });
|
||||
@@ -47,33 +54,37 @@ export function ContentAutoForm({ pageId }: { pageId: string }) {
|
||||
finally { setBusy(false); }
|
||||
}
|
||||
|
||||
return <section className="border border-line rounded-xl p-4 flex flex-col gap-3 bg-paper" aria-label="สร้างเนื้อหาอัตโนมัติ">
|
||||
<h3 className="font-semibold text-[15px]">โหมด auto สร้างเนื้อหา</h3>
|
||||
<p className="text-[13px] text-ink-2">เลือกวันและเวลา ให้ AI คิดหัวข้อจากข้อมูลร้าน เขียนเนื้อหาและสร้างภาพ บันทึกเป็นฉบับร่างรออนุมัติ ปิดหน้าเว็บได้</p>
|
||||
<fieldset disabled={!loaded || busy} className="flex flex-col gap-3">
|
||||
<label className="flex items-center gap-2 text-[14px] font-medium">
|
||||
<input type="checkbox" role="switch" checked={settings.enabled} onChange={(e) => setSettings({ ...settings, enabled: e.target.checked })} /> เปิดสร้างอัตโนมัติสำหรับเพจนี้
|
||||
</label>
|
||||
<fieldset className="flex flex-wrap gap-3">
|
||||
<legend className="text-[13px] mb-2">วันสร้างเนื้อหา (เวลาไทย)</legend>
|
||||
{DAYS.map((label, day) => <label key={day} className="flex items-center gap-1.5 text-[13px] min-h-10">
|
||||
<input type="checkbox" checked={settings.weekdays.includes(day)} onChange={(e) => setSettings({ ...settings, weekdays: e.target.checked ? [...settings.weekdays, day] : settings.weekdays.filter((d) => d !== day) })} />{label}
|
||||
</label>)}
|
||||
return <section className="flex flex-col gap-4" aria-label="วางเนื้อหาอัตโนมัติ">
|
||||
<div><h3 className="font-semibold text-[18px]">วางเนื้อหาอัตโนมัติ</h3><p className="text-[13px] text-ink-2 mt-1">AI จะสร้างโพสต์เป็นฉบับร่างตามแผน ทุกชิ้นยังต้องผ่านการอนุมัติก่อนเผยแพร่</p></div>
|
||||
<form onSubmit={save} noValidate className="flex flex-col gap-5">
|
||||
<fieldset disabled={!loaded || busy} className="contents">
|
||||
<label className="flex items-start gap-3 rounded-xl border border-line bg-blue-soft p-3 text-[14px] font-medium cursor-pointer">
|
||||
<input className="mt-0.5" type="checkbox" checked={settings.enabled} onChange={(e) => setSettings({ ...settings, enabled: e.target.checked })} />
|
||||
<span><b className="block">เปิดใช้สำหรับเพจนี้</b><span className="text-[12px] text-ink-2 font-normal">ระบบทำงานตามแผนได้แม้ปิดหน้าเว็บ</span></span>
|
||||
</label>
|
||||
|
||||
<fieldset><legend className="font-semibold text-[14px] mb-2">1. เลือกวันที่ต้องการโพสต์</legend><div className="grid grid-cols-4 sm:grid-cols-7 gap-2">
|
||||
{DAYS.map((label, day) => <label key={day} className={`min-h-10 rounded-lg border grid place-items-center text-[13px] cursor-pointer ${settings.weekdays.includes(day) ? "border-blue bg-blue-soft text-blue-ink font-semibold" : "border-line bg-paper text-ink-2"}`}><input className="sr-only" type="checkbox" checked={settings.weekdays.includes(day)} onChange={(e) => setSettings({ ...settings, weekdays: e.target.checked ? [...settings.weekdays, day] : settings.weekdays.filter((d) => d !== day) })} />{label}</label>)}
|
||||
</div></fieldset>
|
||||
|
||||
<fieldset><legend className="font-semibold text-[14px] mb-2">2. กำหนดเวลา</legend><div className="grid sm:grid-cols-2 gap-2">
|
||||
{(["FIXED", "RANDOM"] as const).map((mode) => <label key={mode} className={`rounded-xl border p-3 flex gap-2 cursor-pointer ${settings.scheduleMode === mode ? "border-blue bg-blue-soft" : "border-line"}`}><input type="radio" name="scheduleMode" value={mode} checked={settings.scheduleMode === mode} onChange={() => setSettings({ ...settings, scheduleMode: mode })} /><span><b className="block text-[13px]">{mode === "FIXED" ? "ระบุเวลาเอง" : "สุ่มเวลา"}</b><span className="text-[12px] text-ink-2">{mode === "FIXED" ? "เลือกเวลาแต่ละรอบได้ตรง ๆ" : "สุ่มช่วง 08:00–20:00 น."}</span></span></label>)}
|
||||
</div></fieldset>
|
||||
|
||||
{settings.scheduleMode === "FIXED" ? <div className="flex flex-col gap-2">
|
||||
{settings.times.map((time, index) => <div key={index} className="flex items-end gap-2"><label className="field flex-1"><span>เวลารอบที่ {index + 1}</span><input className="input num" type="time" required value={time} onChange={(e) => setSettings({ ...settings, times: settings.times.map((t, i) => i === index ? e.target.value : t) })} /></label>{settings.times.length > 1 && <button type="button" className="btn btn-ghost btn-sm" onClick={() => setSettings({ ...settings, times: settings.times.filter((_, i) => i !== index) })}>ลบ</button>}</div>)}
|
||||
{settings.times.length < 3 && <button type="button" className="btn btn-ghost btn-sm self-start" onClick={() => setSettings({ ...settings, times: [...settings.times, "12:00"] })}>เพิ่มรอบต่อวัน</button>}
|
||||
</div> : <label className="field max-w-48"><span>จำนวนรอบต่อวัน</span><input className="input num" type="number" min={1} max={3} value={settings.randomPostsPerDay} onChange={(e) => setSettings({ ...settings, randomPostsPerDay: Number(e.target.value) })} /></label>}
|
||||
|
||||
<fieldset aria-describedby="content-mix-hint content-mix-error"><legend className="font-semibold text-[14px]">3. แบ่งสัดส่วนเนื้อหา</legend><p id="content-mix-hint" className="text-[12px] text-ink-2 mt-1 mb-3">ทั้ง 3 ประเภทผสมกันได้ และต้องรวมครบ 100%</p><div className="grid sm:grid-cols-3 gap-3">
|
||||
{([{ key: "articlePercent", label: "บทความ", hint: "เล่าเรื่องเชิงลึก" }, { key: "knowledgePercent", label: "ความรู้ทั่วไป", hint: "เคล็ดลับที่นำไปใช้ได้" }, { key: "salesPercent", label: "ปิดงานขาย", hint: "เสนอสินค้าและชวนตัดสินใจ" }] as const).map((item) => <label key={item.key} className="field rounded-xl border border-line p-3"><span>{item.label}</span><small className="text-[11px] text-ink-3">{item.hint}</small><div className="flex items-center gap-2"><input className="input num" type="number" inputMode="numeric" min={0} max={100} step={5} value={settings[item.key]} aria-invalid={mixTotal !== 100} onChange={(e) => setSettings({ ...settings, [item.key]: Number(e.target.value) })} /><b className="text-[13px]">%</b></div></label>)}
|
||||
</div><div className={`mt-3 rounded-lg px-3 py-2 text-[13px] flex justify-between ${mixTotal === 100 ? "bg-green-soft text-green-ink" : "bg-red-soft text-danger-ink"}`}><span>{mixTotal === 100 ? "สัดส่วนพร้อมใช้งาน" : "ยังแบ่งสัดส่วนไม่ครบ"}</span><b className="num">{mixTotal} / 100%</b></div>{mixTotal !== 100 && <p id="content-mix-error" className="text-[12px] text-danger-ink mt-1">ปรับตัวเลขให้ผลรวมเท่ากับ 100%</p>}</fieldset>
|
||||
|
||||
<label className="field"><span>คำแนะนำเพิ่มเติม (ไม่บังคับ)</span><textarea className="textarea" rows={2} value={settings.brief} onChange={(e) => setSettings({ ...settings, brief: e.target.value })} placeholder="เช่น เน้นสินค้ากลุ่มใหม่ ใช้น้ำเสียงเป็นกันเอง" /></label>
|
||||
<fieldset className="text-[13px]"><legend className="font-semibold text-[14px] mb-2">4. ช่องทางของฉบับร่าง</legend><div className="flex flex-wrap gap-4">{(["FACEBOOK", "INSTAGRAM"] as const).map((target) => <label key={target} className="flex items-center gap-2 min-h-10 cursor-pointer"><input type="checkbox" checked={settings.targets.includes(target)} onChange={(e) => setSettings({ ...settings, targets: e.target.checked ? [...settings.targets, target] : settings.targets.filter((t) => t !== target) })} />{target === "FACEBOOK" ? "Facebook" : "Instagram"}</label>)}</div></fieldset>
|
||||
<button type="submit" className="btn btn-primary self-start" disabled={!loaded || busy}>{busy ? "กำลังบันทึก…" : "บันทึกแผนอัตโนมัติ"}</button>
|
||||
</fieldset>
|
||||
<div className="flex flex-col gap-2">
|
||||
{settings.times.map((time, index) => <div key={index} className="flex flex-wrap items-end gap-2">
|
||||
<label className="field"><span>เวลาสร้างรอบที่ {index + 1}</span><input className="input" type="time" required value={time} onChange={(e) => setSettings({ ...settings, times: settings.times.map((t, i) => i === index ? e.target.value : t) })} /></label>
|
||||
{settings.times.length > 1 && <button type="button" className="btn btn-ghost btn-sm" aria-label={`ลบเวลารอบที่ ${index + 1}`} onClick={() => setSettings({ ...settings, times: settings.times.filter((_, i) => i !== index) })}>ลบเวลา</button>}
|
||||
</div>)}
|
||||
{settings.times.length < 3 && <button type="button" className="btn btn-ghost btn-sm self-start" onClick={() => setSettings({ ...settings, times: [...settings.times, "12:00"] })}>เพิ่มเวลา (สูงสุด 3 รอบต่อวัน)</button>}
|
||||
</div>
|
||||
<label className="field"><span>แนวเนื้อหา (เว้นว่างให้ AI เลือกจากข้อมูลร้าน)</span><textarea className="textarea" rows={2} maxLength={1000} value={settings.brief} onChange={(e) => setSettings({ ...settings, brief: e.target.value })} placeholder="เช่น สลับแนะนำสินค้า เคล็ดลับ และเรื่องราวของร้าน" /></label>
|
||||
<fieldset className="flex flex-wrap gap-3 text-[13px]">
|
||||
<legend className="mb-2">ช่องทางของฉบับร่าง auto</legend>
|
||||
{(["FACEBOOK", "INSTAGRAM"] as const).map((target) => <label key={target} className="flex items-center gap-1.5 min-h-10"><input type="checkbox" checked={settings.targets.includes(target)} onChange={(e) => setSettings({ ...settings, targets: e.target.checked ? [...settings.targets, target] : settings.targets.filter((t) => t !== target) })} />{target === "FACEBOOK" ? "Facebook" : "Instagram"}</label>)}
|
||||
</fieldset>
|
||||
<button type="button" className="btn btn-primary btn-sm self-start" onClick={save}>{busy ? "กำลังบันทึก…" : "บันทึกโหมด auto"}</button>
|
||||
</fieldset>
|
||||
</form>
|
||||
{settings.enabled && settings.nextRunAt && <p className="text-[12px] text-ink-2">รอบถัดไป: {formatTime(settings.nextRunAt)} · เวลาเริ่มเข้าคิว ไม่ใช่เวลาเผยแพร่</p>}
|
||||
{settings.lastQueuedAt && <p className="text-[12px] text-ink-2">เข้าคิวล่าสุด: {formatTime(settings.lastQueuedAt)} · ดูผลในงานล่าสุดด้านล่าง</p>}
|
||||
<p className="text-[12px] text-ink-2">ต้องเปิด worker และ login บัญชีสร้างภาพไว้ งานเริ่มตามคิว หาก worker หยุดจะรับเพียงรอบล่าสุดเมื่อกลับมา</p>
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { Icon } from "./Icon";
|
||||
import { ContentAutoForm } from "./ContentAutoForm";
|
||||
|
||||
export function ContentAutoLauncher({ pageId }: { pageId: string }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const close = (event: KeyboardEvent) => { if (event.key === "Escape") setOpen(false); };
|
||||
document.addEventListener("keydown", close);
|
||||
return () => document.removeEventListener("keydown", close);
|
||||
}, [open]);
|
||||
|
||||
return <>
|
||||
<button type="button" className="btn btn-on-band" onClick={() => setOpen(true)} aria-haspopup="dialog"><Icon name="sparkle" /> วางเนื้อหาอัตโนมัติ</button>
|
||||
{open && <div className="fixed inset-0 z-50 bg-ink/35 p-3 sm:p-6 overflow-y-auto" role="presentation" onMouseDown={(event) => { if (event.target === event.currentTarget) setOpen(false); }}>
|
||||
<section role="dialog" aria-modal="true" aria-labelledby="content-auto-title" className="bg-paper border border-line rounded-2xl shadow-xl w-full max-w-3xl mx-auto my-4 p-4 sm:p-6">
|
||||
<div className="flex items-center justify-between gap-3 mb-4 pb-3 border-b border-line"><h2 id="content-auto-title" className="font-semibold text-[16px]">ตั้งค่าแผนอัตโนมัติ</h2><button type="button" className="btn btn-ghost btn-sm" onClick={() => setOpen(false)} aria-label="ปิดหน้าต่าง">ปิด</button></div>
|
||||
<ContentAutoForm pageId={pageId} />
|
||||
</section>
|
||||
</div>}
|
||||
</>;
|
||||
}
|
||||
@@ -2,13 +2,100 @@
|
||||
/* eslint-disable @next/next/no-img-element -- generated image URLs, not optimisable */
|
||||
import { withBase } from "@/lib/base-path";
|
||||
|
||||
import { useState } from "react";
|
||||
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";
|
||||
|
||||
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 = () => {
|
||||
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.75)");
|
||||
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.75)");
|
||||
} else {
|
||||
grad.addColorStop(0, "rgba(0,0,0,0)");
|
||||
grad.addColorStop(0.15, "rgba(0,0,0,0.65)");
|
||||
grad.addColorStop(0.85, "rgba(0,0,0,0.65)");
|
||||
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.55)";
|
||||
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",
|
||||
@@ -42,9 +129,12 @@ export function ImageAssistant({
|
||||
const [prompt, setPrompt] = useState("");
|
||||
const [size, setSize] = useState<ImageSizeKey>("square");
|
||||
const [result, setResult] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState<"prompt" | "generate" | 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");
|
||||
@@ -63,9 +153,56 @@ export function ImageAssistant({
|
||||
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
|
||||
@@ -142,22 +279,56 @@ export function ImageAssistant({
|
||||
|
||||
{result && (
|
||||
<div className="rounded-[10px] border border-line bg-paper p-2 flex flex-col gap-2">
|
||||
<img src={result} alt="รูปที่ AI สร้าง" className="w-full max-h-[320px] object-contain rounded-[6px] bg-board" />
|
||||
<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={() => {
|
||||
if (hasImage && !window.confirm("แทนที่รูปเดิมของโพสต์ด้วยรูปนี้?")) return;
|
||||
onUse(result);
|
||||
setResult(null);
|
||||
setOpen(false);
|
||||
}}
|
||||
onClick={handleUse}
|
||||
>
|
||||
<Icon name="check" size={14} /> ใช้รูปนี้
|
||||
<Icon name="check" size={14} />
|
||||
{busy === "overlay" ? "กำลังบันทึก…" : "ใช้รูปนี้"}
|
||||
</button>
|
||||
<button type="button" className="btn btn-ghost btn-sm" disabled={busy !== null} onClick={() => setResult(null)}>
|
||||
<button type="button" className="btn btn-ghost btn-sm" disabled={busy !== null} onClick={() => { setResult(null); setOverlayPreview(null); setOverlayText(""); }}>
|
||||
ทิ้ง
|
||||
</button>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user