/** * ตัวช่วยจัดการบล็อกบทความของหน้า "สำหรับคนทำโรงหนัง" * แยกออกมาเป็นฟังก์ชันบริสุทธิ์เพื่อเทสต์ได้โดยไม่ต้องพึ่ง fs หรือ React */ import type { ArticleBlock, ArticleImage, ArticleParagraph, } from "@/lib/content-types"; function asString(value: unknown): string { return typeof value === "string" ? value : ""; } /** * ตรวจบล็อกที่รับมาจากหลังบ้าน/ไฟล์ JSON * - เก็บเฉพาะชนิดที่รู้จัก (paragraph / image) * - ย่อหน้าว่าง และรูปที่ไม่มี src → ทิ้ง * - ฟิลด์เกินถูกตัดทิ้ง (ไม่ให้ข้อมูลแปลกปลอมไหลเข้า store) */ export function sanitizeArticleBlocks(input: unknown): ArticleBlock[] { if (!Array.isArray(input)) return []; const blocks: ArticleBlock[] = []; for (const item of input) { if (!item || typeof item !== "object") continue; const raw = item as Record; const type = asString(raw.type); if (type === "paragraph") { const text = asString(raw.text).trim(); if (text) blocks.push({ type: "paragraph", text }); continue; } if (type === "image") { const src = asString(raw.src).trim(); if (!src) continue; const block: ArticleImage = { type: "image", src, alt: asString(raw.alt).trim(), caption: asString(raw.caption).trim(), }; blocks.push(block); } } return blocks; } /** ย่อหน้าใหม่ (ว่าง) สำหรับปุ่ม "เพิ่มย่อหน้า" */ export function createParagraphBlock(text = ""): ArticleParagraph { return { type: "paragraph", text }; } /** รูปใหม่ (ว่าง) สำหรับปุ่ม "เพิ่มรูป" */ export function createImageBlock(): ArticleImage { return { type: "image", src: "", alt: "", caption: "" }; } /** สลับตำแหน่งบล็อกขึ้น/ลง — คืนรายการใหม่ และไม่ทำอะไรถ้าเกินขอบ */ export function moveBlock( blocks: ArticleBlock[], index: number, direction: -1 | 1, ): ArticleBlock[] { const target = index + direction; if (index < 0 || index >= blocks.length) return blocks; if (target < 0 || target >= blocks.length) return blocks; const next = [...blocks]; const [moved] = next.splice(index, 1); next.splice(target, 0, moved); return next; } /** ลบบล็อกตามตำแหน่ง */ export function removeBlock( blocks: ArticleBlock[], index: number, ): ArticleBlock[] { if (index < 0 || index >= blocks.length) return blocks; return blocks.filter((_, i) => i !== index); } /** จำนวนรูปในบทความ (ใช้แสดงสรุป/เตือนในหลังบ้าน) */ export function countImages(blocks: ArticleBlock[]): number { return blocks.filter((block) => block.type === "image").length; }