File size: 2,057 Bytes
4953bfd
 
6e392fe
4953bfd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e392fe
4953bfd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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<EmbedCheckState>({ 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 };
}