Add automated content planning and image overlays
This commit is contained in:
@@ -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