/* ui.js — ตัวช่วยกลาง: ไอคอน SVG, escaping, toast, ตรวจ URL */ const ICON_PATHS = { search: '', close: '', settings: '', arrowRight: '', arrowUp: '', arrowDown: '', plus: '', trash: '', save: '', download: '', refresh: '', check: '', alert: '', shield: '', external: '', folder: '', film: '', bus: '', droplet: '', cpu: '', disc: '', book: '', wrench: '', dashboard: '', palette: '', list: '', spark: '', }; export const ICON_NAMES = Object.keys(ICON_PATHS); /** คืนสตริง SVG (ใช้ innerHTML — ชื่อไอคอนมาจากลิสต์คงที่ ไม่ใช่ข้อมูลผู้ใช้) */ export function icon(name, extraClass = "") { const d = ICON_PATHS[name] || ICON_PATHS.folder; return ``; } /** แทนที่ทุกจุดที่ใส่ [data-icon="name"] ด้วย SVG จริง (สำหรับ markup ใน index.html) */ export function hydrateIcons(root = document) { root.querySelectorAll("[data-icon]").forEach((node) => { const name = node.getAttribute("data-icon"); if (!name || node.dataset.iconReady === "1") return; node.innerHTML = icon(name); node.dataset.iconReady = "1"; }); } export function escapeHtml(value) { return String(value ?? "") .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """) .replace(/'/g, "'"); } /** เติม https:// ถ้าไม่มี scheme และคืน null ถ้าไม่ใช่ http(s) */ export function normalizeUrl(raw) { const value = String(raw ?? "").trim(); if (!value) return null; const withScheme = /^https?:\/\//i.test(value) ? value : `https://${value.replace(/^\/+/, "")}`; try { const parsed = new URL(withScheme); if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null; if (!parsed.hostname.includes(".")) return null; return parsed.toString().replace(/\/$/, ""); } catch { return null; } } export function hostOf(url) { const normalized = normalizeUrl(url); if (!normalized) return ""; try { return new URL(normalized).hostname; } catch { return ""; } } export function isEmail(raw) { return /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(raw ?? "").trim()); } let toastTimer = null; export function toast(message, kind = "info") { const stack = document.getElementById("toast-stack"); if (!stack) return; stack.replaceChildren(); const node = document.createElement("div"); node.className = `toast${kind === "error" ? " toast--error" : ""}`; node.textContent = message; stack.appendChild(node); clearTimeout(toastTimer); toastTimer = setTimeout(() => stack.replaceChildren(), 3600); } export function debounce(fn, wait = 120) { let timer = null; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), wait); }; } export function debounceImmediate(fn, wait = 400) { let timer = null; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), wait); }; }