import { useCallback, useRef, useState } from "react"; import type { CheckSummary } from "../editor/embeds/embed-suggestions"; import { DEMO_MODE } from "../demo/demo-mode"; export type EmbedCheckState = | { status: "idle" } | { status: "running"; html: string } | { status: "done"; html: string; summary: CheckSummary } | { status: "error"; html: string; message: string }; /** * Server-side rendering check of the current chart (POST /api/embed-check). * Once the server says the check is unavailable (503 without Chromium), the * studio stops asking for the rest of the session. */ export function useEmbedCheck() { const [state, setState] = useState({ status: "idle" }); const unavailableRef = useRef(false); const requestRef = useRef(0); const run = useCallback(async (html: string, banner: boolean) => { if (DEMO_MODE || unavailableRef.current || !html.trim()) return; const id = ++requestRef.current; setState({ status: "running", html }); try { const res = await fetch("/api/embed-check", { method: "POST", headers: { "Content-Type": "application/json" }, credentials: "include", body: JSON.stringify({ html, banner }), }); const body = await res.json().catch(() => ({})); if (id !== requestRef.current) return; if (res.status === 503 && /not available/i.test(String(body.error ?? ""))) { unavailableRef.current = true; setState({ status: "idle" }); return; } if (!res.ok) { setState({ status: "error", html, message: String(body.error ?? `HTTP ${res.status}`) }); return; } setState({ status: "done", html, summary: body as CheckSummary }); } catch (err) { if (id !== requestRef.current) return; setState({ status: "error", html, message: err instanceof Error ? err.message : String(err) }); } }, []); const reset = useCallback(() => { requestRef.current++; setState({ status: "idle" }); }, []); return { state, run, reset }; }