Repository Public
1"use client";2import { useCallback, useEffect, useRef, useState } from "react";34export class ApiClientError extends Error { constructor(public status: number, public code: string, message: string, public extra: Record<string, unknown> = {}) { super(message); } }56const csrf = () => document.querySelector<HTMLMetaElement>('meta[name="atlas-csrf"]')?.content ?? "";7export const API = "/admin/api";89/** A full page load, on purpose: after signing in or out the server must render again with (or without) the session cookie. */10export const go = (path: string) => { window.location.assign(path); };1112/** Same-origin call to the studio API, carrying the session's CSRF token (read from the <meta> the studio layout renders). */13export async function api<T = unknown>(path: string, init: { method?: string; body?: unknown; raw?: BodyInit; headers?: Record<string, string>; signal?: AbortSignal } = {}): Promise<T> {14 const res = await fetch(`${API}/${path}`, {15 method: init.method ?? (init.body !== undefined || init.raw !== undefined ? "POST" : "GET"), credentials: "same-origin", signal: init.signal, cache: "no-store",16 headers: { "x-csrf-token": csrf(), ...(init.raw !== undefined ? {} : { "Content-Type": "application/json" }), ...init.headers },17 body: init.raw ?? (init.body !== undefined ? JSON.stringify(init.body) : undefined),18 }).catch((e: unknown) => { if ((e as Error)?.name === "AbortError") throw e; throw new ApiClientError(0, "network", "Le serveur ne répond pas. Vérifiez la connexion."); });19 const data = await res.json().catch(() => ({})) as { error?: { code?: string; message?: string } & Record<string, unknown> };20 if (res.status === 401 && !path.startsWith("auth/")) { go("/admin/connexion"); throw new ApiClientError(401, "unauthenticated", "Session expirée."); }21 if (!res.ok) throw new ApiClientError(res.status, data.error?.code ?? "error", data.error?.message ?? `Erreur ${res.status}`, data.error ?? {});22 return data as T;23}24export const errorText = (e: unknown) => (e instanceof Error ? e.message : "Erreur inattendue.");2526/** Loads a resource of the API; `reload` refetches, `set` replaces the data with what a write returned. */27export function useLoad<T>(path: string | null, opts: { pollMs?: number } = {}) {28 const [data, setData] = useState<T | null>(null), [error, setError] = useState(""), [loading, setLoading] = useState(Boolean(path));29 const current = useRef(path);30 const reload = useCallback(async () => {31 if (!path) return;32 try { const d = await api<T>(path); if (current.current === path) { setData(d); setError(""); } }33 catch (e) { if (current.current === path) setError(errorText(e)); }34 finally { if (current.current === path) setLoading(false); }35 }, [path]);36 useEffect(() => { current.current = path; void reload(); }, [path, reload]);37 useEffect(() => {38 if (!opts.pollMs || !path) return;39 const t = setInterval(() => { if (!document.hidden) void reload(); }, opts.pollMs);40 return () => clearInterval(t);41 }, [opts.pollMs, path, reload]);42 return { data, error, loading, reload, set: setData };43}4445const DATE = new Intl.DateTimeFormat("fr-CA", { dateStyle: "medium", timeStyle: "short" }), DAY = new Intl.DateTimeFormat("fr-CA", { dateStyle: "medium" });46export const fmtDate = (iso: string | null | undefined) => (iso ? DATE.format(new Date(iso)) : "—");47export const fmtDay = (iso: string | null | undefined) => (iso ? DAY.format(new Date(iso)) : "—");48export function fmtBytes(n: number | null | undefined): string {49 if (n === null || n === undefined) return "—";50 const units = ["o", "ko", "Mo", "Go", "To"]; let v = n, i = 0;51 while (v >= 1000 && i < units.length - 1) { v /= 1000; i++; }52 return `${v >= 100 || i === 0 ? Math.round(v) : v.toFixed(1).replace(".", ",")} ${units[i]}`;53}54export const fmtDuration = (s: number | null | undefined) => { if (s === null || s === undefined) return "—"; const t = Math.round(s); return `${Math.floor(t / 60)}:${String(t % 60).padStart(2, "0")}`; };55/** "1:35" or "95" → 95 ; null when it is not a time. */56export function parseClock(v: string): number | null {57 const t = v.trim();58 if (/^\d+(\.\d+)?$/.test(t)) return Number(t);59 if (/^\d+(:[0-5]?\d){1,2}$/.test(t)) return t.split(":").map(Number).reduce((a, n) => a * 60 + n, 0);60 return null;61}62/** Value of a <input type="datetime-local"> for a date, in the browser's time zone. */63export const toLocalInput = (d: Date) => new Date(d.getTime() - d.getTimezoneOffset() * 60_000).toISOString().slice(0, 16);64