Add news research assistant to post editor
This commit is contained in:
@@ -0,0 +1,109 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { withBase } from "@/lib/base-path";
|
||||
import { Icon } from "./Icon";
|
||||
import { Notice } from "./ui";
|
||||
|
||||
type Target = "FACEBOOK" | "INSTAGRAM";
|
||||
type Article = { title: string; url: string; source: string; publishedAt: string | null; description: string };
|
||||
type Draft = { summary: string; keyPoints: string[]; postTitle: string; caption: string };
|
||||
|
||||
const SUGGESTIONS = ["AI รุ่นใหม่", "เทคโนโลยีสำหรับธุรกิจ", "การตลาดออนไลน์", "ความรู้สำหรับเจ้าของร้าน"];
|
||||
|
||||
function thaiDate(value: string | null) {
|
||||
if (!value) return "ไม่ระบุวันที่";
|
||||
return new Intl.DateTimeFormat("th-TH", { day: "numeric", month: "short", year: "numeric", timeZone: "Asia/Bangkok" }).format(new Date(value));
|
||||
}
|
||||
|
||||
export function ContentResearchAssistant({ pageId, targets, onApply }: { pageId: string; targets: Target[]; onApply: (title: string, caption: string) => void }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [query, setQuery] = useState("");
|
||||
const [articles, setArticles] = useState<Article[]>([]);
|
||||
const [selected, setSelected] = useState<Article | null>(null);
|
||||
const [draft, setDraft] = useState<Draft | null>(null);
|
||||
const [sourceRead, setSourceRead] = useState(true);
|
||||
const [busy, setBusy] = useState<"search" | "summarize" | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function request(payload: Record<string, unknown>) {
|
||||
const response = await fetch(withBase("/api/ai/research"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pageId, targets, ...payload }) });
|
||||
const json = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(json.error ?? "ค้นคว้าเนื้อหาไม่สำเร็จ ลองใหม่อีกครั้ง");
|
||||
return json;
|
||||
}
|
||||
|
||||
async function search(nextQuery = query) {
|
||||
setQuery(nextQuery);
|
||||
setBusy("search");
|
||||
setError(null);
|
||||
setSelected(null);
|
||||
setDraft(null);
|
||||
try {
|
||||
const json = await request({ action: "search", query: nextQuery });
|
||||
setArticles(json.articles ?? []);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "ค้นหาข่าวไม่สำเร็จ");
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function summarize(article: Article) {
|
||||
setSelected(article);
|
||||
setDraft(null);
|
||||
setBusy("summarize");
|
||||
setError(null);
|
||||
try {
|
||||
const json = await request({ action: "summarize", ...article });
|
||||
setDraft(json.draft);
|
||||
setSourceRead(json.sourceRead !== false);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "สรุปบทความไม่สำเร็จ");
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
}
|
||||
|
||||
if (!open) return (
|
||||
<button type="button" className="btn btn-ghost btn-sm self-start" onClick={() => setOpen(true)}>
|
||||
<Icon name="search" size={15} /> หาข่าวและความรู้ใหม่
|
||||
</button>
|
||||
);
|
||||
|
||||
return (
|
||||
<section className="content-research" aria-label="หาข่าวและความรู้ใหม่">
|
||||
<div className="content-research-head">
|
||||
<div><b>หาข่าวและความรู้ใหม่</b><p>ค้นแหล่งข่าว แล้วให้ AI สรุปเป็นร่างโพสต์ที่แก้ไขต่อได้</p></div>
|
||||
<button type="button" className="btn btn-ghost btn-sm" onClick={() => setOpen(false)} aria-label="ปิดเครื่องมือค้นคว้า"><Icon name="x" size={15} /></button>
|
||||
</div>
|
||||
<form className="content-research-search" onSubmit={(event) => { event.preventDefault(); void search(); }}>
|
||||
<label className="sr-only" htmlFor="research-query">หัวข้อข่าวหรือความรู้ที่ต้องการ</label>
|
||||
<div className="content-research-input"><Icon name="search" size={17} /><input id="research-query" value={query} maxLength={120} onChange={(event) => setQuery(event.target.value)} placeholder="เช่น โมเดล AI ใหม่สำหรับธุรกิจ" /></div>
|
||||
<button className="btn btn-primary" disabled={busy !== null || query.trim().length < 2}>{busy === "search" ? "กำลังค้น…" : "ค้นหาข่าว"}</button>
|
||||
</form>
|
||||
<div className="content-research-suggestions" aria-label="หัวข้อแนะนำ">
|
||||
{SUGGESTIONS.map((item) => <button type="button" key={item} disabled={busy !== null} onClick={() => void search(item)}>{item}</button>)}
|
||||
</div>
|
||||
{error && <Notice tone="red">{error}</Notice>}
|
||||
{busy === "search" && <div className="research-loading" aria-live="polite"><span /><span /><span /> กำลังหาข่าวล่าสุด…</div>}
|
||||
{!busy && query && articles.length === 0 && !error && <p className="research-empty">ยังไม่พบข่าวในหัวข้อนี้ ลองใช้คำค้นที่กว้างขึ้น</p>}
|
||||
{articles.length > 0 && !draft && <div className="research-results" aria-label="ผลการค้นหา">
|
||||
{articles.map((article) => <article key={article.url} data-selected={selected?.url === article.url || undefined}>
|
||||
<div className="research-meta"><span>{article.source}</span><time dateTime={article.publishedAt ?? undefined}>{thaiDate(article.publishedAt)}</time></div>
|
||||
<h3>{article.title}</h3>
|
||||
{article.description && <p>{article.description}</p>}
|
||||
<div className="research-actions"><a href={article.url} target="_blank" rel="noreferrer"><Icon name="link" size={14} /> เปิดต้นฉบับ</a><button type="button" disabled={busy !== null} onClick={() => void summarize(article)}><Icon name="sparkle" size={14} /> {busy === "summarize" && selected?.url === article.url ? "กำลังอ่านและสรุป…" : "สรุปเป็นโพสต์"}</button></div>
|
||||
</article>)}
|
||||
</div>}
|
||||
{draft && selected && <div className="research-draft" aria-live="polite">
|
||||
<div className="research-meta"><span>{selected.source}</span><a href={selected.url} target="_blank" rel="noreferrer">ตรวจต้นฉบับ <Icon name="link" size={13} /></a></div>
|
||||
<h3>{draft.postTitle}</h3><p>{draft.summary}</p>
|
||||
<ul>{draft.keyPoints.map((point) => <li key={point}>{point}</li>)}</ul>
|
||||
{!sourceRead && <Notice tone="amber">เว็บไซต์ต้นฉบับอ่านอัตโนมัติไม่ได้ ร่างนี้อ้างอิงหัวข้อและคำโปรยเท่านั้น ควรเปิดต้นฉบับตรวจข้อเท็จจริงก่อนใช้</Notice>}
|
||||
<div className="research-draft-actions"><button type="button" className="btn btn-ghost btn-sm" onClick={() => setDraft(null)}>กลับไปดูข่าว</button><button type="button" className="btn btn-primary btn-sm" onClick={() => { onApply(draft.postTitle, draft.caption); setOpen(false); }}><Icon name="check" size={15} /> นำไปใส่ในโพสต์</button></div>
|
||||
</div>}
|
||||
<p className="content-research-foot">AI อาจสรุปคลาดเคลื่อน ควรเปิดแหล่งข่าวและตรวจข้อเท็จจริงก่อนส่งอนุมัติ</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -15,6 +15,8 @@ import { PostCheck } from "./PostCheck";
|
||||
import { PageAvatar } from "./PageAvatar";
|
||||
import { formatDateTime, Notice, StatusPill } from "./ui";
|
||||
import { useToast } from "./Toast";
|
||||
import { ThaiDateTimePicker } from "./ThaiDateTimePicker";
|
||||
import { ContentResearchAssistant } from "./ContentResearchAssistant";
|
||||
|
||||
type Target = "FACEBOOK" | "INSTAGRAM";
|
||||
|
||||
@@ -66,9 +68,16 @@ const ACTION_LABEL: Record<string, string> = {
|
||||
|
||||
const EDITABLE: PostStatus[] = ["DRAFT", "PENDING_APPROVAL", "APPROVED", "FAILED", "CANCELLED"];
|
||||
|
||||
function toLocalInput(d: Date): string {
|
||||
const pad = (n: number) => String(n).padStart(2, "0");
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
function toBangkokInput(d: Date): string {
|
||||
const parts = new Intl.DateTimeFormat("en-CA", { timeZone: "Asia/Bangkok", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).formatToParts(d);
|
||||
const get = (type: Intl.DateTimeFormatPartTypes) => parts.find((part) => part.type === type)?.value ?? "";
|
||||
return `${get("year")}-${get("month")}-${get("day")}T${get("hour")}:${get("minute")}`;
|
||||
}
|
||||
|
||||
function bangkokInputToIso(value: string): string {
|
||||
const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/.exec(value);
|
||||
if (!match) return new Date(value).toISOString();
|
||||
return new Date(Date.UTC(+match[1], +match[2] - 1, +match[3], +match[4] - 7, +match[5])).toISOString();
|
||||
}
|
||||
|
||||
export function PostEditor({
|
||||
@@ -102,7 +111,7 @@ export function PostEditor({
|
||||
const [aiAssisted, setAiAssisted] = useState(post?.aiAssisted ?? Boolean(initialDraft));
|
||||
const [imageUrl, setImageUrl] = useState<string | null>(post?.imageBlobUrl ?? null);
|
||||
const [targets, setTargets] = useState<Target[]>(post?.targets ?? ["FACEBOOK"]);
|
||||
const [scheduleAt, setScheduleAt] = useState(() => toLocalInput(new Date(Date.now() + 60 * 60 * 1000)));
|
||||
const [scheduleAt, setScheduleAt] = useState(() => toBangkokInput(new Date(Date.now() + 60 * 60 * 1000)));
|
||||
const [note, setNote] = useState("");
|
||||
const [plannedDay, setPlannedDay] = useState(initialDay ?? "");
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
@@ -197,10 +206,9 @@ export function PostEditor({
|
||||
}
|
||||
|
||||
function quickSchedule(dayOffset: number, hour: number) {
|
||||
const d = new Date();
|
||||
d.setDate(d.getDate() + dayOffset);
|
||||
d.setHours(hour, 0, 0, 0);
|
||||
setScheduleAt(toLocalInput(d));
|
||||
const [year, month, day] = toBangkokInput(new Date()).slice(0, 10).split("-").map(Number);
|
||||
const target = new Date(Date.UTC(year, month - 1, day + dayOffset));
|
||||
setScheduleAt(`${target.getUTCFullYear()}-${String(target.getUTCMonth() + 1).padStart(2, "0")}-${String(target.getUTCDate()).padStart(2, "0")}T${String(hour).padStart(2, "0")}:00`);
|
||||
}
|
||||
|
||||
// The one next step for this post, surfaced in the phone action dock.
|
||||
@@ -260,14 +268,16 @@ export function PostEditor({
|
||||
<input className="input" value={title} disabled={!canEdit} onChange={(e) => setTitle(e.target.value)} placeholder="เช่น โปรโมชั่นปลายเดือน" />
|
||||
</label>
|
||||
|
||||
{!post && <label className="field">
|
||||
{!post && <div className="field">
|
||||
<span>วันวางแผนโพสต์ (ยังไม่เผยแพร่)</span>
|
||||
<input className="input" type="date" value={plannedDay} disabled={!canEdit} onChange={e => setPlannedDay(e.target.value)} />
|
||||
<ThaiDateTimePicker dateOnly value={plannedDay} disabled={!canEdit} onChange={setPlannedDay} label="เลือกวันวางแผนโพสต์" />
|
||||
<small className="text-ink-3">เว้นว่างเพื่อเลือกวันภายหลัง · อนุมัติก่อน แล้วเลือกเวลาเผยแพร่</small>
|
||||
</label>}
|
||||
</div>}
|
||||
|
||||
{!post && canEdit && pageId && <PostGenerationQueue key={pageId} pageId={pageId} targets={targets} plannedDay={plannedDay} initialTopic={initialDraft?.topic || title} />}
|
||||
|
||||
{canEdit && pageId && <ContentResearchAssistant pageId={pageId} targets={targets} onApply={(nextTitle, nextCaption) => { setTitle(nextTitle); setCaption(nextCaption); setAiAssisted(true); }} />}
|
||||
|
||||
{canEdit && pageId && (
|
||||
<CaptionAssistant
|
||||
pageId={pageId}
|
||||
@@ -448,15 +458,15 @@ export function PostEditor({
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2 items-end">
|
||||
<label className="field flex-1 min-w-0">
|
||||
<div className="field flex-1 min-w-0">
|
||||
<span className="sr-only">วันและเวลาที่จะเผยแพร่</span>
|
||||
<input className="input num" type="datetime-local" value={scheduleAt} onChange={(e) => setScheduleAt(e.target.value)} />
|
||||
</label>
|
||||
<ThaiDateTimePicker value={scheduleAt} onChange={setScheduleAt} label="เลือกวันและเวลาเผยแพร่" />
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
disabled={Boolean(busy) || !scheduleAt}
|
||||
onClick={() => act("schedule", { scheduledAt: new Date(scheduleAt).toISOString() })}
|
||||
onClick={() => act("schedule", { scheduledAt: bangkokInputToIso(scheduleAt) })}
|
||||
>
|
||||
<Icon name="clock" size={16} /> ตั้งเวลา
|
||||
</button>
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useId, useMemo, useRef, useState } from "react";
|
||||
import { Icon } from "./Icon";
|
||||
|
||||
const THAI_MONTHS = ["มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"];
|
||||
const THAI_DAYS = ["อา.", "จ.", "อ.", "พ.", "พฤ.", "ศ.", "ส."];
|
||||
const pad = (value: number) => String(value).padStart(2, "0");
|
||||
|
||||
function parseValue(value: string) {
|
||||
const match = /^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2}))?$/.exec(value);
|
||||
return match ? { year: +match[1], month: +match[2] - 1, day: +match[3], hour: +(match[4] ?? 9), minute: +(match[5] ?? 0) } : null;
|
||||
}
|
||||
|
||||
function bangkokToday() {
|
||||
const parts = new Intl.DateTimeFormat("en-CA", { timeZone: "Asia/Bangkok", year: "numeric", month: "2-digit", day: "2-digit" }).formatToParts(new Date());
|
||||
const get = (type: Intl.DateTimeFormatPartTypes) => Number(parts.find((part) => part.type === type)?.value);
|
||||
return { year: get("year"), month: get("month") - 1, day: get("day") };
|
||||
}
|
||||
|
||||
export function ThaiDateTimePicker({ value, onChange, dateOnly = false, disabled = false, label = "เลือกวันและเวลา" }: { value: string; onChange: (value: string) => void; dateOnly?: boolean; disabled?: boolean; label?: string }) {
|
||||
const id = useId();
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
const selected = parseValue(value);
|
||||
const [today] = useState(() => bangkokToday());
|
||||
const [open, setOpen] = useState(false);
|
||||
const [view, setView] = useState(() => ({ year: selected?.year ?? today.year, month: selected?.month ?? today.month }));
|
||||
|
||||
useEffect(() => {
|
||||
const close = (event: PointerEvent) => { if (!rootRef.current?.contains(event.target as Node)) setOpen(false); };
|
||||
const escape = (event: KeyboardEvent) => { if (event.key === "Escape") setOpen(false); };
|
||||
document.addEventListener("pointerdown", close);
|
||||
document.addEventListener("keydown", escape);
|
||||
return () => { document.removeEventListener("pointerdown", close); document.removeEventListener("keydown", escape); };
|
||||
}, []);
|
||||
|
||||
const days = useMemo(() => {
|
||||
const first = new Date(Date.UTC(view.year, view.month, 1)).getUTCDay();
|
||||
const count = new Date(Date.UTC(view.year, view.month + 1, 0)).getUTCDate();
|
||||
return Array.from({ length: 42 }, (_, index) => { const day = index - first + 1; return day >= 1 && day <= count ? day : null; });
|
||||
}, [view]);
|
||||
const display = selected ? `${selected.day} ${THAI_MONTHS[selected.month]} ${selected.year + 543}${dateOnly ? "" : ` เวลา ${pad(selected.hour)}:${pad(selected.minute)} น.`}` : dateOnly ? "เลือกวันที่" : "เลือกวันและเวลา";
|
||||
|
||||
function pickDay(day: number) {
|
||||
const time = selected ?? { hour: 9, minute: 0 };
|
||||
onChange(`${view.year}-${pad(view.month + 1)}-${pad(day)}${dateOnly ? "" : `T${pad(time.hour)}:${pad(time.minute)}`}`);
|
||||
if (dateOnly) setOpen(false);
|
||||
}
|
||||
function pickToday() {
|
||||
const time = selected ?? { hour: 9, minute: 0 };
|
||||
setView({ year: today.year, month: today.month });
|
||||
onChange(`${today.year}-${pad(today.month + 1)}-${pad(today.day)}${dateOnly ? "" : `T${pad(time.hour)}:${pad(time.minute)}`}`);
|
||||
if (dateOnly) setOpen(false);
|
||||
}
|
||||
function changeTime(kind: "hour" | "minute", next: number) {
|
||||
const date = selected ?? { ...today, hour: 9, minute: 0 };
|
||||
const result = { ...date, [kind]: next };
|
||||
onChange(`${result.year}-${pad(result.month + 1)}-${pad(result.day)}T${pad(result.hour)}:${pad(result.minute)}`);
|
||||
}
|
||||
function moveMonth(offset: number) {
|
||||
const next = new Date(Date.UTC(view.year, view.month + offset, 1));
|
||||
setView({ year: next.getUTCFullYear(), month: next.getUTCMonth() });
|
||||
}
|
||||
function togglePicker() {
|
||||
if (!open && selected) setView({ year: selected.year, month: selected.month });
|
||||
setOpen((current) => !current);
|
||||
}
|
||||
|
||||
return <div className="thai-picker" ref={rootRef}>
|
||||
<button type="button" className="thai-picker-trigger num" disabled={disabled} aria-expanded={open} aria-controls={id} onClick={togglePicker}>
|
||||
<span className={selected ? "" : "text-ink-4"}>{display}</span><Icon name="calendar" size={19} />
|
||||
</button>
|
||||
{open && <div className="thai-picker-popover" id={id} role="dialog" aria-label={label}>
|
||||
<div className="thai-picker-head"><button type="button" aria-label="เดือนก่อนหน้า" onClick={() => moveMonth(-1)}>‹</button><strong>{THAI_MONTHS[view.month]} {view.year + 543}</strong><button type="button" aria-label="เดือนถัดไป" onClick={() => moveMonth(1)}>›</button></div>
|
||||
<div className="thai-picker-week" aria-hidden="true">{THAI_DAYS.map((day) => <span key={day}>{day}</span>)}</div>
|
||||
<div className="thai-picker-grid">{days.map((day, index) => day ? <button type="button" key={index} aria-label={`${day} ${THAI_MONTHS[view.month]} ${view.year + 543}`} aria-pressed={selected?.year === view.year && selected.month === view.month && selected.day === day} data-today={today.year === view.year && today.month === view.month && today.day === day || undefined} onClick={() => pickDay(day)}>{day}</button> : <span key={index} />)}</div>
|
||||
{!dateOnly && <div className="thai-picker-time"><Icon name="clock" size={17} /><span>เวลาไทย</span><select aria-label="ชั่วโมง" value={selected?.hour ?? 9} onChange={(event) => changeTime("hour", +event.target.value)}>{Array.from({ length: 24 }, (_, hour) => <option key={hour} value={hour}>{pad(hour)}</option>)}</select><span>:</span><select aria-label="นาที" value={selected?.minute ?? 0} onChange={(event) => changeTime("minute", +event.target.value)}>{Array.from({ length: 60 }, (_, minute) => <option key={minute} value={minute}>{pad(minute)}</option>)}</select><span>น.</span></div>}
|
||||
<div className="thai-picker-foot"><button type="button" onClick={pickToday}>วันนี้</button>{!dateOnly && <button type="button" className="btn btn-primary btn-sm" onClick={() => setOpen(false)}>เรียบร้อย</button>}</div>
|
||||
</div>}
|
||||
</div>;
|
||||
}
|
||||
Reference in New Issue
Block a user