CenaForge: primeira versão pública

Gerador de vídeos narrativos (Godot + FFmpeg), painel Next.js, serviço de voz,
Clipador de lives e Publicador para YouTube, TikTok e Instagram.

Inclui a leitura das visualizações dos posts para o Dashboard e o botão
"Publicar no <rede>" nos cartões das publicações.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 16:35:09 -03:00
co-authored by Claude Opus 5.5
commit 84f30bbc2d
484 changed files with 74826 additions and 0 deletions
+335
View File
@@ -0,0 +1,335 @@
"use client";
// Canais de publicação (a entidade `accounts`): criar, editar dados, conectar as redes (account-networks.tsx),
// regras de publicação e ligar/encerrar histórias e fontes do Clipador. Fala com /api/accounts/*; depois de cada
// mudança, router.refresh() atualiza a lista do servidor.
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState, useTransition, type FormEvent, type ReactNode } from "react";
import type { AccountView } from "@/lib/accounts";
import { PLATFORMS, type StoryKind } from "@/lib/types";
import { apiCall } from "./api-client";
import { PLATFORM_LABEL, clipperCall, isOfflineError, type ClipperChannel } from "./clipper-client";
import { PlatformIcon } from "./clipper-sessions";
import { PublishingNetworksCard, PublishingRulesCard } from "./account-networks";
import { AlertIcon, FilmIcon, LinkIcon, PlusIcon, ScissorsIcon, TrashIcon, XIcon } from "./icons";
import { PLATFORM_META } from "./platforms";
import { networkName, readNetwork } from "./publishing-client";
import { storyFormatLabel } from "./story-formats";
import { Badge, Button, Card, Feedback, Field, Input, Select, Spinner, Textarea, formatDate } from "./ui";
import { askConfirm } from "./confirm-dialog";
type StoryOption = { id: string; title: string; kind: StoryKind };
type Message = { ok: boolean; text: string } | null;
/** Executa uma chamada, mostra o retorno e atualiza a página do servidor. */
function useMutation() {
const router = useRouter();
const [pending, setPending] = useState<string | null>(null);
const [message, setMessage] = useState<Message>(null);
const [, startTransition] = useTransition();
async function run<T>(key: string, call: () => Promise<{ ok: true; data: T } | { ok: false; error: string }>, success: string | ((data: T) => string), after?: (data: T) => void) {
setPending(key);
setMessage(null);
const result = await call();
setPending(null);
if (!result.ok) {
setMessage({ ok: false, text: result.error });
return false;
}
setMessage({ ok: true, text: typeof success === "function" ? success(result.data) : success });
after?.(result.data);
startTransition(() => router.refresh());
return true;
}
return { pending, message, setMessage, run, router };
}
/* ---------- Novo canal de publicação ---------- */
export function AccountCreateForm() {
const { pending, message, run, router } = useMutation();
async function submit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
const form = new FormData(e.currentTarget);
await run<AccountView>("create",
() => apiCall<AccountView>("/api/accounts", "POST", {
name: String(form.get("name") ?? ""), niche: String(form.get("niche") ?? ""), notes: String(form.get("notes") ?? ""),
}),
(a) => `Canal “${a.name}” criado.`,
(a) => router.push(`/accounts?account=${encodeURIComponent(a.id)}`));
}
return (
<Card eyebrow={<><PlusIcon size={13} />Novo canal</>} title="Criar canal de publicação"
description="Reúne seus perfis no YouTube, TikTok e Instagram."
actions={<Link href="/accounts" aria-label="Cancelar" className="grid size-8 place-items-center rounded-control text-fg-subtle hover:bg-raised hover:text-fg"><XIcon size={16} /></Link>}>
<form onSubmit={submit} className="grid gap-4">
<Field label="Nome" hint="Entre 2 e 60 caracteres. Vira o identificador do canal.">
<Input name="name" required minLength={2} maxLength={60} placeholder="Ex.: Contos de Bolso" autoFocus />
</Field>
<Field label="Nicho (opcional)">
<Input name="niche" maxLength={60} placeholder="Ex.: suspense leve, humor" />
</Field>
<Field label="Notas (opcional)">
<Textarea name="notes" rows={3} maxLength={500} placeholder="Público, horários de postagem, combinados…" />
</Field>
<div className="flex flex-wrap items-center gap-3">
<Button disabled={pending !== null}>{pending ? <><Spinner />Criando…</> : <><PlusIcon size={16} />Criar canal</>}</Button>
</div>
{message && <Feedback ok={message.ok}>{message.text}</Feedback>}
</form>
</Card>
);
}
/* ---------- Detalhe do canal de publicação ---------- */
export function AccountDetail({ account, stories }: { account: AccountView; stories: StoryOption[] }) {
const { pending, message, run, router } = useMutation();
const base = `/api/accounts/${encodeURIComponent(account.id)}`;
const active = account.stories.filter((s) => s.status === "active");
const ended = account.stories.filter((s) => s.status === "ended");
const linkable = stories.filter((s) => !active.some((a) => a.story_id === s.id));
async function save(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
const form = new FormData(e.currentTarget);
await run("save", () => apiCall<AccountView>(base, "PATCH", {
name: String(form.get("name") ?? ""), niche: String(form.get("niche") ?? ""), notes: String(form.get("notes") ?? ""),
}), "Dados do canal salvos.");
}
async function linkStory(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
const storyId = String(new FormData(e.currentTarget).get("storyId") ?? "");
if (!storyId) return;
const title = stories.find((s) => s.id === storyId)?.title ?? storyId;
await run("link-story", () => apiCall<AccountView>(`${base}/stories`, "POST", { storyId }), `“${title}” vinculada e ativa neste canal.`);
}
return (
<div className="grid gap-6">
{message && <Feedback ok={message.ok}>{message.text}</Feedback>}
<Card eyebrow="Canal de publicação" title={account.name}
description={<>Criada em {formatDate(account.created_at)} · identificador <code>{account.id}</code></>}>
<form key={account.updated_at} onSubmit={save} className="grid gap-4">
<div className="grid gap-4 sm:grid-cols-2">
<Field label="Nome"><Input name="name" required minLength={2} maxLength={60} defaultValue={account.name} /></Field>
<Field label="Nicho"><Input name="niche" maxLength={60} defaultValue={account.niche} placeholder="Ex.: suspense leve" /></Field>
</div>
<Field label="Notas"><Textarea name="notes" rows={2} maxLength={500} defaultValue={account.notes} /></Field>
<div><Button variant="secondary" size="sm" disabled={pending !== null}>{pending === "save" ? <><Spinner />Salvando…</> : "Salvar dados"}</Button></div>
</form>
</Card>
<PublishingNetworksCard account={account} />
<PublishingRulesCard account={account} />
<Card title="Histórias" description="Várias podem estar ativas ao mesmo tempo. Encerrar tira das ativas, mas a história fica no histórico e nas métricas.">
<div className="grid gap-5">
{active.length === 0 ? (
<p className="rounded-control border border-dashed border-line-strong px-4 py-3 text-sm text-fg-subtle">Nenhuma história ativa neste canal.</p>
) : (
<ul className="grid divide-y divide-line rounded-control border border-line">
{active.map((s) => (
<li key={s.story_id} className="flex flex-wrap items-center gap-x-3 gap-y-2 px-3.5 py-2.5">
<FilmIcon size={16} className="text-fg-subtle" />
<span className="grid min-w-40 flex-1 gap-0.5">
<Link href={`/stories/${s.story_id}`} className="truncate text-sm font-medium text-fg hover:text-accent hover:underline">{s.title}</Link>
<span className="text-xs text-fg-subtle">{storyFormatLabel(s.kind)} · desde {formatDate(s.linked_at)}</span>
</span>
<Badge tone="success">ativa</Badge>
<Button variant="ghost" size="sm" disabled={pending !== null}
onClick={async () => {
if (!(await askConfirm({ title: `Encerrar “${s.title}” neste canal?`,
message: "Ela sai das ativas, mas fica no histórico e nas métricas.", confirmLabel: "Encerrar" }))) return;
void run(`end-${s.story_id}`, () => apiCall<AccountView>(`${base}/stories/${encodeURIComponent(s.story_id)}`, "DELETE"), `“${s.title}” encerrada neste canal.`);
}}>
{pending === `end-${s.story_id}` ? <Spinner /> : null}Encerrar
</Button>
</li>
))}
</ul>
)}
<form onSubmit={linkStory} className="flex flex-wrap items-end gap-3">
<Field label="Vincular história" className="min-w-0 flex-1 basis-56">
<Select name="storyId" defaultValue="" required disabled={linkable.length === 0}>
<option value="" disabled>{linkable.length === 0 ? "Todas as histórias já estão ativas" : "Escolha uma história…"}</option>
{linkable.map((s) => <option key={s.id} value={s.id}>{s.title}{ended.some((e) => e.story_id === s.id) ? " (reativar)" : ""}</option>)}
</Select>
</Field>
<Button disabled={pending !== null || linkable.length === 0}>
{pending === "link-story" ? <Spinner /> : <LinkIcon size={16} />}Vincular
</Button>
</form>
{ended.length > 0 && (
<div className="grid gap-2">
<h3 className="text-eyebrow font-semibold text-fg-subtle uppercase">Histórico · encerradas</h3>
<ul className="grid gap-1 text-sm">
{ended.map((s) => (
<li key={s.story_id} className="flex flex-wrap items-center gap-x-3 gap-y-1 rounded-lg px-2 py-1.5 text-fg-muted hover:bg-raised/40">
<Link href={`/stories/${s.story_id}`} className="min-w-0 truncate hover:text-fg hover:underline">{s.title}</Link>
<span className="text-xs text-fg-subtle">{formatDate(s.linked_at)} → {formatDate(s.ended_at)}</span>
</li>
))}
</ul>
</div>
)}
</div>
</Card>
<LiveChannelsCard account={account} base={base} pending={pending} run={run} />
<section aria-label="Apagar canal" className="flex flex-wrap items-center justify-between gap-4 rounded-card border border-danger/25 bg-danger-soft/40 px-6 py-4">
<p className="text-sm text-fg-muted">Apagar o canal remove as conexões com as redes, os vínculos e o histórico de publicações dele. As histórias continuam, e os vídeos já publicados ficam nas redes.</p>
<Button variant="danger" size="sm" disabled={pending !== null}
onClick={async () => {
if (!(await askConfirm({ title: `Apagar o canal “${account.name}”?`,
message: "Conexões com as redes, vínculos e histórico de publicações saem junto. Não dá para desfazer.",
confirmLabel: "Apagar canal", tone: "danger" }))) return;
void run("delete", () => apiCall<{ ok: true }>(base, "DELETE"), "Canal apagado.", () => router.push("/accounts"));
}}>
{pending === "delete" ? <Spinner /> : <TrashIcon size={15} />}Apagar canal
</Button>
</section>
</div>
);
}
/* ---------- Fontes do Clipador (no código: channels) ---------- */
type Run = ReturnType<typeof useMutation>["run"];
type Catalog = { ok: true; channels: ClipperChannel[] } | { ok: false; offline: boolean; error: string } | null;
/** Fontes (lives) do Clipador ligadas ao canal: os cortes aprovados delas saem nas redes deste canal. */
function LiveChannelsCard({ account, base, pending, run }: { account: AccountView; base: string; pending: string | null; run: Run }) {
const [catalog, setCatalog] = useState<Catalog>(null);
useEffect(() => {
let cancelled = false;
void clipperCall<{ channels: ClipperChannel[] }>("channels").then((r) => {
if (cancelled) return;
setCatalog(r.ok ? { ok: true, channels: r.data.channels } : { ok: false, offline: isOfflineError(r.error), error: r.error });
});
return () => { cancelled = true; };
}, []);
const channels = catalog?.ok ? catalog.channels : [];
const find = (id: string) => channels.find((c) => c.id === id);
const label = (id: string) => {
const c = find(id);
return c ? `${c.displayName || c.channel} · ${PLATFORM_LABEL[c.platform]}` : id;
};
const active = account.channels.filter((c) => c.status === "active");
const ended = account.channels.filter((c) => c.status === "ended");
const linkable = channels.filter((c) => !active.some((a) => a.channel_id === c.id));
async function link(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
const channelId = String(new FormData(e.currentTarget).get("channelId") ?? "");
if (!channelId) return;
await run("link-channel", () => apiCall<AccountView>(`${base}/channels`, "POST", { channelId }), `${label(channelId)} ligada a este canal.`);
}
return (
<Card eyebrow={<><ScissorsIcon size={13} />Clipador</>} title="Fontes de corte"
description={<>Lives de onde saem os cortes publicados por este canal. As fontes são cadastradas no <Link href="/clipper?tab=canais" className="text-fg-muted underline underline-offset-2 hover:text-fg">Clipador</Link>.</>}>
<div className="grid gap-5">
{catalog && !catalog.ok && (
<p className="flex items-start gap-2 rounded-control border border-warning/25 bg-warning-soft px-3 py-2 text-xs text-warning">
<AlertIcon size={14} className="mt-px" />
{catalog.offline ? "O Clipador está fora do ar: as fontes aparecem pelo identificador e não dá para ligar novas agora." : catalog.error}
</p>
)}
{active.length === 0 ? (
<p className="rounded-control border border-dashed border-line-strong px-4 py-3 text-sm text-fg-subtle">Nenhuma fonte ligada a este canal.</p>
) : (
<ul className="grid divide-y divide-line rounded-control border border-line">
{active.map((l) => {
const c = find(l.channel_id);
return (
<li key={l.channel_id} className="flex flex-wrap items-center gap-x-3 gap-y-2 px-3.5 py-2.5">
{c ? <PlatformIcon platform={c.platform} size={16} className="text-fg-subtle" /> : <ScissorsIcon size={16} className="text-fg-subtle" />}
<span className="grid min-w-40 flex-1 gap-0.5">
<span className="truncate text-sm font-medium text-fg">{c ? c.displayName || c.channel : <code>{l.channel_id}</code>}</span>
<span className="text-xs text-fg-subtle">{c ? `${PLATFORM_LABEL[c.platform]} · ` : ""}desde {formatDate(l.linked_at)}</span>
</span>
{c && !c.authorized && <Badge tone="warning" dot={false}>sem autorização</Badge>}
<Badge tone="success">ativa</Badge>
<Button variant="ghost" size="sm" disabled={pending !== null}
onClick={async () => {
if (!(await askConfirm({ title: `Encerrar ${label(l.channel_id)} neste canal?`,
message: "O vínculo fica no histórico.", confirmLabel: "Encerrar" }))) return;
void run(`end-ch-${l.channel_id}`, () => apiCall<AccountView>(`${base}/channels/${encodeURIComponent(l.channel_id)}`, "DELETE"),
`${label(l.channel_id)} encerrada neste canal.`);
}}>
{pending === `end-ch-${l.channel_id}` ? <Spinner /> : null}Encerrar
</Button>
</li>
);
})}
</ul>
)}
<form onSubmit={link} className="flex flex-wrap items-end gap-3">
<Field label="Ligar fonte" className="min-w-0 flex-1 basis-56">
<Select name="channelId" defaultValue="" required disabled={!catalog?.ok || linkable.length === 0}>
<option value="" disabled>
{catalog === null ? "Carregando fontes…" : !catalog.ok ? "Clipador indisponível"
: channels.length === 0 ? "Nenhuma fonte cadastrada no Clipador" : linkable.length === 0 ? "Todas as fontes já estão ligadas" : "Escolha uma fonte…"}
</option>
{linkable.map((c) => (
<option key={c.id} value={c.id}>
{c.displayName || c.channel} · {PLATFORM_LABEL[c.platform]}{ended.some((e) => e.channel_id === c.id) ? " (religar)" : ""}
</option>
))}
</Select>
</Field>
<Button disabled={pending !== null || !catalog?.ok || linkable.length === 0}>
{pending === "link-channel" ? <Spinner /> : <LinkIcon size={16} />}Ligar
</Button>
</form>
{ended.length > 0 && (
<div className="grid gap-2">
<h3 className="text-eyebrow font-semibold text-fg-subtle uppercase">Histórico · encerradas</h3>
<ul className="grid gap-1 text-sm">
{ended.map((l) => (
<li key={l.channel_id} className="flex flex-wrap items-center gap-x-3 gap-y-1 rounded-lg px-2 py-1.5 text-fg-muted hover:bg-raised/40">
<span className="min-w-0 truncate">{label(l.channel_id)}</span>
<span className="text-xs text-fg-subtle">{formatDate(l.linked_at)} → {formatDate(l.ended_at)}</span>
</li>
))}
</ul>
</div>
)}
</div>
</Card>
);
}
/** Ícone de cada rede com o @ (conectada) ou o estado em palavras, para listas densas. */
export function NetworkHandles({ networks, compact = false }: { networks: AccountView["networks"]; compact?: boolean }): ReactNode {
const shown = PLATFORMS.map((p) => readNetwork(networks.find((n) => n.platform === p), p)).filter((n) => n.status !== "disconnected");
if (shown.length === 0) return <span className="text-xs text-fg-subtle">nenhuma rede conectada</span>;
return (
<span className="flex min-w-0 flex-wrap items-center gap-x-3.5 gap-y-1 text-xs text-fg-muted">
{shown.map((n) => {
const Icon = PLATFORM_META[n.platform].icon;
const text = n.status === "connected" ? networkName(n) ?? "conectado"
: n.status === "needs_login" || n.status === "expired" ? "entrar de novo" : n.status === "error" ? "erro" : "conectando";
const attention = n.status !== "connected";
return (
<span key={n.platform} className="inline-flex min-w-0 items-center gap-1.5" title={`${PLATFORM_META[n.platform].label}: ${text}`}>
<Icon size={14} className="text-fg-subtle" />
{attention && <AlertIcon size={12} className="text-warning" />}
{compact ? <span className="sr-only">{PLATFORM_META[n.platform].label}: {text}</span>
: <span className={attention ? "truncate text-warning" : "truncate"}>{text}</span>}
</span>
);
})}
</span>
);
}
+318
View File
@@ -0,0 +1,318 @@
"use client";
// Canal de publicação: as três redes (estado em palavras, Conectar/Entrar de novo/Desconectar e os
// ajustes de cada uma) e as regras do canal (aprovação, quando publicar, aviso de IA).
// Cada mudança vai direto para /api/accounts/[id]/…; depois, router.refresh() relê a página do servidor.
import { useRouter } from "next/navigation";
import { useState, useTransition, type FormEvent } from "react";
import type { AccountView } from "@/lib/accounts";
import { PLATFORMS, type Platform } from "@/lib/types";
import { askConfirm } from "./confirm-dialog";
import { ConnectWizard } from "./connect-wizard";
import { CheckIcon, ChevronDownIcon, LinkIcon, RefreshIcon, SettingsIcon, UnlinkIcon } from "./icons";
import { PLATFORM_META } from "./platforms";
import {
DAILY_LIMIT_MAX, MODE_LABEL, checkNetwork, disconnectNetwork, readNetwork, readRules, updateNetwork, updateRules,
type AiLabel, type Privacy, type PublishingNetwork, type PublishingRules, type TiktokMode, type PublishTiming,
} from "./publishing-client";
import { NetworkStatusBadge, TextLink } from "./publishing-ui";
import { Button, Card, ChoiceGroup, Feedback, Field, Input, Select, Spinner, Switch, cx, formatRelative } from "./ui";
type Message = { ok: boolean; text: string } | null;
function useRefresh() {
const router = useRouter();
const [, startTransition] = useTransition();
return () => startTransition(() => router.refresh());
}
/* ---------- Redes do canal ---------- */
export function PublishingNetworksCard({ account }: { account: AccountView }) {
const refresh = useRefresh();
const [wizard, setWizard] = useState<{ platform: Platform; reconnect: boolean } | null>(null);
const networks = PLATFORMS.map((p) => {
const raw = account.networks.find((n) => n.platform === p);
return { platform: p, exists: raw !== undefined, network: readNetwork(raw, p) };
});
const target = wizard ? networks.find((n) => n.platform === wizard.platform) : undefined;
return (
<Card title="Redes"
description="Onde os vídeos deste canal são publicados. Conecte cada rede uma vez; o CenaForge envia sozinho depois que você aprova.">
<ul className="grid divide-y divide-line rounded-control border border-line">
{networks.map((n) => (
<NetworkRow key={`${n.platform}-${account.updated_at}`} accountId={account.id} platform={n.platform} exists={n.exists}
network={n.network} onChanged={refresh}
onConnect={(reconnect) => setWizard({ platform: n.platform, reconnect })} />
))}
</ul>
<p className="mt-4 text-xs leading-relaxed text-fg-subtle">
O painel precisa estar aberto para publicar e agendar. Contas e chaves ficam só neste computador.
</p>
{wizard && target && (
<ConnectWizard accountId={account.id} accountName={account.name} platform={wizard.platform}
network={target.exists ? target.network : null} reconnect={wizard.reconnect && target.network.mode !== null}
onClose={() => { setWizard(null); refresh(); }} onChanged={refresh} />
)}
</Card>
);
}
function NetworkRow({ accountId, platform, exists, network, onChanged, onConnect }: {
accountId: string; platform: Platform; exists: boolean; network: PublishingNetwork;
onChanged: () => void; onConnect: (reconnect: boolean) => void;
}) {
const meta = PLATFORM_META[platform];
const Icon = meta.icon;
const [busy, setBusy] = useState<string | null>(null);
const [message, setMessage] = useState<Message>(null);
const [open, setOpen] = useState(false);
const status = network.status;
const linked = status !== "disconnected";
const needsLogin = status === "needs_login" || status === "expired";
async function check() {
setBusy("check");
setMessage(null);
const r = await checkNetwork(accountId, platform);
setBusy(null);
setMessage(r.ok
? { ok: r.data.status === "connected", text: r.data.status === "connected" ? `${meta.label}: tudo certo com a conexão.` : `${meta.label}: ${r.data.last_error ?? "a conexão precisa de atenção."}` }
: { ok: false, text: r.error });
onChanged();
}
async function disconnect() {
const ok = await askConfirm({
title: `Desconectar o ${meta.label} deste canal?`,
message: "O CenaForge apaga o acesso guardado (e a janela de sessão, se houver). Vídeos já publicados continuam na rede. Para voltar a publicar, conecte de novo.",
confirmLabel: "Desconectar", tone: "danger",
});
if (!ok) return;
setBusy("disconnect");
setMessage(null);
const r = await disconnectNetwork(accountId, platform);
setBusy(null);
setMessage(r.ok ? { ok: true, text: `${meta.label} desconectado.` } : { ok: false, text: r.error });
onChanged();
}
return (
<li className="grid gap-3 px-4 py-3.5">
<div className="flex flex-wrap items-center gap-x-3 gap-y-2.5">
<span className={cx("grid size-9 shrink-0 place-items-center rounded-lg border",
status === "connected" ? "border-line-strong bg-raised text-fg" : "border-line bg-sunken/40 text-fg-subtle")}>
<Icon size={18} />
</span>
<span className="grid min-w-40 flex-1 gap-1">
<span className="flex flex-wrap items-center gap-2">
<span className="text-sm font-semibold text-fg">{meta.label}</span>
<NetworkStatusBadge network={network} />
</span>
<span className="text-xs text-fg-subtle">
{network.mode ? MODE_LABEL[network.mode] : "Escolha como conectar"}
{network.checked_at && <> · conferido {formatRelative(network.checked_at)}</>}
{exists && !network.enabled && <> · <span className="font-medium text-warning">pausado neste canal</span></>}
</span>
</span>
<span className="flex flex-wrap gap-1.5">
{status === "disconnected" && (
<Button size="sm" onClick={() => onConnect(false)} disabled={busy !== null}><LinkIcon size={15} />Conectar</Button>
)}
{(needsLogin || status === "connecting") && (
<Button size="sm" onClick={() => onConnect(true)} disabled={busy !== null}><RefreshIcon size={15} />Entrar de novo</Button>
)}
{status === "error" && (
<Button size="sm" onClick={() => onConnect(false)} disabled={busy !== null}><RefreshIcon size={15} />Conectar de novo</Button>
)}
{status === "connected" && (
<Button variant="secondary" size="sm" onClick={() => void check()} disabled={busy !== null}>
{busy === "check" ? <Spinner className="size-3.5" /> : <CheckIcon size={15} />}Conferir conexão
</Button>
)}
{linked && (
<Button variant="ghost" size="sm" onClick={() => void disconnect()} disabled={busy !== null}
className="hover:bg-danger-soft hover:text-danger">
{busy === "disconnect" ? <Spinner className="size-3.5" /> : <UnlinkIcon size={15} />}Desconectar
</Button>
)}
{exists && (
<Button variant="ghost" size="sm" aria-expanded={open} aria-controls={`ajustes-${platform}`} onClick={() => setOpen((v) => !v)}>
<SettingsIcon size={15} />Ajustes desta rede
<ChevronDownIcon size={14} className={cx("transition-transform motion-reduce:transition-none", open && "rotate-180")} />
</Button>
)}
</span>
</div>
{status === "error" && network.last_error && (
<p className="rounded-control border border-danger/30 bg-danger-soft px-3 py-2 text-xs break-words text-danger sm:ml-12">{network.last_error}</p>
)}
<div aria-live="polite" className="empty:hidden sm:ml-12">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
{exists && (
<div id={`ajustes-${platform}`} hidden={!open} className="sm:ml-12">
<NetworkSettings accountId={accountId} network={network} onChanged={onChanged} />
</div>
)}
</li>
);
}
/** Ajustes de uma rede no canal: ligada, máximo por dia, privacidade e, no TikTok, direto ou rascunho. */
function NetworkSettings({ accountId, network, onChanged }: { accountId: string; network: PublishingNetwork; onChanged: () => void }) {
const platform = network.platform;
const label = PLATFORM_META[platform].label;
const [values, setValues] = useState({ enabled: network.enabled, privacy: network.privacy, tiktokMode: network.tiktok_mode });
const [limit, setLimit] = useState(String(network.daily_limit));
const [busy, setBusy] = useState<string | null>(null);
const [message, setMessage] = useState<Message>(null);
async function save(key: string, patch: Parameters<typeof updateNetwork>[2], text: string, revert: () => void) {
setBusy(key);
setMessage(null);
const r = await updateNetwork(accountId, platform, patch);
setBusy(null);
if (!r.ok) { revert(); setMessage({ ok: false, text: r.error }); return; }
setMessage({ ok: true, text });
onChanged();
}
function saveLimit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
const n = Math.round(Number(limit));
if (!Number.isFinite(n) || n < 1 || n > DAILY_LIMIT_MAX) { setMessage({ ok: false, text: `Use um número de 1 a ${DAILY_LIMIT_MAX}.` }); return; }
void save("limit", { dailyLimit: n }, `Máximo de ${n} por dia no ${label}.`, () => setLimit(String(network.daily_limit)));
}
const privacyOptions: { value: Privacy; label: string }[] = platform === "youtube"
? [{ value: "public", label: "Público" }, { value: "unlisted", label: "Não listado (só quem tem o link)" }, { value: "private", label: "Privado (só você)" }]
: [{ value: "public", label: "Público" }, { value: "private", label: "Só eu" }];
return (
<div className="grid gap-5 rounded-control border border-line bg-sunken/30 p-4">
<Switch label={`Publicar no ${label} por este canal`} checked={values.enabled} busy={busy === "enabled"} disabled={busy !== null}
hint="Desligado: os vídeos deste canal não vão para esta rede, mas a conexão continua guardada."
onChange={(enabled) => {
const before = values.enabled;
setValues((v) => ({ ...v, enabled }));
void save("enabled", { enabled }, enabled ? `${label} ligado neste canal.` : `${label} pausado neste canal.`,
() => setValues((v) => ({ ...v, enabled: before })));
}} />
<div className="grid gap-5 sm:grid-cols-2">
<form onSubmit={saveLimit} className="grid content-start gap-2">
<Field label="Máximo por dia" hint="Quantos vídeos, no máximo, saem nesta rede por dia. Os outros esperam o dia seguinte.">
<span className="flex items-center gap-2">
<Input type="number" inputMode="numeric" min={1} max={DAILY_LIMIT_MAX} step={1} value={limit} onChange={(e) => setLimit(e.target.value)} className="w-24" />
{limit !== String(network.daily_limit) && (
<Button type="submit" variant="secondary" size="sm" disabled={busy !== null}>
{busy === "limit" ? <Spinner className="size-3.5" /> : <CheckIcon size={15} />}Salvar
</Button>
)}
</span>
</Field>
</form>
{platform !== "instagram" ? (
<Field label="Quem pode ver" hint={platform === "tiktok"
? "Sem a aprovação do TikTok, o modo oficial só publica como “Só eu”."
: "“Não listado” não aparece no canal nem na busca."}>
<Select value={values.privacy} disabled={busy !== null}
onChange={(e) => {
const privacy = e.target.value as Privacy;
const before = values.privacy;
setValues((v) => ({ ...v, privacy }));
void save("privacy", { privacy }, "Privacidade salva.", () => setValues((v) => ({ ...v, privacy: before })));
}}>
{privacyOptions.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
</Select>
</Field>
) : (
<p className="text-xs leading-relaxed text-fg-subtle sm:pt-7">No Instagram, os Reels saem sempre públicos.</p>
)}
</div>
{platform === "tiktok" && (
<div className="grid gap-2">
<ChoiceGroup<TiktokMode> name={`tiktok-mode-${accountId}`} legend="Como mandar para o TikTok"
value={values.tiktokMode}
onChange={(tiktokMode) => {
const before = values.tiktokMode;
setValues((v) => ({ ...v, tiktokMode }));
void save("tiktok", { tiktokMode }, tiktokMode === "direct" ? "TikTok: publicar direto." : "TikTok: mandar como rascunho.",
() => setValues((v) => ({ ...v, tiktokMode: before })));
}}
options={[
{ value: "direct", label: "Publicar direto", hint: "Sai na hora no perfil" },
{ value: "draft", label: "Mandar como rascunho", hint: "Você termina no app" },
]} />
<p className="text-xs leading-relaxed text-fg-subtle">Rascunho chega na caixa de entrada do app do TikTok; você revisa e publica de lá.</p>
</div>
)}
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</div>
);
}
/* ---------- Regras do canal ---------- */
export function PublishingRulesCard({ account }: { account: AccountView }) {
const refresh = useRefresh();
const [rules, setRules] = useState<PublishingRules>(() => readRules(account));
const [busy, setBusy] = useState<string | null>(null);
const [message, setMessage] = useState<Message>(null);
async function save<K extends keyof PublishingRules>(key: K, value: PublishingRules[K], text: string) {
const before = rules[key];
setRules((r) => ({ ...r, [key]: value }));
setBusy(key);
setMessage(null);
const body = key === "approval_mode" ? { approvalMode: value as PublishingRules["approval_mode"] }
: key === "timing" ? { timing: value as PublishTiming } : { aiLabel: value as AiLabel };
const r = await updateRules(account.id, body);
setBusy(null);
if (!r.ok) { setRules((cur) => ({ ...cur, [key]: before })); setMessage({ ok: false, text: r.error }); return; }
setMessage({ ok: true, text });
refresh();
}
return (
<Card title="Como publicar" description="Valem para todas as redes deste canal.">
<div className="grid gap-6">
<Switch label="Aprovar sozinho os vídeos novos?" checked={rules.approval_mode === "auto"} busy={busy === "approval_mode"} disabled={busy !== null}
hint={rules.approval_mode === "auto"
? "Ligado: cada vídeo novo das histórias e fontes deste canal é publicado sem esperar você."
: <>Desligado: cada vídeo novo espera você aprovar em <TextLink href="/publishing">Publicações</TextLink>.</>}
onChange={(on) => void save("approval_mode", on ? "auto" : "manual",
on ? "Aprovação automática ligada." : "Aprovação automática desligada: os vídeos esperam você.")} />
<div className="grid gap-2">
<ChoiceGroup<PublishTiming> name={`timing-${account.id}`} legend="Quando publicar?" value={rules.timing}
onChange={(timing) => void save("timing", timing, timing === "now" ? "Publica assim que aprovar." : "Publica no próximo horário bom.")}
options={[
{ value: "now", label: "Na hora", hint: "Assim que aprovar" },
{ value: "best_slot", label: "No próximo horário bom", hint: "Mais gente vendo" },
]} />
<p className="text-xs leading-relaxed text-fg-subtle">
Os horários bons de cada rede ficam em <TextLink href="/settings">Configurações</TextLink>. Entre dois vídeos na mesma rede fica pelo menos 1 hora.
</p>
</div>
<div className="grid gap-2">
<ChoiceGroup<AiLabel> name={`ai-${account.id}`} legend="Marcar como feito com IA?" value={rules.ai_label}
onChange={(aiLabel) => void save("ai_label", aiLabel, "Aviso de IA salvo.")}
options={[
{ value: "auto", label: "Automático" },
{ value: "always", label: "Sempre" },
{ value: "never", label: "Nunca" },
]} />
<p className="text-xs leading-relaxed text-fg-subtle">
As redes pedem um aviso quando o vídeo tem voz ou imagem realista feita por IA. Automático marca só quando o episódio usa voz clonada.
</p>
</div>
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</div>
</Card>
);
}
+402
View File
@@ -0,0 +1,402 @@
"use client";
// Console do agente: escolhe a tarefa (que define o agente padrão), o agente, o modelo e o
// contexto; envia o pedido e mostra ao vivo o que o agente faz (texto, ferramentas, resultado, custo).
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useRef, useState, type ComponentType } from "react";
import type { AgentEvent, AgentKind, AgentRun, Provider, StoryKind } from "@/lib/types";
import { BookIcon, CubeIcon, ChatIcon, ClapperIcon, PenIcon, SendIcon, SparkIcon, StopIcon, TerminalIcon } from "./icons";
import { unitTerms } from "./story-formats";
import { Badge, Button, EmptyState, Feedback, Field, Kbd, Select, StatusBadge, Textarea, cx } from "./ui";
type ProviderInfo = { id: Provider; available: boolean; version: string | null; note: string };
type StoryOption = { id: string; title: string; kind: StoryKind; episodes: { id: number; number: number; title: string }[] };
/** Padrões calculados no servidor (defaultProviderFor / defaultModelFor). */
export type AgentDefaults = {
provider: Record<AgentKind, Provider>;
preferred: Record<AgentKind, Provider>;
model: Record<AgentKind, Record<Provider, string>>;
};
const KINDS: { id: AgentKind; label: string; description: string; icon: ComponentType<{ size?: number }> }[] = [
{ id: "story", label: "Nova história", description: "Bíblia, ep01 e título a partir de um texto", icon: BookIcon },
{ id: "script", label: "Roteiro", description: "Escreve o episódio escolhido", icon: PenIcon },
{ id: "scene", label: "Cena", description: "Monta o JSON da cena a partir do roteiro", icon: ClapperIcon },
{ id: "godot", label: "Cena no Godot", description: "Constrói uma cena 3D nova e guarda na biblioteca", icon: CubeIcon },
{ id: "free", label: "Pedido livre", description: "Ajustes no projeto, testes, iluminação", icon: ChatIcon },
];
export const PROVIDER_LABEL: Record<Provider, string> = { claude: "Claude Code", codex: "GPT · Codex" };
const PROVIDER_SHORT: Record<Provider, string> = { claude: "Claude", codex: "GPT" };
const PLACEHOLDER: Record<AgentKind, string> = {
story: "Ex.: Um entregador recebe um pacote sem remetente; toda vez que tenta entregar, o endereço muda. Suspense leve com humor.",
script: "Ex.: Escreva o episódio com tom de suspense leve; o entregador desconfia do pacote.",
scene: "Ex.: Monte a cena a partir do roteiro; fim de tarde, moto azul.",
free: "Ex.: Melhore a iluminação do cenário e rode os testes.",
branches: "Ex.: Prepare as vertentes do episódio com consequências bem diferentes entre si.",
godot: "Ex.: Faça um campo de futebol de estádio, gramado listrado, traves e torcida; câmera de transmissão e atrás do gol. Depois, o Pelé batendo o pênalti do milésimo gol, de 1969, no Maracanã.",
};
const SUGGESTIONS: { kind: AgentKind; text: string }[] = [
{ kind: "script", text: "Escreva o episódio com tom de suspense leve; o entregador desconfia do pacote." },
{ kind: "scene", text: "Monte a cena a partir do roteiro; fim de tarde, moto azul." },
{ kind: "free", text: "Melhore a iluminação do cenário e rode os testes." },
];
export function AgentConsole(props: {
providers: ProviderInfo[];
models: Record<Provider, { id: string; label: string }[]>;
defaults: AgentDefaults;
stories: StoryOption[];
initial: { storyId?: string; episodeId?: number; kind?: AgentKind; runId?: number; request?: string };
viewing: AgentRun | null;
}) {
const router = useRouter();
const initialKind = props.initial.kind ?? "free";
const initialProvider = props.viewing?.provider ?? props.defaults.provider[initialKind];
const [kind, setKind] = useState<AgentKind>(initialKind);
const [provider, setProvider] = useState<Provider>(initialProvider);
const [model, setModel] = useState<string>(props.viewing?.model ?? props.defaults.model[initialKind][initialProvider]);
const [storyId, setStoryId] = useState(props.initial.storyId ?? "");
const [episodeId, setEpisodeId] = useState<number | "">(props.initial.episodeId ?? "");
const [request, setRequest] = useState(props.initial.request ?? "");
const [sentPrompt, setSentPrompt] = useState<string | null>(null);
const [runId, setRunId] = useState<number | null>(props.initial.runId ?? null);
const [events, setEvents] = useState<AgentEvent[]>([]);
const [status, setStatus] = useState<string | null>(props.viewing?.status ?? null);
const [error, setError] = useState<string | null>(null);
const log = useRef<HTMLDivElement>(null);
/** Mensagem enviada durante a execução, aguardando o agente fechar ("Enviar ao terminar"). */
const [queued, setQueued] = useState<string | null>(null);
/** Texto da mensagem durante a execução: vira o "pedido" exibido na continuação. */
const pendingMessage = useRef<string | null>(null);
const story = props.stories.find((s) => s.id === storyId);
const terms = unitTerms(story?.kind);
useEffect(() => {
if (!runId) return;
setEvents([]);
const source = new EventSource(`/api/agent/runs/${runId}/events`);
source.addEventListener("event", (m) => setEvents((prev) => [...prev, JSON.parse((m as MessageEvent).data)]));
source.addEventListener("end", (m) => {
const run = JSON.parse((m as MessageEvent).data) as (AgentRun & { followUpRunId?: number | null }) | null;
source.close();
// Mensagem enviada durante a execução: o servidor já retomou a sessão; seguimos para a continuação.
if (run?.followUpRunId) {
setRunId(run.followUpRunId);
setStatus("running");
setSentPrompt(pendingMessage.current);
pendingMessage.current = null;
setQueued(null);
router.replace(`/agent?run=${run.followUpRunId}`, { scroll: false });
return;
}
setStatus(run?.status ?? "success");
setQueued(null);
router.refresh();
});
source.onerror = () => source.close();
return () => source.close();
}, [runId, router]);
// Rola só a área da conversa (não a página). Sempre com chaves: nenhum useEffect devolve valor
// implícito (no Chromium novo, scrollIntoView devolve uma Promise e quebraria a limpeza do React).
useEffect(() => {
const el = log.current;
if (el) el.scrollTop = el.scrollHeight;
}, [events]);
/** Trocar de tarefa troca também o agente e o modelo padrão dela. */
function chooseKind(next: AgentKind) {
const nextProvider = props.defaults.provider[next];
setKind(next);
setProvider(nextProvider);
setModel(props.defaults.model[next][nextProvider]);
}
function chooseProvider(next: Provider) {
setProvider(next);
setModel(props.defaults.model[kind][next]);
}
async function send(resume: boolean) {
setError(null);
const sent = request;
const r = await fetch("/api/agent/runs", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
provider, model, kind, request,
storyId: storyId || null, episodeId: episodeId || null,
resumeRunId: resume ? runId : null,
}),
});
const body = await r.json();
if (!r.ok) return setError(body.error);
setStatus("running");
setRunId(body.id);
setSentPrompt(sent);
setRequest("");
router.replace(`/agent?run=${body.id}`, { scroll: false });
}
/** Mensagem com o agente rodando: "now" interrompe e corrige; "queue" envia quando ele terminar. */
async function sendDuringRun(mode: "now" | "queue") {
if (!runId) return;
setError(null);
const text = request.trim();
const r = await fetch(`/api/agent/runs/${runId}/messages`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text, mode }),
});
const body = await r.json();
if (!r.ok) return setError(body.error);
pendingMessage.current = text;
setQueued(mode === "queue" ? text : null);
setRequest("");
}
async function cancel() {
if (runId) await fetch(`/api/agent/runs/${runId}/cancel`, { method: "POST" });
}
const running = status === "running";
// Claude (--resume) e Codex (exec resume) retomam a sessão; só vale para o mesmo agente.
const canResume = !!runId && !running && provider === props.viewing?.provider && !!props.viewing?.session_id;
const prompt = props.viewing && props.viewing.id === runId ? props.viewing.prompt : sentPrompt;
const modelOptions = props.models[provider];
const preferred = props.defaults.preferred[kind];
return (
<div className="grid min-w-0 gap-6">
{/* 1. Tarefa: define o agente padrão */}
<fieldset className="grid gap-3">
<legend className="mb-3 text-eyebrow font-semibold uppercase text-fg-subtle">1 · Tarefa</legend>
<div className="grid gap-3 sm:grid-cols-2 2xl:grid-cols-4">
{KINDS.map(({ id, label, description, icon: Icon }) => {
const selected = kind === id;
return (
<label key={id}
className={cx(
"group relative grid cursor-pointer gap-3 rounded-card border p-4 transition-[border-color,background-color]",
"has-focus-visible:outline-2 has-focus-visible:outline-offset-2 has-focus-visible:outline-accent",
selected ? "border-accent/60 bg-accent-soft/60" : "border-line bg-surface hover:border-line-strong hover:bg-raised/50",
)}>
<input type="radio" name="agent-kind" value={id} checked={selected} onChange={() => chooseKind(id)} className="sr-only" />
<span className="flex items-center justify-between gap-2">
<span className={cx("grid size-9 place-items-center rounded-lg border", selected ? "border-accent/40 bg-accent text-accent-fg" : "border-line-strong bg-raised text-fg-muted")}>
<Icon size={18} />
</span>
<span className={cx("rounded-full border px-2 py-0.5 text-[0.6875rem] font-semibold",
props.defaults.preferred[id] === "codex" ? "border-info/25 bg-info-soft text-info" : "border-violet/25 bg-violet-soft text-violet")}>
{PROVIDER_SHORT[props.defaults.preferred[id]]}
</span>
</span>
<span className="grid gap-0.5">
<span className="text-sm font-semibold text-fg">{label}</span>
<span className="text-xs leading-relaxed text-fg-subtle">{description}</span>
</span>
</label>
);
})}
</div>
</fieldset>
{/* 2. Agente */}
<fieldset className="grid gap-3">
<legend className="mb-3 text-eyebrow font-semibold uppercase text-fg-subtle">2 · Agente</legend>
<div className="grid gap-3 md:grid-cols-2">
{props.providers.map((p) => (
<ProviderCard key={p.id} info={p} selected={provider === p.id} recommended={preferred === p.id}
onSelect={() => chooseProvider(p.id)} />
))}
</div>
</fieldset>
{/* 3. Conversa */}
<section aria-label="Conversa com o agente" className="overflow-hidden rounded-panel border border-line bg-sunken shadow-card">
<div className="flex items-center gap-3 border-b border-line bg-surface px-5 py-3">
<TerminalIcon size={16} />
<span className="text-[0.8125rem] font-medium text-fg">{runId ? `Execução #${runId}` : "Nova conversa"}</span>
{status && <StatusBadge status={status} />}
<span className="ml-auto text-xs text-fg-subtle">{PROVIDER_LABEL[provider]}</span>
{running && <Button variant="danger" size="sm" onClick={cancel}><StopIcon size={14} />Cancelar</Button>}
</div>
<div ref={log} className="grid max-h-[60vh] min-h-80 content-start gap-4 overflow-y-auto px-5 py-6" aria-live="polite">
{!runId && (
<EmptyState className="border-none bg-transparent" icon={<SparkIcon />} title="O que vamos produzir agora?">
Escolha a tarefa, descreva o pedido e envie com <Kbd>Ctrl</Kbd> + <Kbd>Enter</Kbd>. Ou comece por um exemplo:
<span className="mt-4 grid gap-2 text-left">
{SUGGESTIONS.map((s) => (
<button key={s.text} type="button" onClick={() => { chooseKind(s.kind); setRequest(s.text); }}
className="flex items-center gap-3 rounded-control border border-line-strong bg-surface px-3.5 py-2.5 text-sm text-fg transition-colors hover:border-accent/40 hover:bg-raised">
<span className="shrink-0 text-eyebrow font-semibold uppercase text-accent">{KINDS.find((k) => k.id === s.kind)?.label ?? (s.kind === "branches" ? "Vertentes" : s.kind)}</span>
<span className="min-w-0 text-fg-muted">{s.text}</span>
</button>
))}
</span>
</EmptyState>
)}
{runId && prompt && (
<div className="ml-auto max-w-[85%] rounded-2xl rounded-br-md border border-accent/20 bg-accent-soft px-4 py-3 text-sm leading-relaxed whitespace-pre-wrap text-fg">{prompt}</div>
)}
{events.map((e, i) => <EventLine key={i} event={e} />)}
{running && events.length === 0 && (
<p className="flex items-center gap-2 text-sm text-fg-subtle"><span className="size-2 animate-pulse rounded-full bg-info" />Aguardando o agente…</p>
)}
</div>
{/* 4. Pedido */}
<div className="grid gap-4 border-t border-line bg-surface p-5">
<div className="grid gap-3 md:grid-cols-3">
<Field label="História">
<Select value={storyId} onChange={(e) => { setStoryId(e.target.value); setEpisodeId(""); }}>
<option value="">Nenhuma</option>
{props.stories.map((s) => <option key={s.id} value={s.id}>{s.title}</option>)}
</Select>
</Field>
<Field label={terms.One}>
<Select value={episodeId} disabled={!story} onChange={(e) => setEpisodeId(e.target.value ? Number(e.target.value) : "")}>
<option value="">—</option>
{story?.episodes.map((ep) => {
const code = terms.code(ep.number);
return <option key={ep.id} value={ep.id}>{code.charAt(0).toUpperCase() + code.slice(1)}{ep.title ? ` — ${ep.title}` : ""}</option>;
})}
</Select>
</Field>
<Field label="Modelo">
<Select value={model} disabled={modelOptions.length < 2} onChange={(e) => setModel(e.target.value)}>
{modelOptions.map((m) => <option key={m.id} value={m.id}>{m.label}</option>)}
</Select>
</Field>
</div>
<Textarea aria-label="Pedido ao agente" className="min-h-28 bg-sunken/80" value={request} onChange={(e) => setRequest(e.target.value)}
placeholder={running ? "Não gostou do rumo? Escreva a correção: \"Corrigir agora\" interrompe e o agente continua com ela." : PLACEHOLDER[kind]}
onKeyDown={(e) => {
if (e.key !== "Enter" || !(e.ctrlKey || e.metaKey) || !request.trim()) return;
void (running ? sendDuringRun("now") : send(false));
}} />
{queued && (
<p className="rounded-control border border-info/25 bg-info-soft px-3.5 py-2.5 text-xs leading-relaxed text-info">
Na fila, vai quando o agente terminar: <span className="text-fg">{queued.length > 160 ? `${queued.slice(0, 160)}…` : queued}</span>
</p>
)}
<div className="flex flex-wrap items-center gap-3">
{running ? <>
<Button disabled={!request.trim()} onClick={() => sendDuringRun("now")}
title="Interrompe o agente e continua a mesma conversa com a sua correção">
<SendIcon size={16} />Corrigir agora
</Button>
<Button variant="secondary" disabled={!request.trim()} onClick={() => sendDuringRun("queue")}
title="Deixa o agente terminar e então envia a mensagem na mesma conversa">
Enviar ao terminar
</Button>
</> : <>
<Button disabled={!request.trim()} onClick={() => send(false)}><SendIcon size={16} />Enviar</Button>
{canResume && <Button variant="secondary" disabled={!request.trim()} onClick={() => send(true)}>Continuar esta conversa</Button>}
</>}
<span className="text-xs text-fg-subtle"><Kbd>Ctrl</Kbd> + <Kbd>Enter</Kbd></span>
<span className="ml-auto max-w-md text-right text-xs leading-relaxed text-fg-subtle max-md:ml-0 max-md:text-left">
Edita só dentro do projeto e roda só os comandos liberados (render, testes, scripts da skill).
</span>
</div>
{error && <Feedback ok={false}>{error}</Feedback>}
</div>
</section>
</div>
);
}
function ProviderCard({ info, selected, recommended, onSelect }:
{ info: ProviderInfo; selected: boolean; recommended: boolean; onSelect: () => void }) {
const disabled = !info.available;
const hintId = `provider-${info.id}-hint`;
return (
<label className={cx(
"relative flex items-start gap-3.5 rounded-card border p-4 transition-[border-color,background-color]",
"has-focus-visible:outline-2 has-focus-visible:outline-offset-2 has-focus-visible:outline-accent",
disabled ? "cursor-not-allowed border-line bg-surface opacity-60"
: selected ? "cursor-pointer border-accent/60 bg-accent-soft/60" : "cursor-pointer border-line bg-surface hover:border-line-strong",
)}>
<input type="radio" name="provider" value={info.id} checked={selected} disabled={disabled} onChange={onSelect}
aria-describedby={hintId} className="sr-only" />
<span aria-hidden="true"
className={cx("mt-0.5 grid size-5 shrink-0 place-items-center rounded-full border-2", selected && !disabled ? "border-accent" : "border-line-strong")}>
{selected && !disabled && <span className="size-2 rounded-full bg-accent" />}
</span>
<span className="grid min-w-0 gap-1">
<span className="flex flex-wrap items-center gap-2">
<span className="text-sm font-semibold text-fg">{PROVIDER_LABEL[info.id]}</span>
{recommended && <Badge tone="accent" dot={false}>padrão desta tarefa</Badge>}
{!info.available && <Badge tone="warning" dot={false}>não instalado</Badge>}
</span>
<span id={hintId} className="grid gap-1 text-xs leading-relaxed text-fg-subtle">
{info.version && <span className="font-mono text-[0.6875rem] text-fg-muted">{info.version}</span>}
{info.note && <span>{info.note}</span>}
</span>
</span>
</label>
);
}
function EventLine({ event }: { event: AgentEvent }) {
switch (event.kind) {
case "text":
return (
<div className="flex max-w-[92%] gap-3">
<span className="mt-0.5 grid size-7 shrink-0 place-items-center rounded-full border border-line-strong bg-raised text-accent"><SparkIcon size={14} /></span>
<div className="min-w-0 rounded-2xl rounded-tl-md border border-line bg-surface px-4 py-3 text-sm leading-relaxed whitespace-pre-wrap text-fg">{event.text}</div>
</div>
);
case "tool":
return <div className="ml-10 flex gap-2 font-mono text-xs text-info"><span aria-hidden="true">▸</span><span className="min-w-0 break-words">{event.text}</span></div>;
case "tool_result":
return (
<details className={cx("ml-10 font-mono text-xs", event.isError ? "text-danger" : "text-fg-subtle")}>
<summary className="cursor-pointer hover:text-fg">resultado{event.isError ? " (erro)" : ""}</summary>
<pre className="mt-1.5 max-h-60 overflow-auto rounded-control border border-line bg-surface p-3 whitespace-pre-wrap">{event.text}</pre>
</details>
);
case "result":
return (
<div className={cx("rounded-control border px-4 py-3 text-sm",
event.isError ? "border-danger/30 bg-danger-soft text-danger" : "border-success/25 bg-success-soft text-success")}>
{event.text}
</div>
);
case "error":
case "stderr":
return <div className="ml-10 font-mono text-xs break-words text-danger">{event.text}</div>;
default:
return <div className="ml-10 font-mono text-xs break-words text-fg-subtle">{event.text}</div>;
}
}
export function RunHistory({ runs, activeId }: { runs: AgentRun[]; activeId?: number }) {
if (runs.length === 0) {
return <EmptyState compact icon={<TerminalIcon />} title="Nenhuma execução ainda">Os pedidos enviados aparecem aqui, com custo e estado.</EmptyState>;
}
return (
<ul className="grid gap-1 text-sm">
{runs.map((r) => (
<li key={r.id}>
<Link href={`/agent?run=${r.id}`} aria-current={r.id === activeId ? "page" : undefined}
className={cx("grid gap-1.5 rounded-control border px-3 py-2.5 transition-colors",
r.id === activeId ? "border-line-strong bg-raised" : "border-transparent hover:bg-raised/60")}>
<span className="flex items-center gap-2">
<StatusBadge status={r.status} />
<span className="truncate text-xs text-fg-subtle">
#{r.id} · {PROVIDER_SHORT[r.provider]}{r.model ? ` ${r.model}` : ""}{r.cost_usd != null ? ` · US$ ${r.cost_usd.toFixed(3)}` : ""}
</span>
</span>
<span className="line-clamp-2 text-[0.8125rem] leading-snug text-fg-muted">{r.prompt.slice(0, 120)}</span>
</Link>
</li>
))}
</ul>
);
}
+21
View File
@@ -0,0 +1,21 @@
// Chamada JSON às rotas do painel (/api/...). Erro do servidor ({ error }) vira mensagem para mostrar;
// falha de rede vira um aviso de que o painel pode estar fora do ar.
export type ApiResult<T> = { ok: true; data: T } | { ok: false; error: string };
export async function apiCall<T>(url: string, method: "GET" | "POST" | "PATCH" | "PUT" | "DELETE" = "GET", body?: unknown): Promise<ApiResult<T>> {
try {
const res = await fetch(url, {
method,
cache: "no-store",
headers: body === undefined ? undefined : { "Content-Type": "application/json" },
body: body === undefined ? undefined : JSON.stringify(body),
});
const data = (await res.json().catch(() => ({}))) as T & { error?: string };
if (!res.ok || (data && typeof data === "object" && "error" in data && data.error)) {
return { ok: false, error: data?.error || `Erro ${res.status} no painel.` };
}
return { ok: true, data };
} catch {
return { ok: false, error: "Sem resposta do painel. Ele está no ar?" };
}
}
+41
View File
@@ -0,0 +1,41 @@
import type { Asset } from "@/lib/types";
import { PromoteButton } from "./asset-upload";
import { CubeIcon } from "./icons";
import { Badge, EmptyState, Table, THead, Td, Th, Tr, fileUrl } from "./ui";
export function AssetTable({ assets, showStory = false }: { assets: Asset[]; showStory?: boolean }) {
if (assets.length === 0) {
return (
<EmptyState compact icon={<CubeIcon />} title="Nenhum asset aqui">
Envie um modelo, textura, fundo ou áudio pelo formulário “Enviar asset”.
</EmptyState>
);
}
return (
<Table>
<THead>
<Th>Nome</Th><Th>Tipo</Th>{showStory && <Th>Onde</Th>}<Th>Licença</Th><Th>Arquivo</Th><Th />
</THead>
<tbody>
{assets.map((a) => (
<Tr key={a.id}>
<Td>
<div className="flex items-center gap-3">
{/\.(png|jpe?g|webp)$/i.test(a.file_path) && (
// eslint-disable-next-line @next/next/no-img-element
<img src={fileUrl(a.file_path)} alt="" className="size-10 rounded-control border border-line object-cover" />
)}
<span className="font-medium">{a.name}</span>
</div>
</Td>
<Td><Badge>{a.kind}</Badge></Td>
{showStory && <Td className="text-fg-muted">{a.scope === "library" ? "biblioteca" : a.story_id}</Td>}
<Td className="text-fg-muted">{a.license}</Td>
<Td><a className="text-accent hover:underline" href={fileUrl(a.file_path)}>{a.file_path.split("/").pop()}</a></Td>
<Td className="text-right">{a.scope === "story" && <PromoteButton assetId={a.id} />}</Td>
</Tr>
))}
</tbody>
</Table>
);
}
+84
View File
@@ -0,0 +1,84 @@
"use client";
// Envio de asset (multipart) e promoção de asset da história para a biblioteca.
import { useRouter } from "next/navigation";
import { useState } from "react";
import { Button, Feedback, Field, Input, Select } from "./ui";
import { askConfirm } from "./confirm-dialog";
export function AssetUpload({ stories, kinds, defaultStoryId }: {
stories: { id: string; title: string }[];
kinds: { id: string; label: string; extensions: string[] }[];
defaultStoryId?: string;
}) {
const router = useRouter();
const [scope, setScope] = useState(defaultStoryId ? "story" : "library");
const [kind, setKind] = useState(kinds[0].id);
const [pending, setPending] = useState(false);
const [feedback, setFeedback] = useState<{ ok: boolean; text: string } | null>(null);
const accept = kinds.find((k) => k.id === kind)?.extensions.join(",");
async function submit(form: HTMLFormElement) {
setPending(true);
setFeedback(null);
const r = await fetch("/api/assets", { method: "POST", body: new FormData(form) });
const body = await r.json();
setPending(false);
if (!r.ok) return setFeedback({ ok: false, text: body.error });
setFeedback({ ok: true, text: `Asset "${body.name}" salvo em ${body.file_path}` });
form.reset();
router.refresh();
}
return (
<form className="grid gap-4" onSubmit={(e) => { e.preventDefault(); void submit(e.currentTarget); }}>
<div className="grid gap-4 md:grid-cols-3">
<Field label="Nome"><Input name="name" required placeholder="Ex.: Moto de entrega azul" /></Field>
<Field label="Tipo">
<Select name="kind" value={kind} onChange={(e) => setKind(e.target.value)}>
{kinds.map((k) => <option key={k.id} value={k.id}>{k.label} ({k.extensions.join(" ")})</option>)}
</Select>
</Field>
<Field label="Arquivo"><Input name="file" type="file" required accept={accept} /></Field>
</div>
<div className="grid gap-4 md:grid-cols-3">
<Field label="Escopo">
<Select name="scope" value={scope} onChange={(e) => setScope(e.target.value)}>
<option value="library">Biblioteca (qualquer história pode usar)</option>
<option value="story">Só de uma história</option>
</Select>
</Field>
<Field label="História">
<Select name="storyId" defaultValue={defaultStoryId ?? ""} disabled={scope !== "story"}>
<option value="">Escolha a história</option>
{stories.map((s) => <option key={s.id} value={s.id}>{s.title}</option>)}
</Select>
</Field>
<Field label="Licença / direito de uso"><Input name="license" required placeholder="Ex.: próprio, CC0" /></Field>
</div>
<div className="grid gap-4 md:grid-cols-2">
<Field label="Origem"><Input name="source" placeholder="Ex.: Meshy, Blender, foto própria" /></Field>
<Field label="Observações"><Input name="notes" placeholder="Escala, orientação, animações…" /></Field>
</div>
<div className="flex items-center gap-3">
<Button disabled={pending}>{pending ? "Enviando…" : "Enviar asset"}</Button>
{feedback && <Feedback ok={feedback.ok}>{feedback.text}</Feedback>}
</div>
</form>
);
}
export function PromoteButton({ assetId }: { assetId: string }) {
const router = useRouter();
const [error, setError] = useState<string | null>(null);
return (
<span className="flex items-center justify-end gap-2">
<Button variant="secondary" size="sm" onClick={async () => {
if (!(await askConfirm({ title: "Mover este asset para a biblioteca compartilhada?", confirmLabel: "Promover" }))) return;
const r = await fetch(`/api/assets/${assetId}/promote`, { method: "POST" });
if (!r.ok) return setError((await r.json()).error);
router.refresh();
}}>Promover à biblioteca</Button>
{error && <span role="alert" className="text-xs text-danger">{error}</span>}
</span>
);
}
+185
View File
@@ -0,0 +1,185 @@
"use client";
// Fontes do corte no navegador: carrega as fontes EMPACOTADAS do repositório (assets/fonts, lista em `fontFiles` das
// rotas de settings do Clipador) com FontFace a partir de /api/files, lê as métricas de cada arquivo e oferece o
// seletor de fonte com amostra ("Aa" na própria fonte), usado no editor de cortes e na "Configuração do corte".
//
// Por que métricas: o libass não usa o "tamanho" do ASS como o canvas usa o px. Ele escala a fonte para que
// usWinAscent + usWinDescent (tabela OS/2) caibam no tamanho pedido, e a linha também segue o win. Então, para a
// prévia bater com o render, o tamanho em px do canvas = tamanho ASS × `em`, e a linha anda (asc + desc) × tamanho
// (= o próprio tamanho). As do Windows foram medidas nos arquivos de C:\Windows\Fonts; as empacotadas são lidas do .ttf.
import { useEffect, useId, useState } from "react";
import { cx, fileUrl } from "./ui";
/** Em frações do tamanho ASS: `em` = px da fonte; `asc`/`desc` = acima/abaixo da linha de base (altura da linha). */
export type FontMetrics = { em: number; asc: number; desc: number };
// unitsPerEm / (winAscent + winDescent) e winAscent/winDescent sobre o total, das fontes do Windows que o serviço aceita.
const SYSTEM_METRICS: Record<string, FontMetrics> = {
"Arial Black": { em: 0.7091, asc: 0.7805, desc: 0.2195 },
Arial: { em: 0.8951, asc: 0.8103, desc: 0.1897 },
Impact: { em: 0.8199, asc: 0.8271, desc: 0.1729 },
Verdana: { em: 0.8228, asc: 0.8272, desc: 0.1728 },
"Segoe UI Black": { em: 0.7518, asc: 0.8113, desc: 0.1887 },
"Trebuchet MS": { em: 0.8612, asc: 0.8087, desc: 0.1913 },
};
const metrics = new Map<string, FontMetrics>();
const loading = new Map<string, Promise<void>>();
/** Métricas da família (empacotada lida do arquivo; do Windows pela tabela; desconhecida = Arial). */
export function fontMetrics(family: string): FontMetrics {
return metrics.get(family) ?? SYSTEM_METRICS[family] ?? SYSTEM_METRICS.Arial;
}
/** `font-family` do canvas/CSS: a família pedida, com reservas parecidas. */
export function fontStack(family: string): string {
return `"${family}", "Arial Black", Arial, sans-serif`;
}
/**
* `font` do canvas como o estilo negrito do ASS: as famílias "Black" do Windows só existem no peso 900 (pedir 700
* faz o Chrome cair no Arial Bold); as demais vão em negrito (sintetizado, se a fonte só tiver o regular, como o libass).
*/
export function canvasFont(family: string, px: number): string {
return `${/black/i.test(family) ? 900 : "bold"} ${px}px ${fontStack(family)}`;
}
/** Lê unitsPerEm (head) e win ascent/descent (OS/2) de um TTF/OTF. null se o arquivo não tiver as tabelas. */
function parseMetrics(buf: ArrayBuffer): FontMetrics | null {
try {
const v = new DataView(buf);
const count = v.getUint16(4);
const table: Record<string, number> = {};
for (let i = 0; i < count; i++) {
const at = 12 + 16 * i;
table[String.fromCharCode(v.getUint8(at), v.getUint8(at + 1), v.getUint8(at + 2), v.getUint8(at + 3))] = v.getUint32(at + 8);
}
if (table.head === undefined || table["OS/2"] === undefined) return null;
const upm = v.getUint16(table.head + 18);
const winAsc = v.getUint16(table["OS/2"] + 74), winDesc = v.getUint16(table["OS/2"] + 76);
const win = winAsc + winDesc;
if (!upm || !win) return null;
// Medido no render da tarja (Luckiest Guy, tamanho 76): linhas a cada 75 px = o tamanho; ou seja, a linha do libass
// segue win ascent/descent (não o hhea, que nessa fonte é menor).
return { em: upm / win, asc: winAsc / win, desc: winDesc / win };
} catch {
return null;
}
}
async function loadOne(family: string, path: string): Promise<void> {
try {
const r = await fetch(fileUrl(path), { cache: "force-cache" });
if (!r.ok) return;
const buf = await r.arrayBuffer();
const m = parseMetrics(buf);
if (m) metrics.set(family, m);
const face = new FontFace(family, buf);
await face.load();
document.fonts.add(face);
} catch {
// Sem a fonte: o canvas cai na reserva do sistema (a prévia fica aproximada; o render usa a certa).
}
}
/** Carrega (uma vez por família, na página toda) as fontes empacotadas. */
export function loadPackagedFonts(files: Record<string, string>): Promise<void> {
return Promise.all(Object.entries(files).map(([family, path]) => {
if (!loading.has(family)) loading.set(family, loadOne(family, path));
return loading.get(family)!;
})).then(() => undefined);
}
/**
* Fontes prontas para desenhar. `files` undefined = a lista ainda não chegou (não está pronto); `{}` = nada a carregar.
* Quem desenha espera `true` para não piscar com a fonte de reserva.
*/
export function usePackagedFonts(files: Record<string, string> | undefined): boolean {
const key = files ? JSON.stringify(files) : null;
const [readyKey, setReadyKey] = useState<string | null>(null);
useEffect(() => {
if (key === null) return;
let alive = true;
void loadPackagedFonts(JSON.parse(key) as Record<string, string>).then(() => { if (alive) setReadyKey(key); });
return () => { alive = false; };
}, [key]);
return key !== null && readyKey === key;
}
/* ---------- Seletor de fonte com amostra ---------- */
type Variant = "nle" | "panel";
const SKIN: Record<Variant, { trigger: string; option: string; on: string; off: string; group: string; name: string; tag: string }> = {
nle: {
trigger: "h-7 rounded-[3px] border border-nle-line bg-nle-well px-2 text-[12px] text-nle-text hover:bg-nle-hover focus-visible:outline-1 focus-visible:outline-nle-focus",
option: "h-9 rounded-[3px] border px-2 text-[11.5px] has-focus-visible:outline-1 has-focus-visible:outline-nle-focus",
on: "border-nle-accent bg-nle-accent/25 text-white",
off: "border-nle-line text-nle-dim hover:bg-nle-hover hover:text-nle-text",
group: "text-[10.5px] text-nle-faint",
name: "truncate",
tag: "text-[10px] text-nle-faint",
},
panel: {
trigger: "h-10 rounded-control border border-line-strong bg-sunken/60 px-3 text-sm text-fg hover:border-fg-subtle/60 focus-visible:outline-2 focus-visible:outline-accent",
option: "h-14 rounded-control border px-3 text-[0.8125rem] has-focus-visible:outline-2 has-focus-visible:outline-offset-2 has-focus-visible:outline-accent",
on: "border-accent bg-accent-soft/50 text-fg",
off: "border-line-strong text-fg-muted hover:border-fg-subtle/60 hover:text-fg",
group: "text-eyebrow font-semibold text-fg-subtle uppercase",
name: "truncate",
tag: "text-[0.6875rem] text-fg-subtle",
},
};
/**
* Seletor de fonte: cada opção mostra "Aa" na própria fonte. Empacotadas primeiro ("vídeo curto"), depois as do
* Windows. Rádios nativos: setas mudam a escolha, Tab sai do grupo. `collapsible` = começa fechado, atrás de um
* botão com a fonte atual (painel estreito do editor).
*/
export function FontPicker({ fonts, packaged, value, onChange, label, variant = "nle", collapsible = false, columns = 2 }: {
fonts: string[]; packaged: string[]; value: string; onChange: (font: string) => void; label: string;
variant?: Variant; collapsible?: boolean; columns?: 2 | 3 | 4;
}) {
const [open, setOpen] = useState(!collapsible);
const name = useId();
const skin = SKIN[variant];
const list = fonts.includes(value) ? fonts : [value, ...fonts];
const groups = [
{ title: "Para vídeo curto (empacotadas)", items: list.filter((f) => packaged.includes(f)) },
{ title: "Do Windows", items: list.filter((f) => !packaged.includes(f)) },
].filter((g) => g.items.length);
const grid = { 2: "grid-cols-2", 3: "grid-cols-3", 4: "grid-cols-2 xl:grid-cols-4" }[columns];
return (
<div className="grid min-w-0 gap-1.5">
{collapsible && (
<button type="button" aria-expanded={open} onClick={() => setOpen((o) => !o)} title={`${label}: ${value}`}
className={cx("flex min-w-0 cursor-pointer items-center gap-2 text-left", skin.trigger)}>
<span aria-hidden="true" className="w-7 shrink-0 text-[17px] leading-none" style={{ fontFamily: fontStack(value), fontWeight: /black/i.test(value) ? 900 : 700 }}>Aa</span>
<span className="min-w-0 flex-1 truncate">{value}</span>
<svg viewBox="0 0 24 24" width={12} height={12} fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true"
className={cx("shrink-0 transition-transform motion-reduce:transition-none", open && "rotate-180")}><path d="m6 9 6 6 6-6" /></svg>
</button>
)}
{open && (
<div role="radiogroup" aria-label={label} className="grid gap-2">
{groups.map((g) => (
<div key={g.title} className="grid gap-1">
<span className={skin.group}>{g.title}</span>
<div className={cx("grid gap-1", grid)}>
{g.items.map((f) => (
<label key={f} title={f} className={cx("flex min-w-0 cursor-pointer items-center gap-2", skin.option, value === f ? skin.on : skin.off)}>
<input type="radio" name={name} value={f} checked={value === f} className="sr-only"
onChange={() => { onChange(f); if (collapsible) setOpen(false); }} />
<span aria-hidden="true" className={cx("shrink-0 leading-none", variant === "nle" ? "w-7 text-[18px]" : "w-9 text-[24px]")}
style={{ fontFamily: fontStack(f), fontWeight: /black/i.test(f) ? 900 : 700 }}>Aa</span>
<span className={cx("min-w-0 flex-1", skin.name)}>{f}</span>
</label>
))}
</div>
</div>
))}
</div>
)}
</div>
);
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,290 @@
"use client";
// Propriedades do REENQUADRAMENTO do jogo (câmera virtual com keyframes) e das CAMADAS INSERIDAS (recortes da tela em
// destaque), no padrão do painel de propriedades do editor. Pedido do dono (17/11/2026, corte 61): "na hora que ele
// abre o inventário eu preciso pegar um ângulo melhor; se quero mostrar alguma coisa no canto da tela, criar camadas".
// Contrato (clipper/app/reframe.py): `project.reframe = {keys: [{t, cx, cy, w, ease}]}` e overlays `kind: "inset"`.
// As contas (interpolação, janela, auto-key) ficam em clip-editor-model.ts, em funções puras; aqui só a interface.
// Tudo passa por `onProject` (desfazer e autosave); arrastes e controles deslizantes juntam passos pela `key`.
import type { InspectorProps } from "./clip-editor-inspector";
import {
KEY_EPS, REFRAME_MIN_W, clamp, cutAt, gameArea, insetAt, reframeAt, resolvedMode, round3, round4, sessionClock, setInsetPlace, upsertKey,
type Ease, type EditProject, type InsetKey, type InsetOverlay, type ReframeKey,
} from "./clip-editor-model";
import { Btn, Check, ColorDot, Hint, Hot, Pick, PropRow, PropSection, RectFields, RowButton, Scrub } from "./clip-editor-ui";
import { PlusIcon, TrashIcon } from "./icons";
import { cx } from "./ui";
export const EASE_LABEL: Record<Ease, { label: string; hint: string }> = {
smooth: { label: "Suave", hint: "acelera e freia (padrão)" },
linear: { label: "Linear", hint: "velocidade constante" },
hold: { label: "Segurar", hint: "fica parado e salta no próximo" },
};
const ANIM_LABEL: Record<InsetOverlay["anim"], string> = { pop: "Entrada pop", fade: "Aparecer suave", slide: "Deslizar da direita", none: "Sem animação" };
/** O que Propriedades precisa do editor para os keyframes: criar no playhead e desenhar uma inserção na Fonte. */
export type KeyframeControl = {
/** Keyframe do enquadramento no playhead (com o valor atual): devolve o índice criado. */
addReframeKey: () => void;
/** Começa a desenhar o recorte de uma inserção nova na Fonte. */
startInset: () => void;
/** Desenhando uma inserção nova (a Fonte está esperando o recorte). */
drawingInset: boolean;
};
const pct = (v: number) => `${Math.round(v * 100)}%`;
const zoomText = (w: number) => `${(1 / w).toFixed(2).replace(".", ",")}×`;
/** Diamante do keyframe (◆ suave, ◇ linear, ■ segurar), igual ao da timeline. */
export function KeyGlyph({ ease, size = 11, className }: { ease: Ease; size?: number; className?: string }) {
return (
<svg viewBox="0 0 12 12" width={size} height={size} aria-hidden="true" className={cx("shrink-0", className)}>
{ease === "hold" ? <rect x="2" y="2" width="8" height="8" rx="1" fill="currentColor" />
: ease === "linear" ? <path d="M6 1 11 6 6 11 1 6Z" fill="none" stroke="currentColor" strokeWidth="1.6" />
: <path d="M6 1 11 6 6 11 1 6Z" fill="currentColor" />}
</svg>
);
}
function EaseButtons({ value, onChange, label }: { value: Ease; onChange: (e: Ease) => void; label: string }) {
return (
<div role="radiogroup" aria-label={label} className="grid grid-cols-3 gap-1">
{(["smooth", "linear", "hold"] as Ease[]).map((e) => (
<button key={e} type="button" role="radio" aria-checked={value === e} title={EASE_LABEL[e].hint} onClick={() => onChange(e)}
className={cx("flex h-7 cursor-pointer items-center justify-center gap-1.5 rounded-[3px] border px-1.5 text-[12px] focus-visible:outline-1 focus-visible:outline-nle-focus",
value === e ? "border-nle-accent bg-nle-accent/25 text-white" : "border-nle-line text-nle-dim hover:bg-nle-hover hover:text-nle-text")}>
<KeyGlyph ease={e} />{EASE_LABEL[e].label}
</button>
))}
</div>
);
}
/** Muda um keyframe de lugar no tempo sem passar dos vizinhos (a ordem e os índices ficam). */
export function moveKeyTime<K extends { t: number }>(keys: K[], index: number, t: number, lo: number, hi: number): K[] {
const min = index > 0 ? keys[index - 1].t + KEY_EPS * 2 : lo;
const max = index + 1 < keys.length ? keys[index + 1].t - KEY_EPS * 2 : hi;
if (max < min) return keys;
return keys.map((k, i) => (i === index ? { ...k, t: round3(clamp(t, min, max)) } : k));
}
/* ---------------- Enquadramento ---------------- */
function setReframeKeys(p: EditProject, keys: ReframeKey[]): EditProject {
if (!keys.length) { const { reframe: _drop, ...rest } = p; return rest as EditProject; }
return { ...p, reframe: { keys } };
}
/** Camada "Enquadramento": o valor no playhead, a lista de keyframes e como mexer. */
export function ReframeLayer({ project, cfg, frame, playhead, onProject, onSelect, onSeek, keyframes }: InspectorProps & { keyframes: KeyframeControl }) {
const keys = project.reframe?.keys ?? [];
const now = reframeAt(project, playhead);
const ci = cutAt(project.cuts, playhead);
const mode = resolvedMode(cfg, ci >= 0 ? project.cuts[ci].mode : null);
const area = gameArea(mode, cfg, frame);
return (
<>
<PropSection title="Enquadramento do jogo" actions={<Btn variant="ghost" className="h-5 px-1.5 text-[11px]" onClick={keyframes.addReframeKey}
title="Grava o enquadramento atual num keyframe no playhead"><KeyGlyph ease="smooth" size={10} />No playhead</Btn>}>
<Hint>Uma câmera virtual dentro da tela do jogo: em cada keyframe você escolhe o centro e o zoom; entre eles a janela anda sozinha. Ex.: abriu o inventário, aproxima; fechou, volta ao quadro inteiro.</Hint>
<PropRow label="No playhead">
{now ? <><Hot>{zoomText(now.w)}</Hot><span className="truncate text-nle-faint">centro {pct(now.cx)}, {pct(now.cy)}</span></>
: <span className="text-nle-faint">quadro inteiro (sem keyframes)</span>}
</PropRow>
{!area && <Hint tone="warn">Neste trecho o layout é “Câmera inteira”: o enquadramento do jogo não vale aqui.</Hint>}
{area && <PropRow label="Área do jogo"><span className="truncate text-nle-faint">{area.w}×{area.h} px · a janela segue essa proporção</span></PropRow>}
</PropSection>
<PropSection title={`Keyframes (${keys.length})`}>
{!keys.length && <p className="text-nle-dim">Nenhum. Ponha o playhead no momento e clique em “No playhead”, ou arraste a janela do jogo na Fonte (cria o keyframe sozinho).</p>}
{keys.map((k, i) => (
<RowButton key={`${i}-${k.t}`} label={`${sessionClock(k.t)} · ${zoomText(k.w)} · ${pct(k.cx)}, ${pct(k.cy)}`} meta={EASE_LABEL[k.ease].label}
onClick={() => { onSelect({ kind: "reframe", key: i }); onSeek(k.t); }} />
))}
{keys.length > 0 && (
<Btn variant="danger" className="justify-self-start" onClick={() => { onProject((p) => setReframeKeys(p, [])); onSelect({ kind: "layer", layer: "reframe" }); }}>
<TrashIcon size={13} />Tirar o enquadramento (todos)
</Btn>
)}
<Hint>Na Fonte: arraste a janela para mover, puxe as alças para o zoom, clique fora para levar o centro até ali. Mexer fora de um keyframe cria outro no playhead. [ e ] pulam de keyframe; Ctrl+C / Ctrl+V copiam; Delete apaga.</Hint>
</PropSection>
</>
);
}
/** Um keyframe do enquadramento selecionado. */
export function ReframeKeyProps({ project, playhead, onProject, onSelect, onSeek, index }: InspectorProps & { index: number }) {
const keys = project.reframe?.keys ?? [];
const k = keys[index];
if (!k) return null;
const { lo, hi } = project.source;
const set = (patch: Partial<ReframeKey>, key?: string) =>
onProject((p) => setReframeKeys(p, (p.reframe?.keys ?? []).map((x, i) => (i === index ? { ...x, ...patch } : x))), key && `rf-${key}-${index}`);
const moveTo = (t: number) => onProject((p) => setReframeKeys(p, moveKeyTime(p.reframe?.keys ?? [], index, t, lo, hi)), `rf-t-${index}`);
return (
<>
<PropSection title={`Keyframe ${index + 1} de ${keys.length}`}>
<PropRow label="Gravação"><Hot>{sessionClock(k.t)}</Hot><span className="truncate text-nle-faint">arraste o losango na timeline</span></PropRow>
<div className="flex flex-wrap gap-1">
{[-1, -1 / 30, 1 / 30, 1].map((d) => (
<Btn key={d} variant="ghost" className="px-1.5" title={Math.abs(d) < 1 ? "Mover um quadro" : "Mover um segundo"} onClick={() => moveTo(k.t + d)}>
{d > 0 ? "+" : "−"}{Math.abs(d) < 1 ? "1 quadro" : "1 s"}
</Btn>
))}
</div>
<div className="flex flex-wrap gap-1.5">
<Btn variant="ghost" onClick={() => onSeek(k.t)}>Ir ao keyframe</Btn>
<Btn variant="ghost" disabled={Math.abs(playhead - k.t) < KEY_EPS} onClick={() => moveTo(playhead)}>Mover para o playhead</Btn>
</div>
</PropSection>
<PropSection title="Janela do jogo">
<PropRow label="Centro horizontal"><Scrub label="Centro horizontal" min={0} max={1} step={0.005} value={k.cx} format={pct} onChange={(v) => set({ cx: round4(v) }, "cx")} /></PropRow>
<PropRow label="Centro vertical"><Scrub label="Centro vertical" min={0} max={1} step={0.005} value={k.cy} format={pct} onChange={(v) => set({ cy: round4(v) }, "cy")} /></PropRow>
<PropRow label="Zoom" hint="1× = o quadro inteiro (o que couber na área do jogo)">
<Scrub label="Zoom" min={1} max={1 / REFRAME_MIN_W} step={0.05} value={round4(1 / k.w)} format={(v) => `${v.toFixed(2).replace(".", ",")}×`}
onChange={(v) => set({ w: round4(clamp(1 / v, REFRAME_MIN_W, 1)) }, "w")} />
</PropRow>
<Btn className="justify-self-start" disabled={k.w === 1 && k.cx === 0.5 && k.cy === 0.5} onClick={() => set({ cx: 0.5, cy: 0.5, w: 1 })}>Voltar ao quadro inteiro</Btn>
</PropSection>
<PropSection title="Até o próximo keyframe">
<EaseButtons label="Curva até o próximo keyframe" value={k.ease} onChange={(ease) => set({ ease })} />
{index === keys.length - 1 && <Hint>É o último: depois dele a janela fica parada.</Hint>}
</PropSection>
<div className="p-3">
<Btn variant="danger" onClick={() => { onProject((p) => setReframeKeys(p, (p.reframe?.keys ?? []).filter((_, i) => i !== index))); onSelect({ kind: "layer", layer: "reframe" }); }}>
<TrashIcon size={13} />Apagar o keyframe
</Btn>
</div>
</>
);
}
/* ---------------- Inserções ---------------- */
/** Sobe/desce uma inserção no empilhamento (ordem no array de overlays, entre as outras inserções). */
export function moveInsetOrder(p: EditProject, id: string, dir: -1 | 1): EditProject {
const idx = p.overlays.findIndex((o) => o.id === id);
const insets = p.overlays.map((o, i) => (o.kind === "inset" ? i : -1)).filter((i) => i >= 0);
const pos = insets.indexOf(idx);
const other = insets[pos + dir];
if (idx < 0 || other === undefined) return p;
const overlays = [...p.overlays];
[overlays[idx], overlays[other]] = [overlays[other], overlays[idx]];
return { ...p, overlays };
}
/** Camada "Inserções": lista (de cima para baixo = da frente para trás), ordem e criar nova. */
export function InsetsLayer({ project, onProject, onSelect, onSeek, keyframes }: InspectorProps & { keyframes: KeyframeControl }) {
const insets = project.overlays.filter((o): o is InsetOverlay => o.kind === "inset");
return (
<PropSection title={`Inserções (${insets.length})`} actions={<Btn variant="ghost" className="h-5 px-1.5 text-[11px]" onClick={keyframes.startInset}><PlusIcon size={12} />Nova</Btn>}>
{keyframes.drawingInset && <Hint tone="warn">Desenhe o recorte na Fonte (arraste sobre o que quer mostrar). Esc cancela.</Hint>}
{!insets.length && !keyframes.drawingInset && <p className="text-nle-dim">Nenhuma. “Nova” pede um recorte na Fonte (ex.: o mapa no canto) e põe ele por cima do vídeo no playhead.</p>}
{[...insets].reverse().map((o, i) => (
<div key={o.id} className="flex items-center gap-1">
<div className="min-w-0 flex-1"><RowButton label={`Inserção · ${pct(o.src.w)} × ${pct(o.src.h)}`} meta={sessionClock(o.start)} onClick={() => { onSelect({ kind: "overlay", id: o.id }); onSeek(o.start); }} /></div>
<OrderButtons first={i === 0} last={i === insets.length - 1} onMove={(dir) => onProject((p) => moveInsetOrder(p, o.id, dir))} />
</div>
))}
<Hint>A de cima fica na frente. Todas ficam acima do vídeo e abaixo da legenda, do gancho, dos textos e do chat.</Hint>
</PropSection>
);
}
function OrderButtons({ first, last, onMove }: { first: boolean; last: boolean; onMove: (dir: -1 | 1) => void }) {
const arrow = (d: string) => <svg viewBox="0 0 24 24" width={12} height={12} fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true"><path d={d} /></svg>;
return (
<span className="flex shrink-0">
<Btn variant="ghost" className="px-1" aria-label="Trazer para a frente" title="Trazer para a frente" disabled={first} onClick={() => onMove(1)}>{arrow("m6 15 6-6 6 6")}</Btn>
<Btn variant="ghost" className="px-1" aria-label="Mandar para trás" title="Mandar para trás" disabled={last} onClick={() => onMove(-1)}>{arrow("m6 9 6 6 6-6")}</Btn>
</span>
);
}
/** Uma inserção selecionada: recorte, lugar no instante (auto-key), keyframes, aparência e ordem. */
export function InsetProps(props: InspectorProps & { inset: InsetOverlay; keyIndex?: number }) {
const { project, playhead, onProject, onSelect, onSeek, inset: o, keyIndex } = props;
const place = insetAt(o, playhead);
const keys = o.keys ?? [];
const { lo, hi } = project.source;
const update = (fn: (x: InsetOverlay) => InsetOverlay, key?: string) =>
onProject((p) => ({ ...p, overlays: p.overlays.map((x) => (x.id === o.id && x.kind === "inset" ? fn(x) : x)) }), key && `in-${key}-${o.id}`);
const set = (patch: Partial<InsetOverlay>, key?: string) => update((x) => ({ ...x, ...patch }), key);
const t = playhead;
const setKeys = (next: InsetKey[]) => update((x) => {
if (next.length) return { ...x, keys: next };
const { keys: _drop, ...rest } = x;
return rest as InsetOverlay;
});
const insetIdx = project.overlays.filter((x) => x.kind === "inset").findIndex((x) => x.id === o.id);
const insetCount = project.overlays.filter((x) => x.kind === "inset").length;
const visible = t >= o.start && t <= o.end;
const sel = keyIndex !== undefined ? keys[keyIndex] : undefined;
return (
<>
<PropSection title="Tempo">
<PropRow label="Gravação"><Hot>{sessionClock(o.start)}</Hot><span className="text-nle-faint">{((o.end - o.start)).toFixed(1).replace(".", ",")} s · arraste na timeline</span></PropRow>
{!visible && <Hint>O playhead está fora da inserção: ela aparece de {sessionClock(o.start)} a {sessionClock(o.end)}.</Hint>}
</PropSection>
<PropSection title="Recorte (da tela original)">
<RectFields label="Recorte" rect={o.src} onChange={(r, field) => set({ src: r }, `src-${field}`)} />
<Hint>Com a inserção selecionada, a Fonte mostra o recorte em verde: arraste para mover, puxe as alças para mudar, ou desenhe outro numa área vazia.</Hint>
</PropSection>
<PropSection title={keys.length ? "Lugar no playhead (keyframe)" : "Lugar na tela"}>
<PropRow label="Posição horizontal"><Scrub label="Posição horizontal" min={0} max={1} step={0.005} value={round4(place.x)} format={pct} onChange={(v) => update((x) => setInsetPlace(x, t, { x: v }), "x")} /></PropRow>
<PropRow label="Posição vertical"><Scrub label="Posição vertical" min={0} max={1} step={0.005} value={round4(place.y)} format={pct} onChange={(v) => update((x) => setInsetPlace(x, t, { y: v }), "y")} /></PropRow>
<PropRow label="Tamanho" hint="Largura, em % da largura do vídeo"><Scrub label="Tamanho" min={0.1} max={1} step={0.01} value={round4(place.size)} format={pct} onChange={(v) => update((x) => setInsetPlace(x, t, { size: v }), "size")} /></PropRow>
<Hint>{keys.length ? "Com keyframes, mexer aqui ou no vídeo grava no playhead (cria um keyframe se não houver)." : "Arraste a inserção no vídeo para mover; com ela selecionada, puxe um canto para o tamanho."}</Hint>
</PropSection>
<PropSection title={`Keyframes de posição e tamanho (${keys.length})`} actions={
<Btn variant="ghost" className="h-5 px-1.5 text-[11px]" title="Grava a posição e o tamanho atuais num keyframe no playhead"
onClick={() => setKeys(upsertKey<InsetKey>(keys, t, { ...place, x: round4(place.x), y: round4(place.y), size: round4(place.size) }, (prev) => ({ ease: prev?.ease ?? "smooth" })).keys)}>
<KeyGlyph ease="smooth" size={10} />No playhead
</Btn>}>
{!keys.length && <p className="text-nle-dim">Sem keyframes: a inserção fica parada. Crie dois em instantes diferentes para ela andar ou crescer.</p>}
{keys.map((k, i) => (
<button key={`${i}-${k.t}`} type="button" onClick={() => { onSelect({ kind: "overlay", id: o.id, key: i }); onSeek(k.t); }}
className={cx("flex h-6 cursor-pointer items-center gap-2 rounded-[3px] px-1.5 text-left hover:bg-nle-hover", keyIndex === i && "bg-nle-accent/25 text-white")}>
<KeyGlyph ease={k.ease ?? "smooth"} className="text-[#7cf08a]" />
<span className="min-w-0 flex-1 truncate">{sessionClock(k.t)} · {pct(k.x)}, {pct(k.y)} · {pct(k.size)}</span>
</button>
))}
{sel && keyIndex !== undefined && (
<>
<EaseButtons label="Curva até o próximo keyframe" value={sel.ease ?? "smooth"} onChange={(ease) => setKeys(keys.map((k, i) => (i === keyIndex ? { ...k, ease } : k)))} />
<div className="flex flex-wrap gap-1.5">
<Btn variant="ghost" disabled={Math.abs(playhead - sel.t) < KEY_EPS} onClick={() => setKeys(moveKeyTime(keys, keyIndex, playhead, Math.max(lo, o.start), Math.min(hi, o.end)))}>Mover para o playhead</Btn>
<Btn variant="danger" onClick={() => { setKeys(keys.filter((_, i) => i !== keyIndex)); onSelect({ kind: "overlay", id: o.id }); }}><TrashIcon size={13} />Apagar o keyframe</Btn>
</div>
</>
)}
{keys.length > 0 && <Btn variant="ghost" className="justify-self-start" onClick={() => { update((x) => ({ ...setInsetPlace({ ...x, keys: undefined }, t, place), keys: undefined })); onSelect({ kind: "overlay", id: o.id }); }}>Tirar os keyframes (fica onde está agora)</Btn>}
</PropSection>
<PropSection title="Aparência">
<PropRow label="Borda">
<Check label="" checked={o.border !== null} onChange={(v) => set({ border: v ? "#FFFFFF" : null })} />
{o.border && <ColorDot label="Cor da borda" value={o.border} onChange={(v) => set({ border: v }, "bc")} />}
</PropRow>
{o.border && <PropRow label="Espessura"><Scrub label="Espessura da borda" min={0} max={40} step={1} value={o.borderW} format={(v) => `${v} px`} onChange={(v) => set({ borderW: v }, "bw")} /></PropRow>}
<PropRow label="Cantos"><Scrub label="Cantos arredondados" min={0} max={200} step={1} value={o.radius} format={(v) => `${v} px`} onChange={(v) => set({ radius: v }, "r")} /></PropRow>
<Check label="Sombra por baixo" checked={o.shadow} onChange={(v) => set({ shadow: v })} />
<PropRow label="Animação">
<Pick label="Animação da inserção" value={o.anim} onChange={(v) => set({ anim: v as InsetOverlay["anim"] })}>
{(["pop", "fade", "slide", "none"] as const).map((a) => <option key={a} value={a}>{ANIM_LABEL[a]}</option>)}
</Pick>
</PropRow>
</PropSection>
<PropSection title="Ordem">
<div className="flex flex-wrap items-center gap-1.5">
<Btn disabled={insetIdx === insetCount - 1} onClick={() => onProject((p) => moveInsetOrder(p, o.id, 1))}>Trazer para a frente</Btn>
<Btn disabled={insetIdx <= 0} onClick={() => onProject((p) => moveInsetOrder(p, o.id, -1))}>Mandar para trás</Btn>
</div>
<Hint>{insetCount > 1 ? `É a ${insetCount - insetIdx}ª de ${insetCount}, contando da frente.` : "Só há esta inserção."}</Hint>
</PropSection>
<div className="p-3">
<Btn variant="danger" onClick={() => { onProject((p) => ({ ...p, overlays: p.overlays.filter((x) => x.id !== o.id) })); onSelect({ kind: "layer", layer: "insets" }); }}>
<TrashIcon size={13} />Remover a inserção
</Btn>
</div>
</>
);
}
+178
View File
@@ -0,0 +1,178 @@
"use client";
// Painel "Camadas" do editor de cortes: tudo o que compõe o corte, de cima (o que fica na frente) para baixo,
// como a lista de camadas de um editor de imagem — textos, legenda, zoom, câmera (layout de cada trecho), vídeo
// (um item por trecho), áudio, narração, música, chat na tela, barra de progresso e capa. Clicar numa linha
// seleciona (as propriedades aparecem à direita e o item acende na timeline); o olho liga/desliga o que tem
// liga/desliga; "+" cria no playhead. Selecionar "Câmera" abre o monitor Fonte, onde a câmera e a área do jogo
// se ajustam com o mouse (mesmo em tela estreita).
import { useState, type ReactNode } from "react";
import type { CutSettings } from "./clipper-client";
import {
RESOLVED_MODE_LABEL, cfgAspect, chatDefault, clockTenths, outputDuration, resolvedMode, sessionClock, toOutput, toggleChat, type EditProject, type LayerKey,
type Selection,
} from "./clip-editor-model";
import { CaretIcon, EyeOffIcon, EyeOnIcon, IconBtn } from "./clip-editor-ui";
import { moveInsetOrder } from "./clip-editor-keyframes";
import { PlusIcon } from "./icons";
import { cx } from "./ui";
const sec = (v: number) => `${v.toFixed(1).replace(".", ",")} s`;
export function EditorLayers({ project, cfg, selection, presetLabel, onSelect, onSeek, onProject, onAdd }: {
project: EditProject;
cfg: CutSettings;
selection: Selection;
presetLabel: string;
onSelect: (s: Selection) => void;
onSeek: (t: number) => void;
onProject: (fn: (p: EditProject) => EditProject, key?: string) => void;
onAdd: (what: "text" | "zoom" | "narration" | "hook" | "reframe-key" | "inset") => void;
}) {
const sel = selection;
const isLayer = (k: LayerKey) => sel?.kind === "layer" && sel.layer === k;
const hook = project.overlays.find((o) => o.kind === "hook");
const texts = project.overlays.filter((o) => o.kind === "text");
const zooms = project.overlays.filter((o) => o.kind === "zoom");
const insets = project.overlays.filter((o) => o.kind === "inset");
const rfKeys = project.reframe?.keys ?? [];
const a = project.audio;
const total = outputDuration(project.cuts);
const overlaySel = (id: string) => sel?.kind === "overlay" && sel.id === id;
const chat = project.chat ?? chatDefault(cfgAspect(cfg));
return (
<div className="pb-2">
<Group chip="V3" title="Textos" meta={`${texts.length + (hook ? 1 : 0)}`} selected={isLayer("texts")} onSelect={() => onSelect({ kind: "layer", layer: "texts" })}
action={<IconBtn label="Novo texto no playhead" className="size-5" onClick={() => onAdd("text")}><PlusIcon size={13} /></IconBtn>}>
{hook ? <Item label={`Gancho · ${hook.kind === "hook" ? hook.text : ""}`} meta={sec(hook.end - hook.start)} color="#96203f" selected={overlaySel(hook.id)}
onClick={() => onSelect({ kind: "overlay", id: hook.id })} />
: <Item label="Adicionar gancho…" meta="" dim onClick={() => onAdd("hook")} />}
{texts.map((o) => <Item key={o.id} label={o.kind === "text" ? o.text : ""} meta={sessionClock(o.start)} color="#6f2f86" selected={overlaySel(o.id)}
onClick={() => { onSelect({ kind: "overlay", id: o.id }); onSeek(o.start); }} />)}
</Group>
<Group chip="C1" tone="#6b4fb3" title="Legenda" meta={project.captions.enabled ? presetLabel : "desligada"} selected={isLayer("captions")}
onSelect={() => onSelect({ kind: "layer", layer: "captions" })}
action={<Eye on={project.captions.enabled} label="a legenda" onToggle={() => onProject((p) => ({ ...p, captions: { ...p.captions, enabled: !p.captions.enabled } }))} />} />
<Group chip="INS" tone="#2f7a3d" title="Inserções" meta={`${insets.length}`} selected={isLayer("insets")} onSelect={() => onSelect({ kind: "layer", layer: "insets" })}
action={<IconBtn label="Nova inserção: desenhe o recorte na Fonte" className="size-5" onClick={() => onAdd("inset")}><PlusIcon size={13} /></IconBtn>}>
{[...insets].reverse().map((o, i) => (
<div key={o.id} className="group/ins flex items-center">
<div className="min-w-0 flex-1">
<Item label={`Inserção ${insets.length - i}`} meta={sessionClock(o.start)} color="#2f7a3d" selected={overlaySel(o.id)}
onClick={() => { onSelect({ kind: "overlay", id: o.id }); onSeek(o.start); }} />
</div>
<IconBtn label="Trazer para a frente" className="size-5" disabled={i === 0} onClick={() => onProject((p) => moveInsetOrder(p, o.id, 1))}>
<svg viewBox="0 0 24 24" width={11} height={11} fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true"><path d="m6 15 6-6 6 6" /></svg>
</IconBtn>
<IconBtn label="Mandar para trás" className="size-5" disabled={i === insets.length - 1} onClick={() => onProject((p) => moveInsetOrder(p, o.id, -1))}>
<svg viewBox="0 0 24 24" width={11} height={11} fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true"><path d="m6 9 6 6 6-6" /></svg>
</IconBtn>
</div>
))}
</Group>
<Group chip="V2" title="Zoom" meta={`${zooms.length}`} selected={isLayer("zooms")} onSelect={() => onSelect({ kind: "layer", layer: "zooms" })}
action={<IconBtn label="Novo zoom no playhead" className="size-5" onClick={() => onAdd("zoom")}><PlusIcon size={13} /></IconBtn>}>
{zooms.map((z) => <Item key={z.id} label={z.kind === "zoom" ? `Zoom ${z.scale.toFixed(2).replace(".", ",")}×` : ""} meta={sessionClock(z.start)} color="#1b665d"
selected={overlaySel(z.id)} onClick={() => { onSelect({ kind: "overlay", id: z.id }); onSeek(z.start); }} />)}
</Group>
<Group chip="CAM" tone="#7a5a16" title="Câmera" meta={cfg.layout.cam ? RESOLVED_MODE_LABEL[resolvedMode(cfg)].label : "câmera não marcada"} selected={isLayer("camera")}
onSelect={() => onSelect({ kind: "layer", layer: "camera" })}>
{project.cuts.map((c, i) => (
<Item key={`cam${i}-${c.start}`} label={`Trecho ${i + 1}`} meta={RESOLVED_MODE_LABEL[resolvedMode(cfg, c.mode)].label} color="#a8451f"
selected={sel?.kind === "cut" && sel.index === i} onClick={() => { onSelect({ kind: "cut", index: i }); onSeek(c.start); }} />
))}
</Group>
<Group chip="ENQ" tone="#7a3b8f" title="Enquadramento" meta={rfKeys.length ? `${rfKeys.length} keyframe${rfKeys.length > 1 ? "s" : ""}` : "quadro inteiro"} selected={isLayer("reframe")}
onSelect={() => onSelect({ kind: "layer", layer: "reframe" })}
action={<IconBtn label="Keyframe do enquadramento no playhead" className="size-5" onClick={() => onAdd("reframe-key")}>
<svg viewBox="0 0 12 12" width={10} height={10} aria-hidden="true"><path d="M6 1 11 6 6 11 1 6Z" fill="currentColor" /></svg>
</IconBtn>}>
{rfKeys.map((k, i) => (
<Item key={`rf${i}-${k.t}`} label={`◆ ${sessionClock(k.t)} · ${(1 / k.w).toFixed(2).replace(".", ",")}×`} meta={k.ease === "hold" ? "segurar" : k.ease === "linear" ? "linear" : "suave"}
color="#b06ad0" selected={sel?.kind === "reframe" && sel.key === i} onClick={() => { onSelect({ kind: "reframe", key: i }); onSeek(k.t); }} />
))}
</Group>
<Group chip="V1" title="Vídeo" meta={`${project.cuts.length} trecho${project.cuts.length > 1 ? "s" : ""} · ${sec(total)}`} selected={isLayer("video")}
onSelect={() => onSelect({ kind: "layer", layer: "video" })}>
{project.cuts.map((c, i) => (
<Item key={`${i}-${c.start}`} label={`Trecho ${i + 1}${c.muted ? " · mudo" : ""}`} color="#2b6389"
meta={`${clockTenths(toOutput(c.start, project.cuts).t)} · ${sec(c.end - c.start)}`}
selected={sel?.kind === "cut" && sel.index === i} onClick={() => { onSelect({ kind: "cut", index: i }); onSeek(c.start); }} />
))}
</Group>
<Group chip="A1" title="Áudio da live" meta={`${Math.round(a.volume * 100)}%`} selected={isLayer("audio")} onSelect={() => onSelect({ kind: "layer", layer: "audio" })} />
<Group chip="A2" title="Narração" meta={`${a.narration.length}`} selected={isLayer("narration")} onSelect={() => onSelect({ kind: "layer", layer: "narration" })}
action={<IconBtn label="Nova narração no playhead" className="size-5" onClick={() => onAdd("narration")}><PlusIcon size={13} /></IconBtn>}>
{a.narration.map((n) => <Item key={n.id} label={n.text} meta={sessionClock(n.at)} color="#0f6475" selected={sel?.kind === "narration" && sel.id === n.id}
onClick={() => { onSelect({ kind: "narration", id: n.id }); onSeek(n.at); }} />)}
</Group>
<Group chip="A3" title="Música e efeitos" meta={a.music ? a.music.file.split("/").pop() ?? "" : a.sfx.length ? `${a.sfx.length} efeito(s)` : "nenhuma"} selected={isLayer("music")}
onSelect={() => onSelect({ kind: "layer", layer: "music" })} />
<Group chip="CH" tone="#3a3a3a" title="Chat na tela" meta={chat.enabled ? `${chat.lines} mensagens` : "desligado"} selected={isLayer("chat")}
onSelect={() => onSelect({ kind: "layer", layer: "chat" })}
action={<Eye on={chat.enabled} label="o chat na tela" onToggle={() => onProject((p) => toggleChat(p, cfgAspect(cfg)))} />} />
<Group chip="▬" tone="#3a3a3a" title="Barra de progresso" meta={project.progress.enabled ? "ligada" : "desligada"} selected={isLayer("progress")}
onSelect={() => onSelect({ kind: "layer", layer: "progress" })}
action={<Eye on={project.progress.enabled} label="a barra de progresso" onToggle={() => onProject((p) => ({ ...p, progress: { ...p.progress, enabled: !p.progress.enabled } }))} />} />
<Group chip="▣" tone="#3a3a3a" title="Capa" meta={project.cover.enabled ? `${project.cover.text || "sem texto"}${project.cover.atStart ? " · no início" : ""}` : "desligada"} selected={isLayer("cover")}
onSelect={() => onSelect({ kind: "layer", layer: "cover" })}
action={<Eye on={project.cover.enabled} label="a capa" onToggle={() => onProject((p) => ({ ...p, cover: { ...p.cover, enabled: !p.cover.enabled } }))} />} />
</div>
);
}
function Eye({ on, label, onToggle }: { on: boolean; label: string; onToggle: () => void }) {
return (
<IconBtn label={`${on ? "Esconder" : "Mostrar"} ${label}`} className="size-5" onClick={onToggle}>
{on ? <EyeOnIcon size={13} /> : <EyeOffIcon size={13} className="text-nle-faint" />}
</IconBtn>
);
}
function Group({ chip, tone = "#265bc1", title, meta, selected, onSelect, action, children }: {
chip: string; tone?: string; title: string; meta: string; selected: boolean; onSelect: () => void; action?: ReactNode; children?: ReactNode;
}) {
const [open, setOpen] = useState(true);
const has = Boolean(children) && (Array.isArray(children) ? children.flat().some(Boolean) : true);
return (
<div className="border-b border-nle-line/70">
<div className={cx("flex h-7 items-center gap-1 pr-1.5 pl-1", selected ? "bg-nle-pressed/80" : "hover:bg-nle-hover/60")}>
<button type="button" aria-label={open ? `Recolher ${title}` : `Expandir ${title}`} aria-expanded={open} disabled={!has} onClick={() => setOpen((o) => !o)}
className={cx("grid size-4 shrink-0 place-items-center text-nle-dim", has ? "cursor-pointer" : "invisible")}><CaretIcon open={open} /></button>
<span className="grid h-[18px] w-6 shrink-0 place-items-center rounded-[2px] text-[10px] font-semibold text-white" style={{ background: tone }}>{chip}</span>
<button type="button" onClick={onSelect} className="flex h-full min-w-0 flex-1 cursor-pointer items-center gap-2 pl-1 text-left focus-visible:outline-1 focus-visible:outline-nle-focus">
<span className="shrink-0 font-semibold">{title}</span>
<span className="min-w-0 flex-1 truncate text-right text-[11px] text-nle-faint">{meta}</span>
</button>
{action}
</div>
{open && has && <div className="pb-1">{children}</div>}
</div>
);
}
function Item({ label, meta, color, selected = false, dim = false, onClick }: {
label: string; meta: string; color?: string; selected?: boolean; dim?: boolean; onClick: () => void;
}) {
return (
<button type="button" onClick={onClick}
className={cx("flex h-6 w-full cursor-pointer items-center gap-2 pr-2.5 pl-[30px] text-left focus-visible:outline-1 focus-visible:outline-nle-focus",
selected ? "bg-nle-accent/35 text-white" : "hover:bg-nle-hover/70", dim && "text-nle-faint")}>
<span className="h-3 w-[3px] shrink-0 rounded-[1px]" style={{ background: color ?? "transparent" }} />
<span className="min-w-0 flex-1 truncate">{label}</span>
<span className="shrink-0 font-mono text-[10.5px] text-nle-dim">{meta}</span>
</button>
);
}
+786
View File
@@ -0,0 +1,786 @@
// Modelo do editor de cortes no navegador: tipos do projeto de edição (mesmo contrato de clipper/app/editor.py),
// contas de tempo (sessão ↔ saída), operações de corte (remover/manter trecho, dividir, remover silêncios) e o
// histórico de desfazer/refazer por instantâneos (padrão de "comandos" do OpenCut, simplificado: o projeto é
// pequeno, então guardamos cópias inteiras).
import { useCallback, useState } from "react";
import {
MODE_LABEL, aspectOf, hookOf, mergeSettings, type Aspect, type Clip, type ClipAnalysis, type CutLayer, type CutSettings, type FrameSize, type HookAnim, type Rect,
type LayoutMode,
} from "./clipper-client";
/** `muted` = trecho sem o som da live (a narração e a música continuam). */
export type EditCut = { start: number; end: number; mode: LayoutMode | null; muted?: boolean };
export type EditWord = { s: number; e: number; w: string; emph?: boolean; hidden?: boolean };
export type CaptionPreset = "classic" | "pop" | "karaoke" | "single" | "minimal";
export type TextAnim = HookAnim;
/** Gancho: tempo de SAÍDA (vale a partir do 1º quadro). Texto: tempo da SESSÃO (gruda no conteúdo). */
export type TextOverlay = {
id: string; kind: "hook" | "text"; text: string; start: number; end: number;
/** Centro do texto na tela (0–1). `x` ausente = 0,5 (centralizado). Na tarja, `x` não conta (largura toda). */
x?: number; y: number; size: number; color: string; box: string | null; anim: TextAnim;
// Opcionais (só entram no projeto quando usados; projeto antigo continua igual):
/** `banner` = tarja na largura toda, centrada em `y`, texto em maiúsculas em até 2 linhas. Ausente = simples. */
style?: "banner";
/** Cor da tarja. */
bg?: string;
/** Fonte (uma das do serviço). Ausente = Arial Black no simples; a do gancho padrão (Luckiest Guy) na tarja. */
font?: string;
};
/** Chat da live na tela: as últimas mensagens num bloco; `x` = borda esquerda, `y` = base do bloco (0–1). */
export type ChatOverlay = { enabled: boolean; x: number; y: number; width: number; lines: number; size: number; showUser: boolean };
export const CHAT_DEFAULT: ChatOverlay = { enabled: false, x: 0.04, y: 0.62, width: 0.6, lines: 5, size: 34, showUser: true };
/** Quanto uma mensagem fica na tela se não chegar outra (igual ao render do servidor). */
export const CHAT_HOLD_S = 9;
/** Zoom (punch-in) em tempo da sessão; foco x/y 0–1 sobre o quadro vertical. */
export type ZoomOverlay = { id: string; kind: "zoom"; start: number; end: number; scale: number; x: number; y: number; ramp: number };
/** Curva de um keyframe até o seguinte: suave (ease in-out), linear ou segurar (salta no próximo). */
export type Ease = "smooth" | "linear" | "hold";
/**
* Keyframe do REENQUADRAMENTO do jogo (tempo da sessão): centro (`cx`, `cy`) e largura `w` da janela, em frações do
* quadro original; a altura sai da proporção da área de destino do jogo no layout daquele instante.
*/
export type ReframeKey = { t: number; cx: number; cy: number; w: number; ease: Ease };
/** Keyframe de posição/tamanho de uma inserção (tempo da sessão). */
export type InsetKey = { t: number; x: number; y: number; size: number; ease?: Ease };
export type InsetAnim = "pop" | "fade" | "slide" | "none";
/**
* Camada INSERIDA: um recorte `src` do quadro original (0–1) colado por cima do vídeo, centrado em (`x`, `y`) da
* saída, com largura `size` (fração da largura da saída; a altura sai da proporção do recorte). Tempo da sessão.
* Fica acima do vídeo e abaixo da legenda, do gancho, dos textos e do chat; a ordem no array é o empilhamento.
*/
export type InsetOverlay = {
id: string; kind: "inset"; start: number; end: number; src: Rect; x: number; y: number; size: number;
/** Cor da borda ou null (sem borda); `borderW` e `radius` em px do QUADRO LÓGICO (no horizontal saem a 75 %). */
border: string | null; borderW: number; radius: number; shadow: boolean; anim: InsetAnim;
keys?: InsetKey[];
};
export type Overlay = TextOverlay | ZoomOverlay | InsetOverlay;
export type Narration = { id: string; file: string; at: number; volume: number; durationS: number; duck: number; text: string; voice: string };
export type Sfx = { id: string; file: string; at: number; volume: number };
export type EditProject = {
schema: 1;
source: { sessionId: number; lo: number; hi: number };
settings: CutLayer;
cuts: EditCut[];
captions: { enabled: boolean; preset: CaptionPreset; style: Partial<CutSettings["caption"]>; emphColor: string; words: EditWord[] };
overlays: Overlay[];
progress: { enabled: boolean; color: string; height: number };
audio: { volume: number; narration: Narration[]; music: { file: string; volume: number; duck: boolean } | null; sfx: Sfx[] };
/** `atStart` = a capa também entra nos 2 primeiros quadros do vídeo (miniatura padrão das redes). */
cover: { enabled: boolean; t: number; text: string; atStart?: boolean };
chat?: ChatOverlay;
/** Reenquadramento do jogo no tempo (com keys, vale no lugar de `layout.game`; não vale na câmera inteira). */
reframe?: { keys: ReframeKey[] };
/** Quem fez esta versão: "ai" = entregue pelo pipeline (passos que a IA aplicou); "user" = editado por você. */
meta?: { origin: "ai" | "user"; generatedAt: string; model: string; steps: string[] };
};
export type ChatItem = { t: number; user: string; text: string; emotes: string[] };
export type PresetInfo = { id: CaptionPreset; label: string; style: Partial<CutSettings["caption"]> };
/** Resposta de GET /v1/clips/{id}/edit. */
export type EditBundle = {
clip: Clip;
project: EditProject;
rev: number;
saved: boolean;
/** Origem da versão salva (ou "ai" quando ainda não há projeto salvo). */
origin: "ai" | "user";
/** O projeto que a IA entregou (para voltar a ele). */
aiProject: EditProject | null;
exportedAt: string | null;
cover: string | null;
window: { lo: number; hi: number };
sessionDurationS: number;
words: EditWord[];
chat: ChatItem[];
chatPerS: number[];
loudnessDb: (number | null)[];
analysis: ClipAnalysis | null;
settings: CutSettings;
credit: string;
presets: PresetInfo[];
audioLibrary: { file: string; name: string }[];
proxy: { file: string; lo: number; hi: number } | null;
waveform: number[] | null;
peaksPerS: number;
judgeEnabled: boolean;
voiceConfigured: boolean;
limits: { maxWindowS: number; maxOutputS: number; minOutputS: number; previewMaxS: number; retranscribeMaxS: number };
};
export type Suggestion = {
hook: string; title: string; start: number; end: number;
remove: { start: number; end: number; why: string }[];
zooms: { t: number; why: string }[];
reason: string; seconds: number; model: string | null;
};
/** Camadas do corte (trilhas da timeline e linhas do painel Camadas). Selecionar uma abre as propriedades dela. */
export type LayerKey = "video" | "camera" | "captions" | "texts" | "zooms" | "audio" | "narration" | "music" | "progress" | "cover" | "chat"
| "reframe" | "insets";
export type Selection =
| { kind: "layer"; layer: LayerKey }
| { kind: "cut"; index: number }
| { kind: "words"; from: number; to: number }
/** `key` = keyframe selecionado da inserção (índice em `keys`). */
| { kind: "overlay"; id: string; key?: number }
/** Keyframe do enquadramento (índice em `reframe.keys`). */
| { kind: "reframe"; key: number }
| { kind: "narration"; id: string }
| { kind: "range"; a: number; b: number }
| null;
export const MIN_CUT_S = 0.2;
export const FPS = 30;
/* ---------- formato (vertical 9:16 ou horizontal 16:9) ---------- */
/** Quadro do corte: tamanho do vídeo de saída e quadro lógico dos textos (ASS). */
export type Frame = FrameSize & { aspect: Aspect };
/**
* Espelho de `layout.FRAME_SIZES`/`CANVAS_SIZES` do serviço. Só vale quando a rota de settings não manda `frames`
* (serviço antigo); o editor usa o que o serviço mandar. No horizontal os textos são contados em 2560×1440 (75 %).
*/
export const FALLBACK_FRAMES: Record<Aspect, FrameSize> = {
vertical: { width: 1080, height: 1920, canvasWidth: 1080, canvasHeight: 1920 },
horizontal: { width: 1920, height: 1080, canvasWidth: 2560, canvasHeight: 1440 },
};
export function frameOf(aspect: Aspect, frames?: Partial<Record<Aspect, FrameSize>> | null): Frame {
return { aspect, ...(frames?.[aspect] ?? FALLBACK_FRAMES[aspect]) };
}
/** Formato efetivo do corte: o do projeto (`settings.format`), senão o da sessão, senão o do arquivo renderizado. */
export function projectAspect(project: EditProject, session: Partial<CutSettings> | null | undefined, clip?: Pick<Clip, "aspect"> | null): Aspect {
return project.settings.format?.aspect ?? session?.format?.aspect ?? aspectOf(clip);
}
/** Layout já resolvido de um instante. `full` = quadro inteiro (só no horizontal). */
export type ResolvedMode = Exclude<LayoutMode, "auto"> | "full";
export const RESOLVED_MODE_LABEL: Record<ResolvedMode, { label: string; hint: string }> = {
...(MODE_LABEL as Record<Exclude<LayoutMode, "auto">, { label: string; hint: string }>),
full: { label: "Quadro inteiro", hint: "o jogo em tela cheia" },
};
/* ---------- tempo ---------- */
export type Piece = { start: number; end: number; out: number; mode: LayoutMode | null };
export function pieces(cuts: EditCut[]): Piece[] {
let acc = 0;
return cuts.map((c) => {
const p = { start: c.start, end: c.end, out: acc, mode: c.mode };
acc += c.end - c.start;
return p;
});
}
export function outputDuration(cuts: EditCut[]): number {
return cuts.reduce((sum, c) => sum + c.end - c.start, 0);
}
/** Sessão → saída. `inside` = o instante está num trecho mantido (senão gruda no começo do próximo). */
export function toOutput(t: number, cuts: EditCut[]): { t: number; inside: boolean } {
for (const p of pieces(cuts)) {
if (t < p.start) return { t: p.out, inside: false };
if (t <= p.end) return { t: p.out + t - p.start, inside: true };
}
return { t: outputDuration(cuts), inside: false };
}
export function toSession(tOut: number, cuts: EditCut[]): number {
const ps = pieces(cuts);
for (const p of ps) if (tOut <= p.out + p.end - p.start) return p.start + Math.max(0, tOut - p.out);
return ps.length ? ps[ps.length - 1].end : 0;
}
/** Índice do trecho que contém `t` (ou -1). */
export function cutAt(cuts: EditCut[], t: number): number {
return cuts.findIndex((c) => t >= c.start && t <= c.end);
}
/** Próximo trecho mantido a partir de `t` (para pular os removidos ao tocar). */
export function nextCut(cuts: EditCut[], t: number): EditCut | null {
return cuts.find((c) => c.end > t + 0.01) ?? null;
}
/* ---------- operações nos trechos ---------- */
export function normalizeCuts(cuts: EditCut[]): EditCut[] {
const out: EditCut[] = [];
for (const c of [...cuts].sort((a, b) => a.start - b.start)) {
if (c.end - c.start < MIN_CUT_S - 1e-6) continue;
const last = out[out.length - 1];
if (last && c.start <= last.end + 0.02 && c.mode === last.mode && Boolean(c.muted) === Boolean(last.muted)) last.end = Math.max(last.end, c.end);
else out.push({ ...c });
}
return out.map((c) => ({ ...c, start: round3(c.start), end: round3(c.end) }));
}
/** Tira [a, b] dos trechos mantidos (edição pela transcrição: apagar palavras/frases). */
export function removeRange(cuts: EditCut[], a: number, b: number): EditCut[] {
const out: EditCut[] = [];
for (const c of cuts) {
if (b <= c.start || a >= c.end) { out.push({ ...c }); continue; }
if (a > c.start) out.push({ ...c, end: a });
if (b < c.end) out.push({ ...c, start: b });
}
return normalizeCuts(out);
}
/** Devolve [a, b] ao corte (une com os trechos vizinhos). */
export function keepRange(cuts: EditCut[], a: number, b: number): EditCut[] {
const mode = cuts[cutAt(cuts, a)]?.mode ?? cuts[cutAt(cuts, b)]?.mode ?? null;
const merged: EditCut[] = [];
for (const c of [...cuts, { start: a, end: b, mode }].sort((x, y) => x.start - y.start)) {
const last = merged[merged.length - 1];
if (last && c.start <= last.end + 0.02) last.end = Math.max(last.end, c.end);
else merged.push({ ...c });
}
return normalizeCuts(merged);
}
export function splitAt(cuts: EditCut[], t: number): EditCut[] {
const i = cutAt(cuts, t);
if (i < 0) return cuts;
const c = cuts[i];
if (t - c.start < MIN_CUT_S || c.end - t < MIN_CUT_S) return cuts;
// Dividir = dois trechos encostados; normalizeCuts juntaria de novo, então não normaliza aqui.
return [...cuts.slice(0, i), { ...c, end: round3(t) }, { ...c, start: round3(t) }, ...cuts.slice(i + 1)];
}
/**
* "Remover silêncios > X s": entre duas palavras seguidas dentro do corte, tira o vão deixando `pad` de respiro
* de cada lado (estilo "Shorten word gaps" do Descript).
*/
export function removeSilences(cuts: EditCut[], words: EditWord[], minGap: number, pad = 0.15): { cuts: EditCut[]; removed: number; seconds: number } {
const visible = words.filter((w) => !w.hidden && w.w.trim()).sort((a, b) => a.s - b.s);
let out = cuts;
let removed = 0;
let seconds = 0;
for (let i = 0; i + 1 < visible.length; i++) {
const a = visible[i].e + pad;
const b = visible[i + 1].s - pad;
if (visible[i + 1].s - visible[i].e < minGap || b - a < 0.1) continue;
const ci = cutAt(out, a);
if (ci < 0 || ci !== cutAt(out, b)) continue;
out = removeRange(out, a, b);
removed += 1;
seconds += b - a;
}
return { cuts: out, removed, seconds };
}
/* ---------- legenda (prévia no navegador) ---------- */
export type OutWord = { start: number; end: number; word: string; emph: boolean };
export function outputWords(project: EditProject): OutWord[] {
const ps = pieces(project.cuts);
const out: OutWord[] = [];
for (const w of project.captions.words) {
if (w.hidden || !w.w.trim()) continue;
const mid = (w.s + w.e) / 2;
const p = ps.find((x) => mid >= x.start && mid <= x.end);
if (!p) continue;
const s = p.out + Math.max(w.s, p.start) - p.start;
const e = p.out + Math.min(w.e, p.end) - p.start;
// Arredondado a 3 casas como `editor.output_words` (o agrupamento compara esses números).
out.push({ start: round3(s), end: round3(Math.max(e, s + 0.05)), word: w.w, emph: Boolean(w.emph) });
}
return out;
}
/*
* Blocos da legenda: PORTE de clipper/app/subtitles.py (clean_words, group_words, caption_blocks), com as mesmas
* constantes. O render do editor usa exatamente isso (editor_render.build_project_ass); se mudar lá, muda aqui.
* Conferido contra o Python com as palavras reais do corte 61 e o caso de fala rápida dos testes do serviço.
*/
export const CAPTION_TIMING = {
MAX_WORDS: 3, MAX_CHARS: 18, MAX_GAP_S: 0.6,
/** Duração mínima de uma palavra na legenda. */
MIN_WORD_S: 0.06,
/** Duas palavras nunca começam no mesmo instante (a palavra destacada precisa de tempo próprio). */
MIN_STEP_S: 0.04,
/** A última palavra do bloco fica pelo menos isto (se o próximo bloco não começar antes). */
MIN_HOLD_S: 0.25,
/** Bloco mais longo que isto quebra (fala arrastada). */
MAX_BLOCK_S: 3.2,
/** Bloco cheio mais curto que isto = fala rápida: aceita uma palavra a mais. */
FAST_BLOCK_S: 0.7,
} as const;
/** `round(x, 3)` do Python (meio para o par), para os tempos saírem iguais aos do serviço. */
function pyRound3(v: number): number {
const x = v * 1000;
const f = Math.floor(x);
const d = x - f;
const r = Math.abs(d - 0.5) < 1e-9 ? (f % 2 === 0 ? f : f + 1) : Math.round(x);
return r / 1000;
}
/**
* Saneia os tempos: ordena, tira vazias, dá duração mínima, empurra a que começa junto com a anterior e corta o fim
* de uma palavra no início da seguinte (sem sobreposição). Idempotente. Puro.
*/
export function cleanWords(words: OutWord[]): OutWord[] {
const { MIN_STEP_S, MIN_WORD_S } = CAPTION_TIMING;
const items = words.filter((w) => w.word.trim()).sort((a, b) => a.start - b.start || a.end - b.end);
const out: OutWord[] = [];
for (const w of items) {
let start = w.start;
const last = out[out.length - 1];
if (last && start < last.start + MIN_STEP_S - 1e-6) start = pyRound3(last.start + MIN_STEP_S);
const end = Math.max(w.end, pyRound3(start + MIN_WORD_S));
if (last && last.end > start + 1e-9) out[out.length - 1] = { ...last, end: start };
out.push({ ...w, start, end, word: w.word.trim() });
}
return out;
}
/** Blocos (palavras saneadas): até `maxWords` e um limite de caracteres; pausa > 0,6 s ou bloco > 3,2 s quebra. */
export function groupWords(words: OutWord[], maxWords: number = CAPTION_TIMING.MAX_WORDS): OutWord[][] {
const { MAX_WORDS, MAX_CHARS, MAX_GAP_S, MAX_BLOCK_S, FAST_BLOCK_S } = CAPTION_TIMING;
const maxChars = MAX_CHARS + 6 * Math.max(0, maxWords - MAX_WORDS);
const groups: OutWord[][] = [];
for (const word of cleanWords(words)) {
const cur = groups[groups.length - 1];
if (cur && word.start - cur[cur.length - 1].end <= MAX_GAP_S && word.end - cur[0].start <= MAX_BLOCK_S) {
const fits = [...cur, word].map((w) => w.word).join(" ").length <= maxChars;
// Fala rápida: o bloco cheio passaria voando; uma palavra a mais (se couber) dá tempo de ler.
const room = cur.length < maxWords || (maxWords >= 2 && cur.length === maxWords && word.end - cur[0].start < FAST_BLOCK_S);
if (fits && room) { cur.push(word); continue; }
}
groups.push([word]);
}
return groups;
}
export type CaptionBlock = { words: OutWord[]; end: number };
/** Blocos com o fim: nunca passa do início do bloco seguinte (dois eventos ativos o libass empilharia). */
export function captionBlocks(words: OutWord[], maxWords: number = CAPTION_TIMING.MAX_WORDS): CaptionBlock[] {
const groups = groupWords(words, maxWords);
return groups.map((g, k) => {
let end = Math.max(g[g.length - 1].end, g[g.length - 1].start + CAPTION_TIMING.MIN_HOLD_S);
if (k + 1 < groups.length) end = Math.min(end, groups[k + 1][0].start);
return { words: g, end: pyRound3(end) };
});
}
/**
* Bloco e palavra destacada no instante `t` (saída), como os eventos do ASS: o bloco vale de `[0].start` até `end`;
* a palavra i vale do início dela até o início da seguinte (a última, até o fim do bloco).
*/
export function captionAt(blocks: CaptionBlock[], t: number): { block: CaptionBlock; active: number } | null {
const block = blocks.find((b) => t >= b.words[0].start && t < b.end);
if (!block) return null;
let active = 0;
for (let i = 0; i < block.words.length; i++) if (t >= block.words[i].start) active = i;
return { block, active };
}
/** Configuração efetiva da prévia: canal/sessão ← projeto ← preset ← estilo da legenda (igual ao servidor). */
export function effectiveSettings(base: CutSettings, project: EditProject, presets: PresetInfo[], clip?: Pick<Clip, "aspect"> | null): CutSettings {
const cfg = mergeSettings(base, project.settings);
Object.assign(cfg.caption, presets.find((p) => p.id === project.captions.preset)?.style ?? {}, project.captions.style);
cfg.caption.enabled = project.captions.enabled;
// Serviço antigo sem `format`: o formato vem do arquivo do corte. Daqui para baixo `format` sempre existe.
cfg.format = { aspect: projectAspect(project, base, clip) };
return cfg;
}
/** Formato da configuração efetiva (ausente = vertical). */
export function cfgAspect(cfg: Pick<CutSettings, "format">): Aspect {
return aspectOf(cfg.format);
}
/** Igual a `layout.resolved_mode` do serviço. No horizontal só há câmera inteira (com câmera marcada) e quadro inteiro. */
export function resolvedMode(cfg: CutSettings, override?: LayoutMode | null): ResolvedMode {
const mode = override && override !== "auto" ? override : cfg.layout.mode;
if (cfgAspect(cfg) === "horizontal") return mode === "cam_only" && cfg.layout.cam ? "cam_only" : "full";
if (mode === "auto") return cfg.layout.cam ? "cam_top" : "blur";
if ((mode === "cam_top" || mode === "cam_only") && !cfg.layout.cam) return "blur";
return mode;
}
/**
* Ajuste de layout DESTE CORTE (`settings.layout` do projeto: câmera, área do jogo, layout e altura da câmera).
* Vale para o corte inteiro; o que muda por trecho é só `cuts[i].mode`. Chave apagada = volta a valer a da sessão.
*/
export function editLayout(project: EditProject, fn: (layout: NonNullable<CutLayer["layout"]>) => void): EditProject {
const layout = { ...(project.settings.layout ?? {}) };
fn(layout);
return { ...project, settings: { ...project.settings, layout } };
}
/** Altura (px do vídeo vertical = quadro lógico) do painel da câmera no "câmera em cima". */
export function camPanelHeight(cfg: CutSettings, frame: Frame): number {
return Math.round((frame.height * cfg.layout.camHeight) / 2) * 2;
}
/** Centro da legenda em px do quadro lógico (igual a `layout.caption_y`): horizontal a 85 %; vertical na emenda ou 1420. */
export function captionY(cfg: CutSettings, mode: ResolvedMode, frame: Frame): number {
if (cfg.caption.y !== null) return Math.round(frame.canvasHeight * cfg.caption.y);
if (frame.aspect === "horizontal") return Math.round(frame.canvasHeight * 0.85);
return mode === "cam_top" ? camPanelHeight(cfg, frame) + 40 : 1420;
}
/** Chat na tela padrão do formato: no 16:9, um bloco estreito no canto de baixo à esquerda, acima da legenda. */
export const CHAT_DEFAULT_HORIZONTAL: ChatOverlay = { ...CHAT_DEFAULT, x: 0.02, y: 0.78, width: 0.3, lines: 6 };
export function chatDefault(aspect: Aspect): ChatOverlay {
return aspect === "horizontal" ? CHAT_DEFAULT_HORIZONTAL : CHAT_DEFAULT;
}
/**
* Liga/desliga o chat na tela. Ao LIGAR, se a posição ainda é o padrão do outro formato (nunca foi mexida), passa
* para o padrão do formato atual: o bloco do 9:16 (60 % da largura) não faz sentido no 16:9.
*/
export function toggleChat(project: EditProject, aspect: Aspect): EditProject {
const cur = project.chat ?? chatDefault(aspect);
if (cur.enabled) return { ...project, chat: { ...cur, enabled: false } };
const other = chatDefault(aspect === "horizontal" ? "vertical" : "horizontal");
const mine = chatDefault(aspect);
const untouched = cur.x === other.x && cur.y === other.y && cur.width === other.width && cur.lines === other.lines;
return { ...project, chat: { ...cur, ...(untouched ? { x: mine.x, y: mine.y, width: mine.width, lines: mine.lines } : {}), enabled: true } };
}
/** Foco padrão de um zoom novo: um pouco acima do meio no 9:16 (rosto/ação); o centro no 16:9. */
export function zoomFocusDefault(aspect: Aspect): { x: number; y: number } {
return aspect === "horizontal" ? { x: 0.5, y: 0.5 } : { x: 0.5, y: 0.45 };
}
/**
* Gancho novo no estilo da configuração do corte (grupo `hook`), como o `editor.auto_project` do serviço: na tarja,
* tamanho 76 e, se a legenda automática estiver perto de 20 % da altura, a tarja vai para o outro lado.
*/
export function newHook(cfg: CutSettings, frame: Frame, text = "ESCREVA O GANCHO"): TextOverlay {
const hk = hookOf(cfg);
const base: TextOverlay = { id: "hook", kind: "hook", text, start: 0, end: round3(hk.seconds), y: 0.2, size: 68, color: "#FFFFFF", box: "#E11D48", anim: "pop" };
if (hk.style !== "banner") return { ...base, color: hk.color, font: hk.font, anim: hk.anim };
const capY = captionY(cfg, resolvedMode(cfg), frame) / frame.canvasHeight;
const y = Math.abs(capY - 0.2) < 0.2 ? round3(capY > 0.3 ? capY - 0.22 : Math.min(0.85, capY + 0.22)) : 0.2;
return { ...base, style: "banner", bg: hk.bg, color: hk.color, font: hk.font, anim: hk.anim, box: null, size: 76, y };
}
/* ---------- tarja do gancho (espelho de editor_render.banner_layout) ---------- */
export const BANNER_MAX_LINES = 2;
/** A tarja atravessa a tela nesse tempo (anim `slide`). */
export const BANNER_SLIDE_MS = 240;
/** O texto entra deslizando, borrado, e assenta nítido nesse intervalo (anim `slide`). */
export const TEXT_SLIDE_MS: [number, number] = [90, 430];
/** Quebra pela largura ESTIMADA em caracteres (a mesma conta do serviço: a quebra da prévia é a do render). */
export function charLines(text: string, size: number, width: number, charW = 0.6, minChars = 4): string[] {
const max = Math.max(minChars, Math.floor(width / (size * charW)));
const lines: string[] = [];
let line = "";
for (const word of text.split(/\s+/).filter(Boolean)) {
if (line && line.length + 1 + word.length > max) { lines.push(line); line = word; }
else line = `${line} ${word}`.trim();
}
if (line) lines.push(line);
return lines;
}
/** Quebra do texto simples (`editor_render._wrap`): até 4 linhas, ~0,58 do tamanho por caractere. */
export function plainLines(text: string, size: number, width: number): string[] {
return charLines(text, size, width, 0.58, 6).slice(0, 4);
}
export type BannerGeometry = { lines: string[]; size: number; top: number; height: number; cy: number };
/** Linhas (até 2, sem cortar palavra: a fonte diminui até caber), tamanho, topo e altura da faixa no quadro lógico. */
export function bannerLayout(o: Pick<TextOverlay, "text" | "size" | "y">, frame: Pick<Frame, "canvasWidth" | "canvasHeight">): BannerGeometry {
const { canvasWidth: cw, canvasHeight: ch } = frame;
const text = o.text.toUpperCase();
let size = Math.trunc(o.size);
let lines = charLines(text, size, Math.trunc(cw * 0.9));
while (lines.length > BANNER_MAX_LINES && size > 24) {
size = Math.max(24, Math.trunc(size * 0.9));
lines = charLines(text, size, Math.trunc(cw * 0.9));
}
const height = Math.round(lines.length * size * 1.18 + 2 * size * 0.42);
const cy = Math.trunc(ch * o.y);
const top = Math.max(0, Math.min(ch - height, cy - Math.floor(height / 2)));
return { lines, size, top, height, cy: top + Math.floor(height / 2) };
}
/**
* Parte do quadro original que o render REALMENTE mostra num `crop=<rect>` seguido de `_fill(dw, dh)`
* (layout.layout_chain do serviço), em frações do original. O FFmpeg não recorta em subpixel: no yuv420 o `crop`
* trunca e arredonda x, y, largura e altura para PAR; o `scale ... force_original_aspect_ratio=increase` arredonda o
* tamanho; e o `crop` central também cai em par. Medido no corte 61 (câmera 18 % × 23 %): sem isso a prévia saía
* 1–3 px deslocada (o render mostrava ~1,3 px do original a mais à esquerda e 2 px em cima). `src` = tamanho da
* gravação em px (sessão › capture); `dw`×`dh` = destino em px do vídeo de saída.
*/
export function ffmpegCropFill(rect: Rect | null, src: { w: number; h: number }, dw: number, dh: number): Rect {
const r = rect ?? { x: 0, y: 0, w: 1, h: 1 };
const even = (v: number) => Math.floor(v) - (Math.floor(v) % 2);
const cw = Math.max(2, even(src.w * r.w)), ch = Math.max(2, even(src.h * r.h));
const cx = clamp(even(src.w * r.x), 0, src.w - cw), cy = clamp(even(src.h * r.y), 0, src.h - ch);
// scale=dw:dh:force_original_aspect_ratio=increase (av_rescale arredonda ao mais próximo)
const W = Math.max(Math.round((dh * cw) / ch), dw), H = Math.max(Math.round((dw * ch) / cw), dh);
// crop=dw:dh no centro: (iw − ow)/2 truncado e em par
const ox = even((W - dw) / 2), oy = even((H - dh) / 2);
const fx = W / cw, fy = H / ch;
return { x: (cx + ox / fx) / src.w, y: (cy + oy / fy) / src.h, w: dw / fx / src.w, h: dh / fy / src.h };
}
/* ---------- keyframes: reenquadramento e inserções (funções puras; o render do serviço faz a mesma conta) ---------- */
/** Proporção do quadro original da gravação (as lives chegam em 16:9; janelas e recortes são frações dele). */
export const SOURCE_RATIO = 16 / 9;
/** Largura mínima da janela do jogo (fração do original): o contrato aceita 0,05–1. */
export const REFRAME_MIN_W = 0.05;
/** Dois keyframes a menos que isto (s) são o mesmo instante (um quadro a 30 fps ≈ 0,033 s). */
export const KEY_EPS = 0.02;
/** Animação das inserções (reframe.py do serviço): alfa de entrada/saída, deslize e sombra. */
export const INSET_ANIM_S = 0.18;
export const INSET_SLIDE_S = 0.35;
export const INSET_SHADOW_ALPHA = 0.55;
/** Fração da curva: suave = smoothstep (3u² − 2u³); linear = u; segurar = 0 até o próximo key. */
export function easeAt(ease: Ease, u: number): number {
const v = clamp(u, 0, 1);
if (ease === "hold") return v >= 1 ? 1 : 0;
if (ease === "linear") return v;
return v * v * (3 - 2 * v);
}
/**
* Interpola keyframes ordenados por `t`: antes do 1º e depois do último segura o valor; entre dois, usa a curva do
* key de ORIGEM. `pick` diz quais campos numéricos entram. Puro.
*/
export function interpolate<K extends { t: number }>(keys: K[], t: number, fields: (keyof K)[], easeOf: (k: K) => Ease): K | null {
if (!keys.length) return null;
if (t <= keys[0].t) return keys[0];
const last = keys[keys.length - 1];
if (t >= last.t) return last;
let i = 0;
while (i + 1 < keys.length && keys[i + 1].t <= t) i++;
const a = keys[i], b = keys[i + 1];
const u = easeAt(easeOf(a), (t - a.t) / Math.max(1e-6, b.t - a.t));
const out = { ...a, t } as K;
for (const f of fields) (out as Record<keyof K, unknown>)[f] = (a[f] as number) + ((b[f] as number) - (a[f] as number)) * u;
return out;
}
/** Centro e largura da janela do jogo no instante `t` (sessão). null = sem keyframes. */
export function reframeAt(project: Pick<EditProject, "reframe">, t: number): { cx: number; cy: number; w: number } | null {
const k = interpolate(project.reframe?.keys ?? [], t, ["cx", "cy", "w"], (x) => x.ease);
return k && { cx: k.cx, cy: k.cy, w: k.w };
}
/**
* Janela (retângulo 0–1 do original) para um destino de proporção `destRatio` (largura/altura em px): a altura sai da
* proporção; se não couber, encolhe; e a janela é presa dentro do quadro.
*/
export function reframeWindow(v: { cx: number; cy: number; w: number }, destRatio: number, srcRatio = SOURCE_RATIO): Rect {
let w = clamp(v.w, REFRAME_MIN_W, 1);
let h = (w * srcRatio) / destRatio;
if (h > 1) { w = w / h; h = 1; }
const x = clamp(v.cx - w / 2, 0, 1 - w), y = clamp(v.cy - h / 2, 0, 1 - h);
return { x, y, w, h };
}
/** Centro e largura de volta a partir de uma janela (para gravar o key depois de arrastar na Fonte). */
export function windowToKey(r: Rect): { cx: number; cy: number; w: number } {
return { cx: round4(r.x + r.w / 2), cy: round4(r.y + r.h / 2), w: round4(r.w) };
}
/**
* Área de destino do jogo com reenquadramento (px do vídeo), como `layout.layout_chain` do serviço: câmera em cima =
* a parte de baixo; nos outros modos (só o jogo, desfoque, quadro inteiro) = a tela toda. Câmera inteira: não vale.
*/
export function gameArea(mode: ResolvedMode, cfg: CutSettings, frame: Frame): { w: number; h: number } | null {
if (mode === "cam_only") return null;
if (mode === "cam_top") return { w: frame.width, h: frame.height - camPanelHeight(cfg, frame) };
return { w: frame.width, h: frame.height };
}
/** Janela do jogo efetiva num instante, ou null se não há keyframes / o layout não tem jogo. */
export function gameWindowAt(project: EditProject, cfg: CutSettings, frame: Frame, t: number): Rect | null {
const v = reframeAt(project, t);
if (!v) return null;
const ci = cutAt(project.cuts, t);
const area = gameArea(resolvedMode(cfg, ci >= 0 ? project.cuts[ci].mode : null), cfg, frame);
return area ? reframeWindow(v, area.w / area.h) : null;
}
/**
* "Auto-key": grava valores num keyframe NO instante `t` — atualiza o que já existe ali ou cria um novo (com a curva
* do key anterior, ou suave). Mantém a lista ordenada. Puro (pode rodar no updater do setState).
*/
export function upsertKey<K extends { t: number }>(keys: K[], t: number, values: Partial<Omit<K, "t">>, fresh: (prev: K | null) => Partial<K> = () => ({})): { keys: K[]; index: number } {
const at = keys.findIndex((k) => Math.abs(k.t - t) < KEY_EPS);
if (at >= 0) {
const next = keys.map((k, i) => (i === at ? { ...k, ...values } : k));
return { keys: next, index: at };
}
const prev = [...keys].reverse().find((k) => k.t < t) ?? null;
const key = { ...fresh(prev), ...values, t: round3(t) } as K;
const next = [...keys, key].sort((a, b) => a.t - b.t);
return { keys: next, index: next.indexOf(key) };
}
/** Altura da inserção em fração da altura da saída (sai da proporção do recorte). */
export function insetHeight(o: Pick<InsetOverlay, "src" | "size">, frame: Pick<Frame, "width" | "height">, srcRatio = SOURCE_RATIO): number {
const ratio = (o.src.w * srcRatio) / Math.max(1e-6, o.src.h); // largura/altura do recorte em px
return (o.size * frame.width) / ratio / frame.height;
}
/**
* Posição e tamanho da inserção no instante `t`. `toTime` converte o tempo dos keys (sessão) para o eixo de `t`: o
* serviço interpola em tempo de SAÍDA (keys convertidos), então a prévia passa `toOutput`; a edição usa a sessão.
*/
export function insetAt(o: InsetOverlay, t: number, toTime: (s: number) => number = (s) => s): { x: number; y: number; size: number } {
const keys = (o.keys ?? []).map((k) => ({ ...k, t: toTime(k.t) }));
const k = interpolate(keys, t, ["x", "y", "size"], (x) => x.ease ?? "smooth");
return k ? { x: k.x, y: k.y, size: k.size } : { x: o.x, y: o.y, size: o.size };
}
/** Grava posição/tamanho da inserção no instante `t`: com keys, auto-key; sem keys, os valores da própria camada. */
export function setInsetPlace(o: InsetOverlay, t: number, place: Partial<{ x: number; y: number; size: number }>): InsetOverlay {
const r = { ...(place.x !== undefined ? { x: round4(place.x) } : {}), ...(place.y !== undefined ? { y: round4(place.y) } : {}), ...(place.size !== undefined ? { size: round4(place.size) } : {}) };
if (!o.keys?.length) return { ...o, ...r };
const cur = insetAt(o, t);
return { ...o, keys: upsertKey<InsetKey>(o.keys, t, { ...cur, ...r }, (prev) => ({ ease: prev?.ease ?? "smooth" })).keys };
}
export function round4(v: number): number {
return Math.round(v * 10000) / 10000;
}
/** Zoom no instante de saída `t`: escala e foco (mesma envoltória do zoompan do servidor). */
export function zoomAt(project: EditProject, t: number): { z: number; fx: number; fy: number } {
let z = 1, fx = 0.5, fy = 0.5;
for (const o of project.overlays) {
if (o.kind !== "zoom") continue;
const a = toOutput(o.start, project.cuts).t;
const b = toOutput(o.end, project.cuts).t;
if (b - a < 0.1) continue;
const r = Math.max(0.001, Math.min(o.ramp, (b - a) / 2));
const env = clamp((t - a) / r, 0, 1) * clamp((b - t) / r, 0, 1);
z += (o.scale - 1) * env;
fx += (o.x - 0.5) * env;
fy += (o.y - 0.5) * env;
}
return { z, fx, fy };
}
/* ---------- utilidades ---------- */
export function clamp(v: number, lo: number, hi: number): number {
return Math.min(hi, Math.max(lo, v));
}
export function round3(v: number): number {
return Math.round(v * 1000) / 1000;
}
export function newId(prefix: string): string {
return `${prefix}${Math.random().toString(36).slice(2, 9)}`;
}
/** "1:05,3" — relógio com décimos (timeline e inspetor). */
export function clockTenths(seconds: number): string {
const s = Math.max(0, seconds);
const m = Math.floor(s / 60);
const rest = s - m * 60;
return `${m}:${rest.toFixed(1).padStart(4, "0").replace(".", ",")}`;
}
/** "00:00:12:15" — timecode de editor (hh:mm:ss:quadros a 30 fps). */
export function timecode(seconds: number): string {
const total = Math.max(0, Math.round(seconds * FPS));
const f = total % FPS;
const s = Math.floor(total / FPS);
const two = (n: number) => String(n).padStart(2, "0");
return `${two(Math.floor(s / 3600))}:${two(Math.floor(s / 60) % 60)}:${two(s % 60)}:${two(f)}`;
}
/** "1:24:35" — posição na gravação (régua da timeline). */
export function sessionClock(seconds: number): string {
const s = Math.max(0, Math.round(seconds));
const two = (n: number) => String(n).padStart(2, "0");
const h = Math.floor(s / 3600);
return h ? `${h}:${two(Math.floor(s / 60) % 60)}:${two(s % 60)}` : `${Math.floor(s / 60)}:${two(s % 60)}`;
}
/** Palavra com fim ≤ início (o Whisper às vezes devolve duração zero) ganha 50 ms: o serviço recusa o projeto. */
export function sanitizeProject(project: EditProject): EditProject {
if (!project.captions.words.some((w) => w.e - w.s < 0.02)) return project;
return { ...project, captions: { ...project.captions, words: project.captions.words.map((w) => (w.e - w.s < 0.02 ? { ...w, e: round3(w.s + 0.05) } : w)) } };
}
/* ---------- desfazer / refazer ---------- */
export type History<T> = {
present: T;
/** `key` junta mudanças seguidas do mesmo controle (arrastar um slider vira um passo só). */
set: (next: T | ((prev: T) => T), key?: string) => void;
reset: (value: T) => void;
undo: () => void;
redo: () => void;
canUndo: boolean;
canRedo: boolean;
};
const HISTORY_LIMIT = 150;
type HistoryState<T> = { past: T[]; present: T; future: T[]; /** Chave e hora da última mudança (para agrupar). */ key: string | null; at: number };
export function useHistory<T>(initial: T): History<T> {
const [state, setState] = useState<HistoryState<T>>({ past: [], present: initial, future: [], key: null, at: 0 });
// O updater do setState precisa ser PURO: o React em modo estrito (dev) roda ele duas vezes. Por isso a chave e a
// hora da última mudança moram no próprio estado (antes ficavam num ref mudado aqui dentro, e a 2ª execução
// "agrupava consigo mesma": nenhuma mudança com chave — slider, arraste, setas — entrava no desfazer).
const set = useCallback((next: T | ((prev: T) => T), key?: string) => {
const now = Date.now();
setState((s) => {
const value = typeof next === "function" ? (next as (prev: T) => T)(s.present) : next;
if (value === s.present) return s;
const coalesce = Boolean(key) && s.key === key && now - s.at < 900;
return {
past: coalesce ? s.past : [...s.past, s.present].slice(-HISTORY_LIMIT),
present: value,
future: [],
key: key ?? null,
at: now,
};
});
}, []);
const reset = useCallback((value: T) => setState({ past: [], present: value, future: [], key: null, at: 0 }), []);
// Depois de desfazer/refazer, a próxima mudança sempre abre uma entrada nova.
const undo = useCallback(() => setState((s) => s.past.length
? { past: s.past.slice(0, -1), present: s.past[s.past.length - 1], future: [s.present, ...s.future], key: null, at: 0 } : s), []);
const redo = useCallback(() => setState((s) => s.future.length
? { past: [...s.past, s.present], present: s.future[0], future: s.future.slice(1), key: null, at: 0 } : s), []);
return { present: state.present, set, reset, undo, redo, canUndo: state.past.length > 0, canRedo: state.future.length > 0 };
}
/** Atualiza uma cópia do projeto com mutações (evita espalhar spreads aninhados pelos componentes). */
export function produce(project: EditProject, mutate: (draft: EditProject) => void): EditProject {
const draft = structuredClone(project);
mutate(draft);
return draft;
}
/**
* Inserção nova a partir de um recorte da Fonte: no canto de cima à esquerda, por ~3 s. Começa 0,3 s ANTES do playhead
* para já aparecer inteira onde se está editando (no 1º quadro a animação de entrada ainda está em alfa 0).
*/
export function newInset(project: EditProject, playhead: number, src: Rect, id: string): InsetOverlay {
const start = round3(clamp(playhead - 0.3, project.source.lo, project.source.hi - 0.3));
return {
id, kind: "inset", start, end: round3(Math.min(project.source.hi, start + 3)), src, x: 0.27, y: 0.2, size: 0.42,
border: "#FFFFFF", borderW: 6, radius: 18, shadow: true, anim: "pop",
};
}
@@ -0,0 +1,690 @@
"use client";
// Monitor PROGRAMA do editor de cortes (o corte como vai sair, no formato dele: vertical 9:16 ou horizontal 16:9).
// PROGRAMA: o <video> é o proxy 480p da janela (tempo 0 = source.lo); um <canvas> no formato do corte desenha, a cada
// quadro, o layout (câmera em cima / câmera inteira / só o jogo / desfoque, por trecho; no horizontal, quadro inteiro
// ou câmera inteira), o zoom, a legenda no preset escolhido, o gancho (simples ou em TARJA animada), os textos, o chat
// da live, a barra de progresso e o crédito. É uma APROXIMAÇÃO do render do FFmpeg; a "Prévia real" renderiza no
// servidor. Para chegar perto, os textos seguem as contas do libass (editor_render.py):
// - posições e tamanhos no QUADRO LÓGICO (`frame.canvasWidth/Height`; no horizontal 2560×1440, ou seja, 75 %);
// - tamanho ASS → px da fonte pelas métricas do arquivo (`fontMetrics`): o libass encaixa win ascent+descent no tamanho;
// - quebra de linha pela mesma estimativa em caracteres do serviço (a tarja quebra igual ao render);
// - tarja: faixa na largura toda que atravessa a tela em 240 ms; texto entra de 90 a 430 ms deslizando com desfoque.
// Só desenha os textos depois que as fontes empacotadas carregaram (sem piscar com a fonte de reserva).
// As camadas se movem COM O MOUSE no próprio vídeo: clique seleciona (contorno azul), arrastar muda a posição —
// textos (x e y), tarja (só y: ela ocupa a largura toda), legenda (altura), chat (x e y); com um zoom selecionado,
// arrastar muda o foco dele.
// O monitor FONTE (quadro original com a câmera e a área do jogo editáveis) fica em clip-editor-source.tsx.
import { useEffect, useRef, type PointerEvent as ReactPointerEvent, type RefObject } from "react";
import type { CutSettings, Rect } from "./clipper-client";
import { canvasFont, fontMetrics } from "./clip-editor-fonts";
import {
BANNER_SLIDE_MS, CHAT_HOLD_S, INSET_ANIM_S, INSET_SHADOW_ALPHA, INSET_SLIDE_S, TEXT_SLIDE_MS, bannerLayout, camPanelHeight, captionY,
captionAt, captionBlocks, chatDefault, clamp, cutAt, easeAt, ffmpegCropFill, gameWindowAt, insetAt, insetHeight, outputDuration, outputWords, plainLines, produce, resolvedMode,
round3, setInsetPlace, toOutput, zoomAt, type ChatItem, type EditProject, type Frame, type InsetOverlay, type OutWord, type Selection, type TextOverlay,
} from "./clip-editor-model";
import { cx } from "./ui";
const SCALE = 0.5; // canvas interno = metade do vídeo (540×960 ou 960×540): leve; o CSS estica para a coluna
const CHAT_COLORS = ["#FF7A7A", "#7AD7FF", "#9BE77A", "#FFD36B", "#C9A2FF", "#FF9FD6"];
/** Fonte do estilo "Text"/"Box" do ASS (texto simples sem `font`). */
const TEXT_FONT = "Arial Black";
/** Fonte da tarja sem `font` (layout.HOOK_FONT do serviço). */
const BANNER_FONT = "Luckiest Guy";
/** Área clicável de uma camada no canvas (px do canvas). `key`: "caption", "chat" ou o id do texto. */
type Hit = { key: string; x: number; y: number; w: number; h: number };
type Box = { x: number; y: number; w: number; h: number } | null;
type Update = (fn: (p: EditProject) => EditProject, key?: string) => void;
export function EditorPreview({ videoRef, project, cfg, frame, fontsReady, lo, credit, timeRef, chat, selection, onSelect, onProject, className, style, sourceSize = null }: {
videoRef: RefObject<HTMLVideoElement | null>;
project: EditProject;
cfg: CutSettings;
/** Formato do corte (tamanho do vídeo e quadro lógico dos textos). */
frame: Frame;
/** Fontes empacotadas carregadas: antes disso só o vídeo é desenhado. */
fontsReady: boolean;
/** Início da janela (s da sessão) = tempo 0 do proxy. */
lo: number;
credit: string;
/** Instante atual (s da sessão) quando não há vídeo (proxy ainda gerando). */
timeRef: RefObject<number>;
chat: ChatItem[];
selection: Selection;
onSelect: (s: Selection) => void;
onProject: Update;
className?: string;
style?: React.CSSProperties;
/** Tamanho da gravação original (px): com ele, os recortes de câmera/jogo seguem o arredondamento do FFmpeg. */
sourceSize?: { w: number; h: number } | null;
}) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const compRef = useRef<HTMLCanvasElement | null>(null);
const hitsRef = useRef<Hit[]>([]);
const state = useRef({ project, cfg, frame, fontsReady, lo, credit, chat, selection, sourceSize });
state.current = { project, cfg, frame, fontsReady, lo, credit, chat, selection, sourceSize };
const drag = useRef<{ key: string; px: number; py: number; x0: number; y0: number; banner: boolean; resize?: boolean } | null>(null);
/** Instante (s da sessão) do último quadro desenhado: o arraste de uma inserção grava o keyframe nele. */
const nowRef = useRef(lo);
useEffect(() => {
let raf = 0;
const draw = () => {
raf = requestAnimationFrame(draw);
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext("2d");
if (!ctx) return;
const s = state.current;
const video = videoRef.current;
const ready = Boolean(video && video.readyState >= 2);
const t = ready && video ? s.lo + video.currentTime : timeRef.current ?? s.lo;
nowRef.current = t;
compRef.current ??= document.createElement("canvas");
hitsRef.current = renderFrame(ctx, compRef.current, ready ? video : null, s.project, s.cfg, s.frame, t, s.credit, s.chat,
selectedKey(s.selection, s.project), s.fontsReady, s.sourceSize);
};
raf = requestAnimationFrame(draw);
return () => cancelAnimationFrame(raf);
}, [videoRef, timeRef]);
/** Ponteiro → posição no quadro (0–1). */
const at = (e: ReactPointerEvent) => {
const r = e.currentTarget.getBoundingClientRect();
return { nx: clamp((e.clientX - r.left) / r.width, 0, 1), ny: clamp((e.clientY - r.top) / r.height, 0, 1) };
};
const hitAt = (nx: number, ny: number) => {
const { frame: f } = state.current;
const x = nx * f.width * SCALE, y = ny * f.height * SCALE;
const inside = (h: Hit) => x >= h.x - 6 && x <= h.x + h.w + 6 && y >= h.y - 6 && y <= h.y + h.h + 6;
// A camada selecionada ganha (dá para pegar a alça mesmo com um texto por cima); depois, o último desenhado.
const chosen = selectedKey(state.current.selection, state.current.project);
const sel = chosen ? hitsRef.current.find((h) => h.key === chosen && inside(h)) : undefined;
return sel ?? [...hitsRef.current].reverse().find(inside) ?? null;
};
function down(e: ReactPointerEvent<HTMLCanvasElement>) {
const { nx, ny } = at(e);
const { project: p, cfg: c, frame: f, selection: sel } = state.current;
const zoom = sel?.kind === "overlay" ? p.overlays.find((o) => o.id === sel.id && o.kind === "zoom") : undefined;
const hit = hitAt(nx, ny);
if (!hit && zoom) { // zoom selecionado: clicar/arrastar no vídeo põe o foco ali
e.currentTarget.setPointerCapture(e.pointerId);
drag.current = { key: `zoom:${zoom.id}`, px: nx, py: ny, x0: nx, y0: ny, banner: false };
setZoomFocus(zoom.id, nx, ny);
return;
}
if (!hit) return onSelect(null);
e.currentTarget.setPointerCapture(e.pointerId);
const inset = p.overlays.find((o): o is InsetOverlay => o.id === hit.key && o.kind === "inset");
if (inset) {
// Inserção: arrastar o corpo move; perto de um canto (com ela selecionada) muda o tamanho.
const place = insetAt(inset, nowRef.current);
const { x: hx, y: hy } = { x: nx * f.width * SCALE, y: ny * f.height * SCALE };
const nearCorner = sel?.kind === "overlay" && sel.id === inset.id
&& [[hit.x, hit.y], [hit.x + hit.w, hit.y], [hit.x, hit.y + hit.h], [hit.x + hit.w, hit.y + hit.h]].some(([cx0, cy0]) => Math.hypot(hx - cx0, hy - cy0) < 12);
onSelect({ kind: "overlay", id: inset.id });
drag.current = { key: inset.id, px: nx, py: ny, x0: place.x, y0: place.y, banner: false, resize: nearCorner };
return;
}
if (hit.key === "caption") {
onSelect({ kind: "layer", layer: "captions" });
drag.current = { key: hit.key, px: nx, py: ny, x0: 0.5, y0: captionY(c, resolvedMode(c), f) / f.canvasHeight, banner: false };
} else if (hit.key === "chat") {
const ch = p.chat ?? chatDefault(f.aspect);
onSelect({ kind: "layer", layer: "chat" });
drag.current = { key: hit.key, px: nx, py: ny, x0: ch.x, y0: ch.y, banner: false };
} else {
const o = p.overlays.find((x) => x.id === hit.key);
if (!o || o.kind === "zoom" || o.kind === "inset") return;
onSelect({ kind: "overlay", id: o.id });
drag.current = { key: hit.key, px: nx, py: ny, x0: o.x ?? 0.5, y0: o.y, banner: o.style === "banner" };
}
}
function setZoomFocus(id: string, nx: number, ny: number) {
onProject((p) => ({ ...p, overlays: p.overlays.map((o) => (o.id === id && o.kind === "zoom" ? { ...o, x: round3(nx), y: round3(ny) } : o)) }), `mon-zoom-${id}`);
}
function move(e: ReactPointerEvent<HTMLCanvasElement>) {
const { nx, ny } = at(e);
const d = drag.current;
if (!d) {
const h = hitAt(nx, ny);
const sel = state.current.selection;
const f = state.current.frame;
const corner = h && sel?.kind === "overlay" && sel.id === h.key && state.current.project.overlays.some((o) => o.id === h.key && o.kind === "inset")
&& [[h.x, h.y], [h.x + h.w, h.y], [h.x, h.y + h.h], [h.x + h.w, h.y + h.h]].some(([cx0, cy0]) => Math.hypot(nx * f.width * SCALE - cx0, ny * f.height * SCALE - cy0) < 12);
e.currentTarget.style.cursor = corner ? "nwse-resize" : h ? "move" : "default";
return;
}
const insetDrag = state.current.project.overlays.some((o) => o.id === d.key && o.kind === "inset");
if (insetDrag) {
// Com keyframes, grava no instante atual (auto-key); sem keys, mexe na própria camada.
const t = nowRef.current;
const patch = d.resize
? { size: clamp(2 * Math.abs(nx - d.x0), 0.1, 1) }
: { x: clamp(d.x0 + nx - d.px, 0, 1), y: clamp(d.y0 + ny - d.py, 0, 1) };
return onProject((p) => ({ ...p, overlays: p.overlays.map((o) => (o.id === d.key && o.kind === "inset" ? setInsetPlace(o, t, patch) : o)) }),
`mon-${d.key}-${d.resize ? "size" : "pos"}`);
}
const x = round3(clamp(d.x0 + nx - d.px, 0.05, 0.95)), y = d.y0 + ny - d.py;
if (d.key.startsWith("zoom:")) return setZoomFocus(d.key.slice(5), nx, ny);
if (d.key === "caption") {
return onProject((p) => produce(p, (draft) => { draft.captions.style = { ...draft.captions.style, y: round3(clamp(y, 0.08, 0.9)) }; }), "mon-caption");
}
if (d.key === "chat") {
const aspect = state.current.frame.aspect;
return onProject((p) => ({ ...p, chat: { ...(p.chat ?? chatDefault(aspect)), x: round3(clamp(d.x0 + nx - d.px, 0, 0.9)), y: round3(clamp(y, 0.1, 0.98)) } }), "mon-chat");
}
// Tarja: ocupa a largura toda, então só a altura muda (o `x` do projeto fica como estava).
onProject((p) => ({
...p, overlays: p.overlays.map((o) => (o.id === d.key && o.kind !== "zoom" ? { ...o, ...(d.banner ? {} : { x }), y: round3(clamp(y, 0.04, 0.96)) } : o)),
}), `mon-${d.key}`);
}
const vertical = frame.aspect === "vertical";
return (
<canvas ref={canvasRef} width={frame.width * SCALE} height={frame.height * SCALE} role="img" style={style}
aria-label={`Prévia do corte ${vertical ? "vertical (9:16)" : "horizontal (16:9)"}, aproximada. Arraste os textos, o gancho, a legenda e o chat para mover.`}
className={cx("touch-none", className)} onPointerDown={down} onPointerMove={move}
onPointerUp={() => { drag.current = null; }} onPointerCancel={() => { drag.current = null; }} />
);
}
function selectedKey(sel: Selection, project: EditProject): string | null {
// Inserção, gancho e textos: o id (zoom não tem contorno no vídeo).
if (sel?.kind === "overlay") return project.overlays.some((o) => o.id === sel.id && o.kind !== "zoom") ? sel.id : null;
if (sel?.kind === "layer" && sel.layer === "captions") return "caption";
if (sel?.kind === "layer" && sel.layer === "chat") return "chat";
return null;
}
function renderFrame(ctx: CanvasRenderingContext2D, comp: HTMLCanvasElement, video: HTMLVideoElement | null,
project: EditProject, cfg: CutSettings, frame: Frame, t: number, credit: string, chat: ChatItem[], selected: string | null,
fontsReady: boolean, sourceSize: { w: number; h: number } | null): Hit[] {
const cw = frame.width * SCALE, ch = frame.height * SCALE;
/** px do canvas por px do vídeo (layout) e por unidade do quadro lógico (textos). */
const kv = cw / frame.width;
const k = cw / frame.canvasWidth;
const hits: Hit[] = [];
const { t: tOut, inside } = toOutput(t, project.cuts);
const ci = cutAt(project.cuts, t);
const mode = resolvedMode(cfg, ci >= 0 ? project.cuts[ci].mode : null);
// 1) layout no canvas auxiliar
if (comp.width !== cw || comp.height !== ch) { comp.width = cw; comp.height = ch; }
const cx2 = comp.getContext("2d")!;
cx2.fillStyle = "#000";
cx2.fillRect(0, 0, cw, ch);
// Reenquadramento (keys): a janela do instante vira a área do jogo (a de baixo no câmera em cima; a tela toda nos
// outros modos, inclusive desfoque) e vale no lugar de `layout.game`. Não vale na câmera inteira.
const win = mode === "cam_only" ? null : gameWindowAt(project, cfg, frame, t);
if (video) {
const vw = video.videoWidth || 16, vh = video.videoHeight || 9;
// crop + _fill do serviço: com o tamanho da gravação, o mesmo arredondamento do FFmpeg (senão, conta exata).
const fill = (rect: Rect | null, dx: number, dy: number, dw: number, dh: number) => {
if (!sourceSize) return drawCover(cx2, video, vw, vh, rect, dx, dy, dw, dh);
const r = ffmpegCropFill(rect, sourceSize, Math.round(dw / kv), Math.round(dh / kv));
cx2.drawImage(video, r.x * vw, r.y * vh, r.w * vw, r.h * vh, dx, dy, dw, dh);
};
if (mode === "cam_top" && cfg.layout.cam) {
const top = camPanelHeight(cfg, frame) * kv;
fill(cfg.layout.cam, 0, 0, cw, top);
if (win) drawCover(cx2, video, vw, vh, win, 0, top, cw, ch - top); // janela do reenquadramento: subpixel (perspective)
else fill(cfg.layout.game, 0, top, cw, ch - top);
} else if (mode === "cam_only" && cfg.layout.cam) {
fill(cfg.layout.cam, 0, 0, cw, ch);
} else if (win) {
drawCover(cx2, video, vw, vh, win, 0, 0, cw, ch);
} else if (mode === "game_only") {
fill(cfg.layout.game, 0, 0, cw, ch);
} else if (mode === "full") {
// Horizontal: a área do jogo marcada preenche a tela; sem ela, o quadro inteiro cabe (faixas pretas se não for 16:9).
if (cfg.layout.game) fill(cfg.layout.game, 0, 0, cw, ch);
else {
const s = Math.min(cw / vw, ch / vh);
cx2.drawImage(video, 0, 0, vw, vh, (cw - vw * s) / 2, (ch - vh * s) / 2, vw * s, vh * s);
}
} else {
cx2.save();
cx2.filter = "blur(10px) brightness(0.9)";
drawCover(cx2, video, vw, vh, null, -20, -20, cw + 40, ch + 40);
cx2.restore();
const fh = (cw * vh) / vw;
cx2.drawImage(video, 0, 0, vw, vh, 0, (ch - fh) / 2 - 80 * kv, cw, fh);
}
}
// 2) zoom (punch-in) recortando o quadro composto
const { z, fx, fy } = zoomAt(project, tOut);
const sw = cw / z, sh = ch / z;
const sx = clamp(fx * cw - sw / 2, 0, cw - sw), sy = clamp(fy * ch - sh / 2, 0, ch - sh);
ctx.clearRect(0, 0, cw, ch);
ctx.drawImage(comp, sx, sy, sw, sh, 0, 0, cw, ch);
// 2b) camadas inseridas (acima do vídeo e do zoom, abaixo dos textos), na ordem do array = empilhamento
if (video) {
for (const o of project.overlays) {
if (o.kind !== "inset") continue;
const box = drawInset(ctx, video, o, project, frame, tOut, cw, ch);
if (box) hits.push({ key: o.id, ...box });
}
}
// 3) legenda, textos, chat, barra, crédito (só com as fontes prontas: nada de piscar com a fonte de reserva)
const total = outputDuration(project.cuts);
if (fontsReady) {
const cap = cfg.caption;
if (cap.enabled && inside) {
const box = drawCaption(ctx, project, cfg, tOut, captionY(cfg, mode, frame) * k, k, cw);
if (box) hits.push({ key: "caption", ...box });
}
for (const o of project.overlays) {
if (o.kind === "zoom" || o.kind === "inset") continue;
const a = o.kind === "hook" ? o.start : toOutput(o.start, project.cuts).t;
const b = o.kind === "hook" ? Math.min(o.end, total) : toOutput(o.end, project.cuts).t;
if (tOut < a || tOut >= b) continue;
const box = o.style === "banner"
? drawBanner(ctx, o, frame, k, (tOut - a) * 1000, (b - tOut) * 1000)
: drawOverlayText(ctx, o, frame, k, (tOut - a) * 1000, (b - tOut) * 1000);
if (box) hits.push({ key: o.id, ...box });
}
const chatCfg = project.chat ?? chatDefault(frame.aspect);
if (chatCfg.enabled && inside) {
const box = drawChat(ctx, chat, project, chatCfg, tOut, k, cw, ch, selected === "chat");
if (box) hits.push({ key: "chat", ...box });
}
}
if (project.progress.enabled && total > 0) {
ctx.fillStyle = project.progress.color;
const h = project.progress.height * k;
ctx.fillRect(0, ch - h, (cw * clamp(tOut, 0, total)) / total, h);
}
if (fontsReady && credit && cfg.credit.enabled) drawCredit(ctx, credit, cfg, mode, frame, k);
if (!inside) {
ctx.fillStyle = "rgb(0 0 0 / 0.55)";
ctx.fillRect(0, 0, cw, ch);
ctx.save();
ctx.font = `bold ${Math.round(23 * (cw / 540))}px Arial, sans-serif`;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "#d8d8de";
ctx.fillText("fora do corte", cw / 2, ch / 2);
ctx.restore();
}
// 4) contorno da camada selecionada (para arrastar)
const sel = selected ? hits.find((h) => h.key === selected) : null;
if (sel) {
ctx.save();
ctx.strokeStyle = "#5895ec";
ctx.lineWidth = 2;
ctx.setLineDash([6, 4]);
ctx.strokeRect(sel.x - 5, sel.y - 5, sel.w + 10, sel.h + 10);
ctx.setLineDash([]);
ctx.fillStyle = "#5895ec";
for (const [hx, hy] of [[sel.x - 5, sel.y - 5], [sel.x + sel.w + 5, sel.y - 5], [sel.x - 5, sel.y + sel.h + 5], [sel.x + sel.w + 5, sel.y + sel.h + 5]]) {
ctx.fillRect(hx - 3, hy - 3, 6, 6);
}
ctx.restore();
}
return hits;
}
/** Escala cobrindo o destino a partir do retângulo `rect` (0–1) do quadro original, recortando no centro. */
function drawCover(ctx: CanvasRenderingContext2D, video: HTMLVideoElement, vw: number, vh: number, rect: Rect | null,
dx: number, dy: number, dw: number, dh: number) {
const r = rect ?? { x: 0, y: 0, w: 1, h: 1 };
let sx = r.x * vw, sy = r.y * vh, sw = r.w * vw, sh = r.h * vh;
const target = dw / dh;
if (sw / sh > target) {
const nw = sh * target;
sx += (sw - nw) / 2;
sw = nw;
} else {
const nh = sw / target;
sy += (sh - nh) / 2;
sh = nh;
}
ctx.drawImage(video, sx, sy, sw, sh, dx, dy, dw, dh);
}
/**
* Camada inserida (reframe.inset_graph do serviço): recorte `src` do quadro original com cantos arredondados, borda e
* sombra borrada; tamanho e posição dos keys (tempo de SAÍDA); pop 82 % → 106 % → 100 % (0,28 s), alfa de 0,18 s na
* entrada e na saída e deslize pela direita (0,35 s). Borda e raio em px do quadro lógico; sombra = 3 % da largura.
*/
function drawInset(ctx: CanvasRenderingContext2D, video: HTMLVideoElement, o: InsetOverlay, project: EditProject, frame: Frame,
tOut: number, cw: number, ch: number): Box {
const out = (s: number) => toOutput(s, project.cuts).t;
const a = out(o.start), b = out(o.end);
if (b - a < 0.05 || tOut < a || tOut > b) return null;
const age = tOut - a;
const place = insetAt(o, tOut, out);
const kv = cw / frame.width; // px do canvas por px do vídeo
const kc = frame.width / frame.canvasWidth; // px do vídeo por px do quadro lógico
let scale = 1, alpha = 1, dx = 0;
if (o.anim === "pop") scale = age < 0.16 ? 0.82 + (0.24 * age) / 0.16 : age < 0.28 ? 1.06 - (0.06 * (age - 0.16)) / 0.12 : 1;
if (o.anim !== "none") alpha = clamp(Math.min(age / INSET_ANIM_S, (b - tOut) / INSET_ANIM_S), 0, 1);
if (o.anim === "slide") dx = frame.width * 0.7 * (1 - easeAt("smooth", age / INSET_SLIDE_S));
const w = place.size * frame.width * scale;
const h = insetHeight({ src: o.src, size: place.size }, frame) * frame.height * scale;
const x = place.x * frame.width + dx - w / 2, y = place.y * frame.height - h / 2;
const pad = o.border ? o.borderW * kc * scale : 0;
const radius = o.radius * kc * scale;
const vw = video.videoWidth || 16, vh = video.videoHeight || 9;
const top = Math.max(...[...(o.keys ?? []).map((k) => k.size), o.keys?.length ? 0 : o.size]);
ctx.save();
ctx.globalAlpha = alpha;
ctx.scale(kv, kv); // daqui para baixo, em px do vídeo
const outer = () => roundRect(ctx, x - pad, y - pad, w + 2 * pad, h + 2 * pad, radius ? radius + pad : 0);
if (o.shadow) {
const sp = Math.max(6, Math.round(0.03 * top * frame.width)) * scale;
ctx.save();
ctx.shadowColor = `rgb(0 0 0 / ${INSET_SHADOW_ALPHA})`;
ctx.shadowBlur = (sp / 2.5) * 2 * kv;
ctx.shadowOffsetX = ctx.shadowOffsetY = Math.max(1, Math.floor(sp / 2)) * kv;
ctx.fillStyle = o.border ?? "#000";
outer();
ctx.fill();
ctx.restore();
}
if (o.border && pad > 0) {
ctx.fillStyle = o.border;
outer();
ctx.fill();
}
ctx.save();
roundRect(ctx, x, y, w, h, radius);
ctx.clip();
ctx.drawImage(video, o.src.x * vw, o.src.y * vh, o.src.w * vw, o.src.h * vh, x, y, w, h);
ctx.restore();
ctx.restore();
return { x: (x - pad) * kv, y: (y - pad) * kv, w: (w + 2 * pad) * kv, h: (h + 2 * pad) * kv };
}
function roundRect(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number) {
ctx.beginPath();
ctx.roundRect(x, y, w, h, Math.max(0, Math.min(r, w / 2, h / 2)));
}
/* ---------- texto no jeito do libass ---------- */
type AssText = {
lines: string[];
/** Ponto de ancoragem em px do canvas; `align` horizontal; `valign` = o bloco centrado (an5), por cima (an7/8/9) ou por baixo (an1/2/3). */
x: number; y: number; align: CanvasTextAlign; valign: "middle" | "top" | "bottom";
/** Tamanho ASS (unidades do quadro lógico) e escala para px do canvas. */
size: number; k: number; font: string;
color: string; outline: string | null; bord: number; shadow: number; shadowColor?: string;
alpha?: number; blur?: number; scale?: number;
};
/**
* Desenha linhas como o libass: px da fonte = tamanho × `em` da fonte; linhas a cada (asc + desc) × tamanho; contorno
* `\bord` (por fora do glifo: traço de 2× centrado) e sombra `\shad` deslocada, com o contorno junto. Devolve a caixa.
*/
function drawAss(ctx: CanvasRenderingContext2D, t: AssText): Box {
if (!t.lines.length) return null;
const m = fontMetrics(t.font);
const s = t.size * t.k * (t.scale ?? 1);
const pitch = (m.asc + m.desc) * s;
const blockH = pitch * t.lines.length;
const top = t.valign === "middle" ? t.y - blockH / 2 : t.valign === "top" ? t.y : t.y - blockH;
ctx.save();
ctx.globalAlpha = clamp(t.alpha ?? 1, 0, 1);
ctx.font = canvasFont(t.font, m.em * s);
ctx.textAlign = t.align;
ctx.textBaseline = "alphabetic";
ctx.lineJoin = "round";
const bord = t.bord * t.k * (t.scale ?? 1);
const shad = t.shadow * t.k * (t.scale ?? 1);
let maxW = 0;
// Como no libass: com contorno, o lur desfoca só o contorno e a sombra; o preenchimento fica nítido.
const blur = t.blur && t.blur > 0.3 ? `blur(${t.blur.toFixed(2)}px)` : "none";
const each = (fn: (line: string, base: number) => void) => t.lines.forEach((line, i) => fn(line, top + m.asc * s + i * pitch));
t.lines.forEach((line) => { maxW = Math.max(maxW, ctx.measureText(line).width + bord * 2); });
ctx.filter = blur;
if (shad > 0) {
ctx.fillStyle = ctx.strokeStyle = t.shadowColor ?? "#000";
ctx.lineWidth = bord * 2;
each((line, base) => { if (bord > 0) ctx.strokeText(line, t.x + shad, base + shad); ctx.fillText(line, t.x + shad, base + shad); });
}
if (t.outline && bord > 0) {
ctx.lineWidth = bord * 2;
ctx.strokeStyle = t.outline;
each((line, base) => ctx.strokeText(line, t.x, base));
}
ctx.filter = t.outline && bord > 0 ? "none" : blur;
ctx.fillStyle = t.color;
each((line, base) => ctx.fillText(line, t.x, base));
ctx.restore();
const left = t.align === "center" ? t.x - maxW / 2 : t.align === "right" || t.align === "end" ? t.x - maxW : t.x;
return { x: left, y: top, w: maxW, h: blockH };
}
/** Entrada/saída dos estilos de animação do serviço (`editor_render._anim`), em ms desde o início e até o fim. */
function animState(anim: TextOverlay["anim"], ageMs: number, leftMs: number): { alpha: number; scale: number; blur: number } {
if (anim === "pop") {
const scale = ageMs < 140 ? 0.7 + (ageMs / 140) * 0.38 : ageMs < 220 ? 1.08 - ((ageMs - 140) / 80) * 0.08 : 1;
return { alpha: Math.min(ageMs / 80, leftMs / 120, 1), scale, blur: 0 };
}
if (anim === "fade") return { alpha: Math.min(ageMs / 250, leftMs / 250, 1), scale: 1, blur: 0 };
if (anim === "slide") return { alpha: Math.min(leftMs / 180, 1), scale: 1, blur: 14 * Math.max(0, 1 - ageMs / 320) };
return { alpha: 1, scale: 1, blur: 0 };
}
/** Interpolação do `\move(x1,y1,x2,y2,t1,t2)`: parado antes de t1, linear até t2. */
function moveAt(from: number, to: number, ageMs: number, t1: number, t2: number): number {
return from + (to - from) * clamp((ageMs - t1) / (t2 - t1), 0, 1);
}
/** Texto simples (gancho ou texto): estilo "Text" (contorno 6, sombra 2) ou "Box" (caixa opaca de 18 px na cor `box`). */
function drawOverlayText(ctx: CanvasRenderingContext2D, o: TextOverlay, frame: Frame, k: number, ageMs: number, leftMs: number): Box {
const lines = plainLines(o.text, o.size, frame.canvasWidth - 120);
const font = o.font ?? TEXT_FONT;
const a = animState(o.anim, ageMs, leftMs);
const x = (o.x ?? 0.5) * frame.canvasWidth;
const [t1, t2] = TEXT_SLIDE_MS;
const px = (o.anim === "slide" ? moveAt(x + frame.canvasWidth * 0.5, x, ageMs, t1, t2) : x) * k;
const py = o.y * frame.canvasHeight * k;
if (o.box) {
// BorderStyle 3: uma caixa por linha, 18 unidades além do texto, na cor `box`.
const m = fontMetrics(font);
const s = o.size * k * a.scale;
ctx.save();
ctx.globalAlpha = clamp(a.alpha, 0, 1);
ctx.font = canvasFont(font, m.em * s);
const pitch = (m.asc + m.desc) * s, pad = 18 * k * a.scale;
const top = py - (pitch * lines.length) / 2;
ctx.fillStyle = o.box;
lines.forEach((line, i) => {
const w = ctx.measureText(line).width;
ctx.fillRect(px - w / 2 - pad, top + i * pitch - pad, w + pad * 2, pitch + pad * 2);
});
ctx.restore();
}
return drawAss(ctx, {
lines, x: px, y: py, align: "center", valign: "middle", size: o.size, k, font, color: o.color,
outline: o.box ? null : "#000", bord: o.box ? 0 : 6, shadow: o.box ? 0 : 2, alpha: a.alpha, scale: a.scale, blur: a.blur * k,
});
}
/**
* Gancho em TARJA (editor_render.banner_events): faixa na largura toda na cor `bg`, texto em maiúsculas na fonte do
* gancho, contorno preto de 10 % do tamanho e sombra. `slide`: a faixa vem da esquerda em 240 ms e o texto entra pela
* direita, borrado (\blur18 → 0), de 90 a 430 ms; sai com fade de 180 ms. Outras animações valem para faixa e texto.
*/
function drawBanner(ctx: CanvasRenderingContext2D, o: TextOverlay, frame: Frame, k: number, ageMs: number, leftMs: number): Box {
const g = bannerLayout(o, frame);
const cw = frame.canvasWidth;
const slide = o.anim === "slide";
const out = Math.min(leftMs / 180, 1);
const a = slide ? { alpha: out, scale: 1, blur: 0 } : animState(o.anim, ageMs, leftMs);
// Faixa: \an7 em (0, topo); com pop, cresce a partir do canto (como o \t de escala do desenho no libass).
const bandX = slide ? moveAt(-cw, 0, ageMs, 0, BANNER_SLIDE_MS) : 0;
const bandScale = o.anim === "pop" ? (ageMs < 140 ? 1 + (ageMs / 140) * 0.08 : ageMs < 220 ? 1.08 - ((ageMs - 140) / 80) * 0.08 : 1) : 1;
ctx.save();
ctx.globalAlpha = clamp(a.alpha, 0, 1);
ctx.fillStyle = o.bg ?? "#00FF00";
ctx.fillRect(bandX * k, g.top * k, cw * k * bandScale, g.height * k * bandScale);
ctx.restore();
// Texto: centro da tela, na altura do meio da faixa.
const [t1, t2] = TEXT_SLIDE_MS;
const tx = slide ? moveAt(cw / 2 + cw * 0.55, cw / 2, ageMs, t1, t2) : cw / 2;
const blur = slide ? 18 * (1 - clamp((ageMs - t1) / (t2 - t1), 0, 1)) : 0;
const border = Math.max(3, Math.round(g.size * 0.1));
drawAss(ctx, {
lines: g.lines, x: tx * k, y: g.cy * k, align: "center", valign: "middle", size: g.size, k, font: o.font ?? BANNER_FONT,
color: o.color, outline: "#000", bord: border, shadow: Math.max(2, Math.floor(border / 2)),
alpha: slide ? out : a.alpha, scale: slide ? 1 : a.scale, blur: blur * k,
});
return { x: 0, y: g.top * k, w: cw * k, h: g.height * k };
}
/**
* Legenda no preset escolhido, com os MESMOS blocos do render (`captionBlocks`, porte de subtitles.py) e o mesmo
* comportamento de cada preset de `editor_render.build_project_ass`. `y` = centro em px do canvas. Estilo "Caption":
* negrito, contorno e sombra 3 (meio preto).
*/
function drawCaption(ctx: CanvasRenderingContext2D, project: EditProject, cfg: CutSettings, t: number, y: number, k: number, cw: number): Box {
const cap = cfg.caption;
const preset = project.captions.preset;
const now = captionAt(captionBlocks(outputWords(project), cap.maxWords), t);
const group = now?.block.words;
const m = fontMetrics(cap.font);
const size = cap.size * k;
const lineH = (m.asc + m.desc) * size;
// Sem fala neste instante: a área da legenda continua clicável (para arrastar a altura).
const empty = { x: cw * 0.2, y: y - lineH / 2, w: cw * 0.6, h: lineH };
if (!group) return empty;
const active = now.active;
const shown: OutWord[] = preset === "single" ? [group[active]] : group;
if (!shown.length) return empty;
ctx.save();
ctx.font = canvasFont(cap.font, m.em * size);
ctx.textBaseline = "alphabetic";
ctx.textAlign = "left";
ctx.lineJoin = "round";
const base = y - lineH / 2 + m.asc * size;
const text = (w: OutWord) => (cap.uppercase ? w.word.toUpperCase() : w.word);
const space = ctx.measureText(" ").width;
// Escala de cada palavra, como as tags do serviço: "pop" = a palavra ativa entra a 118 % e volta a 100 % em 130 ms;
// "single" = `_anim("pop")` na linha (70 % → 108 % em 140 ms → 100 % em 220 ms, com fade de 80 ms). O `intro`
// (85 %) que o serviço põe na 1ª palavra não aparece no render: as tags scx da própria linha sobrepõem a escala.
const scales = shown.map((w) => {
const age = t - w.start;
if (preset === "single") return age < 0.14 ? 0.7 + (0.38 * age) / 0.14 : age < 0.22 ? 1.08 - (0.08 * (age - 0.14)) / 0.08 : 1;
if (preset === "pop" && group.indexOf(w) === active) return age < 0.13 ? 1.18 - (age / 0.13) * 0.18 : 1;
return 1;
});
const alpha = preset === "single" ? clamp((t - shown[0].start) / 0.08, 0, 1) : 1;
// No libass a palavra maior EMPURRA as vizinhas (o avanço cresce com scx); os espaços ficam no tamanho normal.
const widths = shown.map((w, i) => ctx.measureText(text(w)).width * (preset === "single" ? 1 : scales[i]));
const totalW = widths.reduce((a, b) => a + b, 0) + space * (shown.length - 1);
const left = cw / 2 - totalW / 2;
const shad = 3 * k;
// A linha fica centrada em `y` pela altura da maior palavra (n5): a linha de base desce junto.
const big = preset === "single" ? 1 : Math.max(...scales);
const baseLine = y - (lineH * big) / 2 + m.asc * size * big;
ctx.globalAlpha = alpha;
let x = left;
shown.forEach((w, i) => {
const isActive = preset === "single" || group.indexOf(w) === active;
let color = cap.color;
if (preset === "karaoke") color = t >= w.start ? (w.emph ? project.captions.emphColor : cap.highlight) : cap.color; // \kf: enche ao falar
else if (w.emph) color = project.captions.emphColor;
else if (preset === "single") color = group.length > 1 ? cap.highlight : cap.color;
else if (isActive && preset !== "minimal") color = cap.highlight;
const sc = scales[i];
ctx.save();
if (preset === "single") { // a linha (uma palavra) cresce em torno do centro
ctx.translate(x + widths[i] / 2, y);
ctx.scale(sc, sc);
ctx.translate(-widths[i] / 2, base - y);
} else { // a palavra cresce a partir da linha de base, no lugar dela
ctx.translate(x, baseLine);
ctx.scale(sc, sc);
}
ctx.lineWidth = (cap.outlineWidth * k * 2) / sc; // o contorno não cresce com a escala (como no libass)
// Sombra (BackColour meio preto), com o contorno junto, como no libass.
ctx.fillStyle = ctx.strokeStyle = "rgb(0 0 0 / 0.5)";
if (cap.outlineWidth > 0) ctx.strokeText(text(w), shad / sc, shad / sc);
ctx.fillText(text(w), shad / sc, shad / sc);
ctx.strokeStyle = cap.outline;
if (cap.outlineWidth > 0) ctx.strokeText(text(w), 0, 0);
ctx.fillStyle = color;
ctx.fillText(text(w), 0, 0);
ctx.restore();
x += widths[i] + space;
});
ctx.restore();
return { x: left, y: y - lineH / 2, w: totalW, h: lineH };
}
/**
* Crédito do canal (estilo "Credit": Arial negrito, contorno 3, sombra 1), como `layout.credit_placement`: no vertical,
* centralizado (topo a 170, ou rodapé a 90; com a câmera em cima, desce para o pé dela); no horizontal, no canto direito.
*/
function drawCredit(ctx: CanvasRenderingContext2D, credit: string, cfg: CutSettings, mode: ReturnType<typeof resolvedMode>, frame: Frame, k: number) {
const size = cfg.credit.size;
const top = cfg.credit.position === "top";
let x = frame.canvasWidth / 2, y: number, valign: "top" | "bottom" = top ? "top" : "bottom", align: CanvasTextAlign = "center";
if (frame.aspect === "horizontal") {
x = frame.canvasWidth - 48;
align = "right";
y = top ? 36 : frame.canvasHeight - 36;
} else if (top && mode === "cam_top") {
y = Math.max(20, camPanelHeight(cfg, frame) - size - 34);
} else {
y = top ? 170 : frame.canvasHeight - 90;
}
if (!top) valign = "bottom";
drawAss(ctx, { lines: [credit], x: x * k, y: y * k, align, valign, size, k, font: "Arial", color: "#FFFFFF", outline: "#000", bord: 3, shadow: 1 });
}
/** Chat da live na tela: as últimas mensagens até o instante, de baixo para cima, com caixa escura por linha (estilo "Chat"). */
function drawChat(ctx: CanvasRenderingContext2D, chat: ChatItem[], project: EditProject, cfg: NonNullable<EditProject["chat"]>,
tOut: number, k: number, cw: number, ch: number, placeholder: boolean): Box {
const msgs: { t: number; user: string; text: string }[] = [];
for (const m of chat) {
const o = toOutput(m.t, project.cuts);
if (o.inside && m.text.trim()) msgs.push({ t: o.t, user: m.user, text: m.text.replace(/\s+/g, " ").trim() });
}
let last = -1;
for (let i = 0; i < msgs.length && msgs[i].t <= tOut; i++) last = i;
const m = fontMetrics("Arial");
const size = cfg.size * k;
const lh = (m.asc + m.desc) * size;
const pad = 5 * k;
const x0 = cfg.x * cw, yBase = cfg.y * ch, maxW = cfg.width * cw;
let shown = last >= 0 && tOut - msgs[last].t <= CHAT_HOLD_S
? msgs.slice(Math.max(0, last - cfg.lines + 1), last + 1).filter((x) => msgs[last].t - x.t <= CHAT_HOLD_S * 2) : [];
// Selecionado e sem mensagem neste instante: mostra um exemplo para dar o que arrastar.
if (!shown.length && placeholder) shown = [{ t: 0, user: "chat", text: "as mensagens da live aparecem aqui" }];
if (!shown.length) return null;
ctx.save();
ctx.font = `bold ${m.em * size}px Arial, sans-serif`;
ctx.textAlign = "left";
ctx.textBaseline = "alphabetic";
let widest = 0;
shown.forEach((msg, i) => {
const top = yBase - (shown.length - i) * lh;
const name = cfg.showUser && msg.user ? `${msg.user.slice(0, 16)}: ` : "";
let body = msg.text;
while (body.length > 1 && ctx.measureText(name + body).width > maxW) body = `${body.slice(0, -2).trimEnd()}…`;
const wd = ctx.measureText(name + body).width + pad * 2;
widest = Math.max(widest, wd);
ctx.fillStyle = "rgb(0 0 0 / 0.53)";
ctx.fillRect(x0 - pad, top - pad / 2, wd, lh + pad);
const base = top + m.asc * size;
if (name) {
ctx.fillStyle = CHAT_COLORS[[...msg.user].reduce((a, c) => a + c.charCodeAt(0), 0) % CHAT_COLORS.length];
ctx.fillText(name, x0, base);
}
ctx.fillStyle = "#fff";
ctx.fillText(body, x0 + ctx.measureText(name).width, base);
});
ctx.restore();
return { x: x0 - pad, y: yBase - shown.length * lh, w: widest, h: shown.length * lh };
}
+273
View File
@@ -0,0 +1,273 @@
"use client";
// Monitor FONTE do editor de cortes: o quadro original da gravação inteiro (antes do recorte vertical), com os
// retângulos da câmera do streamer e da área do jogo POR CIMA, editáveis direto com o mouse e o teclado — o mesmo
// jeito do editor da "Configuração do corte" (modal), com a mesma geometria (rect-geometry.ts):
// - arrastar o corpo move; as alças dos cantos e das bordas redimensionam;
// - arrastar numa área vazia desenha um retângulo novo para o alvo escolhido (Câmera ou Área do jogo);
// - com o retângulo focado, as setas movem 1% e Shift + setas mudam o tamanho; Esc conclui.
// Outros dois alvos usam o mesmo monitor:
// - "reframe": a JANELA DO JOGO do instante atual (reenquadramento), com a proporção travada na área de destino do
// layout: arrastar move, as alças mudam o zoom (em torno do centro), clicar numa área vazia leva o centro até ali;
// - "inset": o RECORTE de uma camada inserida (proporção livre); numa área vazia, desenha um recorte novo.
// O canvas só desenha o vídeo; os retângulos são elementos HTML (foco, teclado e cursor de verdade).
// Enquanto arrasta, `onDraft` manda o retângulo provisório (o Programa acompanha ao vivo); ao soltar, `onCommit`
// grava UMA vez — cada gesto vira uma entrada do desfazer.
import { useEffect, useRef, useState, type KeyboardEvent, type PointerEvent as ReactPointerEvent, type RefObject } from "react";
import type { Rect } from "./clipper-client";
import { isDrawnEnough, moveRect, nudgeRect, rectBetween, resizeRect, clampRect, type Point, type RectHandle } from "./rect-geometry";
import { cx } from "./ui";
export type SourceTarget = "cam" | "game" | "reframe" | "inset";
export type RectDraft = { which: SourceTarget; rect: Rect };
/** Proporção do quadro original da gravação (as lives chegam em 16:9; os retângulos são frações dele). */
const SOURCE_RATIO = 16 / 9;
const LOOK: Record<SourceTarget, { color: string; tag: string; name: string }> = {
cam: { color: "#f0c04f", tag: "câmera", name: "Câmera" },
game: { color: "#5bd0e6", tag: "jogo", name: "Área do jogo" },
reframe: { color: "#e070ff", tag: "enquadramento", name: "Janela do jogo" },
inset: { color: "#7cf08a", tag: "inserção", name: "Recorte da inserção" },
};
const HANDLES: RectHandle[] = ["nw", "n", "ne", "e", "se", "s", "sw", "w"];
const CURSOR: Record<RectHandle, string> = {
n: "ns-resize", s: "ns-resize", e: "ew-resize", w: "ew-resize", nw: "nwse-resize", se: "nwse-resize", ne: "nesw-resize", sw: "nesw-resize",
};
type Drag =
| { kind: "draw"; which: SourceTarget; origin: Point }
| { kind: "move"; which: SourceTarget; origin: Point; start: Rect }
| { kind: "resize"; which: SourceTarget; handle: RectHandle; start: Rect };
const pct = (v: number) => `${Math.round(v * 100)}%`;
const same = (a: Rect, b: Rect) => a.x === b.x && a.y === b.y && a.w === b.w && a.h === b.h;
export function SourceMonitor({ videoRef, cam, game, reframe = null, reframeRatio = 1, inset = null, target, onTarget, onDraft, onCommit, focusSignal, onDone, className }: {
videoRef: RefObject<HTMLVideoElement | null>;
/** Retângulos efetivos do corte (null = câmera não marcada / jogo = quadro inteiro). */
cam: Rect | null;
game: Rect | null;
/** Janela do jogo no instante atual (alvo "reframe") e a proporção dela em frações do quadro (largura/altura). */
reframe?: Rect | null;
reframeRatio?: number;
/** Recorte da inserção selecionada (alvo "inset"; null = desenhar um novo). */
inset?: Rect | null;
/** Qual retângulo um desenho novo cria (e qual mostra as alças). */
target: SourceTarget;
onTarget: (t: SourceTarget) => void;
/** Retângulo provisório durante o arraste (null ao terminar). */
onDraft: (d: RectDraft | null) => void;
/** Gesto terminado: grava o retângulo. `via` = "mouse" (um gesto) ou "key" (setas). */
onCommit: (which: SourceTarget, rect: Rect, via: "mouse" | "key") => void;
/** Muda de valor para pedir foco no retângulo do alvo (botão "Editar na fonte"). */
focusSignal: number;
/** Esc com o retângulo focado: termina a edição. */
onDone: () => void;
className?: string;
}) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const boxRef = useRef<HTMLDivElement>(null);
const drag = useRef<Drag | null>(null);
const [live, setLive] = useState<RectDraft | null>(null);
// Só o vídeo no canvas (os retângulos são HTML por cima).
useEffect(() => {
let raf = 0;
const draw = () => {
raf = requestAnimationFrame(draw);
const canvas = canvasRef.current;
const ctx = canvas?.getContext("2d");
if (!canvas || !ctx) return;
const video = videoRef.current;
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
if (video && video.readyState >= 2) ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
};
raf = requestAnimationFrame(draw);
return () => cancelAnimationFrame(raf);
}, [videoRef]);
// "Editar na fonte": foca o retângulo do alvo (o monitor pode ter acabado de aparecer).
useEffect(() => {
if (!focusSignal) return;
const raf = requestAnimationFrame(() => boxRef.current?.querySelector<HTMLElement>(`[data-rect="${target}"]`)?.focus({ preventScroll: true }));
return () => cancelAnimationFrame(raf);
// eslint-disable-next-line react-hooks/exhaustive-deps -- só quando pedem foco
}, [focusSignal]);
const point = (e: ReactPointerEvent): Point => {
const b = boxRef.current!.getBoundingClientRect();
return { x: Math.min(1, Math.max(0, (e.clientX - b.left) / b.width)), y: Math.min(1, Math.max(0, (e.clientY - b.top) / b.height)) };
};
function show(d: RectDraft | null) {
setLive(d);
onDraft(d && isDrawnEnough(d.rect) ? d : null);
}
function down(e: ReactPointerEvent<HTMLDivElement>) {
if (e.button !== 0) return;
const el = e.target as HTMLElement;
const rectEl = el.closest<HTMLElement>("[data-rect]");
const which = rectEl?.dataset.rect as SourceTarget | undefined;
const handle = el.dataset.handle as RectHandle | undefined;
const current = { cam, game, reframe, inset };
const p = point(e);
if (which && current[which]) {
drag.current = handle ? { kind: "resize", which, handle, start: current[which]! } : { kind: "move", which, origin: p, start: current[which]! };
onTarget(which);
rectEl?.focus({ preventScroll: true });
} else if (target === "reframe" && reframe) {
// Janela do jogo: clicar fora leva o centro até ali (e arrastar continua movendo).
const start = clampRect({ ...reframe, x: p.x - reframe.w / 2, y: p.y - reframe.h / 2 });
drag.current = { kind: "move", which: "reframe", origin: p, start };
show({ which: "reframe", rect: start });
} else {
drag.current = { kind: "draw", which: target, origin: p };
}
boxRef.current!.setPointerCapture(e.pointerId);
e.preventDefault();
}
function move(e: ReactPointerEvent<HTMLDivElement>) {
const d = drag.current;
if (!d) return;
const p = point(e);
show({ which: d.which, rect: dragRect(d, p) });
}
/** Retângulo do gesto: a janela do jogo muda de tamanho em torno do centro, sem perder a proporção. */
function dragRect(d: Drag, p: Point): Rect {
if (d.kind === "draw") return rectBetween(d.origin, p);
if (d.kind === "move") return moveRect(d.start, d.origin, p);
return d.which === "reframe" ? resizeLocked(d.start, p, reframeRatio) : resizeRect(d.start, d.handle, p);
}
function up(e: ReactPointerEvent<HTMLDivElement>) {
const d = drag.current;
drag.current = null;
if (boxRef.current?.hasPointerCapture(e.pointerId)) boxRef.current.releasePointerCapture(e.pointerId);
if (!d) return;
const p = point(e);
let rect: Rect | null;
if (d.kind === "draw") {
const drawn = rectBetween(d.origin, p);
rect = isDrawnEnough(drawn) ? clampRect(drawn) : null; // um clique sem arrastar não apaga o que existia
} else {
rect = dragRect(d, p);
// Clique sem mexer: nada a desfazer (a janela levada até o clique conta como mudança).
if (same(rect, d.start) && !(d.which === "reframe" && reframe && !same(rect, reframe))) rect = null;
}
if (rect) onCommit(d.which, rect, "mouse");
setLive(null);
onDraft(null);
if (d.kind === "draw" && rect) requestAnimationFrame(() => boxRef.current?.querySelector<HTMLElement>(`[data-rect="${d.which}"]`)?.focus({ preventScroll: true }));
}
function cancel() {
drag.current = null;
setLive(null);
onDraft(null);
}
function key(which: SourceTarget, r: Rect, e: KeyboardEvent<HTMLDivElement>) {
if (e.ctrlKey || e.metaKey || e.altKey) return; // Ctrl+Z etc. seguem para o editor
if (e.key === "Escape") { e.stopPropagation(); e.currentTarget.blur(); onDone(); return; }
// Delete/Backspace aqui não tira o trecho selecionado do corte por engano.
if (e.key === "Delete" || e.key === "Backspace") { e.preventDefault(); e.stopPropagation(); return; }
// Janela do jogo: Shift + ↑/→ aproxima, Shift + ↓/← afasta (em torno do centro, sem perder a proporção).
const next = which === "reframe" && e.shiftKey
? (["ArrowUp", "ArrowRight", "ArrowDown", "ArrowLeft"].includes(e.key)
? zoomLocked(r, e.key === "ArrowUp" || e.key === "ArrowRight" ? -0.02 : 0.02, reframeRatio) : null)
: nudgeRect(r, e.key, e.shiftKey);
if (!next) return;
e.preventDefault();
e.stopPropagation(); // as setas não andam o playhead enquanto o retângulo tem foco
onTarget(which);
if (!same(next, r)) onCommit(which, next, "key");
}
const shown = (which: SourceTarget) => (live?.which === which ? live.rect : { cam, game, reframe, inset }[which]);
// O alvo fica por cima (z) para as alças dele nunca ficarem atrás do outro retângulo. Enquadramento e recorte da
// inserção aparecem sozinhos (são de outro assunto que a câmera e o jogo).
const order: SourceTarget[] = target === "reframe" ? ["reframe"] : target === "inset" ? ["inset"] : target === "cam" ? ["game", "cam"] : ["cam", "game"];
return (
// Quadro 16:9 encaixado (object-contain) na área disponível, via unidades de container.
<div className={cx("relative min-h-0 w-full [container-type:size]", className)}>
<div ref={boxRef} onPointerDown={down} onPointerMove={move} onPointerUp={up} onPointerCancel={cancel}
aria-label={target === "reframe" ? "Quadro original da gravação. Arraste a janela do jogo para mover e as alças para o zoom; clique fora para levar o centro até ali."
: `Quadro original da gravação. Arraste numa área vazia para desenhar ${target === "cam" ? "a câmera" : target === "game" ? "a área do jogo" : "o recorte da inserção"}.`}
className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 cursor-crosshair touch-none bg-black select-none"
style={{ width: `min(100cqw, calc(100cqh * ${SOURCE_RATIO}))`, height: `min(100cqh, calc(100cqw / ${SOURCE_RATIO}))` }}>
<canvas ref={canvasRef} width={640} height={360} className="pointer-events-none absolute inset-0 size-full" />
{order.map((which) => {
const r = shown(which);
if (!r || r.w <= 0 || r.h <= 0) return null;
const look = LOOK[which];
const active = which === target;
const drawing = live?.which === which && !isDrawnEnough(live.rect);
return (
<div key={which} data-rect={which} tabIndex={0} role="group"
aria-label={`${look.name}: x ${pct(r.x)}, y ${pct(r.y)}, largura ${pct(r.w)}, altura ${pct(r.h)}. Arraste para mover, puxe as alças para redimensionar. Setas movem; Shift + setas mudam o tamanho; Esc conclui.`}
onKeyDown={(e) => key(which, r, e)}
className={cx("absolute cursor-move border-2 outline-offset-2 focus-visible:outline-2 focus-visible:outline-white",
active ? "z-10" : "opacity-60 hover:opacity-90", drawing && "border-dashed")}
style={{ left: `${r.x * 100}%`, top: `${r.y * 100}%`, width: `${r.w * 100}%`, height: `${r.h * 100}%`,
borderColor: look.color, background: `${look.color}1f` }}>
<span className={cx("pointer-events-none absolute left-[-2px] px-1 text-[10.5px] leading-[15px] font-semibold whitespace-nowrap text-black",
r.y > 0.05 ? "bottom-full" : "top-0")} style={{ background: look.color }}>
{look.tag}
</span>
{active && HANDLES.map((h) => {
const corner = h.length === 2;
return (
<span key={h} data-handle={h} aria-hidden="true" style={{ cursor: CURSOR[h] }}
className={cx("absolute grid place-items-center",
corner ? "size-3.5" : h === "n" || h === "s" ? "inset-x-3 h-3" : "inset-y-3 w-3",
h.includes("n") ? "-top-[7px]" : h.includes("s") ? "-bottom-[7px]" : "",
h.includes("w") ? "-left-[7px]" : h.includes("e") ? "-right-[7px]" : "")}>
{/* A parte visível da alça é menor que a área de pegar. */}
<span className={cx("pointer-events-none block rounded-[2px] border border-black/70",
corner ? "size-2.5" : h === "n" || h === "s" ? "h-1.5 w-4" : "h-4 w-1.5")} style={{ background: look.color }} />
</span>
);
})}
</div>
);
})}
</div>
</div>
);
}
/** Muda o tamanho da janela em torno do centro pela distância do ponteiro, mantendo `ratio` (largura/altura, frações). */
function resizeLocked(s: Rect, p: Point, ratio: number): Rect {
const cx = s.x + s.w / 2, cy = s.y + s.h / 2;
let w = Math.max(2 * Math.abs(p.x - cx), 2 * Math.abs(p.y - cy) * ratio);
w = Math.min(w, 1, ratio); // altura = w / ratio ≤ 1
w = Math.max(w, 0.05);
return clampRect({ x: cx - w / 2, y: cy - w / ratio / 2, w, h: w / ratio });
}
/** Zoom pelo teclado: muda a largura em `dw` em torno do centro, mantendo a proporção. */
function zoomLocked(s: Rect, dw: number, ratio: number): Rect {
return resizeLocked(s, { x: s.x + s.w / 2 + (s.w + dw) / 2, y: s.y + s.h / 2 }, ratio);
}
/** Alternância de qual retângulo está em edição (Câmera / Área do jogo): usada na Fonte e em Propriedades. */
export function SourceTargetToggle({ target, onTarget, className }: { target: SourceTarget; onTarget: (t: "cam" | "game") => void; className?: string }) {
return (
<div role="radiogroup" aria-label="Retângulo em edição" className={cx("flex shrink-0 rounded-[3px] border border-nle-line bg-nle-well p-px", className)}>
{(["cam", "game"] as const).map((t) => (
<button key={t} type="button" role="radio" aria-checked={target === t} onClick={() => onTarget(t)}
className={cx("flex h-[21px] cursor-pointer items-center gap-1.5 rounded-[2px] px-2 text-[11.5px] whitespace-nowrap focus-visible:outline-1 focus-visible:outline-nle-focus",
target === t ? "bg-nle-pressed text-white" : "text-nle-dim hover:text-nle-text")}>
<span aria-hidden="true" className="size-2 rounded-[1px]" style={{ background: LOOK[t].color }} />
{LOOK[t].name}
</button>
))}
</div>
);
}
@@ -0,0 +1,802 @@
"use client";
// Timeline do editor de cortes, no padrão dos editores de vídeo (referência de desenho: FilmCraft):
// - à esquerda, timecode azul, ferramentas (seleção, lâmina, ímã) e um cabeçalho por trilha;
// - régua com marcadores (pico do chat, início da ação, fim da reação, quadro da capa);
// - trilhas: C1 legenda · V3 textos · V2 zoom · CAM layout de cada trecho (câmera em cima, câmera inteira, só o
// jogo, desfoque; a POSIÇÃO da câmera vale para o corte inteiro e se edita no monitor Fonte) · V1 vídeo
// (miniaturas) | A1 áudio da live (forma de onda) · A2 narração · A3 música/efeitos · CH chat da live
// (mensagens por segundo e emotes; o olho do cabeçalho liga/desliga o chat na tela do corte).
// A timeline mostra a JANELA INTEIRA da gravação (tempo da sessão): o que está no corte aparece como clipe
// cheio; o que foi tirado fica apagado e hachurado, e volta com um clique ("Manter"). A lâmina divide um clipe
// em qualquer ponto; Delete tira o pedaço selecionado; as bordas do clipe arrastam para esticar ou encolher.
// Arrastar o corpo de um bloco move: palavra da legenda (ou o grupo selecionado), texto, zoom, narração e trecho
// de vídeo (que desliza sobre a gravação). As duas bordas de cada palavra aparam a legenda sem mexer no áudio.
// Ctrl+Shift+clique num clipe divide ali, sem trocar de ferramenta.
// ENQ = keyframes do reenquadramento do jogo (losangos: ◆ suave, ◇ linear, ■ segurar; arrastar muda o instante, duplo
// clique troca a curva) e INS = camadas inseridas (blocos como os textos, com os keyframes de posição/tamanho dentro).
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type PointerEvent as ReactPointerEvent, type ReactNode } from "react";
import type { ClipAnalysis, CutSettings } from "./clipper-client";
import {
RESOLVED_MODE_LABEL, cfgAspect, chatDefault, toggleChat, MIN_CUT_S, clamp, clockTenths, cutAt, outputDuration, resolvedMode, round3, sessionClock, splitAt, timecode, toOutput, toSession,
type ChatItem, type EditProject, type EditWord, type LayerKey, type Overlay, type Selection,
} from "./clip-editor-model";
import { KeyGlyph, moveKeyTime } from "./clip-editor-keyframes";
import { CursorIcon, EyeOffIcon, EyeOnIcon, FitIcon, IconBtn, MagnetIcon, RazorIcon, SpeakerIcon } from "./clip-editor-ui";
import { PlusIcon } from "./icons";
import { cx } from "./ui";
export type Tool = "select" | "razor";
/** Miniaturas da janela, tiradas do proxy no navegador: `frames[i]` é o quadro em `lo + (i + 0,5) · step`. */
export type Filmstrip = { lo: number; step: number; frames: HTMLCanvasElement[] };
const SNAP_PX = 8;
/** O arraste de mover só começa depois deste deslocamento: um clique simples nunca tira o bloco do lugar. */
const DRAG_START_PX = 4;
const MIN_WORD_S = 0.05;
const MAX_CANVAS_PX = 16000;
const HEADER_W = 176;
const TOP_H = 52;
const LABEL_H = 15;
const FIXED = { caption: 24, text: 26, inset: 26, zoom: 24, camera: 24, reframe: 22, divider: 3, narration: 26, music: 24, chat: 34 };
const EASE_NEXT = { smooth: "linear", linear: "hold", hold: "smooth" } as const;
/** Cor do bloco na trilha da câmera, por layout. */
const MODE_COLOR: Record<string, string> = { cam_top: "#7a5a16", cam_only: "#a8451f", game_only: "#1f5a7a", blur: "#4a4a4a", full: "#1f5a7a" };
const COLORS = {
video: "#1f4a66", videoLabel: "#2b6389", audio: "#1b4666", wave: "#86c5f7", caption: "#4a3a86", hook: "#96203f",
text: "#6f2f86", zoom: "#1b665d", narration: "#0f6475", music: "#3c6b1f", chat: "#8f7bd6",
};
type Drag =
| { kind: "cut-start" | "cut-end"; index: number }
| { kind: "ov-move"; id: string; grab: number; len: number }
| { kind: "ov-start" | "ov-end"; id: string }
| { kind: "word-move"; index: number; from: number; to: number; grab: number; base: { s: number; e: number }[] }
| { kind: "word-start" | "word-end"; index: number }
| { kind: "cut-move"; index: number; grab: number; start: number; end: number }
| { kind: "nar-move"; id: string; grab: number; at: number }
| { kind: "range"; anchor: number }
| { kind: "rf-key"; index: number }
| { kind: "in-key"; id: string; index: number }
| { kind: "seek" };
export function EditorTimeline({ project, cfg, lo, hi, playhead, words, peaks, peaksPerS, chatPerS, chat, analysis, peakS,
selection, tool, snapping, filmstrip, onTool, onSnapping, onSeek, onSelect, onProject, onAdd }: {
project: EditProject;
/** Configuração efetiva do corte (para saber o layout de cada trecho na trilha da câmera). */
cfg: CutSettings;
lo: number;
hi: number;
playhead: number;
words: EditWord[];
peaks: number[] | null;
peaksPerS: number;
chatPerS: number[];
chat: ChatItem[];
analysis: ClipAnalysis | null;
peakS: number;
selection: Selection;
tool: Tool;
snapping: boolean;
filmstrip: Filmstrip | null;
onTool: (t: Tool) => void;
onSnapping: (on: boolean) => void;
onSeek: (t: number) => void;
onSelect: (s: Selection) => void;
/** `key` junta os passos do arraste num só no desfazer. */
onProject: (fn: (p: EditProject) => EditProject, key?: string) => void;
/** Botão "+" do cabeçalho da trilha: novo texto, zoom, narração, keyframe do enquadramento ou inserção. */
onAdd: (what: "text" | "zoom" | "narration" | "reframe-key" | "inset") => void;
}) {
const span = Math.max(1, hi - lo);
const innerRef = useRef<HTMLDivElement>(null);
const scrollRef = useRef<HTMLDivElement>(null);
const headersRef = useRef<HTMLDivElement>(null);
const videoCanvas = useRef<HTMLCanvasElement>(null);
const audioCanvas = useRef<HTMLCanvasElement>(null);
const [drag, setDrag] = useState<Drag | null>(null);
const [view, setView] = useState({ w: 1200, h: 320 });
const [zoom, setZoom] = useState<number | null>(null); // px por segundo; null = ajustar à largura
const [razorT, setRazorT] = useState<number | null>(null);
const dragX0 = useRef(0);
const dragMoved = useRef(false);
const mutedVolume = useRef(1);
// Tamanho visível: define o "ajustar à largura" e a altura das trilhas de vídeo e áudio (as que crescem).
useLayoutEffect(() => {
const el = scrollRef.current;
if (!el) return;
const measure = () => setView({ w: el.clientWidth, h: el.clientHeight });
measure();
const ro = new ResizeObserver(measure);
ro.observe(el);
return () => ro.disconnect();
}, []);
const fitPx = Math.max(1.5, (view.w - 12) / span);
const maxPx = Math.max(fitPx, Math.min(160, MAX_CANVAS_PX / span));
const px = clamp(zoom ?? fitPx, fitPx, maxPx);
const width = Math.max(view.w, Math.ceil(span * px) + 12);
const fixedH = FIXED.caption + FIXED.text + FIXED.inset + FIXED.zoom + FIXED.camera + FIXED.reframe + FIXED.divider + FIXED.narration + FIXED.music + FIXED.chat;
const spare = view.h - TOP_H - fixedH;
const videoH = Math.round(clamp(spare * 0.56, 46, 132));
const audioH = Math.round(clamp(spare * 0.44, 38, 104));
const x = (t: number) => (t - lo) * px;
const timeAt = (clientX: number) => {
const rect = innerRef.current?.getBoundingClientRect();
return clamp(lo + (clientX - (rect?.left ?? 0)) / px, lo, hi);
};
const snapPoints = useMemo(() => {
const pts = [playhead, peakS];
for (const w of words) pts.push(w.s, w.e);
for (const c of project.cuts) pts.push(c.start, c.end);
return pts;
}, [words, playhead, peakS, project.cuts]);
const snap = (t: number) => {
if (!snapping) return round3(t);
let best = t, dist = SNAP_PX / px;
for (const p of snapPoints) if (Math.abs(p - t) < dist) { best = p; dist = Math.abs(p - t); }
return round3(best);
};
// Segue o playhead quando ele sai da área visível (tocando).
useEffect(() => {
const el = scrollRef.current;
if (!el || drag) return;
const at = x(playhead);
if (at < el.scrollLeft + 20 || at > el.scrollLeft + el.clientWidth - 40) el.scrollLeft = Math.max(0, at - el.clientWidth * 0.3);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [Math.floor(playhead * 2), px]);
// Ctrl + roda do mouse: zoom em torno do cursor.
useEffect(() => {
const el = scrollRef.current;
if (!el) return;
const onWheel = (e: WheelEvent) => {
if (!e.ctrlKey && !e.metaKey) return;
e.preventDefault();
const rect = el.getBoundingClientRect();
const cursor = e.clientX - rect.left;
const t = lo + (el.scrollLeft + cursor) / px;
const next = clamp(px * (e.deltaY < 0 ? 1.25 : 0.8), fitPx, maxPx);
setZoom(next <= fitPx * 1.01 ? null : next);
requestAnimationFrame(() => { el.scrollLeft = Math.max(0, (t - lo) * next - cursor); });
};
el.addEventListener("wheel", onWheel, { passive: false });
return () => el.removeEventListener("wheel", onWheel);
}, [px, fitPx, maxPx, lo]);
// V1: miniaturas — apagadas na janela inteira, cheias só dentro dos clipes (o que está no corte).
useEffect(() => {
const canvas = videoCanvas.current;
if (!canvas) return;
canvas.width = Math.ceil(span * px);
canvas.height = videoH;
const ctx = canvas.getContext("2d");
if (!ctx) return;
ctx.fillStyle = "#151515";
ctx.fillRect(0, 0, canvas.width, canvas.height);
const bodyH = videoH - LABEL_H;
const tileW = Math.max(24, Math.round((bodyH * 16) / 9));
const paint = (from: number, to: number, alpha: number) => {
if (!filmstrip?.frames.length) return;
ctx.save();
ctx.beginPath();
ctx.rect(from, LABEL_H, to - from, bodyH);
ctx.clip();
ctx.globalAlpha = alpha;
for (let tx = Math.floor(from / tileW) * tileW; tx < to; tx += tileW) {
const t = lo + (tx + tileW / 2) / px;
const i = Math.max(0, Math.floor((t - filmstrip.lo) / filmstrip.step));
if (i < filmstrip.frames.length) ctx.drawImage(filmstrip.frames[i], tx, LABEL_H, tileW, bodyH); // o resto ainda está carregando
}
ctx.restore();
};
paint(0, canvas.width, 0.22);
for (const c of project.cuts) {
const a = x(c.start), b = x(c.end);
ctx.fillStyle = COLORS.video;
ctx.fillRect(a, 0, b - a, videoH);
paint(a, b, 1);
ctx.fillStyle = COLORS.videoLabel;
ctx.fillRect(a, 0, b - a, LABEL_H);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [filmstrip, px, span, lo, videoH, project.cuts]);
// A1: forma de onda apoiada na base — azul dentro dos clipes, cinza no que foi tirado.
useEffect(() => {
const canvas = audioCanvas.current;
if (!canvas) return;
canvas.width = Math.ceil(span * px);
canvas.height = audioH;
const ctx = canvas.getContext("2d");
if (!ctx) return;
ctx.fillStyle = "#151515";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (const c of project.cuts) {
ctx.fillStyle = COLORS.audio;
ctx.fillRect(x(c.start), 0, x(c.end) - x(c.start), audioH);
}
if (!peaks?.length) return;
const step = peaksPerS / px; // picos por pixel
const room = audioH - 4;
for (let i = 0; i < canvas.width; i++) {
const from = Math.floor(i * step), to = Math.max(from + 1, Math.floor((i + 1) * step));
let peak = 0;
for (let j = from; j < to && j < peaks.length; j++) peak = Math.max(peak, peaks[j]);
const t = lo + i / px;
const ci = cutAt(project.cuts, t);
ctx.fillStyle = ci >= 0 && !project.cuts[ci].muted ? COLORS.wave : "rgb(120 120 126 / 0.45)";
const h = Math.max(1, peak * room);
ctx.fillRect(i, audioH - h, 1, h);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [peaks, peaksPerS, px, span, lo, audioH, project.cuts]);
function startDrag(e: ReactPointerEvent, d: Drag) {
e.stopPropagation();
e.preventDefault();
(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
dragX0.current = e.clientX;
dragMoved.current = false;
setDrag(d);
}
/** Solta o arraste. Clique sem arrastar numa palavra de um grupo selecionado fica só com ela. */
function endDrag() {
if (drag?.kind === "word-move" && !dragMoved.current && drag.to > drag.from) onSelect({ kind: "words", from: drag.index, to: drag.index });
setDrag(null);
}
const setWords = (fn: (ws: EditWord[]) => EditWord[], key: string) =>
onProject((p) => ({ ...p, captions: { ...p.captions, words: fn(p.captions.words) } }), key);
function onMove(e: ReactPointerEvent) {
const cutting = tool === "razor" || (e.ctrlKey && e.shiftKey);
if (cutting && !drag) setRazorT(snap(timeAt(e.clientX)));
else if (razorT !== null) setRazorT(null);
if (!drag) return;
const t = timeAt(e.clientX);
if (drag.kind === "word-move" || drag.kind === "cut-move" || drag.kind === "nar-move") {
if (!dragMoved.current && Math.abs(e.clientX - dragX0.current) < DRAG_START_PX) return;
dragMoved.current = true;
}
if (drag.kind === "word-move") {
const d = drag;
return setWords((ws) => {
if (d.to >= ws.length) return ws;
// O grupo anda inteiro, sem passar por cima da palavra de antes nem da de depois.
const min = (d.from > 0 ? ws[d.from - 1].e : lo) - d.base[0].s;
const max = (d.to + 1 < ws.length ? ws[d.to + 1].s : hi) - d.base[d.base.length - 1].e;
if (min > max) return ws;
const delta = clamp(t - d.grab, min, max);
return ws.map((w, i) => (i >= d.from && i <= d.to ? { ...w, s: round3(d.base[i - d.from].s + delta), e: round3(d.base[i - d.from].e + delta) } : w));
}, `word-move-${d.from}-${d.to}`);
}
if (drag.kind === "word-start" || drag.kind === "word-end") {
const d = drag;
return setWords((ws) => {
const w = ws[d.index];
if (!w) return ws;
const next = { ...w };
if (d.kind === "word-start") next.s = round3(clamp(t, Math.min(d.index > 0 ? ws[d.index - 1].e : lo, w.e - MIN_WORD_S), w.e - MIN_WORD_S));
else next.e = round3(clamp(t, w.s + MIN_WORD_S, Math.max(d.index + 1 < ws.length ? ws[d.index + 1].s : hi, w.s + MIN_WORD_S)));
return ws.map((v, i) => (i === d.index ? next : v));
}, `${d.kind}-${d.index}`);
}
if (drag.kind === "cut-move") {
const d = drag;
return onProject((p) => {
const cuts = p.cuts.map((c) => ({ ...c }));
const c = cuts[d.index];
if (!c) return p;
const len = d.end - d.start;
const min = d.index > 0 ? cuts[d.index - 1].end : lo;
const max = (d.index + 1 < cuts.length ? cuts[d.index + 1].start : hi) - len;
if (max < min) return p;
const start = round3(clamp(snap(d.start + (t - d.grab)), min, max));
c.start = start;
c.end = round3(start + len);
return { ...p, cuts };
}, `cut-move-${d.index}`);
}
if (drag.kind === "nar-move") {
const d = drag;
return onProject((p) => ({
...p, audio: { ...p.audio, narration: p.audio.narration.map((n) => (n.id === d.id ? { ...n, at: round3(clamp(snap(d.at + (t - d.grab)), lo, hi - 0.1)) } : n)) },
}), `nar-move-${d.id}`);
}
if (drag.kind === "seek") return onSeek(t);
if (drag.kind === "rf-key") {
const i = drag.index, st = snap(t);
onProject((p) => (p.reframe ? { ...p, reframe: { keys: moveKeyTime(p.reframe.keys, i, st, lo, hi) } } : p), `rf-key-${i}`);
return onSeek(st);
}
if (drag.kind === "in-key") {
const d = drag, st = snap(t);
onProject((p) => ({ ...p, overlays: p.overlays.map((o) => (o.id === d.id && o.kind === "inset" && o.keys
? { ...o, keys: moveKeyTime(o.keys, d.index, st, o.start, o.end) } : o)) }), `in-key-${d.id}-${d.index}`);
return onSeek(st);
}
if (drag.kind === "range") {
const a = Math.min(drag.anchor, t), b = Math.max(drag.anchor, t);
return onSelect(b - a > 0.05 ? { kind: "range", a: round3(a), b: round3(b) } : null);
}
if (drag.kind === "cut-start" || drag.kind === "cut-end") {
const i = drag.index;
const edge = drag.kind;
onProject((p) => {
const cuts = p.cuts.map((c) => ({ ...c }));
const c = cuts[i];
if (!c) return p;
const st = snap(t);
if (edge === "cut-start") c.start = clamp(st, i > 0 ? cuts[i - 1].end : lo, c.end - MIN_CUT_S);
else c.end = clamp(st, c.start + MIN_CUT_S, i + 1 < cuts.length ? cuts[i + 1].start : hi);
return { ...p, cuts };
}, `${edge}-${i}`);
return onSeek(t);
}
if (drag.kind !== "ov-move" && drag.kind !== "ov-start" && drag.kind !== "ov-end") return;
const d = drag; // aqui só sobram os arrastes de texto/zoom
onProject((p) => ({ ...p, overlays: p.overlays.map((o) => (o.id === d.id ? moveOverlay(o, d, t, p) : o)) }), `ov-${d.kind}-${d.id}`);
}
function moveOverlay(o: Overlay, d: Extract<Drag, { id: string }>, t: number, p: EditProject): Overlay {
// O gancho vive em tempo de SAÍDA; os outros em tempo da sessão.
const hook = o.kind === "hook";
const conv = (s: number) => (hook ? round3(toOutput(s, p.cuts).t) : round3(snap(s)));
const maxEnd = hook ? outputDuration(p.cuts) : hi;
const minStart = hook ? 0 : lo;
if (d.kind === "ov-move") {
const start = clamp(conv(t - d.grab), minStart, maxEnd - d.len);
return { ...o, start: round3(start), end: round3(start + d.len) };
}
if (d.kind === "ov-start") return { ...o, start: clamp(conv(t), minStart, o.end - 0.2) };
return { ...o, end: clamp(conv(t), o.start + 0.2, maxEnd) };
}
/** Clique numa trilha de mídia (V1/A1): lâmina divide; seleção escolhe o clipe ou o trecho tirado. */
function mediaDown(e: ReactPointerEvent) {
const raw = timeAt(e.clientX);
const i = cutAt(project.cuts, raw);
if (tool === "razor" || (e.ctrlKey && e.shiftKey)) {
if (i < 0) return;
const t = snap(raw);
const next = splitAt(project.cuts, t);
if (next === project.cuts) return;
onProject((p) => ({ ...p, cuts: splitAt(p.cuts, t) }));
onSelect({ kind: "cut", index: cutAt(next, t + 0.01) });
return;
}
onSeek(raw);
if (i >= 0) {
onSelect({ kind: "cut", index: i });
// Segurar e arrastar o corpo do clipe desliza o trecho sobre a gravação (mesma duração, outro pedaço).
return startDrag(e, { kind: "cut-move", index: i, grab: raw, start: project.cuts[i].start, end: project.cuts[i].end });
}
const gap = gaps(project.cuts, lo, hi).find(([a, b]) => raw >= a && raw <= b);
onSelect(gap ? { kind: "range", a: gap[0], b: gap[1] } : null);
}
const removed = gaps(project.cuts, lo, hi);
const maxChat = Math.max(1, ...chatPerS);
const overlayRange = (o: Overlay) => o.kind === "hook"
? { a: toSession(o.start, project.cuts), b: toSession(Math.min(o.end, outputDuration(project.cuts)), project.cuts) }
: { a: o.start, b: o.end };
const sel = selection;
const layerSel = sel?.kind === "layer" ? sel.layer : null;
const out = toOutput(playhead, project.cuts);
const texts = project.overlays.filter((o) => o.kind === "hook" || o.kind === "text");
const zooms = project.overlays.filter((o) => o.kind === "zoom");
const insets = project.overlays.filter((o) => o.kind === "inset");
const rfKeys = project.reframe?.keys ?? [];
const showWords = px > 26;
const chatOn = (project.chat ?? chatDefault(cfgAspect(cfg))).enabled;
const clipFrames = (lane: "v" | "a", h: number) => project.cuts.map((c, i) => {
const selected = sel?.kind === "cut" && sel.index === i;
return (
<div key={`${lane}${i}`}
className={cx("absolute inset-y-0 overflow-hidden border-x border-black/70", tool === "select" && "cursor-grab", selected && "z-10 outline-[1.5px] -outline-offset-[1.5px] outline-[#ebebeb]")}
style={{ left: x(c.start), width: Math.max(2, (c.end - c.start) * px), height: h }}>
{lane === "v" && (
<span className="pointer-events-none absolute inset-x-1.5 top-0 truncate text-[10.5px] leading-[15px] text-white/90">
Trecho {i + 1} · {clockTenths(toOutput(c.start, project.cuts).t)}
</span>
)}
{lane === "a" && c.muted && (
<span className="pointer-events-none absolute inset-0 grid place-items-center bg-black/55 text-[10.5px] font-semibold tracking-wide text-[#f08a7a]">MUDO</span>
)}
<Handle side="left" onPointerDown={(e) => startDrag(e, { kind: "cut-start", index: i })} label={`Início do trecho ${i + 1}`} />
<Handle side="right" onPointerDown={(e) => startDrag(e, { kind: "cut-end", index: i })} label={`Fim do trecho ${i + 1}`} />
</div>
);
});
const gapMarks = removed.map(([a, b]) => (
<div key={`g${a}`} title="Fora do corte — clique para selecionar e “Manter”"
className="pointer-events-none absolute inset-y-0 bg-[repeating-linear-gradient(135deg,rgb(255_255_255/0.07)_0_5px,transparent_5px_10px)]"
style={{ left: x(a), width: (b - a) * px }} />
));
return (
<div className="flex h-full min-h-0 flex-col bg-nle-panel select-none">
<div className="flex min-h-0 flex-1">
{/* Coluna da esquerda: timecode, ferramentas e cabeçalhos das trilhas */}
<div className="flex shrink-0 flex-col border-r border-nle-line" style={{ width: HEADER_W }}>
<div className="shrink-0 border-b border-nle-line px-2.5 pt-1.5" style={{ height: TOP_H }}>
<p className="font-mono text-[15px] leading-none text-nle-hot tabular-nums" title="Posição no corte final (hh:mm:ss:quadros)">
{timecode(out.t)}
</p>
<div className="mt-1.5 flex items-center gap-0.5">
<IconBtn label="Seleção" kbd="V" active={tool === "select"} onClick={() => onTool("select")}><CursorIcon size={14} /></IconBtn>
<IconBtn label="Lâmina: clique num clipe para dividir" kbd="C" active={tool === "razor"} onClick={() => onTool("razor")}><RazorIcon size={15} /></IconBtn>
<span className="mx-1 h-4 w-px bg-nle-line" />
<IconBtn label="Ímã: gruda nas palavras, bordas e playhead" kbd="N" active={snapping} onClick={() => onSnapping(!snapping)}><MagnetIcon size={14} /></IconBtn>
<IconBtn label="Ajustar a janela inteira à largura" onClick={() => setZoom(null)}><FitIcon size={14} /></IconBtn>
</div>
</div>
<div ref={headersRef} className="min-h-0 flex-1 overflow-hidden">
<TrackHeader id="C1" tone="#6b4fb3" name="Legenda" h={FIXED.caption} selected={layerSel === "captions"} onSelect={() => onSelect({ kind: "layer", layer: "captions" })}>
<IconBtn label={project.captions.enabled ? "Esconder a legenda" : "Mostrar a legenda"} className="size-5"
onClick={() => onProject((p) => ({ ...p, captions: { ...p.captions, enabled: !p.captions.enabled } }))}>
{project.captions.enabled ? <EyeOnIcon size={13} /> : <EyeOffIcon size={13} className="text-nle-faint" />}
</IconBtn>
</TrackHeader>
<TrackHeader id="V3" name="Textos" h={FIXED.text} selected={layerSel === "texts"} onSelect={() => onSelect({ kind: "layer", layer: "texts" })}>
<IconBtn label="Novo texto no playhead" className="size-5" onClick={() => onAdd("text")}><PlusIcon size={13} /></IconBtn>
</TrackHeader>
<TrackHeader id="INS" tone="#2f7a3d" name="Inserções" h={FIXED.inset} selected={layerSel === "insets"} onSelect={() => onSelect({ kind: "layer", layer: "insets" })}>
<IconBtn label="Nova inserção: desenhe o recorte na Fonte" className="size-5" onClick={() => onAdd("inset")}><PlusIcon size={13} /></IconBtn>
</TrackHeader>
<TrackHeader id="V2" name="Zoom" h={FIXED.zoom} selected={layerSel === "zooms"} onSelect={() => onSelect({ kind: "layer", layer: "zooms" })}>
<IconBtn label="Novo zoom no playhead" className="size-5" onClick={() => onAdd("zoom")}><PlusIcon size={13} /></IconBtn>
</TrackHeader>
<TrackHeader id="CAM" tone="#7a5a16" name="Câmera" h={FIXED.camera} selected={layerSel === "camera"} onSelect={() => onSelect({ kind: "layer", layer: "camera" })} />
<TrackHeader id="ENQ" tone="#7a3b8f" name="Enquadramento" h={FIXED.reframe} selected={layerSel === "reframe" || sel?.kind === "reframe"}
onSelect={() => onSelect({ kind: "layer", layer: "reframe" })}>
<IconBtn label="Adicionar keyframe do enquadramento no playhead" className="size-5" onClick={() => onAdd("reframe-key")}><KeyGlyph ease="smooth" size={10} /></IconBtn>
</TrackHeader>
<TrackHeader id="V1" name="Vídeo" h={videoH} selected={layerSel === "video"} onSelect={() => onSelect({ kind: "layer", layer: "video" })}
note={`${project.cuts.length} trecho${project.cuts.length > 1 ? "s" : ""}`} />
<div className="bg-nle-app" style={{ height: FIXED.divider }} />
<TrackHeader id="A1" name="Áudio da live" h={audioH} selected={layerSel === "audio"} onSelect={() => onSelect({ kind: "layer", layer: "audio" })}
note={`${Math.round(project.audio.volume * 100)}%`}>
<IconBtn label={project.audio.volume > 0 ? "Silenciar a live" : "Voltar o som da live"} className="size-5" active={project.audio.volume === 0}
onClick={() => onProject((p) => {
if (p.audio.volume > 0) mutedVolume.current = p.audio.volume;
return { ...p, audio: { ...p.audio, volume: p.audio.volume > 0 ? 0 : mutedVolume.current || 1 } };
})}>
<SpeakerIcon size={13} className={project.audio.volume === 0 ? "text-nle-danger" : undefined} />
</IconBtn>
</TrackHeader>
<TrackHeader id="A2" name="Narração" h={FIXED.narration} selected={layerSel === "narration"} onSelect={() => onSelect({ kind: "layer", layer: "narration" })}>
<IconBtn label="Nova narração no playhead" className="size-5" onClick={() => onAdd("narration")}><PlusIcon size={13} /></IconBtn>
</TrackHeader>
<TrackHeader id="A3" name="Música e efeitos" h={FIXED.music} selected={layerSel === "music"} onSelect={() => onSelect({ kind: "layer", layer: "music" })} />
<TrackHeader id="CH" tone="#3a3a3a" name="Chat da live" h={FIXED.chat} note={chatOn ? "na tela" : "mensagens/s"} selected={layerSel === "chat"}
onSelect={() => onSelect({ kind: "layer", layer: "chat" })}>
<IconBtn label={chatOn ? "Tirar o chat da tela" : "Mostrar o chat na tela"} className="size-5"
onClick={() => onProject((p) => toggleChat(p, cfgAspect(cfg)))}>
{chatOn ? <EyeOnIcon size={13} /> : <EyeOffIcon size={13} className="text-nle-faint" />}
</IconBtn>
</TrackHeader>
</div>
</div>
{/* Régua + trilhas (rolam juntas na horizontal) */}
<div ref={scrollRef} className={cx("relative min-w-0 flex-1 overflow-x-auto overflow-y-auto", tool === "razor" && "cursor-crosshair")}
onScroll={(e) => { if (headersRef.current) headersRef.current.scrollTop = e.currentTarget.scrollTop; }}>
<div ref={innerRef} className="relative" style={{ width }}
onPointerMove={onMove} onPointerUp={endDrag} onPointerCancel={() => setDrag(null)} onPointerLeave={() => setRazorT(null)}>
{/* Régua: clique = ir; arrastar = percorrer; Shift + arrastar = selecionar um trecho */}
<div className="sticky top-0 z-30 cursor-pointer border-b border-nle-line bg-nle-panel" style={{ height: TOP_H }}
onPointerDown={(e) => {
const t = timeAt(e.clientX);
if (e.shiftKey) startDrag(e, { kind: "range", anchor: t });
else { onSeek(t); startDrag(e, { kind: "seek" }); }
}}>
{ticks(lo, hi, px).map(({ t, major }) => (
<span key={t} className={cx("absolute bottom-0 border-l", major ? "h-[18px] border-[#8d8d8d]" : "h-[7px] border-[#5a5a5a]")} style={{ left: x(t) }}>
{major && <span className="absolute bottom-[15px] left-1 font-mono text-[10.5px] whitespace-nowrap text-nle-dim">{sessionClock(t)}</span>}
</span>
))}
{/* Faixa amarela = o que entra no corte (como a barra de área de trabalho) */}
{project.cuts.map((c, i) => <span key={i} className="absolute bottom-0 h-[2px] bg-[#f0e04f]" style={{ left: x(c.start), width: (c.end - c.start) * px }} />)}
<RulerMarker x={x(peakS)} color="#e34850" label={`Pico do chat · ${sessionClock(peakS)}`} onClick={() => onSeek(peakS)} />
{analysis && <RulerMarker x={x(analysis.action_start_s)} color="#2d9d78" label={`Início da ação (IA) · ${sessionClock(analysis.action_start_s)}`} onClick={() => onSeek(analysis.action_start_s)} />}
{analysis && <RulerMarker x={x(analysis.reaction_end_s)} color="#5895ec" label={`Fim da reação (IA) · ${sessionClock(analysis.reaction_end_s)}`} onClick={() => onSeek(analysis.reaction_end_s)} />}
{project.cover.enabled && <RulerMarker x={x(project.cover.t)} color="#e8a23a" label={`Quadro da capa · ${sessionClock(project.cover.t)}`} onClick={() => onSeek(project.cover.t)} />}
<span className="pointer-events-none absolute bottom-0 z-10 -translate-x-1/2" style={{ left: x(playhead) }}>
<svg width="13" height="20" viewBox="0 0 13 20" aria-hidden="true"><path d="M1 0h11v12l-5.5 7L1 12V0Z" fill="#5895ec" /></svg>
</span>
</div>
{/* C1 — legenda: uma pílula por palavra */}
<Lane h={FIXED.caption} tint="#23202a">
{words.map((w, i) => {
const kept = cutAt(project.cuts, (w.s + w.e) / 2) >= 0;
const selected = sel?.kind === "words" && i >= sel.from && i <= sel.to;
const wpx = Math.max(2, (w.e - w.s) * px - 1);
// Palavra de um grupo selecionado arrasta o grupo; fora dele, só ela.
const group = selected && sel?.kind === "words" ? sel : { from: i, to: i };
return (
<div key={`w${i}`} role="button" aria-label={`Palavra “${w.w}” da legenda`} title={`${w.w} — arraste para mover; as bordas aparam`}
onPointerDown={(e) => {
onSeek(w.s);
if (!selected) onSelect({ kind: "words", from: i, to: i });
startDrag(e, { kind: "word-move", index: i, from: group.from, to: group.to, grab: timeAt(e.clientX),
base: words.slice(group.from, group.to + 1).map((v) => ({ s: v.s, e: v.e })) });
}}
className={cx("group/word absolute top-[3px] h-[18px] cursor-grab overflow-hidden rounded-[2px] px-1 text-left text-[10px] leading-[18px] text-[#e3dcff]",
selected && "z-10 outline-[1.5px] outline-[#ebebeb]", (!kept || w.hidden || !project.captions.enabled) && "opacity-30")}
style={{ left: x(w.s), width: wpx, background: w.emph ? "#2d7d4f" : COLORS.caption }}>
{showWords ? w.w : ""}
{wpx >= 12 && (
<>
<Handle side="left" small quiet={!selected} label={`Início de “${w.w}”`}
onPointerDown={(e) => { onSelect({ kind: "words", from: i, to: i }); startDrag(e, { kind: "word-start", index: i }); }} />
<Handle side="right" small quiet={!selected} label={`Fim de “${w.w}”`}
onPointerDown={(e) => { onSelect({ kind: "words", from: i, to: i }); startDrag(e, { kind: "word-end", index: i }); }} />
</>
)}
</div>
);
})}
</Lane>
{/* V3 — gancho e textos */}
<Lane h={FIXED.text}>
{texts.map((o) => <OverlayClip key={o.id} o={o} range={overlayRange(o)} x={x} px={px} selected={sel?.kind === "overlay" && sel.id === o.id}
color={o.kind === "hook" ? COLORS.hook : COLORS.text} label={o.kind === "hook" ? `Gancho · ${o.text}` : o.kind === "text" ? o.text : ""}
onDown={(e, a) => { onSelect({ kind: "overlay", id: o.id }); const t = timeAt(e.clientX); startDrag(e, { kind: "ov-move", id: o.id, grab: o.kind === "hook" ? t - a : t - o.start, len: o.end - o.start }); }}
onEdge={(e, side) => startDrag(e, { kind: side === "left" ? "ov-start" : "ov-end", id: o.id })} />)}
{project.cover.enabled && project.cover.atStart && (
<button type="button" tabIndex={-1} title="Capa nos 2 primeiros quadros do vídeo"
onPointerDown={(e) => { e.stopPropagation(); onSelect({ kind: "layer", layer: "cover" }); }}
className="absolute top-[3px] bottom-[3px] cursor-pointer rounded-[2px] bg-[#e8a23a] px-1 text-[10px] font-semibold text-black"
style={{ left: x(project.cuts[0].start) }}>CAPA</button>
)}
</Lane>
{/* INS — camadas inseridas (recortes em destaque) e os keyframes de cada uma */}
<Lane h={FIXED.inset}>
{insets.map((o, n) => {
const selected = sel?.kind === "overlay" && sel.id === o.id;
return (
<div key={o.id}>
<OverlayClip o={o} range={overlayRange(o)} x={x} px={px} selected={selected && sel?.kind === "overlay" && sel.key === undefined}
color="#2f7a3d" label={`Inserção ${n + 1}${o.keys?.length ? ` · ${o.keys.length} keyframe(s)` : ""}`}
onDown={(e) => { onSelect({ kind: "overlay", id: o.id }); const t = timeAt(e.clientX); startDrag(e, { kind: "ov-move", id: o.id, grab: t - o.start, len: o.end - o.start }); }}
onEdge={(e, side) => startDrag(e, { kind: side === "left" ? "ov-start" : "ov-end", id: o.id })} />
{(o.keys ?? []).map((k, i) => (
<KeyDiamond key={`${o.id}-${i}`} x={x(k.t)} ease={k.ease ?? "smooth"} color="#9bf0a8" small
selected={sel?.kind === "overlay" && sel.id === o.id && sel.key === i}
label={`Keyframe ${i + 1} da inserção ${n + 1} em ${sessionClock(k.t)}`}
onDown={(e) => { onSelect({ kind: "overlay", id: o.id, key: i }); onSeek(k.t); startDrag(e, { kind: "in-key", id: o.id, index: i }); }}
onCycle={() => onProject((p) => ({ ...p, overlays: p.overlays.map((v) => (v.id === o.id && v.kind === "inset" && v.keys
? { ...v, keys: v.keys.map((kk, j) => (j === i ? { ...kk, ease: EASE_NEXT[kk.ease ?? "smooth"] } : kk)) } : v)) }))} />
))}
</div>
);
})}
</Lane>
{/* V2 — zoom */}
<Lane h={FIXED.zoom}>
{zooms.map((o) => <OverlayClip key={o.id} o={o} range={overlayRange(o)} x={x} px={px} selected={sel?.kind === "overlay" && sel.id === o.id}
color={COLORS.zoom} label={o.kind === "zoom" ? `Zoom ${o.scale.toFixed(2).replace(".", ",")}×` : ""}
onDown={(e) => { onSelect({ kind: "overlay", id: o.id }); const t = timeAt(e.clientX); startDrag(e, { kind: "ov-move", id: o.id, grab: t - o.start, len: o.end - o.start }); }}
onEdge={(e, side) => startDrag(e, { kind: side === "left" ? "ov-start" : "ov-end", id: o.id })} />)}
</Lane>
{/* CAM — câmera/layout de cada trecho (câmera em cima, câmera inteira, só o jogo, desfoque) */}
<Lane h={FIXED.camera}>
{project.cuts.map((c, i) => {
const mode = resolvedMode(cfg, c.mode);
return (
<button key={`cam${i}-${c.start}`} type="button" tabIndex={-1} title={`Trecho ${i + 1}: ${RESOLVED_MODE_LABEL[mode].label}${c.mode ? "" : " (o do corte)"}`}
onPointerDown={(e) => { e.stopPropagation(); onSelect({ kind: "cut", index: i }); }}
className={cx("absolute top-[3px] bottom-[3px] cursor-pointer truncate rounded-[2px] px-1.5 text-left text-[10.5px] leading-[18px] text-white/90",
sel?.kind === "cut" && sel.index === i && "outline-[1.5px] outline-[#ebebeb]", !c.mode && "opacity-70")}
style={{ left: x(c.start), width: Math.max(4, (c.end - c.start) * px - 1), background: MODE_COLOR[mode] }}>
{RESOLVED_MODE_LABEL[mode].label}
</button>
);
})}
</Lane>
{/* ENQ — keyframes do reenquadramento do jogo, com a linha do movimento entre eles */}
<Lane h={FIXED.reframe} tint="#1d1820">
{rfKeys.slice(0, -1).map((k, i) => (
<span key={`l${i}`} className={cx("pointer-events-none absolute top-1/2 h-px", k.ease === "hold" ? "border-t border-dashed border-[#b06ad0]/70" : "bg-[#b06ad0]/70")}
style={{ left: x(k.t), width: Math.max(0, (rfKeys[i + 1].t - k.t) * px) }} />
))}
{rfKeys.map((k, i) => (
<KeyDiamond key={`rf${i}`} x={x(k.t)} ease={k.ease} color="#e070ff" selected={sel?.kind === "reframe" && sel.key === i}
label={`Keyframe ${i + 1} do enquadramento em ${sessionClock(k.t)} (${k.ease === "hold" ? "segurar" : k.ease === "linear" ? "linear" : "suave"}). Duplo clique troca a curva.`}
onDown={(e) => { onSelect({ kind: "reframe", key: i }); onSeek(k.t); startDrag(e, { kind: "rf-key", index: i }); }}
onCycle={() => onProject((p) => (p.reframe ? { ...p, reframe: { keys: p.reframe.keys.map((kk, j) => (j === i ? { ...kk, ease: EASE_NEXT[kk.ease] } : kk)) } } : p))} />
))}
{!rfKeys.length && <span className="pointer-events-none absolute top-0 left-2 text-[10.5px] leading-[22px] text-nle-faint">sem keyframes: o jogo usa o quadro inteiro (ou a área marcada)</span>}
</Lane>
{/* V1 — vídeo: miniaturas, clipes e o que ficou fora do corte */}
<Lane h={videoH} onPointerDown={mediaDown}>
<canvas ref={videoCanvas} aria-hidden="true" className="pointer-events-none absolute top-0 left-0" style={{ width: Math.ceil(span * px), height: videoH }} />
{gapMarks}
{clipFrames("v", videoH)}
{!filmstrip && <span className="pointer-events-none absolute bottom-1 left-2 text-[10.5px] text-nle-faint">gerando miniaturas…</span>}
</Lane>
<div className="bg-nle-app" style={{ height: FIXED.divider }} />
{/* A1 — áudio da live (ligado ao vídeo: os mesmos clipes) */}
<Lane h={audioH} onPointerDown={mediaDown}>
<canvas ref={audioCanvas} aria-hidden="true" className="pointer-events-none absolute top-0 left-0" style={{ width: Math.ceil(span * px), height: audioH }} />
{gapMarks}
{clipFrames("a", audioH)}
{peaks === null && <span className="pointer-events-none absolute bottom-1 left-2 text-[10.5px] text-nle-faint">gerando forma de onda…</span>}
</Lane>
{/* A2 — narração */}
<Lane h={FIXED.narration}>
{project.audio.narration.map((n) => (
<button key={n.id} type="button" title={n.text} tabIndex={-1}
onPointerDown={(e) => { onSelect({ kind: "narration", id: n.id }); onSeek(n.at); startDrag(e, { kind: "nar-move", id: n.id, grab: timeAt(e.clientX), at: n.at }); }}
className={cx("absolute top-[3px] h-5 cursor-grab truncate rounded-[2px] px-1.5 text-left text-[10.5px] leading-5 text-white/90",
sel?.kind === "narration" && sel.id === n.id && "outline-[1.5px] outline-[#ebebeb]")}
style={{ left: x(n.at), width: Math.max(6, (n.durationS || 1) * px), background: COLORS.narration }}>{n.text}</button>
))}
</Lane>
{/* A3 — música (sob o corte inteiro) e efeitos */}
<Lane h={FIXED.music}>
{project.audio.music && project.cuts.map((c, i) => (
<div key={`m${i}`} className="absolute top-[3px] h-[18px] truncate rounded-[2px] px-1.5 text-[10.5px] leading-[18px] text-white/85"
style={{ left: x(c.start), width: (c.end - c.start) * px, background: COLORS.music }}>
{i === 0 ? project.audio.music?.file.split("/").pop() : ""}
</div>
))}
{project.audio.sfx.map((s) => (
<span key={s.id} title={s.file.split("/").pop()} className="absolute top-[5px] h-3.5 w-1.5 -translate-x-1/2 rounded-[1px] bg-[#e8a23a]" style={{ left: x(s.at) }} />
))}
</Lane>
{/* Chat: mensagens por segundo e emotes */}
<Lane h={FIXED.chat} tint="#191919">
{chatPerS.map((n, i) => n > 0 && (
<span key={i} className="absolute bottom-0 rounded-t-[1px]" title={`${n} mensagem(ns) em ${sessionClock(lo + i)}`}
style={{ left: i * px, width: Math.max(2, px - 1), height: Math.max(2, (n / maxChat) * (FIXED.chat - 8)), background: COLORS.chat }} />
))}
{chat.filter((m) => m.emotes.length).slice(0, 240).map((m, i) => (
<span key={`e${i}`} className="absolute top-[3px] size-[5px] rounded-full bg-[#f0c04f]" style={{ left: x(m.t) }} title={`${m.user}: ${m.text}`} />
))}
</Lane>
{/* Seleção de trecho, linha da lâmina e playhead (por cima das trilhas, abaixo da régua) */}
{sel?.kind === "range" && (
<div className="pointer-events-none absolute bottom-0 z-20 bg-[#5895ec]/15 outline-1 -outline-offset-1 outline-[#5895ec]"
style={{ top: TOP_H, left: x(sel.a), width: (sel.b - sel.a) * px }} />
)}
{razorT !== null && (
<div className="pointer-events-none absolute bottom-0 z-20 w-px bg-[#e34850]" style={{ top: TOP_H - 6, left: x(razorT) }} />
)}
<div className="pointer-events-none absolute bottom-0 z-20 w-px bg-[#5895ec]" style={{ top: TOP_H, left: x(playhead) }} />
</div>
</div>
</div>
{/* Rodapé da timeline: zoom e a janela carregada */}
<div className="flex h-[22px] shrink-0 items-center gap-2 border-t border-nle-line px-2.5 text-[11px] text-nle-faint">
<span className="shrink-0">Zoom</span>
<input type="range" aria-label="Zoom da timeline" min={0} max={1000} step={1} className="w-36"
value={Math.round(((px - fitPx) / Math.max(0.001, maxPx - fitPx)) * 1000)}
onChange={(e) => { const v = fitPx + (Number(e.target.value) / 1000) * (maxPx - fitPx); setZoom(v <= fitPx * 1.01 ? null : v); }} />
<span className="shrink-0 font-mono tabular-nums">{px.toFixed(1).replace(".", ",")} px/s</span>
<span className="ml-auto truncate">
Janela da gravação {sessionClock(lo)}–{sessionClock(hi)} ({Math.round(span)} s) · Ctrl + roda = zoom · Shift + arrastar na régua = selecionar
</span>
</div>
</div>
);
}
/* ---------- peças ---------- */
function TrackHeader({ id, name, h, note, tone = "#265bc1", selected = false, onSelect, children }: {
id: string; name: string; h: number; note?: string; tone?: string; selected?: boolean; onSelect?: () => void; children?: ReactNode;
}) {
return (
<div className={cx("flex items-center gap-1.5 border-b border-nle-line pr-1.5", selected ? "bg-nle-pressed/70" : onSelect && "hover:bg-nle-hover/60")} style={{ height: h }}>
<span className="grid h-full w-[26px] shrink-0 place-items-center text-[10.5px] font-semibold text-white" style={{ background: tone }}>{id}</span>
<button type="button" disabled={!onSelect} onClick={onSelect}
className={cx("flex h-full min-w-0 flex-1 flex-col justify-center text-left focus-visible:outline-1 focus-visible:outline-nle-focus", onSelect && "cursor-pointer")}>
<span className="truncate text-[11.5px] leading-tight text-nle-text">{name}</span>
{note && h >= 34 && <span className="truncate text-[10.5px] leading-tight text-nle-faint">{note}</span>}
</button>
{children}
</div>
);
}
function Lane({ h, children, tint, onPointerDown }: { h: number; children?: ReactNode; tint?: string; onPointerDown?: (e: ReactPointerEvent) => void }) {
return <div className="relative border-b border-nle-line" style={{ height: h, background: tint }} onPointerDown={onPointerDown}>{children}</div>;
}
function OverlayClip({ o, range, x, px, selected, color, label, onDown, onEdge }: {
o: Overlay; range: { a: number; b: number }; x: (t: number) => number; px: number; selected: boolean; color: string; label: string;
onDown: (e: ReactPointerEvent, a: number) => void; onEdge: (e: ReactPointerEvent, side: "left" | "right") => void;
}) {
return (
<div data-overlay={o.id}
className={cx("absolute top-[3px] bottom-[3px] cursor-grab overflow-hidden rounded-[2px] px-1.5 text-[10.5px] text-white/90", selected && "outline-[1.5px] outline-[#ebebeb]")}
style={{ left: x(range.a), width: Math.max(6, (range.b - range.a) * px), background: color }}
onPointerDown={(e) => onDown(e, range.a)}>
<span className="pointer-events-none block truncate leading-[18px]">{label}</span>
<Handle side="left" small onPointerDown={(e) => onEdge(e, "left")} label="Início" />
<Handle side="right" small onPointerDown={(e) => onEdge(e, "right")} label="Fim" />
</div>
);
}
/** Losango de keyframe (◆ suave, ◇ linear, ■ segurar): arrastar muda o instante; duplo clique troca a curva. */
function KeyDiamond({ x, ease, color, selected, label, onDown, onCycle, small = false }: {
x: number; ease: "smooth" | "linear" | "hold"; color: string; selected: boolean; label: string; small?: boolean;
onDown: (e: ReactPointerEvent) => void; onCycle: () => void;
}) {
return (
<button type="button" tabIndex={-1} title={label} aria-label={label} onPointerDown={onDown} onDoubleClick={onCycle}
className={cx("absolute top-1/2 z-10 grid -translate-x-1/2 -translate-y-1/2 cursor-ew-resize place-items-center rounded-[2px]", small ? "size-3.5" : "size-4",
selected && "bg-white/25 outline-[1.5px] outline-[#ebebeb]")}
style={{ left: x, color }}>
<KeyGlyph ease={ease} size={small ? 10 : 12} />
</button>
);
}
function Handle({ side, onPointerDown, label, small = false, quiet = false }: {
side: "left" | "right"; onPointerDown: (e: ReactPointerEvent) => void; label: string; small?: boolean;
/** Só aparece com o ponteiro em cima (para blocos pequenos e numerosos, como as palavras). */
quiet?: boolean;
}) {
return (
<span role="separator" aria-label={label} onPointerDown={onPointerDown}
className={cx("absolute inset-y-0 z-20 cursor-ew-resize hover:bg-white/70", small ? "w-1" : "w-[5px]",
quiet ? "bg-transparent" : small ? "bg-white/25" : "bg-white/35",
side === "left" ? "left-0" : "right-0")} />
);
}
function RulerMarker({ x, color, label, onClick }: { x: number; color: string; label: string; onClick: () => void }) {
return (
<button type="button" title={label} aria-label={label} tabIndex={-1}
onPointerDown={(e) => { e.stopPropagation(); onClick(); }}
className="absolute top-[3px] z-[5] -translate-x-1/2 cursor-pointer" style={{ left: x }}>
<svg width="11" height="13" viewBox="0 0 11 13" aria-hidden="true"><path d="M0.5 0.5h10v7L5.5 12.5 0.5 7.5v-7Z" fill={color} stroke="rgb(0 0 0 / 0.5)" /></svg>
</button>
);
}
function gaps(cuts: { start: number; end: number }[], lo: number, hi: number): [number, number][] {
const out: [number, number][] = [];
let cur = lo;
for (const c of cuts) {
if (c.start > cur + 0.001) out.push([cur, c.start]);
cur = Math.max(cur, c.end);
}
if (cur < hi - 0.001) out.push([cur, hi]);
return out;
}
/** Marcas da régua: as maiores (com rótulo) a cada ~90 px; quatro menores entre elas. */
function ticks(lo: number, hi: number, px: number): { t: number; major: boolean }[] {
const major = [1, 2, 5, 10, 15, 30, 60, 120, 300].find((s) => s * px >= 90) ?? 600;
const minor = major / (major % 5 === 0 ? 5 : major === 2 ? 2 : major === 1 ? 2 : 4);
const out = [];
for (let k = Math.ceil(lo / minor); k * minor <= hi; k++) {
const t = round3(k * minor);
out.push({ t, major: Math.abs(t / major - Math.round(t / major)) < 1e-6 });
}
return out;
}
@@ -0,0 +1,220 @@
"use client";
// Transcrição clicável (edição pelo texto, como no Descript) e o chat da live, nos painéis do editor de cortes.
// Transcrição: clique = ir ao instante; Shift + clique = estender a seleção; duplo clique = corrigir a palavra.
// Com palavras selecionadas, a barra oferece tirar/manter no corte e ênfase (o resto fica em Propriedades).
// Palavras fora do corte aparecem riscadas. Ferramentas: remover silêncios maiores que X s e re-transcrever um
// trecho com o Whisper do serviço de voz. Chat: as mensagens da janela, com o tempo; clique = ir ao instante.
import { useEffect, useRef, useState } from "react";
import { clipperCall } from "./clipper-client";
import {
cutAt, keepRange, produce, removeRange, removeSilences, sessionClock, type ChatItem, type EditProject, type EditWord, type Selection,
} from "./clip-editor-model";
import { Btn } from "./clip-editor-ui";
import { MicIcon, ScissorsIcon } from "./icons";
import { Spinner, cx } from "./ui";
export function EditorTranscript({ clipId, project, playhead, selection, onSelect, onSeek, onProject, onNotice, retranscribeMaxS, voiceConfigured }: {
clipId: number;
project: EditProject;
playhead: number;
selection: Selection;
onSelect: (s: Selection) => void;
onSeek: (t: number) => void;
onProject: (fn: (p: EditProject) => EditProject, key?: string) => void;
onNotice: (ok: boolean, text: string) => void;
retranscribeMaxS: number;
voiceConfigured: boolean;
}) {
const words = project.captions.words;
const [editing, setEditing] = useState<number | null>(null);
// Edição do texto de uma frase inteira (as palavras selecionadas viram um campo de texto).
const [phrase, setPhrase] = useState<string | null>(null);
const [gap, setGap] = useState(0.6);
const [busy, setBusy] = useState(false);
const activeRef = useRef<HTMLSpanElement>(null);
const range = selection?.kind === "words" ? selection : null;
const active = words.findIndex((w) => playhead >= w.s && playhead < w.e);
useEffect(() => {
activeRef.current?.scrollIntoView({ block: "nearest" });
}, [active]);
const sel = range ? words.slice(range.from, range.to + 1) : [];
const selA = sel.length ? sel[0].s : 0;
const selB = sel.length ? sel[sel.length - 1].e : 0;
function click(i: number, shift: boolean) {
if (shift && range) onSelect({ kind: "words", from: Math.min(range.from, i), to: Math.max(range.to, i) });
else onSelect({ kind: "words", from: i, to: i });
onSeek(words[i].s);
}
function setWords(fn: (ws: EditWord[]) => EditWord[], key?: string) {
onProject((p) => produce(p, (d) => { d.captions.words = fn(d.captions.words); }), key);
}
/** Troca o texto das palavras selecionadas: o tempo do trecho é repartido entre as palavras novas pelo tamanho. */
function commitPhrase() {
const text = (phrase ?? "").trim();
setPhrase(null);
if (!range || !sel.length) return;
const parts = text.split(/\s+/).filter(Boolean);
if (!parts.length || parts.join(" ") === sel.map((w) => w.w).join(" ")) return;
const weight = parts.reduce((n, w) => n + w.length + 1, 0);
let cursor = selA;
const fresh: EditWord[] = parts.map((w) => {
const dur = Math.max(0.06, ((selB - selA) * (w.length + 1)) / weight);
const item = { s: Math.round(cursor * 1000) / 1000, e: Math.round(Math.min(selB, cursor + dur) * 1000) / 1000, w: w.slice(0, 40) };
cursor += dur;
return item;
}).filter((w) => w.e > w.s);
setWords((ws) => [...ws.slice(0, range.from), ...fresh, ...ws.slice(range.to + 1)]);
onSelect(fresh.length ? { kind: "words", from: range.from, to: range.from + fresh.length - 1 } : null);
onNotice(true, "Texto da legenda trocado (o áudio não muda).");
}
async function retranscribe() {
// Trecho = a seleção (com folga) ou o trecho do corte onde está o playhead.
let a = selA - 0.3, b = selB + 0.3;
if (!sel.length) {
const c = project.cuts.find((x) => playhead >= x.start && playhead <= x.end) ?? project.cuts[0];
a = c.start;
b = Math.min(c.end, c.start + retranscribeMaxS);
}
a = Math.max(project.source.lo, a);
b = Math.min(project.source.hi, b);
setBusy(true);
const r = await clipperCall<{ words: EditWord[]; seconds: number }>(`clips/${clipId}/retranscribe`, "POST", { startS: a, endS: b });
setBusy(false);
if (!r.ok) return onNotice(false, r.error);
setWords((ws) => [...ws.filter((w) => w.e <= a || w.s >= b), ...r.data.words].sort((x, y) => x.s - y.s));
onSelect(null);
onNotice(true, `Whisper transcreveu ${sessionClock(a)}–${sessionClock(b)} de novo: ${r.data.words.length} palavras em ${r.data.seconds.toLocaleString("pt-BR")} s.`);
}
// Parágrafos: quebra quando a fala para mais de 1,2 s (fica mais fácil achar onde cortar).
const paragraphs: number[][] = [];
words.forEach((w, i) => {
const last = paragraphs[paragraphs.length - 1];
if (!last || w.s - words[i - 1].e > 1.2) paragraphs.push([i]);
else last.push(i);
});
return (
<div className="flex h-full min-h-0 flex-col">
<div className="flex h-8 shrink-0 items-center gap-1.5 border-b border-nle-line px-2.5">
{sel.length > 0 ? (
<>
<span className="mr-auto truncate font-mono text-[11px] text-nle-dim">{sel.length} palavra(s) · {sessionClock(selA)}</span>
<Btn variant="danger" className="px-2" onClick={() => { onProject((p) => ({ ...p, cuts: removeRange(p.cuts, selA, selB) })); onSelect(null); }}>
<ScissorsIcon size={13} />Tirar
</Btn>
<Btn className="px-2" onClick={() => onProject((p) => ({ ...p, cuts: keepRange(p.cuts, selA, selB) }))}>Manter</Btn>
<Btn variant="ghost" className="px-2" title="Trocar o texto da legenda deste trecho (o áudio não muda)"
onClick={() => setPhrase(sel.map((w) => w.w).join(" "))}>Editar</Btn>
<Btn variant="ghost" className="px-2" title="Tirar estas palavras só da legenda (o vídeo continua)" onClick={() => {
const on = !sel.every((w) => w.hidden);
setWords((ws) => ws.map((w, i) => (range && i >= range.from && i <= range.to ? { ...w, hidden: on || undefined } : w)));
}}>{sel.every((w) => w.hidden) ? "Mostrar" : "Ocultar"}</Btn>
<Btn variant="ghost" className="px-2" onClick={() => {
const on = !sel.every((w) => w.emph);
setWords((ws) => ws.map((w, i) => (range && i >= range.from && i <= range.to ? { ...w, emph: on || undefined } : w)));
}}>Ênfase</Btn>
</>
) : (
<>
<label className="mr-auto flex items-center gap-1.5 text-nle-dim">
Silêncios &gt;
<input type="number" min={0.3} max={5} step={0.1} value={gap} onChange={(e) => setGap(Number(e.target.value) || 0.6)}
aria-label="Duração mínima do silêncio (s)"
className="h-[22px] w-12 rounded-[3px] border border-nle-line bg-nle-well px-1 text-center font-mono text-[11.5px] text-nle-hot focus-visible:border-nle-focus focus-visible:outline-none" />s
</label>
<Btn className="px-2" title="Tira do corte as pausas maiores que o valor ao lado" onClick={() => {
const r = removeSilences(project.cuts, words, gap);
if (!r.removed) return onNotice(true, `Nenhum silêncio maior que ${gap} s dentro do corte.`);
onProject((p) => ({ ...p, cuts: r.cuts }));
onNotice(true, `${r.removed} silêncio(s) removido(s): −${r.seconds.toFixed(1).replace(".", ",")} s.`);
}}><ScissorsIcon size={13} />Remover</Btn>
</>
)}
<Btn variant="ghost" className="px-2" disabled={busy || !voiceConfigured} onClick={() => void retranscribe()}
title={sel.length ? "Transcrever de novo as palavras selecionadas (Whisper)" : "Transcrever de novo o trecho do playhead (Whisper)"}>
{busy ? <Spinner className="size-3" /> : <MicIcon size={13} />}Whisper
</Btn>
</div>
{phrase !== null && (
<div className="grid shrink-0 gap-1.5 border-b border-nle-line bg-nle-row px-2.5 py-2">
<textarea autoFocus rows={2} aria-label="Novo texto da legenda para o trecho selecionado" value={phrase} onChange={(e) => setPhrase(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); commitPhrase(); } if (e.key === "Escape") setPhrase(null); }}
className="w-full resize-none rounded-[3px] border border-nle-focus bg-nle-well px-2 py-1 text-[12.5px] text-nle-text outline-none" />
<div className="flex items-center gap-1.5">
<span className="mr-auto text-[11px] text-nle-faint">Enter aplica · Esc cancela · só a legenda muda</span>
<Btn variant="ghost" className="px-2" onClick={() => setPhrase(null)}>Cancelar</Btn>
<Btn variant="primary" className="px-2" onClick={commitPhrase}>Aplicar</Btn>
</div>
</div>
)}
<div className="min-h-0 flex-1 overflow-y-auto px-3 py-2 text-[13px] leading-[1.75]">
{!words.length && <p className="text-nle-faint">Sem fala transcrita nesta janela. Use “Whisper” para transcrever.</p>}
{paragraphs.map((para) => (
<p key={para[0]} className="mb-1.5 grid grid-cols-[52px_minmax(0,1fr)] gap-x-2">
<button type="button" tabIndex={-1} onClick={() => onSeek(words[para[0]].s)}
className="cursor-pointer pt-[3px] text-left font-mono text-[10.5px] text-nle-hot/80 hover:text-nle-hot">{sessionClock(words[para[0]].s)}</button>
<span>
{para.map((i) => {
const w = words[i];
const kept = cutAt(project.cuts, (w.s + w.e) / 2) >= 0;
const selected = range && i >= range.from && i <= range.to;
if (editing === i) {
return (
<input key={i} autoFocus defaultValue={w.w} aria-label="Corrigir palavra" maxLength={40}
className="mx-0.5 w-24 rounded-[2px] border border-nle-focus bg-nle-well px-1 text-[12.5px] outline-none"
onBlur={(e) => { setEditing(null); const v = e.target.value.trim(); if (v && v !== w.w) setWords((ws) => ws.map((x, j) => (j === i ? { ...x, w: v } : x))); }}
onKeyDown={(e) => { if (e.key === "Enter") (e.target as HTMLInputElement).blur(); if (e.key === "Escape") setEditing(null); }} />
);
}
return (
<span key={i} ref={i === active ? activeRef : undefined} role="button" tabIndex={-1}
onClick={(e) => click(i, e.shiftKey)} onDoubleClick={() => setEditing(i)}
title={`${sessionClock(w.s)} · duplo clique para corrigir`}
className={cx("cursor-pointer rounded-[2px] px-[2px] hover:bg-nle-hover",
!kept && "text-nle-faint line-through decoration-nle-danger/60",
w.hidden && "opacity-50",
w.emph && kept && "text-[#6fd39b]",
i === active && !selected && "bg-nle-accent/40 text-white",
selected && "bg-nle-accent text-white")}>{w.w} </span>
);
})}
</span>
</p>
))}
</div>
</div>
);
}
/** Chat da janela: o que o público disse e quando (contexto do momento, ex.: "server chinês" = lag). */
export function EditorChat({ chat, playhead, onSeek }: { chat: ChatItem[]; playhead: number; onSeek: (t: number) => void }) {
const nowRef = useRef<HTMLButtonElement>(null);
let current = -1;
for (let i = 0; i < chat.length && chat[i].t <= playhead; i++) current = i;
useEffect(() => {
nowRef.current?.scrollIntoView({ block: "nearest" });
}, [current]);
if (!chat.length) return <p className="px-3 py-2 text-nle-faint">Sem mensagens do chat nesta janela.</p>;
return (
<div className="py-1">
{chat.map((m, i) => (
<button key={`${m.t}-${i}`} ref={i === current ? nowRef : undefined} type="button" tabIndex={-1} onClick={() => onSeek(m.t)}
className={cx("grid w-full cursor-pointer grid-cols-[52px_minmax(0,1fr)] gap-x-2 px-3 py-[3px] text-left leading-snug hover:bg-nle-hover/70", i === current && "bg-nle-row")}>
<span className="font-mono text-[10.5px] text-nle-hot/80">{sessionClock(m.t)}</span>
<span className="min-w-0 break-words">
<span className="text-nle-faint">{m.user}: </span>
<span className={m.emotes.length ? "text-[#f0c04f]" : "text-nle-text"}>{m.text}</span>
</span>
</button>
))}
</div>
);
}
+309
View File
@@ -0,0 +1,309 @@
"use client";
// Peças de interface do editor de cortes, no padrão dos editores de vídeo (referência: FilmCraft): painéis
// encostados com faixa de abas, linhas de propriedade "rótulo · controle · valor em azul", seções que recolhem,
// botões de ícone pequenos e modais nativos. Tudo denso (12 px) e neutro; as cores vêm dos tokens `nle-*`.
import { useEffect, useRef, useState, type ButtonHTMLAttributes, type ReactNode } from "react";
import type { Rect } from "./clipper-client";
import { clampRect } from "./rect-geometry";
import { cx } from "./ui";
type IconProps = { size?: number; className?: string };
function Svg({ children, size = 16, className, fill = false }: IconProps & { children: ReactNode; fill?: boolean }) {
return (
<svg viewBox="0 0 24 24" width={size} height={size} fill={fill ? "currentColor" : "none"} stroke={fill ? "none" : "currentColor"}
strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className={cx("shrink-0", className)} aria-hidden="true" focusable="false">
{children}
</svg>
);
}
/* Ícones próprios do editor (grade 24, traço 1,75 — mesma família de icons.tsx). */
export const CursorIcon = (p: IconProps) => <Svg {...p} fill><path d="M5 3.2v16.4l4.6-4.3 2.9 6.2 2.5-1.2-2.9-6.1h6.3L5 3.2Z" /></Svg>;
export const RazorIcon = (p: IconProps) => (
<Svg {...p}><path d="M4 15.5 14.5 5l4.5 4.5L8.5 20H4v-4.5Z" /><path d="m11.5 8 4.5 4.5M7 13l1 1M9.5 10.5l1 1" /></Svg>
);
export const HandIcon = (p: IconProps) => (
<Svg {...p}><path d="M8 12V5.5a1.5 1.5 0 0 1 3 0V11m0-6.5V4a1.5 1.5 0 0 1 3 0v7m0-5.5a1.5 1.5 0 0 1 3 0V13m0-3.5a1.5 1.5 0 0 1 3 0V15a6 6 0 0 1-6 6h-1.5a6 6 0 0 1-5-2.7L4.6 14a1.6 1.6 0 0 1 2.6-1.8L8 13.2" /></Svg>
);
export const MagnetIcon = (p: IconProps) => (
<Svg {...p}><path d="M5 4h4v8a3 3 0 0 0 6 0V4h4v8a7 7 0 0 1-14 0V4Z" /><path d="M5 8h4M15 8h4" /></Svg>
);
export const TextToolIcon = (p: IconProps) => <Svg {...p}><path d="M5 6V4h14v2M12 4v16M9 20h6" /></Svg>;
export const ZoomToolIcon = (p: IconProps) => <Svg {...p}><circle cx="11" cy="11" r="6.5" /><path d="m20 20-4.2-4.2M11 8.2v5.6M8.2 11h5.6" /></Svg>;
export const EyeOnIcon = (p: IconProps) => <Svg {...p}><path d="M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12Z" /><circle cx="12" cy="12" r="2.6" /></Svg>;
export const EyeOffIcon = (p: IconProps) => <Svg {...p}><path d="M4 4l16 16M9.9 6A9.6 9.6 0 0 1 12 5.5c6 0 9.5 6.5 9.5 6.5a16 16 0 0 1-2.9 3.7M6.3 7.7A16 16 0 0 0 2.5 12S6 18.5 12 18.5a9 9 0 0 0 3.6-.8" /></Svg>;
export const SpeakerIcon = (p: IconProps) => <Svg {...p}><path d="M4 9.5v5h3.5L12 18.5v-13L7.5 9.5H4Z" /><path d="M15.5 9a4 4 0 0 1 0 6M18 6.5a7.5 7.5 0 0 1 0 11" /></Svg>;
export const KeyboardIcon = (p: IconProps) => <Svg {...p}><rect x="2.5" y="6" width="19" height="12" rx="2" /><path d="M6.5 10h.01M10 10h.01M13.5 10h.01M17 10h.01M6.5 14h11" /></Svg>;
export const StepBackIcon = (p: IconProps) => <Svg {...p} fill><path d="M7 5h2v14H7zM20 5v14l-9.5-7L20 5Z" /></Svg>;
export const StepFwdIcon = (p: IconProps) => <Svg {...p} fill><path d="M15 5h2v14h-2zM4 5v14l9.5-7L4 5Z" /></Svg>;
export const ToStartIcon = (p: IconProps) => <Svg {...p} fill><path d="M4 5h2.2v14H4zM20 5v14l-6.2-4.6V19L7 12l6.8-7v4.6L20 5Z" /></Svg>;
export const ToEndIcon = (p: IconProps) => <Svg {...p} fill><path d="M17.8 5H20v14h-2.2zM4 5v14l6.2-4.6V19L17 12l-6.8-7v4.6L4 5Z" /></Svg>;
export const PlaySolidIcon = (p: IconProps) => <Svg {...p} fill><path d="M7 4.5v15l12.5-7.5L7 4.5Z" /></Svg>;
export const PauseSolidIcon = (p: IconProps) => <Svg {...p} fill><path d="M6.5 4.5h4v15h-4zM13.5 4.5h4v15h-4z" /></Svg>;
export const FitIcon = (p: IconProps) => <Svg {...p}><path d="M4 9V5h4M20 9V5h-4M4 15v4h4M20 15v4h-4" /></Svg>;
export const LayersIcon = (p: IconProps) => <Svg {...p}><path d="m12 3.5 9 5-9 5-9-5 9-5Z" /><path d="m3 13.5 9 5 9-5" /></Svg>;
export const CaretIcon = ({ open, ...p }: IconProps & { open: boolean }) => (
<Svg {...p} size={p.size ?? 12} className={cx("transition-transform", open && "rotate-90", p.className)}><path d="m9 5 7 7-7 7" /></Svg>
);
/* ---------- Painel com faixa de abas ---------- */
export type PanelTab<T extends string> = { id: T; label: string; count?: number };
/** Painel encostado nos vizinhos: faixa de abas de 30 px (a ativa em branco e sublinhada) e corpo que rola sozinho. */
export function Panel<T extends string>({ tabs, active, onTab, actions, children, className, label, bodyClassName }: {
tabs: PanelTab<T>[]; active: T; onTab?: (id: T) => void; actions?: ReactNode; children: ReactNode;
className?: string; label: string; bodyClassName?: string;
}) {
return (
<section aria-label={label} className={cx("flex min-h-0 min-w-0 flex-col bg-nle-panel", className)}>
<div className="flex h-[30px] shrink-0 items-center gap-4 border-b border-nle-line px-3">
<div role="tablist" aria-label={label} className="flex min-w-0 items-center gap-4 overflow-hidden">
{tabs.map((t) => (
<button key={t.id} type="button" role="tab" aria-selected={active === t.id} disabled={!onTab}
onClick={() => onTab?.(t.id)}
className={cx("h-[30px] shrink-0 border-b-[1.5px] pt-px text-[12px] whitespace-nowrap focus-visible:outline-1 focus-visible:outline-nle-focus",
active === t.id ? "border-nle-text text-nle-text" : "border-transparent text-nle-dim/80 hover:text-nle-text",
onTab && "cursor-pointer")}>
{t.label}{t.count !== undefined && <span className="ml-1.5 text-nle-faint tabular-nums">{t.count}</span>}
</button>
))}
</div>
{actions && <div className="ml-auto flex shrink-0 items-center gap-0.5">{actions}</div>}
</div>
<div className={cx("min-h-0 flex-1 overflow-y-auto", bodyClassName)}>{children}</div>
</section>
);
}
/* ---------- Botões ---------- */
/** Botão de ícone quadrado (24 px). `active` = ferramenta/alternância ligada. */
export function IconBtn({ label, active = false, className, children, kbd, ...props }:
ButtonHTMLAttributes<HTMLButtonElement> & { label: string; active?: boolean; kbd?: string }) {
return (
<button type="button" aria-label={label} title={kbd ? `${label} (${kbd})` : label} aria-pressed={active || undefined} {...props}
className={cx("grid size-6 shrink-0 cursor-pointer place-items-center rounded-[3px] focus-visible:outline-1 focus-visible:outline-nle-focus",
"disabled:cursor-default disabled:opacity-35",
active ? "bg-nle-pressed text-white" : "text-nle-dim hover:bg-nle-hover hover:text-nle-text", className)}>
{children}
</button>
);
}
type BtnVariant = "default" | "primary" | "danger" | "ghost";
/** Botão de texto compacto (24 px). */
export function Btn({ variant = "default", className, ...props }: ButtonHTMLAttributes<HTMLButtonElement> & { variant?: BtnVariant }) {
const tone: Record<BtnVariant, string> = {
default: "border-[#4b4b4b] bg-nle-panel text-nle-text hover:bg-nle-hover",
primary: "border-nle-accent bg-nle-accent text-white hover:bg-[#3f7ce8]",
danger: "border-nle-danger/60 text-[#f08a7a] hover:bg-nle-danger/20",
ghost: "border-transparent text-nle-dim hover:bg-nle-hover hover:text-nle-text",
};
return (
<button type="button" {...props}
className={cx("inline-flex h-6 shrink-0 cursor-pointer items-center justify-center gap-1.5 rounded-[3px] border px-2.5 text-[12px] whitespace-nowrap",
"focus-visible:outline-1 focus-visible:outline-offset-1 focus-visible:outline-nle-focus disabled:cursor-default disabled:opacity-40",
tone[variant], className)} />
);
}
/* ---------- Propriedades ---------- */
/** Seção que recolhe (como um efeito no painel de controles): seta, título e ações à direita. */
export function PropSection({ title, children, actions, defaultOpen = true, className }: {
title: ReactNode; children: ReactNode; actions?: ReactNode; defaultOpen?: boolean; className?: string;
}) {
const [open, setOpen] = useState(defaultOpen);
return (
<div className={cx("border-b border-nle-line", className)}>
<div className="flex h-7 items-center gap-1 pr-2 pl-1.5">
<button type="button" aria-expanded={open} onClick={() => setOpen((o) => !o)}
className="flex min-w-0 flex-1 cursor-pointer items-center gap-1 text-left text-[12px] font-semibold text-nle-text focus-visible:outline-1 focus-visible:outline-nle-focus">
<CaretIcon open={open} className="text-nle-dim" /><span className="truncate">{title}</span>
</button>
{actions}
</div>
{open && <div className="grid gap-1.5 pt-0.5 pr-3 pb-2.5 pl-[22px]">{children}</div>}
</div>
);
}
/** Linha "rótulo | controle". */
export function PropRow({ label, children, hint, top = false }: { label: ReactNode; children: ReactNode; hint?: string; /** Rótulo no alto (controle alto, que abre). */ top?: boolean }) {
return (
<div className={cx("grid min-h-6 grid-cols-[104px_minmax(0,1fr)] gap-2", top ? "items-start" : "items-center")} title={hint}>
<span className={cx("truncate text-nle-dim", top && "pt-1.5")}>{label}</span>
<div className="flex min-w-0 items-center gap-2">{children}</div>
</div>
);
}
/** Controle deslizante com o valor em azul (clique no valor para digitar). */
export function Scrub({ value, min, max, step, onChange, format, label, parse }: {
value: number; min: number; max: number; step: number; onChange: (v: number) => void;
format?: (v: number) => string; label: string; parse?: (text: string) => number;
}) {
const [typing, setTyping] = useState<string | null>(null);
const shown = format ? format(value) : String(value);
const commit = (text: string) => {
setTyping(null);
const n = parse ? parse(text) : Number(text.replace(",", ".").replace(/[^\d.-]/g, ""));
if (Number.isFinite(n)) onChange(Math.min(max, Math.max(min, n)));
};
return (
<>
<input type="range" aria-label={label} min={min} max={max} step={step} value={value}
onChange={(e) => onChange(Number(e.target.value))} className="min-w-0 flex-1" />
{typing === null ? (
<button type="button" title="Clique para digitar" onClick={() => setTyping(String(value))}
className="w-[52px] shrink-0 cursor-text text-right font-mono text-[11.5px] text-nle-hot tabular-nums hover:underline">{shown}</button>
) : (
<input autoFocus aria-label={`${label} (valor)`} defaultValue={typing} onBlur={(e) => commit(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") commit((e.target as HTMLInputElement).value); if (e.key === "Escape") setTyping(null); }}
className="w-[52px] shrink-0 rounded-[2px] border border-nle-focus bg-nle-well px-1 text-right font-mono text-[11.5px] text-nle-text outline-none" />
)}
</>
);
}
export function Check({ checked, onChange, label }: { checked: boolean; onChange: (v: boolean) => void; label: string }) {
return (
<label className="flex cursor-pointer items-center gap-2 text-nle-text">
<input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked)} className="size-3.5 cursor-pointer accent-[#d1d1d1]" />
<span className="truncate">{label}</span>
</label>
);
}
export function ColorDot({ value, onChange, label }: { value: string; onChange: (v: string) => void; label: string }) {
return (
<span className="flex items-center gap-2">
<input type="color" aria-label={label} value={value} onChange={(e) => onChange(e.target.value.toUpperCase())}
className="h-[18px] w-7 cursor-pointer rounded-[2px] border border-[#4b4b4b] bg-transparent p-0" />
<span className="font-mono text-[11px] text-nle-dim">{value}</span>
</span>
);
}
export function Pick({ value, onChange, children, label, className }: {
value: string; onChange: (v: string) => void; children: ReactNode; label: string; className?: string;
}) {
return (
<select aria-label={label} value={value} onChange={(e) => onChange(e.target.value)}
className={cx("h-6 min-w-0 flex-1 cursor-pointer rounded-[3px] border border-nle-line bg-nle-well px-1.5 text-[12px] text-nle-text",
"focus-visible:outline-1 focus-visible:outline-nle-focus disabled:opacity-50", className)}>
{children}
</select>
);
}
export const fieldClass = "w-full rounded-[3px] border border-nle-line bg-nle-well px-2 py-1 text-[12px] text-nle-text placeholder:text-nle-faint focus-visible:border-nle-focus focus-visible:outline-none";
/** Texto azul de valor/tempo (não editável). */
export function Hot({ children, className }: { children: ReactNode; className?: string }) {
return <span className={cx("font-mono text-[11.5px] text-nle-hot tabular-nums", className)}>{children}</span>;
}
export function Hint({ children, tone = "faint" }: { children: ReactNode; tone?: "faint" | "warn" | "bad" }) {
return <p className={cx("text-[11px] leading-snug", tone === "warn" ? "text-[#e2b340]" : tone === "bad" ? "text-[#f08a7a]" : "text-nle-faint")}>{children}</p>;
}
/* ---------- Modal ---------- */
/** Modal nativo (<dialog>): foco preso, Esc fecha, fundo escurecido. O conteúdo só monta aberto. */
export function Modal({ open, onClose, title, children, footer, width = 560 }: {
open: boolean; onClose: () => void; title: string; children: ReactNode; footer?: ReactNode; width?: number;
}) {
const ref = useRef<HTMLDialogElement>(null);
const openRef = useRef(open);
openRef.current = open;
useEffect(() => {
const dialog = ref.current;
if (!dialog) return;
if (open && !dialog.open) dialog.showModal();
if (!open && dialog.open) dialog.close();
}, [open]);
return (
// Esc fecha pelo próprio navegador (evento `close`); só sincronizamos o estado. Segurar o `cancel` com
// preventDefault faz o Chrome ignorar o Esc seguinte e o modal fica preso aberto.
// Só avisa quando foi o usuário que fechou: fechar por código (trocar de modal) também dispara `close`.
<dialog ref={ref} aria-label={title} onClose={() => { if (openRef.current) onClose(); }}
onClick={(e) => { if (e.target === ref.current) onClose(); }}
style={{ width: `min(94vw, ${width}px)` }}
className="m-auto max-h-[90vh] overflow-hidden rounded-[6px] border border-[#3a3a3a] bg-nle-panel p-0 text-[12px] text-nle-text shadow-[0_24px_80px_rgb(0_0_0/0.7)]">
{open && (
<div className="flex max-h-[90vh] flex-col">
<header className="flex h-9 shrink-0 items-center border-b border-nle-line pr-1.5 pl-3.5">
<h2 className="text-[13px] font-semibold">{title}</h2>
<IconBtn label="Fechar" kbd="Esc" className="ml-auto" onClick={onClose}>
<svg viewBox="0 0 24 24" width={14} height={14} fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18" /></svg>
</IconBtn>
</header>
<div className="min-h-0 flex-1 overflow-y-auto p-3.5">{children}</div>
{footer && <footer className="flex shrink-0 items-center justify-end gap-2 border-t border-nle-line px-3.5 py-2.5">{footer}</footer>}
</div>
)}
</dialog>
);
}
export function Keycap({ children }: { children: ReactNode }) {
return <kbd className="rounded-[3px] border border-[#4b4b4b] bg-nle-well px-1.5 py-px font-mono text-[10.5px] text-nle-dim">{children}</kbd>;
}
/* ---------- Linhas de lista e campos de retângulo (Propriedades) ---------- */
export function RowButton({ label, meta, onClick }: { label: string; meta: string; onClick: () => void }) {
return (
<button type="button" onClick={onClick} className="flex h-6 cursor-pointer items-center gap-2 rounded-[3px] px-1.5 text-left hover:bg-nle-hover">
<span className="min-w-0 flex-1 truncate">{label}</span>
<span className="shrink-0 font-mono text-[11px] text-nle-dim">{meta}</span>
</button>
);
}
const RECT_FIELDS: { key: keyof Rect; label: string }[] = [{ key: "x", label: "X" }, { key: "y", label: "Y" }, { key: "w", label: "Largura" }, { key: "h", label: "Altura" }];
/** Campos numéricos do retângulo, em % do quadro (alternativa ao mouse). Grava ao sair do campo, com Enter ou ↑/↓. */
export function RectFields({ label, rect, onChange }: { label: string; rect: Rect | null; onChange: (r: Rect, field: keyof Rect) => void }) {
return (
<fieldset className="grid grid-cols-4 gap-1.5" disabled={!rect}>
<legend className="sr-only">{label} (% do quadro)</legend>
{RECT_FIELDS.map((f) => (
<PctField key={f.key} label={`${label}: ${f.label} (%)`} short={f.label} value={rect ? rect[f.key] : null}
onCommit={(v) => rect && onChange(clampRect({ ...rect, [f.key]: v }), f.key)} />
))}
</fieldset>
);
}
function PctField({ label, short, value, onCommit }: { label: string; short: string; value: number | null; onCommit: (v: number) => void }) {
const [text, setText] = useState<string | null>(null);
const shown = value === null ? "" : String(Math.round(value * 1000) / 10).replace(".", ",");
const commit = (raw: string) => {
setText(null);
const n = Number(raw.replace(",", ".").replace(/[^\d.-]/g, ""));
if (raw.trim() !== "" && Number.isFinite(n)) onCommit(n / 100);
};
return (
<label className="grid gap-0.5 text-[10.5px] text-nle-faint">
{short}
<input aria-label={label} inputMode="decimal" value={text ?? shown} disabled={value === null}
onChange={(e) => setText(e.target.value)} onBlur={(e) => { if (text !== null) commit(e.target.value); }}
onKeyDown={(e) => {
if (e.key === "Enter") commit(e.currentTarget.value);
else if (e.key === "Escape") { setText(null); e.currentTarget.blur(); }
else if ((e.key === "ArrowUp" || e.key === "ArrowDown") && value !== null) {
e.preventDefault();
const step = (e.shiftKey ? 5 : 0.5) * (e.key === "ArrowUp" ? 1 : -1);
setText(null);
onCommit((Math.round(value * 1000) / 10 + step) / 100);
}
}}
className="h-6 w-full min-w-0 rounded-[3px] border border-nle-line bg-nle-well px-1.5 text-right font-mono text-[11.5px] text-nle-hot tabular-nums focus-visible:border-nle-focus focus-visible:outline-none disabled:opacity-40" />
</label>
);
}
File diff suppressed because it is too large Load Diff
+203
View File
@@ -0,0 +1,203 @@
"use client";
// "Publicar" no cartão de um corte aprovado do Clipador: abre um diálogo para escolher o canal de publicação, as
// redes (só as conectadas) e quando sai (agora ou no próximo horário bom). Não precisa ligar a fonte inteira ao
// canal: POST /api/publishing/clips/[id] cria os jobs já aprovados (o clique é a aprovação), com origem "manual".
// Título e legenda são os do cartão (salvos). Cada rede mostra por que não pode ser escolhida, quando for o caso.
import { useEffect, useState } from "react";
import type { AccountView } from "@/lib/accounts";
import type { Platform } from "@/lib/types";
import { apiCall } from "./api-client";
import type { Clip } from "./clipper-client";
import { Dialog } from "./dialog";
import { AlertIcon, CheckIcon, PublishIcon } from "./icons";
import { PLATFORM_META } from "./platforms";
import { publishClip, type PublishJob, type PublishTiming } from "./publishing-client";
import { TextLink } from "./publishing-ui";
import { Button, ChoiceGroup, Feedback, Field, Select, Spinner, cx } from "./ui";
const PLATFORM_ORDER: Platform[] = ["youtube", "tiktok", "instagram"];
const NETWORK_NOTE: Record<string, string> = {
connected: "conectada",
connecting: "ainda conectando (sai quando terminar)",
needs_login: "precisa entrar de novo (sai depois que você entrar)",
expired: "conexão vencida (sai depois que você conectar de novo)",
error: "com erro na conexão (sai quando voltar)",
};
/** O que esta rede já tem deste corte, quando impede de mandar de novo (texto curto). */
function blockedByJob(job: PublishJob | undefined): string | null {
if (!job) return null;
if (job.status === "published") return "já publicado nesta rede";
if (job.mayBeLive) return "o envio anterior pode ter saído: confira em Publicações";
if (job.status === "publishing") return "sendo enviado agora";
if (job.status === "queued") return "já está na fila";
if (job.status === "scheduled") return "já está agendado";
return null;
}
export function ClipPublishButton({ clip, jobs, onDone, variant = "primary" }: {
clip: Clip;
/** Jobs deste corte (sem os cancelados), para saber o que cada rede já tem. */
jobs: PublishJob[];
/** Depois de publicar: mensagem para o cartão e recarregar o estado. */
onDone: (message: { ok: boolean; text: string }) => void;
variant?: "primary" | "secondary";
}) {
const [open, setOpen] = useState(false);
return (
<>
<Button size="sm" variant={variant} onClick={() => setOpen(true)} disabled={!clip.file}>
<PublishIcon size={15} />{jobs.length ? "Publicar em outra rede" : "Publicar"}
</Button>
{open && <PublishDialog clip={clip} jobs={jobs} onClose={() => setOpen(false)}
onDone={(m) => { setOpen(false); onDone(m); }} />}
</>
);
}
function PublishDialog({ clip, jobs, onClose, onDone }: {
clip: Clip; jobs: PublishJob[]; onClose: () => void; onDone: (message: { ok: boolean; text: string }) => void;
}) {
const [accounts, setAccounts] = useState<AccountView[] | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [accountId, setAccountId] = useState("");
const [chosen, setChosen] = useState<ReadonlySet<Platform>>(() => new Set());
const [timing, setTiming] = useState<PublishTiming>("best_slot");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const account = accounts?.find((a) => a.id === accountId) ?? null;
/** Redes do canal: escolhível? por quê não? (a ordem é sempre YouTube, TikTok, Instagram) */
const networksOf = (a: AccountView | null) => PLATFORM_ORDER.map((platform) => {
const n = a?.networks.find((x) => x.platform === platform);
const job = jobs.find((j) => j.accountId === a?.id && j.platform === platform);
const blocked = !n || n.status === "disconnected" ? "não conectada neste canal"
: n.enabled !== 1 ? "pausada neste canal" : blockedByJob(job);
return { platform, blocked, note: blocked ?? NETWORK_NOTE[n!.status] ?? "conectada" };
});
function pickAccount(a: AccountView | null) {
setAccountId(a?.id ?? "");
setChosen(new Set(networksOf(a).filter((n) => !n.blocked).map((n) => n.platform)));
setTiming(a?.timing === "now" ? "now" : "best_slot");
}
useEffect(() => {
let cancelled = false;
void apiCall<AccountView[]>("/api/accounts").then((r) => {
if (cancelled) return;
if (!r.ok) { setLoadError(r.error); return; }
setAccounts(r.data);
// Abre já no canal com mais redes prontas para receber este corte.
const ready = (a: AccountView) => a.networks.filter((n) => n.status !== "disconnected" && n.enabled === 1).length;
pickAccount([...r.data].sort((x, y) => ready(y) - ready(x))[0] ?? null);
});
return () => { cancelled = true; };
}, []); // carrega uma vez por abertura do diálogo (o diálogo só monta aberto)
const networks = networksOf(account);
const selected = networks.filter((n) => !n.blocked && chosen.has(n.platform)).map((n) => n.platform);
const toggle = (platform: Platform, on: boolean) => setChosen((prev) => {
const next = new Set(prev);
if (on) next.add(platform); else next.delete(platform);
return next;
});
async function submit() {
if (!account) { setError("Escolha um canal de publicação."); return; }
if (selected.length === 0) { setError("Marque pelo menos uma rede."); return; }
setBusy(true);
setError(null);
const r = await publishClip(clip.id, { accountId: account.id, platforms: selected, timing });
setBusy(false);
if (!r.ok) { setError(r.error); return; }
const label = (p: Platform) => PLATFORM_META[p].label;
const skipped = r.data.skipped.map((s) => `${label(s.platform)}: ${s.reason}`).join("; ");
const placed = r.data.placed;
const head = placed === 0 ? "Nenhuma rede entrou na fila."
: timing === "now" ? `${placed === 1 ? "1 rede" : `${placed} redes`} na fila para sair agora.`
: `${placed === 1 ? "1 rede agendada" : `${placed} redes agendadas`} no próximo horário bom.`;
onDone({ ok: placed > 0, text: skipped ? `${head} Ficou de fora — ${skipped}.` : head });
}
return (
<Dialog open onClose={onClose} eyebrow={<><PublishIcon size={14} />Publicar nas redes</>}
title="Publicar este corte"
description="Escolha o canal, as redes e quando sai. Clicar em Publicar já é a sua aprovação."
footer={<>
<Button variant="secondary" onClick={onClose}>Voltar</Button>
<Button onClick={() => void submit()} disabled={busy || !account || selected.length === 0}>
{busy ? <><Spinner />Publicando…</>
: <><CheckIcon size={16} />{selected.length > 1 ? `Publicar em ${selected.length} redes` : "Publicar"}</>}
</Button>
</>}>
<div className="grid gap-5">
<div className="grid gap-1 rounded-control border border-line bg-sunken/40 px-3.5 py-2.5">
<p className="text-sm font-medium text-fg">{clip.title || `Corte ${clip.id}`}</p>
<p className="line-clamp-2 text-xs leading-relaxed text-fg-muted">{clip.caption || "Sem legenda."}</p>
<p className="text-xs text-fg-subtle">Vai com o título e a legenda do cartão. Para mudar, edite no cartão e salve antes.</p>
</div>
{loadError ? (
<Feedback ok={false}>Não deu para ler os canais de publicação ({loadError}).</Feedback>
) : !accounts ? (
<p className="flex items-center gap-2 text-sm text-fg-muted"><Spinner className="size-4" />Carregando os canais…</p>
) : accounts.length === 0 ? (
<p className="flex gap-2 rounded-control border border-warning/30 bg-warning-soft px-3 py-2 text-[0.8125rem] leading-relaxed text-warning">
<AlertIcon size={15} className="mt-0.5 shrink-0" />
<span>Você ainda não tem canal de publicação. Crie um e conecte as redes em <TextLink href="/accounts">Canais de publicação</TextLink>.</span>
</p>
) : (
<>
{accounts.length > 1 ? (
<Field label="Canal de publicação">
<Select value={accountId} onChange={(e) => pickAccount(accounts.find((a) => a.id === e.target.value) ?? null)}>
{accounts.map((a) => <option key={a.id} value={a.id}>{a.name}</option>)}
</Select>
</Field>
) : (
<p className="text-[0.8125rem] text-fg-muted">Canal de publicação: <span className="font-medium text-fg">{account?.name}</span></p>
)}
<fieldset className="grid gap-2">
<legend className="mb-2 text-[0.8125rem] font-medium text-fg-muted">Em quais redes</legend>
<ul className="grid divide-y divide-line rounded-control border border-line">
{networks.map(({ platform, blocked, note }) => {
const Icon = PLATFORM_META[platform].icon;
const id = `publicar-${clip.id}-${platform}`;
return (
<li key={platform}>
<label htmlFor={id} className={cx("flex items-center gap-3 px-3.5 py-2.5", blocked ? "cursor-not-allowed" : "cursor-pointer hover:bg-raised/50")}>
<input id={id} type="checkbox" className="size-4 shrink-0 accent-accent" disabled={!!blocked}
checked={!blocked && chosen.has(platform)} onChange={(e) => toggle(platform, e.target.checked)} />
<Icon size={16} className={blocked ? "text-fg-subtle" : "text-fg"} />
<span className="grid min-w-0">
<span className={cx("text-sm font-medium", blocked ? "text-fg-subtle" : "text-fg")}>{PLATFORM_META[platform].label}</span>
<span className="text-xs text-fg-subtle">{note}</span>
</span>
</label>
</li>
);
})}
</ul>
{networks.every((n) => n.blocked) && (
<p className="text-xs leading-relaxed text-warning">
Nenhuma rede deste canal pode receber agora. Conecte em <TextLink href="/accounts">Canais de publicação</TextLink>.
</p>
)}
</fieldset>
<ChoiceGroup name={`quando-${clip.id}`} legend="Quando sai" value={timing} onChange={setTiming} options={[
{ value: "now", label: "Agora", hint: "no próximo ciclo (até 20 s)" },
{ value: "best_slot", label: "No próximo horário bom", hint: "respeita o limite por dia" },
]} />
</>
)}
<div aria-live="assertive" className="empty:hidden">{error && <Feedback ok={false}>{error}</Feedback>}</div>
</div>
</Dialog>
);
}
+182
View File
@@ -0,0 +1,182 @@
"use client";
// Canais do Clipador: cadastrar pelo link do canal, ligar o monitor (grava sozinho quando entra ao
// vivo), marcar se o streamer autorizou os cortes, checar agora, renomear e remover.
import Link from "next/link";
import { useState, type FormEvent } from "react";
import { PLATFORM_LABEL, clipperCall, useClipperAction, type ClipperChannel, type ClipperSession } from "./clipper-client";
import { ChannelEmotes } from "./clipper-games";
import { PlatformIcon } from "./clipper-sessions";
import { AlertIcon, BroadcastIcon, CheckIcon, PenIcon, PlusIcon, RefreshIcon, SettingsIcon, TrashIcon, UsersIcon } from "./icons";
import { Badge, Button, Card, EmptyState, Feedback, Field, Input, Spinner, Switch, formatRelative } from "./ui";
import { askConfirm } from "./confirm-dialog";
export type ChannelAccounts = Record<string, { id: string; name: string }[]>;
export function ChannelAddForm({ onChanged, disabled }: { onChanged: () => void; disabled: boolean }) {
const { pending, message, run } = useClipperAction(onChanged);
const [monitor, setMonitor] = useState(true);
const [authorized, setAuthorized] = useState(false);
const [formKey, setFormKey] = useState(0);
async function submit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
const form = new FormData(e.currentTarget);
const displayName = String(form.get("displayName") ?? "").trim();
const done = await run("add", () => clipperCall<ClipperChannel>("channels", "POST", {
url: String(form.get("url") ?? "").trim(), ...(displayName ? { displayName } : {}), monitor, authorized,
}), (c) => `Fonte “${c.displayName || c.channel}” adicionada${c.monitor ? " e monitorada" : ""}.`);
if (done) { setFormKey((k) => k + 1); setAuthorized(false); }
}
return (
<Card eyebrow={<><PlusIcon size={13} />Nova fonte</>} title="Adicionar fonte"
description="Link do perfil do streamer (não de um vídeo): twitch.tv/nome, kick.com/nome ou youtube.com/@nome.">
<form key={formKey} onSubmit={submit} className="grid gap-4">
<div className="grid gap-4 md:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
<Field label="Link da fonte">
<Input name="url" type="url" required disabled={disabled} placeholder="https://www.twitch.tv/nome" />
</Field>
<Field label="Nome para mostrar (opcional)">
<Input name="displayName" maxLength={60} disabled={disabled} placeholder="Ex.: Alanzoka" />
</Field>
</div>
<div className="grid gap-4 md:grid-cols-2">
<Switch label="Monitorar" checked={monitor} onChange={setMonitor} disabled={disabled}
hint="Checa de minuto em minuto e grava sozinho quando a fonte entra ao vivo." />
<Switch label="O streamer autorizou cortes" checked={authorized} onChange={setAuthorized} disabled={disabled}
hint="Cortar live de terceiros sem autorização pode render strike de direitos autorais." />
</div>
<div className="flex flex-wrap items-center gap-3">
<Button disabled={disabled || pending !== null}>{pending === "add" ? <Spinner /> : <PlusIcon size={16} />}Adicionar fonte</Button>
</div>
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</form>
</Card>
);
}
export function ChannelList({ channels, accounts, onChanged, onConfigure, showEmotes }: {
channels: ClipperChannel[]; accounts: ChannelAccounts; onChanged: () => void;
/** Abre a "Configuração do corte" com o padrão do canal. */
onConfigure: (channel: ClipperChannel) => void;
/** O serviço novo (fase 2) tem a tabela de emotes. */
showEmotes: boolean;
}) {
if (channels.length === 0) {
return (
<EmptyState compact icon={<BroadcastIcon size={18} />} title="Nenhuma fonte cadastrada">
Adicione uma fonte acima. Com o monitor ligado, o Clipador grava sozinho sempre que ela entrar ao vivo.
</EmptyState>
);
}
return (
<ul className="grid divide-y divide-line overflow-hidden rounded-card border border-line bg-surface shadow-card">
{channels.map((c) => <li key={c.id}><ChannelRow channel={c} accounts={accounts[c.id] ?? []} onChanged={onChanged} onConfigure={onConfigure} showEmotes={showEmotes} /></li>)}
</ul>
);
}
function ChannelRow({ channel: c, accounts, onChanged, onConfigure, showEmotes }: {
channel: ClipperChannel; accounts: { id: string; name: string }[]; onChanged: () => void;
onConfigure: (channel: ClipperChannel) => void; showEmotes: boolean;
}) {
const { pending, message, setMessage, run } = useClipperAction(onChanged);
const [renaming, setRenaming] = useState(false);
const [checked, setChecked] = useState<{ live: boolean; title: string } | null>(null);
const base = `channels/${encodeURIComponent(c.id)}`;
const name = c.displayName || c.channel;
const isLive = checked ? checked.live : c.lastStatus === "ao vivo";
const patch = (key: string, body: Partial<Pick<ClipperChannel, "displayName" | "monitor" | "authorized">>, text: string) =>
run(key, () => clipperCall<ClipperChannel>(base, "PATCH", body), text);
async function check() {
setChecked(null);
const r = await run("check", () => clipperCall<{ live: boolean; title: string }>(`${base}/check`, "POST"),
(d) => d.live ? `Ao vivo agora${d.title ? `: ${d.title}` : "."}` : "Offline agora.");
if (r) setChecked(r);
}
return (
<div className="grid gap-3 px-5 py-4">
<div className="flex flex-wrap items-center gap-x-4 gap-y-3">
<span className="grid size-10 shrink-0 place-items-center rounded-control border border-line-strong bg-raised text-fg-muted">
<PlatformIcon platform={c.platform} size={19} />
</span>
<div className="grid min-w-44 flex-1 gap-1">
{renaming ? (
<form className="flex flex-wrap items-center gap-2" onSubmit={async (e) => {
e.preventDefault();
const displayName = String(new FormData(e.currentTarget).get("displayName") ?? "").trim();
if (await patch("rename", { displayName }, "Nome atualizado.")) setRenaming(false);
}}>
<Input name="displayName" defaultValue={c.displayName} maxLength={60} autoFocus aria-label={`Nome da fonte ${c.channel}`} className="h-8 max-w-60" />
<Button size="sm" variant="secondary" disabled={pending !== null}>{pending === "rename" ? <Spinner className="size-3.5" /> : <CheckIcon size={15} />}Salvar</Button>
<Button type="button" size="sm" variant="ghost" onClick={() => setRenaming(false)}>Cancelar</Button>
</form>
) : (
<p className="flex flex-wrap items-center gap-2">
<span className="font-semibold text-fg">{name}</span>
<button type="button" onClick={() => { setRenaming(true); setMessage(null); }} aria-label={`Renomear ${name}`}
className="grid size-6 place-items-center rounded text-fg-subtle hover:bg-raised hover:text-fg focus-visible:outline-2 focus-visible:outline-accent">
<PenIcon size={13} />
</button>
{isLive ? <Badge tone="danger" pulse>ao vivo</Badge> : c.lastStatus === "offline" || checked ? <Badge>offline</Badge> : null}
{c.authorized
? <Badge tone="success">autorizado</Badge>
: <Badge tone="warning" dot={false}><AlertIcon size={12} />sem autorização · risco de strike</Badge>}
</p>
)}
<p className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-fg-subtle">
<span>{PLATFORM_LABEL[c.platform]}</span>
<a href={c.url} target="_blank" rel="noreferrer noopener" className="hover:text-fg hover:underline">{c.url.replace(/^https?:\/\/(www\.)?/, "")}</a>
<span>{c.lastCheckAt ? `checado ${formatRelative(c.lastCheckAt)}` : "nunca checado"}</span>
{accounts.length > 0 && (
<span className="inline-flex flex-wrap items-center gap-1.5">
<UsersIcon size={13} />
<span className="sr-only">Publicada pelos canais:</span>
{accounts.map((a, i) => (
<span key={a.id}>
<Link href={`/accounts?account=${encodeURIComponent(a.id)}`} className="text-fg-muted hover:text-fg hover:underline">{a.name}</Link>
{i < accounts.length - 1 ? "," : ""}
</span>
))}
</span>
)}
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
<Button variant="ghost" size="sm" onClick={() => onConfigure(c)}><SettingsIcon size={15} />Padrão da fonte</Button>
<Button variant="secondary" size="sm" disabled={pending !== null} onClick={() => void check()}>
{pending === "check" ? <><Spinner className="size-3.5" />Checando…</> : <><RefreshIcon size={15} />Checar agora</>}
</Button>
{isLive && checked?.live && (
<Button size="sm" disabled={pending !== null}
onClick={() => void run("record", () => clipperCall<ClipperSession>("sessions", "POST", { url: c.url }), (s) => `Gravando: sessão #${s.id}.`)}>
{pending === "record" ? <Spinner className="size-3.5" /> : <BroadcastIcon size={15} />}Gravar agora
</Button>
)}
<Button variant="ghost" size="sm" disabled={pending !== null} aria-label={`Remover a fonte ${name}`}
onClick={async () => {
if (!(await askConfirm({ title: `Remover a fonte “${name}”?`,
message: "Ela deixa de ser monitorada. Sessões e cortes já gravados continuam.",
confirmLabel: "Remover fonte", tone: "danger" }))) return;
void run("delete", () => clipperCall(base, "DELETE"), "Fonte removida.");
}}>
{pending === "delete" ? <Spinner className="size-3.5" /> : <TrashIcon size={15} />}Remover
</Button>
</div>
</div>
<div className="flex flex-wrap gap-x-8 gap-y-3 sm:pl-14">
<Switch label="Monitorar" checked={c.monitor} busy={pending === "monitor"} disabled={pending !== null}
onChange={(v) => void patch("monitor", { monitor: v }, v ? "Monitor ligado: grava sozinho quando entrar ao vivo." : "Monitor desligado.")}
hint="Grava sozinho quando entra ao vivo" />
<Switch label="Autorizou cortes" checked={c.authorized} busy={pending === "authorized"} disabled={pending !== null}
onChange={(v) => void patch("authorized", { authorized: v }, v ? "Marcado como autorizado." : "Autorização desmarcada.")}
hint="O streamer permitiu publicar cortes" />
</div>
{showEmotes && <div className="sm:pl-12"><ChannelEmotes channelKey={c.id} /></div>}
<div aria-live="polite" className="empty:hidden sm:pl-14">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</div>
);
}
+524
View File
@@ -0,0 +1,524 @@
// Cliente do Clipador no navegador: tipos do contrato de /api/clipper/* (repassado a /v1/* do serviço
// Python em 127.0.0.1:4520), rótulos, formatação e o gancho de ações com retorno. Não importa de
// lib/clipper.ts, que roda só no servidor.
import { useCallback, useState } from "react";
import { apiCall, type ApiResult } from "./api-client";
import type { Tone } from "./ui";
export type ClipperPlatform = "twitch" | "youtube" | "kick";
export type JudgeProvider = "codex" | "claude" | "off";
export type ClipperStatus = {
version: string;
tools: { streamlink: string | null; ffmpeg: string | null };
voice: { configured: boolean; online: boolean };
judge: { provider: JudgeProvider; model: string; available: boolean; path: string | null; minScore: number };
recording: number;
settings: { quality: string; segmentS: number; pollS: number; keepHours: number; language: string };
};
export type JudgeModel = { id: string; label: string; description?: string };
/** `faceTrack` é opcional: o serviço antigo (antes do rastreio de reação) não manda. */
export type JudgeOptions = { scanEnabled: boolean; scanIntervalS: number; vision: boolean; camDetect: boolean; faceTrack?: boolean };
export type JudgeConfig = {
provider: JudgeProvider;
/** Modelo do EDITOR (2º juiz). null com o juiz desligado. */
model: string | null;
/** Modelo do ANALISTA (1º juiz, vê os frames); vem resolvido (igual ao editor quando não há um próprio). */
analystModel?: string | null;
available: boolean | null;
path: string | null;
minScore: number;
options?: JudgeOptions;
lastScanError?: string | null;
models: { codex: JudgeModel[]; claude: JudgeModel[]; defaults: { codex: string; claude: string } };
};
export type ClipperChannel = {
id: string;
platform: ClipperPlatform;
channel: string;
url: string;
displayName: string;
monitor: boolean;
authorized: boolean;
lastCheckAt: string | null;
lastStatus: "ao vivo" | "offline" | "";
createdAt: string;
};
export type SessionStatus = "starting" | "recording" | "processing" | "done" | "stopped" | "error" | "interrupted";
export type ClipStatus = "candidate" | "pending" | "rendering" | "ready" | "approved" | "rejected" | "discarded" | "published" | "error";
export type ClipperSession = {
id: number;
channelId: string | null;
platform: ClipperPlatform;
kind: "live" | "vod";
url: string;
title: string;
status: SessionStatus;
/** "connected" | "connecting" | "unsupported" | "off" | "error: …" */
chatStatus: string;
chatMessages: number;
durationS: number;
startedAt: string;
endedAt: string | null;
error: string | null;
segments: { total: number; analyzed: number; transcriptErrors: number };
clips: Partial<Record<ClipStatus, number>>;
// Fase 2 (opcionais: o serviço antigo não manda).
game?: string;
gameSource?: GameSource;
/** O que a IA viu na tela; pode divergir da categoria da plataforma. */
screenGame?: string;
gameHistory?: { game: string; source: GameSource; atS: number; at: string }[];
gameProfileReady?: boolean;
/** Até onde (s) a varredura da IA já assistiu. */
scannedUntilS?: number;
memory?: MemoryEntry[];
camDetect?: CamDetect | null;
roomId?: string | null;
hasOwnSettings?: boolean;
/** O que a captura gravou de fato (1º bloco de cada execução). null = sessão antiga ou ainda sem bloco; ausente = serviço antigo. */
capture?: CaptureInfo | null;
};
export type GameSource = "platform" | "screen" | "user" | "";
export type MemoryEntry = { fromS: number; toS: number; summary: string };
export type CamDetect = {
hasWebcam: boolean; cam: Rect | null; gameOnScreen?: boolean; frame?: string; at?: string;
/** Quem achou: yunet = local (rosto no quadro, sem IA) · ai = IA olhando quadros · manual = você marcou. */
source?: "yunet" | "ai" | "manual";
confidence?: number; fullFrame?: boolean;
};
/** Reação no rosto do streamer (rastreio local, reaction.py): pico, início e intensidade (z relativo ao normal dele). */
export type FaceReaction = {
peakS: number; onsetS: number; endS: number; intensity: number; strong: boolean;
label: "risada" | "grito" | "susto" | "choque" | "confuso" | "raiva" | "neutro";
};
export type Situation = "lag_ou_bug" | "jogada" | "falha_engracada" | "morte" | "susto" | "treta" | "conversa_engracada"
| "historia" | "informacao_do_jogo" | "reacao" | "outro";
/** O que o ANALISTA (1º juiz) viu: tela + fala + chat. */
export type ClipAnalysis = {
situation: string;
what_happened: string;
screen: string;
speech: string;
chat_meaning: string;
/** 0–1 */
confidence: number;
action_start_s: number;
reaction_end_s: number;
hook: string;
};
export type ClipJudge = null
| { model: string; keep: boolean; score: number; reason: string; analysis?: ClipAnalysis | null; analystModel?: string }
| { error: string };
export type ClipTags = { risada?: number; susto?: number; hype?: number; clip?: number };
export type Clip = {
id: number;
sessionId: number;
peakS: number;
startS: number;
endS: number;
durationS: number;
score: number;
source: "chat" | "audio" | "manual" | "ai" | "face";
reasons: {
peakRatio?: number; messages?: number; tags?: ClipTags; topMessages?: string[];
/** Emotes do chat no pico: nome → quantidade. */
emotes?: Record<string, number>;
// Cortes da varredura da IA (source "ai").
proposalTitle?: string; proposalScore?: number; proposalReason?: string; scanFromS?: number; scanToS?: number;
/** Reação no rosto do streamer dentro do trecho (opcional: só com câmera e rastreio ligado). */
face?: FaceReaction;
/** Corte de fonte "face": o apoio do áudio (sinal suavizado) e do chat (mensagens de reação) que deixou o rosto virar corte. */
support?: { audioZ: number; chatReactions: number };
};
judge: ClipJudge;
title: string;
caption: string;
transcript: string;
status: ClipStatus;
file: string | null;
thumb: string | null;
error: string | null;
createdAt: string;
updatedAt: string;
channelId: string | null;
platform: ClipperPlatform;
sessionUrl: string;
/** Editor de cortes: há projeto de edição (o render usa ele); capa gerada no export. Opcional: serviço antigo não manda. */
edit?: { updatedAt: string; exportedAt: string | null; cover: string | null; origin?: "ai" | "user" | null } | null;
/** Formato do vídeo renderizado. Opcional: o serviço antigo não manda (ausente = vertical). */
aspect?: Aspect;
};
/* ---------- Configuração do corte ---------- */
/** Retângulo normalizado (0–1) sobre o quadro original 16:9; x, y = canto superior esquerdo. */
export type Rect = { x: number; y: number; w: number; h: number };
export type LayoutMode = "auto" | "blur" | "cam_top" | "game_only" | "cam_only";
/** Formato do corte: vertical = 1080×1920 (Shorts/Reels/TikTok); horizontal = 1920×1080 (YouTube, jogo em tela cheia). */
export type Aspect = "vertical" | "horizontal";
export type CutSettings = {
layout: { mode: LayoutMode; cam: Rect | null; game: Rect | null; camHeight: number };
caption: {
enabled: boolean; font: string; size: number; color: string; highlight: string; outline: string;
outlineWidth: number; y: number | null; uppercase: boolean; maxWords: number;
};
credit: { enabled: boolean; position: "top" | "bottom"; size: number };
duration: { minS: number; maxS: number; backtrackS: number };
/** O serviço antigo não manda este grupo: use `withFormat` para preencher com vertical. */
format: { aspect: Aspect };
/** Estilo do gancho que o projeto da IA põe no começo. Opcional: o serviço antigo não manda (use `hookOf`). */
hook?: HookSettings;
/** Qualidade de gravação da live (vale na próxima gravação ou retomada). Opcional: o serviço antigo não manda. */
capture?: { quality: CaptureQuality };
};
/** Camada parcial (canal ou sessão): só o que ela fixa. */
export type CutLayer = { [G in keyof CutSettings]?: Partial<CutSettings[G]> };
export type SettingsPayload = {
own: CutLayer;
effective: CutSettings;
defaults: CutSettings;
modes: LayoutMode[];
fonts: string[];
/** Só nas configurações da sessão: a camada do canal (null se a sessão não tem canal). */
channel?: CutLayer | null;
// Opcionais (o serviço antigo não manda): formatos, fontes empacotadas e opções do gancho.
aspects?: Aspect[];
/** {família: "assets/fonts/….ttf"} das fontes empacotadas, relativo à raiz do repositório. */
fontFiles?: Record<string, string>;
hookStyles?: HookStyle[];
hookAnims?: HookAnim[];
/** Tamanho do vídeo e quadro lógico dos textos (ASS) de cada formato. */
frames?: Record<Aspect, FrameSize>;
/** Opções de qualidade de gravação, com o disco por hora medido (serviço antigo não manda). */
captureQualities?: CaptureOption[];
};
export type FrameResult = { t: number; file: string; version: string };
export type PreviewResult = { t: number; file: string; mode: LayoutMode; version: string; aspect?: Aspect };
/** Formato de um corte ou configuração; ausente (serviço antigo) = vertical. */
export function aspectOf(value: { aspect?: Aspect | null } | null | undefined): Aspect {
return value?.aspect === "horizontal" ? "horizontal" : "vertical";
}
/** Completa uma configuração vinda do serviço antigo (sem o grupo `format`) com o formato vertical. */
export function withFormat(settings: CutSettings): CutSettings {
return { ...settings, format: { aspect: aspectOf(settings.format) } };
}
/** Mescla campo a campo: base ← camadas (igual ao serviço). */
export function mergeSettings(base: CutSettings, ...layers: (CutLayer | null | undefined)[]): CutSettings {
const out = structuredClone(base);
for (const layer of layers) {
if (!layer) continue;
for (const group of new Set([...Object.keys(out), "format"]) as Set<keyof CutSettings>) {
const values = layer[group];
// Grupo que a base não tem (ex.: `format` com o serviço antigo): cria em vez de quebrar.
if (values) (out as Record<string, unknown>)[group] = { ...(out[group] ?? {}), ...values };
}
}
return out;
}
/**
* Camada mínima para salvar: campos que diferem da base de baixo, mais os que a camada já fixava
* (para não "soltar" um valor que o usuário fixou de propósito, mesmo igual ao herdado).
*/
export function layerFrom(draft: CutSettings, base: CutSettings, own: CutLayer | null | undefined): CutLayer {
const out: Record<string, Record<string, unknown>> = {};
for (const group of Object.keys(draft) as (keyof CutSettings)[]) {
const values = (draft[group] ?? {}) as Record<string, unknown>;
const under = (base[group] ?? {}) as Record<string, unknown>;
const pinned = (own?.[group] ?? {}) as Record<string, unknown>;
for (const key of Object.keys(values)) {
if (key in pinned || JSON.stringify(values[key]) !== JSON.stringify(under[key])) (out[group] ??= {})[key] = values[key];
}
}
return out as CutLayer;
}
/* ---------- Jogos e emotes ---------- */
export type GameProfile = {
name: string; summary: string; genre: string;
mechanics: string[]; clip_worthy: string[]; avoid: string[]; jargon: string[]; news: string[]; sources: string[];
/** Hashtags do jogo (a 1ª é a principal): entram em toda legenda de corte deste jogo, depois da do canal. */
hashtags?: string[];
};
export type Game = {
id: string; name: string; status: "pending" | "ready" | "error"; error: string | null;
model: string | null; researchedAt: string | null; profile: GameProfile | null;
/** Última edição à mão ou por pedido seu à IA (serviço antigo não manda). */
editedAt?: string | null;
/** Pedidos que você fez à IA; voltam em toda pesquisa nova. */
notes?: { text: string; at: string; section?: string }[];
};
export type Emote = { name: string; source: string; uses: number; weight: number; lastSeen: string | null };
/** Id do jogo no serviço (mesma regra de intel.game_id). */
export function gameIdOf(name: string): string {
return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "desconhecido";
}
/** Chave do canal para os emotes: "<plataforma>-<login>" (ex.: twitch-skipnho). */
export function channelKeyOf(session: Pick<ClipperSession, "channelId" | "platform" | "url">): string {
if (session.channelId) return session.channelId;
const login = channelFromUrl(session.url).replace(/^@/, "").toLowerCase();
return login ? `${session.platform}-${login}` : "";
}
export type Timeline = { durationS: number; messagesPerS: number[]; ratio: number[]; loudnessDb: (number | null)[] };
/* ---------- Chamadas ---------- */
/** Chama /api/clipper/<path>. O erro do serviço ({error}) vira a mensagem. */
export function clipperCall<T>(path: string, method: "GET" | "POST" | "PATCH" | "PUT" | "DELETE" = "GET", body?: unknown): Promise<ApiResult<T>> {
return apiCall<T>(`/api/clipper/${path}`, method, body);
}
/** O painel responde "Clipador fora do ar…" (ou "não instalado") quando não alcança o serviço. */
export function isOfflineError(message: string): boolean {
return /fora do ar|não instalado/i.test(message);
}
export type ActionMessage = { ok: boolean; text: string } | null;
/**
* Ações com retorno: guarda qual está rodando (para o spinner certo), mostra sucesso/erro e,
* se deu certo, chama `onDone` (normalmente recarregar os dados).
*/
export function useClipperAction(onDone?: () => void) {
const [pending, setPending] = useState<string | null>(null);
const [message, setMessage] = useState<ActionMessage>(null);
const run = useCallback(async <T,>(key: string, call: () => Promise<ApiResult<T>>, success: string | ((data: T) => string)) => {
setPending(key);
setMessage(null);
const result = await call();
setPending(null);
if (!result.ok) {
setMessage({ ok: false, text: result.error });
return null;
}
setMessage({ ok: true, text: typeof success === "function" ? success(result.data) : success });
onDone?.();
return result.data;
}, [onDone]);
return { pending, message, setMessage, run };
}
/* ---------- Rótulos ---------- */
export const PLATFORM_LABEL: Record<ClipperPlatform, string> = { twitch: "Twitch", youtube: "YouTube", kick: "Kick" };
export const SESSION_STATUS: Record<SessionStatus, { label: string; tone: Tone; pulse?: boolean }> = {
starting: { label: "iniciando", tone: "info", pulse: true },
recording: { label: "gravando", tone: "danger", pulse: true },
processing: { label: "processando", tone: "info", pulse: true },
done: { label: "concluída", tone: "success" },
stopped: { label: "parada", tone: "neutral" },
error: { label: "erro", tone: "danger" },
interrupted: { label: "interrompida", tone: "warning" },
};
export const CLIP_STATUS: Record<ClipStatus, { label: string; tone: Tone; pulse?: boolean }> = {
candidate: { label: "esperando a IA", tone: "violet", pulse: true },
pending: { label: "na fila de render", tone: "info" },
rendering: { label: "renderizando", tone: "info", pulse: true },
ready: { label: "pronto para aprovar", tone: "accent" },
approved: { label: "aprovado", tone: "success" },
rejected: { label: "rejeitado", tone: "neutral" },
discarded: { label: "descartado pela IA", tone: "warning" },
published: { label: "publicado", tone: "success" },
error: { label: "erro", tone: "danger" },
};
export const CLIP_STATUS_ORDER: ClipStatus[] = ["candidate", "pending", "rendering", "ready", "approved", "published", "rejected", "discarded", "error"];
export const SOURCE_LABEL: Record<Clip["source"], string> = {
chat: "pico do chat", audio: "pico do áudio", manual: "corte manual", ai: "IA viu na tela", face: "reação no rosto",
};
export const FACE_LABEL: Record<FaceReaction["label"], string> = {
risada: "risada", grito: "grito", susto: "susto", choque: "choque", confuso: "confuso", raiva: "raiva", neutro: "neutro",
};
export const SITUATION_LABEL: Record<Situation, string> = {
lag_ou_bug: "lag ou bug", jogada: "jogada", falha_engracada: "falha engraçada", morte: "morte", susto: "susto", treta: "treta",
conversa_engracada: "conversa engraçada", historia: "história", informacao_do_jogo: "informação do jogo", reacao: "reação", outro: "outro",
};
export const GAME_SOURCE_LABEL: Record<GameSource, string> = {
platform: "categoria da plataforma", screen: "a IA viu na tela", user: "confirmado por você", "": "",
};
export const MODE_LABEL: Record<LayoutMode, { label: string; hint: string }> = {
auto: { label: "Automático", hint: "câmera em cima se houver" },
cam_top: { label: "Câmera em cima", hint: "webcam + jogo" },
blur: { label: "Desfoque", hint: "vídeo inteiro" },
game_only: { label: "Só o jogo", hint: "recorta o jogo" },
cam_only: { label: "Câmera inteira", hint: "só o streamer" },
};
export const TAG_LABEL: Record<keyof ClipTags, string> = { risada: "risada", susto: "susto", hype: "hype", clip: "“clip” no chat" };
export const PROVIDER_LABEL: Record<JudgeProvider, string> = { codex: "Codex (GPT)", claude: "Claude", off: "Desligado" };
/** Sessões que ainda mudam sozinhas (vale consultar de novo). */
export const ACTIVE_SESSION: SessionStatus[] = ["starting", "recording", "processing"];
/** Cortes que ainda mudam sozinhos (IA ou render). */
export const ACTIVE_CLIP: ClipStatus[] = ["candidate", "pending", "rendering"];
export function chatStatusInfo(status: string): { label: string; tone: Tone } {
if (status === "connected") return { label: "chat conectado", tone: "success" };
if (status === "connecting") return { label: "conectando ao chat", tone: "info" };
if (status === "unsupported") return { label: "sem chat (plataforma)", tone: "neutral" };
if (status === "off" || status === "") return { label: "chat desligado", tone: "neutral" };
return { label: "erro no chat", tone: "danger" };
}
/* ---------- Formatação ---------- */
/** Relógio "m:ss" ou "h:mm:ss". */
export function formatClock(seconds: number): string {
const total = Math.max(0, Math.round(seconds));
const h = Math.floor(total / 3600);
const m = Math.floor((total % 3600) / 60);
const s = String(total % 60).padStart(2, "0");
return h > 0 ? `${h}:${String(m).padStart(2, "0")}:${s}` : `${m}:${s}`;
}
/** Duração curta: "42 s", "4 min 30 s", "1 h 05 min". */
export function formatDuration(seconds: number): string {
const total = Math.max(0, Math.round(seconds));
if (total < 60) return `${total} s`;
const h = Math.floor(total / 3600);
const m = Math.floor((total % 3600) / 60);
if (h > 0) return `${h} h ${String(m).padStart(2, "0")} min`;
const s = total % 60;
return s ? `${m} min ${s} s` : `${m} min`;
}
export function formatScore(score: number): string {
return score.toLocaleString("pt-BR", { maximumFractionDigits: 1 });
}
/** Nome do canal a partir do link da live/VOD (twitch.tv/<canal>, kick.com/<canal>, youtube.com/@canal). */
export function channelFromUrl(url: string): string {
try {
const u = new URL(url);
const first = u.pathname.split("/").filter(Boolean)[0] ?? "";
if (u.hostname.includes("youtu")) return first.startsWith("@") ? first : u.hostname.replace(/^www\./, "");
return first === "videos" ? u.hostname.replace(/^www\./, "") : first || u.hostname;
} catch {
return url;
}
}
/** Rótulo de quem é a live: o nome do canal cadastrado ou o que dá para tirar do link. */
export function sourceName(channelId: string | null, url: string, channels: ClipperChannel[]): string {
const channel = channelId ? channels.find((c) => c.id === channelId) : undefined;
return channel?.displayName || channel?.channel || channelFromUrl(url);
}
/* ---------- Gancho, fontes e formatos (editor de cortes e "Configuração do corte") ---------- */
/** `plain` = texto solto (com caixa opcional); `banner` = tarja na largura toda, texto em maiúsculas em até 2 linhas. */
export type HookStyle = "plain" | "banner";
/** `slide`: a tarja atravessa a tela e o texto entra deslizando, borrado, e assenta nítido. */
export type HookAnim = "pop" | "fade" | "none" | "slide";
export type HookSettings = { style: HookStyle; bg: string; color: string; font: string; anim: HookAnim; seconds: number };
/** Tamanho do vídeo de saída e quadro lógico do ASS (no horizontal os textos são contados em 2560×1440). */
export type FrameSize = { width: number; height: number; canvasWidth: number; canvasHeight: number };
/** Espelho de `layout.DEFAULTS["hook"]` do serviço, só para quando ele não manda o grupo (serviço antigo). */
export const HOOK_FALLBACK: HookSettings = { style: "banner", bg: "#00FF00", color: "#FFFFFF", font: "Luckiest Guy", anim: "slide", seconds: 3 };
/** Grupo `hook` efetivo (o serviço antigo não manda: usa o espelho do padrão). */
export function hookOf(settings: Pick<CutSettings, "hook"> | null | undefined): HookSettings {
return { ...HOOK_FALLBACK, ...(settings?.hook ?? {}) };
}
export const HOOK_STYLE_LABEL: Record<HookStyle, { label: string; hint: string }> = {
banner: { label: "Tarja", hint: "faixa colorida na largura toda" },
plain: { label: "Simples", hint: "texto solto, com caixa opcional" },
};
export const HOOK_ANIM_LABEL: Record<HookAnim, string> = {
slide: "Deslizar com desfoque", pop: "Entrada pop", fade: "Aparecer suave", none: "Sem animação",
};
/** Fontes do Windows que o serviço sempre aceita (as empacotadas vêm de `fontFiles`). */
export const SYSTEM_FONTS = ["Arial Black", "Arial", "Impact", "Verdana", "Segoe UI Black", "Trebuchet MS"];
/* ---------- Qualidade de gravação (grupo `capture`) ---------- */
/** `best` = a maior resolução que a live oferece; as outras são teto (a maior variante que não passa dele). */
export type CaptureQuality = "best" | "1440p" | "1080p" | "720p" | "480p";
/** Uma opção do seletor, como o serviço manda em `captureQualities`. */
export type CaptureOption = {
id: CaptureQuality; label: string; maxHeight: number | null; gbPerHour: number; gbPerHourMax: number; hint: string;
};
/** Resolução, fps, codec e taxa lidos do 1º bloco da gravação (ffprobe). `mixed` = blocos em mais de uma resolução. */
export type CaptureInfo = {
quality: CaptureQuality; width: number; height: number; fps: number | null; codec: string;
kbps: number | null; gbPerHour: number | null; fromIdx: number; at: string; mixed: boolean;
runs?: { fromIdx: number; quality: CaptureQuality; width: number; height: number; fps: number | null; codec: string }[];
};
/** "2560×1440 · 60 fps". */
export function captureLabel(info: Pick<CaptureInfo, "width" | "height" | "fps">): string {
return `${info.width}×${info.height}${info.fps ? ` · ${info.fps} fps` : ""}`;
}
/** "3,2 GB/h" (ou "3,2–4,5 GB/h" quando a opção tem faixa). */
export function gbPerHourLabel(min: number, max?: number | null): string {
const f = (v: number) => v.toLocaleString("pt-BR", { maximumFractionDigits: v < 1 ? 2 : 1 });
return max && max - min >= 0.2 ? `${f(min)}–${f(max)} GB/h` : `${f(min)} GB/h`;
}
/* ---------- Apagar cortes (DELETE clips/<id> · POST clips/delete) ---------- */
/** Por que um corte não foi apagado. `busy_*` = o motor está mexendo nele; `published` = falta confirmar. */
export type ClipDeleteCode = "not_found" | "busy_candidate" | "busy_rendering" | "published" | "changed";
/** Arquivo que ficou no disco (fora das pastas do Clipador, ou em uso). */
export type ClipLeftFile = { file: string; reason: string };
export type ClipDeleted = { id: number; sessionId: number; status: ClipStatus; removedFiles: number; left: ClipLeftFile[] };
export type ClipDeleteFailure = { id: number; code: ClipDeleteCode; reason: string };
/** Resposta do lote: `remaining` = quantos passaram do limite de uma chamada (500). */
export type ClipDeleteResult = { requested: number; remaining: number; deleted: ClipDeleted[]; failed: ClipDeleteFailure[] };
/** Máximo de cortes numa chamada de lote (`clip_delete.MAX_BATCH` do serviço). */
export const CLIP_DELETE_MAX = 500;
/** Estados que o serviço recusa apagar (a IA ou o render está trabalhando no corte). */
export const UNDELETABLE_CLIP: ClipStatus[] = ["candidate", "rendering"];
/** "12 apagados, 1 não pôde: está renderizando" (motivos iguais agrupados). */
export function deleteSummary(result: Pick<ClipDeleteResult, "deleted" | "failed">): string {
const n = result.deleted.length;
const parts = [n === 1 ? "1 corte apagado" : `${n} cortes apagados`];
if (result.failed.length) {
const reasons = new Map<string, number>();
for (const f of result.failed) reasons.set(f.reason, (reasons.get(f.reason) ?? 0) + 1);
const why = [...reasons].map(([reason, k]) => (reasons.size > 1 ? `${k} ${reason}` : reason)).join("; ");
parts.push(`${result.failed.length} não pôde${result.failed.length === 1 ? "" : "ram"}: ${why}`);
}
const left = result.deleted.reduce((sum, d) => sum + (d.left?.length ?? 0), 0); // resposta sem `left` = nada ficou
if (left) parts.push(`${left} arquivo${left === 1 ? " ficou" : "s ficaram"} no disco`);
return parts.join(", ");
}
File diff suppressed because it is too large Load Diff
+734
View File
@@ -0,0 +1,734 @@
"use client";
// Contexto do jogo e emotes do Clipador: o jogo da sessão (com correção à mão e aviso quando a tela
// diverge da categoria), o perfil que a IA pesquisou ("O que a IA sabe do jogo") e a tabela de emotes
// do canal com o peso que eles aprenderam com as suas aprovações.
import { useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react";
import {
GAME_SOURCE_LABEL, clipperCall, gameIdOf, useClipperAction, type ClipperSession, type Emote, type Game, type GameProfile,
} from "./clipper-client";
import type { ApiResult } from "./api-client";
import { AlertIcon, BookIcon, ChatIcon, CheckIcon, ChevronDownIcon, LinkIcon, PenIcon, RefreshIcon, SendIcon, SparkIcon, XIcon } from "./icons";
import {
Badge, Button, EmptyState, Feedback, Field, Input, Spinner, Switch, Table, Td, Th, THead, Textarea, Tr, cx, formatRelative, hueOf,
} from "./ui";
import { askConfirm } from "./confirm-dialog";
/* ---------- Jogo da sessão ---------- */
export function SessionGame({ session, games, onChanged, onGamesChanged }: {
session: ClipperSession; games: Game[]; onChanged: () => void; onGamesChanged: (games: Game[]) => void;
}) {
const { pending, message, run } = useClipperAction(onChanged);
const [choosing, setChoosing] = useState(false);
const [open, setOpen] = useState(false);
const game = session.game ?? "";
const screen = session.screenGame ?? "";
const confirmed = session.gameSource === "user";
const mismatch = Boolean(game && screen && !confirmed && gameIdOf(screen) !== gameIdOf(game));
const profile = game ? games.find((g) => g.id === gameIdOf(game)) : undefined;
/** Confirma o jogo: trava a troca automática e a IA deixa de questionar o que vê na tela. */
async function confirmGame(name: string) {
const ok = await run("game", () => clipperCall<ClipperSession>(`sessions/${session.id}/game`, "PUT", { name }),
`Jogo confirmado: “${name}”. A IA não questiona mais o jogo nesta sessão.`);
if (ok) setChoosing(false);
}
return (
<div className="grid gap-2">
<div className="flex flex-wrap items-center gap-x-3 gap-y-2 text-xs">
<span className="text-eyebrow font-semibold text-fg-subtle uppercase">Jogo</span>
<span className="text-sm font-medium text-fg">{game || <span className="text-fg-subtle">não identificado</span>}</span>
{session.gameSource && (
<Badge tone={confirmed ? "success" : "neutral"} dot={false}>
{confirmed && <CheckIcon size={12} />}{GAME_SOURCE_LABEL[session.gameSource]}
</Badge>
)}
{game && !confirmed && (
<Button variant="secondary" size="sm" disabled={pending !== null} onClick={() => void confirmGame(game)}>
{pending === "game" ? <Spinner className="size-3.5" /> : <CheckIcon size={14} />}Sim, é {game}
</Button>
)}
<Button variant="ghost" size="sm" onClick={() => setChoosing(true)}><PenIcon size={14} />{confirmed ? "Trocar jogo" : "Escolher o jogo"}</Button>
{game && (
<Button variant="ghost" size="sm" aria-expanded={open} onClick={() => setOpen((o) => !o)}>
<BookIcon size={14} />O que a IA sabe do jogo
{profile?.status === "pending" && <Spinner className="size-3" />}
<ChevronDownIcon size={14} className={cx("transition-transform", open && "rotate-180")} />
</Button>
)}
</div>
{mismatch && (
<div className="flex flex-wrap items-center gap-x-3 gap-y-2 rounded-control border border-warning/25 bg-warning-soft px-3 py-2 text-xs text-warning">
<AlertIcon size={14} />
<span className="min-w-0 flex-1">A categoria diz <strong>{game}</strong>, mas a tela parece <strong>{screen}</strong>. Jogo novo costuma lembrar outro na tela — qual é o certo?</span>
<Button size="sm" variant="secondary" disabled={pending !== null} onClick={() => void confirmGame(game)}>Sim, é {game}</Button>
<Button size="sm" variant="ghost" onClick={() => setChoosing(true)}>Escolher o jogo</Button>
</div>
)}
<GameChoiceDialog open={choosing} session={session} pending={pending === "game"}
onClose={() => setChoosing(false)} onConfirm={(name) => void confirmGame(name)} />
{open && game && (
<GameCard game={profile} name={game} onGamesChanged={onGamesChanged} />
)}
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</div>
);
}
/* ---------- Escolher/confirmar o jogo ---------- */
/** Modal nativo: o usuário confirma qual jogo está sendo jogado (categoria, o que a IA viu na tela ou outro nome). */
function GameChoiceDialog({ open, session, pending, onClose, onConfirm }: {
open: boolean; session: ClipperSession; pending: boolean; onClose: () => void; onConfirm: (name: string) => void;
}) {
const ref = useRef<HTMLDialogElement>(null);
const options = useMemo(() => {
const list: { name: string; from: string }[] = [];
const add = (name: string | undefined, from: string) => {
const clean = (name ?? "").trim();
if (clean && !list.some((o) => gameIdOf(o.name) === gameIdOf(clean))) list.push({ name: clean, from });
};
add(session.game, session.gameSource === "user" ? "confirmado por você" : "categoria da plataforma");
for (const h of [...(session.gameHistory ?? [])].reverse()) add(h.game, GAME_SOURCE_LABEL[h.source as keyof typeof GAME_SOURCE_LABEL] || "histórico");
add(session.screenGame, "a IA viu na tela");
return list;
}, [session]);
const [choice, setChoice] = useState(0);
const [other, setOther] = useState("");
useEffect(() => {
const dialog = ref.current;
if (!dialog) return;
if (open && !dialog.open) {
setChoice(0);
setOther("");
dialog.showModal();
}
if (!open && dialog.open) dialog.close();
}, [open]);
const chosen = choice === -1 ? other.trim() : options[choice]?.name ?? "";
return (
<dialog ref={ref} aria-labelledby={`game-choice-${session.id}`} onCancel={(e) => { e.preventDefault(); onClose(); }}
className="m-auto w-[min(92vw,30rem)] rounded-panel border border-line-strong bg-canvas p-0 text-fg shadow-pop backdrop:bg-black/70">
<form className="grid gap-4 p-5" onSubmit={(e) => { e.preventDefault(); if (chosen) onConfirm(chosen); }}>
<div className="grid gap-1">
<h2 id={`game-choice-${session.id}`} className="text-base font-semibold">Qual jogo está sendo jogado?</h2>
<p className="text-xs leading-relaxed text-fg-muted">
O jogo confirmado vai para a IA como certo: ela usa o perfil dele para entender os momentos e deixa de
questionar o que vê na tela. A troca automática pela categoria fica travada nesta sessão.
</p>
</div>
<fieldset className="grid gap-2">
<legend className="sr-only">Jogo</legend>
{options.map((o, i) => (
<label key={o.name} className={cx("flex cursor-pointer items-center gap-3 rounded-control border px-3 py-2.5 text-sm",
choice === i ? "border-accent/60 bg-accent-soft" : "border-line hover:border-line-strong")}>
<input type="radio" name="game" checked={choice === i} onChange={() => setChoice(i)} className="accent-[var(--color-accent)]" />
<span className="min-w-0 flex-1 font-medium">{o.name}</span>
<span className="text-xs text-fg-subtle">{o.from}</span>
</label>
))}
<label className={cx("flex cursor-pointer items-center gap-3 rounded-control border px-3 py-2.5 text-sm",
choice === -1 ? "border-accent/60 bg-accent-soft" : "border-line hover:border-line-strong")}>
<input type="radio" name="game" checked={choice === -1} onChange={() => setChoice(-1)} className="accent-[var(--color-accent)]" />
<span className="shrink-0">Outro:</span>
<Input value={other} maxLength={120} placeholder="nome do jogo" aria-label="Outro jogo" className="h-8 min-w-0 flex-1" size={10}
onFocus={() => setChoice(-1)} onChange={(e) => { setOther(e.target.value); setChoice(-1); }} />
</label>
</fieldset>
<div className="flex justify-end gap-2">
<Button type="button" variant="ghost" size="sm" onClick={onClose}>Cancelar</Button>
<Button type="submit" size="sm" disabled={!chosen || pending}>
{pending ? <Spinner className="size-3.5" /> : <CheckIcon size={15} />}Confirmar {chosen ? `“${chosen}”` : "jogo"}
</Button>
</div>
</form>
</dialog>
);
}
/* ---------- Perfil do jogo ---------- */
type GameAction = "research" | "save" | "note";
type GamesReply = { games: Game[] };
type RefineReply = GamesReply & { reply?: string };
type ListKey = Exclude<keyof GameProfile, "name" | "summary" | "genre">;
/** Seção que o chat da IA edita ("" = o perfil inteiro). */
type SectionKey = ListKey | "summary" | "";
/** Como cada seção aparece: cor, ícone, dica de edição e atalhos de pedido para o chat. */
const SECTIONS: Record<ListKey, { title: string; tone: "success" | "danger" | "info" | "violet" | "neutral"; hint: string; suggestions: string[] }> = {
clip_worthy: {
title: "O que rende corte", tone: "success", hint: "Uma situação por linha.",
suggestions: ["Reação do streamer conta (grito, risada, raiva)", "Momentos em que o chat explode de emotes", "Falha engraçada ou bug bizarro"],
},
avoid: {
title: "Evitar", tone: "danger", hint: "Uma situação por linha.",
suggestions: ["Tela de carregamento e fila", "Streamer lendo doação sem reação", "AFK ou pausa"],
},
mechanics: { title: "Mecânicas", tone: "info", hint: "Uma por linha.", suggestions: ["Explique melhor as mecânicas que aparecem nas lives", "Acrescente as mecânicas da última atualização"] },
news: { title: "Novidades", tone: "violet", hint: "Uma por linha, com mês/ano.", suggestions: ["Pesquise as novidades deste mês", "Tire as novidades com mais de 6 meses"] },
jargon: { title: "Gírias e termos", tone: "neutral", hint: "Um por linha.", suggestions: ["Acrescente as gírias que o chat usa", "Explique cada gíria em poucas palavras"] },
hashtags: {
title: "Hashtags", tone: "violet",
hint: "Uma por linha, a principal primeiro. As 3 primeiras entram em toda legenda de corte deste jogo, junto com a do canal e as do momento.",
suggestions: ["Pesquise as hashtags que o público usa para este jogo no TikTok", "Acrescente a hashtag do modo que o streamer joga"],
},
sources: { title: "Fontes", tone: "neutral", hint: "Uma URL por linha.", suggestions: [] },
};
const TONE_TEXT = { success: "text-success", danger: "text-danger", info: "text-info", violet: "text-violet", neutral: "text-fg-subtle" } as const;
const TONE_BAR = { success: "bg-success", danger: "bg-danger", info: "bg-info", violet: "bg-violet", neutral: "bg-line-strong" } as const;
/**
* Ações do perfil do jogo que não são o chat: pesquisar de novo, salvar a edição à mão, esquecer um pedido.
* Pesquisa pode levar minutos: se o painel desistir de esperar, o serviço segue.
*/
function useGameActions(onGamesChanged: (games: Game[]) => void) {
const [pending, setPending] = useState<GameAction | null>(null);
const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null);
async function run(action: GameAction, call: () => Promise<ApiResult<GamesReply>>, okText: string, slow = false) {
setPending(action);
setMessage(null);
const r = await call();
setPending(null);
if (r.ok) {
onGamesChanged(r.data.games);
setMessage({ ok: true, text: okText });
return true;
}
setMessage({ ok: false, text: slow ? `${r.error} Se demorou demais, a IA pode continuar no serviço: clique em Atualizar daqui a pouco.` : r.error });
if (slow) {
const list = await clipperCall<GamesReply>("games");
if (list.ok) onGamesChanged(list.data.games);
}
return false;
}
return { pending, message, run };
}
/** Iniciais do jogo para o selo: primeira e última palavra ("Call of Duty: Warzone" → "CW"). */
function monogram(title: string): string {
const words = title.replace(/[^\p{L}\p{N} ]/gu, " ").split(/\s+/).filter(Boolean);
if (words.length === 0) return "?";
return (words.length === 1 ? words[0].slice(0, 2) : words[0][0] + words[words.length - 1][0]).toUpperCase();
}
/** Itens que entraram/saíram numa lista (para destacar o que a IA acrescentou). */
function diffList(before: string[] = [], after: string[] = []) {
const had = new Set(before.map((s) => s.toLowerCase()));
const has = new Set(after.map((s) => s.toLowerCase()));
return { added: after.filter((s) => !had.has(s.toLowerCase())), removed: before.filter((s) => !has.has(s.toLowerCase())) };
}
export function GameCard({ game, name, onGamesChanged }: { game: Game | undefined; name: string; onGamesChanged: (games: Game[]) => void }) {
const { pending, message, run } = useGameActions(onGamesChanged);
const [editing, setEditing] = useState(false);
const [chatOpen, setChatOpen] = useState<SectionKey | null>(null);
const [chatBusy, setChatBusy] = useState(false);
const [fresh, setFresh] = useState<Set<string>>(new Set()); // itens que a IA acabou de acrescentar (destaque)
const id = game?.id ?? gameIdOf(name);
const path = `games/${encodeURIComponent(id)}`;
const busy = pending !== null || chatBusy || game?.status === "pending";
const title = game?.profile?.name || game?.name || name;
const hue = hueOf(title);
async function research() {
// Pesquisar refaz o perfil do zero: a edição à mão some; os pedidos guardados entram de novo na pesquisa.
if (game?.editedAt && !(await askConfirm({ title: "Pesquisar de novo?",
message: "Refaz o perfil do zero e apaga o que você editou à mão. Os pedidos que você fez à IA são aplicados de novo.",
confirmLabel: "Pesquisar de novo", tone: "danger" }))) return;
void run("research", () => clipperCall<GamesReply>(`${path}/research`, "POST"), "Pesquisa concluída.", true);
}
/** Manda um pedido do chat; aplica o perfil novo e devolve a resposta da IA + o que mudou na seção. */
async function ask(section: SectionKey, instruction: string, search: boolean, history: ChatTurn[]): Promise<ChatTurn> {
setChatBusy(true);
const before = game?.profile;
const r = await clipperCall<RefineReply>(`${path}/refine`, "POST", {
instruction, search, section, history: history.map(({ role, text }) => ({ role, text })),
});
setChatBusy(false);
if (!r.ok) {
if (search) {
const list = await clipperCall<GamesReply>("games");
if (list.ok) onGamesChanged(list.data.games);
}
return { role: "ai", text: r.error, error: true };
}
onGamesChanged(r.data.games);
const after = r.data.games.find((g) => g.id === id)?.profile;
let added = 0, removed = 0;
const nextFresh = new Set<string>();
for (const key of Object.keys(SECTIONS) as ListKey[]) {
const d = diffList(before?.[key], after?.[key]);
added += d.added.length;
removed += d.removed.length;
for (const item of d.added) nextFresh.add(`${key}:${item.toLowerCase()}`);
}
setFresh(nextFresh);
return { role: "ai", text: r.data.reply || "Pronto, atualizei o perfil.", added, removed };
}
return (
<article className="overflow-hidden rounded-panel border border-line bg-surface/60">
{/* Cabeçalho: monograma do jogo, nome, gênero, de onde veio e ações. */}
<header className="relative flex flex-wrap items-start gap-4 border-b border-line p-4 sm:p-5"
style={{ backgroundImage: `linear-gradient(120deg, hsl(${hue} 70% 50% / 0.10), transparent 55%)` }}>
<div aria-hidden="true" className="grid size-12 shrink-0 place-items-center rounded-xl text-lg font-bold text-white shadow-sm"
style={{ background: `linear-gradient(135deg, hsl(${hue} 65% 52%), hsl(${(hue + 40) % 360} 70% 40%))` }}>
{monogram(title)}
</div>
<div className="grid min-w-0 flex-1 gap-1.5">
<div className="flex flex-wrap items-center gap-2">
<h3 className="text-lg font-semibold tracking-tight text-fg">{title}</h3>
{!game ? <Badge>não pesquisado</Badge>
: game.status === "pending" ? <Badge tone="info" pulse>pesquisando</Badge>
: game.status === "error" ? <Badge tone="danger">erro na pesquisa</Badge> : null}
</div>
{game?.profile?.genre && <p className="text-xs font-medium text-fg-muted">{game.profile.genre}</p>}
<p className="flex flex-wrap gap-x-2 text-xs text-fg-subtle">
{game?.researchedAt && <span>pesquisado {formatRelative(game.researchedAt)}</span>}
{game?.editedAt && <span>· editado {formatRelative(game.editedAt)}</span>}
{game?.model && <span className="font-mono">· {game.model}</span>}
</p>
</div>
<div className="flex flex-wrap gap-1.5">
{game?.profile && !editing && (
<Button variant="secondary" size="sm" disabled={busy} onClick={() => setChatOpen(chatOpen === "" ? null : "")}>
<SparkIcon size={14} />Conversar com a IA
</Button>
)}
{game && !editing && (
<Button variant="ghost" size="sm" disabled={busy} onClick={() => setEditing(true)}><PenIcon size={14} />Editar</Button>
)}
<Button variant="ghost" size="sm" disabled={busy || editing} onClick={research}>
{pending === "research" ? <><Spinner className="size-3.5" />Pesquisando…</> : <><RefreshIcon size={15} />{game?.profile ? "Pesquisar de novo" : "Pesquisar"}</>}
</Button>
</div>
</header>
<div className="grid gap-4 p-4 sm:p-5">
{game?.status === "error" && game.error && <Feedback ok={false}>{game.error}</Feedback>}
{chatOpen === "" && game?.profile && !editing && (
<AiChat key="general" sectionTitle="o perfil inteiro" suggestions={["Reação do streamer conta como corte", "Acrescente as gírias que o chat usa", "Deixe o resumo mais curto"]}
disabled={busy && !chatBusy} onAsk={(text, search, history) => ask("", text, search, history)} onClose={() => setChatOpen(null)} />
)}
{editing && game ? (
<ProfileEditor profile={game.profile} fallbackName={game.name} saving={pending === "save"} onCancel={() => setEditing(false)}
onSave={async (profile) => {
const ok = await run("save", () => clipperCall<GamesReply>(path, "PUT", profile), "Perfil salvo. A IA já usa a versão nova.");
if (ok) setEditing(false);
}} />
) : game?.profile ? (
<ProfileView profile={game.profile} fresh={fresh} chatOpen={chatOpen} disabled={busy && !chatBusy}
onToggleChat={(key) => setChatOpen(chatOpen === key ? null : key)}
renderChat={(key) => (
<AiChat key={key} sectionTitle={SECTIONS[key].title} suggestions={SECTIONS[key].suggestions} compact
disabled={busy && !chatBusy} onAsk={(text, search, history) => ask(key, text, search, history)} onClose={() => setChatOpen(null)} />
)} />
) : (
<EmptyState compact icon={<BookIcon size={18} />} title="Ainda sem perfil">
A IA pesquisa o jogo na web (mecânicas, gírias, o que costuma render corte) e usa isso para entender a live.
</EmptyState>
)}
{game && !editing && <SavedNotes notes={game.notes ?? []} disabled={busy}
onForget={(i) => void run("note", () => clipperCall<GamesReply>(`${path}/notes/${i}`, "DELETE"), "Pedido esquecido.")} />}
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</div>
</article>
);
}
/* ---------- Chat com a IA ---------- */
type ChatTurn = { role: "user" | "ai"; text: string; error?: boolean; added?: number; removed?: number };
/**
* Conversa com a IA sobre uma seção do perfil: você fala ("adicione que reação do streamer conta"), ela edita a
* lista e responde o que fez. Enter envia; Shift+Enter quebra linha. A conversa vale enquanto o chat está aberto;
* cada pedido fica guardado no serviço e volta nas próximas pesquisas.
*/
function AiChat({ sectionTitle, suggestions, compact = false, disabled, onAsk, onClose }: {
sectionTitle: string; suggestions: string[]; compact?: boolean; disabled: boolean;
onAsk: (text: string, search: boolean, history: ChatTurn[]) => Promise<ChatTurn>; onClose: () => void;
}) {
const [turns, setTurns] = useState<ChatTurn[]>([]);
const [text, setText] = useState("");
const [search, setSearch] = useState(false);
const [thinking, setThinking] = useState(false);
const inputId = useId();
const logRef = useRef<HTMLOListElement>(null);
const inputRef = useRef<HTMLTextAreaElement>(null);
useEffect(() => { inputRef.current?.focus(); }, []);
useEffect(() => { logRef.current?.scrollTo({ top: logRef.current.scrollHeight, behavior: "smooth" }); }, [turns, thinking]);
async function send(raw: string) {
const clean = raw.trim();
if (clean.length < 3 || thinking || disabled) return;
const history = turns.filter((t) => !t.error);
setTurns((t) => [...t, { role: "user", text: clean }]);
setText("");
setThinking(true);
const reply = await onAsk(clean, search, history);
setThinking(false);
setTurns((t) => [...t, reply]);
inputRef.current?.focus();
}
return (
<section aria-label={`Conversa com a IA sobre ${sectionTitle}`}
className={cx("grid gap-3 rounded-control border border-accent/30 bg-accent-soft/40", compact ? "p-3" : "p-4")}>
<div className="flex items-center gap-2">
<span className="grid size-6 place-items-center rounded-full bg-accent text-accent-fg"><SparkIcon size={13} /></span>
<p className="min-w-0 flex-1 text-[0.8125rem] font-medium text-fg">IA · editando <span className="text-accent">{sectionTitle}</span></p>
<button type="button" onClick={onClose} aria-label="Fechar conversa"
className="rounded-md p-1 text-fg-subtle hover:bg-overlay hover:text-fg"><XIcon size={14} /></button>
</div>
{turns.length === 0 && !thinking ? (
<div className="grid gap-2">
<p className="text-xs leading-relaxed text-fg-muted">
Diga o que acrescentar, tirar ou corrigir — a IA edita a lista e explica o que fez.
</p>
{suggestions.length > 0 && (
<ul className="flex flex-wrap gap-1.5">
{suggestions.map((s) => (
<li key={s}>
<button type="button" disabled={disabled} onClick={() => void send(s)}
className="rounded-full border border-line bg-raised/70 px-2.5 py-1 text-xs text-fg-muted transition-colors hover:border-accent/50 hover:text-fg disabled:opacity-50">
{s}
</button>
</li>
))}
</ul>
)}
</div>
) : (
<ol ref={logRef} aria-live="polite" className="grid max-h-72 gap-2 overflow-y-auto pr-1">
{turns.map((t, i) => (
<li key={i} className={cx("flex", t.role === "user" ? "justify-end" : "justify-start")}>
<div className={cx("max-w-[85%] rounded-2xl px-3 py-2 text-[0.8125rem] leading-relaxed",
t.role === "user" ? "rounded-br-md bg-accent text-accent-fg"
: t.error ? "rounded-bl-md border border-danger/30 bg-danger-soft text-danger"
: "rounded-bl-md border border-line bg-raised text-fg")}>
{t.text}
{t.role === "ai" && !t.error && (t.added || t.removed) ? (
<span className="mt-1.5 flex gap-2 text-xs font-medium">
{t.added ? <span className="text-success">+{t.added} {t.added === 1 ? "item novo" : "itens novos"}</span> : null}
{t.removed ? <span className="text-danger">−{t.removed} {t.removed === 1 ? "removido" : "removidos"}</span> : null}
</span>
) : null}
</div>
</li>
))}
{thinking && (
<li className="flex justify-start">
<div role="status" className="flex items-center gap-1.5 rounded-2xl rounded-bl-md border border-line bg-raised px-3 py-2.5 text-xs text-fg-muted">
<span className="sr-only">A IA está editando…</span>
{[0, 150, 300].map((d) => <span key={d} aria-hidden="true" className="size-1.5 animate-bounce rounded-full bg-fg-subtle" style={{ animationDelay: `${d}ms` }} />)}
{search && <span className="ml-1">pesquisando na web…</span>}
</div>
</li>
)}
</ol>
)}
<form className="grid gap-2" onSubmit={(e) => { e.preventDefault(); void send(text); }}>
<label htmlFor={inputId} className="sr-only">Pedido para a IA</label>
<div className="flex items-end gap-2 rounded-control border border-line-strong bg-canvas/70 p-1.5 focus-within:border-accent/60">
<textarea ref={inputRef} id={inputId} rows={1} maxLength={1500} value={text} disabled={thinking}
placeholder="Ex.: adicione que reação do streamer conta para corte"
className="max-h-32 min-h-9 flex-1 resize-none bg-transparent px-2 py-1.5 text-sm text-fg placeholder:text-fg-subtle focus:outline-none"
onChange={(e) => { setText(e.target.value); e.target.style.height = "auto"; e.target.style.height = `${e.target.scrollHeight}px`; }}
onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); void send(text); } }} />
<Button type="submit" size="sm" aria-label="Enviar" disabled={text.trim().length < 3 || thinking || disabled}>
{thinking ? <Spinner className="size-3.5" /> : <SendIcon size={14} />}
</Button>
</div>
<Switch label="Confirmar na web" checked={search} onChange={setSearch} disabled={thinking}
hint={search ? "Mais lento: a IA pesquisa antes (até alguns minutos)." : "Rápido: usa só o que você escreveu."} />
</form>
</section>
);
}
/** Pedidos que você fez à IA: voltam em toda pesquisa nova. Recolhido por padrão. */
function SavedNotes({ notes, disabled, onForget }: { notes: { text: string; at: string; section?: string }[]; disabled: boolean; onForget: (index: number) => void }) {
const [open, setOpen] = useState(false);
if (notes.length === 0) return null;
return (
<div className="grid gap-2 border-t border-line pt-3">
<button type="button" aria-expanded={open} onClick={() => setOpen((o) => !o)}
className="flex w-fit items-center gap-1.5 text-xs font-medium text-fg-muted hover:text-fg">
<BookIcon size={13} />Memória da IA · {notes.length} {notes.length === 1 ? "pedido seu" : "pedidos seus"}
<ChevronDownIcon size={13} className={cx("transition-transform", open && "rotate-180")} />
</button>
{open && (
<>
<p className="text-xs text-fg-subtle">Voltam em toda pesquisa nova, para “Pesquisar de novo” não apagar o que você acrescentou.</p>
<ul className="grid gap-1">
{notes.map((n, i) => (
<li key={`${n.at}-${i}`} className="flex items-start gap-2 rounded-lg border border-line bg-raised/40 px-2.5 py-1.5 text-xs text-fg-muted">
{n.section && n.section in SECTIONS && (
<span className={cx("shrink-0 font-medium", TONE_TEXT[SECTIONS[n.section as ListKey].tone])}>{SECTIONS[n.section as ListKey].title}</span>
)}
<span className="min-w-0 flex-1 leading-relaxed break-words">{n.text}</span>
<span className="shrink-0 text-fg-subtle">{formatRelative(n.at)}</span>
<button type="button" aria-label={`Esquecer o pedido “${n.text.slice(0, 40)}”`} disabled={disabled}
title="Esquecer (não volta nas próximas pesquisas; o perfil atual fica como está)"
className="shrink-0 rounded p-0.5 text-fg-subtle hover:bg-overlay hover:text-danger disabled:opacity-50"
onClick={() => onForget(i)}>
<XIcon size={13} />
</button>
</li>
))}
</ul>
</>
)}
</div>
);
}
/* ---------- Edição à mão ---------- */
const EDIT_LISTS = (Object.keys(SECTIONS) as ListKey[]).map((key) => ({ key, label: SECTIONS[key].title, hint: SECTIONS[key].hint }));
type ProfileDraft = { name: string; genre: string; summary: string; lists: Record<string, string> };
function toDraft(profile: GameProfile | null, fallbackName: string): ProfileDraft {
return {
name: profile?.name || fallbackName,
genre: profile?.genre ?? "",
summary: profile?.summary ?? "",
lists: Object.fromEntries(EDIT_LISTS.map(({ key }) => [key, (profile?.[key] ?? []).join("\n")])),
};
}
function fromDraft(draft: ProfileDraft): GameProfile {
const lines = (text: string) => text.split(/\r?\n/).map((l) => l.replace(/^\s*[-•*]\s*/, "").trim()).filter(Boolean);
const lists = Object.fromEntries(EDIT_LISTS.map(({ key }) => [key, lines(draft.lists[key] ?? "")]));
return { name: draft.name.trim(), genre: draft.genre.trim(), summary: draft.summary.trim(), ...lists } as GameProfile;
}
function ProfileEditor({ profile, fallbackName, saving, onSave, onCancel }: {
profile: GameProfile | null; fallbackName: string; saving: boolean; onSave: (profile: GameProfile) => void; onCancel: () => void;
}) {
const [draft, setDraft] = useState(() => toDraft(profile, fallbackName));
const setList = (key: string, value: string) => setDraft((d) => ({ ...d, lists: { ...d.lists, [key]: value } }));
return (
<form className="grid gap-4" onSubmit={(e) => { e.preventDefault(); onSave(fromDraft(draft)); }}>
<div className="grid gap-4 md:grid-cols-2">
<Field label="Nome do jogo">
<Input value={draft.name} maxLength={120} onChange={(e) => setDraft({ ...draft, name: e.target.value })} />
</Field>
<Field label="Gênero">
<Input value={draft.genre} maxLength={120} onChange={(e) => setDraft({ ...draft, genre: e.target.value })} />
</Field>
</div>
<Field label="Resumo" hint="O que é o jogo e como se joga (2–3 frases).">
<Textarea rows={3} maxLength={1500} value={draft.summary} onChange={(e) => setDraft({ ...draft, summary: e.target.value })} />
</Field>
<div className="grid gap-4 md:grid-cols-2">
{EDIT_LISTS.map(({ key, label, hint }) => (
<Field key={key} label={<span className={TONE_TEXT[SECTIONS[key].tone]}>{label}</span>} hint={hint}>
<Textarea rows={Math.min(10, Math.max(3, (draft.lists[key] ?? "").split("\n").length + 1))}
value={draft.lists[key] ?? ""} onChange={(e) => setList(key, e.target.value)}
className={key === "sources" ? "font-mono text-xs" : undefined} />
</Field>
))}
</div>
<div className="sticky bottom-0 flex justify-end gap-2 border-t border-line bg-surface/90 py-3 backdrop-blur">
<Button type="button" variant="ghost" size="sm" disabled={saving} onClick={onCancel}>Cancelar</Button>
<Button type="submit" size="sm" disabled={saving}>
{saving ? <Spinner className="size-3.5" /> : <CheckIcon size={15} />}Salvar perfil
</Button>
</div>
</form>
);
}
/* ---------- Leitura do perfil ---------- */
function ProfileView({ profile: p, fresh, chatOpen, disabled, onToggleChat, renderChat }: {
profile: GameProfile; fresh: Set<string>; chatOpen: SectionKey | null; disabled: boolean;
onToggleChat: (key: ListKey) => void; renderChat: (key: ListKey) => ReactNode;
}) {
const block = (key: ListKey, wide = false) => (
<SectionBlock key={key} sectionKey={key} items={p[key] ?? []} fresh={fresh} wide={wide}
chatOpen={chatOpen === key} disabled={disabled} onToggleChat={() => onToggleChat(key)} chat={chatOpen === key ? renderChat(key) : null} />
);
return (
<div className="grid gap-4 text-[0.8125rem]">
{p.summary && <p className="max-w-[95ch] text-sm leading-relaxed text-fg-muted">{p.summary}</p>}
<div className="grid gap-3 lg:grid-cols-2">
{block("clip_worthy")}
{block("avoid")}
{block("mechanics")}
{block("news")}
{block("jargon", true)}
{block("hashtags", true)}
</div>
{p.sources?.length > 0 && <Sources sources={p.sources} />}
</div>
);
}
function SectionBlock({ sectionKey, items, fresh, wide, chatOpen, disabled, onToggleChat, chat }: {
sectionKey: ListKey; items: string[]; fresh: Set<string>; wide: boolean; chatOpen: boolean; disabled: boolean;
onToggleChat: () => void; chat: ReactNode;
}) {
const { title, tone } = SECTIONS[sectionKey];
const isFresh = (item: string) => fresh.has(`${sectionKey}:${item.toLowerCase()}`);
const chips = sectionKey === "jargon" || sectionKey === "hashtags";
return (
<section className={cx("relative grid content-start gap-3 overflow-hidden rounded-control border bg-sunken/40 p-4 pl-5 transition-colors",
chatOpen ? "border-accent/40" : "border-line", wide && "lg:col-span-2")}>
<span aria-hidden="true" className={cx("absolute inset-y-0 left-0 w-1", TONE_BAR[tone])} />
<div className="flex items-center gap-2">
<h4 className={cx("text-eyebrow font-semibold uppercase", TONE_TEXT[tone])}>{title}</h4>
<span className="rounded-full bg-overlay px-1.5 text-[0.6875rem] font-medium tabular-nums text-fg-subtle">{items.length}</span>
<button type="button" disabled={disabled} aria-expanded={chatOpen} onClick={onToggleChat}
className={cx("ml-auto flex items-center gap-1 rounded-full px-2 py-1 text-xs font-medium transition-colors disabled:opacity-50",
chatOpen ? "bg-accent text-accent-fg" : "text-fg-subtle hover:bg-accent-soft hover:text-accent")}>
<SparkIcon size={12} />{chatOpen ? "Fechar IA" : "Pedir à IA"}
</button>
</div>
{items.length === 0 ? (
<p className="text-xs text-fg-subtle">Vazio. Peça à IA para preencher.</p>
) : chips ? (
<ul className="flex flex-wrap gap-1.5">
{items.map((j, i) => (
<li key={i} className={cx("rounded-lg border px-2 py-1 text-xs transition-colors",
isFresh(j) ? "border-success/50 bg-success-soft text-success" : "border-line bg-raised/60 text-fg-muted")}>{j}</li>
))}
</ul>
) : (
<ul className="grid gap-1.5 text-fg-muted">
{items.map((it, i) => (
<li key={i} className={cx("flex gap-2 rounded-md leading-relaxed transition-colors",
isFresh(it) && "-mx-2 bg-success-soft px-2 py-1 text-fg")}>
<span aria-hidden="true" className={cx("mt-2 size-1.5 shrink-0 rounded-full", TONE_BAR[tone], !isFresh(it) && "opacity-60")} />
<span className="min-w-0 flex-1">{it}</span>
{isFresh(it) && <span className="mt-0.5 h-fit shrink-0 rounded-full bg-success px-1.5 text-[0.625rem] font-semibold text-canvas uppercase">novo</span>}
</li>
))}
</ul>
)}
{chat}
</section>
);
}
function Sources({ sources }: { sources: string[] }) {
const [open, setOpen] = useState(false);
return (
<div className="grid gap-1.5">
<button type="button" aria-expanded={open} onClick={() => setOpen((o) => !o)}
className="flex w-fit items-center gap-1.5 text-xs font-medium text-fg-subtle hover:text-fg">
<LinkIcon size={13} />{sources.length} {sources.length === 1 ? "fonte" : "fontes"}
<ChevronDownIcon size={13} className={cx("transition-transform", open && "rotate-180")} />
</button>
{open && (
<ul className="grid gap-1">
{sources.map((s, i) => (
<li key={i} className="truncate text-xs">
{/^https?:\/\//.test(s)
? <a href={s} target="_blank" rel="noreferrer noopener" className="text-fg-muted hover:text-fg hover:underline">{s.replace(/^https?:\/\/(www\.)?/, "")}</a>
: <span className="text-fg-subtle">{s}</span>}
</li>
))}
</ul>
)}
</div>
);
}
/* ---------- Aba Jogos ---------- */
export function GamesPanel({ games, available, onGamesChanged }: { games: Game[]; available: boolean; onGamesChanged: (games: Game[]) => void }) {
if (!available) {
return (
<EmptyState compact icon={<BookIcon size={18} />} title="Perfis de jogo indisponíveis">
O Clipador no ar ainda é a versão antiga. Reinicie o serviço para a IA pesquisar os jogos das lives.
</EmptyState>
);
}
if (games.length === 0) {
return (
<EmptyState compact icon={<BookIcon size={18} />} title="Nenhum jogo pesquisado ainda">
Quando uma sessão identifica o jogo (pela categoria ou pela tela), a IA pesquisa o que ele tem de engraçado, as gírias e as novidades.
</EmptyState>
);
}
return (
<ul className="grid gap-5">
{games.map((g) => <li key={g.id}><GameCard game={g} name={g.name} onGamesChanged={onGamesChanged} /></li>)}
</ul>
);
}
/* ---------- Emotes do canal ---------- */
const EMOTE_SOURCE: Record<string, string> = { twitch: "Twitch", "7tv": "7TV", bttv: "BTTV", ffz: "FFZ", kick: "Kick", emoji: "emoji" };
export function ChannelEmotes({ channelKey, title = "Emotes da fonte" }: { channelKey: string; title?: ReactNode }) {
const [open, setOpen] = useState(false);
const [emotes, setEmotes] = useState<Emote[] | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!open || !channelKey) return;
let cancelled = false;
void clipperCall<{ emotes: Emote[] }>(`emotes?channel=${encodeURIComponent(channelKey)}`).then((r) => {
if (cancelled) return;
if (r.ok) { setEmotes(r.data.emotes); setError(null); } else setError(r.error);
});
return () => { cancelled = true; };
}, [open, channelKey]);
if (!channelKey) return null;
return (
<div className="grid gap-3">
<div>
<Button variant="ghost" size="sm" aria-expanded={open} onClick={() => setOpen((o) => !o)}>
<ChatIcon size={15} />{title}
<ChevronDownIcon size={14} className={cx("transition-transform", open && "rotate-180")} />
</Button>
</div>
{open && (
<div className="grid gap-3">
<p className="max-w-[90ch] text-xs leading-relaxed text-fg-subtle">
Emotes nos cortes que você aprova ganham peso; nos rejeitados, perdem. O chat pesa mais quando reage com os emotes de peso positivo.
</p>
{error ? <Feedback ok={false}>{error}</Feedback>
: !emotes ? <p role="status" className="flex items-center gap-2 text-xs text-fg-muted"><Spinner className="size-3.5" />Carregando emotes…</p>
: emotes.length === 0 ? <p className="text-xs text-fg-subtle">Nenhum emote registrado ainda para <code>{channelKey}</code>.</p>
: (
<Table className="max-h-80 overflow-y-auto">
<THead><Th>Emote</Th><Th>Origem</Th><Th className="text-right">Usos</Th><Th className="text-right">Peso aprendido</Th><Th>Visto</Th></THead>
<tbody>
{emotes.map((e) => (
<Tr key={`${e.source}-${e.name}`}>
<Td className="font-mono text-[0.8125rem] text-fg">{e.name}</Td>
<Td className="text-xs text-fg-subtle">{EMOTE_SOURCE[e.source] ?? e.source}</Td>
<Td className="text-right tabular-nums text-fg-muted">{e.uses}</Td>
<Td className={cx("text-right font-mono text-xs tabular-nums", e.weight > 0 ? "text-success" : e.weight < 0 ? "text-danger" : "text-fg-subtle")}>
{e.weight > 0 ? "+" : ""}{e.weight.toLocaleString("pt-BR", { maximumFractionDigits: 2 })}
</Td>
<Td className="text-xs text-fg-subtle">{formatRelative(e.lastSeen)}</Td>
</Tr>
))}
</tbody>
</Table>
)}
</div>
)}
</div>
);
}
+146
View File
@@ -0,0 +1,146 @@
"use client";
// Juiz (IA) do Clipador: provedor (Codex/GPT, Claude ou desligado), os dois juízes (analista e editor),
// nota mínima e as opções da IA (varredura, visão, achar câmera). Roda pela CLI já logada no PC.
import { useState } from "react";
import {
PROVIDER_LABEL, clipperCall, formatScore, useClipperAction, type JudgeConfig, type JudgeOptions, type JudgeProvider,
} from "./clipper-client";
import { DescribedSelect } from "./forms";
import { AlertIcon, EyeIcon, SparkIcon } from "./icons";
import { Badge, Button, Card, ChoiceGroup, Feedback, RangeField, Spinner, Switch } from "./ui";
const OPTION_DEFAULTS: JudgeOptions = { scanEnabled: true, scanIntervalS: 180, vision: true, camDetect: true, faceTrack: true };
export function JudgeForm({ judge, onSaved }: { judge: JudgeConfig; onSaved: (next: JudgeConfig) => void }) {
const savedOptions = judge.options ?? OPTION_DEFAULTS;
const [provider, setProvider] = useState<JudgeProvider>(judge.provider);
const [model, setModel] = useState(judge.model ?? "");
// O serviço devolve o analista resolvido: igual ao editor = "" (segue o editor).
const savedAnalyst = judge.analystModel && judge.analystModel !== judge.model ? judge.analystModel : "";
const [analyst, setAnalyst] = useState(savedAnalyst);
const [minScore, setMinScore] = useState(judge.minScore);
const [options, setOptions] = useState<JudgeOptions>(savedOptions);
const { pending, message, run } = useClipperAction();
const models = provider === "off" ? [] : judge.models[provider];
const fallback = provider === "off" ? "" : judge.models.defaults[provider];
// Modelo vazio = padrão do provedor. Ao trocar de provedor, o modelo antigo não vale mais.
const currentModel = models.some((m) => m.id === model) ? model : "";
const currentAnalyst = models.some((m) => m.id === analyst) ? analyst : "";
const savedModel = models.some((m) => m.id === judge.model) ? judge.model ?? "" : "";
const analystChanged = provider !== judge.provider || currentAnalyst !== (models.some((m) => m.id === savedAnalyst) ? savedAnalyst : "");
const dirty = provider !== judge.provider || (provider !== "off" && (currentModel !== savedModel || analystChanged))
|| minScore !== judge.minScore || JSON.stringify(options) !== JSON.stringify(savedOptions);
const off = provider === "off";
const setOption = (values: Partial<JudgeOptions>) => setOptions((o) => ({ ...o, ...values }));
const scansPerHour = Math.round(3600 / options.scanIntervalS);
async function save() {
const next = await run("save", () => clipperCall<JudgeConfig>("judge", "PUT", {
provider, model: currentModel, minScore,
...(off ? {} : { analystModel: currentAnalyst }),
...(judge.options ? options : {}),
}), (j) => j.provider === "off" ? "Juiz desligado: só a heurística do chat decide." : `Juiz salvo: ${PROVIDER_LABEL[j.provider]} · ${j.model}.`);
if (next) onSaved(next);
}
const modelOptions = [
{ value: "", label: `Padrão do provedor (${fallback})`, description: "Usa o modelo recomendado; troca sozinho se o padrão mudar." },
...models.map((m) => ({ value: m.id, label: m.label, description: m.description })),
];
return (
<Card eyebrow={<><SparkIcon size={13} />Juiz (IA)</>}
title={<span className="flex flex-wrap items-center gap-3">
Quem decide o que vira corte
{judge.provider === "off" ? <Badge>desligado</Badge>
: judge.available ? <Badge tone="success">disponível</Badge> : <Badge tone="danger">CLI não encontrada</Badge>}
</span>}
description="A IA confirma o momento, dá nota de 0 a 10 e escreve título e legenda. Roda pelo Codex ou pelo Claude já logado no PC, sem chave de API.">
<form className="grid gap-7" onSubmit={(e) => { e.preventDefault(); void save(); }}>
<ChoiceGroup name="provider" legend="Provedor" value={provider} onChange={(p) => { setProvider(p); setModel(""); setAnalyst(""); }}
options={[
{ value: "codex", label: "Codex (GPT)", hint: "padrão" },
{ value: "claude", label: "Claude" },
{ value: "off", label: "Desligado", hint: "só heurística" },
]} />
{off ? (
<p className="text-sm leading-relaxed text-fg-muted">
Sem juiz, todo pico do chat acima do limiar vira corte, com título tirado da transcrição. Mais rápido, mas sem filtro de qualidade, sem varredura e sem visão.
</p>
) : (
<section aria-labelledby="dois-juizes" className="grid gap-4">
<div className="grid gap-1">
<h3 id="dois-juizes" className="text-sm font-semibold text-fg">Dois juízes</h3>
<p className="max-w-[80ch] text-[0.8125rem] leading-relaxed text-fg-muted">
O <strong className="text-fg">analista</strong> vê os frames da tela, a fala e o chat e descreve o que aconteceu (lag, jogada, treta…).
O <strong className="text-fg">editor</strong> decide se vira corte e escreve título e legenda a partir disso.
</p>
</div>
<div className="grid gap-6 md:grid-cols-2">
<DescribedSelect name="analystModel" label="Analista (1º juiz, vê a tela)" value={currentAnalyst} onChange={setAnalyst}
options={[{ value: "", label: "Igual ao editor", description: "Usa o mesmo modelo do editor." }, ...modelOptions.slice(1)]} />
<DescribedSelect name="model" label="Editor (2º juiz, decide e escreve)" value={currentModel} onChange={setModel} options={modelOptions} />
</div>
</section>
)}
<RangeField label="Nota mínima para virar corte" min={0} max={10} step={0.5} value={minScore} onChange={setMinScore}
disabled={off} format={(v) => `${formatScore(v)} / 10`} className="max-w-xl"
hint="Momentos com nota abaixo disso vão para “Descartados pela IA” (dá para forçar o render de lá)." />
{judge.options ? (
<fieldset disabled={off} className="grid gap-5 rounded-card border border-line bg-sunken/30 p-5 disabled:opacity-50">
<legend className="px-1 text-sm font-semibold text-fg">O que a IA faz sozinha</legend>
<div className="grid gap-5 lg:grid-cols-2">
<div className="grid content-start gap-3">
<Switch label="Varredura" checked={options.scanEnabled} onChange={(scanEnabled) => setOption({ scanEnabled })}
hint="A cada N segundos de gravação a IA assiste a janela (tela + fala + chat) e propõe momentos mesmo sem pico de chat. Essencial em live pequena." />
<RangeField label="Intervalo da varredura" min={60} max={900} step={30} value={options.scanIntervalS}
onChange={(scanIntervalS) => setOption({ scanIntervalS })} disabled={!options.scanEnabled}
format={(v) => (v % 60 === 0 ? `${v / 60} min` : `${Math.floor(v / 60)} min ${v % 60} s`)}
hint={`Cerca de ${scansPerHour} chamada${scansPerHour === 1 ? "" : "s"} à IA por hora de live.`} />
</div>
<div className="grid content-start gap-4">
<Switch label="Visão" checked={options.vision} onChange={(vision) => setOption({ vision })}
hint="Manda frames da tela para a IA. Sem visão, ela julga só pela fala e pelo chat." />
<Switch label="Achar a câmera automaticamente" checked={options.camDetect} onChange={(camDetect) => setOption({ camDetect })}
hint="No início de cada sessão o Clipador procura o rosto do streamer no quadro (sem gastar IA) e monta o layout com câmera em cima. A IA só olha se ele não achar." />
</div>
</div>
{judge.lastScanError && (
<p className="flex items-start gap-2 rounded-control border border-warning/25 bg-warning-soft px-3 py-2 text-xs text-warning">
<AlertIcon size={14} className="mt-px" />
<span>Última varredura falhou: <span className="break-words">{judge.lastScanError}</span></span>
</p>
)}
</fieldset>
) : (
<p className="flex items-center gap-2 text-xs text-fg-subtle"><EyeIcon size={14} />Varredura, visão e câmera automática aparecem quando o Clipador for reiniciado com a versão nova.</p>
)}
{/* Rastreio de reação roda no PC (MediaPipe), sem IA: vale mesmo com o juiz desligado. */}
{judge.options && options.faceTrack !== undefined && (
<div className="max-w-xl">
<Switch label="Rastrear a reação do streamer" checked={options.faceTrack} onChange={(faceTrack) => setOption({ faceTrack })}
hint="Segue o rosto na webcam (risada, grito, susto, confusão) no próprio PC, sem gastar IA. Reforça os cortes do chat, cria corte quando o rosto reage junto com o áudio ou o chat e conta ao analista o que o streamer fez." />
</div>
)}
{judge.provider !== "off" && !judge.available && (
<Feedback ok={false}>
A CLI do {PROVIDER_LABEL[judge.provider]} não foi encontrada. Instale e faça login no terminal ({judge.provider === "codex" ? <code>codex login</code> : <code>claude</code>}), ou escolha outro provedor.
</Feedback>
)}
{judge.path && <p className="font-mono text-xs break-all text-fg-subtle">{judge.path}</p>}
<div className="flex flex-wrap items-center gap-3">
<Button type="submit" disabled={pending !== null || !dirty}>{pending === "save" ? <><Spinner />Salvando…</> : "Salvar juiz"}</Button>
{!dirty && <span className="text-xs text-fg-subtle">Nada mudou.</span>}
</div>
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</form>
</Card>
);
}
+889
View File
@@ -0,0 +1,889 @@
"use client";
// Fila de cortes do Clipador: filtros por etapa (para aprovar, na fila, aprovados…) e um cartão por
// corte com o vídeo (9:16, ou 16:9 se o corte for horizontal; sem `aspect` = vertical), título e legenda editáveis, o veredito da IA, os sinais do chat, ajuste fino
// de início/fim e as ações da etapa. Os dados vêm de cima (ClipperStudio); cada ação recarrega tudo.
// Apagar: "Apagar" em cada cartão (confirmação curta no próprio cartão). Seleção discreta (pedido do dono: "bem
// sutil, no cantinho"): "Selecionar" e o menu "⋯" (com "Apagar todos desta aba", modal que respeita o filtro de
// sessão) no canto da linha das abas; a caixa de cada cartão só aparece no hover/foco ou no modo de seleção; com algo
// selecionado, uma pílula pequena no canto de baixo. Nada disso ocupa espaço na página: a lista nunca se mexe.
// O resultado sai num aviso fixo, que também não empurra a lista.
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import {
ACTIVE_CLIP, CLIP_DELETE_MAX, CLIP_STATUS, FACE_LABEL, UNDELETABLE_CLIP, aspectOf, SITUATION_LABEL, SOURCE_LABEL, TAG_LABEL, clipperCall, deleteSummary, formatClock, formatDuration, formatScore, useClipperAction,
type Clip, type ClipAnalysis, type ClipDeleteResult, type ClipDeleted, type ClipStatus, type ClipTags, type ClipperSession, type Situation,
} from "./clipper-client";
import { ClipPublishButton } from "./clip-publish";
import { askConfirm } from "./confirm-dialog";
import { AlertIcon, ChatIcon, CheckIcon, ClockIcon, EyeIcon, PublishIcon, RefreshIcon, ScissorsIcon, SparkIcon, TrashIcon, UndoIcon, XIcon } from "./icons";
import { listJobs, type PublishJob } from "./publishing-client";
import { PublishChips, TextLink } from "./publishing-ui";
import { Badge, Button, EmptyState, Feedback, Input, LinkButton, Select, Spinner, Textarea, cx, fileUrl, formatRelative } from "./ui";
export type QueueFilter = "ready" | "queue" | "approved" | "discarded" | "rejected" | "error";
export const QUEUE_FILTERS: { id: QueueFilter; label: string; statuses: ClipStatus[]; empty: string }[] = [
{ id: "ready", label: "Para aprovar", statuses: ["ready"], empty: "Quando a IA aprovar um momento e o vídeo ficar pronto, ele aparece aqui para você decidir." },
{ id: "queue", label: "Na fila", statuses: ["candidate", "pending", "rendering"], empty: "Nada esperando a IA ou o render agora." },
{ id: "approved", label: "Aprovados", statuses: ["approved", "published"], empty: "Os cortes que você aprovar ficam aqui." },
{ id: "discarded", label: "Descartados pela IA", statuses: ["discarded"], empty: "A IA não descartou nenhum momento. Os descartados podem ser renderizados à força." },
{ id: "rejected", label: "Rejeitados", statuses: ["rejected"], empty: "Nenhum corte rejeitado." },
{ id: "error", label: "Com erro", statuses: ["error"], empty: "Nenhum corte com erro." },
];
/** Duração mínima e máxima de um corte (limites do serviço; Shorts aceita até 180 s). */
const MIN_CLIP_S = 5;
const MAX_CLIP_S = 180;
/** Estado da publicação na aba Aprovados: relê a cada 15 s enquanto a aba está aberta. */
const PUBLISH_POLL_MS = 15_000;
/**
* Jobs de publicação dos cortes (GET /api/publishing/jobs?sourceKind=clip), agrupados pelo id do corte.
* Só busca com a aba Aprovados aberta e a página visível. `null` = ainda não leu; `error` = rota fora.
*/
function useClipPublishing(active: boolean) {
const [byClip, setByClip] = useState<Map<string, PublishJob[]> | null>(null);
const [error, setError] = useState<string | null>(null);
// Muda para reler na hora (depois de "Publicar" num cartão), sem esperar os 15 s.
const [version, setVersion] = useState(0);
const reload = useCallback(() => setVersion((v) => v + 1), []);
useEffect(() => {
if (!active) return;
let cancelled = false;
const load = async () => {
if (document.visibilityState === "hidden") return;
const r = await listJobs({ sourceKind: "clip" });
if (cancelled) return;
if (!r.ok) { setError(r.error); return; }
const map = new Map<string, PublishJob[]>();
for (const j of r.data) if (j.status !== "canceled") map.set(j.sourceId, [...(map.get(j.sourceId) ?? []), j]);
setByClip(map);
setError(null);
};
void load();
const timer = setInterval(load, PUBLISH_POLL_MS);
return () => { cancelled = true; clearInterval(timer); };
}, [active, version]);
return { byClip, error, reload };
}
/** Passos do ajuste: o início volta bastante (a ação costuma vir antes da reação); o fim estica um pouco. */
const START_STEPS = [-30, -10, -5, -2, 2] as const;
const END_STEPS = [-2, 2, 5, 10] as const;
export function ClipQueue({ clips, sessions, sessionFilter, onSessionFilter, nameOf, onChanged }: {
clips: Clip[];
sessions: ClipperSession[];
sessionFilter: number | null;
onSessionFilter: (id: number | null) => void;
/** Nome da fonte de um corte (vem das fontes cadastradas ou do link). */
nameOf: (clip: Clip) => string;
onChanged: () => void;
}) {
const [filter, setFilter] = useState<QueueFilter>("ready");
const scoped = sessionFilter === null ? clips : clips.filter((c) => c.sessionId === sessionFilter);
const current = QUEUE_FILTERS.find((f) => f.id === filter)!;
const shown = scoped.filter((c) => current.statuses.includes(c.status));
const sessionIds = [...new Set(clips.map((c) => c.sessionId))];
const publishing = useClipPublishing(filter === "approved");
// Seleção para apagar: vale só para o que está na aba (trocar de aba ou de sessão limpa).
const [selected, setSelected] = useState<ReadonlySet<number>>(() => new Set());
const [deleting, setDeleting] = useState<ReadonlySet<number>>(() => new Set());
const [notice, setNotice] = useState<DeleteNotice | null>(null);
// Modo de seleção: ligado pelo botão "Selecionar" (ou ao marcar a 1ª caixa). Esc sai e limpa.
const [selecting, setSelecting] = useState(false);
const selectable = shown.filter(canDelete);
const chosen = selectable.filter((c) => selected.has(c.id));
const working = deleting.size > 0;
const choosing = selecting || chosen.length > 0;
const exitSelecting = useCallback(() => { setSelecting(false); setSelected(new Set()); }, []);
const changeFilter = (id: QueueFilter) => { setFilter(id); exitSelecting(); };
const changeSession = (id: number | null) => { onSessionFilter(id); exitSelecting(); };
useEffect(() => {
if (!choosing) return;
const onKey = (e: KeyboardEvent) => {
// Esc de um modal, menu ou confirmação do cartão é deles (o modal nativo também dispara keydown aqui).
if (e.key !== "Escape" || e.defaultPrevented || document.querySelector("dialog[open]")) return;
exitSelecting();
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [choosing, exitSelecting]);
const toggle = useCallback((id: number, on: boolean) => setSelected((prev) => {
const next = new Set(prev);
if (on) next.add(id); else next.delete(id);
return next;
}), []);
/** Apaga e mostra o resultado no aviso. Um corte vai pela rota própria; vários, pelo lote (de 500 em 500). */
const remove = useCallback(async (targets: Clip[], confirmPublished: boolean): Promise<boolean> => {
const ids = targets.map((c) => c.id);
setDeleting((prev) => new Set([...prev, ...ids]));
const total: Pick<ClipDeleteResult, "deleted" | "failed"> = { deleted: [], failed: [] };
let error: string | null = null;
if (ids.length === 1) {
const result = await clipperCall<ClipDeleted>(`clips/${ids[0]}${confirmPublished ? "?confirmPublished=true" : ""}`, "DELETE");
if (result.ok) total.deleted.push(result.data); else error = result.error;
} else {
for (let i = 0; i < ids.length && !error; i += CLIP_DELETE_MAX) {
const result = await clipperCall<ClipDeleteResult>("clips/delete", "POST", { ids: ids.slice(i, i + CLIP_DELETE_MAX), confirmPublished });
if (!result.ok) error = result.error;
else { total.deleted.push(...result.data.deleted); total.failed.push(...result.data.failed); }
}
}
setDeleting((prev) => new Set([...prev].filter((id) => !ids.includes(id))));
const gone = new Set(total.deleted.map((d) => d.id));
setSelected((prev) => new Set([...prev].filter((id) => !gone.has(id))));
const text = !error ? deleteSummary(total) : total.deleted.length ? `${deleteSummary(total)}. O resto falhou: ${error}` : error;
setNotice({ ok: !error && total.failed.length === 0, text, key: Date.now() });
// Recarrega no lugar (os dados de cima trocam; nada some da tela antes da resposta, a lista não pula).
if (total.deleted.length) onChanged();
return error === null;
}, [onChanged]);
/** Seleção ou aba inteira: modal com a contagem e o alcance (filtro de sessão); o 2º clique apaga. */
const confirmMany = async (targets: Clip[], scope: "selected" | "tab") => {
const n = targets.length;
if (n === 0) return;
const what = n === 1 ? "1 corte" : `${n} cortes`;
const published = targets.filter((c) => c.status === "published").length;
const left = scope === "tab" ? shown.length - n : 0;
const ok = await askConfirm({
tone: "danger",
title: scope === "tab"
? (n === 1 ? `Apagar o único corte de “${current.label}”?` : `Apagar todos os ${n} cortes de “${current.label}”?`)
: `Apagar ${what} selecionado${n === 1 ? "" : "s"}?`,
message: <>
<p>Some o vídeo, a capa, a miniatura e o projeto de edição de cada um. Não dá para desfazer, e a IA não recria esses momentos.</p>
{scope === "tab" && (
<p className="mt-2 font-medium text-fg">
{sessionFilter !== null
? `Vale só para a sessão #${sessionFilter} (o filtro da fila). Os cortes das outras sessões ficam.`
: "Vale para todas as sessões desta aba."}
</p>
)}
{published > 0 && <p className="mt-2">Inclui {published === 1 ? "1 corte publicado" : `${published} cortes publicados`}: só a cópia local some.</p>}
{left > 0 && <p className="mt-2">{left === 1 ? "1 corte em andamento (IA ou render) fica" : `${left} cortes em andamento (IA ou render) ficam`}.</p>}
</>,
confirmLabel: `Apagar ${what}`,
});
if (ok) await remove(targets, published > 0);
};
return (
<section aria-labelledby="fila-titulo" className="grid gap-5">
<h2 id="fila-titulo" className="sr-only">Fila de cortes</h2>
<div className="flex flex-wrap items-end justify-between gap-x-6 gap-y-3">
<div role="group" aria-label="Filtrar cortes por etapa"
className="flex flex-wrap gap-1 rounded-control border border-line-strong bg-sunken/60 p-1">
{QUEUE_FILTERS.map((f) => {
const count = scoped.filter((c) => f.statuses.includes(c.status)).length;
const selected = f.id === filter;
return (
<button key={f.id} type="button" aria-pressed={selected} onClick={() => changeFilter(f.id)}
className={cx("flex items-center gap-2 rounded-[0.45rem] px-3 py-1.5 text-[0.8125rem] font-medium transition-colors",
"focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-accent",
selected ? "bg-overlay text-fg shadow-[0_1px_0_0_rgb(255_255_255/0.06)_inset,0_1px_3px_rgb(0_0_0/0.5)]" : "text-fg-muted hover:text-fg")}>
{f.label}
<span className={cx("grid h-5 min-w-5 place-items-center rounded-full px-1.5 text-[0.6875rem] font-semibold tabular-nums",
selected ? (f.id === "error" && count > 0 ? "bg-danger-soft text-danger" : "bg-accent-soft text-accent") : "bg-overlay text-fg-subtle")}>
{count}
</span>
</button>
);
})}
</div>
<div className="ml-auto flex min-w-0 flex-wrap items-center justify-end gap-x-3 gap-y-2">
{sessionIds.length > 1 || sessionFilter !== null ? (
<label className="flex min-w-0 items-center gap-2 text-[0.8125rem] text-fg-muted">
Sessão
<Select value={sessionFilter ?? ""} onChange={(e) => changeSession(e.target.value ? Number(e.target.value) : null)} className="h-9 w-auto min-w-48">
<option value="">Todas as sessões</option>
{sessions.filter((s) => sessionIds.includes(s.id) || s.id === sessionFilter).map((s) => (
<option key={s.id} value={s.id}>#{s.id} · {s.title || s.url.replace(/^https?:\/\/(www\.)?/, "")}</option>
))}
</Select>
</label>
) : null}
{/* Sempre no lugar (mesmo vazio, desabilitado): ligar/desligar a seleção não mexe no layout. */}
<div className="flex items-center gap-0.5">
<Button variant="ghost" size="sm" aria-pressed={selecting} disabled={selectable.length === 0 || working}
onClick={() => (selecting ? exitSelecting() : setSelecting(true))} title="Escolher cortes para apagar (Esc sai)"
className={cx("text-fg-muted", selecting && "bg-raised text-fg")}>
<CheckIcon size={15} />{selecting ? "Selecionando" : "Selecionar"}
</Button>
<TabMenu count={selectable.length} disabled={selectable.length === 0 || working}
onDeleteAll={() => void confirmMany(selectable, "tab")} />
</div>
</div>
</div>
{filter === "approved" && (
<p className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs leading-relaxed text-fg-muted">
<PublishIcon size={14} className="text-fg-subtle" />
{publishing.error
? <span className="text-warning">Não deu para ler o estado da publicação agora ({publishing.error}).</span>
: <span>Use “Publicar” em cada corte para escolher o canal, as redes e quando sai. Se a fonte estiver ligada a um canal, os aprovados saem sozinhos nele. Cada cartão mostra como está em cada rede.</span>}
<TextLink href="/publishing">Abrir Publicações</TextLink>
</p>
)}
{shown.length === 0 ? (
<EmptyState compact icon={<ScissorsIcon size={18} />} title={`Nenhum corte em “${current.label}”`}>
{current.empty}
{sessionFilter !== null && <> Filtrando pela sessão #{sessionFilter}.</>}
</EmptyState>
) : (
<ul className="grid grid-cols-[repeat(auto-fill,minmax(min(100%,40rem),1fr))] gap-5">
{shown.map((clip) => (
<li key={clip.id} className="min-w-0">
<ClipCard clip={clip} name={nameOf(clip)} onChanged={onChanged} revealed={choosing}
publishJobs={filter === "approved" && publishing.byClip ? publishing.byClip.get(String(clip.id)) ?? [] : null}
onPublished={publishing.reload}
selected={selected.has(clip.id)} onSelect={toggle} deleting={deleting.has(clip.id)}
onDelete={(c, confirmPublished) => remove([c], confirmPublished)} />
</li>
))}
</ul>
)}
{choosing && (
<SelectionPill chosen={chosen.length} total={selectable.length} working={working}
onSelectAll={(on) => setSelected(on ? new Set(selectable.map((c) => c.id)) : new Set())}
onDelete={() => void confirmMany(chosen, "selected")} onExit={exitSelecting} />
)}
{notice && <DeleteToast key={notice.key} notice={notice} raised={choosing} onClose={() => setNotice(null)} />}
</section>
);
}
/* ---------- Apagar: seleção, barra e aviso ---------- */
/** O serviço recusa apagar enquanto a IA avalia (`candidate`) ou o FFmpeg renderiza (`rendering`). */
function canDelete(clip: Clip): boolean {
return !UNDELETABLE_CLIP.includes(clip.status);
}
type DeleteNotice = { ok: boolean; text: string; key: number };
type DeleteClip = (clip: Clip, confirmPublished: boolean) => Promise<boolean>;
const PILL_BUTTON = "inline-flex h-7 items-center gap-1.5 rounded-full px-2.5 font-medium text-fg-muted transition-colors hover:bg-overlay hover:text-fg focus-visible:outline-2 focus-visible:outline-accent disabled:pointer-events-none disabled:opacity-45 motion-reduce:transition-none";
/** Pílula da seleção: pequena, neutra, presa no canto de baixo à direita (deixa o canto extremo para o indicador
* do Next em desenvolvimento). Fica por cima da página sem ocupar espaço nela: nada se mexe ao aparecer. */
function SelectionPill({ chosen, total, working, onSelectAll, onDelete, onExit }: {
chosen: number; total: number; working: boolean; onSelectAll: (on: boolean) => void; onDelete: () => void; onExit: () => void;
}) {
const all = total > 0 && chosen === total;
return (
<div role="group" aria-label="Cortes selecionados"
className="fixed right-4 bottom-4 left-4 z-30 flex items-center justify-between gap-0.5 rounded-full border border-line-strong bg-raised/95 py-1 pr-1 pl-3.5 text-[0.8125rem] shadow-pop backdrop-blur-sm sm:left-auto sm:right-20 sm:justify-start">
<span aria-live="polite" className="pr-1.5 whitespace-nowrap text-fg tabular-nums">
{chosen === 0 ? "Nenhum selecionado" : `${chosen} selecionado${chosen === 1 ? "" : "s"}`}
</span>
<span aria-hidden="true" className="text-fg-subtle">·</span>
<button type="button" className={PILL_BUTTON} disabled={total === 0 || working} onClick={() => onSelectAll(!all)}>
{all ? "Desmarcar todos" : "Selecionar todos"}
</button>
<span aria-hidden="true" className="text-fg-subtle">·</span>
{/* Vermelho só no hover/foco; a confirmação (modal) é que fala em apagar de vez. */}
<button type="button" className={cx(PILL_BUTTON, "hover:bg-danger-soft hover:text-danger focus-visible:text-danger")}
disabled={chosen === 0 || working} onClick={onDelete}>
{working ? <Spinner className="size-3.5" /> : <TrashIcon size={14} />}Apagar
</button>
<button type="button" onClick={onExit} aria-label="Sair da seleção (Esc)" title="Sair da seleção (Esc)"
className={cx(PILL_BUTTON, "w-7 justify-center px-0")}>
<XIcon size={14} />
</button>
</div>
);
}
/** Menu "⋯" da aba: ações em massa que não precisam de seleção. Esc fecha e devolve o foco ao botão. */
function TabMenu({ count, disabled, onDeleteAll }: { count: number; disabled: boolean; onDeleteAll: () => void }) {
const [open, setOpen] = useState(false);
const wrapRef = useRef<HTMLDivElement>(null);
const buttonRef = useRef<HTMLButtonElement>(null);
const itemRef = useRef<HTMLButtonElement>(null);
useEffect(() => {
if (!open) return;
itemRef.current?.focus();
const onDown = (e: PointerEvent) => { if (!wrapRef.current?.contains(e.target as Node)) setOpen(false); };
document.addEventListener("pointerdown", onDown);
return () => document.removeEventListener("pointerdown", onDown);
}, [open]);
const close = () => { setOpen(false); buttonRef.current?.focus(); };
return (
<div ref={wrapRef} className="relative"
onKeyDown={(e) => { if (e.key === "Escape" && open) { e.preventDefault(); e.stopPropagation(); close(); } }}
onBlur={(e) => { if (open && !wrapRef.current?.contains(e.relatedTarget as Node)) setOpen(false); }}>
<button ref={buttonRef} type="button" aria-haspopup="menu" aria-expanded={open} aria-label="Mais ações desta aba"
title="Mais ações desta aba" disabled={disabled} onClick={() => setOpen((v) => !v)}
className={cx("grid size-8 place-items-center rounded-control text-fg-muted transition-colors hover:bg-raised hover:text-fg",
"focus-visible:outline-2 focus-visible:outline-accent disabled:pointer-events-none disabled:opacity-45 motion-reduce:transition-none",
open && "bg-raised text-fg")}>
<svg aria-hidden="true" width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
<circle cx="5" cy="12" r="1.8" /><circle cx="12" cy="12" r="1.8" /><circle cx="19" cy="12" r="1.8" />
</svg>
</button>
{open && (
<div role="menu" aria-label="Ações desta aba"
className="absolute top-full right-0 z-30 mt-1 min-w-60 rounded-control border border-line-strong bg-raised p-1 shadow-pop">
<button ref={itemRef} type="button" role="menuitem"
onClick={() => { close(); onDeleteAll(); }}
className="flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left text-[0.8125rem] text-fg-muted hover:bg-danger-soft hover:text-danger focus-visible:bg-danger-soft focus-visible:text-danger focus-visible:outline-none">
<TrashIcon size={15} />Apagar todos desta aba ({count})
</button>
</div>
)}
</div>
);
}
/** Resultado da exclusão num aviso fixo no canto (não muda a altura da página). Recebe o foco: o cartão apagado
* some e o teclado não fica perdido. Esc ou o X fecham. `raised`: sobe para não ficar em cima da pílula. */
function DeleteToast({ notice, raised, onClose }: { notice: DeleteNotice; raised: boolean; onClose: () => void }) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => { ref.current?.focus({ preventScroll: true }); }, []);
return (
<div ref={ref} tabIndex={-1} role={notice.ok ? "status" : "alert"} aria-live={notice.ok ? "polite" : "assertive"}
onKeyDown={(e) => { if (e.key === "Escape") { e.stopPropagation(); onClose(); } }}
// Embaixo e no centro: o canto direito é do indicador do Next em desenvolvimento.
className={cx("fixed inset-x-4 z-40 flex items-start gap-3 rounded-card border px-4 py-3 text-sm shadow-pop",
raised ? "bottom-20 sm:bottom-20" : "bottom-16 sm:bottom-6",
"sm:inset-x-auto sm:left-1/2 sm:w-max sm:max-w-[min(36rem,calc(100vw-8rem))] sm:-translate-x-1/2",
"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent",
notice.ok ? "border-success/30 bg-raised text-fg" : "border-danger/35 bg-raised text-fg")}>
<span aria-hidden="true" className={cx("mt-0.5 grid size-6 shrink-0 place-items-center rounded-full",
notice.ok ? "bg-success-soft text-success" : "bg-danger-soft text-danger")}>
{notice.ok ? <CheckIcon size={14} /> : <AlertIcon size={14} />}
</span>
<p className="min-w-0 flex-1 pt-0.5 leading-relaxed break-words">{notice.text}</p>
<button type="button" onClick={onClose} aria-label="Fechar aviso"
className="grid size-7 shrink-0 place-items-center rounded-md text-fg-subtle hover:bg-overlay hover:text-fg focus-visible:outline-2 focus-visible:outline-accent">
<XIcon size={14} />
</button>
</div>
);
}
/** "Apagar" com confirmação curta no próprio cartão: o 1º clique pergunta, o 2º apaga; Cancelar ou Esc desiste. */
function DeleteControl({ clip, deleting, disabled, onDelete }: { clip: Clip; deleting: boolean; disabled: boolean; onDelete: DeleteClip }) {
const [asking, setAsking] = useState(false);
const openRef = useRef<HTMLButtonElement>(null);
const cancelRef = useRef<HTMLButtonElement>(null);
const wasAsking = useRef(false);
useEffect(() => {
// Foco: ao perguntar vai para Cancelar (Enter de novo não apaga por engano); ao desistir volta para Apagar.
if (asking) cancelRef.current?.focus();
else if (wasAsking.current) openRef.current?.focus();
wasAsking.current = asking;
}, [asking]);
const published = clip.status === "published";
if (!asking) {
return (
<Button ref={openRef} variant="ghost" size="sm" disabled={disabled || deleting} onClick={() => setAsking(true)}
className="text-fg-muted hover:bg-danger-soft hover:text-danger" aria-label={`Apagar o corte ${clip.id}`}>
{deleting ? <Spinner className="size-3.5" /> : <TrashIcon size={15} />}Apagar
</Button>
);
}
return (
<div role="group" aria-label={`Confirmar: apagar o corte ${clip.id}`}
onKeyDown={(e) => { if (e.key === "Escape") { e.stopPropagation(); setAsking(false); } }}
// Mesma altura do botão "Apagar" (h-8): perguntar não muda a altura do cartão.
className="flex flex-wrap items-center gap-2">
<span className="text-xs font-medium text-danger">{published ? "Publicado: apagar só a cópia local?" : "Apagar vídeo e edição?"}</span>
<Button variant="danger" size="sm" disabled={deleting}
onClick={async () => {
// Deu certo: o foco já foi para o aviso (o cartão vai sumir); não volta para cá.
if (await onDelete(clip, published)) wasAsking.current = false;
setAsking(false);
}}>
{deleting ? <Spinner className="size-3.5" /> : <TrashIcon size={15} />}Apagar
</Button>
<Button ref={cancelRef} variant="ghost" size="sm" disabled={deleting} onClick={() => setAsking(false)}>Cancelar</Button>
</div>
);
}
/* ---------- Cartão do corte ---------- */
function ClipCard({ clip, name, onChanged, revealed, selected, onSelect, deleting, onDelete, publishJobs = null, onPublished }: {
clip: Clip; name: string; onChanged: () => void;
/** Aba Aprovados: jobs de publicação deste corte (um por rede/canal); null = não mostrar. */
publishJobs?: PublishJob[] | null;
/** Depois de "Publicar": relê o estado da publicação. */
onPublished?: () => void;
/** Modo de seleção ligado: a caixa aparece em todos os cartões (senão, só no hover/foco do cartão). */
revealed: boolean;
selected: boolean; onSelect: (id: number, on: boolean) => void; deleting: boolean; onDelete: DeleteClip;
}) {
const { pending, message, setMessage, run } = useClipperAction(onChanged);
const base = `clips/${clip.id}`;
const status = CLIP_STATUS[clip.status];
// "Publicar" só aparece com o estado da publicação lido (aba Aprovados): o diálogo precisa saber o que cada rede já tem.
const publish = publishJobs ? {
jobs: publishJobs,
onDone: (m: { ok: boolean; text: string }) => { setMessage(m); onPublished?.(); },
} : null;
const busy = ACTIVE_CLIP.includes(clip.status);
// Rascunho de título e legenda: a consulta periódica não apaga o que está sendo digitado.
const [saved, setSaved] = useState({ title: clip.title, caption: clip.caption });
const [title, setTitle] = useState(clip.title);
const [caption, setCaption] = useState(clip.caption);
if (saved.title !== clip.title || saved.caption !== clip.caption) {
setSaved({ title: clip.title, caption: clip.caption });
if (title === saved.title) setTitle(clip.title);
if (caption === saved.caption) setCaption(clip.caption);
}
const textDirty = title !== clip.title || caption !== clip.caption;
// Versão do vídeo: muda quando um render termina (mesmo caminho de arquivo, conteúdo novo).
const [videoVersion, setVideoVersion] = useState(clip.updatedAt);
const [lastStatus, setLastStatus] = useState(clip.status);
if (lastStatus !== clip.status) {
setLastStatus(clip.status);
if (ACTIVE_CLIP.includes(lastStatus)) setVideoVersion(clip.updatedAt);
}
const editable = !busy && clip.status !== "published";
const horizontal = aspectOf(clip) === "horizontal";
// Horizontal: o vídeo 16:9 vai em cima, na largura do cartão (numa coluna de 13rem ficaria minúsculo).
return (
<article aria-label={clip.title || `Corte ${clip.id}`}
className={cx("group/card grid h-full gap-5 rounded-card border bg-surface p-4 shadow-card", !horizontal && "sm:grid-cols-[13rem_minmax(0,1fr)]",
selected ? "border-accent/70 ring-1 ring-accent/40" : clip.status === "ready" ? "border-accent/25" : "border-line",
deleting && "opacity-60")}>
<ClipMedia clip={clip} version={videoVersion} />
<div className="grid min-w-0 content-start gap-4">
<header className="grid gap-2">
<div className="flex flex-wrap items-center gap-2">
<Badge tone={status.tone} pulse={status.pulse}>{status.label}</Badge>
<Badge tone={clip.source === "manual" ? "info" : clip.source === "ai" ? "violet" : "neutral"} dot={false}>
{clip.source === "manual" ? <ScissorsIcon size={12} /> : clip.source === "chat" ? <ChatIcon size={12} /> : clip.source === "ai" ? <EyeIcon size={12} /> : null}
{SOURCE_LABEL[clip.source]}
</Badge>
{horizontal && <Badge tone="info" dot={false}>horizontal 16:9</Badge>}
<span className="ml-auto text-xs text-fg-subtle" title={new Date(clip.createdAt).toLocaleString("pt-BR")}>{formatRelative(clip.createdAt)}</span>
{/* Caixa de seleção: sempre ocupa o lugar (nada se mexe), mas só aparece no hover/foco do cartão, no modo
de seleção ou marcada. Pelo teclado ela recebe foco normalmente e aparece ao receber. */}
<input type="checkbox" checked={selected} disabled={!canDelete(clip) || deleting}
onChange={(e) => onSelect(clip.id, e.target.checked)}
aria-label={`Selecionar o corte ${clip.id}${clip.title ? `: ${clip.title}` : ""}`}
title={canDelete(clip) ? "Selecionar para apagar" : "A IA ou o render está trabalhando neste corte"}
className={cx("size-4 shrink-0 cursor-pointer accent-accent transition-opacity duration-150 motion-reduce:transition-none disabled:cursor-not-allowed",
!canDelete(clip)
? (revealed ? "opacity-40" : "opacity-0 group-hover/card:opacity-40")
: revealed || selected ? "opacity-100" : "opacity-0 group-hover/card:opacity-100 group-focus-within/card:opacity-100")} />
</div>
<p className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-fg-muted">
<span className="font-medium text-fg">{name}</span>
<span className="inline-flex items-center gap-1"><ClockIcon size={13} className="text-fg-subtle" />{formatDuration(clip.durationS)}</span>
<span className="text-fg-subtle">sessão #{clip.sessionId} · {formatClock(clip.startS)}–{formatClock(clip.endS)}</span>
</p>
</header>
{publishJobs && (
<section aria-label="Publicação nas redes" className="grid gap-1.5">
<h4 className="text-eyebrow font-semibold text-fg-subtle uppercase">Publicação</h4>
<PublishChips jobs={publishJobs} showAccount={new Set(publishJobs.map((j) => j.accountId)).size > 1}
emptyText={<>Ainda não foi para nenhuma rede. Use “Publicar” abaixo para escolher o canal e as redes.</>} />
</section>
)}
<JudgeVerdict clip={clip} />
<ChatSignals clip={clip} />
<FaceSignal clip={clip} />
{clip.status === "error" && clip.error && (
<p className="rounded-control border border-danger/30 bg-danger-soft px-3 py-2 font-mono text-xs break-words text-danger">{clip.error}</p>
)}
<form className="grid gap-3" onSubmit={(e) => {
e.preventDefault();
void run("text", () => clipperCall<Clip>(base, "PATCH", { title, caption }), "Título e legenda salvos.");
}}>
<label className="grid gap-1.5">
<span className="text-[0.8125rem] font-medium text-fg-muted">Título</span>
<Input value={title} onChange={(e) => setTitle(e.target.value)} maxLength={100} disabled={!editable} className="h-9" />
</label>
<label className="grid gap-1.5">
<span className="text-[0.8125rem] font-medium text-fg-muted">Legenda do post</span>
<Textarea value={caption} onChange={(e) => setCaption(e.target.value)} rows={3} maxLength={2200} disabled={!editable} className="text-[0.8125rem]" />
</label>
{textDirty && (
<div className="flex flex-wrap items-center gap-2">
<Button type="submit" variant="secondary" size="sm" disabled={pending !== null}>
{pending === "text" ? <Spinner className="size-3.5" /> : <CheckIcon size={15} />}Salvar texto
</Button>
<Button type="button" variant="ghost" size="sm" onClick={() => { setTitle(clip.title); setCaption(clip.caption); }}>Desfazer</Button>
</div>
)}
</form>
{editable && <TrimControl clip={clip} pending={pending} run={run} />}
{clip.transcript && (
<details className="group rounded-control border border-line bg-sunken/30 px-3 py-2 text-[0.8125rem]">
<summary className="cursor-pointer text-fg-muted select-none hover:text-fg">Transcrição</summary>
<p className="mt-2 leading-relaxed text-fg-muted">{clip.transcript}</p>
</details>
)}
<ClipActions clip={clip} pending={pending} run={run} deleting={deleting} onDelete={onDelete} publish={publish} />
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</div>
</article>
);
}
type Run = ReturnType<typeof useClipperAction>["run"];
function ClipMedia({ clip, version }: { clip: Clip; version: string }) {
const busy = ACTIVE_CLIP.includes(clip.status);
const poster = clip.thumb ? fileUrl(clip.thumb) : undefined;
const frame = aspectOf(clip) === "horizontal" ? "aspect-video" : "aspect-9/16 max-sm:max-w-60";
if (clip.file && !busy) {
return (
<video key={version} controls preload="metadata" poster={poster} aria-label={`Vídeo do corte: ${clip.title || clip.id}`}
src={`${fileUrl(clip.file)}&v=${encodeURIComponent(version)}`}
className={cx(frame, "w-full self-start rounded-control border border-line bg-sunken object-contain")} />
);
}
return (
<div className={cx(frame, "relative grid w-full self-start overflow-hidden rounded-control border border-line bg-sunken")}>
{/* eslint-disable-next-line @next/next/no-img-element -- miniatura local servida por /api/files */}
{poster && <img src={poster} alt="" className="absolute inset-0 size-full object-cover opacity-35" />}
<div className="relative grid place-content-center justify-items-center gap-2 p-4 text-center text-xs text-fg-muted">
{busy ? <Spinner className="size-5 text-accent" /> : <ScissorsIcon size={22} className="text-fg-subtle" />}
<span>{busy ? CLIP_STATUS[clip.status].label : clip.status === "discarded" ? "Não renderizado: a IA descartou" : "Sem vídeo"}</span>
</div>
</div>
);
}
function JudgeVerdict({ clip }: { clip: Clip }) {
const judge = clip.judge;
if (!judge) {
return (
<>
<Proposal clip={clip} />
<p className="flex items-center gap-2 text-xs text-fg-subtle">
<SparkIcon size={14} className={clip.status === "candidate" ? "text-violet" : undefined} />
{clip.status === "candidate" ? "A IA está avaliando este momento…"
: clip.source === "manual" ? "Corte manual: não passa pela IA."
: "Sem veredito da IA (juiz desligado ou avaliado só pela heurística)."}
</p>
</>
);
}
if ("error" in judge) {
return (
<>
<Proposal clip={clip} />
<p className="flex items-start gap-2 rounded-control border border-warning/25 bg-warning-soft px-3 py-2 text-xs text-warning">
<AlertIcon size={14} className="mt-px" />
<span>A IA não conseguiu avaliar: <span className="break-words">{judge.error}</span></span>
</p>
</>
);
}
const tone = judge.keep ? (judge.score >= 7 ? "text-success" : "text-fg") : "text-warning";
const a = judge.analysis;
return (
<>
<Proposal clip={clip} />
{a && <AnalysisView analysis={a} model={judge.analystModel} />}
<div className="grid grid-cols-[auto_minmax(0,1fr)] items-start gap-x-3.5 gap-y-1 rounded-control border border-violet/20 bg-violet-soft/40 px-3.5 py-2.5">
<div className="row-span-2 grid justify-items-center leading-none" aria-label={`Nota da IA: ${formatScore(judge.score)} de 10`}>
<span className={cx("font-display text-2xl font-semibold tabular-nums", tone)}>{formatScore(judge.score)}</span>
<span className="mt-1 text-[0.6875rem] text-fg-subtle">de 10</span>
</div>
<p className="flex flex-wrap items-center gap-2 text-xs">
<span className="inline-flex items-center gap-1.5 font-semibold text-violet"><SparkIcon size={13} />{a ? "Editor" : "Juiz"}</span>
<Badge tone={judge.keep ? "success" : "warning"} dot={false}>{judge.keep ? "manteve" : "descartou"}</Badge>
<span className="font-mono text-[0.6875rem] text-fg-subtle">{judge.model}</span>
</p>
{judge.reason && <p className="text-[0.8125rem] leading-relaxed text-fg-muted">{judge.reason}</p>}
</div>
</>
);
}
/** Corte da varredura (source "ai"): a proposta que a IA fez ao assistir a janela, antes dos juízes. */
function Proposal({ clip }: { clip: Clip }) {
const r = clip.reasons ?? {};
if (clip.source !== "ai" || !(r.proposalTitle || r.proposalReason)) return null;
return (
<div className="grid gap-1 rounded-control border border-info/20 bg-info-soft/40 px-3.5 py-2.5 text-xs">
<p className="flex flex-wrap items-center gap-2">
<span className="inline-flex items-center gap-1.5 font-semibold text-info"><EyeIcon size={13} />Varredura viu na tela</span>
{r.proposalScore !== undefined && <Badge tone="info" dot={false}>proposta {formatScore(r.proposalScore)}/10</Badge>}
{r.scanFromS !== undefined && r.scanToS !== undefined && <span className="text-fg-subtle">janela {formatClock(r.scanFromS)}–{formatClock(r.scanToS)}</span>}
</p>
{r.proposalTitle && <p className="font-medium text-fg">{r.proposalTitle}</p>}
{r.proposalReason && <p className="leading-relaxed text-fg-muted">{r.proposalReason}</p>}
</div>
);
}
/** O que o ANALISTA (1º juiz) entendeu: situação, o que aconteceu, confiança; tela/fala/chat expansíveis. */
function AnalysisView({ analysis: a, model }: { analysis: ClipAnalysis; model?: string }) {
const confidence = Math.round(Math.min(1, Math.max(0, a.confidence ?? 0)) * 100);
const details = [
{ label: "Tela", text: a.screen }, { label: "Fala", text: a.speech }, { label: "Chat", text: a.chat_meaning }, { label: "Gancho", text: a.hook },
].filter((d) => d.text);
return (
<div className="grid gap-2 rounded-control border border-line bg-sunken/40 px-3.5 py-2.5">
<p className="flex flex-wrap items-center gap-2 text-xs">
<span className="font-semibold text-fg">O que aconteceu</span>
<Badge tone="accent" dot={false}>{SITUATION_LABEL[a.situation as Situation] ?? a.situation}</Badge>
<span className={cx("tabular-nums", confidence >= 70 ? "text-success" : confidence >= 40 ? "text-fg-muted" : "text-warning")}>
confiança {confidence}%
</span>
{model && <span className="font-mono text-[0.6875rem] text-fg-subtle">analista {model}</span>}
</p>
{a.what_happened && <p className="text-[0.8125rem] leading-relaxed text-fg-muted">{a.what_happened}</p>}
{details.length > 0 && (
<details className="text-xs">
<summary className="cursor-pointer text-fg-subtle select-none hover:text-fg">Tela, fala e chat</summary>
<dl className="mt-2 grid gap-1.5">
{details.map((d) => (
<div key={d.label} className="grid grid-cols-[4.5rem_minmax(0,1fr)] gap-2">
<dt className="font-semibold text-fg-subtle">{d.label}</dt>
<dd className="leading-relaxed text-fg-muted">{d.text}</dd>
</div>
))}
</dl>
</details>
)}
</div>
);
}
function ChatSignals({ clip }: { clip: Clip }) {
const { peakRatio, messages, tags, topMessages, emotes } = clip.reasons ?? {};
const tagEntries = Object.entries(tags ?? {}).filter(([, n]) => (n ?? 0) > 0) as [keyof ClipTags, number][];
const emoteEntries = Object.entries(emotes ?? {}).filter(([, n]) => n > 0).sort((x, y) => y[1] - x[1]);
if (peakRatio === undefined && messages === undefined && tagEntries.length === 0 && emoteEntries.length === 0 && !topMessages?.length) return null;
return (
<div className="grid gap-2">
<div className="flex flex-wrap items-center gap-1.5 text-xs">
{peakRatio !== undefined && <Chip strong>pico {formatScore(peakRatio)}× o normal</Chip>}
{messages !== undefined && <Chip>{messages} mensage{messages === 1 ? "m" : "ns"}</Chip>}
{tagEntries.map(([tag, n]) => <Chip key={tag} accent>{TAG_LABEL[tag] ?? tag} ×{n}</Chip>)}
</div>
{emoteEntries.length > 0 && (
<ul aria-label="Emotes do chat no pico" className="flex flex-wrap gap-1.5 text-xs">
{emoteEntries.slice(0, 8).map(([name, n]) => (
<li key={name} className="inline-flex h-6 items-center gap-1 rounded-full border border-option-b/25 bg-option-b-soft px-2.5 font-mono text-option-b">
{name}<span className="text-option-b/70">×{n}</span>
</li>
))}
</ul>
)}
{topMessages && topMessages.length > 0 && (
<ul aria-label="Mensagens do chat no pico" className="flex flex-wrap gap-1.5">
{topMessages.slice(0, 6).map((m, i) => (
<li key={i} title={m}
className="max-w-56 truncate rounded-lg border border-line bg-sunken/50 px-2 py-1 text-[0.75rem] text-fg-muted">
{m}
</li>
))}
</ul>
)}
</div>
);
}
/** Reação no rosto do streamer (rastreio local): rótulo, intensidade relativa ao normal dele e quando aconteceu. */
function FaceSignal({ clip }: { clip: Clip }) {
const face = clip.reasons?.face;
if (!face || face.label === "neutro") return null;
const support = clip.reasons?.support;
return (
<p className="flex flex-wrap items-center gap-1.5 text-xs" aria-label="Reação no rosto do streamer">
<Chip accent>rosto: {FACE_LABEL[face.label] ?? face.label}{face.strong ? " forte" : ""}</Chip>
<span title="Quantos desvios acima do rosto normal deste streamer (3 = começa a contar; 6 ou mais = forte)">
<Chip>intensidade {formatScore(face.intensity)}</Chip>
</span>
<span className="text-fg-subtle" title={`começou em ${formatClock(face.onsetS)}`}>pico em {formatClock(face.peakS)}</span>
{clip.source === "face" && support && (
<span className="text-fg-subtle">com apoio {support.chatReactions >= 2 ? `do chat (${support.chatReactions} reações)` : "do áudio"}</span>
)}
</p>
);
}
function Chip({ children, strong = false, accent = false }: { children: ReactNode; strong?: boolean; accent?: boolean }) {
return (
<span className={cx("inline-flex h-6 items-center rounded-full border px-2.5 font-medium whitespace-nowrap",
accent ? "border-accent/25 bg-accent-soft text-accent" : strong ? "border-line-strong bg-raised text-fg" : "border-line bg-raised/60 text-fg-muted")}>
{children}
</span>
);
}
/** Ajuste fino de início/fim (±2 s). Aplicar reenfileira o render. */
function TrimControl({ clip, pending, run }: { clip: Clip; pending: string | null; run: Run }) {
const [trim, setTrim] = useState<{ start: number; end: number } | null>(null);
const start = trim?.start ?? clip.startS;
const end = trim?.end ?? clip.endS;
const dirty = trim !== null && (trim.start !== clip.startS || trim.end !== clip.endS);
const length = end - start;
const valid = length >= MIN_CLIP_S && length <= MAX_CLIP_S;
const nudge = (step: number, edge: "start" | "end") => {
const next = edge === "start" ? { start: Math.max(0, start + step), end } : { start, end: end + step };
const span = next.end - next.start;
const ok = span >= MIN_CLIP_S && span <= MAX_CLIP_S && !(edge === "start" && step < 0 && start <= 0);
const word = step < 0 ? "antes" : "depois";
return (
<button key={`${edge}${step}`} type="button" disabled={!ok || pending !== null} onClick={() => setTrim(next)}
aria-label={`${edge === "start" ? "Começar" : "Terminar"} ${Math.abs(step)} segundos ${word}`}
className={cx("h-7 rounded-md px-1.5 font-mono text-xs transition-colors hover:bg-overlay hover:text-fg focus-visible:outline-2 focus-visible:outline-accent disabled:opacity-40",
Math.abs(step) >= 10 ? "text-accent" : "text-fg-muted")}>
{step > 0 ? "+" : "−"}{Math.abs(step)} s
</button>
);
};
const delta = (now: number, was: number) => {
const d = Math.round(now - was);
return d === 0 ? null : <span className="text-accent"> ({d > 0 ? "+" : "−"}{Math.abs(d)} s)</span>;
};
return (
<fieldset className="grid gap-2">
<legend className="mb-1.5 text-[0.8125rem] font-medium text-fg-muted">Ajuste do trecho</legend>
<div className="flex flex-wrap items-center gap-2">
<span className="inline-flex flex-wrap items-center gap-0.5 rounded-control border border-line-strong bg-sunken/60 p-0.5">
{START_STEPS.filter((st) => st < 0).map((st) => nudge(st, "start"))}
<span className="px-1.5 text-xs text-fg-subtle">início <span className="font-mono text-fg tabular-nums">{formatClock(start)}</span>{delta(start, clip.startS)}</span>
{START_STEPS.filter((st) => st > 0).map((st) => nudge(st, "start"))}
</span>
<span className="inline-flex flex-wrap items-center gap-0.5 rounded-control border border-line-strong bg-sunken/60 p-0.5">
{END_STEPS.filter((st) => st < 0).map((st) => nudge(st, "end"))}
<span className="px-1.5 text-xs text-fg-subtle">fim <span className="font-mono text-fg tabular-nums">{formatClock(end)}</span>{delta(end, clip.endS)}</span>
{END_STEPS.filter((st) => st > 0).map((st) => nudge(st, "end"))}
</span>
<span className={cx("text-xs tabular-nums", !valid ? "text-danger" : dirty ? "text-accent" : "text-fg-subtle")}>{formatDuration(length)}</span>
</div>
{dirty && (
<div className="flex flex-wrap items-center gap-2">
<Button type="button" size="sm" variant="secondary" disabled={pending !== null || !valid}
onClick={async () => {
const done = await run("trim", () => clipperCall<Clip>(`clips/${clip.id}`, "PATCH", { startS: start, endS: end }),
"Novo trecho salvo. O corte voltou para a fila de render.");
if (done) setTrim(null);
}}>
{pending === "trim" ? <Spinner className="size-3.5" /> : <RefreshIcon size={15} />}Aplicar e re-renderizar
</Button>
<Button type="button" variant="ghost" size="sm" onClick={() => setTrim(null)}>Desfazer</Button>
<span className="text-xs text-fg-subtle">Entre {MIN_CLIP_S} e {MAX_CLIP_S} s. A gravação inteira fica guardada por cerca de 6 h.</span>
</div>
)}
</fieldset>
);
}
function ClipActions({ clip, pending, run, deleting, onDelete, publish }: {
clip: Clip; pending: string | null; run: Run; deleting: boolean; onDelete: DeleteClip;
/** Aprovados/publicados: botão "Publicar" (null enquanto o estado da publicação não foi lido). */
publish: { jobs: PublishJob[]; onDone: (m: { ok: boolean; text: string }) => void } | null;
}) {
const base = `clips/${clip.id}`;
const icon = (key: string, fallback: ReactNode) => (pending === key ? <Spinner className="size-3.5" /> : fallback);
const setStatus = (key: string, status: "approved" | "rejected" | "ready", text: string) =>
run(key, () => clipperCall<Clip>(base, "PATCH", { status }), text);
const render = (text: string) => run("render", () => clipperCall<Clip>(`${base}/render`, "POST"), text);
const rejudge = () => run("rejudge", () => clipperCall<Clip>(`${base}/rejudge`, "POST"), "Mandado de novo para a IA.");
const disabled = pending !== null;
const rejudgeButton = clip.source !== "manual" && (
<Button variant="ghost" size="sm" disabled={disabled} onClick={() => void rejudge()}>
{icon("rejudge", <SparkIcon size={15} />)}Mandar de novo para a IA
</Button>
);
let buttons: ReactNode = null;
switch (clip.status) {
case "ready":
buttons = <>
<Button size="sm" disabled={disabled} onClick={() => void setStatus("approve", "approved", "Corte aprovado.")}>
{icon("approve", <CheckIcon size={15} />)}Aprovar
</Button>
<Button variant="secondary" size="sm" disabled={disabled} onClick={() => void setStatus("reject", "rejected", "Corte rejeitado.")}>
{icon("reject", <XIcon size={15} />)}Rejeitar
</Button>
<Button variant="ghost" size="sm" disabled={disabled} onClick={() => void render("Re-render pedido. O corte voltou para a fila.")}>
{icon("render", <RefreshIcon size={15} />)}Re-renderizar
</Button>
{rejudgeButton}
</>;
break;
case "approved":
buttons = <>
{publish && <ClipPublishButton clip={clip} jobs={publish.jobs} onDone={publish.onDone} />}
<Button variant="ghost" size="sm" disabled={disabled} onClick={() => void setStatus("undo", "ready", "Aprovação desfeita.")}>
{icon("undo", <UndoIcon size={15} />)}Desfazer aprovação
</Button>
</>;
break;
case "published":
// Publicado: dá para mandar para outra rede ou outro canal; editar não (o vídeo já está no ar).
return (
<div className="flex flex-wrap items-center gap-2 border-t border-line pt-4">
{publish && <ClipPublishButton clip={clip} jobs={publish.jobs} onDone={publish.onDone} variant="secondary" />}
<span className="ml-auto" />
<DeleteControl clip={clip} deleting={deleting} disabled={disabled} onDelete={onDelete} />
</div>
);
case "rejected":
buttons = <>
{clip.file && <Button variant="secondary" size="sm" disabled={disabled} onClick={() => void setStatus("undo", "ready", "Corte de volta para aprovar.")}>
{icon("undo", <UndoIcon size={15} />)}Voltar para aprovar
</Button>}
<Button variant="ghost" size="sm" disabled={disabled} onClick={() => void render("Re-render pedido.")}>
{icon("render", <RefreshIcon size={15} />)}Re-renderizar
</Button>
</>;
break;
case "discarded":
buttons = <>
<Button variant="secondary" size="sm" disabled={disabled} onClick={() => void render("Render forçado: o corte entrou na fila.")}>
{icon("render", <ScissorsIcon size={15} />)}Forçar render
</Button>
{rejudgeButton}
</>;
break;
case "error":
buttons = <>
<Button variant="secondary" size="sm" disabled={disabled} onClick={() => void render("Tentando de novo: o corte entrou na fila.")}>
{icon("render", <RefreshIcon size={15} />)}Tentar render de novo
</Button>
{rejudgeButton}
</>;
break;
default:
// Na fila: só o pendente pode sair (a IA ou o render ainda não pegou); avaliando/renderizando, nada.
if (!canDelete(clip)) return null;
return (
<div className="flex flex-wrap items-center justify-end gap-2 border-t border-line pt-4">
<DeleteControl clip={clip} deleting={deleting} disabled={disabled} onDelete={onDelete} />
</div>
);
}
return (
<div className="flex flex-wrap items-center gap-2 border-t border-line pt-4">
{buttons}
{/* Editor em tela cheia: abre o projeto que a IA montou (ou o seu) para ajustar e exportar de novo. */}
<LinkButton href={`/clipper/edit/${clip.id}`} variant="secondary" size="sm" className="ml-auto">
<ScissorsIcon size={15} />{clip.edit?.origin === "user" ? "Continuar edição" : "Editar"}
</LinkButton>
<DeleteControl clip={clip} deleting={deleting} disabled={disabled} onDelete={onDelete} />
</div>
);
}
+818
View File
@@ -0,0 +1,818 @@
"use client";
// Sessões do Clipador: gravar uma live ou baixar um VOD pelo link, acompanhar cada sessão (chat,
// transcrição, varredura da IA, cortes), "Cortar agora" na live, parar, apagar e ver o gráfico do chat.
//
// O cartão da sessão se lê de cima para baixo: quem/estado/tempo + ações principais → saúde em uma frase →
// o que está acontecendo (resumo da IA + jogo) → quatro blocos comparáveis do pipeline → ferramentas.
// A página consulta o serviço a cada 5 s: todo bloco tem altura fixa (linhas truncadas, barra sempre
// presente, espaço reservado) para nada pular nem mudar de altura quando um número muda.
import { useEffect, useId, useLayoutEffect, useState, useSyncExternalStore, type FormEvent, type ReactNode } from "react";
import {
ACTIVE_SESSION, CLIP_STATUS, CLIP_STATUS_ORDER, PLATFORM_LABEL, SESSION_STATUS, chatStatusInfo, clipperCall, formatClock,
captureLabel, channelKeyOf, formatDuration, gameIdOf, gbPerHourLabel, useClipperAction,
type Clip, type ClipStatus, type ClipperPlatform, type ClipperSession, type Game, type JudgeOptions, type Timeline,
} from "./clipper-client";
import { ChannelEmotes, SessionGame } from "./clipper-games";
import {
AlertIcon, BroadcastIcon, ChartIcon, ChatIcon, CheckIcon, ChevronDownIcon, EyeIcon, KickIcon, MicIcon, ScissorsIcon, SettingsIcon,
SparkIcon, StopIcon, TrashIcon, TwitchIcon, YouTubeIcon,
} from "./icons";
import { Badge, Button, EmptyState, Feedback, Input, ProgressBar, Spinner, cx, formatDate, formatInteger, type Tone } from "./ui";
import { askConfirm } from "./confirm-dialog";
/** Opções do "Cortar agora" (últimos N segundos). */
const CUT_OPTIONS = [30, 45, 60] as const;
/** A varredura da IA assiste janelas de 3 min: padrão de `scanIntervalS` em `OPTION_DEFAULTS` (clipper/app/intel.py).
* O valor em uso vem de `judge.options.scanIntervalS` em /status; este é o reserva (serviço antigo ou fora do ar). */
const SCAN_WINDOW_S = 180;
/** Ao vivo, a IA fica até uma janela atrás por natureza; mais de duas janelas e pouco = atrasada. */
const SCAN_LATE_S = SCAN_WINDOW_S * 2 + 60;
/** Trechos de 30 s esperando transcrição acima disso, ao vivo = transcrição atrasada. */
const TRANSCRIPT_LATE_SEGMENTS = 4;
type Run = ReturnType<typeof useClipperAction>["run"];
export function PlatformIcon({ platform, size = 16, className }: { platform: ClipperPlatform; size?: number; className?: string }) {
const Icon = platform === "twitch" ? TwitchIcon : platform === "kick" ? KickIcon : YouTubeIcon;
return <Icon size={size} className={className} />;
}
/* ---------- Gravar pelo link ---------- */
export function RecordForm({ onChanged, disabled }: { onChanged: () => void; disabled: boolean }) {
const { pending, message, run } = useClipperAction(onChanged);
const [url, setUrl] = useState("");
const titleId = useId();
const hintId = useId();
async function submit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
const done = await run("record", () => clipperCall<ClipperSession>("sessions", "POST", { url: url.trim() }),
(s) => s.kind === "vod" ? `VOD na fila: sessão #${s.id}. Baixando e processando.` : `Gravando: sessão #${s.id}.`);
if (done) setUrl("");
}
return (
<section aria-labelledby={titleId} className="grid gap-3 rounded-card border border-line bg-surface px-5 py-4 shadow-card">
<form onSubmit={submit} className="grid items-center gap-x-8 gap-y-3 lg:grid-cols-[minmax(0,24rem)_minmax(0,1fr)]">
<div className="flex items-start gap-3">
<span aria-hidden="true" className="grid size-10 shrink-0 place-items-center rounded-control border border-accent/30 bg-accent-soft text-accent">
<BroadcastIcon size={18} />
</span>
<div className="grid min-w-0 gap-0.5">
<h2 id={titleId} className="text-[0.9375rem] font-semibold text-fg">Gravar pelo link</h2>
<p id={hintId} className="text-xs leading-relaxed text-fg-subtle">
Live no ar: começa a gravar agora. Vídeo (VOD) da Twitch, do YouTube ou da Kick: baixa e processa inteiro.
</p>
</div>
</div>
<div className="flex min-w-0 items-center gap-2.5">
<Input type="url" required value={url} onChange={(e) => setUrl(e.target.value)} disabled={disabled}
aria-label="Link da live ou do VOD" aria-describedby={hintId} placeholder="https://www.twitch.tv/nome ou link de um vídeo"
className="min-w-0 flex-1" />
<Button disabled={disabled || pending !== null || !url.trim()} className="shrink-0">
{pending === "record" ? <Spinner /> : <BroadcastIcon size={16} />}Gravar
</Button>
</div>
</form>
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</section>
);
}
/* ---------- Cortar agora ---------- */
/** Botões "Cortar agora" (últimos 30/45/60 s). O corte manual nunca é descartado pela IA. */
export function CutNow({ sessionId, pending, run }: { sessionId: number; pending: string | null; run: Run }) {
return (
<span role="group" aria-label="Cortar agora: últimos segundos"
className="inline-flex items-center gap-0.5 rounded-control border border-accent/35 bg-accent-soft p-0.5">
<span className="flex items-center gap-1.5 px-2 text-[0.8125rem] font-semibold text-accent">
{pending?.startsWith("cut-") ? <Spinner className="size-3.5" /> : <ScissorsIcon size={15} />}Cortar agora
</span>
{CUT_OPTIONS.map((s) => (
<button key={s} type="button" disabled={pending !== null} aria-label={`Cortar os últimos ${s} segundos`}
onClick={() => void run(`cut-${s}`, () => clipperCall<Clip>(`sessions/${sessionId}/clips`, "POST", { lastS: s }),
`Corte manual dos últimos ${s} s criado. Ele vai direto para o render.`)}
className="h-7 rounded-md px-2.5 text-[0.8125rem] font-semibold text-accent tabular-nums transition-colors hover:bg-accent hover:text-accent-fg focus-visible:outline-2 focus-visible:outline-accent disabled:opacity-45">
{s} s
</button>
))}
</span>
);
}
/* ---------- Lista de sessões ---------- */
export function SessionList({ sessions, clips, games, nameOf, onChanged, onShowClips, onConfigure, onGamesChanged }: {
sessions: ClipperSession[];
clips: Clip[];
games: Game[];
nameOf: (s: ClipperSession) => string;
onChanged: () => void;
onShowClips: (sessionId: number) => void;
/** Abre a "Configuração do corte" da sessão. */
onConfigure: (session: ClipperSession) => void;
onGamesChanged: (games: Game[]) => void;
}) {
const scanIntervalS = useScanInterval();
if (sessions.length === 0) {
return (
<EmptyState compact icon={<BroadcastIcon size={18} />} title="Nenhuma sessão ainda">
Cole o link de uma live acima, ou ligue o monitor de uma fonte na aba Fontes para gravar sozinho quando ela entrar ao vivo.
</EmptyState>
);
}
return (
<ul className="grid gap-4">
{sessions.map((s) => (
<li key={s.id}>
<SessionRow session={s} name={nameOf(s)} clips={clips.filter((c) => c.sessionId === s.id)} games={games} onChanged={onChanged}
onShowClips={onShowClips} onConfigure={onConfigure} onGamesChanged={onGamesChanged} scanIntervalS={scanIntervalS} />
</li>
))}
</ul>
);
}
/* ---------- Saúde da sessão ---------- */
type Level = "danger" | "warning" | "note";
type Issue = { level: Level; text: string };
type Health = { tone: Tone; text: string; full: string };
/** Uma frase que responde "está tudo bem com esta sessão?": o pior problema primeiro, observações depois. */
function sessionHealth(s: ClipperSession, mismatch: boolean): Health {
const live = s.status === "recording" || s.status === "starting";
const issues: Issue[] = [];
const seg = s.segments;
if (s.status === "error") issues.push({ level: "danger", text: "Parou com erro (detalhe abaixo)" });
if (s.status === "interrupted") {
issues.push({ level: "warning", text: "Interrompida: o serviço reiniciou no meio da gravação. Retome ou processe o que já foi gravado" });
}
if (s.chatStatus.startsWith("error")) issues.push({ level: "danger", text: `Chat com erro: ${s.chatStatus.replace(/^error:\s*/, "")}` });
else if (live && s.chatStatus === "connecting") issues.push({ level: "note", text: "conectando ao chat" });
else if (live && (s.chatStatus === "off" || s.chatStatus === "")) {
issues.push({ level: "warning", text: "Sem chat: os cortes dependem só do áudio e da IA" });
}
const waiting = seg.total - seg.analyzed;
if (live && waiting > TRANSCRIPT_LATE_SEGMENTS) issues.push({ level: "warning", text: `Transcrição atrasada: ${waiting} trechos na fila` });
if (live && s.scannedUntilS !== undefined && s.durationS - s.scannedUntilS > SCAN_LATE_S) {
issues.push({ level: "warning", text: `IA ${formatDuration(s.durationS - s.scannedUntilS)} atrás da gravação` });
}
if (mismatch) issues.push({ level: "warning", text: "Confirme o jogo: a tela não bate com a categoria" });
if (seg.transcriptErrors > 0) {
// Um ou outro trecho sem fala é normal (silêncio, música); muitos indicam o serviço de voz com problema.
const many = seg.transcriptErrors > Math.max(2, seg.total * 0.05);
issues.push({ level: many ? "warning" : "note", text: `${seg.transcriptErrors} trecho${seg.transcriptErrors === 1 ? "" : "s"} sem transcrição` });
}
if (live && s.camDetect === null) issues.push({ level: "note", text: "câmera ainda não identificada" });
const serious = issues.filter((i) => i.level !== "note");
const notes = issues.filter((i) => i.level === "note").map((i) => i.text);
if (serious.length > 0) {
const tone: Tone = serious.some((i) => i.level === "danger") ? "danger" : "warning";
const parts = [...serious.map((i) => i.text), ...notes];
return { tone, text: parts.join(" · "), full: parts.join("\n") };
}
const base: { tone: Tone; text: string } =
s.status === "starting" ? { tone: "info", text: "Iniciando a gravação" }
: s.status === "recording" ? { tone: "success", text: "Tudo certo: gravando, com o chat e a IA em dia" }
: s.status === "processing"
? s.kind === "live"
? { tone: "info", text: "A gravação parou e a IA está processando o que foi gravado. Se a live continua no ar, use “Retomar gravação”" }
: { tone: "info", text: "Processando: transcrição, varredura da IA e juízes em andamento" }
: s.status === "done" ? { tone: "success", text: "Concluída: tudo processado" }
: { tone: "neutral", text: "Gravação parada" };
const parts = [base.text, ...notes];
return { tone: base.tone, text: parts.join(" · "), full: parts.join("\n") };
}
const TONE_TEXT: Record<Tone, string> = {
neutral: "text-fg-muted", accent: "text-accent", info: "text-info", violet: "text-violet", success: "text-success",
warning: "text-warning", danger: "text-danger", optionB: "text-option-b", optionC: "text-option-c", optionD: "text-option-d",
};
const TONE_FILL: Record<Tone, string> = {
neutral: "bg-fg-subtle", accent: "bg-accent", info: "bg-info", violet: "bg-violet", success: "bg-success",
warning: "bg-warning", danger: "bg-danger", optionB: "bg-option-b", optionC: "bg-option-c", optionD: "bg-option-d",
};
/** Cor do ícone da plataforma e da borda do cartão, por estado da sessão. */
const STATUS_FRAME: Record<ClipperSession["status"], { icon: string; border: string }> = {
starting: { icon: "border-info/35 bg-info-soft text-info", border: "border-info/30" },
recording: { icon: "border-danger/35 bg-danger-soft text-danger", border: "border-danger/30" },
processing: { icon: "border-info/35 bg-info-soft text-info", border: "border-info/25" },
done: { icon: "border-line-strong bg-raised text-fg-muted", border: "border-line" },
stopped: { icon: "border-line-strong bg-raised text-fg-muted", border: "border-line" },
error: { icon: "border-danger/35 bg-danger-soft text-danger", border: "border-danger/30" },
interrupted: { icon: "border-warning/35 bg-warning-soft text-warning", border: "border-warning/30" },
};
/* ---------- Cartão da sessão ---------- */
function SessionRow({ session: s, name, clips, games, onChanged, onShowClips, onConfigure, onGamesChanged, scanIntervalS }: {
session: ClipperSession; name: string; clips: Clip[]; games: Game[]; onChanged: () => void; onShowClips: (id: number) => void;
onConfigure: (session: ClipperSession) => void; onGamesChanged: (games: Game[]) => void; scanIntervalS: number;
}) {
const { pending, message, run } = useClipperAction(onChanged);
const [chartOpen, setChartOpen] = useState(false);
const chartId = useId();
const frame = STATUS_FRAME[s.status];
const live = s.status === "recording" || s.status === "starting";
const active = ACTIVE_SESSION.includes(s.status);
const totalClips = CLIP_STATUS_ORDER.reduce((n, k) => n + (s.clips[k] ?? 0), 0);
const lastMemory = s.memory?.length ? s.memory[s.memory.length - 1] : null;
const confirmedGame = s.gameSource === "user";
const mismatch = Boolean(s.game && s.screenGame && !confirmedGame && gameIdOf(s.screenGame) !== gameIdOf(s.game));
const health = sessionHealth(s, mismatch);
const showNow = Boolean(lastMemory?.summary) || s.game !== undefined;
// Relógio da gravação: anda a cada segundo só enquanto grava; os números que dependem dele se inscrevem sozinhos.
const clock = useRecordingClock(s.durationS, s.status === "recording");
return (
<article aria-label={`Sessão ${s.id}: ${name}`}
// contain: a largura do cartão vem da página, nunca do texto (linhas truncadas longas não alargam a tela).
className={cx("overflow-hidden rounded-card border bg-surface shadow-card [contain:inline-size]", frame.border)}>
{/* 1. Quem, estado, tempo e ações principais */}
<header className="flex flex-wrap items-start gap-x-5 gap-y-3 px-5 pt-4 pb-3">
<span className={cx("grid size-11 shrink-0 place-items-center rounded-control border", frame.icon)}>
<PlatformIcon platform={s.platform} size={20} />
</span>
<div className="grid min-w-[min(100%,18rem)] flex-1 gap-1">
<p className="flex flex-wrap items-center gap-2">
<span className="font-display text-[1.0625rem] leading-tight font-semibold text-fg">{name}</span>
<StatusBadge status={s.status} clock={clock} />
<Badge dot={false}>{s.kind === "vod" ? "VOD" : "live"}</Badge>
</p>
<p className="flex flex-wrap items-center gap-x-2 text-xs text-fg-subtle">
<span>#{s.id}</span><Dot /><span>{PLATFORM_LABEL[s.platform]}</span><Dot />
<span>início {formatDate(s.startedAt)}</span><Dot />
<CaptureState session={s} live={live} />
<a href={s.url} target="_blank" rel="noreferrer noopener"
className="max-w-72 truncate rounded-sm hover:text-fg hover:underline focus-visible:outline-2 focus-visible:outline-accent">
{s.url.replace(/^https?:\/\/(www\.)?/, "")}
</a>
</p>
{s.title && <p className="truncate text-[0.8125rem] text-fg-muted" title={s.title}>{s.title}</p>}
</div>
{/* Largura fixa: o relógio anda a cada segundo e o rótulo troca para o aviso sem empurrar nada. */}
<div className="grid w-[8.5rem] shrink-0 justify-items-end gap-0.5 text-right">
<span className="font-display text-2xl leading-none font-semibold text-fg tabular-nums"><ClockText clock={clock} /></span>
<ClockLabel clock={clock} live={live} />
</div>
<div className="flex flex-wrap items-center gap-2">
{live && s.kind === "live" && <CutNow sessionId={s.id} pending={pending} run={run} />}
{active && (
<Button variant="secondary" size="sm" disabled={pending !== null}
onClick={async () => {
if (!(await askConfirm({ title: `Parar a sessão #${s.id}?`,
message: "A gravação para; o que já foi gravado continua sendo analisado.", confirmLabel: "Parar" }))) return;
void run("stop", () => clipperCall(`sessions/${s.id}/stop`, "POST"), "Sessão parada.");
}}>
{pending === "stop" ? <Spinner className="size-3.5" /> : <StopIcon size={15} />}Parar
</Button>
)}
{/* Interrompida = o serviço reiniciou no meio da gravação. Retomar continua NA MESMA sessão (a parte perdida
durante o reinício não existe na gravação); processar encerra e deixa a IA analisar o que foi gravado.
Live em "processando" (retomada automática falhou, live ainda no ar) também pode voltar a gravar: o serviço
confere se o canal está no ar e devolve erro legível se não estiver. */}
{s.kind === "live" && !live && (
<Button variant={s.status === "interrupted" ? "primary" : "secondary"} size="sm" disabled={pending !== null}
title="Se a live ainda está no ar, volta a gravar nesta mesma sessão."
onClick={() => void run("resume", () => clipperCall(`sessions/${s.id}/resume`, "POST"), "Gravação retomada.")}>
{pending === "resume" ? <Spinner className="size-3.5" /> : <BroadcastIcon size={15} />}Retomar gravação
</Button>
)}
{["interrupted", "stopped", "error"].includes(s.status) && (
<Button variant="secondary" size="sm" disabled={pending !== null}
title="Encerra e manda a IA analisar o que já foi gravado (varredura, juízes e render)."
onClick={() => void run("finish", () => clipperCall(`sessions/${s.id}/finish`, "POST"), "Processando o que foi gravado.")}>
{pending === "finish" ? <Spinner className="size-3.5" /> : <SparkIcon size={15} />}Processar o que foi gravado
</Button>
)}
<Button variant="ghost" size="sm" disabled={pending !== null} aria-label={`Apagar a sessão ${s.id}`}
className="hover:bg-danger-soft hover:text-danger"
onClick={async () => {
if (!(await askConfirm({ title: `Apagar a sessão #${s.id}?`,
message: "A gravação e TODOS os cortes dela (inclusive aprovados) são apagados. Não dá para desfazer.",
confirmLabel: "Apagar sessão", tone: "danger" }))) return;
void run("delete", () => clipperCall(`sessions/${s.id}`, "DELETE"), "Sessão apagada.");
}}>
{pending === "delete" ? <Spinner className="size-3.5" /> : <TrashIcon size={15} />}Apagar
</Button>
</div>
</header>
{/* 2. Saúde em uma frase (uma linha só: o texto muda, a altura não) */}
<p title={health.full}
className={cx("mx-5 flex h-9 items-center gap-2 rounded-control border px-3 text-[0.8125rem] font-medium",
health.tone === "success" ? "border-success/20 bg-success-soft/50"
: health.tone === "warning" ? "border-warning/25 bg-warning-soft/60"
: health.tone === "danger" ? "border-danger/30 bg-danger-soft/60"
: health.tone === "info" ? "border-info/20 bg-info-soft/50" : "border-line bg-raised/50",
TONE_TEXT[health.tone])}>
{health.tone === "success" ? <CheckIcon size={15} className="shrink-0" />
: health.tone === "warning" || health.tone === "danger" ? <AlertIcon size={15} className="shrink-0" />
: active ? <Spinner className="size-3.5 shrink-0" /> : <BroadcastIcon size={15} className="shrink-0" />}
<span className="min-w-0 truncate">{health.text}</span>
</p>
<div className="grid gap-4 px-5 pt-4 pb-5">
{/* 3. O que está acontecendo: resumo da IA + jogo */}
{showNow && (
<section aria-label="O que está acontecendo" className="grid rounded-control border border-line bg-raised/40">
{lastMemory?.summary && (
<div className="flex items-start gap-2.5 px-4 py-3">
<SparkIcon size={15} className="mt-0.5 shrink-0 text-violet" />
{/* Duas linhas reservadas: o resumo novo (a cada 3 min) não muda a altura do cartão. */}
<p className="line-clamp-2 min-h-[2lh] min-w-0 flex-1 text-[0.8125rem] leading-relaxed text-fg-muted" title={lastMemory.summary}>
<span className="font-semibold text-violet">{live ? "Agora na live" : "Último resumo da IA"}</span>
<span className="text-fg-subtle tabular-nums"> · {formatClock(lastMemory.fromS)}–{formatClock(lastMemory.toS)}</span>
<span className="text-fg-subtle">: </span>{lastMemory.summary}
</p>
<SummaryCadence clock={clock} live={live} scannedUntilS={s.scannedUntilS ?? null} intervalS={scanIntervalS} />
</div>
)}
{s.game !== undefined && (
<div className={cx("px-4 py-2", lastMemory?.summary && "border-t border-line")}>
<SessionGame session={s} games={games} onChanged={onChanged} onGamesChanged={onGamesChanged} />
</div>
)}
</section>
)}
{/* 4. Saúde do pipeline: quatro blocos com a mesma estrutura (rótulo/estado, número, barra, detalhe) */}
<dl className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
<ChatTile session={s} live={live} />
<TranscriptTile session={s} live={live} active={active} />
<ScanTile session={s} live={live} active={active} clock={clock} intervalS={scanIntervalS} />
<ClipsTile session={s} total={totalClips} active={active} />
</dl>
{s.error && <p className="rounded-control border border-danger/30 bg-danger-soft px-3 py-2 font-mono text-xs break-words text-danger">{s.error}</p>}
</div>
{/* 5. Ferramentas: tudo o que é secundário num lugar só. Os painéis abertos (gráfico, emotes) ocupam a linha toda abaixo. */}
<div role="group" aria-label="Ferramentas da sessão"
className="flex flex-wrap items-center gap-2 border-t border-line bg-sunken/40 px-5 py-2.5">
<Button variant="secondary" size="sm" onClick={() => onConfigure(s)}>
<SettingsIcon size={15} />Configurar corte
{s.hasOwnSettings && <><span aria-hidden="true" className="size-1.5 rounded-full bg-accent" /><span className="sr-only">(com ajustes próprios)</span></>}
</Button>
<CameraState session={s} live={live} />
<span aria-hidden="true" className="mx-1 h-5 w-px bg-line-strong" />
{totalClips > 0 && (
<Button variant="ghost" size="sm" onClick={() => onShowClips(s.id)}><ScissorsIcon size={15} />Ver cortes desta sessão</Button>
)}
<Button variant="ghost" size="sm" aria-expanded={chartOpen} aria-controls={chartId} onClick={() => setChartOpen((o) => !o)}>
<ChartIcon size={15} />Gráfico do chat
<ChevronDownIcon size={14} className={cx("transition-transform motion-reduce:transition-none", chartOpen && "rotate-180")} />
</Button>
{/* O painel de emotes (clipper-games) traz o próprio botão e a tabela: `contents` põe os dois direto nesta
linha — o botão ao lado dos outros e a tabela, quando aberta, na linha de baixo inteira. */}
{s.game !== undefined && (
<div className="contents [&>div]:contents [&>div>div:nth-child(2)]:order-last [&>div>div:nth-child(2)]:basis-full [&>div>div:nth-child(2)]:pt-1 [&>div>div:nth-child(2)]:pb-2">
<ChannelEmotes channelKey={channelKeyOf(s)} />
</div>
)}
{chartOpen && <div id={chartId} className="order-last basis-full pt-1 pb-2"><SessionTimeline session={s} clips={clips} /></div>}
</div>
<div aria-live="polite" className="px-5 empty:hidden [&:not(:empty)]:pb-4">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</article>
);
}
function Dot() {
return <span aria-hidden="true" className="text-line-strong">·</span>;
}
/* ---------- Relógio da gravação ---------- */
// O `durationS` do serviço só sobe quando um bloco .ts fecha (a cada 30 s) e a página consulta a cada 5 s. Enquanto
// grava, o relógio anda sozinho a partir do último valor real e da hora em que ele chegou, com um teto para não
// inventar tempo: passou do teto sem bloco novo, ele para e o cartão mostra que está esperando.
/** Quanto o relógio pode andar além do último `durationS` real (um bloco de 30 s + a consulta de 5 s + folga). */
const CLOCK_MAX_AHEAD_S = 45;
/** Passo da conferência: curto para o segundo virar no momento certo; só avisa quem lê quando o número muda. */
const CLOCK_TICK_MS = 250;
/** Ao voltar à aba, a página reconsulta o serviço: espera isso antes de acusar "aguardando" pelo tempo escondido. */
const CLOCK_VISIBLE_GRACE_MS = 6000;
class RecordingClock {
private realS: number;
private running: boolean;
private receivedAt = performance.now();
private visibleSince = performance.now();
private shown: number;
private stalled = false;
private mounted = false;
private timer: ReturnType<typeof setInterval> | null = null;
private readonly listeners = new Set<() => void>();
constructor(realS: number, running: boolean) {
this.realS = realS;
this.running = running;
this.shown = running ? Math.floor(realS) : realS;
}
readonly subscribe = (listener: () => void) => {
this.listeners.add(listener);
return () => { this.listeners.delete(listener); };
};
/** Segundos exibidos: nunca voltam enquanto grava. Parado, é o valor real. */
readonly getShown = () => this.shown;
/** Chegou ao teto sem bloco novo: o relógio está parado esperando o serviço. */
readonly getStalled = () => this.stalled;
/** Estimativa contínua da gravação agora (já com o teto). */
estimate(): number {
return this.running ? this.realS + Math.min(CLOCK_MAX_AHEAD_S, (performance.now() - this.receivedAt) / 1000) : this.realS;
}
/** Valor novo da consulta. Menor que o exibido: o exibido segura até a estimativa alcançar; maior: pula. */
sync(realS: number, running: boolean) {
if (realS !== this.realS || running !== this.running) {
this.realS = realS;
this.receivedAt = performance.now();
}
this.running = running;
this.schedule();
this.update();
}
/** Liga o passo do relógio (só com o cartão na tela); devolve a limpeza. */
mount() {
this.mounted = true;
this.visibleSince = performance.now();
document.addEventListener("visibilitychange", this.onVisibility);
this.schedule();
this.update();
return () => {
this.mounted = false;
document.removeEventListener("visibilitychange", this.onVisibility);
this.schedule();
};
}
private readonly onVisibility = () => {
if (document.visibilityState === "visible") this.visibleSince = performance.now();
this.schedule();
this.update();
};
/** Um intervalo só, e só enquanto grava com a aba visível. */
private schedule() {
const wanted = this.mounted && this.running && document.visibilityState === "visible";
if (wanted && this.timer === null) this.timer = setInterval(this.update, CLOCK_TICK_MS);
else if (!wanted && this.timer !== null) {
clearInterval(this.timer);
this.timer = null;
}
}
private readonly update = () => {
let shown = this.realS;
let stalled = false;
if (this.running) {
const now = performance.now();
const elapsed = (now - this.receivedAt) / 1000;
shown = Math.max(Math.floor(this.shown), Math.floor(this.realS + Math.min(CLOCK_MAX_AHEAD_S, elapsed)));
stalled = elapsed >= CLOCK_MAX_AHEAD_S && now - this.visibleSince >= CLOCK_VISIBLE_GRACE_MS;
}
if (shown === this.shown && stalled === this.stalled) return;
this.shown = shown;
this.stalled = stalled;
for (const listener of this.listeners) listener();
};
}
/** Um relógio por cartão. O cartão não re-renderiza a cada segundo: só os números inscritos nele. */
function useRecordingClock(durationS: number, running: boolean): RecordingClock {
const [clock] = useState(() => new RecordingClock(durationS, running));
// Antes da pintura: o valor novo da consulta não aparece um quadro atrasado.
useLayoutEffect(() => { clock.sync(durationS, running); }, [clock, durationS, running]);
useEffect(() => clock.mount(), [clock]);
return clock;
}
function useClockShown(clock: RecordingClock): number {
return useSyncExternalStore(clock.subscribe, clock.getShown, clock.getShown);
}
function useClockStalled(clock: RecordingClock): boolean {
return useSyncExternalStore(clock.subscribe, clock.getStalled, clock.getStalled);
}
function ClockText({ clock }: { clock: RecordingClock }) {
return <>{formatClock(useClockShown(clock))}</>;
}
function ClockLabel({ clock, live }: { clock: RecordingClock; live: boolean }) {
const stalled = useClockStalled(clock);
if (stalled) {
return (
<span className="max-w-full truncate text-xs font-medium text-warning"
title={`Nenhum bloco novo há mais de ${CLOCK_MAX_AHEAD_S} s: o relógio parou no último tempo provável e espera a gravação.`}>
aguardando o bloco
</span>
);
}
return <span className="max-w-full truncate text-xs text-fg-subtle">{live ? "gravados" : "de duração"}</span>;
}
/** Selo do estado. Gravando sem bloco novo além do teto: mesmo texto (a largura não muda), em alerta e sem pulsar. */
function StatusBadge({ status, clock }: { status: ClipperSession["status"]; clock: RecordingClock }) {
const stalled = useClockStalled(clock) && status === "recording";
const info = SESSION_STATUS[status];
return (
<span className="inline-flex" title={stalled ? "A gravação não entrega um bloco novo há mais do que o esperado." : undefined}>
<Badge tone={stalled ? "warning" : info.tone} pulse={!stalled && info.pulse}>{info.label}</Badge>
</span>
);
}
/* ---------- Cadência do resumo ---------- */
/** Intervalo da varredura em uso no serviço (`judge.options.scanIntervalS` em /status), lido uma vez por montagem. */
function useScanInterval(): number {
const [intervalS, setIntervalS] = useState(SCAN_WINDOW_S);
useEffect(() => {
let cancelled = false;
void clipperCall<{ judge?: { options?: JudgeOptions } }>("status").then((r) => {
const value = r.ok ? r.data.judge?.options?.scanIntervalS : undefined;
if (!cancelled && typeof value === "number" && value > 0) setIntervalS(value);
});
return () => { cancelled = true; };
}, []);
return intervalS;
}
/**
* Quando vem o próximo resumo. No serviço (intel.scan_due/scan_session), a janela seguinte é
* [scannedUntilS, scannedUntilS + intervalo]; ela só é varrida quando a transcrição passa do fim dela, o laço da
* varredura confere a cada 20 s (worker._scan_loop) e a IA leva o tempo da CLI. Só então o resumo e o
* `scannedUntilS` são gravados. Por isso a previsão = fim da janela + a demora da IA medida nesta tela (a diferença
* entre o relógio e o novo `scannedUntilS` quando ele avança); antes da 1ª medida, conta só até o fim da janela.
*/
function SummaryCadence({ clock, live, scannedUntilS, intervalS }: {
clock: RecordingClock; live: boolean; scannedUntilS: number | null; intervalS: number;
}) {
const shown = useClockShown(clock);
const [seen, setSeen] = useState({ scannedUntilS, delayS: 0 });
if (scannedUntilS !== seen.scannedUntilS) {
// Estado derivado (padrão do React para "valor anterior"): mede a demora só quando a janela avança uma vez.
const stepped = seen.scannedUntilS !== null && scannedUntilS !== null && scannedUntilS > seen.scannedUntilS;
setSeen({
scannedUntilS,
delayS: stepped ? Math.min(intervalS, Math.max(0, clock.estimate() - (scannedUntilS ?? 0))) : seen.delayS,
});
}
const cadence = `atualiza a cada ${formatDuration(intervalS)}`;
let next: string;
let tone = "text-fg-subtle";
if (!live || scannedUntilS === null) next = "último resumo";
else {
const remaining = scannedUntilS + intervalS + seen.delayS - shown;
if (remaining >= 1) next = `próximo em ${formatClock(remaining)}`;
else { next = "gerando o próximo resumo…"; tone = "text-violet"; }
}
return (
// Largura e duas linhas fixas, dentro da altura das duas linhas do resumo: a contagem não empurra o texto.
<p className="grid w-48 shrink-0 text-right text-xs leading-5 tabular-nums">
<span className="truncate text-fg-subtle">{live ? cadence : "fora de gravação"}</span>
<span className={cx("truncate", tone)}>{next}</span>
</p>
);
}
/** Resolução gravada de fato (1º bloco). Ao vivo sem bloco ainda: aviso no mesmo lugar, para a linha não mudar de forma. */
function CaptureState({ session: s, live }: { session: ClipperSession; live: boolean }) {
if (s.capture === undefined || (s.capture === null && !live)) return null; // serviço antigo ou sessão antiga
if (s.capture === null) return <><span>resolução: aguardando o 1º bloco</span><Dot /></>;
const c = s.capture;
const detail = [`pedido: ${CAPTURE_ASKED[c.quality] ?? c.quality}`, c.codec.toUpperCase(),
c.gbPerHour ? `≈ ${gbPerHourLabel(c.gbPerHour)}` : "", c.mixed ? "há trechos gravados em outra resolução" : ""].filter(Boolean).join(" · ");
return (
<>
<span title={`Gravação: ${captureLabel(c)} · ${detail}`} className={cx("tabular-nums", c.mixed && "text-warning")}>
{live ? "gravando em" : "gravado em"} <span className="font-mono text-fg-muted">{captureLabel(c)}</span>
</span>
<Dot />
</>
);
}
const CAPTURE_ASKED: Record<string, string> = {
best: "melhor disponível", "1440p": "até 1440p", "1080p": "até 1080p", "720p": "até 720p", "480p": "até 480p",
};
/** Câmera do streamer: achada pela IA, pelo rosto, marcada à mão, ausente ou ainda não procurada. */
function CameraState({ session: s, live }: { session: ClipperSession; live: boolean }) {
if (s.camDetect === undefined) return null; // serviço antigo: não há detecção
if (s.camDetect === null) {
return <Badge tone={live ? "warning" : "neutral"}>{live ? "câmera ainda não identificada" : "câmera não marcada"}</Badge>;
}
const c = s.camDetect;
return (
<Badge tone={c.hasWebcam || c.source === "manual" ? "success" : "neutral"}>
{c.source === "manual" ? "câmera marcada por você"
: !c.hasWebcam ? "sem webcam na tela"
: c.source === "yunet" ? "câmera achada (rosto, sem IA)" : "câmera achada pela IA"}
</Badge>
);
}
/* ---------- Blocos do pipeline ---------- */
/** Bloco de altura fixa: cabeçalho (rótulo + estado), número grande, barra (ou espaço reservado) e uma linha de detalhe. */
function Tile({ icon, label, state, value, unit, meter, detail, detailTone }: {
icon: ReactNode; label: string; state: { tone: Tone; text: string; pulse?: boolean };
value: ReactNode; unit?: ReactNode; meter?: ReactNode; detail: ReactNode; detailTone?: Tone;
}) {
return (
<div className="grid min-w-0 content-start gap-2.5 rounded-control border border-line bg-raised/40 px-4 py-3">
<dt className="flex items-center justify-between gap-2">
<span className="flex items-center gap-1.5 text-eyebrow font-semibold text-fg-subtle uppercase">{icon}{label}</span>
<Badge tone={state.tone} pulse={state.pulse}>{state.text}</Badge>
</dt>
<dd className="grid gap-2.5">
<p className="flex min-w-0 items-baseline gap-1.5">
<span className="font-display text-[1.625rem] leading-none font-semibold text-fg tabular-nums">{value}</span>
{unit && <span className="truncate text-xs text-fg-subtle tabular-nums">{unit}</span>}
</p>
<div className="h-1.5">{meter}</div>
<p className={cx("truncate text-xs tabular-nums", detailTone ? TONE_TEXT[detailTone] : "text-fg-subtle")}
title={typeof detail === "string" ? detail : undefined}>
{detail}
</p>
</dd>
</div>
);
}
function ChatTile({ session: s, live }: { session: ClipperSession; live: boolean }) {
const chat = chatStatusInfo(s.chatStatus);
const error = s.chatStatus.startsWith("error") ? s.chatStatus.replace(/^error:\s*/, "") : null;
// Rótulo curto no selo; o texto completo do estado vai para a linha de detalhe.
const short = s.chatStatus === "connected" ? "conectado" : s.chatStatus === "connecting" ? "conectando"
: s.chatStatus === "unsupported" ? "sem chat" : error ? "erro" : "desligado";
return (
<Tile icon={<ChatIcon size={13} />} label="Chat" state={{ tone: chat.tone, text: short, pulse: live && s.chatStatus === "connected" }}
value={formatInteger(s.chatMessages)} unit={`mensage${s.chatMessages === 1 ? "m" : "ns"}`}
detail={error ?? (s.chatStatus === "unsupported" ? "a plataforma não tem chat para ler"
: live && s.chatStatus === "connected" ? "lendo em tempo real" : chat.label)}
detailTone={error ? "danger" : undefined} />
);
}
function TranscriptTile({ session: s, live, active }: { session: ClipperSession; live: boolean; active: boolean }) {
const seg = s.segments;
const waiting = seg.total - seg.analyzed;
const state: { tone: Tone; text: string; pulse?: boolean } =
seg.total === 0 ? (active ? { tone: "info", text: "esperando", pulse: true } : { tone: "neutral", text: "vazia" })
: waiting <= 0 ? { tone: "success", text: "em dia" }
: live && waiting > TRANSCRIPT_LATE_SEGMENTS ? { tone: "warning", text: "atrasada" }
: active ? { tone: "info", text: `${waiting} na fila`, pulse: true } : { tone: "neutral", text: `${waiting} pendentes` };
return (
<Tile icon={<MicIcon size={13} />} label="Transcrição" state={state}
value={formatInteger(seg.analyzed)} unit={`de ${formatInteger(seg.total)} trecho${seg.total === 1 ? "" : "s"} de 30 s`}
meter={<ProgressBar value={seg.total ? seg.analyzed / seg.total : active ? undefined : 0} label={`Trechos analisados da sessão ${s.id}`} />}
detail={seg.transcriptErrors > 0
? `${seg.transcriptErrors} trecho${seg.transcriptErrors === 1 ? "" : "s"} sem fala reconhecida`
: "fala e volume de cada trecho"}
detailTone={seg.transcriptErrors > 0 ? "warning" : undefined} />
);
}
function ScanTile({ session: s, live, active, clock, intervalS }: {
session: ClipperSession; live: boolean; active: boolean; clock: RecordingClock; intervalS: number;
}) {
const scanned = s.scannedUntilS ?? null;
if (scanned === null) {
return (
<Tile icon={<EyeIcon size={13} />} label="IA assistiu" state={{ tone: "neutral", text: "desligada" }}
value="—" detail="varredura da IA desligada nesta sessão" />
);
}
const lag = Math.max(0, s.durationS - scanned);
const state: { tone: Tone; text: string; pulse?: boolean } =
live ? (lag > SCAN_LATE_S ? { tone: "warning", text: "atrasada" } : { tone: "success", text: "em dia" })
: lag < SCAN_WINDOW_S ? { tone: "success", text: "completa" }
: active ? { tone: "info", text: "assistindo", pulse: true } : { tone: "neutral", text: "parcial" };
return (
<Tile icon={<EyeIcon size={13} />} label="IA assistiu" state={state}
// O quanto a IA assistiu é sempre o real; só o total ("de H:MM:SS") acompanha o relógio da gravação.
value={formatClock(scanned)} unit={<>de <ClockText clock={clock} /></>}
meter={<ProgressBar value={s.durationS > 0 ? scanned / s.durationS : 0} label={`Quanto da sessão ${s.id} a IA já assistiu`} />}
detail={live ? `olha janelas de ${formatDuration(intervalS)} · ${lag < 1 ? "em dia" : `${formatDuration(lag)} atrás`}`
: lag < SCAN_WINDOW_S ? "assistiu a sessão inteira" : `faltam ${formatDuration(lag)}`}
detailTone={live && lag > SCAN_LATE_S ? "warning" : undefined} />
);
}
/** Estados que entram no detalhe do bloco de cortes (o "pronto para aprovar" é o número grande). */
const CLIP_DETAIL_ORDER: ClipStatus[] = CLIP_STATUS_ORDER.filter((k) => k !== "ready");
const CLIP_IN_PROGRESS: ClipStatus[] = ["candidate", "pending", "rendering"];
function ClipsTile({ session: s, total, active }: { session: ClipperSession; total: number; active: boolean }) {
const ready = s.clips.ready ?? 0;
const working = CLIP_IN_PROGRESS.reduce((n, k) => n + (s.clips[k] ?? 0), 0);
const parts = CLIP_DETAIL_ORDER.filter((k) => (s.clips[k] ?? 0) > 0).map((k) => `${s.clips[k]} ${CLIP_STATUS[k].label}`);
const state: { tone: Tone; text: string; pulse?: boolean } =
working > 0 ? { tone: "violet", text: `IA avaliando ${working}`, pulse: true }
: total > 0 ? { tone: "neutral", text: `${total} no total` }
: { tone: "neutral", text: active ? "nenhum ainda" : "nenhum" };
return (
<Tile icon={<ScissorsIcon size={13} />} label="Cortes" state={state}
value={<span className={ready > 0 ? "text-accent" : undefined}>{formatInteger(ready)}</span>} unit="para aprovar"
meter={total > 0 ? (
<div role="img" aria-label={`Cortes da sessão ${s.id} por estado: ${[`${ready} pronto para aprovar`, ...parts].join(", ")}`}
className="flex h-1.5 w-full gap-px overflow-hidden rounded-full bg-overlay">
{CLIP_STATUS_ORDER.filter((k) => (s.clips[k] ?? 0) > 0).map((k) => (
<span key={k} className={cx("h-full", TONE_FILL[CLIP_STATUS[k].tone])} style={{ width: `${((s.clips[k] ?? 0) / total) * 100}%` }} />
))}
</div>
) : <div className="h-1.5 w-full rounded-full bg-overlay" />}
detail={parts.length ? parts.join(" · ") : total > 0 ? "todos prontos para aprovar" : active ? "a IA ainda não achou um momento" : "nenhum corte nesta sessão"} />
);
}
/* ---------- Gráfico de mensagens/s ---------- */
/** Pontos no máximo: sessões de horas são agrupadas (máximo de cada grupo) para o SVG ficar leve. */
const MAX_POINTS = 480;
const CHART_H = 100;
function SessionTimeline({ session, clips }: { session: ClipperSession; clips: Clip[] }) {
const [data, setData] = useState<Timeline | null>(null);
const [error, setError] = useState<string | null>(null);
const live = ACTIVE_SESSION.includes(session.status);
// Ao vivo, o gráfico acompanha a duração (que muda a cada consulta da página).
const refreshKey = live ? Math.floor(session.durationS / 30) : 0;
useEffect(() => {
let cancelled = false;
void clipperCall<Timeline>(`sessions/${session.id}/timeline`).then((r) => {
if (cancelled) return;
if (r.ok) { setData(r.data); setError(null); } else setError(r.error);
});
return () => { cancelled = true; };
}, [session.id, refreshKey]);
if (error) return <Feedback ok={false}>Não deu para ler o gráfico: {error}</Feedback>;
if (!data) return <p role="status" className="flex items-center gap-2 text-xs text-fg-muted"><Spinner className="size-3.5" />Carregando o gráfico…</p>;
if (data.messagesPerS.length === 0 || data.durationS <= 0) {
return <p className="text-xs text-fg-subtle">Sem mensagens de chat registradas nesta sessão.</p>;
}
const series = data.messagesPerS;
const bucket = Math.max(1, Math.ceil(series.length / MAX_POINTS));
const points: number[] = [];
for (let i = 0; i < series.length; i += bucket) points.push(Math.max(...series.slice(i, i + bucket)));
const peak = Math.max(1, ...points);
const width = points.length;
const secondsPerPoint = data.durationS / width;
const y = (v: number) => CHART_H - (v / peak) * (CHART_H - 6);
const area = `M0 ${CHART_H} ${points.map((v, i) => `L${i} ${y(v).toFixed(1)} L${i + 1} ${y(v).toFixed(1)}`).join(" ")} L${width} ${CHART_H} Z`;
const x = (s: number) => Math.min(width, Math.max(0, s / secondsPerPoint));
const ticks = [0, 0.25, 0.5, 0.75, 1];
return (
<figure className="grid gap-2">
<div className="relative rounded-control border border-line bg-sunken/50 p-2">
<svg viewBox={`0 0 ${width} ${CHART_H}`} preserveAspectRatio="none" className="block h-28 w-full" role="img"
aria-label={`Mensagens por segundo ao longo de ${formatClock(data.durationS)}; pico de ${peak} por segundo; ${clips.length} corte${clips.length === 1 ? "" : "s"} marcado${clips.length === 1 ? "" : "s"}.`}>
{clips.map((c) => (
<rect key={c.id} x={x(c.startS)} y={0} width={Math.max(0.6, x(c.endS) - x(c.startS))} height={CHART_H}
fill={c.status === "discarded" || c.status === "rejected" ? "var(--color-fg-subtle)" : "var(--color-accent)"}
opacity={c.status === "discarded" || c.status === "rejected" ? 0.12 : 0.2}>
<title>{`Corte ${c.id} · ${CLIP_STATUS[c.status].label} · ${formatClock(c.startS)}–${formatClock(c.endS)}`}</title>
</rect>
))}
<path d={area} fill="var(--color-option-b)" fillOpacity={0.35} stroke="var(--color-option-b)" strokeWidth={1}
vectorEffect="non-scaling-stroke" />
{clips.map((c) => (
<line key={`p${c.id}`} x1={x(c.peakS)} x2={x(c.peakS)} y1={0} y2={CHART_H} stroke="var(--color-accent)" strokeWidth={1.5}
vectorEffect="non-scaling-stroke" />
))}
</svg>
</div>
<div className="relative h-4 text-[0.6875rem] text-fg-subtle tabular-nums" aria-hidden="true">
{ticks.map((t) => (
<span key={t} className={cx("absolute top-0", t === 0 ? "left-2" : t === 1 ? "right-2" : "-translate-x-1/2")}
style={t > 0 && t < 1 ? { left: `${t * 100}%` } : undefined}>
{formatClock(data.durationS * t)}
</span>
))}
</div>
<figcaption className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-fg-subtle">
<span className="inline-flex items-center gap-1.5"><span className="size-2.5 rounded-sm bg-option-b/60" />mensagens/s (pico {peak})</span>
<span className="inline-flex items-center gap-1.5"><span className="size-2.5 rounded-sm bg-accent/40" />trecho do corte</span>
<span className="inline-flex items-center gap-1.5"><span className="h-2.5 w-0.5 bg-accent" />pico usado no corte</span>
<span>{formatDuration(data.durationS)} no total</span>
</figcaption>
</figure>
);
}
+333
View File
@@ -0,0 +1,333 @@
"use client";
// Página do Clipador: lê estado, cortes, sessões e canais de /api/clipper/* e distribui em abas —
// Fila de cortes (o foco), Sessões, Canais e Juiz (IA). Acima das abas ficam o resumo do serviço e
// as lives gravando agora, com "Cortar agora" sempre à mão.
// Consulta de novo a cada 5 s enquanto houver sessão gravando/processando ou corte na fila (e a cada
// 10 s com o serviço fora do ar, para perceber quando ele volta); para quando a aba fica oculta.
import Link from "next/link";
import { useCallback, useEffect, useState, type ReactNode } from "react";
import { ChannelAddForm, ChannelList, type ChannelAccounts } from "./clipper-channels";
import {
ACTIVE_CLIP, ACTIVE_SESSION, PROVIDER_LABEL, clipperCall, formatClock, formatScore, isOfflineError, sourceName, useClipperAction,
type Clip, type ClipperChannel, type ClipperSession, type ClipperStatus, type Game, type JudgeConfig,
} from "./clipper-client";
import { CutSettingsDialog, type CutScope } from "./clipper-cut-settings";
import { GamesPanel } from "./clipper-games";
import { JudgeForm } from "./clipper-judge";
import { ClipQueue } from "./clipper-queue";
import { CutNow, PlatformIcon, RecordForm, SessionList } from "./clipper-sessions";
import { AlertIcon, BookIcon, BroadcastIcon, ListIcon, MicIcon, RefreshIcon, ScissorsIcon, ServerIcon, SparkIcon, StopIcon } from "./icons";
import { Tabs } from "./tabs";
import { Badge, Button, Card, Feedback, SectionHeader, Spinner, cx, formatInteger } from "./ui";
import { askConfirm } from "./confirm-dialog";
const POLL_ACTIVE_MS = 5000;
const POLL_OFFLINE_MS = 10_000;
type Data = { status: ClipperStatus; clips: Clip[]; sessions: ClipperSession[]; channels: ClipperChannel[] };
type TabId = "cortes" | "sessoes" | "canais" | "jogos" | "juiz";
/** Troca de aba pela URL (o componente Tabs lê ?tab=). */
function goToTab(tab: TabId) {
const params = new URLSearchParams(window.location.search);
if (tab === "cortes") params.delete("tab");
else params.set("tab", tab);
const query = params.toString();
window.history.pushState(null, "", `${window.location.pathname}${query ? `?${query}` : ""}`);
window.scrollTo({ top: 0, behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" });
}
export function ClipperStudio({ channelAccounts }: { channelAccounts: ChannelAccounts }) {
const [data, setData] = useState<Data | null>(null);
const [judge, setJudge] = useState<JudgeConfig | null>(null);
const [offline, setOffline] = useState<string | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [refreshing, setRefreshing] = useState(false);
const [loadedOnce, setLoadedOnce] = useState(false);
const [visible, setVisible] = useState(true);
const [sessionFilter, setSessionFilter] = useState<number | null>(null);
// Jogos pesquisados pela IA; null = serviço antigo, sem a rota /games.
const [games, setGames] = useState<Game[] | null>(null);
const [cutScope, setCutScope] = useState<CutScope | null>(null);
const refresh = useCallback(async (withJudge = false) => {
setRefreshing(true);
const [status, clips, sessions, channels, judgeResult, gamesResult] = await Promise.all([
clipperCall<ClipperStatus>("status"),
clipperCall<{ clips: Clip[] }>("clips?limit=500"),
clipperCall<{ sessions: ClipperSession[] }>("sessions?limit=50"),
clipperCall<{ channels: ClipperChannel[] }>("channels"),
withJudge ? clipperCall<JudgeConfig>("judge") : Promise.resolve(null),
clipperCall<{ games: Game[] }>("games"),
]);
setRefreshing(false);
setLoadedOnce(true);
if (!status.ok) {
if (isOfflineError(status.error)) { setOffline(status.error); setLoadError(null); }
else setLoadError(status.error);
return;
}
setOffline(null);
const firstError = [clips, sessions, channels].find((r) => !r.ok);
setLoadError(firstError && !firstError.ok ? firstError.error : null);
setData((prev) => ({
status: status.data,
clips: clips.ok ? clips.data.clips : prev?.clips ?? [],
sessions: sessions.ok ? sessions.data.sessions : prev?.sessions ?? [],
channels: channels.ok ? channels.data.channels : prev?.channels ?? [],
}));
if (judgeResult?.ok) setJudge(judgeResult.data);
setGames(gamesResult.ok ? gamesResult.data.games : null);
}, []);
useEffect(() => { void refresh(true); }, [refresh]);
useEffect(() => {
const onVisibility = () => {
const now = document.visibilityState === "visible";
setVisible(now);
if (now) void refresh();
};
document.addEventListener("visibilitychange", onVisibility);
return () => document.removeEventListener("visibilitychange", onVisibility);
}, [refresh]);
const active = Boolean(data && (data.sessions.some((s) => ACTIVE_SESSION.includes(s.status)) || data.clips.some((c) => ACTIVE_CLIP.includes(c.status))));
const interval = !visible ? null : offline ? POLL_OFFLINE_MS : active ? POLL_ACTIVE_MS : null;
useEffect(() => {
if (interval === null) return;
// Voltou do "fora do ar": recarrega também o juiz.
const timer = setInterval(() => void refresh(offline !== null), interval);
return () => clearInterval(timer);
}, [interval, offline, refresh]);
const reload = useCallback(() => void refresh(), [refresh]);
if (!loadedOnce) {
return <div role="status" className="flex items-center gap-3 text-sm text-fg-muted"><Spinner />Consultando o Clipador…</div>;
}
if (offline || !data) {
return (
<div className="grid gap-4">
<div role="alert" className="grid gap-2 rounded-card border border-danger/30 bg-danger-soft px-5 py-4 text-sm">
<p className="flex items-start gap-2 font-semibold text-danger"><AlertIcon size={16} className="mt-0.5" />O Clipador está fora do ar.</p>
{(offline ?? loadError) && <p className="font-mono text-xs break-words text-danger/90">{offline ?? loadError}</p>}
<p className="text-fg-muted">
Rode <code>start.bat</code> (ou <code>pnpm dev</code>) para subir o painel com o Clipador (porta 4520). Se ainda não instalou,
rode <code>setup.bat</code> antes. Esta página tenta de novo a cada 10 s.
</p>
</div>
<div>
<Button variant="secondary" onClick={() => void refresh(true)} disabled={refreshing}>
{refreshing ? <Spinner /> : <RefreshIcon size={16} />}Tentar de novo
</Button>
</div>
</div>
);
}
const { status, clips, sessions, channels } = data;
const nameOfSession = (s: ClipperSession) => sourceName(s.channelId, s.url, channels);
const nameOfClip = (c: Clip) => sourceName(c.channelId, c.sessionUrl, channels);
const liveSessions = sessions.filter((s) => s.status === "recording" || s.status === "starting");
const readyCount = clips.filter((c) => c.status === "ready").length;
const refreshButton = (
<Button variant="ghost" size="sm" onClick={() => void refresh(true)} disabled={refreshing} aria-label="Atualizar os dados do Clipador">
{refreshing ? <Spinner className="size-3.5" /> : <RefreshIcon size={15} />}Atualizar
</Button>
);
return (
<div className="grid gap-6">
<Overview status={status} clips={clips} action={refreshButton} polling={interval !== null} />
{loadError && <Feedback ok={false}>Falha ao atualizar parte dos dados: {loadError}</Feedback>}
{liveSessions.length > 0 && (
<section aria-labelledby="ao-vivo" className="grid gap-2">
<h2 id="ao-vivo" className="sr-only">Gravando agora</h2>
{liveSessions.map((s) => <LiveBar key={s.id} session={s} name={nameOfSession(s)} onChanged={reload} />)}
</section>
)}
<Tabs<TabId> label="Seções do Clipador"
items={[
{ id: "cortes", label: "Fila de cortes", icon: <ScissorsIcon size={16} />, count: readyCount },
{ id: "sessoes", label: "Sessões", icon: <BroadcastIcon size={16} />, count: sessions.length },
{ id: "canais", label: "Fontes", icon: <ListIcon size={16} />, count: channels.length },
{ id: "jogos", label: "Jogos", icon: <BookIcon size={16} />, ...(games ? { count: games.length } : {}) },
{ id: "juiz", label: "Juiz (IA)", icon: <SparkIcon size={16} /> },
]}
panels={{
cortes: (
<ClipQueue clips={clips} sessions={sessions} sessionFilter={sessionFilter} onSessionFilter={setSessionFilter}
nameOf={nameOfClip} onChanged={reload} />
),
sessoes: <>
<RecordForm onChanged={reload} disabled={false} />
<section aria-labelledby="sessoes-titulo" className="grid gap-4">
<SectionHeader id="sessoes-titulo" title="Sessões"
description="Cada live gravada ou VOD processado, da mais nova para a mais antiga. Apagar uma sessão apaga a gravação e todos os cortes dela."
actions={sessions.length > 0 && (
<span className="flex items-center gap-3 text-xs text-fg-subtle tabular-nums">
{liveSessions.length > 0 && <Badge tone="danger" pulse>{liveSessions.length} gravando</Badge>}
<span>{sessions.length} sess{sessions.length === 1 ? "ão" : "ões"}</span>
</span>
)} />
<SessionList sessions={sessions} clips={clips} games={games ?? []} nameOf={nameOfSession} onChanged={reload}
onShowClips={(id) => { setSessionFilter(id); goToTab("cortes"); }}
onConfigure={(s) => setCutScope({ kind: "session", session: s, name: nameOfSession(s) })}
onGamesChanged={setGames} />
</section>
</>,
canais: <>
<ChannelAddForm onChanged={reload} disabled={false} />
<section aria-labelledby="canais-titulo" className="grid gap-4">
<SectionHeader id="canais-titulo" title="Fontes"
description={<>As lives de onde saem os cortes. Para publicar os cortes de uma fonte, ligue-a a um canal em <Link href="/accounts" className="text-fg underline underline-offset-2 hover:text-accent">Canais de publicação</Link>.</>} />
<ChannelList channels={channels} accounts={channelAccounts} onChanged={reload} showEmotes={games !== null}
onConfigure={(c) => setCutScope({
kind: "channel", channel: c,
// Sessões vêm da mais nova para a mais antiga: a primeira do canal dá o quadro de referência.
session: sessions.find((s) => s.channelId === c.id) ?? null,
})} />
</section>
</>,
jogos: (
<section aria-labelledby="jogos-titulo" className="grid gap-4">
<SectionHeader id="jogos-titulo" title="O que a IA sabe dos jogos"
description="Perfil pesquisado na web para cada jogo das lives: o que rende corte, o que evitar, gírias e novidades. A IA usa isso para entender o que está acontecendo na tela." />
<GamesPanel games={games ?? []} available={games !== null} onGamesChanged={setGames} />
</section>
),
juiz: judge
? <JudgeForm key={JSON.stringify([judge.provider, judge.model, judge.minScore, judge.available])} judge={judge} onSaved={setJudge} />
: (
<Card>
<div className="grid justify-items-start gap-3">
<Feedback ok={false}>Não foi possível ler a configuração do juiz.</Feedback>
<Button variant="secondary" size="sm" onClick={() => void refresh(true)}><RefreshIcon size={15} />Tentar de novo</Button>
</div>
</Card>
),
}} />
<CutSettingsDialog scope={cutScope} onClose={() => setCutScope(null)} onSaved={reload} />
</div>
);
}
/* ---------- Resumo do serviço ---------- */
function StatusItem({ icon, label, children }: { icon: ReactNode; label: string; children: ReactNode }) {
return (
<div className="grid content-start gap-1.5 rounded-control border border-line bg-surface px-4 py-3 shadow-card">
<dt className="flex items-center gap-1.5 text-eyebrow font-semibold uppercase text-fg-subtle">{icon}{label}</dt>
<dd className="grid gap-1 text-sm">{children}</dd>
</div>
);
}
function ToolState({ name, path }: { name: string; path: string | null }) {
return (
<span className="flex items-center gap-2 text-xs" title={path ?? undefined}>
<span className={cx("size-1.5 rounded-full", path ? "bg-success" : "bg-danger")} aria-hidden="true" />
<span className={path ? "text-fg-muted" : "text-danger"}>{name} {path ? "ok" : "não encontrado"}</span>
</span>
);
}
function Overview({ status, clips, action, polling }: { status: ClipperStatus; clips: Clip[]; action: ReactNode; polling: boolean }) {
const queued = clips.filter((c) => ACTIVE_CLIP.includes(c.status)).length;
const ready = clips.filter((c) => c.status === "ready").length;
const j = status.judge;
return (
<section aria-labelledby="clipador-resumo" className="grid gap-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<h2 id="clipador-resumo" className="text-title text-fg">Resumo</h2>
<div className="flex items-center gap-3">
{polling && <span className="text-xs text-fg-subtle">atualizando a cada 5 s</span>}
{action}
</div>
</div>
<dl className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
<StatusItem icon={<ServerIcon size={15} />} label="Serviço">
<span className="flex flex-wrap items-center gap-2"><Badge tone="success">online</Badge><span className="text-xs text-fg-subtle">v{status.version}</span></span>
<ToolState name="Streamlink" path={status.tools.streamlink} />
<ToolState name="FFmpeg" path={status.tools.ffmpeg} />
</StatusItem>
<StatusItem icon={<MicIcon size={15} />} label="Transcrição">
{!status.voice.configured ? <span className="text-fg-subtle">serviço de voz não configurado</span>
: status.voice.online ? <span className="text-success">serviço de voz online</span>
: <span className="text-warning">serviço de voz offline</span>}
<span className="text-xs text-fg-subtle">Whisper · {status.settings.language} · trechos de {status.settings.segmentS} s</span>
</StatusItem>
<StatusItem icon={<SparkIcon size={15} />} label="Juiz (IA)">
{j.provider === "off" ? <span className="text-fg">desligado <span className="text-xs text-fg-subtle">· só heurística</span></span> : (
<>
<span className="flex flex-wrap items-center gap-2">
<span className="text-fg">{PROVIDER_LABEL[j.provider]}</span>
{j.available ? <Badge tone="success">disponível</Badge> : <Badge tone="danger">indisponível</Badge>}
</span>
<span className="font-mono text-xs text-fg-subtle">{j.model} · nota mínima {formatScore(j.minScore)}</span>
</>
)}
</StatusItem>
<StatusItem icon={<ScissorsIcon size={15} />} label="Agora">
<span className="flex flex-wrap items-baseline gap-x-4 gap-y-1">
<Count n={status.recording} label="gravando" tone={status.recording > 0 ? "text-danger" : undefined} />
<Count n={queued} label="na fila" />
<Count n={ready} label="para aprovar" tone={ready > 0 ? "text-accent" : undefined} />
</span>
</StatusItem>
</dl>
</section>
);
}
function Count({ n, label, tone }: { n: number; label: string; tone?: string }) {
return (
<span>
<span className={cx("font-display text-xl font-semibold tabular-nums", tone ?? "text-fg")}>{formatInteger(n)}</span>{" "}
<span className="text-xs text-fg-subtle">{label}</span>
</span>
);
}
/* ---------- Live gravando agora ---------- */
function LiveBar({ session: s, name, onChanged }: { session: ClipperSession; name: string; onChanged: () => void }) {
const { pending, message, run } = useClipperAction(onChanged);
return (
<div className="grid gap-2 rounded-card border border-danger/30 bg-linear-to-r from-danger-soft/70 to-surface px-4 py-3 shadow-card">
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
<span className="flex min-w-0 flex-1 basis-64 items-center gap-3">
<span className="relative grid size-9 shrink-0 place-items-center rounded-control border border-danger/35 bg-danger-soft text-danger">
<PlatformIcon platform={s.platform} size={18} />
</span>
<span className="grid min-w-0 gap-0.5">
<span className="flex flex-wrap items-center gap-2">
<span className="truncate font-semibold text-fg">{name}</span>
<Badge tone="danger" pulse>{s.status === "starting" ? "iniciando" : "ao vivo · gravando"}</Badge>
</span>
<span className="text-xs text-fg-muted tabular-nums">
{formatClock(s.durationS)} gravados · {formatInteger(s.chatMessages)} mensagens no chat · sessão #{s.id}
</span>
</span>
</span>
<span className="flex flex-wrap items-center gap-2">
{s.kind === "live" && <CutNow sessionId={s.id} pending={pending} run={run} />}
<Button variant="ghost" size="sm" disabled={pending !== null}
onClick={async () => {
if (!(await askConfirm({ title: `Parar a gravação de ${name}?`,
message: "O que já foi gravado continua sendo analisado.", confirmLabel: "Parar" }))) return;
void run("stop", () => clipperCall(`sessions/${s.id}/stop`, "POST"), "Gravação parada.");
}}>
{pending === "stop" ? <Spinner className="size-3.5" /> : <StopIcon size={15} />}Parar
</Button>
</span>
</div>
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</div>
);
}
+148
View File
@@ -0,0 +1,148 @@
"use client";
// Modal de confirmação/aviso do painel — substitui window.confirm/window.alert.
// Uso: `if (!(await askConfirm({ title: "Apagar?", tone: "danger" }))) return;` em qualquer handler de cliente.
// Um único <ConfirmHost /> fica montado no layout; os pedidos entram numa fila e aparecem um de cada vez.
import { useEffect, useId, useRef, useState, type FormEvent, type ReactNode } from "react";
import { AlertIcon } from "./icons";
import { Button } from "./ui";
export type ConfirmTone = "default" | "danger";
export type ConfirmOptions = {
title: string;
/** Explicação abaixo do título (o que acontece se confirmar). */
message?: ReactNode;
confirmLabel?: string;
cancelLabel?: string;
/** "danger": botão vermelho e foco inicial em Cancelar (Enter não apaga nada por engano). */
tone?: ConfirmTone;
};
export type AlertOptions = { title: string; message?: ReactNode; okLabel?: string; tone?: ConfirmTone };
type Request =
| { kind: "confirm"; options: ConfirmOptions; resolve: (ok: boolean) => void }
| { kind: "alert"; options: AlertOptions & { cancelLabel?: undefined; confirmLabel?: undefined }; resolve: (ok: boolean) => void };
// Ponte entre as funções soltas e o host montado. Antes do host montar, os pedidos esperam no backlog.
let deliver: ((request: Request) => void) | null = null;
const backlog: Request[] = [];
function enqueue(request: Request) {
if (deliver) deliver(request);
else backlog.push(request);
}
/** Abre o modal de confirmação. Resolve `true` se confirmou; `false` em Cancelar, Esc ou clique fora. */
export function askConfirm(options: ConfirmOptions): Promise<boolean> {
return new Promise((resolve) => enqueue({ kind: "confirm", options, resolve }));
}
/** Aviso com um botão só (substitui window.alert). Resolve quando fecha. */
export function showAlert(options: AlertOptions): Promise<void> {
return new Promise((resolve) => enqueue({ kind: "alert", options, resolve: () => resolve() }));
}
/**
* onSubmit de formulário com server action: segura o envio, pergunta e, se confirmou, reenvia o
* formulário com o mesmo botão (requestSubmit). `when` decide se precisa perguntar.
*/
export function confirmSubmit(options: ConfirmOptions, when: () => boolean = () => true) {
return (e: FormEvent<HTMLFormElement>) => {
const form = e.currentTarget;
if (form.dataset.confirmed === "1") {
delete form.dataset.confirmed;
return;
}
if (!when()) return;
e.preventDefault();
const submitter = (e.nativeEvent as SubmitEvent).submitter;
void askConfirm(options).then((ok) => {
if (!ok || !form.isConnected) return;
form.dataset.confirmed = "1";
form.requestSubmit(submitter instanceof HTMLElement && submitter.isConnected ? submitter : undefined);
});
};
}
/** Host único (no layout). Mostra o primeiro pedido da fila num <dialog> nativo: foco preso, Esc cancela. */
export function ConfirmHost() {
const [queue, setQueue] = useState<Request[]>([]);
const ref = useRef<HTMLDialogElement>(null);
const answeredRef = useRef(false);
const cancelRef = useRef<HTMLButtonElement>(null);
const confirmRef = useRef<HTMLButtonElement>(null);
const titleId = useId();
const messageId = useId();
const current = queue[0];
useEffect(() => {
deliver = (request) => setQueue((q) => [...q, request]);
if (backlog.length) setQueue((q) => [...q, ...backlog.splice(0)]);
return () => { deliver = null; };
}, []);
useEffect(() => {
const dialog = ref.current;
if (!dialog) return;
if (current && !dialog.open) {
answeredRef.current = false;
dialog.showModal();
// Foco inicial: em "danger", Cancelar (Enter não confirma por engano); senão, o botão de confirmar.
(current.options.tone === "danger" && cancelRef.current ? cancelRef.current : confirmRef.current)?.focus();
}
if (!current && dialog.open) dialog.close();
}, [current]);
function answer(ok: boolean) {
if (!current || answeredRef.current) return;
answeredRef.current = true;
current.resolve(ok);
ref.current?.close();
setQueue((q) => q.slice(1));
}
const danger = current?.options.tone === "danger";
const isAlert = current?.kind === "alert";
const confirmLabel = current?.kind === "alert" ? current.options.okLabel ?? "Entendi"
: current?.options.confirmLabel ?? "Confirmar";
return (
<dialog ref={ref} aria-labelledby={titleId} aria-describedby={current?.options.message ? messageId : undefined}
role={isAlert ? "alertdialog" : undefined}
// Esc: o navegador dispara `cancel`; tratamos como "não".
onCancel={(e) => { e.preventDefault(); answer(false); }}
// Clique no fundo escurecido (fora da caixa) = cancelar.
onClick={(e) => { if (e.target === ref.current) answer(false); }}
className="m-auto w-[min(92vw,28rem)] rounded-panel border border-line-strong bg-canvas p-0 text-fg shadow-pop backdrop:bg-black/70 backdrop:backdrop-blur-[2px]">
{current && (
<div className="grid gap-5 p-5 sm:p-6">
<div className="flex gap-3.5">
<span aria-hidden="true"
className={danger
? "grid size-10 shrink-0 place-items-center rounded-full bg-danger-soft text-danger"
: "grid size-10 shrink-0 place-items-center rounded-full bg-accent-soft text-accent"}>
<AlertIcon size={20} />
</span>
<div className="grid min-w-0 content-start gap-1.5 pt-1">
<h2 id={titleId} className="text-base leading-snug font-semibold text-fg">{current.options.title}</h2>
{current.options.message && (
<div id={messageId} className="text-sm leading-relaxed whitespace-pre-line text-fg-muted">{current.options.message}</div>
)}
</div>
</div>
<div className="flex flex-wrap justify-end gap-2">
{!isAlert && (
<Button ref={cancelRef} type="button" variant="secondary" onClick={() => answer(false)}>
{current.options.cancelLabel ?? "Cancelar"}
</Button>
)}
<Button ref={confirmRef} type="button" variant={danger ? "danger" : "primary"} onClick={() => answer(true)}>
{confirmLabel}
</Button>
</div>
</div>
)}
</dialog>
);
}
+425
View File
@@ -0,0 +1,425 @@
"use client";
// Passo a passo para conectar uma rede (YouTube, TikTok, Instagram) a um canal de publicação:
// 1) escolher o modo — "Conta oficial (API)" ou "Sessão logada" (nenhum vem marcado: decisão do dono);
// a sessão logada exige marcar "Entendi o risco" (viola os termos da rede);
// 2) entrar na conta, conforme o `next` que o Publicador devolve (abrir login / colar token / "Já entrei");
// 3) resultado, anunciado para leitores de tela.
// `reconnect`: pula a escolha e reabre o login no mesmo modo (botão "Entrar de novo").
// Quem usa monta o componente só quando ele deve aparecer (o diálogo abre ao montar e devolve o foco ao fechar).
import Link from "next/link";
import { useEffect, useRef, useState, type ReactNode } from "react";
import type { Platform } from "@/lib/types";
import { Dialog, Steps } from "./dialog";
import { AlertIcon, ArrowRightIcon, CheckIcon, LinkIcon, RefreshIcon, XIcon } from "./icons";
import { PLATFORM_META } from "./platforms";
import {
MODE_LABEL, checkNetwork, connectNetwork, getApp, reopenNetwork, submitToken,
type ConnectionMode, type ConnectNext, type PublishingNetwork,
} from "./publishing-client";
import { NetworkStatusBadge, networkStatusText } from "./publishing-ui";
import { Button, Feedback, Field, Input, Spinner, cx } from "./ui";
const STEPS = ["Como conectar", "Entrar na conta", "Pronto"];
/** Enquanto espera o login oficial numa aba nova, confere o estado do perfil a cada 3 s. */
const WAIT_POLL_MS = 3000;
/** Quanto esperar a autorização na outra aba antes de desistir (o link do OAuth também vence). */
const WAIT_LIMIT_MS = 10 * 60 * 1000;
type ModeInfo = { what: string; pros: string[]; cons: string[] };
function modeInfo(platform: Platform, mode: ConnectionMode): ModeInfo {
const label = PLATFORM_META[platform].label;
if (mode === "official") {
const cons: Record<Platform, string[]> = {
youtube: [
"Antes, é preciso criar um app grátis no Google (passo a passo em Configurações).",
"Até 100 envios por dia.",
"O Google mostra o aviso “app não verificado”. É esperado: o app é seu.",
],
tiktok: [
"Antes, é preciso criar um app no site do TikTok (passo a passo em Configurações).",
"Sem a aprovação do TikTok, o vídeo sai só como privado ou vai como rascunho para o app, e você publica de lá.",
"Até 5 rascunhos por dia.",
],
instagram: [
"Só funciona com conta Profissional (Comercial ou Criador de conteúdo).",
"Você copia um código de acesso no site da Meta e cola aqui. Ele vale 60 dias e é renovado sozinho.",
],
};
return {
what: `Você autoriza o CenaForge na página oficial do ${label}. O envio usa a API: a porta oficial que a rede oferece para programas.`,
pros: [
"É o caminho permitido pela rede: risco baixo para a conta.",
"Não quebra quando o site muda de visual.",
...(platform === "youtube" ? ["Dá para agendar no próprio YouTube."] : []),
...(platform === "instagram" ? ["Publica o Reel com capa e aviso de IA."] : []),
],
cons: cons[platform],
};
}
return {
what: `Abre um Chrome (ou Edge) separado, só para este perfil. Você entra na conta do ${label} à mão, como sempre, e o CenaForge publica pelo site usando essa janela.`,
pros: ["Não precisa criar app nem copiar código.", "Publica como público, igual a você fazendo à mão."],
cons: [
"Pode parar de funcionar quando o site muda.",
"De vez em quando a rede pede para entrar de novo.",
"O painel precisa ficar aberto para publicar.",
],
};
}
export function ConnectWizard({ accountId, accountName, platform, network, reconnect = false, onClose, onChanged }: {
accountId: string;
accountName?: string;
platform: Platform;
/** Estado atual da rede (null = nunca vinculada). */
network: PublishingNetwork | null;
reconnect?: boolean;
onClose: () => void;
/** Algo mudou no servidor (conectou, falhou): quem usa recarrega os dados. */
onChanged: () => void;
}) {
const label = PLATFORM_META[platform].label;
const Icon = PLATFORM_META[platform].icon;
const [step, setStep] = useState(reconnect ? 1 : 0);
const [mode, setMode] = useState<ConnectionMode | null>(reconnect ? network?.mode ?? null : null);
const [risk, setRisk] = useState(false);
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [next, setNext] = useState<ConnectNext | null>(null);
const [result, setResult] = useState<PublishingNetwork | null>(null);
const [waiting, setWaiting] = useState(false);
const [waitExpired, setWaitExpired] = useState(false);
const [token, setToken] = useState("");
const [appConfigured, setAppConfigured] = useState<boolean | null>(null);
const headingRef = useRef<HTMLHeadingElement>(null);
const firstStep = useRef(true);
// O app da rede (YouTube/TikTok) precisa estar criado em Configurações para o modo oficial.
useEffect(() => {
if (platform === "instagram") return;
let cancelled = false;
void getApp(platform).then((r) => { if (!cancelled) setAppConfigured(r.ok ? r.data.configured : null); });
return () => { cancelled = true; };
}, [platform]);
// Ao trocar de etapa, o foco vai para o título dela (teclado e leitor de tela sabem onde estão).
useEffect(() => {
if (firstStep.current) { firstStep.current = false; return; }
headingRef.current?.focus();
}, [step]);
// "Entrar de novo": já começa pedindo o login no mesmo modo.
const started = useRef(false);
useEffect(() => {
if (!reconnect || started.current || !network?.mode) return;
started.current = true;
void begin(network.mode);
// Roda uma vez, ao abrir (begin só usa estado local).
}, []);
// Login oficial numa aba nova: relê o perfil no Publicador (no modo oficial, "conferir" só relê, não abre nada)
// até ele aparecer como conectado.
useEffect(() => {
if (!waiting) return;
const startedAt = Date.now();
const timer = setInterval(async () => {
// Passou do limite: para de esperar e pede para começar de novo (não fica consultando para sempre).
if (Date.now() - startedAt > WAIT_LIMIT_MS) {
clearInterval(timer);
setWaiting(false);
setWaitExpired(true);
return;
}
if (document.visibilityState === "hidden") return;
const r = await checkNetwork(accountId, platform);
if (r.ok && (r.data.status === "connected" || r.data.status === "error")) finish(r.data);
}, WAIT_POLL_MS);
return () => clearInterval(timer);
// finish só muda estado local e avisa quem usa: não precisa entrar nas dependências.
}, [waiting, accountId, platform]);
function finish(n: PublishingNetwork) {
setWaiting(false);
setResult(n);
setStep(2);
onChanged();
}
async function begin(chosen: ConnectionMode) {
setBusy("connect");
setError(null);
setWaitExpired(false);
const r = reconnect && chosen === "session"
? await reopenNetwork(accountId, platform)
: await connectNetwork(accountId, platform, chosen);
setBusy(null);
// Erro: fica na etapa atual (a escolha do modo continua marcada) e mostra a mensagem do servidor.
if (!r.ok) { setError(r.error); setNext(null); return; }
onChanged();
if (r.data.next.kind === "none") { finish(r.data.network); return; }
setNext(r.data.next);
setStep(1);
}
async function confirmSession() {
setBusy("check");
setError(null);
const r = await checkNetwork(accountId, platform);
setBusy(null);
if (!r.ok) { setError(r.error); return; }
if (r.data.status === "connected") finish(r.data);
else setError(r.data.last_error ?? `Ainda não deu para ver você logado no ${label}. Entre na conta na janela que abriu e tente de novo.`);
}
async function reopen() {
setBusy("reopen");
setError(null);
const r = await reopenNetwork(accountId, platform);
setBusy(null);
if (!r.ok) { setError(r.error); return; }
setNext(r.data.next.kind === "none" ? next : r.data.next);
}
async function sendToken() {
if (!token.trim()) { setError("Cole o código de acesso antes de continuar."); return; }
setBusy("token");
setError(null);
const r = await submitToken(accountId, platform, token.trim());
setBusy(null);
if (!r.ok) { setError(r.error); return; }
setToken("");
finish(r.data);
}
function continueFromChoice() {
if (!mode) { setError("Escolha um dos dois jeitos de conectar."); return; }
if (mode === "session" && !risk) { setError("Para usar a sessão logada, marque que entendeu o risco."); return; }
void begin(mode);
}
const ok = result?.status === "connected";
const footer: ReactNode = step === 0 ? <>
<Button variant="secondary" onClick={onClose}>Cancelar</Button>
<Button onClick={continueFromChoice} disabled={busy !== null}>
{busy === "connect" ? <><Spinner />Preparando…</> : <>Continuar<ArrowRightIcon size={16} /></>}
</Button>
</> : step === 1 ? <>
{!reconnect && <Button variant="ghost" onClick={() => { setStep(0); setNext(null); setWaiting(false); setError(null); }} disabled={busy !== null}>Voltar</Button>}
<Button variant="secondary" onClick={onClose}>Fechar</Button>
</> : <>
{!ok && <Button variant="secondary" onClick={() => { setResult(null); setError(null); setStep(reconnect ? 1 : 0); if (reconnect && mode) void begin(mode); }}>
<RefreshIcon size={16} />Tentar de novo
</Button>}
<Button onClick={onClose}>{ok ? "Concluir" : "Fechar"}</Button>
</>;
return (
<Dialog open onClose={onClose} size="lg" footer={footer}
eyebrow={<><Icon size={14} />{accountName ? `Canal ${accountName}` : "Canal de publicação"}</>}
title={reconnect ? `Entrar de novo no ${label}` : `Conectar o ${label}`}>
<div className="grid gap-6">
<Steps steps={STEPS} current={step} />
{step === 0 && (
<section aria-labelledby="wizard-step" className="grid gap-4">
<h3 id="wizard-step" ref={headingRef} tabIndex={-1} className="text-base font-semibold text-fg focus-visible:outline-none">
Como você quer conectar o {label}?
</h3>
<p className="-mt-2 text-sm text-fg-muted">São dois jeitos. Escolha um; dá para trocar depois desconectando.</p>
<fieldset className="grid gap-3 md:grid-cols-2">
<legend className="sr-only">Modo de conexão</legend>
{(["official", "session"] as ConnectionMode[]).map((m) => (
<ModeCard key={m} platform={platform} mode={m} checked={mode === m}
appMissing={m === "official" && appConfigured === false}
onSelect={() => { setMode(m); setError(null); }} />
))}
</fieldset>
{mode === "session" && (
<label className="flex cursor-pointer items-start gap-3 rounded-control border border-warning/35 bg-warning-soft px-4 py-3 text-sm has-focus-visible:outline-2 has-focus-visible:outline-accent">
<input type="checkbox" checked={risk} onChange={(e) => { setRisk(e.target.checked); setError(null); }}
className="mt-0.5 size-5 shrink-0 cursor-pointer accent-accent" />
<span className="grid gap-0.5">
<span className="font-semibold text-fg">Entendi o risco</span>
<span className="text-[0.8125rem] leading-relaxed text-fg-muted">
Sei que publicar por automação vai contra os termos do {label} e que a conta pode ser bloqueada.
</span>
</span>
</label>
)}
<div aria-live="assertive" className="empty:hidden">{error && <Feedback ok={false}>{error}</Feedback>}</div>
</section>
)}
{step === 1 && (
<section aria-labelledby="wizard-step" className="grid gap-4">
<h3 id="wizard-step" ref={headingRef} tabIndex={-1} className="text-base font-semibold text-fg focus-visible:outline-none">
{next?.kind === "paste_token" ? "Cole o código de acesso"
: next?.kind === "browser_opened" ? `Entre na sua conta do ${label}`
: next?.kind === "open_url" ? `Autorize o CenaForge no ${label}`
: "Preparando a conexão"}
</h3>
{mode && <p className="-mt-2 text-sm text-fg-subtle">Modo: {MODE_LABEL[mode]}</p>}
{!next && busy === "connect" && (
<p role="status" className="flex items-center gap-2 text-sm text-fg-muted"><Spinner />Falando com o Publicador…</p>
)}
{next?.kind === "open_url" && (
<div className="grid gap-4">
<ol className="grid list-decimal gap-2 pl-5 text-sm leading-relaxed text-fg-muted marker:font-semibold marker:text-fg">
<li>Clique no botão abaixo. A página oficial do {label} abre numa aba nova.</li>
<li>Entre com a conta que vai publicar e permita o acesso.</li>
<li>Quando aparecer “Conectado, pode fechar esta aba”, feche e volte para cá.</li>
</ol>
<div className="flex flex-wrap items-center gap-3">
<a href={next.url} target="_blank" rel="noopener noreferrer" onClick={() => { setWaitExpired(false); setWaiting(true); }}
className="inline-flex h-10 items-center gap-2 rounded-control bg-accent px-4 text-sm font-semibold text-accent-fg hover:bg-accent-hover focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent">
<LinkIcon size={16} />Abrir o login do {label}<span className="sr-only"> (abre numa aba nova)</span>
</a>
{waiting && (
<Button variant="secondary" onClick={() => void confirmSession()} disabled={busy !== null}>
{busy === "check" ? <Spinner /> : <CheckIcon size={16} />}Já autorizei
</Button>
)}
</div>
{waiting && (
<p role="status" className="flex items-center gap-2 text-sm text-info"><Spinner className="size-3.5" />Esperando você autorizar na outra aba…</p>
)}
{waitExpired && (
<div role="alert" className="flex flex-wrap items-center gap-3 text-sm text-fg">
<span>O tempo para entrar acabou — clique em Conectar de novo.</span>
{mode && (
<Button variant="secondary" onClick={() => void begin(mode)} disabled={busy !== null}>
{busy === "connect" ? <Spinner /> : <LinkIcon size={16} />}Conectar de novo
</Button>
)}
</div>
)}
</div>
)}
{next?.kind === "paste_token" && (
<form className="grid gap-4" onSubmit={(e) => { e.preventDefault(); void sendToken(); }}>
{next.help && <p className="text-sm leading-relaxed whitespace-pre-line text-fg-muted">{next.help}</p>}
<ol className="grid list-decimal gap-2 pl-5 text-sm leading-relaxed text-fg-muted marker:font-semibold marker:text-fg">
<li>No site de desenvolvedores da Meta, abra o seu app › Instagram › “Gerar token”.</li>
<li>Entre com a conta Profissional do Instagram e copie o código que aparece.</li>
<li>Cole aqui embaixo.</li>
</ol>
<Field label="Código de acesso (token)"
hint="Fica guardado só neste computador, protegido pela sua conta do Windows. Não aparece de novo aqui.">
<Input type="password" value={token} onChange={(e) => setToken(e.target.value)} autoComplete="off" spellCheck={false}
placeholder="Cole o código aqui" className="font-mono" />
</Field>
<div>
<Button type="submit" disabled={busy !== null}>{busy === "token" ? <><Spinner />Conferindo…</> : <><CheckIcon size={16} />Conectar com este código</>}</Button>
</div>
</form>
)}
{next?.kind === "browser_opened" && (
<div className="grid gap-4">
<ol className="grid list-decimal gap-2 pl-5 text-sm leading-relaxed text-fg-muted marker:font-semibold marker:text-fg">
<li>Uma janela do navegador abriu (pode estar atrás desta).</li>
<li>Entre na sua conta do {label} nela, do jeito de sempre. Se pedir código ou confirmação no celular, faça normalmente.</li>
<li>Depois de ver a sua conta aberta, clique em <strong className="text-fg">Já entrei</strong>.</li>
</ol>
{next.help && <p className="text-[0.8125rem] leading-relaxed whitespace-pre-line text-fg-subtle">{next.help}</p>}
<div className="flex flex-wrap items-center gap-2">
<Button onClick={() => void confirmSession()} disabled={busy !== null}>
{busy === "check" ? <><Spinner />Conferindo…</> : <><CheckIcon size={16} />Já entrei</>}
</Button>
<Button variant="ghost" onClick={() => void reopen()} disabled={busy !== null}>
{busy === "reopen" ? <Spinner /> : <RefreshIcon size={16} />}Abrir a janela de novo
</Button>
</div>
<p className="text-xs leading-relaxed text-fg-subtle">
O CenaForge nunca digita sua senha nem resolve verificações por você. Não feche essa janela: é nela que os vídeos são enviados.
</p>
</div>
)}
<div aria-live="assertive" className="empty:hidden">
{error && <Feedback ok={false}>{error}{/app|client/i.test(error) && <> Veja <Link className="underline" href="/settings?tab=apps">Configurações › Apps das redes</Link>.</>}</Feedback>}
</div>
</section>
)}
{step === 2 && result && (
<section aria-labelledby="wizard-step" className="grid gap-4">
<div role="status" className={cx("flex items-start gap-4 rounded-card border p-5",
ok ? "border-success/30 bg-success-soft" : "border-danger/30 bg-danger-soft")}>
<span aria-hidden="true" className={cx("grid size-11 shrink-0 place-items-center rounded-full", ok ? "bg-success text-sunken" : "bg-danger text-sunken")}>
{ok ? <CheckIcon size={22} /> : <XIcon size={22} />}
</span>
<div className="grid min-w-0 gap-1.5">
<h3 id="wizard-step" ref={headingRef} tabIndex={-1} className="text-base font-semibold text-fg focus-visible:outline-none">
{ok ? `${label} conectado` : "Não deu para conectar"}
</h3>
<p className="text-sm text-fg-muted">{networkStatusText(result)}</p>
<div><NetworkStatusBadge network={result} short /></div>
</div>
</div>
{ok && (
<p className="text-sm leading-relaxed text-fg-muted">
Pronto. Os vídeos aprovados deste canal passam a sair no {label}. Ajuste o limite por dia e a privacidade em “Ajustes desta rede”.
</p>
)}
</section>
)}
</div>
</Dialog>
);
}
function ModeCard({ platform, mode, checked, appMissing, onSelect }: {
platform: Platform; mode: ConnectionMode; checked: boolean; appMissing: boolean; onSelect: () => void;
}) {
const info = modeInfo(platform, mode);
const label = PLATFORM_META[platform].label;
return (
<label className={cx("grid cursor-pointer content-start gap-3 rounded-card border p-4 transition-colors",
"has-focus-visible:outline-2 has-focus-visible:outline-offset-2 has-focus-visible:outline-accent",
checked ? "border-accent bg-accent-soft/50" : "border-line-strong bg-surface hover:border-fg-subtle/50")}>
<span className="flex items-start gap-3">
<input type="radio" name="connect-mode" value={mode} checked={checked} onChange={onSelect}
className="mt-1 size-5 shrink-0 cursor-pointer accent-accent" />
<span className="grid gap-1">
<span className="text-[0.9375rem] font-semibold text-fg">{MODE_LABEL[mode]}</span>
<span className="text-[0.8125rem] leading-relaxed text-fg-muted">{info.what}</span>
</span>
</span>
<span className="grid gap-1.5 pl-8">
<span className="text-eyebrow font-semibold text-success uppercase">A favor</span>
<ul className="grid gap-1">
{info.pros.map((p) => (
<li key={p} className="flex gap-2 text-[0.8125rem] leading-snug text-fg-muted"><CheckIcon size={14} className="mt-0.5 text-success" />{p}</li>
))}
</ul>
</span>
<span className="grid gap-1.5 pl-8">
<span className="text-eyebrow font-semibold text-warning uppercase">Contra</span>
<ul className="grid gap-1">
{info.cons.map((c) => (
<li key={c} className="flex gap-2 text-[0.8125rem] leading-snug text-fg-muted">
<span aria-hidden="true" className="mt-[0.55rem] h-0.5 w-2.5 shrink-0 rounded-full bg-warning" />{c}
</li>
))}
</ul>
</span>
{mode === "session" && (
<span className="ml-8 flex gap-2 rounded-control border border-danger/30 bg-danger-soft px-3 py-2 text-[0.8125rem] leading-relaxed text-danger">
<AlertIcon size={15} className="mt-0.5" />
<span>Vai contra os termos de uso do {label}. A rede pode bloquear ou suspender a conta.</span>
</span>
)}
{appMissing && (
<span className="ml-8 flex gap-2 rounded-control border border-info/30 bg-info-soft px-3 py-2 text-[0.8125rem] leading-relaxed text-info">
<AlertIcon size={15} className="mt-0.5" />
<span>O app do {label} ainda não foi configurado. Faça isso antes em <Link href="/settings?tab=apps" className="font-semibold underline">Configurações › Apps das redes</Link>.</span>
</span>
)}
</label>
);
}
+25
View File
@@ -0,0 +1,25 @@
"use client";
// Copia um texto para a área de transferência (ex.: a narração inteira, para colar na página Vozes).
import { useState } from "react";
import { CheckIcon } from "./icons";
import { Button, type ButtonVariant } from "./ui";
export function CopyButton({ text, label, icon, variant = "secondary", size = "md" }: {
text: string; label: string; icon?: React.ReactNode; variant?: ButtonVariant; size?: "sm" | "md";
}) {
const [state, setState] = useState<"idle" | "done" | "error">("idle");
async function copy() {
try {
await navigator.clipboard.writeText(text);
setState("done");
} catch {
setState("error");
}
setTimeout(() => setState("idle"), 2200);
}
return (
<Button type="button" variant={variant} size={size} onClick={copy} aria-live="polite">
{state === "done" ? <><CheckIcon size={16} />Copiado</> : state === "error" ? "Não deu para copiar" : <>{icon}{label}</>}
</Button>
);
}
+161
View File
@@ -0,0 +1,161 @@
"use client";
// Partes interativas do dashboard: filtro por conta (vai para a URL, ?account=), leitura dos números das redes
// (POST /api/dashboard/metrics) e os botões de dados simulados (POST/DELETE /api/dashboard/simulate).
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useId, useState, useTransition } from "react";
import { apiCall } from "./api-client";
import type { Platform } from "@/lib/types";
import { RefreshIcon, SparkIcon, TrashIcon } from "./icons";
import { PLATFORM_META } from "./platforms";
import { Button, Feedback, Select, Spinner, cx } from "./ui";
import { askConfirm } from "./confirm-dialog";
export function DashboardFilter({ accounts, value }: { accounts: { id: string; name: string }[]; value: string }) {
const router = useRouter();
const id = useId();
const [pending, startTransition] = useTransition();
return (
<div className="grid gap-2">
<label htmlFor={id} className="text-[0.8125rem] font-medium text-fg-muted">Canal de publicação</label>
<div className="flex items-center gap-2">
<Select id={id} value={value} className="min-w-56"
onChange={(e) => {
const next = e.target.value;
startTransition(() => router.push(next ? `/dashboard?account=${encodeURIComponent(next)}` : "/dashboard"));
}}>
<option value="">Todos os canais</option>
{accounts.map((a) => <option key={a.id} value={a.id}>{a.name}</option>)}
</Select>
{pending && <Spinner className="text-fg-subtle" />}
</div>
</div>
);
}
export function SimulatedControls({ simulated, className }: { simulated: boolean; className?: string }) {
const router = useRouter();
const [busy, setBusy] = useState<"generate" | "clear" | null>(null);
const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null);
const [, startTransition] = useTransition();
async function generate() {
setBusy("generate");
setMessage(null);
const r = await apiCall<{ publications: number; snapshots: number }>("/api/dashboard/simulate", "POST");
setBusy(null);
if (!r.ok) return setMessage({ ok: false, text: r.error });
setMessage(r.data.publications === 0
? { ok: false, text: "Nada novo para simular. Ligue redes e histórias (com episódios) aos canais, em Canais de publicação." }
: { ok: true, text: `${r.data.publications} publicações simuladas, com ${r.data.snapshots} medições.` });
startTransition(() => router.refresh());
}
async function clear() {
if (!(await askConfirm({ title: "Apagar todos os dados simulados?",
message: "Publicações e métricas reais (quando existirem) ficam.", confirmLabel: "Apagar simulados", tone: "danger" }))) return;
setBusy("clear");
setMessage(null);
const r = await apiCall<{ removed: number }>("/api/dashboard/simulate", "DELETE");
setBusy(null);
if (!r.ok) return setMessage({ ok: false, text: r.error });
setMessage({ ok: true, text: `${r.data.removed} publicações simuladas apagadas.` });
startTransition(() => router.refresh());
}
return (
<div className={cx("grid gap-3", className)}>
<div className="flex flex-wrap items-center gap-2.5">
<Button variant={simulated ? "secondary" : "primary"} size="sm" onClick={generate} disabled={busy !== null}>
{busy === "generate" ? <Spinner /> : <SparkIcon size={15} />}Gerar dados simulados
</Button>
{simulated && (
<Button variant="danger" size="sm" onClick={clear} disabled={busy !== null}>
{busy === "clear" ? <Spinner /> : <TrashIcon size={15} />}Apagar simulados
</Button>
)}
</div>
{message && <Feedback ok={message.ok}>{message.text}</Feedback>}
</div>
);
}
type SyncRow = { accountId: string; accountName: string; platform: Platform; lastRunAt: string | null; lastOkAt: string | null; lastError: string | null; read: number; missing: number };
type CollectResult = { groups: { accountId: string; platform: Platform; read: number; missing: number; error: string | null }[]; snapshots: number };
/** "Há 5 min", "há 2 h", "há 3 dias". */
function ago(iso: string): string {
const min = Math.max(0, Math.round((Date.now() - new Date(iso).getTime()) / 60_000));
if (min < 1) return "agora há pouco";
if (min < 60) return `há ${min} min`;
const h = Math.round(min / 60);
return h < 48 ? `há ${h} h` : `há ${Math.round(h / 24)} dias`;
}
/**
* Números das redes: quando cada rede foi lida (ou o erro) e o botão para ler agora. TikTok e Instagram abrem a
* janela logada por alguns segundos; o YouTube lê a página pública.
*/
export function MetricsSyncControls({ syncs, accountId, everyHours, showAccount }: {
syncs: SyncRow[]; accountId?: string; everyHours: number; showAccount: boolean;
}) {
const router = useRouter();
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null);
const [, startTransition] = useTransition();
async function collect() {
setBusy(true);
setMessage(null);
const r = await apiCall<CollectResult>("/api/dashboard/metrics", "POST", accountId ? { accountId } : {});
setBusy(false);
if (!r.ok) { setMessage({ ok: false, text: r.error }); return; }
if (r.data.groups.length === 0) {
setMessage({ ok: false, text: "Nada para ler: nenhum vídeo publicado com link nas redes conectadas." });
} else {
const parts = r.data.groups.map((g) => {
const label = PLATFORM_META[g.platform].label;
if (g.error) return `${label}: não deu (${g.error})`;
return `${label}: ${g.read} vídeo${g.read === 1 ? "" : "s"}${g.missing ? ` (${g.missing} não ${g.missing === 1 ? "achado" : "achados"})` : ""}`;
});
setMessage({ ok: r.data.groups.every((g) => !g.error), text: `Números lidos. ${parts.join(" · ")}.` });
}
startTransition(() => router.refresh());
}
return (
<div className="grid gap-3 rounded-card border border-line bg-surface px-5 py-4 shadow-card">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="grid gap-1">
<h2 className="text-sm font-semibold text-fg">Números das redes</h2>
<p className="text-xs leading-relaxed text-fg-subtle">
{everyHours > 0 ? `O painel lê sozinho a cada ${everyHours} h (com o painel aberto).` : "Leitura automática desligada: só pelo botão."}{" "}
Muda em <Link href="/settings" className="underline underline-offset-2 hover:text-fg">Configurações</Link>.
TikTok e Instagram abrem a janela do navegador por alguns segundos.
</p>
</div>
<Button size="sm" onClick={() => void collect()} disabled={busy}>
{busy ? <Spinner /> : <RefreshIcon size={15} />}{busy ? "Lendo as redes…" : "Atualizar números agora"}
</Button>
</div>
{syncs.length > 0 && (
<ul className="flex flex-wrap gap-x-5 gap-y-1.5 text-xs">
{syncs.map((s) => {
const Icon = PLATFORM_META[s.platform].icon;
return (
<li key={`${s.accountId}-${s.platform}`} className="inline-flex max-w-full items-center gap-1.5">
<Icon size={13} className="shrink-0 text-fg-subtle" />
<span className="font-medium text-fg">{PLATFORM_META[s.platform].label}{showAccount && <span className="font-normal text-fg-subtle"> · {s.accountName}</span>}</span>
{s.lastError
? <span className="truncate text-danger" title={s.lastError}>falhou {s.lastRunAt ? ago(s.lastRunAt) : ""}: {s.lastError}</span>
: <span className="text-fg-muted">{s.lastOkAt ? `lido ${ago(s.lastOkAt)}` : "ainda não lido"}</span>}
</li>
);
})}
</ul>
)}
{busy && <p role="status" className="text-xs text-fg-subtle">Lendo… pode levar até 1 minuto por rede (espera um envio em andamento terminar).</p>}
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</div>
);
}
@@ -0,0 +1,41 @@
"use client";
// Excluir história: pede confirmação e chama deleteStoryAction. Os arquivos vão para data/trash/
// (recuperáveis); em sucesso a ação redireciona para a página inicial.
import { useActionState, useEffect } from "react";
import { deleteStoryAction } from "@/app/actions";
import { TrashIcon } from "./icons";
import { Button, Feedback, Spinner, cx } from "./ui";
import { confirmSubmit, showAlert } from "./confirm-dialog";
export function DeleteStoryButton({ storyId, title, compact = false, className }: {
storyId: string; title: string;
/** Só o ícone (cartão da biblioteca); o erro aparece num alerta. */
compact?: boolean;
className?: string;
}) {
const [state, action, pending] = useActionState(deleteStoryAction, null);
useEffect(() => {
if (compact && state?.error) void showAlert({ title: "Não deu para excluir a história", message: state.error, tone: "danger" });
}, [compact, state]);
return (
<form action={action} className={cx("grid gap-2", className)}
onSubmit={confirmSubmit({ title: `Excluir “${title}”?`,
message: "Episódios, votos e vínculos com contas saem do painel. "
+ "Os arquivos (roteiros e cenas) vão para data/trash/ e podem ser recuperados de lá.",
confirmLabel: "Excluir história", tone: "danger" })}>
<input type="hidden" name="storyId" value={storyId} />
{compact ? (
<button type="submit" disabled={pending} aria-label={`Excluir a história ${title}`} title="Excluir história"
className="grid size-8 place-items-center rounded-lg border border-line bg-surface/90 text-fg-subtle backdrop-blur transition-colors hover:border-danger/50 hover:text-danger focus-visible:text-danger disabled:opacity-60">
{pending ? <Spinner /> : <TrashIcon size={15} />}
</button>
) : (
<Button type="submit" variant="danger" disabled={pending}>
{pending ? <><Spinner />Excluindo…</> : <><TrashIcon size={16} />Excluir</>}
</Button>
)}
{!compact && state?.error && <Feedback ok={false}>{state.error}</Feedback>}
</form>
);
}
+95
View File
@@ -0,0 +1,95 @@
"use client";
// Diálogo do design system (modal nativo <dialog> com showModal): o resto da página fica inerte, o foco
// fica preso dentro, Esc fecha e, ao fechar, o foco volta para quem abriu. O conteúdo só monta aberto:
// cada abertura começa do zero (formulário limpo, passo 1).
//
// Uso:
// <Dialog open={open} onClose={() => setOpen(false)} title="Conectar o YouTube" footer={<Button…/>}>…</Dialog>
//
// `Steps`: indicador "Etapa 2 de 3" para passo a passo dentro do diálogo (ou fora dele).
import { useEffect, useId, useRef, type ReactNode } from "react";
import { CheckIcon, XIcon } from "./icons";
import { cx } from "./ui";
const SIZE = { sm: "w-[min(94vw,30rem)]", md: "w-[min(94vw,42rem)]", lg: "w-[min(96vw,60rem)]" } as const;
export function Dialog({ open, onClose, title, description, eyebrow, children, footer, size = "md", dismissOnBackdrop = false }: {
open: boolean;
onClose: () => void;
title: ReactNode;
description?: ReactNode;
eyebrow?: ReactNode;
children: ReactNode;
/** Botões fixos no rodapé (ficam visíveis mesmo com o corpo rolando). */
footer?: ReactNode;
size?: keyof typeof SIZE;
/** Clique no fundo escurecido fecha. Desligado por padrão: num passo a passo, um clique perdido perderia o progresso. */
dismissOnBackdrop?: boolean;
}) {
const ref = useRef<HTMLDialogElement>(null);
const titleId = useId();
const descriptionId = useId();
// Abre ao montar/abrir; ao fechar (ou ao sair da página, se quem usa desmontar o diálogo) devolve o
// foco para o botão que abriu, se ele ainda existe.
useEffect(() => {
const dialog = ref.current;
if (!open || !dialog) return;
const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null;
if (!dialog.open) dialog.showModal();
return () => {
if (dialog.open) dialog.close();
if (opener?.isConnected) opener.focus();
};
}, [open]);
return (
<dialog ref={ref} aria-labelledby={titleId} aria-describedby={description ? descriptionId : undefined}
onCancel={(e) => { e.preventDefault(); onClose(); }}
onClick={(e) => { if (dismissOnBackdrop && e.target === ref.current) onClose(); }}
className={cx("m-auto max-h-[92vh] overflow-hidden rounded-panel border border-line-strong bg-canvas p-0 text-fg shadow-pop backdrop:bg-black/75 backdrop:backdrop-blur-[2px]", SIZE[size])}>
{open && (
<div className="flex max-h-[92vh] flex-col">
<header className="flex items-start justify-between gap-4 border-b border-line bg-surface px-5 py-4 sm:px-6">
<div className="grid min-w-0 gap-1">
{eyebrow && <p className="flex items-center gap-2 text-eyebrow font-semibold text-accent uppercase">{eyebrow}</p>}
<h2 id={titleId} className="text-title text-fg">{title}</h2>
{description && <p id={descriptionId} className="text-sm leading-relaxed text-fg-muted">{description}</p>}
</div>
<button type="button" onClick={onClose} aria-label="Fechar"
className="grid size-9 shrink-0 place-items-center rounded-control text-fg-subtle hover:bg-raised hover:text-fg focus-visible:outline-2 focus-visible:outline-accent">
<XIcon size={18} />
</button>
</header>
<div className="min-h-0 flex-1 overflow-y-auto px-5 py-5 sm:px-6">{children}</div>
{footer && <footer className="flex flex-wrap items-center justify-end gap-2 border-t border-line bg-surface px-5 py-3.5 sm:px-6">{footer}</footer>}
</div>
)}
</dialog>
);
}
/** Etapas de um passo a passo. A atual leva aria-current="step"; as anteriores, um visto. */
export function Steps({ steps, current, className }: { steps: string[]; current: number; className?: string }) {
return (
<ol aria-label="Etapas" className={cx("flex flex-wrap items-center gap-x-2 gap-y-2", className)}>
{steps.map((label, i) => {
const done = i < current;
const active = i === current;
return (
<li key={label} aria-current={active ? "step" : undefined} className="flex items-center gap-2">
{i > 0 && <span aria-hidden="true" className={cx("h-px w-5 sm:w-8", done || active ? "bg-accent/60" : "bg-line-strong")} />}
<span aria-hidden="true"
className={cx("grid size-6 shrink-0 place-items-center rounded-full border text-xs font-semibold tabular-nums",
done ? "border-accent bg-accent text-accent-fg" : active ? "border-accent bg-accent-soft text-accent" : "border-line-strong bg-raised text-fg-subtle")}>
{done ? <CheckIcon size={13} /> : i + 1}
</span>
<span className={cx("text-[0.8125rem]", active ? "font-semibold text-fg" : done ? "text-fg-muted" : "text-fg-subtle")}>
<span className="sr-only">Etapa {i + 1} de {steps.length}{done ? " (feita)" : active ? " (atual)" : ""}: </span>{label}
</span>
</li>
);
})}
</ol>
);
}
+214
View File
@@ -0,0 +1,214 @@
"use client";
// "Aprovar para publicar" na página do episódio: abre um diálogo com a prévia do vídeo final, título e
// legenda editáveis e os canais de publicação (com as redes) que vão receber. POST /api/episodes/[id]/approve
// cria os jobs já aprovados; DELETE desfaz (cancela o que ainda não saiu). Depois, router.refresh().
import { useRouter } from "next/navigation";
import { useState, useTransition } from "react";
import type { EpisodeApproval } from "@/lib/publishing";
import { askConfirm } from "./confirm-dialog";
import { Dialog } from "./dialog";
import { AlertIcon, CheckIcon, PublishIcon, UndoIcon, UsersIcon } from "./icons";
import { PLATFORM_META } from "./platforms";
import { approveEpisode, unapproveEpisode } from "./publishing-client";
import { PublishChips, TextLink } from "./publishing-ui";
import { Badge, Button, Feedback, Field, Input, Select, Spinner, Textarea, cx, fileUrl, formatDate } from "./ui";
const TITLE_MAX = 100;
const CAPTION_MAX = 2200;
const NETWORK_REASON: Record<string, string> = {
disconnected: "não conectado",
connecting: "conectando",
needs_login: "precisa entrar de novo (sai depois que você entrar)",
expired: "conexão vencida (sai depois que você conectar de novo)",
error: "com erro na conexão",
};
export function EpisodeApprove({ episodeId, approval, label }: {
episodeId: number;
approval: EpisodeApproval;
/** Como a interface chama o vídeo: "ep01" ou "vídeo". */
label: string;
}) {
const router = useRouter();
const [, startTransition] = useTransition();
const [open, setOpen] = useState(false);
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null);
const jobs = approval.jobs.filter((j) => j.status !== "canceled");
const hasFinal = approval.renders.length > 0;
const approved = approval.approvedAt !== null;
async function undo() {
const ok = await askConfirm({
title: "Desfazer a aprovação?",
message: "O que ainda não saiu é cancelado. O que já foi publicado continua nas redes.",
confirmLabel: "Desfazer aprovação", cancelLabel: "Voltar", tone: "danger",
});
if (!ok) return;
setBusy(true);
const r = await unapproveEpisode(episodeId);
setBusy(false);
setMessage(r.ok ? { ok: true, text: "Aprovação desfeita." } : { ok: false, text: r.error });
startTransition(() => router.refresh());
}
return (
<div className="grid gap-3 rounded-card border border-line bg-sunken/30 p-4">
<div className="flex flex-wrap items-center justify-between gap-2">
<h3 className="text-eyebrow font-semibold text-fg-subtle uppercase">Publicar nas redes</h3>
{approved && <Badge tone="success" dot={false}><CheckIcon size={13} />Aprovado</Badge>}
</div>
{approved ? (
<>
<p className="text-xs text-fg-muted">Aprovado em {formatDate(approval.approvedAt)}.</p>
<PublishChips jobs={jobs} showAccount={new Set(jobs.map((j) => j.accountId)).size > 1}
emptyText="Nenhuma rede vai receber: nenhum canal ligado a esta história tem rede conectada." />
<div className="flex flex-wrap gap-2">
<Button variant="secondary" size="sm" onClick={() => { setMessage(null); setOpen(true); }} disabled={busy}>
<PublishIcon size={15} />Mudar e aprovar de novo
</Button>
<Button variant="ghost" size="sm" onClick={() => void undo()} disabled={busy}>
{busy ? <Spinner className="size-3.5" /> : <UndoIcon size={15} />}Desfazer aprovação
</Button>
</div>
<TextLink href="/publishing">Acompanhar em Publicações</TextLink>
</>
) : (
<>
<p className="text-xs leading-relaxed text-fg-muted">
{hasFinal
? `Confira o vídeo final, o título e a legenda, e libere o ${label} para os canais de publicação desta história.`
: "Precisa de um vídeo final antes: use “Renderizar final (1080×1920)” ou monte o vídeo."}
</p>
<div>
<Button size="sm" onClick={() => { setMessage(null); setOpen(true); }} disabled={!hasFinal}
aria-describedby={hasFinal ? undefined : `sem-final-${episodeId}`}>
<PublishIcon size={15} />Aprovar para publicar
</Button>
{!hasFinal && <span id={`sem-final-${episodeId}`} className="sr-only">Indisponível: falta o vídeo final.</span>}
</div>
</>
)}
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
{open && (
<ApproveDialog episodeId={episodeId} approval={approval} label={label} onClose={() => setOpen(false)}
onDone={(text) => { setOpen(false); setMessage({ ok: true, text }); startTransition(() => router.refresh()); }} />
)}
</div>
);
}
function ApproveDialog({ episodeId, approval, label, onClose, onDone }: {
episodeId: number; approval: EpisodeApproval; label: string; onClose: () => void; onDone: (text: string) => void;
}) {
const [renderId, setRenderId] = useState(() => approval.renderId && approval.renders.some((r) => r.id === approval.renderId)
? approval.renderId : approval.renders[0]?.id ?? 0);
const [title, setTitle] = useState(approval.title);
const [caption, setCaption] = useState(approval.caption);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const render = approval.renders.find((r) => r.id === renderId);
const receiving = approval.targets.reduce((n, t) => n + t.networks.filter((x) => x.willReceive).length, 0);
async function submit() {
if (!title.trim()) { setError("Escreva um título."); return; }
if (!render) { setError("Escolha o vídeo final."); return; }
setBusy(true);
setError(null);
const r = await approveEpisode(episodeId, { renderId: render.id, title: title.trim(), caption: caption.trim() });
setBusy(false);
if (!r.ok) { setError(r.error); return; }
onDone(receiving === 1 ? "Aprovado: 1 rede vai receber." : `Aprovado: ${receiving} redes vão receber.`);
}
return (
<Dialog open onClose={onClose} size="lg" eyebrow={<><PublishIcon size={14} />Publicar nas redes</>}
title={`Aprovar o ${label} para publicar`}
description="Depois de aprovar, cada canal publica no horário que ele usa (na hora ou no próximo horário bom)."
footer={<>
<Button variant="secondary" onClick={onClose}>Voltar</Button>
<Button onClick={() => void submit()} disabled={busy || receiving === 0}>
{busy ? <><Spinner />Aprovando…</> : <><CheckIcon size={16} />Aprovar para publicar</>}
</Button>
</>}>
<div className="grid gap-6 md:grid-cols-[minmax(0,14rem)_minmax(0,1fr)]">
<div className="grid content-start gap-3">
<div className="aspect-9/16 w-full overflow-hidden rounded-control border border-line-strong bg-sunken">
{render
? <video key={render.mp4} controls preload="metadata" src={fileUrl(render.mp4)} aria-label="Prévia do vídeo final" className="size-full object-contain" />
: <p className="grid size-full place-items-center p-4 text-center text-xs text-fg-subtle">Sem vídeo final.</p>}
</div>
{approval.renders.length > 1 && (
<Field label="Vídeo final">
<Select value={renderId} onChange={(e) => setRenderId(Number(e.target.value))}>
{approval.renders.map((r) => (
<option key={r.id} value={r.id}>{r.profile === "documentary" ? "Montagem" : "Final"} · {formatDate(r.finishedAt)}</option>
))}
</Select>
</Field>
)}
</div>
<div className="grid content-start gap-5">
<Field label="Título" hint={<Counter value={title.length} max={TITLE_MAX} note="O YouTube usa o título; TikTok e Instagram usam a legenda." />}>
<Input value={title} onChange={(e) => setTitle(e.target.value)} maxLength={TITLE_MAX} required />
</Field>
<Field label="Legenda" hint={<Counter value={caption.length} max={CAPTION_MAX} note="Descrição do post, com as hashtags." />}>
<Textarea value={caption} onChange={(e) => setCaption(e.target.value)} maxLength={CAPTION_MAX} rows={5} />
</Field>
<section aria-labelledby="quem-recebe" className="grid gap-2">
<h3 id="quem-recebe" className="text-[0.8125rem] font-medium text-fg-muted">Quem vai receber</h3>
{approval.targets.length === 0 ? (
<p className="flex gap-2 rounded-control border border-warning/30 bg-warning-soft px-3 py-2 text-[0.8125rem] leading-relaxed text-warning">
<AlertIcon size={15} className="mt-0.5" />
<span>Nenhum canal de publicação tem esta história. Ligue a história a um canal em <TextLink href="/accounts">Canais de publicação</TextLink>.</span>
</p>
) : (
<ul className="grid divide-y divide-line rounded-control border border-line">
{approval.targets.map((t) => (
<li key={t.accountId} className="grid gap-2 px-3.5 py-2.5">
<span className="flex items-center gap-2 text-sm font-medium text-fg"><UsersIcon size={15} className="text-fg-subtle" />{t.name}</span>
<ul className="grid gap-1 pl-6">
{(["youtube", "tiktok", "instagram"] as const).map((p) => {
const n = t.networks.find((x) => x.platform === p);
const Icon = PLATFORM_META[p].icon;
const reason = !n ? "não conectado" : n.willReceive ? null : !n.enabled ? "pausado neste canal" : NETWORK_REASON[n.status] ?? "não recebe";
return (
<li key={p} className={cx("flex flex-wrap items-center gap-x-2 text-[0.8125rem]", reason ? "text-fg-subtle" : "text-fg")}>
<Icon size={14} />
<span>{PLATFORM_META[p].label}:</span>
{reason ? <span>não recebe ({reason})</span>
: <span className="inline-flex items-center gap-1 font-medium text-success"><CheckIcon size={13} />vai receber</span>}
</li>
);
})}
</ul>
</li>
))}
</ul>
)}
{approval.targets.length > 0 && receiving === 0 && (
<p className="text-xs leading-relaxed text-warning">Nenhuma rede conectada para receber. Conecte em <TextLink href="/accounts">Canais de publicação</TextLink>.</p>
)}
</section>
<div aria-live="assertive" className="empty:hidden">{error && <Feedback ok={false}>{error}</Feedback>}</div>
</div>
</div>
</Dialog>
);
}
function Counter({ value, max, note }: { value: number; max: number; note: string }) {
return (
<span className="flex flex-wrap justify-between gap-x-3">
<span>{note}</span>
<span className={cx("tabular-nums", value > max * 0.9 && "text-warning")}>{value}/{max}</span>
</span>
);
}
+221
View File
@@ -0,0 +1,221 @@
"use client";
// Formulários que usam server actions e mostram erro/sucesso.
import { useActionState, useId, useState, type ReactNode } from "react";
import Link from "next/link";
import {
addCommentsAction, closeDecisionAction, createEpisodeAction, createStoryAction, prepareBranchesAction, type FormState,
} from "@/app/actions";
import type { BranchesStatus, Choice, StoryKind } from "@/lib/types";
import { RefreshIcon, SparkIcon, TerminalIcon } from "./icons";
import { DEFAULT_STORY_FORMAT, STORY_FORMATS } from "./story-formats";
import { Badge, Button, ChoiceGroup, Feedback, Field, Input, Select, Spinner, Textarea, cx, type Tone } from "./ui";
import { confirmSubmit } from "./confirm-dialog";
export type DescribedOption<T extends string> = { value: T; label: string; description?: ReactNode; disabled?: boolean };
/**
* Select com rótulo e a descrição da opção escolhida logo abaixo (ligada por aria-describedby).
* Serve para listas que crescem (formatos de história, modelos, vozes), onde botões segmentados não cabem.
* Controlado (`value` + `onChange`) ou não (`defaultValue`); o valor vai no formulário pelo `name`.
*/
export function DescribedSelect<T extends string>({
label, name, options, value, defaultValue, onChange, placeholder, required, disabled, className,
}: {
label: ReactNode; name: string; options: DescribedOption<T>[];
value?: T | ""; defaultValue?: T; onChange?: (value: T) => void;
/** Primeira opção vazia e desabilitada ("Escolha…"), para obrigar uma escolha consciente. */
placeholder?: string; required?: boolean; disabled?: boolean; className?: string;
}) {
const id = useId();
const [internal, setInternal] = useState<T | "">(defaultValue ?? "");
const current = value !== undefined ? value : internal;
const description = options.find((o) => o.value === current)?.description;
return (
<div className={cx("grid content-start gap-2", className)}>
<label htmlFor={`${id}-select`} className="text-[0.8125rem] font-medium text-fg-muted">{label}</label>
<Select id={`${id}-select`} name={name} value={current} required={required} disabled={disabled}
aria-describedby={description ? `${id}-desc` : undefined}
onChange={(e) => {
const next = e.target.value as T;
if (value === undefined) setInternal(next);
onChange?.(next);
}}>
{placeholder && <option value="" disabled>{placeholder}</option>}
{options.map((o) => <option key={o.value} value={o.value} disabled={o.disabled}>{o.label}</option>)}
</Select>
{description && <p id={`${id}-desc`} className="text-xs leading-relaxed text-fg-subtle">{description}</p>}
</div>
);
}
/** Formato da história (interativa com votação, linear, …), lido da lista central STORY_FORMATS. */
export function StoryFormatSelect({ className, value, onChange }: { className?: string; value?: StoryKind; onChange?: (kind: StoryKind) => void }) {
return (
<DescribedSelect name="kind" label="Formato" className={className}
{...(value !== undefined ? { value, onChange } : { defaultValue: DEFAULT_STORY_FORMAT, onChange })}
options={STORY_FORMATS.map((f) => ({ value: f.id, label: f.label, description: f.description }))} />
);
}
export const BRANCH_COUNT_HINT = "Quantas opções o público terá em cada episódio. A IA prepara todas antes da votação.";
/**
* Vertentes por decisão (2, 3 ou 4; campo `branchCount`). Só vale para histórias interativas: em
* formato linear o grupo fica desabilitado (rádio desabilitado não vai no formulário; o servidor usa 2).
*/
export function BranchCountField({ enabled, className }: { enabled: boolean; className?: string }) {
return (
<div className={cx("grid content-start gap-2", className)}>
<ChoiceGroup name="branchCount" legend="Vertentes por decisão" defaultValue="2"
options={(["2", "3", "4"] as const).map((n) => ({ value: n, label: n, disabled: !enabled }))} />
<p className="text-xs leading-relaxed text-fg-subtle">{enabled ? BRANCH_COUNT_HINT : "Só em histórias interativas."}</p>
</div>
);
}
function FormFeedback({ state }: { state: FormState }) {
if (!state) return null;
return state.error ? <Feedback ok={false}>{state.error}</Feedback> : <Feedback ok>{state.message}</Feedback>;
}
export function CreateStoryForm() {
const [state, action, pending] = useActionState(createStoryAction, null);
const [kind, setKind] = useState<StoryKind>(DEFAULT_STORY_FORMAT);
return (
<form action={action} className="grid gap-5">
<div className="grid gap-5 md:grid-cols-2 xl:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_minmax(0,0.9fr)_minmax(0,0.9fr)]">
<Field label="Título">
<Input name="title" required placeholder="Ex.: Entrega Inesperada" />
</Field>
<Field label="Identificador (opcional)" hint="Vira o nome da pasta em stories/.">
<Input name="id" placeholder="Gerado do título se ficar vazio" />
</Field>
<StoryFormatSelect value={kind} onChange={setKind} />
<BranchCountField enabled={kind === "interactive"} />
</div>
<Field label="Premissa">
<Textarea name="logline" rows={2} placeholder="Premissa em uma ou duas frases" />
</Field>
<div className="flex flex-wrap items-center gap-3">
<Button variant="secondary" disabled={pending}>{pending ? "Criando…" : "Criar história vazia"}</Button>
<FormFeedback state={state} />
</div>
</form>
);
}
export function CreateEpisodeForm({ storyId, parentEpisodeId, label }: { storyId: string; parentEpisodeId?: number; label: string }) {
const [state, action, pending] = useActionState(createEpisodeAction, null);
return (
<form action={action} className="flex flex-wrap items-center gap-3">
<input type="hidden" name="storyId" value={storyId} />
{parentEpisodeId && <input type="hidden" name="parentEpisodeId" value={parentEpisodeId} />}
<Input name="title" aria-label="Título interno do episódio" placeholder="Título interno (opcional)" className="max-w-xs" />
<Button disabled={pending}>{pending ? "Criando…" : label}</Button>
<FormFeedback state={state} />
</form>
);
}
export function CommentsForm({ episodeId }: { episodeId: number }) {
const [state, action, pending] = useActionState(addCommentsAction, null);
return (
<form action={action} className="grid gap-3">
<input type="hidden" name="episodeId" value={episodeId} />
<Field label="Comentários do público" hint="Uma linha por comentário, no formato autor: texto.">
<Textarea name="comments" rows={5} required className="font-mono"
placeholder={"@maria: A\n@joao: opção B, com certeza\n@ana: adorei o episódio"} />
</Field>
<div className="flex items-center gap-3">
<Button variant="secondary" disabled={pending}>{pending ? "Adicionando…" : "Adicionar comentários"}</Button>
<FormFeedback state={state} />
</div>
</form>
);
}
export function CloseDecisionForm({ episodeId, tied, letters = ["A", "B"] }: {
episodeId: number; tied: boolean;
/** Letras em jogo nesta decisão (2 a 4). */
letters?: Choice[];
}) {
const [state, action, pending] = useActionState(closeDecisionAction, null);
const [manual, setManual] = useState(tied);
return (
<form action={action} className="grid gap-3"
onSubmit={confirmSubmit({ title: "Fechar a votação?", message: "A fotografia é imutável e não pode ser reaberta.",
confirmLabel: "Fechar votação", tone: "danger" })}>
<input type="hidden" name="episodeId" value={episodeId} />
<label className="flex items-center gap-2 text-sm text-fg-muted">
<input type="checkbox" checked={manual} onChange={(e) => setManual(e.target.checked)} className="size-4 accent-accent" />
Decisão manual (obrigatória em empate ou sem votos)
</label>
{manual && (
<div className="grid gap-3 sm:grid-cols-[120px_1fr]">
<Select name="manualWinner" aria-label="Opção vencedora" defaultValue={letters[0]}>
{letters.map((l) => <option key={l} value={l}>Vence {l}</option>)}
</Select>
<Input name="reason" aria-label="Justificativa" placeholder="Justificativa (fica registrada na fotografia da votação)" />
</div>
)}
<div className="flex items-center gap-3">
<Button disabled={pending}>
{pending ? "Fechando…" : "Fechar votação"}
</Button>
<FormFeedback state={state} />
</div>
</form>
);
}
export const BRANCHES_STATUS: Record<BranchesStatus, { label: string; tone: Tone; pulse?: boolean }> = {
none: { label: "vertentes não preparadas", tone: "neutral" },
queued: { label: "na fila", tone: "warning" },
running: { label: "preparando…", tone: "info", pulse: true },
ready: { label: "vertentes prontas", tone: "success" },
error: { label: "erro no preparo", tone: "danger" },
};
/** Selo do preparo das vertentes (na fila, preparando…, prontas, erro). */
export function BranchesStatusBadge({ status, className }: { status: BranchesStatus; className?: string }) {
const s = BRANCHES_STATUS[status];
return <Badge tone={s.tone} pulse={s.pulse} className={className}>{s.label}</Badge>;
}
/**
* "Preparar vertentes" (server action prepareBranchesAction): a IA escreve as opções, o roteiro e a cena
* de cada vertente do próximo nível. Com as vertentes prontas, vira "Gerar de novo" (regenerate=1).
*/
export function PrepareBranchesForm({ episodeId, status, runId, hasScript }: {
episodeId: number; status: BranchesStatus; runId: number | null; hasScript: boolean;
}) {
const [state, action, pending] = useActionState(prepareBranchesAction, null);
const busy = status === "queued" || status === "running";
const regenerate = status === "ready";
return (
<form action={action} className="grid gap-3"
onSubmit={confirmSubmit({ title: "Gerar as vertentes de novo?",
message: "A IA reescreve opções, roteiros e cenas das vertentes deste episódio.", confirmLabel: "Gerar de novo" },
() => regenerate)}>
<input type="hidden" name="episodeId" value={episodeId} />
{regenerate && <input type="hidden" name="regenerate" value="1" />}
<div className="flex flex-wrap items-center gap-2.5">
<BranchesStatusBadge status={status} />
{runId && status !== "none" && (
<Link href={`/agent?run=${runId}`} className="inline-flex items-center gap-1.5 rounded text-xs font-medium text-fg-muted hover:text-fg hover:underline">
<TerminalIcon size={14} />ver no console
</Link>
)}
</div>
<div className="flex flex-wrap items-center gap-3">
<Button variant={regenerate ? "secondary" : "primary"} disabled={pending || busy || !hasScript}>
{pending || busy ? <><Spinner />{status === "queued" ? "Na fila…" : "Preparando…"}</>
: regenerate ? <><RefreshIcon size={16} />Gerar de novo</>
: <><SparkIcon size={16} />Preparar vertentes</>}
</Button>
<FormFeedback state={state} />
</div>
{!hasScript && <p className="text-xs text-fg-subtle">Escreva o roteiro deste episódio antes de preparar as vertentes.</p>}
</form>
);
}
+205
View File
@@ -0,0 +1,205 @@
// Ícones SVG inline (traço de 1,75 px, grade 24×24). Decorativos: sempre aria-hidden.
// Sempre `shrink-0`: um SVG dentro de um flex encolhe até 0 px quando o texto ao lado não cabe
// (era o que apagava a faísca do "Nova história com IA" na barra recolhida).
import type { ReactNode } from "react";
type IconProps = { size?: number; className?: string };
function Svg({ children, size = 20, className }: IconProps & { children: ReactNode }) {
return (
<svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke="currentColor" strokeWidth="1.75"
strokeLinecap="round" strokeLinejoin="round" className={className ? `shrink-0 ${className}` : "shrink-0"}
aria-hidden="true" focusable="false">
{children}
</svg>
);
}
export const FilmIcon = (p: IconProps) => (
<Svg {...p}><rect x="3" y="4" width="18" height="16" rx="2.5" /><path d="M7 4v16M17 4v16M3 9h4M3 15h4M17 9h4M17 15h4" /></Svg>
);
export const CubeIcon = (p: IconProps) => (
<Svg {...p}><path d="M12 3l8 4.5v9L12 21l-8-4.5v-9L12 3Z" /><path d="M4 7.5l8 4.5 8-4.5M12 12v9" /></Svg>
);
export const TerminalIcon = (p: IconProps) => (
<Svg {...p}><rect x="3" y="4" width="18" height="16" rx="2.5" /><path d="M7 9l3 3-3 3M13 15h4" /></Svg>
);
export const XIcon = (p: IconProps) => (
<Svg {...p}><path d="M6 6l12 12M18 6 6 18" /></Svg>
);
export const PlusIcon = (p: IconProps) => (
<Svg {...p}><path d="M12 5v14M5 12h14" /></Svg>
);
export const SendIcon = (p: IconProps) => (
<Svg {...p}><path d="M5 12h13M13 6l6 6-6 6" /></Svg>
);
/** Faíscas: tudo que é feito pela IA. */
export const SparkIcon = (p: IconProps) => (
<Svg {...p}><path d="M10 3.5l1.6 4.4L16 9.5l-4.4 1.6L10 15.5l-1.6-4.4L4 9.5l4.4-1.6L10 3.5Z" /><path d="M18 14l.8 2.2L21 17l-2.2.8L18 20l-.8-2.2L15 17l2.2-.8L18 14Z" /></Svg>
);
export const PlayIcon = (p: IconProps) => (
<Svg {...p}><path d="M8 5.5v13a.5.5 0 0 0 .77.42l10-6.5a.5.5 0 0 0 0-.84l-10-6.5A.5.5 0 0 0 8 5.5Z" /></Svg>
);
export const ArrowRightIcon = (p: IconProps) => (
<Svg {...p}><path d="M5 12h14M13 6l6 6-6 6" /></Svg>
);
export const ArrowLeftIcon = (p: IconProps) => (
<Svg {...p}><path d="M19 12H5M11 6l-6 6 6 6" /></Svg>
);
export const AlertIcon = (p: IconProps) => (
<Svg {...p}><path d="M12 4l9 16H3L12 4Z" /><path d="M12 10v4M12 17.5v.01" /></Svg>
);
export const BookIcon = (p: IconProps) => (
<Svg {...p}><path d="M4 5.5A2.5 2.5 0 0 1 6.5 3H20v15H6.5A2.5 2.5 0 0 0 4 20.5v-15Z" /><path d="M4 20.5A2.5 2.5 0 0 0 6.5 23H20v-5" /><path d="M9 8h7" /></Svg>
);
export const PenIcon = (p: IconProps) => (
<Svg {...p}><path d="M4 20h4L19 9a2.83 2.83 0 0 0-4-4L4 16v4Z" /><path d="M13.5 6.5l4 4" /></Svg>
);
export const ClapperIcon = (p: IconProps) => (
<Svg {...p}><path d="M4 11h16v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8Z" /><path d="M4 11l-.6-3.2a1.5 1.5 0 0 1 1.2-1.75L17.4 3.6a1.5 1.5 0 0 1 1.75 1.2L19.7 8 4 11Z" /><path d="M8.5 5.6l2.6 3.6M13.5 4.7l2.6 3.6" /></Svg>
);
export const WandIcon = (p: IconProps) => (
<Svg {...p}><path d="M4 20 15 9M13 7l4 4" /><path d="M19 3v3M17.5 4.5h3M20 13v2M19 14h2M9 3v2M8 4h2" /></Svg>
);
export const CheckIcon = (p: IconProps) => (
<Svg {...p}><path d="M5 12.5l4.5 4.5L19 7.5" /></Svg>
);
export const FolderIcon = (p: IconProps) => (
<Svg {...p}><path d="M3 7a2 2 0 0 1 2-2h4l2 2.5h8a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Z" /></Svg>
);
export const UploadIcon = (p: IconProps) => (
<Svg {...p}><path d="M12 15V4M7 9l5-5 5 5" /><path d="M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3" /></Svg>
);
export const LibraryIcon = (p: IconProps) => (
<Svg {...p}><path d="M4 4h4v16H4zM10 4h4v16h-4z" /><path d="m16.5 4.8 3.8-1 3.2 15.6-3.8 1z" transform="translate(-2.5 .5)" /></Svg>
);
export const ClockIcon = (p: IconProps) => (
<Svg {...p}><circle cx="12" cy="12" r="8.5" /><path d="M12 7.5V12l3 2" /></Svg>
);
export const ChevronDownIcon = (p: IconProps) => (
<Svg {...p}><path d="m6 9 6 6 6-6" /></Svg>
);
export const StopIcon = (p: IconProps) => (
<Svg {...p}><rect x="6" y="6" width="12" height="12" rx="2" /></Svg>
);
export const ChatIcon = (p: IconProps) => (
<Svg {...p}><path d="M5 18.5V6a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H8l-3 2.5Z" /><path d="M9 9h6M9 12h4" /></Svg>
);
/** Microfone com onda: vozes, narração e legenda. */
export const MicIcon = (p: IconProps) => (
<Svg {...p}><rect x="9" y="3" width="6" height="11" rx="3" /><path d="M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21M9 21h6" /></Svg>
);
/** Onda sonora: áudio e síntese. */
export const WaveIcon = (p: IconProps) => (
<Svg {...p}><path d="M3 12h1.5M7 8v8M10.5 5v14M14 9v6M17.5 7v10M21 12h-1" /></Svg>
);
export const TrashIcon = (p: IconProps) => (
<Svg {...p}><path d="M4 7h16M9.5 7V4.5h5V7M6.5 7l1 12.5a1.5 1.5 0 0 0 1.5 1.5h6a1.5 1.5 0 0 0 1.5-1.5l1-12.5" /><path d="M10 11v6M14 11v6" /></Svg>
);
export const DownloadIcon = (p: IconProps) => (
<Svg {...p}><path d="M12 4v11M7 10l5 5 5-5" /><path d="M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3" /></Svg>
);
export const CpuIcon = (p: IconProps) => (
<Svg {...p}><rect x="6" y="6" width="12" height="12" rx="2" /><path d="M10 10h4v4h-4zM9 3v3M15 3v3M9 18v3M15 18v3M3 9h3M3 15h3M18 9h3M18 15h3" /></Svg>
);
export const SettingsIcon = (p: IconProps) => (
<Svg {...p}><path d="M4 7h10M18 7h2M4 17h4M12 17h8" /><circle cx="16" cy="7" r="2" /><circle cx="10" cy="17" r="2" /></Svg>
);
export const RefreshIcon = (p: IconProps) => (
<Svg {...p}><path d="M19.5 12a7.5 7.5 0 1 1-2.2-5.3L19.5 9" /><path d="M19.5 4v5h-5" /></Svg>
);
/** Mostrador: visão geral de uma área. */
export const GaugeIcon = (p: IconProps) => (
<Svg {...p}><path d="M4.2 17.5a8.5 8.5 0 1 1 15.6 0" /><path d="m12 14 3.5-4.5" /><path d="M12 14h.01M7 12.5h.01M17 12.5h.01M12 7.5h.01" /></Svg>
);
/** Lupa: busca. */
export const SearchIcon = (p: IconProps) => (
<Svg {...p}><circle cx="11" cy="11" r="6.5" /><path d="m20 20-4.2-4.2" /></Svg>
);
/** Lista: catálogos e coleções. */
export const ListIcon = (p: IconProps) => (
<Svg {...p}><path d="M9 6h11M9 12h11M9 18h11M4.5 6h.01M4.5 12h.01M4.5 18h.01" /></Svg>
);
/** Servidor: serviços locais e suas configurações. */
export const ServerIcon = (p: IconProps) => (
<Svg {...p}><rect x="3.5" y="4" width="17" height="7" rx="2" /><rect x="3.5" y="13" width="17" height="7" rx="2" /><path d="M7.5 7.5h.01M7.5 16.5h.01M11 7.5h5.5M11 16.5h5.5" /></Svg>
);
/** Contas: duas pessoas. */
export const UsersIcon = (p: IconProps) => (
<Svg {...p}><circle cx="9" cy="8" r="3.25" /><path d="M3 19.5c.6-3.2 3-5 6-5s5.4 1.8 6 5" /><path d="M15.5 4.9a3.25 3.25 0 0 1 0 6.2M17.5 14.7c1.8.6 3.1 2.2 3.5 4.8" /></Svg>
);
export const LinkIcon = (p: IconProps) => (
<Svg {...p}><path d="M10 14a4 4 0 0 0 5.66 0l3-3a4 4 0 0 0-5.66-5.66l-1 1" /><path d="M14 10a4 4 0 0 0-5.66 0l-3 3a4 4 0 0 0 5.66 5.66l1-1" /></Svg>
);
export const UnlinkIcon = (p: IconProps) => (
<Svg {...p}><path d="M15.5 13.5l3.2-3.2a4 4 0 0 0-5.66-5.66l-1.6 1.6M8.5 10.5l-3.2 3.2a4 4 0 0 0 5.66 5.66l1.6-1.6" /><path d="M4 4l16 16" /></Svg>
);
/** Dashboard: barras subindo. */
export const ChartIcon = (p: IconProps) => (
<Svg {...p}><path d="M4 20h16" /><path d="M7 16v-4M12 16V7M17 16v-7" /></Svg>
);
/** Fluxo da história: um nó que se divide em vertentes. */
export const FlowIcon = (p: IconProps) => (
<Svg {...p}><rect x="3" y="9.5" width="5" height="5" rx="1.25" /><rect x="16" y="3.5" width="5" height="5" rx="1.25" /><rect x="16" y="15.5" width="5" height="5" rx="1.25" /><path d="M8 12h3.5M11.5 6v12M11.5 6H16M11.5 18H16" /></Svg>
);
export const EyeIcon = (p: IconProps) => (
<Svg {...p}><path d="M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12Z" /><circle cx="12" cy="12" r="2.75" /></Svg>
);
export const HeartIcon = (p: IconProps) => (
<Svg {...p}><path d="M12 20s-7.5-4.4-7.5-10A4.25 4.25 0 0 1 12 7.4 4.25 4.25 0 0 1 19.5 10c0 5.6-7.5 10-7.5 10Z" /></Svg>
);
export const TrophyIcon = (p: IconProps) => (
<Svg {...p}><path d="M8 4h8v5a4 4 0 0 1-8 0V4Z" /><path d="M8 6H5a3 3 0 0 0 3 4M16 6h3a3 3 0 0 1-3 4M12 13v4M8.5 20h7M10 17h4" /></Svg>
);
export const TrendDownIcon = (p: IconProps) => (
<Svg {...p}><path d="M3 7l6 6 4-4 8 8" /><path d="M15 17h6v-6" /></Svg>
);
/** Tesoura: cortes de live (Clipador). */
export const ScissorsIcon = (p: IconProps) => (
<Svg {...p}><circle cx="6.5" cy="6.5" r="2.75" /><circle cx="6.5" cy="17.5" r="2.75" /><path d="M8.6 8.3 20 18.5M8.6 15.7 20 5.5" /></Svg>
);
/** Desfazer: seta voltando. */
export const UndoIcon = (p: IconProps) => (
<Svg {...p}><path d="M9 14 4 9l5-5" /><path d="M4 9h10.5a5.5 5.5 0 0 1 0 11H11" /></Svg>
);
/** Transmissão ao vivo: ponto com ondas. */
export const BroadcastIcon = (p: IconProps) => (
<Svg {...p}><circle cx="12" cy="12" r="2" /><path d="M8.5 8.5a5 5 0 0 0 0 7M15.5 8.5a5 5 0 0 1 0 7M5.6 5.6a9 9 0 0 0 0 12.8M18.4 5.6a9 9 0 0 1 0 12.8" /></Svg>
);
/* Redes sociais: traços próprios e simples (não são os logotipos oficiais). */
export const TikTokIcon = (p: IconProps) => (
<Svg {...p}><path d="M14 4v10.5a3.5 3.5 0 1 1-3.5-3.5" /><path d="M14 4c.4 2.6 2.2 4.2 5 4.5" /></Svg>
);
export const InstagramIcon = (p: IconProps) => (
<Svg {...p}><rect x="3.5" y="3.5" width="17" height="17" rx="5" /><circle cx="12" cy="12" r="3.75" /><path d="M17 7v.01" /></Svg>
);
export const YouTubeIcon = (p: IconProps) => (
<Svg {...p}><rect x="2.5" y="5.5" width="19" height="13" rx="4" /><path d="M10.25 9.25v5.5L15 12l-4.75-2.75Z" /></Svg>
);
export const TwitchIcon = (p: IconProps) => (
<Svg {...p}><path d="M5 3.5h15v10l-4 4h-4l-3 3v-3H5v-14Z" /><path d="M11 8v4M15.5 8v4" /></Svg>
);
export const KickIcon = (p: IconProps) => (
<Svg {...p}><rect x="3.5" y="3.5" width="17" height="17" rx="3.5" /><path d="M9.5 7.5v9M9.5 12l4.5-4.5M9.5 12l4.5 4.5" /></Svg>
);
// Publicação: avião de papel (publicar), calendário (agendar), chave (apps), globo (navegador), informação, pausa.
export const PublishIcon = (p: IconProps) => (
<Svg {...p}><path d="M21 3 10.5 13.5" /><path d="M21 3l-6.5 18-4-7.5L3 9.5 21 3Z" /></Svg>
);
export const CalendarIcon = (p: IconProps) => (
<Svg {...p}><rect x="3.5" y="5" width="17" height="15.5" rx="2.5" /><path d="M3.5 10h17M8 3v4M16 3v4" /></Svg>
);
export const KeyIcon = (p: IconProps) => (
<Svg {...p}><circle cx="8" cy="15.5" r="4" /><path d="m10.9 12.6 9.1-9.1M16.5 7l3 3M14 9.5l2 2" /></Svg>
);
export const GlobeIcon = (p: IconProps) => (
<Svg {...p}><circle cx="12" cy="12" r="9" /><path d="M3 12h18M12 3c2.5 2.6 3.8 5.6 3.8 9s-1.3 6.4-3.8 9c-2.5-2.6-3.8-5.6-3.8-9S9.5 5.6 12 3Z" /></Svg>
);
export const InfoIcon = (p: IconProps) => (
<Svg {...p}><circle cx="12" cy="12" r="9" /><path d="M12 11v5.5M12 7.5v.01" /></Svg>
);
export const PauseIcon = (p: IconProps) => (
<Svg {...p}><rect x="6.5" y="5" width="3.5" height="14" rx="1" /><rect x="14" y="5" width="3.5" height="14" rx="1" /></Svg>
);
+43
View File
@@ -0,0 +1,43 @@
// Identidade do CenaForge: um quadro vertical (o episódio 9:16) aceso pela brasa da forja,
// com o "play" no centro. A mesma geometria vive em app/icon.svg (favicon); legível a 16 e 32 px.
// Geometria na grade de 32: o quadro ocupa x 8–24 e y 4–28 (bordas em pixel inteiro, nítidas a 16/32 px)
// e o play fica no centro óptico, com folga parecida dos dois lados — antes ele encostava na borda direita.
import { useId } from "react";
const PLAY_PATH = "M13.9 12.75v6.5a.75.75 0 0 0 1.14.64l5.05-3.25a.75.75 0 0 0 0-1.28l-5.05-3.25a.75.75 0 0 0-1.14.64Z";
export function LogoMark({ size = 32, className }: { size?: number; className?: string }) {
const id = `logo${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;
return (
<svg viewBox="0 0 32 32" width={size} height={size} className={className} aria-hidden="true" focusable="false">
<defs>
<linearGradient id={`${id}-g`} x1="4" y1="2" x2="28" y2="30" gradientUnits="userSpaceOnUse">
<stop offset="0" stopColor="var(--color-glow)" />
<stop offset="0.5" stopColor="var(--color-accent)" />
<stop offset="1" stopColor="var(--color-flame)" />
</linearGradient>
</defs>
<rect width="32" height="32" rx="9" fill={`url(#${id}-g)`} />
<rect x="8" y="4" width="16" height="24" rx="4" fill="var(--color-accent-fg)" />
<path d={PLAY_PATH} fill={`url(#${id}-g)`} />
</svg>
);
}
export function Wordmark({ className }: { className?: string }) {
return (
<span className={className}>
<span className="font-display text-[1.0625rem] font-semibold tracking-[-0.02em] text-fg">Cena</span>
<span className="font-display text-[1.0625rem] font-semibold tracking-[-0.02em] text-flame">Forge</span>
</span>
);
}
export function Logo() {
return (
<span className="flex items-center gap-2.5">
<LogoMark />
<Wordmark />
</span>
);
}
+228
View File
@@ -0,0 +1,228 @@
// Peças do dashboard (sem estado): KPI, gráfico de views por dia, tabela de métricas e tabela de vídeos.
// Gráficos leves em HTML/CSS com as cores do tema; cada gráfico tem a tabela de dados para leitores de tela.
import Link from "next/link";
import type { ReactNode } from "react";
import type { VideoMetrics } from "@/lib/metrics";
import type { MetricTotals, Platform } from "@/lib/types";
import { PLATFORM_META } from "./platforms";
import { cx, fileUrl, formatCompact, formatInteger, formatPercent } from "./ui";
export function Kpi({ label, value, hint, icon, emphasis = false }: { label: string; value: string; hint?: ReactNode; icon?: ReactNode; emphasis?: boolean }) {
return (
<div className={cx("grid content-start gap-2 rounded-card border bg-surface px-5 py-4 shadow-card",
emphasis ? "border-accent/30" : "border-line")}>
<dt className="flex min-w-0 items-center gap-2 text-eyebrow font-semibold tracking-[0.08em] text-fg-subtle uppercase md:tracking-[0.16em] [&_svg]:text-fg-subtle">{icon}{label}</dt>
<dd className="grid gap-1">
<span className={cx("font-display text-[1.5rem] leading-none font-semibold tracking-tight tabular-nums md:text-[1.875rem]", emphasis ? "text-accent" : "text-fg")}>{value}</span>
{hint && <span className="text-xs text-fg-subtle">{hint}</span>}
</dd>
</div>
);
}
function shortDay(day: string): string {
const [, m, d] = day.split("-");
return `${d}/${m}`;
}
/** Views por dia de publicação: barras verticais, com linhas de grade e a tabela equivalente escondida. */
export function DailyViewsChart({ daily }: { daily: { day: string; views: number; publications: number }[] }) {
if (daily.length === 0) return <p className="text-sm text-fg-subtle">Sem publicações no período.</p>;
const max = Math.max(1, ...daily.map((d) => d.views));
const step = niceStep(max);
const top = Math.ceil(max / step) * step;
const ticks = [top, top * (2 / 3), top / 3, 0].map((v) => Math.round(v));
const labelEvery = daily.length > 16 ? Math.ceil(daily.length / 8) : daily.length > 8 ? 2 : 1;
const total = daily.reduce((sum, d) => sum + d.views, 0);
const best = daily.reduce((a, b) => (b.views > a.views ? b : a));
return (
<figure className="grid gap-3">
<div className="grid grid-cols-[3rem_minmax(0,1fr)] gap-x-2">
{/* Eixo Y */}
<div aria-hidden="true" className="relative h-52 text-right text-[0.6875rem] text-fg-subtle tabular-nums">
{ticks.map((t, i) => (
<span key={i} className="absolute right-0 -translate-y-1/2" style={{ top: `${(i / (ticks.length - 1)) * 100}%` }}>{formatCompact(t)}</span>
))}
</div>
<div aria-hidden="true" className="relative h-52">
{ticks.map((_, i) => (
<span key={i} className={cx("absolute inset-x-0 h-px", i === ticks.length - 1 ? "bg-line-strong" : "bg-line")}
style={{ top: `${(i / (ticks.length - 1)) * 100}%` }} />
))}
<div className="absolute inset-0 flex items-end gap-[3px]">
{daily.map((d) => (
<div key={d.day} className="group relative flex h-full min-w-0 flex-1 items-end"
title={`${shortDay(d.day)}: ${formatInteger(d.views)} views, ${d.publications} publicação(ões)`}>
<div className={cx("mx-auto w-full max-w-12 rounded-t-[3px] bg-accent/80 transition-colors group-hover:bg-accent", d === best && "bg-accent")}
style={{ height: `${Math.max(d.views > 0 ? 1.5 : 0, (d.views / top) * 100)}%` }} />
</div>
))}
</div>
</div>
{/* Eixo X */}
<span />
<div aria-hidden="true" className="mt-2 flex gap-[3px] text-[0.6875rem] text-fg-subtle tabular-nums">
{daily.map((d, i) => (
<span key={d.day} className="min-w-0 flex-1 text-center whitespace-nowrap">
{i % labelEvery === 0 ? shortDay(d.day) : ""}
</span>
))}
</div>
</div>
<figcaption className="text-xs text-fg-subtle">
{formatCompact(total)} views em {daily.length} dia{daily.length === 1 ? "" : "s"} com publicação · pico em {shortDay(best.day)} ({formatCompact(best.views)}).
</figcaption>
<table className="sr-only">
<caption>Views por dia de publicação</caption>
<thead><tr><th scope="col">Dia</th><th scope="col">Views</th><th scope="col">Publicações</th></tr></thead>
<tbody>{daily.map((d) => <tr key={d.day}><td>{shortDay(d.day)}</td><td>{formatInteger(d.views)}</td><td>{d.publications}</td></tr>)}</tbody>
</table>
</figure>
);
}
function niceStep(max: number): number {
const raw = max / 3;
const pow = 10 ** Math.floor(Math.log10(raw));
const n = raw / pow;
return (n <= 1 ? 1 : n <= 2 ? 2 : n <= 5 ? 5 : 10) * pow;
}
export type MetricRow = { key: string; label: ReactNode; sub?: ReactNode; href?: string; totals: MetricTotals };
/**
* Tabela de desempenho: views (com barra relativa à maior), engajamento, conclusão e publicações.
* `accent` destaca a coluna de engajamento (usado em melhores/piores).
*/
export function MetricTable({ rows, caption, firstColumn, empty = "Sem dados." }: {
rows: MetricRow[]; caption: string; firstColumn: string; empty?: string;
}) {
if (rows.length === 0) return <p className="rounded-control border border-dashed border-line-strong px-4 py-3 text-sm text-fg-subtle">{empty}</p>;
const max = Math.max(1, ...rows.map((r) => r.totals.views));
return (
<div className="overflow-x-auto rounded-control border border-line">
<table className="w-full min-w-[34rem] text-left text-sm">
<caption className="sr-only">{caption}</caption>
<thead className="bg-raised/60 text-[0.6875rem] tracking-[0.12em] text-fg-subtle uppercase">
<tr>
<th scope="col" className="px-4 py-2.5 font-semibold">{firstColumn}</th>
<th scope="col" className="px-4 py-2.5 text-right font-semibold">Views</th>
<th scope="col" className="px-4 py-2.5 text-right font-semibold">Engaj.</th>
<th scope="col" className="px-4 py-2.5 text-right font-semibold">Conclusão</th>
<th scope="col" className="px-4 py-2.5 text-right font-semibold">Public.</th>
</tr>
</thead>
<tbody>
{rows.map((r) => (
<tr key={r.key} className="border-t border-line transition-colors hover:bg-raised/40">
<th scope="row" className="min-w-40 px-4 py-2.5 font-normal">
<span className="grid max-w-72 min-w-0 gap-0.5">
{r.href
? <Link href={r.href} className="truncate font-medium text-fg hover:text-accent hover:underline">{r.label}</Link>
: <span className="truncate font-medium text-fg">{r.label}</span>}
{r.sub && <span className="truncate text-xs text-fg-subtle">{r.sub}</span>}
</span>
</th>
<td className="w-40 px-4 py-2.5 text-right">
<span className="grid justify-items-end gap-1">
<span className="tabular-nums text-fg" title={`${formatInteger(r.totals.views)} views`}>{formatCompact(r.totals.views)}</span>
<span aria-hidden="true" className="h-1 w-full max-w-28 overflow-hidden rounded-full bg-overlay">
<span className="block h-full rounded-full bg-accent/70" style={{ width: `${(r.totals.views / max) * 100}%` }} />
</span>
</span>
</td>
<td className="px-4 py-2.5 text-right tabular-nums text-fg">{formatPercent(r.totals.engagementRate)}</td>
<td className="px-4 py-2.5 text-right tabular-nums text-fg-muted">{formatPercent(r.totals.completionRate)}</td>
<td className="px-4 py-2.5 text-right tabular-nums text-fg-muted">{formatInteger(r.totals.publications)}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
const VIDEO_PLATFORMS: Platform[] = ["youtube", "tiktok", "instagram"];
/**
* Cada vídeo (corte ou episódio) numa linha: capa, título, views de cada rede (link para o post) e o total.
* "—" = não saiu nessa rede; "…" = saiu, mas os números ainda não foram lidos.
*/
export function VideoTable({ videos }: { videos: VideoMetrics[] }) {
if (videos.length === 0) return <p className="rounded-control border border-dashed border-line-strong px-4 py-3 text-sm text-fg-subtle">Nenhum vídeo publicado ainda.</p>;
const max = Math.max(1, ...videos.map((v) => v.totals.views));
return (
<div className="overflow-x-auto rounded-control border border-line">
<table className="w-full min-w-[46rem] text-left text-sm">
<caption className="sr-only">Views de cada vídeo, por rede e no total</caption>
<thead className="bg-raised/60 text-[0.6875rem] tracking-[0.12em] text-fg-subtle uppercase">
<tr>
<th scope="col" className="px-4 py-2.5 font-semibold">Vídeo</th>
{VIDEO_PLATFORMS.map((p) => {
const Icon = PLATFORM_META[p].icon;
return <th key={p} scope="col" className="px-3 py-2.5 text-right font-semibold"><span className="inline-flex items-center gap-1.5"><Icon size={13} />{PLATFORM_META[p].label}</span></th>;
})}
<th scope="col" className="px-4 py-2.5 text-right font-semibold">Total de views</th>
<th scope="col" className="px-3 py-2.5 text-right font-semibold">Curtidas</th>
<th scope="col" className="px-3 py-2.5 text-right font-semibold">Coment.</th>
</tr>
</thead>
<tbody>
{videos.map((v) => (
<tr key={v.key} className="border-t border-line align-middle transition-colors hover:bg-raised/40">
<th scope="row" className="px-4 py-2.5 font-normal">
<span className="flex min-w-0 items-center gap-3">
{v.cover
? <img src={fileUrl(v.cover)} alt="" loading="lazy" className="h-12 w-[1.6875rem] shrink-0 rounded-[3px] border border-line object-cover" />
: <span aria-hidden="true" className="h-12 w-[1.6875rem] shrink-0 rounded-[3px] border border-line bg-sunken" />}
<span className="grid max-w-80 min-w-0 gap-0.5">
{v.href
? <Link href={v.href} className="line-clamp-2 font-medium text-fg hover:text-accent hover:underline">{v.title}</Link>
: <span className="line-clamp-2 font-medium text-fg">{v.title}</span>}
<span className="text-xs text-fg-subtle">{v.kind === "clip" ? "Corte do Clipador" : "Episódio"} · {shortDate(v.publishedAt)}</span>
</span>
</span>
</th>
{VIDEO_PLATFORMS.map((p) => {
const posts = v.networks.filter((n) => n.platform === p);
if (posts.length === 0) return <td key={p} className="px-3 py-2.5 text-right text-fg-subtle"><span aria-label="não publicado">—</span></td>;
return (
<td key={p} className="px-3 py-2.5 text-right">
<span className="grid justify-items-end gap-0.5">
{posts.map((n) => (
<a key={n.url} href={n.url} target="_blank" rel="noopener noreferrer" title={n.capturedAt ? `Lido em ${shortDateTime(n.capturedAt)} · ${n.accountName}` : "Números ainda não lidos"}
className="tabular-nums text-fg underline-offset-2 hover:text-accent hover:underline">
{n.views === null ? <span className="text-fg-subtle">…</span> : formatCompact(n.views)}
<span className="sr-only"> views no {PLATFORM_META[p].label} (abre o post numa aba nova)</span>
</a>
))}
</span>
</td>
);
})}
<td className="w-40 px-4 py-2.5 text-right">
<span className="grid justify-items-end gap-1">
<span className="font-semibold tabular-nums text-fg" title={`${formatInteger(v.totals.views)} views`}>{formatCompact(v.totals.views)}</span>
<span aria-hidden="true" className="h-1 w-full max-w-28 overflow-hidden rounded-full bg-overlay">
<span className="block h-full rounded-full bg-accent/70" style={{ width: `${(v.totals.views / max) * 100}%` }} />
</span>
</span>
</td>
<td className="px-3 py-2.5 text-right tabular-nums text-fg-muted">{formatCompact(v.totals.likes)}</td>
<td className="px-3 py-2.5 text-right tabular-nums text-fg-muted">{formatCompact(v.totals.comments)}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
function shortDate(iso: string): string {
return new Date(iso).toLocaleDateString("pt-BR", { day: "2-digit", month: "2-digit", timeZone: "America/Sao_Paulo" });
}
function shortDateTime(iso: string): string {
return new Date(iso).toLocaleString("pt-BR", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit", timeZone: "America/Sao_Paulo" });
}
+665
View File
@@ -0,0 +1,665 @@
"use client";
// Montagem do vídeo documental: um trecho do roteiro = um áudio (gerado parágrafo a parágrafo, com
// números por extenso) + um visual (imagem, clipe, cena 2D/3D do Godot ou cartela). Fala com
// /api/episodes/<id>/montage*. O MP4 sai pelo FFmpeg no servidor; aqui só acompanhamos.
import { useCallback, useEffect, useRef, useState } from "react";
import type { RenderJob } from "@/lib/types";
import { AlertIcon, CheckIcon, ClapperIcon, EyeIcon, MicIcon, PlayIcon, RefreshIcon, SparkIcon, StopIcon, UploadIcon, WaveIcon } from "./icons";
import { Badge, Button, ChoiceGroup, Feedback, Input, RangeField, Select, Spinner, StatusBadge, Switch, Textarea, cx, fileUrl, formatDate } from "./ui";
type VisualKind = "image" | "video" | "godot3d" | "card" | "godot2d";
type Template = "title" | "counter" | "map";
type Scene = { kind?: "doc2d" | "doc3d"; template: Template | "island"; params: Record<string, unknown> };
type ShotVisual = {
kind: VisualKind; file: string | null; credit: string; license: string; sourceUrl: string;
scene?: Scene; sceneKey?: string; search?: { queries: string[]; pick: number }; auto?: boolean;
inset?: { file: string; credit: string; license: string; sourceUrl: string } | null;
};
type MontageShot = {
index: number; time: string; narration: string; onScreen: string; visualHint: string;
spoken: string; spokenEdited: boolean; visual: ShotVisual;
audio: { file: string; durationMs: number } | null; audioStale: boolean;
};
type Montage = { episodeId: number; voiceId: string; speed: number; captions: boolean; style: "mixed" | "3d"; shots: MontageShot[] };
type Option = { file: string; name: string };
type State = {
storyId: string;
montage: Montage;
kinds: { id: VisualKind; label: string; available: boolean; hint: string }[];
templates: { id: Template; label: string }[];
library: LibraryScene[];
job: { renderId: number; progress: string } | null;
options: { images: Option[]; videos: Option[]; renders: Option[] };
renders: RenderJob[];
};
/** Cena da biblioteca do Godot (godot/library/<id>/manifest.json). */
type LibraryParam = { name: string; label: string; type: "select" | "bool" | "number" | "text"; default?: unknown; options?: { value: string; label: string }[] };
type LibraryScene = { id: string; kind: "doc3d" | "doc2d"; label: string; description: string; params: LibraryParam[] };
type Voice = { id: string; name: string; languages: string[]; provider: string; offline: boolean; default: boolean };
const fmtSeconds = (ms: number) => `${(ms / 1000).toFixed(1).replace(".", ",")} s`;
async function call<T>(url: string, init?: RequestInit): Promise<T> {
const r = await fetch(url, init);
const body = await r.json().catch(() => ({}));
if (!r.ok) throw new Error((body as { error?: string }).error ?? `Erro ${r.status}`);
return body as T;
}
export function MontageEditor({ episodeId }: { episodeId: number }) {
const base = `/api/episodes/${episodeId}/montage`;
const [state, setState] = useState<State | null>(null);
const [voices, setVoices] = useState<Voice[] | null>(null);
const [voiceOnline, setVoiceOnline] = useState(true);
const [error, setError] = useState<string | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [busyShot, setBusyShot] = useState<number | null>(null);
const [batch, setBatch] = useState<{ done: number; total: number } | null>(null);
const [starting, setStarting] = useState(false);
const refresh = useCallback(async () => {
try {
setState(await call<State>(base));
setLoadError(null);
} catch (e) {
setLoadError((e as Error).message);
}
}, [base]);
useEffect(() => { void refresh(); }, [refresh]);
useEffect(() => {
fetch("/api/voice/status").then((r) => r.json()).then((s: { online?: boolean; voices?: Voice[] }) => {
setVoiceOnline(!!s.online);
setVoices((s.voices ?? []).filter((v) => v.languages?.includes("pt-BR")));
}).catch(() => { setVoiceOnline(false); setVoices([]); });
}, []);
// Montagem rodando: consulta o estado até terminar.
const running = state?.renders.find((r) => r.status === "running") ?? null;
useEffect(() => {
if (!running) return;
const t = setInterval(() => void refresh(), 2000);
return () => clearInterval(t);
}, [running, refresh]);
async function patch(body: unknown) {
setError(null);
try {
setState(await call<State>(base, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }));
} catch (e) {
setError((e as Error).message);
}
}
async function generate(index: number): Promise<boolean> {
setBusyShot(index);
try {
await call(`${base}/audio`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ index }) });
return true;
} catch (e) {
setError(`Trecho ${index + 1}: ${(e as Error).message}`);
return false;
} finally {
setBusyShot(null);
}
}
async function generateOne(index: number) {
setError(null);
await generate(index);
await refresh();
}
async function generateMissing() {
if (!state) return;
setError(null);
const todo = state.montage.shots.filter((s) => !s.audio || s.audioStale).map((s) => s.index);
setBatch({ done: 0, total: todo.length });
for (const [i, index] of todo.entries()) {
if (!(await generate(index))) break;
setBatch({ done: i + 1, total: todo.length });
await refresh();
}
setBatch(null);
}
/** auto = um clique: o servidor planeja as cenas, gera narração, renderiza no Godot e monta. */
async function startRender(auto: boolean, replan = false) {
setError(null);
setStarting(true);
try {
await call(`${base}/render`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ auto, replan }) });
await refresh();
} catch (e) {
setError((e as Error).message);
} finally {
setStarting(false);
}
}
async function cancelRender(id: number) {
try {
await call(`${base}/render?render=${id}`, { method: "DELETE" });
} catch (e) {
setError((e as Error).message);
}
await refresh();
}
if (loadError) return <Feedback ok={false}>{loadError}</Feedback>;
if (!state) return <p className="flex items-center gap-2 text-sm text-fg-subtle"><Spinner />Carregando a montagem…</p>;
const { montage } = state;
const missingAudioList = montage.shots.filter((s) => !s.audio || s.audioStale).map((s) => s.index + 1);
// Cena 2D do Godot conta como visual escolhido: ela é renderizada na hora de montar.
const missingVisualList = montage.shots.filter((s) => s.visual.kind !== "card" && s.visual.kind !== "godot2d" && !s.visual.file).map((s) => s.index + 1);
const missingAudio = missingAudioList.length;
const missingVisual = missingVisualList.length;
/** Rascunho rápido: trechos sem imagem viram cartela de texto (dá para trocar depois). */
async function fillWithCards() {
for (const n of missingVisualList) await patch({ shot: { index: n - 1, visual: { kind: "card", file: null } } });
}
const totalMs = montage.shots.reduce((sum, s) => sum + (s.audio?.durationMs ?? 0), 0);
const latest = state.renders[0] ?? null;
const latestOk = state.renders.find((r) => r.status === "success" && r.mp4) ?? null;
const working = busyShot !== null || !!batch;
return (
<div className="grid gap-8">
{/* Configuração geral e ações */}
<div className="grid gap-5 rounded-card border border-line bg-sunken/50 p-5">
<div className="grid gap-5 md:grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)_auto] md:items-end">
<label className="grid gap-2">
<span className="flex items-center gap-1.5 text-[0.8125rem] font-medium text-fg-muted"><MicIcon size={14} />Voz da narração</span>
<Select value={montage.voiceId} onChange={(e) => void patch({ voiceId: e.target.value })} disabled={!voices || working}>
<option value="">{voices === null ? "Carregando vozes…" : "Escolha a voz"}</option>
{(voices ?? []).map((v) => <option key={v.id} value={v.id}>{v.name} · {v.provider}{v.offline ? " (offline)" : ""}</option>)}
</Select>
</label>
<RangeField label="Velocidade" min={0.7} max={1.3} step={0.05} value={montage.speed} disabled={working}
onChange={(v) => void patch({ speed: v })}
format={(v) => `${v.toLocaleString("pt-BR", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}×`} />
<Switch label="Legenda na tela" checked={montage.captions} onChange={(v) => void patch({ captions: v })} />
</div>
<ChoiceGroup name="montage-style" legend="Estilo do vídeo" value={montage.style}
onChange={(v) => void patch({ style: v })}
options={[
{ value: "mixed", label: "Misto: fotos, 2D e 3D" },
{ value: "3d", label: "Tudo em 3D (fotos em cartão)" },
]} />
{!voiceOnline && <p className="flex items-center gap-2 text-xs text-warning"><AlertIcon size={14} />O serviço de voz está fora do ar: sem ele não dá para gerar os áudios.</p>}
{/* Um clique: plano das cenas + narração + cenas 2D no Godot + montagem. */}
<div className="grid gap-4 border-t border-line pt-5 md:grid-cols-[auto_minmax(0,1fr)] md:items-center">
<Button variant="flame" size="lg" disabled={!!running || starting || working || !voiceOnline} onClick={() => void startRender(true)}>
{running || starting ? <><Spinner />Gerando o vídeo…</> : <><SparkIcon size={18} />Gerar vídeo automático</>}
</Button>
{running && state.job ? (
<p className="flex items-center gap-2 text-sm text-fg" aria-live="polite">
<span className="size-2 animate-pulse rounded-full bg-accent" />{state.job.progress}
<Button size="sm" variant="ghost" onClick={() => void cancelRender(state.job!.renderId)}><StopIcon size={14} />Cancelar</Button>
</p>
) : (
<p className="text-xs leading-relaxed text-fg-subtle">
Um clique: para cada trecho, pelo roteiro, busca a foto real na internet (animal, lugar), cria mapa ou infográfico em 2D,
usa uma cena 3D da biblioteca do Godot quando combina, gera a narração trecho a trecho e monta o vídeo.
Não gostou de um trecho? “Gerar de novo” nele. O que você escolheu à mão é mantido.
</p>
)}
</div>
{/* Modo manual: passo a passo. */}
<div className="flex flex-wrap items-center gap-3">
<Button size="sm" variant="secondary" disabled={!montage.voiceId || working || !!running || missingAudio === 0} onClick={() => void generateMissing()}>
{batch ? <><Spinner />Gerando {batch.done + 1} de {batch.total}…</> : <><WaveIcon size={14} />{missingAudio ? `Gerar ${missingAudio} ${missingAudio === 1 ? "áudio" : "áudios"}` : "Áudios prontos"}</>}
</Button>
<Button size="sm" variant="secondary" disabled={!!running || starting || working || missingAudio > 0 || missingVisual > 0} onClick={() => void startRender(false)}
title={missingAudio || missingVisual ? "Faltam áudios ou visuais: veja o aviso abaixo, ou use Gerar vídeo automático" : undefined}>
<ClapperIcon size={14} />Só montar
</Button>
<Button size="sm" variant="ghost" disabled={!!running || starting || working || !voiceOnline} onClick={() => void startRender(true, true)}
title="Escolhe de novo o visual de todos os trechos automáticos (os que você escolheu à mão ficam)">
<RefreshIcon size={14} />Refazer tudo do zero
</Button>
<span className="text-xs text-fg-subtle">
{totalMs ? <>Narração: <span className="tabular-nums text-fg-muted">{fmtSeconds(totalMs)}</span> · </> : null}
{missingAudio > 0 ? `${missingAudio} sem áudio` : "áudios prontos"}{missingVisual > 0 ? ` · ${missingVisual} sem visual (o automático usa cena 2D)` : ""}
</span>
</div>
{/* O que falta para o modo manual, com atalho para cada trecho. */}
{(missingAudio > 0 || missingVisual > 0) && !running && (
<div className="grid gap-2.5 rounded-control border border-line bg-surface/60 px-4 py-3">
{missingAudioList.length > 0 && <MissingLine label="Sem áudio" shots={missingAudioList} />}
{missingVisualList.length > 0 && <MissingLine label="Sem visual" shots={missingVisualList} />}
{missingVisual > 0 && (
<div className="flex flex-wrap items-center gap-3">
<Button size="sm" variant="ghost" disabled={working} onClick={() => void fillWithCards()}>Usar cartela nos vazios</Button>
<span className="text-xs text-fg-subtle">ou deixe o automático criar as cenas 2D.</span>
</div>
)}
</div>
)}
{error && <Feedback ok={false}>{error}</Feedback>}
</div>
{/* Trechos */}
<ol className="grid gap-4">
{montage.shots.map((shot) => (
<ShotRow key={shot.index} shot={shot} state={state} base={base} busy={busyShot === shot.index} disabled={working}
canGenerate={!!montage.voiceId && voiceOnline}
onGenerate={() => void generateOne(shot.index)} onPatch={patch} onUploaded={setState} onError={setError} />
))}
</ol>
{/* Resultado */}
<section aria-label="Vídeo montado" className="grid gap-4 rounded-card border border-line bg-surface p-5">
<h3 className="flex items-center gap-2 font-display text-[1.0625rem] font-semibold"><PlayIcon size={16} />Vídeo montado</h3>
<div className="grid gap-6 md:grid-cols-[minmax(0,15rem)_minmax(0,1fr)]">
<div className="relative aspect-[9/16] w-full overflow-hidden rounded-2xl border border-line-strong bg-sunken">
{latestOk?.mp4
? <video key={latestOk.mp4} controls className="size-full object-contain" src={fileUrl(latestOk.mp4)} />
: <div className="grid size-full place-items-center p-4 text-center text-xs leading-relaxed text-fg-subtle">Gere os áudios, escolha os visuais e clique em “Montar vídeo”.</div>}
</div>
<div className="grid content-start gap-3">
{latest && (
<div className="flex flex-wrap items-center gap-3">
<StatusBadge status={latest.status} />
<span className="text-xs text-fg-subtle">{formatDate(latest.started_at)}</span>
{latest.status === "running" && <Button size="sm" variant="danger" onClick={() => void cancelRender(latest.id)}><StopIcon size={14} />Cancelar</Button>}
{latestOk?.mp4 && <a className="text-sm font-medium text-accent hover:underline" href={fileUrl(latestOk.mp4)} download>Baixar MP4</a>}
</div>
)}
{latest?.error && <Feedback ok={false}>{latest.error}</Feedback>}
<p className="text-xs leading-relaxed text-fg-subtle">
Cada trecho dura o tempo da própria fala (mais uma pausa curta); no fim entra uma cartela com os créditos das imagens e as fontes do roteiro.
Vídeo vertical 1080×1920, 30 fps, H.264 + AAC.
</p>
</div>
</div>
</section>
</div>
);
}
/** "Sem visual: 1 2 3": cada número leva ao trecho. */
function MissingLine({ label, shots }: { label: string; shots: number[] }) {
return (
<p className="flex flex-wrap items-center gap-1.5 text-xs text-fg-muted">
<span className="mr-1 font-medium">{label}:</span>
{shots.map((n) => (
<a key={n} href={`#montagem-${n}`}
className="grid size-6 place-items-center rounded-full border border-warning/40 bg-surface font-semibold text-warning hover:bg-warning-soft">{n}</a>
))}
</p>
);
}
function ShotRow({ shot, state, base, busy, disabled, canGenerate, onGenerate, onPatch, onUploaded, onError }: {
shot: MontageShot; state: State; base: string; busy: boolean; disabled: boolean; canGenerate: boolean;
onGenerate: () => void; onPatch: (body: unknown) => Promise<void>; onUploaded: (s: State) => void; onError: (e: string | null) => void;
}) {
const [spoken, setSpoken] = useState(shot.spoken);
const saved = useRef(shot.spoken);
useEffect(() => { setSpoken(shot.spoken); saved.current = shot.spoken; }, [shot.spoken]);
const n = shot.index + 1;
const audioOk = !!shot.audio && !shot.audioStale;
const visualOk = shot.visual.kind === "card" || shot.visual.kind === "godot2d" || !!shot.visual.file;
function saveSpoken() {
if (spoken.trim() === saved.current.trim()) return;
saved.current = spoken;
void onPatch({ shot: { index: shot.index, spoken } });
}
return (
<li id={`montagem-${n}`} className="grid scroll-mt-24 gap-4 rounded-card border border-line bg-surface p-5 shadow-card">
<header className="flex flex-wrap items-center gap-x-3 gap-y-2">
<span className="grid size-8 place-items-center rounded-full border border-accent/40 bg-accent-soft font-display text-sm font-bold text-accent">{n}</span>
<span className="font-mono text-sm font-semibold text-fg">{shot.time} s</span>
{shot.onScreen && <span className="rounded-md bg-black/70 px-2 py-0.5 text-xs font-bold text-white ring-1 ring-white/10">{shot.onScreen}</span>}
<span className="ml-auto flex flex-wrap gap-2">
<Badge tone={audioOk ? "success" : shot.audioStale ? "warning" : "neutral"}>
{audioOk ? `áudio ${fmtSeconds(shot.audio!.durationMs)}` : shot.audioStale ? "áudio desatualizado" : "sem áudio"}
</Badge>
<Badge tone={visualOk ? "success" : "neutral"}>{shot.visual.kind === "godot2d" ? "cena 2D" : visualOk ? "visual ok" : "sem visual"}</Badge>
</span>
</header>
<div className="grid gap-6 lg:grid-cols-2">
{/* Voz */}
<div className="grid content-start gap-3">
<label className="grid gap-2">
<span className="flex items-center justify-between gap-2 text-eyebrow font-semibold text-fg-subtle uppercase">
<span className="flex items-center gap-1.5"><MicIcon size={13} />Texto falado</span>
{shot.spokenEdited && (
<button type="button" className="text-[0.6875rem] font-medium tracking-normal text-fg-muted normal-case hover:text-accent"
onClick={() => void onPatch({ shot: { index: shot.index, resetSpoken: true } })}>
Refazer a partir do roteiro
</button>
)}
</span>
<Textarea rows={3} value={spoken} disabled={disabled} onChange={(e) => setSpoken(e.target.value)} onBlur={saveSpoken}
className="bg-sunken/70 text-[0.9375rem] leading-relaxed" />
</label>
<p className="text-xs leading-relaxed text-fg-subtle">Números já por extenso para a voz ler bem. Ajuste a pronúncia aqui; a legenda usa o texto do roteiro.</p>
<div className="flex flex-wrap items-center gap-3">
<Button size="sm" variant={audioOk ? "ghost" : "secondary"} disabled={!canGenerate || disabled || spoken.trim() !== saved.current.trim()} onClick={onGenerate}>
{busy ? <><Spinner />Gerando…</> : audioOk ? <><RefreshIcon size={14} />Refazer áudio</> : <><WaveIcon size={14} />Gerar áudio</>}
</Button>
{shot.audio && <audio key={`${shot.audio.file}-${shot.audio.durationMs}`} controls preload="none" className="h-9 max-w-full" src={`${fileUrl(shot.audio.file)}&v=${shot.audio.durationMs}`} />}
</div>
</div>
{/* Visual */}
<VisualEditor shot={shot} state={state} base={base} disabled={disabled} onPatch={onPatch} onUploaded={onUploaded} onError={onError} />
</div>
</li>
);
}
function VisualEditor({ shot, state, base, disabled, onPatch, onUploaded, onError }: {
shot: MontageShot; state: State; base: string; disabled: boolean;
onPatch: (body: unknown) => Promise<void>; onUploaded: (s: State) => void; onError: (e: string | null) => void;
}) {
const [uploading, setUploading] = useState(false);
const fileInput = useRef<HTMLInputElement>(null);
const [meta, setMeta] = useState({ credit: shot.visual.credit, license: shot.visual.license, sourceUrl: shot.visual.sourceUrl });
useEffect(() => setMeta({ credit: shot.visual.credit, license: shot.visual.license, sourceUrl: shot.visual.sourceUrl }),
[shot.visual.credit, shot.visual.license, shot.visual.sourceUrl]);
const kind = shot.visual.kind;
const [regenerating, setRegenerating] = useState(false);
/** "Gerar de novo": outra variação da cena do Godot ou outra imagem da internet. */
async function regenerate() {
onError(null);
setRegenerating(true);
try {
const r = await fetch(`${base}/regenerate`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ index: shot.index }) });
const body = await r.json();
if (!r.ok) throw new Error(body.error ?? `Erro ${r.status}`);
onUploaded(await (await fetch(base)).json());
} catch (err) {
onError(`Trecho ${shot.index + 1}: ${(err as Error).message}`);
} finally {
setRegenerating(false);
}
}
const choices = kind === "image" ? state.options.images : kind === "video" ? state.options.videos : [];
const isVideo = kind === "video";
async function upload(file: File) {
onError(null);
setUploading(true);
try {
const form = new FormData();
form.set("file", file);
form.set("index", String(shot.index));
form.set("credit", meta.credit);
form.set("license", meta.license);
form.set("sourceUrl", meta.sourceUrl);
const r = await fetch(`${base}/upload`, { method: "POST", body: form });
const body = await r.json();
if (!r.ok) throw new Error(body.error ?? `Erro ${r.status}`);
onUploaded(await (await fetch(base)).json());
} catch (e) {
onError(`Trecho ${shot.index + 1}: ${(e as Error).message}`);
} finally {
setUploading(false);
if (fileInput.current) fileInput.current.value = "";
}
}
const saveMeta = () => {
if (meta.credit === shot.visual.credit && meta.license === shot.visual.license && meta.sourceUrl === shot.visual.sourceUrl) return;
void onPatch({ shot: { index: shot.index, visual: meta } });
};
return (
<div className="grid content-start gap-3">
<div className="flex items-center justify-between gap-2">
<span className="flex items-center gap-1.5 text-eyebrow font-semibold text-fg-subtle uppercase"><EyeIcon size={13} />Visual</span>
{(kind === "godot2d" || kind === "godot3d" || kind === "image") && (
<Button size="sm" variant="ghost" disabled={disabled || regenerating} onClick={() => void regenerate()}
title={kind === "image" ? "Busca outra imagem na internet (sem repetir as dos outros trechos)" : "Outra variação de layout, câmera e cores, renderizada no Godot"}>
{regenerating ? <><Spinner />{kind === "image" ? "Buscando…" : "Renderizando…"}</> : <><RefreshIcon size={14} />{kind === "image" && !shot.visual.file ? "Buscar na internet" : "Gerar de novo"}</>}
</Button>
)}
</div>
{/* Estilo do trecho: pode misturar no mesmo vídeo */}
<div role="radiogroup" aria-label={`Estilo do visual do trecho ${shot.index + 1}`} className="grid grid-cols-3 gap-1.5 sm:grid-cols-5">
{state.kinds.map((k) => (
<button key={k.id} type="button" role="radio" aria-checked={kind === k.id} disabled={!k.available || disabled} title={k.hint}
onClick={() => void onPatch({ shot: { index: shot.index, visual: { kind: k.id, file: null } } })}
className={cx("h-8 w-full truncate rounded-control border px-2 text-xs font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-45",
kind === k.id ? "border-accent/60 bg-accent-soft text-accent" : "border-line-strong bg-raised text-fg-muted hover:text-fg")}>
{k.label}{!k.available && " · em breve"}
</button>
))}
</div>
{shot.visualHint && <p className="text-xs leading-relaxed text-fg-subtle"><span className="font-medium text-fg-muted">O roteiro pede:</span> {shot.visualHint}</p>}
{kind === "godot2d" || kind === "godot3d" ? (
<SceneEditor shot={shot} state={state} base={base} disabled={disabled} onPatch={onPatch} onUploaded={onUploaded} onError={onError} />
) : kind === "card" ? (
<div className="grid h-28 place-items-center rounded-control border border-line bg-[#0d0d10] px-4 text-center font-display text-lg font-bold text-white">
{shot.onScreen || <span className="text-sm font-normal text-fg-subtle">Sem texto na tela neste trecho</span>}
</div>
) : (
<div className="grid gap-3 sm:grid-cols-[6.5rem_minmax(0,1fr)]">
<div className="relative aspect-[9/16] w-full overflow-hidden rounded-lg border border-line-strong bg-sunken">
{shot.visual.file
? isVideo
? <video key={shot.visual.file} muted playsInline preload="metadata" className="size-full object-cover" src={fileUrl(shot.visual.file)} />
: <img src={fileUrl(shot.visual.file)} alt={`Visual do trecho ${shot.index + 1}`} className="size-full object-cover" />
: <span className="grid size-full place-items-center text-[0.6875rem] text-fg-subtle">vazio</span>}
</div>
<div className="grid content-start gap-2">
{choices.length > 0 && (
<Select value={shot.visual.file ?? ""} disabled={disabled} aria-label="Escolher um arquivo já existente"
onChange={(e) => void onPatch({ shot: { index: shot.index, visual: { file: e.target.value || null } } })}>
<option value="">Escolher dos assets…</option>
{choices.map((c) => <option key={c.file} value={c.file}>{c.name}</option>)}
</Select>
)}
{(
<>
<div className="grid gap-2 sm:grid-cols-2">
<Input placeholder="Licença (opcional)" value={meta.license} disabled={disabled} onBlur={saveMeta}
onChange={(e) => setMeta({ ...meta, license: e.target.value })} aria-label="Licença" />
<Input placeholder="Crédito (autor / banco)" value={meta.credit} disabled={disabled} onBlur={saveMeta}
onChange={(e) => setMeta({ ...meta, credit: e.target.value })} aria-label="Crédito" />
</div>
<Input placeholder="Link da fonte (https://…)" value={meta.sourceUrl} disabled={disabled} onBlur={saveMeta}
onChange={(e) => setMeta({ ...meta, sourceUrl: e.target.value })} aria-label="Link da fonte" />
<input ref={fileInput} type="file" className="sr-only" accept={kind === "video" ? "video/mp4,video/quicktime,video/webm" : "image/png,image/jpeg,image/webp"}
onChange={(e) => { const f = e.target.files?.[0]; if (f) void upload(f); }} />
<Button size="sm" variant="secondary" className="w-fit" disabled={disabled || uploading} onClick={() => fileInput.current?.click()}>
{uploading ? <><Spinner />Enviando…</> : <><UploadIcon size={14} />{shot.visual.file ? "Trocar arquivo" : kind === "video" ? "Enviar clipe" : "Enviar imagem"}</>}
</Button>
</>
)}
{shot.visual.file && (shot.visual.sourceUrl
? <a href={shot.visual.sourceUrl} target="_blank" rel="noopener noreferrer" className="flex items-center gap-1.5 truncate text-[0.6875rem] text-fg-subtle hover:text-accent"><CheckIcon size={12} /><span className="truncate">{shot.visual.credit || "fonte"} · ver origem</span></a>
: <p className="flex items-center gap-1.5 truncate text-[0.6875rem] text-fg-subtle"><CheckIcon size={12} /><span className="truncate">{shot.visual.file}</span></p>)}
</div>
</div>
)}
</div>
);
}
/**
* Cena do Godot de um trecho: 2D (título, infográfico, mapa) ou 3D (cena da biblioteca, com o
* formulário vindo do manifesto). Mostra a prévia renderizada e o pedido de cena nova ao agente.
*/
function SceneEditor({ shot, state, base, disabled, onPatch, onUploaded, onError }: {
shot: MontageShot; state: State; base: string; disabled: boolean;
onPatch: (body: unknown) => Promise<void>; onUploaded: (s: State) => void; onError: (e: string | null) => void;
}) {
const is3d = shot.visual.kind === "godot3d";
const scene = shot.visual.scene ?? { kind: is3d ? "doc3d" as const : "doc2d" as const, template: "title" as Template, params: {} };
const p = scene.params as Record<string, unknown>;
const [rendering, setRendering] = useState(false);
const str = (v: unknown) => (v === undefined || v === null ? "" : String(v));
const setScene = (template: string, params: Record<string, unknown>) =>
void onPatch({ shot: { index: shot.index, visual: { scene: { kind: is3d ? "doc3d" : "doc2d", template, params } } } });
const setParams = (next: Record<string, unknown>) => setScene(scene.template, { ...p, ...next });
const markers = Array.isArray(p.markers) ? (p.markers as { label?: string }[]).map((m) => m.label ?? "").filter(Boolean) : [];
const route = (p.route ?? null) as { from?: string; to?: string; label?: string } | null;
const library3d = state.library.filter((l) => l.kind === "doc3d");
const current3d = library3d.find((l) => l.id === scene.template);
async function renderNow() {
onError(null);
setRendering(true);
try {
const r = await fetch(`${base}/scene`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ index: shot.index }) });
const body = await r.json();
if (!r.ok) throw new Error(body.error ?? `Erro ${r.status}`);
onUploaded(await (await fetch(base)).json());
} catch (e) {
onError(`Trecho ${shot.index + 1}: ${(e as Error).message}`);
} finally {
setRendering(false);
}
}
// Campos de texto salvam ao sair do campo (não a cada tecla).
const field = (label: string, value: string, onSave: (v: string) => void, placeholder = "") => (
<label className="grid gap-1">
<span className="text-[0.6875rem] font-medium text-fg-subtle">{label}</span>
<Input key={`${shot.index}-${label}-${value}`} defaultValue={value} placeholder={placeholder} disabled={disabled}
onBlur={(e) => { if (e.target.value !== value) onSave(e.target.value); }} />
</label>
);
const pill = (active: boolean) => cx("h-7 w-full truncate rounded-control border px-2 text-[0.6875rem] font-medium transition-colors",
active ? "border-info/50 bg-info-soft text-info" : "border-line-strong bg-raised text-fg-muted hover:text-fg");
const agentHref = `/agent?kind=godot&story=${encodeURIComponent(state.storyId)}&prompt=${encodeURIComponent(
`Crie uma cena 3D nova na biblioteca do Godot para este trecho do vídeo: ${shot.visualHint || shot.onScreen}`)}`;
return (
<div className="grid gap-3 sm:grid-cols-[6.5rem_minmax(0,1fr)]">
<div className="relative aspect-[9/16] w-full overflow-hidden rounded-lg border border-line-strong bg-sunken">
{shot.visual.file
? <video key={shot.visual.file} muted playsInline loop autoPlay preload="metadata" className="size-full object-cover" src={fileUrl(shot.visual.file)} />
: <span className="grid size-full place-items-center p-2 text-center text-[0.6875rem] leading-snug text-fg-subtle">renderiza ao gerar o vídeo</span>}
</div>
<div className="grid content-start gap-2.5">
{is3d ? (
<>
<label className="grid gap-1">
<span className="text-[0.6875rem] font-medium text-fg-subtle">Cena da biblioteca</span>
<Select value={scene.template} disabled={disabled}
onChange={(e) => { const lib = library3d.find((l) => l.id === e.target.value); setScene(e.target.value, Object.fromEntries((lib?.params ?? []).filter((x) => x.default !== undefined).map((x) => [x.name, x.default]))); }}>
{library3d.map((l) => <option key={l.id} value={l.id}>{l.label}</option>)}
</Select>
</label>
{current3d?.description && <p className="text-[0.6875rem] leading-relaxed text-fg-subtle">{current3d.description}</p>}
{current3d?.params.map((param) => param.type === "select" ? (
<div key={param.name} className="grid gap-1">
<span className="text-[0.6875rem] font-medium text-fg-subtle">{param.label}</span>
<div role="radiogroup" aria-label={param.label} className="grid grid-cols-2 gap-1.5">
{param.options?.map((o) => (
<button key={o.value} type="button" role="radio" aria-checked={str(p[param.name] ?? param.default) === o.value} disabled={disabled}
onClick={() => setParams({ [param.name]: o.value })} className={pill(str(p[param.name] ?? param.default) === o.value)}>{o.label}</button>
))}
</div>
</div>
) : param.type === "bool" ? (
<Switch key={param.name} label={param.label} checked={Boolean(p[param.name] ?? param.default)} onChange={(v) => setParams({ [param.name]: v })} />
) : (
<div key={param.name}>{field(param.label, str(p[param.name] ?? param.default), (v) => setParams({ [param.name]: param.type === "number" ? Number(v.replace(",", ".")) : v }))}</div>
))}
<InsetCard shot={shot} base={base} disabled={disabled} onUploaded={onUploaded} onError={onError} />
<a href={agentHref} className="text-[0.6875rem] font-medium text-accent hover:underline">
Não tem a cena que você quer? Peça uma nova ao agente (ela fica na biblioteca) →
</a>
</>
) : (
<>
<div className="grid grid-cols-3 gap-1.5" role="radiogroup" aria-label="Modelo da cena 2D">
{state.templates.map((t) => (
<button key={t.id} type="button" role="radio" aria-checked={scene.template === t.id} disabled={disabled}
onClick={() => setScene(t.id, t.id === scene.template ? p : {})} className={pill(scene.template === t.id)}>
{t.label}
</button>
))}
</div>
{scene.template === "title" && <>
{field("Título", str(p.title), (v) => setParams({ title: v }))}
{field("Linha de cima (opcional)", str(p.kicker), (v) => setParams({ kicker: v }))}
{field("Subtítulo (opcional)", str(p.subtitle), (v) => setParams({ subtitle: v }))}
</>}
{scene.template === "counter" && <>
<div className="grid grid-cols-[6rem_minmax(0,1fr)] gap-2">
{field("Número", str(p.value), (v) => { const n = Number(v.replace(/\./g, "").replace(",", ".")); if (Number.isFinite(n)) setParams({ value: n }); })}
{field("Rótulo", str(p.label), (v) => setParams({ label: v }), "jararacas por hectare")}
</div>
{field("Linha de cima (opcional)", str(p.kicker), (v) => setParams({ kicker: v }), "Há cerca de")}
{field("Nota (opcional)", str(p.note), (v) => setParams({ note: v }))}
</>}
{scene.template === "map" && <>
{field("Título do mapa", str(p.title), (v) => setParams({ title: v }))}
{field("Lugares (separados por vírgula)", markers.join(", "),
(v) => setParams({ markers: v.split(",").map((x) => x.trim()).filter(Boolean).map((label) => ({ label })) }), "Itanhaém, Ilha da Queimada Grande")}
<div className="grid grid-cols-2 gap-2">
{field("Linha de", str(route?.from), (v) => setParams({ route: v ? { ...route, from: v } : null }), "Itanhaém")}
{field("até", str(route?.to), (v) => setParams({ route: route ? { ...route, to: v } : null }), "Ilha da Queimada Grande")}
</div>
<p className="text-[0.6875rem] leading-relaxed text-fg-subtle">Lugares conhecidos: litoral de SP (Santos, Itanhaém, Peruíbe, ilhas da Queimada…). Mapa ilustrativo.</p>
</>}
</>
)}
<div className="flex flex-wrap items-center gap-2">
<Button size="sm" variant="secondary" disabled={disabled || rendering || !shot.audio || shot.audioStale} onClick={() => void renderNow()}
title={!shot.audio || shot.audioStale ? "Gere o áudio primeiro: a cena dura o tempo da fala" : undefined}>
{rendering ? <><Spinner />Renderizando no Godot…</> : <><PlayIcon size={14} />Prévia da cena</>}
</Button>
<span className="text-[0.6875rem] text-fg-subtle">A cena é refeita sozinha se a fala ou os campos mudarem.</span>
</div>
</div>
</div>
);
}
/** Cartão de foto por cima da cena 3D (ex.: a foto real da cobra): ver, trocar, pôr ou tirar. */
function InsetCard({ shot, base, disabled, onUploaded, onError }: {
shot: MontageShot; base: string; disabled: boolean; onUploaded: (s: State) => void; onError: (e: string | null) => void;
}) {
const [busy, setBusy] = useState(false);
const inset = shot.visual.inset;
async function run(target: "inset" | "remove-inset") {
onError(null);
setBusy(true);
try {
const r = await fetch(`${base}/regenerate`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ index: shot.index, target }) });
const body = await r.json();
if (!r.ok) throw new Error(body.error ?? `Erro ${r.status}`);
onUploaded(await (await fetch(base)).json());
} catch (e) {
onError(`Trecho ${shot.index + 1}: ${(e as Error).message}`);
} finally {
setBusy(false);
}
}
return (
<div className="grid gap-2 rounded-control border border-line bg-sunken/50 p-2.5">
<span className="text-[0.6875rem] font-medium text-fg-subtle">Cartão de foto por cima da cena</span>
{inset ? (
<div className="flex items-center gap-3">
<img src={fileUrl(inset.file)} alt={`Foto do cartão do trecho ${shot.index + 1}`} className="h-14 w-20 shrink-0 rounded border-2 border-white object-cover" />
<a href={inset.sourceUrl || "#"} target="_blank" rel="noopener noreferrer" className="min-w-0 truncate text-[0.6875rem] text-fg-subtle hover:text-accent">Foto: {inset.credit || "—"}</a>
<span className="ml-auto flex gap-1">
<Button size="sm" variant="ghost" disabled={disabled || busy} onClick={() => void run("inset")}>{busy ? <Spinner /> : <RefreshIcon size={13} />}Outra foto</Button>
<Button size="sm" variant="ghost" disabled={disabled || busy} onClick={() => void run("remove-inset")}>Tirar</Button>
</span>
</div>
) : (
<Button size="sm" variant="ghost" className="w-fit" disabled={disabled || busy} onClick={() => void run("inset")}>
{busy ? <><Spinner />Buscando…</> : <><UploadIcon size={13} />Pôr foto da internet</>}
</Button>
)}
</div>
);
}
+10
View File
@@ -0,0 +1,10 @@
// Redes sociais suportadas pelas contas vinculadas: nome e ícone de cada uma, num lugar só.
import type { ComponentType } from "react";
import type { Platform } from "@/lib/types";
import { InstagramIcon, TikTokIcon, YouTubeIcon } from "./icons";
export const PLATFORM_META: Record<Platform, { label: string; icon: ComponentType<{ size?: number; className?: string }> }> = {
tiktok: { label: "TikTok", icon: TikTokIcon },
instagram: { label: "Instagram", icon: InstagramIcon },
youtube: { label: "YouTube", icon: YouTubeIcon },
};
+605
View File
@@ -0,0 +1,605 @@
"use client";
// Página Publicações: a fila de envio para as redes, em abas por etapa (aguardando aprovação, agendadas,
// publicando, publicadas, com problema). Cada vídeo vira um cartão com uma linha por rede, e cada linha tem o
// estado em texto, o horário, o progresso e as ações da etapa.
// Atualiza sozinha: a cada 3 s enquanto algo está publicando ou na fila; senão a cada 30 s (e só com a aba
// do navegador visível). Acima das abas, avisos fixos se o Publicador estiver fora ou a publicação pausada.
import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
import type { AccountView } from "@/lib/accounts";
import type { Platform } from "@/lib/types";
import { apiCall } from "./api-client";
import { askConfirm } from "./confirm-dialog";
import { ConnectWizard } from "./connect-wizard";
import { Dialog } from "./dialog";
import {
AlertIcon, CalendarIcon, CheckIcon, ClockIcon, FilmIcon, LinkIcon, PublishIcon, RefreshIcon, ScissorsIcon, UndoIcon, XIcon,
} from "./icons";
import { PLATFORM_META } from "./platforms";
import {
formatTime, getPublisherStatus, getSettings, getSummary, listJobs, markJobPublished, markJobRemoved, patchJob, publishClip, putSettings, readNetwork, runJobAction,
type JobAction, type PublisherStatus, type PublishJob, type PublishJobAction, type PublishJobStatus, type PublishingNetwork, type PublishingSummary,
} from "./publishing-client";
import { JobStatusBadge, NoticeBar, PlatformName, TextLink } from "./publishing-ui";
import { Tabs } from "./tabs";
import { Button, EmptyState, Feedback, Field, Input, ProgressBar, Spinner, fileUrl } from "./ui";
const POLL_BUSY_MS = 3000;
const POLL_IDLE_MS = 30_000;
const PUBLISHED_SHOWN = 60;
const PLATFORM_ORDER: Platform[] = ["youtube", "tiktok", "instagram"];
type TabId = "aprovar" | "agendadas" | "publicando" | "publicadas" | "problemas";
const TABS: { id: TabId; label: string; statuses: PublishJobStatus[]; icon: ReactNode; empty: { title: string; text: ReactNode } }[] = [
{
id: "aprovar", label: "Aguardando aprovação", statuses: ["awaiting_approval"], icon: <CheckIcon size={16} />,
empty: {
title: "Nada esperando você",
text: <>Quando um corte novo ficar pronto no Clipador, ele aparece aqui para você liberar. Canais com “Aprovar sozinho” ligado pulam esta etapa, e episódios são aprovados na página do episódio.</>,
},
},
{
id: "agendadas", label: "Agendadas", statuses: ["scheduled"], icon: <CalendarIcon size={16} />,
empty: { title: "Nenhuma publicação agendada", text: "Vídeos aprovados esperam aqui o próximo horário bom da rede. Os horários ficam em Configurações." },
},
{
id: "publicando", label: "Publicando", statuses: ["queued", "publishing"], icon: <PublishIcon size={16} />,
empty: { title: "Nada sendo enviado agora", text: "Quando chegar a hora de um vídeo, ele aparece aqui com o progresso do envio." },
},
{
id: "publicadas", label: "Publicadas", statuses: ["published"], icon: <LinkIcon size={16} />,
empty: { title: "Nenhuma publicação ainda", text: "Cada vídeo que sair numa rede aparece aqui com o link para abrir." },
},
{
id: "problemas", label: "Com problema", statuses: ["failed", "needs_login"], icon: <AlertIcon size={16} />,
empty: { title: "Tudo certo", text: "Se um envio falhar ou uma rede pedir para entrar de novo, ele aparece aqui com o que fazer." },
},
];
type Group = { key: string; jobs: PublishJob[]; head: PublishJob };
/** Junta as redes do mesmo vídeo (mesma origem e canal) num cartão só. */
function groupJobs(jobs: PublishJob[]): Group[] {
const map = new Map<string, PublishJob[]>();
for (const j of jobs) {
const key = `${j.accountId}|${j.sourceKind}|${j.sourceId}`;
map.set(key, [...(map.get(key) ?? []), j]);
}
return [...map.entries()].map(([key, list]) => ({ key, jobs: list, head: list[0] }));
}
function sortFor(tab: TabId, jobs: PublishJob[]): PublishJob[] {
const time = (iso: string | null) => (iso ? new Date(iso).getTime() : 0);
const copy = [...jobs];
if (tab === "agendadas") copy.sort((a, b) => time(a.scheduledAt) - time(b.scheduledAt));
else if (tab === "aprovar") copy.sort((a, b) => time(a.createdAt) - time(b.createdAt));
else copy.sort((a, b) => time(b.updatedAt) - time(a.updatedAt));
return tab === "publicadas" ? copy.slice(0, PUBLISHED_SHOWN) : copy;
}
export function PublishingBoard() {
const [jobs, setJobs] = useState<PublishJob[] | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [publisher, setPublisher] = useState<PublisherStatus | null>(null);
const [paused, setPaused] = useState<boolean | null>(null);
const [dispatcher, setDispatcher] = useState<PublishingSummary["dispatcher"] | null>(null);
const [timezone, setTimezone] = useState("America/Sao_Paulo");
const [refreshing, setRefreshing] = useState(false);
const [resumeBusy, setResumeBusy] = useState(false);
const [notice, setNotice] = useState<{ ok: boolean; text: string } | null>(null);
const [reschedule, setReschedule] = useState<PublishJob | null>(null);
const [reconnect, setReconnect] = useState<{ job: PublishJob; network: PublishingNetwork; accountName: string } | null>(null);
const [markJob, setMarkJob] = useState<PublishJob | null>(null);
const [accounts, setAccounts] = useState<AccountView[] | null>(null);
const load = useCallback(async (withStatus = false) => {
setRefreshing(true);
const [list, status, settings, summary, accountList] = await Promise.all([
// Canceladas não aparecem em nenhuma aba.
listJobs({ status: ["awaiting_approval", "scheduled", "queued", "publishing", "published", "failed", "needs_login"], limit: 500 }),
withStatus ? getPublisherStatus() : Promise.resolve(null),
withStatus ? getSettings() : Promise.resolve(null),
withStatus ? getSummary() : Promise.resolve(null),
// Redes de cada canal: para oferecer "Publicar no <rede>" onde o corte ainda não saiu.
withStatus ? apiCall<AccountView[]>("/api/accounts") : Promise.resolve(null),
]);
setRefreshing(false);
if (list.ok) { setJobs(list.data); setLoadError(null); } else setLoadError(list.error);
if (status) setPublisher(status);
if (settings?.ok) { setPaused(settings.data.publishingPaused); setTimezone(settings.data.timezone); }
if (summary?.ok) setDispatcher(summary.data.dispatcher);
if (accountList?.ok) setAccounts(accountList.data);
}, []);
useEffect(() => { void load(true); }, [load]);
// Atualiza rápido só quando algo está de fato saindo: enviando, ou na fila sem estar parado esperando
// (pausa, rede desconectada, Publicador fora — o `step` desses começa com "Esperando").
const busy = jobs?.some((j) => j.status === "publishing" || (j.status === "queued" && !j.step.startsWith("Esperando"))) ?? false;
useEffect(() => {
let ticks = 0;
const timer = setInterval(() => {
if (document.visibilityState === "hidden") return;
ticks += 1;
// O estado do Publicador e a pausa mudam pouco: relê a cada ~30 s.
void load(!busy || ticks % 10 === 0);
}, busy ? POLL_BUSY_MS : POLL_IDLE_MS);
return () => clearInterval(timer);
}, [busy, load]);
const byTab = useMemo(() => {
const out = {} as Record<TabId, PublishJob[]>;
for (const t of TABS) out[t.id] = sortFor(t.id, (jobs ?? []).filter((j) => t.statuses.includes(j.status)));
return out;
}, [jobs]);
async function act(job: PublishJob, action: JobAction) {
const label = PLATFORM_META[job.platform].label;
if (action === "cancel") {
// Cancelar um job tira só aquela rede do vídeo; as outras seguem.
const ok = await askConfirm({
title: job.status === "awaiting_approval" ? `Tirar o ${label} deste vídeo?` : `Cancelar a publicação no ${label}?`,
message: "Só esta rede deixa de receber o vídeo. As outras redes do mesmo vídeo continuam como estão.",
confirmLabel: job.status === "awaiting_approval" ? "Tirar esta rede" : "Cancelar publicação", cancelLabel: "Voltar", tone: "danger",
});
if (!ok) return false;
}
let confirmRetry = false;
if (action === "retry" && job.mayBeLive) {
// O envio anterior chegou ao Publicador e falhou no meio: o vídeo pode já estar na rede.
const ok = await askConfirm({
title: `O vídeo pode já estar no ${label}`,
message: "Confira na rede se o vídeo já saiu antes de tentar de novo. Se ele já estiver lá, tentar de novo publica uma segunda vez.",
confirmLabel: "Já conferi, tentar de novo", cancelLabel: "Voltar", tone: "danger",
});
if (!ok) return false;
confirmRetry = true;
}
const r = confirmRetry
? await apiCall<PublishJob>(`/api/publishing/jobs/${job.id}/retry`, "POST", { confirm: true })
: await runJobAction(job.id, action);
const done: Record<JobAction, string> = {
// Aprovar vale para o vídeo inteiro: todas as redes que estavam aguardando.
approve: "Vídeo aprovado: vai para todas as redes que estavam aguardando.",
"publish-now": `${label}: vai sair agora.`,
retry: `${label}: tentando de novo.`,
cancel: `${label}: publicação cancelada.`,
};
setNotice(r.ok ? { ok: true, text: done[action] } : { ok: false, text: r.error });
await load();
return r.ok;
}
/** "Apaguei na rede": confirma e libera a rede para publicar de novo. O painel não apaga nada na rede. */
async function markRemoved(job: PublishJob) {
const label = PLATFORM_META[job.platform].label;
const ok = await askConfirm({
title: `Você apagou o vídeo no ${label}?`,
message: `Apague primeiro direto no ${label} (o painel não apaga nada lá). Confirmando, esta rede deixa de contar como publicada e fica livre: use “Publicar” no corte para mandar de novo.`,
confirmLabel: "Já apaguei, liberar", cancelLabel: "Voltar", tone: "danger",
});
if (!ok) return;
const r = await markJobRemoved(job.id);
setNotice(r.ok ? { ok: true, text: `${label}: liberado para publicar de novo.` } : { ok: false, text: r.error });
await load();
}
/** Redes conectadas e ligadas do canal onde este corte ainda não tem publicação (nem na fila). Só cortes. */
const missingFor = useCallback((head: PublishJob): Platform[] => {
if (head.sourceKind !== "clip" || !jobs || !accounts) return [];
const account = accounts.find((a) => a.id === head.accountId);
if (!account) return [];
// A lista não traz canceladas: cancelada ou "Apaguei na rede" conta como livre.
const taken = new Set(jobs.filter((j) => j.accountId === head.accountId && j.sourceKind === "clip" && j.sourceId === head.sourceId)
.map((j) => j.platform));
return PLATFORM_ORDER.filter((p) => !taken.has(p)
&& account.networks.some((n) => n.platform === p && n.status !== "disconnected" && n.enabled === 1));
}, [jobs, accounts]);
/** "Publicar no <rede>": manda o corte só para essa rede, no horário do canal (agora ou próximo horário bom). */
async function publishMore(head: PublishJob, platform: Platform) {
const label = PLATFORM_META[platform].label;
const now = accounts?.find((a) => a.id === head.accountId)?.timing === "now";
const ok = await askConfirm({
title: `Publicar este corte no ${label}?`,
message: `Vai com o mesmo título e legenda das outras redes e sai ${now ? "agora (no próximo ciclo, até 20 s)" : "no próximo horário bom do canal"}. Clicar já é a sua aprovação.`,
confirmLabel: `Publicar no ${label}`, cancelLabel: "Voltar",
});
if (!ok) return;
const r = await publishClip(Number(head.sourceId), { accountId: head.accountId, platforms: [platform], timing: now ? "now" : "best_slot" });
if (!r.ok) setNotice({ ok: false, text: r.error });
else if (r.data.placed === 0) setNotice({ ok: false, text: `${label}: não entrou na fila — ${r.data.skipped.map((s) => s.reason).join("; ") || "motivo desconhecido"}.` });
else setNotice({ ok: true, text: now ? `${label}: na fila para sair agora.` : `${label}: agendado no próximo horário bom (veja em Agendadas).` });
await load();
}
async function openReconnect(job: PublishJob) {
const r = await apiCall<AccountView>(`/api/accounts/${encodeURIComponent(job.accountId)}`);
if (!r.ok) { setNotice({ ok: false, text: r.error }); return; }
const row = r.data.networks.find((n) => n.platform === job.platform);
setReconnect({ job, network: readNetwork(row, job.platform), accountName: r.data.name || job.accountName });
}
async function resume() {
setResumeBusy(true);
const r = await putSettings({ publishingPaused: false });
setResumeBusy(false);
if (r.ok) setPaused(false);
setNotice(r.ok ? { ok: true, text: "Publicação retomada." } : { ok: false, text: r.error });
}
return (
<div className="grid gap-6">
<div className="grid gap-3">
{publisher && !publisher.online && (
<NoticeBar tone="danger" title="O Publicador está desligado: nada é enviado agora"
action={<Button variant="secondary" size="sm" onClick={() => void load(true)} disabled={refreshing}>
{refreshing ? <Spinner className="size-3.5" /> : <RefreshIcon size={15} />}Conferir de novo
</Button>}>
O Publicador é o programa que envia os vídeos para as redes. Ele liga junto com o CenaForge (<code>pnpm dev</code>).
Os vídeos continuam na fila e saem quando ele voltar.{publisher.reason && !publisher.reason.includes("pnpm dev") && <> Detalhe: {publisher.reason}</>}
</NoticeBar>
)}
{dispatcher && !dispatcher.running && (
<NoticeBar tone="warning" title="O agendador do painel está parado">
É ele que manda os vídeos para o Publicador na hora certa. Recarregue a página; se continuar, reinicie o painel.
{dispatcher.lastError && <> Último erro: {dispatcher.lastError}</>}
</NoticeBar>
)}
{paused && (
<NoticeBar tone="warning" title="Publicação pausada"
action={<Button size="sm" onClick={() => void resume()} disabled={resumeBusy}>
{resumeBusy ? <Spinner className="size-3.5" /> : <PublishIcon size={15} />}Retomar
</Button>}>
Nada sai para as redes até você retomar. Dá para aprovar e agendar normalmente. A pausa também fica em <TextLink href="/settings">Configurações</TextLink>.
</NoticeBar>
)}
</div>
<div aria-live="polite" className="empty:hidden">
{notice && <Feedback ok={notice.ok}>{notice.text}</Feedback>}
</div>
{loadError && (
<div className="grid justify-items-start gap-3">
<Feedback ok={false}>Não deu para ler a fila de publicações: {loadError}</Feedback>
<Button variant="secondary" size="sm" onClick={() => void load(true)}><RefreshIcon size={15} />Tentar de novo</Button>
</div>
)}
{jobs === null && !loadError ? (
<p role="status" className="flex items-center gap-2 text-sm text-fg-muted"><Spinner />Carregando publicações…</p>
) : jobs !== null && (
<Tabs<TabId> label="Etapas da publicação"
items={TABS.map((t) => ({ id: t.id, label: t.label, icon: t.icon, count: byTab[t.id].length }))}
panels={Object.fromEntries(TABS.map((t) => [t.id, (
<JobList key={t.id} tab={t.id} jobs={byTab[t.id]} empty={t.empty} total={jobs.filter((j) => t.statuses.includes(j.status)).length}
onAction={act} onReschedule={setReschedule} onReconnect={(j) => void openReconnect(j)} onMarkPublished={setMarkJob} onMarkRemoved={(j) => void markRemoved(j)}
missingFor={missingFor} onPublishMore={publishMore} />
)])) as Record<TabId, ReactNode>} />
)}
<p className="text-xs leading-relaxed text-fg-subtle">
O painel precisa ficar aberto para publicar e agendar. {refreshing ? "Atualizando…" : busy ? "Atualiza sozinho a cada 3 segundos enquanto algo é enviado." : "Atualiza sozinho a cada 30 segundos."}
</p>
{reschedule && (
<RescheduleDialog job={reschedule} timezone={timezone} onClose={() => setReschedule(null)}
onSaved={(text) => { setReschedule(null); setNotice({ ok: true, text }); void load(); }} />
)}
{markJob && (
<MarkPublishedDialog job={markJob} onClose={() => setMarkJob(null)}
onSaved={(text) => { setMarkJob(null); setNotice({ ok: true, text }); void load(); }} />
)}
{reconnect && (
<ConnectWizard accountId={reconnect.job.accountId} accountName={reconnect.accountName} platform={reconnect.job.platform}
network={reconnect.network} reconnect={reconnect.network.mode !== null}
onClose={() => { setReconnect(null); void load(); }} onChanged={() => void load()} />
)}
</div>
);
}
/* ---------- Lista e cartão ---------- */
type Handlers = {
onAction: (job: PublishJob, action: JobAction) => Promise<boolean>;
onReschedule: (job: PublishJob) => void;
onReconnect: (job: PublishJob) => void;
onMarkPublished: (job: PublishJob) => void;
onMarkRemoved: (job: PublishJob) => void;
missingFor: (head: PublishJob) => Platform[];
onPublishMore: (head: PublishJob, platform: Platform) => Promise<void>;
};
type RowHandlers = Omit<Handlers, "missingFor" | "onPublishMore">;
function JobList({ tab, jobs, empty, total, ...handlers }: Handlers & {
tab: TabId; jobs: PublishJob[]; total: number; empty: { title: string; text: ReactNode };
}) {
if (jobs.length === 0) {
return <EmptyState icon={<PublishIcon />} title={empty.title}>{empty.text}</EmptyState>;
}
const groups = groupJobs(jobs);
return (
<div className="grid gap-4">
<ul className="grid gap-4">
{groups.map((g) => <li key={g.key}><JobGroup tab={tab} group={g} {...handlers} /></li>)}
</ul>
{tab === "publicadas" && total > jobs.length && (
<p className="text-xs text-fg-subtle">Mostrando as {jobs.length} mais recentes de {total}.</p>
)}
</div>
);
}
function JobGroup({ tab, group, onAction, onReschedule, onReconnect, onMarkPublished, onMarkRemoved, missingFor, onPublishMore }: Handlers & { tab: TabId; group: Group }) {
const { head, jobs } = group;
const [approving, setApproving] = useState(false);
const [sending, setSending] = useState<Platform | null>(null);
const missing = missingFor(head);
// Aprovar um job aprova o vídeo inteiro (todas as redes aguardando): um botão por vídeo, não por rede.
const approvable = jobs.find((j) => j.status === "awaiting_approval" && j.actions.includes("approve"));
const awaitingCount = jobs.filter((j) => j.status === "awaiting_approval").length;
const title = head.title || head.caption.split("\n")[0] || (head.sourceKind === "clip" ? `Corte ${head.sourceId}` : `Episódio ${head.sourceId}`);
const SourceIcon = head.sourceKind === "clip" ? ScissorsIcon : FilmIcon;
async function approve() {
if (!approvable) return;
setApproving(true);
await onAction(approvable, "approve");
setApproving(false);
}
return (
<article aria-label={title} className="grid gap-4 rounded-card border border-line bg-surface p-4 shadow-card sm:grid-cols-[5.5rem_minmax(0,1fr)]">
<Cover job={head} />
<div className="grid min-w-0 content-start gap-3">
<header className="flex flex-wrap items-start justify-between gap-x-4 gap-y-2">
<div className="grid min-w-0 gap-1">
<h3 className="line-clamp-2 text-[0.9375rem] leading-snug font-semibold text-fg">{title}</h3>
<p className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-fg-muted">
<span className="inline-flex items-center gap-1.5"><SourceIcon size={13} className="text-fg-subtle" />
{head.sourceKind === "clip" ? "Corte do Clipador" : "Episódio"}{head.sourceLabel && <> · {head.sourceLabel}</>}
</span>
<span>Canal <TextLink href={`/accounts?account=${encodeURIComponent(head.accountId)}`}>{head.accountName || head.accountId}</TextLink></span>
</p>
</div>
{tab === "aprovar" && approvable && (
<Button onClick={() => void approve()} disabled={approving}>
{approving ? <Spinner /> : <CheckIcon size={16} />}
{awaitingCount > 1 ? `Aprovar vídeo (${awaitingCount} redes)` : "Aprovar vídeo"}
</Button>
)}
</header>
{head.caption && (
<details className="rounded-control border border-line bg-sunken/30 px-3 py-2 text-[0.8125rem]">
<summary className="cursor-pointer text-fg-muted select-none hover:text-fg">Legenda</summary>
<p className="mt-2 leading-relaxed whitespace-pre-line text-fg-muted">{head.caption}</p>
</details>
)}
<ul className="grid divide-y divide-line rounded-control border border-line">
{jobs.map((j) => <li key={j.id}><JobRow job={j} onAction={onAction} onReschedule={onReschedule} onReconnect={onReconnect} onMarkPublished={onMarkPublished} onMarkRemoved={onMarkRemoved} /></li>)}
</ul>
{missing.length > 0 && (
<div className="flex flex-wrap items-center gap-2 rounded-control border border-dashed border-line px-3 py-2">
<span className="text-xs text-fg-muted">Ainda não saiu em:</span>
{missing.map((p) => {
const Icon = PLATFORM_META[p].icon;
return (
<Button key={p} size="sm" variant="secondary" disabled={sending !== null}
onClick={async () => { setSending(p); await onPublishMore(head, p); setSending(null); }}>
{sending === p ? <Spinner className="size-3.5" /> : <Icon size={15} />}Publicar no {PLATFORM_META[p].label}
</Button>
);
})}
</div>
)}
</div>
</article>
);
}
function Cover({ job }: { job: PublishJob }) {
const [failed, setFailed] = useState(false);
return (
<div className="relative aspect-9/16 w-full max-w-24 overflow-hidden rounded-control border border-line bg-sunken max-sm:w-20">
{job.cover && !failed ? (
// eslint-disable-next-line @next/next/no-img-element -- capa local servida por /api/files
<img src={fileUrl(job.cover)} alt="" className="size-full object-cover" onError={() => setFailed(true)} />
) : (
<span className="grid size-full place-items-center text-fg-subtle">
{job.sourceKind === "clip" ? <ScissorsIcon size={20} /> : <FilmIcon size={20} />}
</span>
)}
</div>
);
}
/** Uma rede do vídeo: estado, horário, progresso e ações. */
function JobRow({ job, onAction, onReschedule, onReconnect, onMarkPublished, onMarkRemoved }: RowHandlers & { job: PublishJob }) {
const [busy, setBusy] = useState<JobAction | null>(null);
const label = PLATFORM_META[job.platform].label;
const run = async (action: JobAction) => { setBusy(action); await onAction(job, action); setBusy(null); };
const icon = (action: JobAction, fallback: ReactNode) => (busy === action ? <Spinner className="size-3.5" /> : fallback);
const disabled = busy !== null;
const percent = job.progress;
// O servidor diz quais botões valem para o job (`actions`): a tela não recalcula pelo status.
const can = (action: PublishJobAction) => job.actions.includes(action);
// Horário em destaque; o resto vem pronto do servidor em `step` (frase em pt-BR).
const when = job.status === "published" ? `Publicada ${formatTime(job.publishedAt ?? job.updatedAt)}`
: job.status === "scheduled" && job.scheduledAt ? `Sai ${formatTime(job.scheduledAt)}`
: job.status === "failed" || job.status === "needs_login" ? `Parou ${formatTime(job.updatedAt)}` : null;
const actions: ReactNode = (() => {
switch (job.status) {
case "awaiting_approval":
return <>
{can("reschedule") && <Button variant="secondary" size="sm" disabled={disabled} onClick={() => onReschedule(job)}><ClockIcon size={15} />Mudar horário</Button>}
{can("cancel") && <Button variant="ghost" size="sm" disabled={disabled} onClick={() => void run("cancel")}>{icon("cancel", <XIcon size={15} />)}Tirar esta rede</Button>}
</>;
case "scheduled":
return <>
{can("publish-now") && <Button size="sm" disabled={disabled} onClick={() => void run("publish-now")}>{icon("publish-now", <PublishIcon size={15} />)}Publicar agora</Button>}
{can("reschedule") && <Button variant="secondary" size="sm" disabled={disabled} onClick={() => onReschedule(job)}><ClockIcon size={15} />Mudar horário</Button>}
{can("cancel") && <Button variant="ghost" size="sm" disabled={disabled} onClick={() => void run("cancel")}>{icon("cancel", <XIcon size={15} />)}Cancelar</Button>}
</>;
case "queued":
return can("cancel") ? <Button variant="ghost" size="sm" disabled={disabled} onClick={() => void run("cancel")}>{icon("cancel", <XIcon size={15} />)}Cancelar</Button> : null;
case "published":
return <>
{job.url && (
<a href={job.url} target="_blank" rel="noopener noreferrer"
className="inline-flex h-8 items-center gap-2 rounded-control border border-line-strong bg-raised px-3 text-[0.8125rem] font-semibold text-fg hover:bg-overlay focus-visible:outline-2 focus-visible:outline-accent">
<LinkIcon size={15} />Abrir no {label}<span className="sr-only"> (abre numa aba nova)</span>
</a>
)}
{can("removed") && (
<Button variant="ghost" size="sm" disabled={disabled} onClick={() => onMarkRemoved(job)}>
<UndoIcon size={15} />Apaguei na rede
</Button>
)}
</>;
case "failed":
// Pode já estar na rede (o envio chegou ao Publicador): "Já saiu" vem primeiro, para não publicar duas vezes.
return <>
{can("mark-published") && <Button size="sm" variant={job.mayBeLive ? "primary" : "secondary"} disabled={disabled} onClick={() => onMarkPublished(job)}><LinkIcon size={15} />Já saiu: informar o link</Button>}
{can("retry") && <Button size="sm" variant={job.mayBeLive ? "secondary" : "primary"} disabled={disabled} onClick={() => void run("retry")}>{icon("retry", <RefreshIcon size={15} />)}Tentar de novo</Button>}
{can("cancel") && <Button variant="ghost" size="sm" disabled={disabled} onClick={() => void run("cancel")}>{icon("cancel", <XIcon size={15} />)}Cancelar</Button>}
</>;
case "needs_login":
return <>
{can("relogin") && <Button size="sm" disabled={disabled} onClick={() => onReconnect(job)}><RefreshIcon size={15} />Entrar de novo</Button>}
{can("retry") && <Button variant="secondary" size="sm" disabled={disabled} onClick={() => void run("retry")}>{icon("retry", <PublishIcon size={15} />)}Tentar de novo</Button>}
{can("mark-published") && job.mayBeLive && <Button variant="secondary" size="sm" disabled={disabled} onClick={() => onMarkPublished(job)}><LinkIcon size={15} />Já saiu: informar o link</Button>}
{can("cancel") && <Button variant="ghost" size="sm" disabled={disabled} onClick={() => void run("cancel")}>{icon("cancel", <XIcon size={15} />)}Cancelar</Button>}
</>;
default:
return null;
}
})();
return (
<div className="grid gap-2.5 px-3.5 py-3">
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
<PlatformName platform={job.platform as Platform} className="min-w-24 text-sm font-medium text-fg" />
<JobStatusBadge job={job} />
{when && <span className="text-xs text-fg-muted">{when}</span>}
{actions && <span className="ml-auto flex flex-wrap items-center gap-1.5">{actions}</span>}
</div>
{(job.status === "publishing" || job.status === "queued") && (
<div className="grid gap-1.5">
<ProgressBar value={job.status === "publishing" ? percent : undefined} label={`Envio para o ${label}`} />
<p aria-live="polite" className="text-xs text-fg-muted">
{job.step || (job.status === "queued" ? "Na fila." : "Enviando…")}
{job.status === "publishing" && <span className="tabular-nums"> · {Math.round(percent * 100)}%</span>}
</p>
</div>
)}
{job.status === "published" && job.draft && (
<p className="text-xs leading-relaxed text-warning">Foi como rascunho: abra o app do {label} para revisar e publicar.</p>
)}
{job.status !== "publishing" && job.status !== "queued" && job.status !== "failed" && job.step && (
<p className="text-xs leading-relaxed text-fg-subtle">{job.step}</p>
)}
{job.status === "needs_login" && (
<p className="text-xs leading-relaxed text-warning">O {label} pediu para entrar na conta de novo. Entre, e depois clique em “Tentar de novo”.</p>
)}
{job.status === "failed" && job.error && (
<p className="rounded-control border border-danger/30 bg-danger-soft px-3 py-2 text-xs break-words text-danger">
{job.error}{job.attempts > 1 && <span className="text-fg-muted"> · {job.attempts} tentativas</span>}
</p>
)}
</div>
);
}
/* ---------- Já saiu: informar o link ---------- */
const LINK_EXAMPLE: Record<Platform, string> = {
tiktok: "https://www.tiktok.com/@suaconta/video/7709…",
youtube: "https://www.youtube.com/shorts/AbC123…",
instagram: "https://www.instagram.com/reel/AbC123…",
};
function MarkPublishedDialog({ job, onClose, onSaved }: { job: PublishJob; onClose: () => void; onSaved: (text: string) => void }) {
const [value, setValue] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const label = PLATFORM_META[job.platform].label;
async function save() {
if (!value.trim()) { setError(`Cole o link do vídeo no ${label}.`); return; }
setBusy(true);
setError(null);
const r = await markJobPublished(job.id, value.trim());
setBusy(false);
if (!r.ok) { setError(r.error); return; }
onSaved(`${label}: marcado como publicado.`);
}
return (
<Dialog open onClose={onClose} size="sm" title={`O vídeo já está no ${label}?`}
description={`Abra o ${label}, confira que “${job.title}” saiu e copie o link dele. O painel marca como publicado, sem enviar de novo.`}
footer={<>
<Button variant="secondary" onClick={onClose}>Voltar</Button>
<Button onClick={() => void save()} disabled={busy}>{busy ? <Spinner /> : <CheckIcon size={16} />}Marcar como publicado</Button>
</>}>
<form className="grid gap-4" onSubmit={(e) => { e.preventDefault(); void save(); }}>
<Field label={`Link do vídeo no ${label}`} hint={`Exemplo: ${LINK_EXAMPLE[job.platform]}`}>
<Input type="url" inputMode="url" value={value} onChange={(e) => setValue(e.target.value)} placeholder={LINK_EXAMPLE[job.platform]}
autoComplete="off" spellCheck={false} required />
</Field>
<p className="text-xs leading-relaxed text-fg-muted">Se o vídeo <strong className="text-fg">não</strong> estiver lá, volte e use “Tentar de novo”.</p>
<div aria-live="assertive" className="empty:hidden">{error && <Feedback ok={false}>{error}</Feedback>}</div>
</form>
</Dialog>
);
}
/* ---------- Mudar horário ---------- */
/** Valor de <input type="datetime-local"> no horário local do navegador. */
function toLocalInput(iso: string | null): string {
const d = iso ? new Date(iso) : new Date(Date.now() + 3_600_000);
const pad = (n: number) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
function RescheduleDialog({ job, timezone, onClose, onSaved }: {
job: PublishJob; timezone: string; onClose: () => void; onSaved: (text: string) => void;
}) {
const [value, setValue] = useState(() => toLocalInput(job.scheduledAt));
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const label = PLATFORM_META[job.platform].label;
async function save() {
const date = new Date(value);
if (!value || Number.isNaN(date.getTime())) { setError("Escolha a data e a hora."); return; }
if (date.getTime() < Date.now() - 60_000) { setError("Escolha um horário daqui para a frente."); return; }
setBusy(true);
setError(null);
const r = await patchJob(job.id, { scheduledAt: date.toISOString() });
setBusy(false);
if (!r.ok) { setError(r.error); return; }
onSaved(`${label}: sai ${formatTime(date.toISOString())}.`);
}
return (
<Dialog open onClose={onClose} size="sm" title={`Mudar horário no ${label}`}
description="O vídeo sai nesse horário, se o limite por dia da rede deixar."
footer={<>
<Button variant="secondary" onClick={onClose}>Voltar</Button>
<Button onClick={() => void save()} disabled={busy}>{busy ? <Spinner /> : <CheckIcon size={16} />}Salvar horário</Button>
</>}>
<form className="grid gap-4" onSubmit={(e) => { e.preventDefault(); void save(); }}>
<Field label="Data e hora" hint={timezone === "America/Sao_Paulo" ? "Horário de Brasília." : `Fuso: ${timezone}.`}>
<Input type="datetime-local" value={value} onChange={(e) => setValue(e.target.value)} required />
</Field>
<div aria-live="assertive" className="empty:hidden">{error && <Feedback ok={false}>{error}</Feedback>}</div>
</form>
</Dialog>
);
}
+178
View File
@@ -0,0 +1,178 @@
// Publicação automática (YouTube, TikTok, Instagram): chamadas às rotas do painel (doc/publicacao/PLANO.md,
// seções 4–6) com os tipos reais de @/lib/types. Erros chegam como `{ error }` (400 uso, 503 Publicador fora).
//
// Uma visão só para a rede de um canal (`PublishingNetwork`): redes que o canal nunca configurou não vêm em
// `networks[]`, então `readNetwork` aplica os padrões (desconectada, ligada, 3 por dia, pública, TikTok direto)
// e troca o `enabled` 0/1 do SQLite por booleano.
import type {
AccountNetwork, AiLabel, AppSettings, ApprovalMode, ConnectNext, ConnectionMode, NetworkStatus, Platform, Privacy,
PublishJob, PublishJobAction, PublishJobStatus, PublishSourceKind, PublishTiming, PublishingSummary, TiktokMode,
} from "@/lib/types";
import { apiCall, type ApiResult } from "./api-client";
export type {
AiLabel, AppSettings, ApprovalMode, ConnectNext, ConnectionMode, NetworkStatus, Privacy, PublishJob, PublishJobAction,
PublishJobStatus, PublishTiming, PublishingSummary, TiktokMode,
};
/* ---------- Tipos só da interface ---------- */
/** Rede de um canal pronta para a tela (sempre existe, mesmo sem linha no banco). */
export type PublishingNetwork = Omit<AccountNetwork, "id" | "account_id" | "enabled"> & { enabled: boolean };
/** Regras do canal de publicação (colunas de `accounts`). */
export type PublishingRules = { approval_mode: ApprovalMode; timing: PublishTiming; ai_label: AiLabel };
/** App de uma rede no Publicador (sem segredo: só se está configurado). */
export type AppState = { configured: boolean; clientId: string | null; redirectUri: string; notes: string };
export type BrowserInfo = { found: boolean; kind: "chrome" | "msedge" | null; path: string | null };
/** GET /api/publisher/status: `{ online: true, browser, worker, queue }` ou `{ online: false, reason }`. */
export type PublisherStatus =
| { online: true; browser: BrowserInfo; worker: "idle" | "busy"; queue: number }
| { online: false; reason: string };
/* ---------- Leitores ---------- */
const NETWORK_DEFAULTS: Omit<PublishingNetwork, "platform"> = {
handle: null, status: "disconnected", mode: null, enabled: true, daily_limit: 3, privacy: "public", tiktok_mode: "direct",
display_name: null, last_error: null, checked_at: null, expires_at: null, connected_at: null,
};
/** Rede do canal a partir da linha do banco (ou `undefined`, se nunca configurada). */
export function readNetwork(row: AccountNetwork | undefined, platform: Platform): PublishingNetwork {
if (!row) return { ...NETWORK_DEFAULTS, platform };
const { id: _id, account_id: _account, enabled, ...rest } = row;
return { ...NETWORK_DEFAULTS, ...rest, platform, enabled: enabled !== 0 };
}
export function readRules(account: { approval_mode?: ApprovalMode; timing?: PublishTiming; ai_label?: AiLabel }): PublishingRules {
return {
approval_mode: account.approval_mode ?? "manual",
timing: account.timing ?? "best_slot",
ai_label: account.ai_label ?? "auto",
};
}
/* ---------- Chamadas ---------- */
async function mapped<T, U>(call: Promise<ApiResult<T>>, map: (data: T) => U): Promise<ApiResult<U>> {
const r = await call;
return r.ok ? { ok: true, data: map(r.data) } : r;
}
const networkBase = (accountId: string, platform: Platform) =>
`/api/accounts/${encodeURIComponent(accountId)}/networks/${platform}`;
type ConnectResult = { network: PublishingNetwork; next: ConnectNext };
const toConnectResult = (platform: Platform) => (d: { network: AccountNetwork; next: ConnectNext }): ConnectResult =>
({ network: readNetwork(d.network, platform), next: d.next ?? { kind: "none" } });
export function connectNetwork(accountId: string, platform: Platform, mode: ConnectionMode) {
return mapped(apiCall<{ network: AccountNetwork; next: ConnectNext }>(`${networkBase(accountId, platform)}/connect`, "POST", { mode }), toConnectResult(platform));
}
export function submitToken(accountId: string, platform: Platform, accessToken: string) {
return mapped(apiCall<AccountNetwork>(`${networkBase(accountId, platform)}/token`, "POST", { accessToken }), (n) => readNetwork(n, platform));
}
/** Confere a conexão. Sessão logada: abre a página de envio e vê se está logado ("Já entrei"); oficial: só relê o perfil. */
export function checkNetwork(accountId: string, platform: Platform) {
return mapped(apiCall<AccountNetwork>(`${networkBase(accountId, platform)}/check`, "POST"), (n) => readNetwork(n, platform));
}
/** Só sessão logada: reabre a janela do navegador para entrar de novo. */
export function reopenNetwork(accountId: string, platform: Platform) {
return mapped(apiCall<{ network: AccountNetwork; next: ConnectNext }>(`${networkBase(accountId, platform)}/reopen`, "POST"), toConnectResult(platform));
}
export function disconnectNetwork(accountId: string, platform: Platform) {
return apiCall<unknown>(networkBase(accountId, platform), "DELETE");
}
export const DAILY_LIMIT_MAX = 20;
export function updateNetwork(accountId: string, platform: Platform,
patch: Partial<{ enabled: boolean; dailyLimit: number; privacy: Privacy; tiktokMode: TiktokMode }>) {
return mapped(apiCall<AccountNetwork>(networkBase(accountId, platform), "PUT", patch), (n) => readNetwork(n, platform));
}
export function updateRules(accountId: string, patch: Partial<{ approvalMode: ApprovalMode; timing: PublishTiming; aiLabel: AiLabel }>) {
return mapped(apiCall<PublishingRules>(`/api/accounts/${encodeURIComponent(accountId)}`, "PATCH", patch), readRules);
}
export function listJobs(filter: { status?: PublishJobStatus[]; accountId?: string; sourceKind?: PublishSourceKind; sourceId?: string; limit?: number } = {}) {
const params = new URLSearchParams();
if (filter.status?.length) params.set("status", filter.status.join(","));
if (filter.accountId) params.set("accountId", filter.accountId);
if (filter.sourceKind) params.set("sourceKind", filter.sourceKind);
if (filter.sourceId) params.set("sourceId", filter.sourceId);
if (filter.limit) params.set("limit", String(filter.limit));
const query = params.toString();
return apiCall<PublishJob[]>(`/api/publishing/jobs${query ? `?${query}` : ""}`);
}
/** Ações por POST. Atenção: "approve" aprova o vídeo inteiro (todos os jobs aguardando da mesma origem). */
export type JobAction = Extract<PublishJobAction, "approve" | "publish-now" | "retry" | "cancel">;
export function runJobAction(id: number, action: JobAction) {
return apiCall<PublishJob>(`/api/publishing/jobs/${id}/${action}`, "POST");
}
/** "Já saiu: informar o link" — o vídeo foi para a rede mas o envio não trouxe o link. */
export function markJobPublished(id: number, url: string) {
return apiCall<PublishJob>(`/api/publishing/jobs/${id}/mark-published`, "POST", { url });
}
/** "Apaguei na rede" — libera a rede para publicar de novo (o painel não apaga nada na rede). */
export function markJobRemoved(id: number) {
return apiCall<PublishJob>(`/api/publishing/jobs/${id}/removed`, "POST");
}
export function patchJob(id: number, patch: Partial<{ scheduledAt: string | null; title: string; caption: string }>) {
return apiCall<PublishJob>(`/api/publishing/jobs/${id}`, "PATCH", patch);
}
export function getSummary() {
return apiCall<PublishingSummary>("/api/publishing/summary");
}
export async function getPublisherStatus(): Promise<PublisherStatus> {
const r = await apiCall<PublisherStatus>("/api/publisher/status");
return r.ok ? r.data : { online: false, reason: r.error };
}
export function getSettings() {
return apiCall<AppSettings>("/api/settings");
}
export function putSettings(patch: Partial<AppSettings>) {
return apiCall<AppSettings>("/api/settings", "PUT", patch);
}
export function getApp(platform: Platform) {
return apiCall<AppState>(`/api/settings/apps/${platform}`);
}
export function putApp(platform: Platform, body: { clientId: string; clientSecret: string }) {
return apiCall<AppState>(`/api/settings/apps/${platform}`, "PUT", body);
}
export function deleteApp(platform: Platform) {
return apiCall<AppState>(`/api/settings/apps/${platform}`, "DELETE");
}
/** "Publicar" um corte aprovado num canal, nas redes escolhidas (não precisa ligar a fonte ao canal). */
export type ClipPublishResult = { jobs: PublishJob[]; skipped: { platform: Platform; reason: string }[]; placed: number };
export function publishClip(clipId: number, body: { accountId: string; platforms: Platform[]; timing: PublishTiming }) {
return apiCall<ClipPublishResult>(`/api/publishing/clips/${clipId}`, "POST", body);
}
export function approveEpisode(episodeId: number, body: { renderId: number; title: string; caption: string }) {
return apiCall<unknown>(`/api/episodes/${episodeId}/approve`, "POST", body);
}
export function unapproveEpisode(episodeId: number) {
return apiCall<unknown>(`/api/episodes/${episodeId}/approve`, "DELETE");
}
/* ---------- Textos ---------- */
/** Nome do perfil para mostrar: @handle, nome lido da rede ou nada. */
export function networkName(n: { handle: string | null; display_name?: string | null; displayName?: string | null }): string | null {
if (n.handle) return n.handle.startsWith("@") ? n.handle : `@${n.handle}`;
return n.display_name ?? n.displayName ?? null;
}
export const MODE_LABEL: Record<ConnectionMode, string> = { official: "Conta oficial (API)", session: "Sessão logada" };
export const PRIVACY_LABEL: Record<Privacy, string> = { public: "Público", unlisted: "Não listado", private: "Privado" };
/** Horário curto e humano: "hoje, 19:00", "amanhã, 08:00" ou "qua., 19/11, 12:00". */
export function formatTime(iso: string | null): string {
if (!iso) return "—";
const d = new Date(iso);
const today = new Date();
const tomorrow = new Date(today.getTime() + 86_400_000);
const time = d.toLocaleTimeString("pt-BR", { hour: "2-digit", minute: "2-digit" });
if (d.toDateString() === today.toDateString()) return `hoje, ${time}`;
if (d.toDateString() === tomorrow.toDateString()) return `amanhã, ${time}`;
return d.toLocaleString("pt-BR", { weekday: "short", day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" });
}
+141
View File
@@ -0,0 +1,141 @@
// Peças visuais da publicação, reaproveitadas nas páginas Canais de publicação, Publicações, Configurações,
// Clipador e episódio. Estado sempre em palavras + ícone (nunca só pela cor).
import Link from "next/link";
import type { ReactNode } from "react";
import type { Platform } from "@/lib/types";
import { AlertIcon, CheckIcon, ClockIcon, PenIcon, UnlinkIcon, XIcon } from "./icons";
import { PLATFORM_META } from "./platforms";
import { formatTime, networkName, type NetworkStatus, type PublishJob, type PublishJobStatus, type PublishingNetwork } from "./publishing-client";
import { Badge, Spinner, cx, type Tone } from "./ui";
/* ---------- Rede ---------- */
export function PlatformName({ platform, size = 16, className }: { platform: Platform; size?: number; className?: string }) {
const meta = PLATFORM_META[platform];
const Icon = meta.icon;
return (
<span className={cx("inline-flex items-center gap-1.5", className)}>
<Icon size={size} className="text-fg-muted" />{meta.label}
</span>
);
}
const NETWORK_STATUS: Record<NetworkStatus, { tone: Tone; icon: ReactNode; label: string }> = {
disconnected: { tone: "neutral", icon: <UnlinkIcon size={13} />, label: "Não conectado" },
connecting: { tone: "info", icon: <Spinner className="size-3" />, label: "Conectando…" },
connected: { tone: "success", icon: <CheckIcon size={13} />, label: "Conectado" },
needs_login: { tone: "warning", icon: <AlertIcon size={13} />, label: "Precisa entrar de novo" },
expired: { tone: "warning", icon: <ClockIcon size={13} />, label: "Conexão vencida" },
error: { tone: "danger", icon: <AlertIcon size={13} />, label: "Erro" },
};
/** Texto completo do estado da rede: "Conectado como @x", "Erro: …". */
export function networkStatusText(n: Pick<PublishingNetwork, "status" | "handle" | "display_name" | "last_error">): string {
const name = networkName(n);
if (n.status === "connected") return name ? `Conectado como ${name}` : "Conectado";
if (n.status === "error") return n.last_error ? `Erro: ${n.last_error}` : "Erro na conexão";
return NETWORK_STATUS[n.status].label;
}
export function NetworkStatusBadge({ network, short = false }: { network: Pick<PublishingNetwork, "status" | "handle" | "display_name" | "last_error">; short?: boolean }) {
const s = NETWORK_STATUS[network.status];
const text = short ? s.label : networkStatusText(network);
return (
<Badge tone={s.tone} dot={false} className="max-w-full">
{s.icon}<span className="truncate" title={text}>{text}</span>
</Badge>
);
}
/* ---------- Job de publicação ---------- */
export const JOB_STATUS: Record<PublishJobStatus, { tone: Tone; icon: ReactNode; label: string }> = {
awaiting_approval: { tone: "accent", icon: <ClockIcon size={13} />, label: "Aguardando aprovação" },
scheduled: { tone: "info", icon: <ClockIcon size={13} />, label: "Agendada" },
queued: { tone: "info", icon: <ClockIcon size={13} />, label: "Na fila para enviar" },
publishing: { tone: "info", icon: <Spinner className="size-3" />, label: "Publicando" },
published: { tone: "success", icon: <CheckIcon size={13} />, label: "Publicada" },
failed: { tone: "danger", icon: <AlertIcon size={13} />, label: "Falhou" },
needs_login: { tone: "warning", icon: <AlertIcon size={13} />, label: "Precisa entrar de novo" },
canceled: { tone: "neutral", icon: <XIcon size={13} />, label: "Cancelada" },
};
export function jobStatusLabel(job: Pick<PublishJob, "status" | "draft">): string {
if (job.status === "published" && job.draft) return "Enviada como rascunho";
return JOB_STATUS[job.status].label;
}
export function JobStatusBadge({ job }: { job: Pick<PublishJob, "status" | "draft"> }) {
const s = JOB_STATUS[job.status];
const draft = job.status === "published" && job.draft;
return (
<Badge tone={draft ? "warning" : s.tone} dot={false}>
{draft ? <PenIcon size={13} /> : s.icon}{jobStatusLabel(job)}
</Badge>
);
}
/* ---------- Avisos ---------- */
/** Faixa de aviso (Publicador fora, publicação pausada). Fica no topo da página, sem sumir sozinha. */
export function NoticeBar({ tone, title, children, action }: { tone: "warning" | "danger" | "info"; title: ReactNode; children?: ReactNode; action?: ReactNode }) {
const styles = {
warning: "border-warning/30 bg-warning-soft text-warning",
danger: "border-danger/30 bg-danger-soft text-danger",
info: "border-info/30 bg-info-soft text-info",
}[tone];
return (
<div role={tone === "danger" ? "alert" : "status"}
className={cx("flex flex-wrap items-start gap-x-3 gap-y-2 rounded-card border px-4 py-3", styles)}>
<AlertIcon size={18} className="mt-0.5" />
<div className="grid min-w-0 flex-1 basis-64 gap-0.5">
<p className="text-sm font-semibold">{title}</p>
{children && <div className="text-[0.8125rem] leading-relaxed text-fg-muted">{children}</div>}
</div>
{action && <div className="flex flex-wrap items-center gap-2">{action}</div>}
</div>
);
}
/** Link de texto padrão dentro de frases. */
export function TextLink({ href, children }: { href: string; children: ReactNode }) {
return <Link href={href} className="font-medium text-fg underline underline-offset-2 hover:text-accent">{children}</Link>;
}
/* ---------- Estado da publicação de um vídeo, por rede (Clipador, episódio) ---------- */
const CHIP_TONE: Partial<Record<Tone, string>> = {
neutral: "border-line-strong text-fg-muted", accent: "border-accent/30 text-accent", info: "border-info/30 text-info",
success: "border-success/30 text-success", warning: "border-warning/30 text-warning", danger: "border-danger/30 text-danger",
};
/** Uma pílula por rede/canal: "YouTube · Agendada · hoje, 19:00". Sem jobs: diz que nada foi criado ainda. */
export function PublishChips({ jobs, emptyText, showAccount = false }: {
jobs: Pick<PublishJob, "id" | "platform" | "status" | "draft" | "scheduledAt" | "url" | "accountId" | "accountName">[];
emptyText: ReactNode; showAccount?: boolean;
}) {
if (jobs.length === 0) return <p className="text-xs leading-relaxed text-fg-subtle">{emptyText}</p>;
return (
<ul className="flex flex-wrap gap-1.5" aria-label="Publicação por rede">
{jobs.map((j) => {
const s = JOB_STATUS[j.status];
const draft = j.status === "published" && j.draft;
const Icon = PLATFORM_META[j.platform].icon;
const when = j.status === "scheduled" && j.scheduledAt ? ` · ${formatTime(j.scheduledAt)}` : "";
const text = `${PLATFORM_META[j.platform].label}${showAccount ? ` (${j.accountName || j.accountId})` : ""}: ${jobStatusLabel(j)}${when}`;
const toneClass = CHIP_TONE[draft ? "warning" : s.tone] ?? CHIP_TONE.neutral;
const body = <><Icon size={13} />{draft ? <PenIcon size={12} /> : s.icon}<span>{text}</span></>;
const cls = cx("inline-flex h-7 items-center gap-1.5 rounded-full border bg-raised px-2.5 text-xs font-medium", toneClass);
return (
<li key={j.id}>
{j.url
? <a href={j.url} target="_blank" rel="noopener noreferrer" className={cx(cls, "hover:bg-overlay focus-visible:outline-2 focus-visible:outline-accent")}>
{body}<span className="sr-only"> (abrir na rede, nova aba)</span>
</a>
: <span className={cls}>{body}</span>}
</li>
);
})}
</ul>
);
}
+54
View File
@@ -0,0 +1,54 @@
// Geometria dos retângulos de câmera e de área do jogo, em frações (0–1) do quadro original da gravação.
// Compartilhada pelo editor da "Configuração do corte" (modal, aba Câmera e layout) e pelo monitor "Fonte" do
// editor de cortes, para os dois se comportarem igual. Os limites são os do serviço (clipper/app/layout.py:
// largura e altura de 3% a 100%, sempre dentro do quadro).
import type { Rect } from "./clipper-client";
/** Menor largura/altura aceita (o serviço recusa abaixo disso). */
export const RECT_MIN_SIZE = 0.03;
/** Alça de redimensionar: cantos (nw, ne, sw, se) ou bordas (n, s, e, w). */
export type RectHandle = "n" | "s" | "e" | "w" | "nw" | "ne" | "sw" | "se";
export type Point = { x: number; y: number };
/** Põe o retângulo dentro do quadro, com o tamanho mínimo, arredondado a 4 casas. */
export function clampRect(r: Rect): Rect {
const w = Math.min(1, Math.max(RECT_MIN_SIZE, r.w));
const h = Math.min(1, Math.max(RECT_MIN_SIZE, r.h));
const x = Math.min(1 - w, Math.max(0, r.x));
const y = Math.min(1 - h, Math.max(0, r.y));
const round = (v: number) => Math.round(v * 10000) / 10000;
return { x: round(x), y: round(y), w: round(w), h: round(h) };
}
/** Retângulo entre dois pontos (sem limite: é o que aparece enquanto se desenha). */
export function rectBetween(a: Point, b: Point): Rect {
return { x: Math.min(a.x, b.x), y: Math.min(a.y, b.y), w: Math.abs(a.x - b.x), h: Math.abs(a.y - b.y) };
}
/** Desenho grande o bastante para virar retângulo (um clique sem arrastar não apaga o que existia). */
export function isDrawnEnough(r: Rect): boolean {
return r.w >= RECT_MIN_SIZE && r.h >= RECT_MIN_SIZE;
}
/** Arrastar o corpo: desloca `start` o quanto o ponteiro andou desde `origin`. */
export function moveRect(start: Rect, origin: Point, p: Point): Rect {
return clampRect({ ...start, x: start.x + p.x - origin.x, y: start.y + p.y - origin.y });
}
/** Arrastar uma alça: só os lados dela andam; o lado oposto fica parado e o tamanho nunca passa do mínimo. */
export function resizeRect(s: Rect, handle: RectHandle, p: Point): Rect {
const left = handle.includes("w") ? Math.min(p.x, s.x + s.w - RECT_MIN_SIZE) : s.x;
const right = handle.includes("e") ? Math.max(p.x, s.x + RECT_MIN_SIZE) : s.x + s.w;
const top = handle.includes("n") ? Math.min(p.y, s.y + s.h - RECT_MIN_SIZE) : s.y;
const bottom = handle.includes("s") ? Math.max(p.y, s.y + RECT_MIN_SIZE) : s.y + s.h;
return clampRect({ x: left, y: top, w: right - left, h: bottom - top });
}
/** Teclado: setas movem 1%; com Shift mudam o tamanho. `null` = a tecla não é seta. */
export function nudgeRect(r: Rect, key: string, shift: boolean, step = 0.01): Rect | null {
const dx = key === "ArrowLeft" ? -step : key === "ArrowRight" ? step : 0;
const dy = key === "ArrowUp" ? -step : key === "ArrowDown" ? step : 0;
if (!dx && !dy) return null;
return clampRect(shift ? { ...r, w: r.w + dx, h: r.h + dy } : { ...r, x: r.x + dx, y: r.y + dy });
}
+55
View File
@@ -0,0 +1,55 @@
"use client";
// Dispara o render do episódio e acompanha o estado até terminar.
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import type { RenderJob } from "@/lib/types";
import { PlayIcon } from "./icons";
import { Button, Feedback } from "./ui";
export function RenderControls({ episodeId, hasConfig, running }: { episodeId: number; hasConfig: boolean; running: RenderJob | null }) {
const router = useRouter();
const [job, setJob] = useState<RenderJob | null>(running);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!job || job.status !== "running") return;
const timer = setInterval(async () => {
const r = await fetch(`/api/renders/${job.id}`);
if (!r.ok) return;
const next = (await r.json()) as RenderJob;
setJob(next);
if (next.status !== "running") router.refresh();
}, 2000);
return () => clearInterval(timer);
}, [job, router]);
async function start(profile: "preview" | "final") {
setError(null);
const r = await fetch(`/api/episodes/${episodeId}/render`, {
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ profile }),
});
const body = await r.json();
if (!r.ok) return setError(body.error);
setJob(body);
router.refresh();
}
async function cancel() {
if (job) await fetch(`/api/renders/${job.id}`, { method: "DELETE" });
router.refresh();
}
const isRunning = job?.status === "running";
return (
<div className="grid gap-2">
<div className="flex flex-wrap items-center gap-2">
<Button disabled={!hasConfig || isRunning} onClick={() => start("preview")}><PlayIcon size={16} />Renderizar prévia (540×960)</Button>
<Button variant="secondary" disabled={!hasConfig || isRunning} onClick={() => start("final")}>Renderizar final (1080×1920)</Button>
{isRunning && <Button variant="danger" onClick={cancel}>Cancelar</Button>}
</div>
{isRunning && <p role="status" className="animate-pulse text-sm text-info">Renderizando ({job.profile})… a prévia leva ~45 s e o final ~3 min.</p>}
{!hasConfig && <p className="text-sm text-fg-subtle">Monte a cena primeiro (botão “Montar cena com IA”).</p>}
{error && <Feedback ok={false}>{error}</Feedback>}
</div>
);
}
+346
View File
@@ -0,0 +1,346 @@
// Leitor de roteiro: mostra o .md da história de forma diagramada, sem HTML cru (tudo vira
// elemento React, então nada do arquivo é executado). O documental ganha a régua de tempo e os
// trechos com narração, texto na tela e imagem; a ficção usa o mesmo leitor com o que tiver.
import type { ReactNode } from "react";
import { CopyButton } from "./copy-button";
import { AlertIcon, BookIcon, ClockIcon, EyeIcon, FilmIcon, LinkIcon, MicIcon, PenIcon, SparkIcon, WaveIcon } from "./icons";
import { Badge, LinkButton, cx } from "./ui";
import { WORDS_PER_SECOND, countWords, parseScript, type Block, type ScriptSection, type Shot } from "@/lib/script-doc";
/* ---------- Texto em linha: **negrito**, *itálico*, `código`, [link](url) e URLs soltas ---------- */
const INLINE_RE = /(\*\*[^*]+\*\*|`[^`]+`|\[[^\]]+\]\(https?:\/\/[^)\s]+\)|https?:\/\/[^\s<>()]+[^\s<>().,;:!?"'’”)]|\*[^*\s][^*]*\*|_[^_\s][^_]*_)/g;
function hostOf(url: string): string {
try {
return new URL(url).hostname.replace(/^www\./, "");
} catch {
return url;
}
}
function ExternalLink({ href, children }: { href: string; children: ReactNode }) {
return (
<a href={href} target="_blank" rel="noopener noreferrer"
className="font-medium text-accent underline decoration-accent/35 underline-offset-[3px] transition-colors hover:decoration-accent [overflow-wrap:anywhere]">
{children}
</a>
);
}
export function Inline({ text }: { text: string }): ReactNode {
const parts = text.split(INLINE_RE);
return parts.map((part, i) => {
if (i % 2 === 0) return part;
if (part.startsWith("**")) return <strong key={i} className="font-semibold text-fg"><Inline text={part.slice(2, -2)} /></strong>;
if (part.startsWith("`")) return <code key={i} className="rounded border border-line bg-sunken px-1.5 py-0.5 font-mono text-[0.85em] text-fg">{part.slice(1, -1)}</code>;
if (part.startsWith("[")) {
const m = /^\[([^\]]+)\]\((.+)\)$/.exec(part)!;
return <ExternalLink key={i} href={m[2]}>{m[1]}</ExternalLink>;
}
if (part.startsWith("http")) return <ExternalLink key={i} href={part}>{hostOf(part)}</ExternalLink>;
return <em key={i} className="italic"><Inline text={part.slice(1, -1)} /></em>;
});
}
/* ---------- Blocos genéricos ---------- */
function Blocks({ blocks }: { blocks: Block[] }) {
return (
<div className="grid gap-4">
{blocks.map((b, i) => {
switch (b.type) {
case "paragraph":
return <p key={i} className="max-w-[72ch] text-[0.9375rem] leading-[1.75] text-fg-muted"><Inline text={b.text} /></p>;
case "heading":
return <h4 key={i} className="mt-2 font-display text-[0.9375rem] font-semibold text-fg"><Inline text={b.text} /></h4>;
case "quote":
return <blockquote key={i} className="border-l-2 border-accent/50 pl-4 text-[0.9375rem] leading-[1.75] text-fg-muted italic"><Inline text={b.text} /></blockquote>;
case "code":
return <pre key={i} className="overflow-x-auto rounded-control border border-line bg-sunken p-4 font-mono text-[0.8125rem] leading-relaxed text-fg">{b.text}</pre>;
case "list": {
const Tag = b.ordered ? "ol" : "ul";
return (
<Tag key={i} className={cx("grid max-w-[72ch] gap-2 pl-5 text-[0.9375rem] leading-[1.7] text-fg-muted", b.ordered ? "list-decimal" : "list-disc marker:text-accent")}>
{b.items.map((item, j) => <li key={j} className="pl-1"><Inline text={item} /></li>)}
</Tag>
);
}
case "table":
return (
<div key={i} className="overflow-x-auto rounded-control border border-line">
<table className="w-full min-w-[36rem] text-left text-sm">
<thead className="bg-raised/60 text-xs font-semibold text-fg-subtle uppercase">
<tr>{b.header.map((h, j) => <th key={j} className="px-3.5 py-2.5"><Inline text={h} /></th>)}</tr>
</thead>
<tbody className="divide-y divide-line">
{b.rows.map((row, j) => (
<tr key={j}>{row.map((cell, k) => <td key={k} className="px-3.5 py-2.5 align-top leading-relaxed text-fg-muted"><Inline text={cell} /></td>)}</tr>
))}
</tbody>
</table>
</div>
);
}
})}
</div>
);
}
/* ---------- Peças do roteiro ---------- */
/** Título de seção sem a dica entre parênteses que o guia pede ("Fontes (título, instituição…)" → "Fontes"). */
const cleanTitle = (title: string) => title.replace(/\s*\(.*\)\s*$/, "").trim() || title;
const ROLE_TITLE: Partial<Record<ScriptSection["role"], string>> = {
hook: "Gancho", sources: "Fontes", needs: "Necessidades de produção", cover: "Texto de capa",
summary: "Resumo", ending: "Chamada final", consequences: "Consequências", overlay: "Campos de overlay",
};
function SectionTitle({ icon, children, aside }: { icon: ReactNode; children: ReactNode; aside?: ReactNode }) {
return (
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
<span className="grid size-8 place-items-center rounded-lg border border-line-strong bg-raised text-accent">{icon}</span>
<h3 className="font-display text-[1.125rem] font-semibold tracking-[-0.015em] text-fg">{children}</h3>
{aside && <span className="ml-auto">{aside}</span>}
</div>
);
}
/** Texto do jeito que aparece no vídeo: legenda clara sobre fundo escuro. */
function OnScreenText({ text, large = false }: { text: string; large?: boolean }) {
return (
<span className={cx(
"inline-block rounded-lg bg-black/75 px-3 py-1.5 font-display font-bold text-white shadow-pop ring-1 ring-white/10",
large ? "text-[1.375rem] leading-tight" : "text-[0.9375rem] leading-snug",
)}>
<Inline text={text.replace(/^["“](.*)["”]$/, "$1")} />
</span>
);
}
function Stat({ icon, label, value, hint, tone }: { icon: ReactNode; label: string; value: ReactNode; hint?: ReactNode; tone?: "warning" }) {
return (
<div className={cx("grid gap-1 rounded-card border px-4 py-3.5", tone === "warning" ? "border-warning/30 bg-warning-soft/40" : "border-line bg-surface")}>
<span className="flex items-center gap-1.5 text-xs font-medium text-fg-subtle">{icon}{label}</span>
<span className="font-display text-[1.375rem] leading-tight font-semibold tabular-nums text-fg">{value}</span>
{hint && <span className={cx("text-xs", tone === "warning" ? "text-warning" : "text-fg-subtle")}>{hint}</span>}
</div>
);
}
const shotLength = (s: Shot) => (s.start !== null && s.end !== null && s.end > s.start ? s.end - s.start : null);
const fmtSeconds = (n: number) => `${Number.isInteger(n) ? n : n.toFixed(1).replace(".", ",")} s`;
/** Régua do vídeo: cada trecho com largura proporcional à duração. */
function Timeline({ shots }: { shots: Shot[] }) {
const lengths = shots.map((s) => shotLength(s) ?? 1);
const total = lengths.reduce((a, b) => a + b, 0);
return (
<div className="grid gap-2">
<div className="flex h-9 overflow-hidden rounded-control border border-line bg-sunken" role="img"
aria-label={`Régua do vídeo com ${shots.length} trechos`}>
{shots.map((s, i) => (
<a key={i} href={`#trecho-${i + 1}`} title={`Trecho ${i + 1} · ${s.time} s`}
style={{ width: `${(lengths[i] / total) * 100}%` }}
className={cx("grid min-w-0 place-items-center border-r border-canvas/70 text-[0.6875rem] font-semibold tabular-nums transition-colors last:border-r-0",
i % 2 === 0 ? "bg-accent/30 text-fg hover:bg-accent/45" : "bg-accent/12 text-accent hover:bg-accent/25")}>
{i + 1}
</a>
))}
</div>
<div className="flex justify-between font-mono text-[0.6875rem] text-fg-subtle">
<span>0 s</span>
<span>{shots.at(-1)?.end != null ? fmtSeconds(shots.at(-1)!.end!) : ""}</span>
</div>
</div>
);
}
function ShotCard({ shot, n }: { shot: Shot; n: number }) {
const length = shotLength(shot);
const words = countWords(shot.narration);
const spoken = words / WORDS_PER_SECOND;
const tight = length !== null && spoken > length * 1.15;
return (
<li id={`trecho-${n}`} className="relative grid scroll-mt-24 gap-x-6 gap-y-3 md:grid-cols-[6.5rem_minmax(0,1fr)]">
{/* Coluna do tempo, com a linha que liga os trechos */}
<div className="flex items-start gap-3 md:flex-col md:items-stretch md:gap-1.5 md:pt-4">
<span className="grid size-8 shrink-0 place-items-center rounded-full border border-accent/40 bg-accent-soft font-display text-sm font-bold text-accent">{n}</span>
<span className="grid gap-0.5">
<span className="font-mono text-[0.9375rem] font-semibold text-fg">{shot.time ? `${shot.time} s` : "—"}</span>
{length !== null && <span className="text-xs text-fg-subtle">{fmtSeconds(length)} de tela</span>}
</span>
</div>
<article className="grid gap-5 rounded-card border border-line bg-surface p-5 shadow-card">
{shot.narration && (
<div className="grid gap-2">
<span className="flex flex-wrap items-center gap-2 text-eyebrow font-semibold text-fg-subtle uppercase">
<MicIcon size={13} />Narração
<span className={cx("font-normal tracking-normal normal-case", tight ? "text-warning" : "text-fg-subtle")}>
· {words} palavras ≈ {fmtSeconds(Math.round(spoken * 10) / 10)}{tight ? " (mais longa que o trecho)" : ""}
</span>
</span>
<p className="max-w-[68ch] text-[1.0625rem] leading-[1.7] text-fg"><Inline text={shot.narration} /></p>
</div>
)}
{(shot.onScreen || shot.visual) && (
<div className="grid gap-4 border-t border-line pt-4 sm:grid-cols-2">
{shot.visual && (
<div className="grid content-start gap-2">
<span className="flex items-center gap-2 text-eyebrow font-semibold text-fg-subtle uppercase"><EyeIcon size={13} />Imagem</span>
<p className="text-sm leading-relaxed text-fg-muted"><Inline text={shot.visual} /></p>
</div>
)}
{shot.onScreen && (
<div className="grid content-start justify-items-start gap-2">
<span className="flex items-center gap-2 text-eyebrow font-semibold text-fg-subtle uppercase"><FilmIcon size={13} />Texto na tela</span>
<OnScreenText text={shot.onScreen} />
</div>
)}
</div>
)}
</article>
</li>
);
}
/** Itens de fonte: "**título** — instituição — link — fato". O link vira o botão do cartão. */
function SourceCard({ text }: { text: string }) {
const url = /https?:\/\/[^\s<>()]+[^\s<>().,;:!?"'’”)]/.exec(text)?.[0] ?? null;
const parts = text.split(/\s+[—–]\s+/).filter((p) => p !== url);
const [head, ...rest] = parts;
return (
<li className="grid content-start gap-2 rounded-card border border-line bg-surface p-4">
<p className="text-[0.9375rem] leading-snug font-semibold text-fg [&_strong]:font-semibold"><Inline text={head ?? text} /></p>
{rest.length > 0 && <p className="text-[0.8125rem] leading-relaxed text-fg-muted"><Inline text={rest.join(" · ")} /></p>}
{url && (
<a href={url} target="_blank" rel="noopener noreferrer"
className="mt-1 inline-flex w-fit max-w-full items-center gap-1.5 truncate rounded-full border border-line-strong bg-raised px-2.5 py-1 text-xs font-medium text-fg-muted transition-colors hover:border-accent/40 hover:text-accent">
<LinkIcon size={12} /><span className="truncate">{hostOf(url)}</span>
</a>
)}
</li>
);
}
function listItems(section: ScriptSection): string[] {
return section.blocks.flatMap((b) => (b.type === "list" ? b.items : b.type === "paragraph" ? [b.text] : []));
}
/* ---------- Leitor ---------- */
export function ScriptReader({ markdown, readingHref, voicesHref = "/voices" }: {
markdown: string;
/** Link para o modo leitura (página só do roteiro). Ausente quando já estamos nela. */
readingHref?: string;
voicesHref?: string;
}) {
const doc = parseScript(markdown);
const bySection = (role: ScriptSection["role"]) => doc.sections.find((s) => s.role === role);
const hook = bySection("hook");
const sources = bySection("sources");
const needs = bySection("needs");
const cover = bySection("cover");
const shotsSection = bySection("shots");
const sourceItems = sources ? listItems(sources) : [];
const spokenSeconds = Math.round(doc.narrationWords / WORDS_PER_SECOND);
const overTarget = doc.targetSeconds !== null && spokenSeconds > doc.targetSeconds * 1.1;
const narrationText = doc.shots.map((s) => s.narration).filter(Boolean).join("\n\n");
const coverText = cover ? (/`([^`]+)`/.exec(listItems(cover).join(" "))?.[1] ?? null) : null;
// Seções já desenhadas de forma própria; as demais saem como texto comum, na ordem do arquivo.
const special = new Set([hook, sources, needs, cover, shotsSection].filter(Boolean));
const others = doc.sections.filter((s) => !special.has(s));
return (
<div className="grid gap-10">
{/* Resumo e ações */}
<div className="grid gap-4">
<div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
<Stat icon={<ClockIcon size={13} />} label="Duração alvo" value={doc.targetSeconds ? `${doc.targetSeconds} s` : "—"} />
<Stat icon={<FilmIcon size={13} />} label="Trechos" value={doc.shots.length || "—"} />
<Stat icon={<MicIcon size={13} />} label="Narração" value={doc.narrationWords ? `≈ ${spokenSeconds} s` : "—"}
hint={doc.narrationWords ? `${doc.narrationWords} palavras${overTarget ? " · passa da duração alvo" : ""}` : undefined}
tone={overTarget ? "warning" : undefined} />
<Stat icon={<BookIcon size={13} />} label="Fontes" value={sourceItems.length || "—"} />
</div>
<div className="flex flex-wrap items-center gap-2.5">
{narrationText && <CopyButton text={narrationText} label="Copiar narração" icon={<MicIcon size={16} />} />}
{narrationText && <LinkButton variant="ghost" href={`${voicesHref}?text=${encodeURIComponent(narrationText.slice(0, 2000))}`}><WaveIcon size={16} />Gerar áudio em Vozes</LinkButton>}
{readingHref && <LinkButton variant="ghost" href={readingHref}><BookIcon size={16} />Modo leitura</LinkButton>}
</div>
</div>
{hook && (
<section aria-label="Gancho" className="relative overflow-hidden rounded-card border border-accent/30 bg-linear-to-br from-accent-soft/70 via-surface to-surface p-6">
<span aria-hidden="true" className="absolute inset-y-0 left-0 w-1 bg-linear-to-b from-glow via-accent to-flame" />
<p className="mb-3 flex items-center gap-2 text-eyebrow font-semibold text-accent uppercase"><SparkIcon size={13} />{cleanTitle(hook.title)}</p>
<div className="text-[1.0625rem] [&_p]:max-w-[68ch] [&_p]:text-fg"><Blocks blocks={hook.blocks} /></div>
</section>
)}
{doc.shots.length > 0 && (
<section aria-labelledby="trechos" className="grid gap-5">
<SectionTitle icon={<FilmIcon size={16} />}
aside={<span className="flex flex-wrap gap-2"><Badge tone="neutral" dot={false}><MicIcon size={12} />narração</Badge><Badge tone="neutral" dot={false}><EyeIcon size={12} />imagem</Badge><Badge tone="neutral" dot={false}><FilmIcon size={12} />texto na tela</Badge></span>}>
<span id="trechos">Trecho a trecho</span>
</SectionTitle>
<Timeline shots={doc.shots} />
<ol className="grid gap-4">
{doc.shots.map((shot, i) => <ShotCard key={i} shot={shot} n={i + 1} />)}
</ol>
</section>
)}
{cover && (
<section aria-label="Texto de capa" className="grid gap-4">
<SectionTitle icon={<PenIcon size={16} />}
aside={coverText ? <Badge tone={coverText.length <= 30 ? "success" : coverText.length <= 80 ? "warning" : "danger"} dot={false}>{coverText.length} caracteres</Badge> : undefined}>
{ROLE_TITLE.cover}
</SectionTitle>
{coverText
? <div className="grid place-items-center rounded-card border border-line bg-[radial-gradient(circle_at_50%_30%,rgb(255_122_26/0.12),transparent_70%)] px-6 py-8"><OnScreenText text={coverText} large /></div>
: <Blocks blocks={cover.blocks} />}
</section>
)}
{sources && (
<section aria-label="Fontes" className="grid gap-4">
<SectionTitle icon={<BookIcon size={16} />} aside={<span className="text-xs text-fg-subtle">Confira antes de publicar</span>}>{ROLE_TITLE.sources}</SectionTitle>
{sourceItems.length > 0
? <ul className="grid gap-3 md:grid-cols-2">{sourceItems.map((item, i) => <SourceCard key={i} text={item} />)}</ul>
: <Blocks blocks={sources.blocks} />}
</section>
)}
{others.map((section, i) => (
<section key={i} aria-label={cleanTitle(section.title)} className="grid gap-4">
<SectionTitle icon={<PenIcon size={16} />}>{ROLE_TITLE[section.role] ?? cleanTitle(section.title)}</SectionTitle>
<Blocks blocks={section.blocks} />
</section>
))}
{needs && (
<section aria-label="Necessidades de produção" className="grid gap-4 rounded-card border border-warning/25 bg-warning-soft/25 p-5">
<SectionTitle icon={<AlertIcon size={16} />}>{ROLE_TITLE.needs}</SectionTitle>
<ul className="grid gap-2.5">
{listItems(needs).map((item, i) => (
<li key={i} className="flex gap-3 text-[0.9375rem] leading-relaxed text-fg-muted">
<span aria-hidden="true" className="mt-1.5 size-3.5 shrink-0 rounded border border-warning/60" />
<span className="min-w-0"><Inline text={item} /></span>
</li>
))}
</ul>
</section>
)}
<details className="group rounded-card border border-line bg-surface/60">
<summary className="flex cursor-pointer list-none items-center gap-2 px-5 py-3.5 text-sm font-medium text-fg-muted hover:text-fg [&::-webkit-details-marker]:hidden">
<PenIcon size={15} />Ver o arquivo original (.md)
</summary>
<pre className="max-h-[60vh] overflow-auto border-t border-line px-5 py-4 font-mono text-[0.8125rem] leading-relaxed whitespace-pre-wrap text-fg-muted">{markdown}</pre>
</details>
</div>
);
}
+545
View File
@@ -0,0 +1,545 @@
"use client";
// Configurações do painel (por enquanto, tudo da publicação nas redes), em abas:
// Publicação — pausar tudo, horários bons por rede, fuso e de quanto em quanto tempo ler os números dos posts
// (GET/PUT /api/settings);
// Apps das redes — passo a passo para criar o app de cada rede e os campos Client ID/Secret
// (GET/PUT/DELETE /api/settings/apps/[platform]); o segredo nunca volta para a tela;
// Navegador — navegador encontrado pelo Publicador (modo sessão) e onde ficam as sessões;
// Sobre os modos — comparação simples entre "Conta oficial (API)" e "Sessão logada".
import { useCallback, useEffect, useState, type FormEvent, type ReactNode } from "react";
import type { Platform } from "@/lib/types";
import { askConfirm } from "./confirm-dialog";
import { CopyButton } from "./copy-button";
import { AlertIcon, CheckIcon, ClockIcon, GlobeIcon, InfoIcon, KeyIcon, PlusIcon, RefreshIcon, TrashIcon, XIcon } from "./icons";
import { PLATFORM_META } from "./platforms";
import {
deleteApp, getApp, getPublisherStatus, getSettings, putApp, putSettings,
type AppState, type PublisherStatus, type AppSettings,
} from "./publishing-client";
import { NoticeBar, PlatformName, TextLink } from "./publishing-ui";
import { Tabs } from "./tabs";
import { Badge, Button, Card, Feedback, Field, Input, Select, Spinner, Switch, Table, Td, Th, THead, Tr, cx } from "./ui";
type TabId = "publicacao" | "apps" | "navegador" | "modos";
type Message = { ok: boolean; text: string } | null;
/** Ordem de exibição das redes nestas telas (a mais usada primeiro). */
const ORDER: Platform[] = ["youtube", "tiktok", "instagram"];
const TIMEZONES: { value: string; label: string }[] = [
{ value: "America/Sao_Paulo", label: "Brasília (São Paulo, Rio, BH, Sul)" },
{ value: "America/Manaus", label: "Amazonas (Manaus)" },
{ value: "America/Cuiaba", label: "Mato Grosso (Cuiabá)" },
{ value: "America/Rio_Branco", label: "Acre (Rio Branco)" },
{ value: "America/Noronha", label: "Fernando de Noronha" },
{ value: "UTC", label: "UTC" },
];
export function SettingsPanel() {
return (
<Tabs<TabId> label="Seções das configurações"
items={[
{ id: "publicacao", label: "Publicação", icon: <ClockIcon size={16} /> },
{ id: "apps", label: "Apps das redes", icon: <KeyIcon size={16} /> },
{ id: "navegador", label: "Navegador", icon: <GlobeIcon size={16} /> },
{ id: "modos", label: "Sobre os modos", icon: <InfoIcon size={16} /> },
]}
panels={{
publicacao: <PublishingTab />,
apps: <AppsTab />,
navegador: <BrowserTab />,
modos: <ModesTab />,
}} />
);
}
/* ---------- Publicação ---------- */
function PublishingTab() {
const [settings, setSettings] = useState<AppSettings | null>(null);
const [draft, setDraft] = useState<AppSettings | null>(null);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState<string | null>(null);
const [message, setMessage] = useState<Message>(null);
const load = useCallback(async () => {
const r = await getSettings();
if (r.ok) { setSettings(r.data); setDraft(r.data); setError(null); } else setError(r.error);
}, []);
useEffect(() => { void load(); }, [load]);
if (error && !settings) return <LoadError text={`Não deu para ler as configurações: ${error}`} onRetry={load} />;
if (!settings || !draft) return <Loading />;
const dirty = JSON.stringify(draft.slots) !== JSON.stringify(settings.slots) || draft.timezone !== settings.timezone;
async function togglePause(paused: boolean) {
setBusy("pause");
setMessage(null);
const r = await putSettings({ publishingPaused: paused });
setBusy(null);
if (!r.ok) { setMessage({ ok: false, text: r.error }); return; }
setSettings((s) => (s ? { ...s, publishingPaused: r.data.publishingPaused } : s));
setDraft((d) => (d ? { ...d, publishingPaused: r.data.publishingPaused } : d));
setMessage({ ok: true, text: r.data.publishingPaused ? "Publicação pausada: nada sai até você retomar." : "Publicação retomada." });
}
async function saveMetricsEvery(hours: number) {
setBusy("metrics");
setMessage(null);
const r = await putSettings({ metricsEveryHours: hours });
setBusy(null);
if (!r.ok) { setMessage({ ok: false, text: r.error }); return; }
setSettings((s) => (s ? { ...s, metricsEveryHours: r.data.metricsEveryHours } : s));
setDraft((d) => (d ? { ...d, metricsEveryHours: r.data.metricsEveryHours } : d));
setMessage({ ok: true, text: hours ? `Os números dos posts serão lidos a cada ${hours} h.` : "Leitura automática desligada: use “Atualizar números agora” no Dashboard." });
}
async function saveSlots(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
if (!draft) return;
setBusy("slots");
setMessage(null);
const r = await putSettings({ slots: draft.slots, timezone: draft.timezone });
setBusy(null);
if (!r.ok) { setMessage({ ok: false, text: r.error }); return; }
setSettings(r.data);
setDraft(r.data);
setMessage({ ok: true, text: "Horários salvos." });
}
return (
<div className="grid gap-6">
<Card title="Pausar tudo" description="Para quando você precisa segurar as postagens (viagem, revisão, problema numa rede).">
<Switch label="Pausar todas as publicações" checked={settings.publishingPaused} busy={busy === "pause"} disabled={busy !== null}
hint="Ligado: nada sai para as redes. Aprovar e agendar continuam funcionando; os vídeos esperam na fila."
onChange={(v) => void togglePause(v)} />
</Card>
<Card title="Horários bons"
description="Quando um canal usa “No próximo horário bom”, cada vídeo sai no próximo destes horários que estiver livre, respeitando o máximo por dia de cada rede.">
<form onSubmit={saveSlots} className="grid gap-6">
<div className="grid gap-5 lg:grid-cols-3">
{ORDER.map((p) => (
<SlotEditor key={p} platform={p} slots={draft.slots[p]}
onChange={(slots) => setDraft((d) => (d ? { ...d, slots: { ...d.slots, [p]: slots } } : d))} />
))}
</div>
<Field label="Fuso horário" hint="Os horários acima valem neste fuso." className="max-w-sm">
<Select value={draft.timezone} onChange={(e) => setDraft((d) => (d ? { ...d, timezone: e.target.value } : d))}>
{!TIMEZONES.some((t) => t.value === draft.timezone) && <option value={draft.timezone}>{draft.timezone}</option>}
{TIMEZONES.map((t) => <option key={t.value} value={t.value}>{t.label}</option>)}
</Select>
</Field>
<div className="flex flex-wrap items-center gap-2">
<Button type="submit" disabled={!dirty || busy !== null}>{busy === "slots" ? <Spinner /> : <CheckIcon size={16} />}Salvar horários</Button>
{dirty && <Button type="button" variant="ghost" onClick={() => setDraft(settings)}>Desfazer</Button>}
{dirty && <span className="text-xs text-warning">Há mudanças não salvas.</span>}
</div>
</form>
</Card>
<Card title="Números das redes"
description="Views, curtidas e comentários de cada vídeo publicado, para o Dashboard. O YouTube é lido pela página pública do vídeo; o TikTok e o Instagram, pela janela logada, que abre por alguns segundos e fecha sozinha.">
<Field label="Ler sozinho" hint="Só com o painel aberto. Lê os vídeos dos últimos 90 dias; o botão do Dashboard lê todos." className="max-w-sm">
<Select value={String(settings.metricsEveryHours)} disabled={busy !== null}
onChange={(e) => void saveMetricsEvery(Number(e.target.value))}>
{METRICS_OPTIONS.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
</Select>
</Field>
</Card>
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</div>
);
}
const METRICS_OPTIONS = [
{ value: "3", label: "A cada 3 horas" },
{ value: "6", label: "A cada 6 horas (recomendado)" },
{ value: "12", label: "A cada 12 horas" },
{ value: "24", label: "Uma vez por dia" },
{ value: "0", label: "Só quando eu pedir (botão no Dashboard)" },
];
function SlotEditor({ platform, slots, onChange }: { platform: Platform; slots: string[]; onChange: (slots: string[]) => void }) {
const [time, setTime] = useState("");
const [error, setError] = useState<string | null>(null);
const label = PLATFORM_META[platform].label;
const inputId = `slot-${platform}`;
function add() {
if (!/^\d{2}:\d{2}$/.test(time)) { setError("Escolha um horário."); return; }
if (slots.includes(time)) { setError(`${time} já está na lista.`); return; }
setError(null);
onChange([...slots, time].sort());
setTime("");
}
return (
<fieldset className="grid content-start gap-3 rounded-control border border-line bg-sunken/30 p-4">
<legend className="sr-only">Horários bons do {label}</legend>
<PlatformName platform={platform} className="text-sm font-semibold text-fg" />
{slots.length === 0 ? (
<p className="text-xs text-warning">Sem horário: no modo “próximo horário bom”, nada sai nesta rede.</p>
) : (
<ul className="flex flex-wrap gap-1.5" aria-label={`Horários do ${label}`}>
{slots.map((s) => (
<li key={s}>
<span className="inline-flex h-8 items-center gap-1 rounded-full border border-line-strong bg-raised pr-1 pl-3 text-sm font-medium text-fg tabular-nums">
{s}
<button type="button" onClick={() => onChange(slots.filter((x) => x !== s))} aria-label={`Tirar ${s} do ${label}`}
className="grid size-6 place-items-center rounded-full text-fg-subtle hover:bg-overlay hover:text-fg focus-visible:outline-2 focus-visible:outline-accent">
<XIcon size={13} />
</button>
</span>
</li>
))}
</ul>
)}
<div className="flex items-end gap-2">
<label htmlFor={inputId} className="sr-only">Novo horário para o {label}</label>
<Input id={inputId} type="time" value={time} onChange={(e) => { setTime(e.target.value); setError(null); }}
onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); add(); } }} className="h-9 w-32" />
<Button type="button" variant="secondary" size="sm" onClick={add}><PlusIcon size={15} />Adicionar</Button>
</div>
<div aria-live="polite" className="empty:hidden">{error && <p className="text-xs text-danger">{error}</p>}</div>
</fieldset>
);
}
/* ---------- Apps das redes ---------- */
type Guide = { title: string; intro: ReactNode; steps: ReactNode[]; clientIdLabel: string; secretLabel: string; redirectNote: string };
const GUIDES: Record<"youtube" | "tiktok", Guide> = {
youtube: {
title: "App do Google (YouTube)",
intro: "O Google pede um “app” seu para deixar o CenaForge enviar vídeos pelo caminho oficial. É grátis e leva uns 10 minutos.",
steps: [
<>Abra <ExternalLink href="https://console.cloud.google.com/">console.cloud.google.com</ExternalLink>, entre com a sua conta Google e crie um projeto (ex.: “CenaForge”).</>,
<>Em <b>APIs e serviços › Biblioteca</b>, procure <b>YouTube Data API v3</b> e clique em <b>Ativar</b>.</>,
<>Em <b>Tela de consentimento</b> (Google Auth Platform), escolha <b>Externo</b>, preencha o nome e o seu e-mail.</>,
<>Ainda lá, clique em <b>Publicar app</b> (“Em produção”). Se ficar em “Teste”, a conexão vence a cada 7 dias. O aviso “app não verificado” é normal: o app é seu.</>,
<>Em <b>Credenciais › Criar credenciais › ID do cliente OAuth</b>, escolha o tipo <b>App para computador</b>.</>,
<>Copie o <b>ID do cliente</b> e a <b>Chave secreta do cliente</b> e cole nos campos ao lado.</>,
],
clientIdLabel: "ID do cliente (Client ID)",
secretLabel: "Chave secreta do cliente (Client secret)",
redirectNote: "No tipo “App para computador” o Google aceita este endereço sozinho: não precisa cadastrar.",
},
tiktok: {
title: "App do TikTok",
intro: "O TikTok pede um app seu no site de desenvolvedores. Sem a aprovação (auditoria) do TikTok, o modo oficial publica só como privado ou manda como rascunho para o app.",
steps: [
<>Abra <ExternalLink href="https://developers.tiktok.com/">developers.tiktok.com</ExternalLink>, entre e crie um app em <b>Manage apps</b>.</>,
<>Adicione os produtos <b>Login Kit</b> e <b>Content Posting API</b>.</>,
<>No Login Kit, escolha a plataforma <b>Desktop</b> e cole o <b>endereço de retorno</b> deste cartão em <b>Redirect URI</b>.</>,
<>Marque as permissões <code>user.info.basic</code>, <code>video.upload</code> e <code>video.publish</code>.</>,
<>Copie o <b>Client key</b> e o <b>Client secret</b> e cole nos campos ao lado.</>,
],
clientIdLabel: "Client key",
secretLabel: "Client secret",
redirectNote: "Cole exatamente este endereço no Login Kit do TikTok.",
},
};
function AppsTab() {
return (
<div className="grid gap-6">
<p className="max-w-[75ch] text-sm leading-relaxed text-fg-muted">
Só precisa disto para conectar no modo <b className="text-fg">Conta oficial (API)</b>. API é a porta oficial que cada rede oferece para
programas publicarem. Cada rede pede um “app” seu (um cadastro grátis no site de desenvolvedores dela). As chaves ficam guardadas só neste computador.
</p>
<AppCard platform="youtube" guide={GUIDES.youtube} />
<AppCard platform="tiktok" guide={GUIDES.tiktok} />
<InstagramCard />
</div>
);
}
function AppCard({ platform, guide }: { platform: "youtube" | "tiktok"; guide: Guide }) {
const [app, setApp] = useState<AppState | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [clientId, setClientId] = useState("");
const [secret, setSecret] = useState("");
const [busy, setBusy] = useState<string | null>(null);
const [message, setMessage] = useState<Message>(null);
const Icon = PLATFORM_META[platform].icon;
const load = useCallback(async () => {
const r = await getApp(platform);
if (r.ok) { setApp(r.data); setClientId(r.data.clientId ?? ""); setLoadError(null); } else setLoadError(r.error);
}, [platform]);
useEffect(() => { void load(); }, [load]);
async function save(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
if (!clientId.trim() || !secret.trim()) { setMessage({ ok: false, text: "Preencha os dois campos." }); return; }
setBusy("save");
setMessage(null);
const r = await putApp(platform, { clientId: clientId.trim(), clientSecret: secret.trim() });
setBusy(null);
if (!r.ok) { setMessage({ ok: false, text: r.error }); return; }
setApp(r.data);
setSecret("");
setMessage({ ok: true, text: "App salvo. Agora dá para conectar no modo oficial em Canais de publicação." });
}
async function remove() {
const ok = await askConfirm({
title: `Apagar o app do ${PLATFORM_META[platform].label}?`,
message: "As chaves somem deste computador. Perfis já conectados no modo oficial podem parar de publicar até você cadastrar o app de novo.",
confirmLabel: "Apagar app", tone: "danger",
});
if (!ok) return;
setBusy("delete");
setMessage(null);
const r = await deleteApp(platform);
setBusy(null);
if (!r.ok) { setMessage({ ok: false, text: r.error }); return; }
setApp(r.data);
setClientId("");
setMessage({ ok: true, text: "App apagado." });
}
const redirect = app?.redirectUri ?? `http://127.0.0.1:4530/oauth/callback/${platform}`;
return (
<Card eyebrow={<><Icon size={13} />{PLATFORM_META[platform].label}</>} title={guide.title} description={guide.intro}
actions={app ? <AppBadge configured={app.configured} /> : undefined}>
<div className="grid gap-6 lg:grid-cols-[minmax(0,1.1fr)_minmax(0,1fr)]">
<div className="grid content-start gap-4">
<h3 className="text-eyebrow font-semibold text-fg-subtle uppercase">Passo a passo</h3>
<StepList steps={guide.steps} />
{app?.notes && <p className="text-xs leading-relaxed whitespace-pre-line text-fg-subtle">{app.notes}</p>}
</div>
<div className="grid content-start gap-5">
<div className="grid gap-2">
<span className="text-[0.8125rem] font-medium text-fg-muted">Endereço de retorno (Redirect URI)</span>
<div className="flex flex-wrap items-center gap-2">
<code className="min-w-0 flex-1 basis-56 truncate rounded-control border border-line-strong bg-sunken/60 px-3 py-2 font-mono text-xs text-fg" title={redirect}>{redirect}</code>
<CopyButton text={redirect} label="Copiar" size="sm" />
</div>
<span className="text-xs leading-relaxed text-fg-subtle">{guide.redirectNote}</span>
</div>
{loadError && !app ? (
<LoadError text={`Não deu para ler o app: ${loadError}`} onRetry={load} />
) : (
<form onSubmit={save} className="grid gap-4" autoComplete="off">
<Field label={guide.clientIdLabel}>
<Input value={clientId} onChange={(e) => setClientId(e.target.value)} spellCheck={false} className="font-mono text-xs" disabled={!app} />
</Field>
<Field label={guide.secretLabel}
hint={app?.configured
? "Já tem um segredo guardado. Por segurança ele não aparece aqui; para trocar, cole o novo."
: "Fica guardado só neste computador, protegido pela sua conta do Windows. Depois de salvo, não aparece de novo."}>
<Input type="password" value={secret} onChange={(e) => setSecret(e.target.value)} spellCheck={false} autoComplete="new-password"
placeholder={app?.configured ? "•••••••• (guardado)" : "Cole aqui"} className="font-mono text-xs" disabled={!app} />
</Field>
<div className="flex flex-wrap items-center gap-2">
<Button type="submit" disabled={!app || busy !== null}>{busy === "save" ? <Spinner /> : <CheckIcon size={16} />}{app?.configured ? "Trocar chaves" : "Salvar app"}</Button>
{app?.configured && (
<Button type="button" variant="ghost" onClick={() => void remove()} disabled={busy !== null} className="hover:bg-danger-soft hover:text-danger">
{busy === "delete" ? <Spinner /> : <TrashIcon size={15} />}Apagar app
</Button>
)}
</div>
</form>
)}
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</div>
</div>
</Card>
);
}
function InstagramCard() {
const Icon = PLATFORM_META.instagram.icon;
return (
<Card eyebrow={<><Icon size={13} />Instagram</>} title="Instagram: código colado (sem app aqui)"
description="A Meta não aceita devolver o login para um endereço deste computador. Por isso, no Instagram você gera um código de acesso (token) no site da Meta e cola no passo a passo de conexão. Ele vale 60 dias e o CenaForge renova sozinho.">
<div className="grid gap-4">
<h3 className="text-eyebrow font-semibold text-fg-subtle uppercase">Passo a passo</h3>
<StepList steps={[
<>A conta do Instagram precisa ser <b>Profissional</b> (Comercial ou Criador de conteúdo). Dá para mudar no app, em Configurações › Tipo de conta.</>,
<>Abra <ExternalLink href="https://developers.facebook.com/apps/">developers.facebook.com/apps</ExternalLink> e crie um app. Adicione o produto <b>Instagram</b> › <b>API com login do Instagram</b>.</>,
<>Em <b>Gerar tokens de acesso</b>, adicione a sua conta do Instagram e clique em <b>Gerar token</b>.</>,
<>Copie o código e cole no passo a passo <b>Conectar</b> do Instagram, em <TextLink href="/accounts">Canais de publicação</TextLink>.</>,
]} />
</div>
</Card>
);
}
function AppBadge({ configured }: { configured: boolean }) {
return configured
? <Badge tone="success" dot={false}><CheckIcon size={13} />Configurado</Badge>
: <Badge tone="neutral" dot={false}><AlertIcon size={13} />Não configurado</Badge>;
}
function StepList({ steps }: { steps: ReactNode[] }) {
return (
<ol className="grid gap-3">
{steps.map((step, i) => (
<li key={i} className="flex gap-3 text-sm leading-relaxed text-fg-muted [&_b]:font-semibold [&_b]:text-fg [&_code]:rounded [&_code]:bg-raised [&_code]:px-1 [&_code]:text-xs">
<span aria-hidden="true" className="grid size-6 shrink-0 place-items-center rounded-full border border-line-strong bg-raised text-xs font-semibold text-fg tabular-nums">{i + 1}</span>
<span className="min-w-0"><span className="sr-only">Passo {i + 1}: </span>{step}</span>
</li>
))}
</ol>
);
}
function ExternalLink({ href, children }: { href: string; children: ReactNode }) {
return (
<a href={href} target="_blank" rel="noopener noreferrer" className="font-medium text-fg underline underline-offset-2 hover:text-accent">
{children}<span className="sr-only"> (abre numa aba nova)</span>
</a>
);
}
/* ---------- Navegador ---------- */
function BrowserTab() {
const [status, setStatus] = useState<PublisherStatus | null>(null);
const [busy, setBusy] = useState(false);
const load = useCallback(async () => {
setBusy(true);
setStatus(await getPublisherStatus());
setBusy(false);
}, []);
useEffect(() => { void load(); }, [load]);
const browser = status?.online ? status.browser : null;
const browserName = browser?.kind === "chrome" ? "Google Chrome" : browser?.kind === "msedge" ? "Microsoft Edge" : "Navegador";
return (
<div className="grid gap-6">
<NoticeBar tone="warning" title="Sessão logada vai contra os termos das redes">
Publicar por automação no site (sem a API) viola os termos de uso do YouTube, do TikTok e do Instagram. A rede pode bloquear ou suspender a conta.
O CenaForge nunca digita a sua senha nem resolve verificações: você entra à mão, e ele para e avisa quando a rede pedir login de novo.
</NoticeBar>
<Card title="Navegador usado na sessão logada"
description="No modo sessão, o Publicador abre um Chrome (ou Edge) normal, já instalado no computador, com um perfil separado para cada rede de cada canal."
actions={<Button variant="ghost" size="sm" onClick={() => void load()} disabled={busy}>{busy ? <Spinner className="size-3.5" /> : <RefreshIcon size={15} />}Conferir de novo</Button>}>
{!status ? <Loading /> : !status.online ? (
<Feedback ok={false}>O Publicador está desligado, então não dá para saber qual navegador ele achou. Ele liga junto com o CenaForge (<code>pnpm dev</code>).</Feedback>
) : (
<dl className="grid gap-4 sm:grid-cols-2">
<div className="grid gap-1.5">
<dt className="text-eyebrow font-semibold text-fg-subtle uppercase">Navegador encontrado</dt>
<dd className="flex flex-wrap items-center gap-2 text-sm">
{browser?.found
? <><Badge tone="success" dot={false}><CheckIcon size={13} />Encontrado</Badge><span className="font-medium text-fg">{browserName}</span></>
: <><Badge tone="warning" dot={false}><AlertIcon size={13} />Nenhum encontrado</Badge><span className="text-fg-muted">Instale o Google Chrome ou o Microsoft Edge.</span></>}
</dd>
{browser?.path && <dd className="truncate font-mono text-xs text-fg-subtle" title={browser.path}>{browser.path}</dd>}
</div>
<div className="grid gap-1.5">
<dt className="text-eyebrow font-semibold text-fg-subtle uppercase">Onde ficam as sessões</dt>
<dd className="font-mono text-xs break-all text-fg-muted">data/publisher/browser/&lt;canal&gt;--&lt;rede&gt;</dd>
<dd className="text-xs leading-relaxed text-fg-subtle">Uma pasta por rede de cada canal. “Desconectar” apaga a pasta e a sessão junto.</dd>
</div>
<div className="grid gap-1.5">
<dt className="text-eyebrow font-semibold text-fg-subtle uppercase">Publicador</dt>
<dd className="text-sm text-fg-muted">
{status.worker === "busy" ? "Enviando um vídeo agora" : "Livre"}{status.queue !== null && <> · {status.queue} na fila</>}
</dd>
</div>
</dl>
)}
</Card>
</div>
);
}
/* ---------- Sobre os modos ---------- */
const MODES_TABLE: Record<Platform, { official: string[]; session: string[] }> = {
youtube: {
official: ["Publica público, privado ou agendado; vira Short sozinho", "Até 100 envios por dia", "Aviso “app não verificado” no login (normal)"],
session: ["O mesmo, pelo YouTube Studio", "O Google às vezes bloqueia o login nessa janela", "Quebra quando o site muda"],
},
tiktok: {
official: ["Sem aprovação do TikTok: só privado ou rascunho no app", "Até 5 rascunhos por dia", "Você termina a publicação no app"],
session: ["Publica como público", "Pode pedir verificação (captcha): aí você resolve à mão", "Quebra quando o site muda"],
},
instagram: {
official: ["Publica o Reel com capa e aviso de IA", "Só conta Profissional", "Código de acesso de 60 dias, renovado sozinho"],
session: ["Publica o Reel pelo site", "Pede verificação de segurança com frequência", "Quebra quando o site muda"],
},
};
function ModesTab() {
return (
<div className="grid gap-6">
<Card title="Os dois jeitos de conectar uma rede"
description="Você escolhe o modo em cada rede de cada canal, na hora de conectar. Dá para trocar depois: desconecte e conecte de novo.">
<div className="grid gap-4 md:grid-cols-2">
<ModeSummary title="Conta oficial (API)" tone="success" risk="Risco baixo"
text="Você autoriza o CenaForge na página oficial da rede. O envio usa a API: a porta oficial que a rede oferece para programas. Precisa criar um app grátis em cada rede (menos no Instagram, que usa um código colado)." />
<ModeSummary title="Sessão logada" tone="danger" risk="Risco alto: vai contra os termos"
text="Abre um Chrome separado; você entra na conta à mão e o CenaForge publica pelo site, como se fosse você. Não precisa de app, mas a rede pode bloquear a conta, e pode quebrar quando o site muda." />
</div>
</Card>
<Card title="Rede por rede" padded={false}>
<Table className="rounded-none border-0">
<THead><Th>Rede</Th><Th>Conta oficial (API)</Th><Th>Sessão logada</Th></THead>
<tbody>
{ORDER.map((p) => (
<Tr key={p}>
<Td className="align-top"><PlatformName platform={p} className="font-medium text-fg" /></Td>
<Td className="align-top"><CellList items={MODES_TABLE[p].official} risk="Risco baixo" tone="success" /></Td>
<Td className="align-top"><CellList items={MODES_TABLE[p].session} risk="Risco alto" tone="danger" /></Td>
</Tr>
))}
</tbody>
</Table>
</Card>
<p className="text-xs text-fg-subtle">Pesquisa de 17/11/2026. As regras das redes mudam; o CenaForge revisa a cada 3 meses.</p>
</div>
);
}
function ModeSummary({ title, text, risk, tone }: { title: string; text: string; risk: string; tone: "success" | "danger" }) {
return (
<div className={cx("grid content-start gap-2 rounded-card border p-4", tone === "success" ? "border-success/25" : "border-danger/25")}>
<div className="flex flex-wrap items-center justify-between gap-2">
<h3 className="text-[0.9375rem] font-semibold text-fg">{title}</h3>
<Badge tone={tone} dot={false}>{tone === "success" ? <CheckIcon size={13} /> : <AlertIcon size={13} />}{risk}</Badge>
</div>
<p className="text-sm leading-relaxed text-fg-muted">{text}</p>
</div>
);
}
function CellList({ items, risk, tone }: { items: string[]; risk: string; tone: "success" | "danger" }) {
return (
<div className="grid gap-2">
<ul className="grid gap-1 text-[0.8125rem] leading-snug text-fg-muted">
{items.map((i) => <li key={i} className="flex gap-2"><span aria-hidden="true" className="mt-[0.45rem] size-1 shrink-0 rounded-full bg-fg-subtle" />{i}</li>)}
</ul>
<span><Badge tone={tone} dot={false}>{tone === "success" ? <CheckIcon size={12} /> : <AlertIcon size={12} />}{risk}</Badge></span>
</div>
);
}
/* ---------- Estados ---------- */
function Loading() {
return <p role="status" className="flex items-center gap-2 text-sm text-fg-muted"><Spinner />Carregando…</p>;
}
function LoadError({ text, onRetry }: { text: string; onRetry: () => void }) {
return (
<div className="grid justify-items-start gap-3">
<Feedback ok={false}>{text}</Feedback>
<Button variant="secondary" size="sm" onClick={onRetry}><RefreshIcon size={15} />Tentar de novo</Button>
</div>
);
}
+141
View File
@@ -0,0 +1,141 @@
"use client";
// Barra lateral: recolhida em 72 px (só ícones) e expandida POR CIMA do conteúdo ao passar o mouse
// ou ao navegar pelo teclado (regras .rail em globals.css). Os rótulos ficam sempre no DOM, então
// leitores de tela os leem mesmo com a barra recolhida.
// Geometria recolhida: cada item tem 48 px (72 − 2×12) e o ícone de 20 px fica em x 26–46, ou seja,
// centrado na barra. Por isso os itens nunca podem crescer com o rótulo: a lista é flex em coluna
// (uma trilha de grid "auto" cresceria até a largura do texto e empurraria o fundo do item ativo
// para fora da barra) e o rótulo pode transbordar, invisível, dentro do item.
// Em tela baixa (1024×768) a barra rola na vertical, para Configurações (no rodapé) não ficar cortada.
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState, type ComponentType } from "react";
import { ChartIcon, CubeIcon, FilmIcon, MicIcon, PublishIcon, ScissorsIcon, SettingsIcon, SparkIcon, TerminalIcon, UsersIcon } from "./icons";
import { LogoMark, Wordmark } from "./logo";
import { getSummary } from "./publishing-client";
import { cx } from "./ui";
type NavItem = { href: string; label: string; hint: string; icon: ComponentType<{ size?: number }> };
/** Contador de "aguardando aprovação" no menu: relê a cada 30 s (só com a aba visível) e ao trocar de página. */
const SUMMARY_POLL_MS = 30_000;
const NAV: NavItem[] = [
{ href: "/dashboard", label: "Dashboard", hint: "O que funciona e o que não", icon: ChartIcon },
{ href: "/", label: "Histórias", hint: "Episódios e votação", icon: FilmIcon },
{ href: "/clipper", label: "Clipador", hint: "Cortes de live", icon: ScissorsIcon },
{ href: "/assets", label: "Assets", hint: "Biblioteca e envios", icon: CubeIcon },
{ href: "/voices", label: "Vozes", hint: "Narração e legenda", icon: MicIcon },
{ href: "/agent", label: "Agente", hint: "Claude e Codex", icon: TerminalIcon },
];
/** Depois do estúdio: onde as histórias vão ao ar. */
const DISTRIBUTION: NavItem[] = [
{ href: "/accounts", label: "Canais de publicação", hint: "YouTube, TikTok e Instagram", icon: UsersIcon },
{ href: "/publishing", label: "Publicações", hint: "Aprovar, agendar, acompanhar", icon: PublishIcon },
];
const SETTINGS: NavItem = { href: "/settings", label: "Configurações", hint: "Horários, apps e navegador", icon: SettingsIcon };
function useAwaitingCount(pathname: string): number | null {
const [count, setCount] = useState<number | null>(null);
useEffect(() => {
let cancelled = false;
const load = async () => {
if (document.visibilityState === "hidden") return;
const r = await getSummary();
if (!cancelled) setCount(r.ok ? r.data.awaitingApproval : null);
};
void load();
const timer = setInterval(load, SUMMARY_POLL_MS);
document.addEventListener("visibilitychange", load);
return () => { cancelled = true; clearInterval(timer); document.removeEventListener("visibilitychange", load); };
}, [pathname]);
return count;
}
function isActive(pathname: string, href: string): boolean {
return href === "/" ? pathname === "/" || pathname.startsWith("/stories") : pathname.startsWith(href);
}
export function Sidebar() {
const pathname = usePathname();
const awaiting = useAwaitingCount(pathname);
return (
<aside aria-label="Navegação"
className="rail fixed inset-y-0 left-0 z-50 flex flex-col overflow-x-hidden overflow-y-auto border-r border-line [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
<Link href="/" className="mx-3 mt-4 mb-6 flex h-12 shrink-0 items-center gap-3 rounded-control px-[0.5rem]">
<LogoMark size={32} className="shrink-0" />
<Wordmark className="rail-label whitespace-nowrap" />
<span className="sr-only">— início</span>
</Link>
{/* Ação principal do produto, sempre à mão */}
<Link href="/#nova-historia"
className="group mx-3 mb-5 flex h-11 min-w-0 shrink-0 items-center gap-3 overflow-hidden rounded-control border border-accent/30 bg-accent-soft px-[0.8125rem] text-accent transition-colors hover:border-accent/60 hover:bg-accent/15">
<SparkIcon size={20} />
<span className="rail-label whitespace-nowrap text-sm font-semibold">Nova história com IA</span>
</Link>
<div className="rail-label mx-6 mb-2 text-eyebrow font-semibold uppercase whitespace-nowrap text-fg-subtle" aria-hidden="true">Estúdio</div>
<nav aria-label="Principal" className="flex flex-col gap-1 px-3">
{NAV.map((item) => <NavLink key={item.href} item={item} active={isActive(pathname, item.href)} />)}
</nav>
{/* Separador: com a barra recolhida, só a linha marca a troca de grupo. */}
<div aria-hidden="true" className="mx-6 mt-5 mb-4 h-px shrink-0 bg-line" />
<div className="rail-label mx-6 mb-2 text-eyebrow font-semibold uppercase whitespace-nowrap text-fg-subtle" aria-hidden="true">Distribuição</div>
<nav aria-label="Distribuição" className="flex flex-col gap-1 px-3">
{DISTRIBUTION.map((item) => (
<NavLink key={item.href} item={item} active={isActive(pathname, item.href)}
count={item.href === "/publishing" ? awaiting : null} countLabel="aguardando aprovação" />
))}
</nav>
<nav aria-label="Ajustes" className="mt-auto flex flex-col gap-1 px-3 pt-4">
<NavLink item={SETTINGS} active={isActive(pathname, SETTINGS.href)} />
</nav>
<div className="mt-3 mb-20 flex items-center gap-3 px-[1.9375rem] text-xs text-fg-subtle">
<span className="relative flex size-2.5 shrink-0" aria-hidden="true">
<span className="absolute inset-0 rounded-full bg-success/40" />
<span className="relative m-[2px] size-1.5 rounded-full bg-success" />
</span>
<span className="rail-label whitespace-nowrap">Painel local · porta 4500</span>
</div>
</aside>
);
}
function NavLink({ item: { href, label, hint, icon: Icon }, active, count = null, countLabel }: {
item: NavItem; active: boolean;
/** Número ao lado do ícone (some quando é 0 ou desconhecido). */
count?: number | null; countLabel?: string;
}) {
const showCount = count !== null && count > 0;
return (
<Link href={href} aria-current={active ? "page" : undefined}
className={cx(
"relative flex h-12 min-w-0 shrink-0 items-center gap-3 overflow-hidden rounded-control px-3.5 transition-colors",
active ? "bg-raised text-fg" : "text-fg-muted hover:bg-raised/70 hover:text-fg",
)}>
<span aria-hidden="true"
className={cx("absolute top-3 bottom-3 left-0 w-[3px] rounded-r-full bg-accent transition-opacity", active ? "opacity-100" : "opacity-0")} />
<span className={cx("relative shrink-0", active && "text-accent")}>
<Icon size={20} />
{/* Com a barra recolhida o número fica no canto do ícone; o texto completo vai para leitores de tela. */}
{showCount && (
<span aria-hidden="true"
className="absolute -top-2 -right-2.5 grid h-4 min-w-4 place-items-center rounded-full bg-accent px-1 text-[0.625rem] leading-none font-bold text-accent-fg tabular-nums">
{count > 99 ? "99+" : count}
</span>
)}
</span>
<span className="rail-label grid min-w-0 whitespace-nowrap leading-tight">
<span className="text-sm font-medium">{label}</span>
<span className="text-[0.6875rem] text-fg-subtle">{hint}</span>
</span>
{showCount && <span className="sr-only">: {count} {countLabel}</span>}
</Link>
);
}
+144
View File
@@ -0,0 +1,144 @@
"use client";
// "Nova história com IA": o criador cola uma ideia, sinopse ou rascunho e a IA monta título,
// bíblia e ep01. Usa a server action createStoryFromTextAction; em sucesso, ela redireciona para
// o console do agente (/agent?run=<id>), onde o progresso aparece ao vivo.
import { useActionState, useState } from "react";
import { createStoryFromTextAction } from "@/app/actions";
import type { Provider, StoryKind } from "@/lib/types";
import { BranchCountField, StoryFormatSelect } from "./forms";
import { BookIcon, CheckIcon, PenIcon, SparkIcon, TerminalIcon } from "./icons";
import { DEFAULT_STORY_FORMAT } from "./story-formats";
import { Button, ChoiceGroup, Feedback, Input, Kbd, Select, Spinner, Textarea, cx } from "./ui";
const MIN_CHARS = 20;
const MAX_CHARS = 20_000;
const PROVIDER_NAME: Record<Provider, string> = { codex: "GPT · Codex", claude: "Claude" };
export function StoryComposer({ autoProvider, available, models }: {
/** Agente que o modo automático vai usar agora (Codex, se estiver instalado). */
autoProvider: Provider;
available: Record<Provider, boolean>;
/** Modelos de cada agente (o do Codex vem do cache da própria CLI). */
models: Record<Provider, { id: string; label: string }[]>;
}) {
const [state, action, pending] = useActionState(createStoryFromTextAction, null);
const [length, setLength] = useState(0);
const [provider, setProvider] = useState<"" | "claude">("");
const [kind, setKind] = useState<StoryKind>(DEFAULT_STORY_FORMAT);
const [model, setModel] = useState("");
const short = length > 0 && length < MIN_CHARS;
const engine: Provider = provider === "claude" ? "claude" : autoProvider;
const documentary = kind === "documentary";
return (
<section id="nova-historia" aria-labelledby="nova-historia-titulo"
className="flame-frame scroll-mt-10 overflow-hidden rounded-panel bg-surface shadow-card">
{/* Brilho de fundo: chama no canto superior */}
<div aria-hidden="true" className="pointer-events-none absolute -top-40 -right-24 -z-10 size-[28rem] rounded-full bg-accent/10 blur-3xl" />
<div aria-hidden="true" className="pointer-events-none absolute -top-24 right-64 -z-10 size-72 rounded-full bg-flame/8 blur-3xl" />
<form action={action} className="grid lg:grid-cols-[minmax(0,1fr)_19rem]">
<fieldset disabled={pending} className="grid min-w-0 gap-6 p-8 max-lg:p-6">
<div className="grid gap-3">
<div className="flex flex-wrap items-center gap-2.5">
<span className="inline-flex h-7 items-center gap-1.5 rounded-full border border-accent/30 bg-accent-soft px-3 text-xs font-semibold text-accent">
<SparkIcon size={14} />Nova história com IA
</span>
<span className="inline-flex h-7 items-center gap-1.5 rounded-full border border-line-strong bg-raised px-3 text-xs font-medium text-fg-muted">
Enredo com <span className="font-semibold text-fg">{PROVIDER_NAME[engine]}</span>
</span>
</div>
<h2 id="nova-historia-titulo" className="font-display text-[1.875rem] leading-tight font-semibold tracking-[-0.025em] text-fg">
Do texto à <span className="text-flame">história pronta</span>
</h2>
<p className="max-w-xl text-[0.9375rem] leading-relaxed text-fg-muted">
Cole uma ideia, uma sinopse ou um rascunho. A IA escreve o título, a bíblia da história e o roteiro do ep01 sozinha.
</p>
</div>
<div className="grid gap-2">
<label htmlFor="story-text" className="sr-only">Ideia, sinopse ou rascunho da história</label>
<div className="relative">
<Textarea id="story-text" name="text" required rows={7} maxLength={MAX_CHARS}
onChange={(e) => setLength(e.target.value.trim().length)}
onKeyDown={(e) => { if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) e.currentTarget.form?.requestSubmit(); }}
aria-describedby="story-text-count"
className="min-h-44 bg-sunken/80 pb-10 text-[0.9375rem]"
placeholder={documentary
? "Ex.: A Ilha da Queimada Grande, no litoral de São Paulo: por que é proibido desembarcar, a jararaca-ilhoa e o que é mito ou verdade. Tom de curiosidade, para um canal de curiosidades."
: "Ex.: Um entregador de aplicativo recebe um pacote sem remetente. Toda vez que tenta entregá-lo, o endereço muda. Tom de suspense leve, com humor; cada episódio termina numa escolha do público."} />
<div id="story-text-count" aria-live="polite"
className={cx("pointer-events-none absolute right-3.5 bottom-3 text-xs tabular-nums", short ? "text-warning" : "text-fg-subtle")}>
{short ? `faltam ${MIN_CHARS - length} caracteres` : `${length.toLocaleString("pt-BR")} / 20.000`}
</div>
</div>
</div>
<div className="grid gap-5 md:grid-cols-2">
<label className="grid content-start gap-2">
<span className="text-[0.8125rem] font-medium text-fg-muted">Título <span className="font-normal text-fg-subtle">(opcional)</span></span>
<Input name="title" placeholder="A IA sugere, se ficar vazio" maxLength={120} />
</label>
<StoryFormatSelect value={kind} onChange={setKind} />
<BranchCountField enabled={kind === "interactive"} />
<ChoiceGroup name="provider" legend="Quem escreve" value={provider}
onChange={(next) => { setProvider(next); setModel(""); }}
options={[
{ value: "", label: autoProvider === "codex" ? "GPT · Codex" : "Automático" },
{ value: "claude", label: "Claude", disabled: !available.claude },
]} />
<label className="grid content-start gap-2">
<span className="text-[0.8125rem] font-medium text-fg-muted">Modelo</span>
<Select name="model" value={model} onChange={(e) => setModel(e.target.value)} disabled={models[engine].length < 2}>
{models[engine].map((m) => <option key={m.id} value={m.id}>{m.label}</option>)}
</Select>
</label>
</div>
{!available.codex && (
<p className="text-xs text-warning">O Codex não está instalado aqui: o modo automático vai usar o Claude. Instale com <code>npm install -g @openai/codex</code> e rode <code>codex login</code>.</p>
)}
<div className="flex flex-wrap items-center gap-x-5 gap-y-3 border-t border-line pt-6">
<Button type="submit" variant="flame" size="lg" className="min-w-52">
{pending ? <><Spinner />Enviando para a IA…</> : <><SparkIcon size={18} />Criar história com IA</>}
</Button>
<span className="text-xs text-fg-subtle">Você acompanha a escrita ao vivo no console do agente.</span>
</div>
{state?.error && <Feedback ok={false}>{state.error}</Feedback>}
</fieldset>
<aside aria-label="O que a IA entrega" className="grid content-start gap-5 border-line bg-sunken/40 p-8 max-lg:border-t max-lg:p-6 lg:border-l">
<div className="text-eyebrow font-semibold uppercase text-fg-subtle">O que você recebe</div>
<ol className="grid gap-4">
<Deliverable icon={<PenIcon size={16} />} title="Título e premissa">Um nome forte e a premissa em uma frase.</Deliverable>
{documentary ? <>
<Deliverable icon={<BookIcon size={16} />} title="Ficha de pauta">Fatos conferidos, cada um com a fonte, e os mitos a desmentir.</Deliverable>
<Deliverable icon={<CheckIcon size={16} />} title="Roteiro do vídeo">Gancho, cena a cena, texto na tela e fontes.</Deliverable>
</> : <>
<Deliverable icon={<BookIcon size={16} />} title="Bíblia da história">Personagens, tom, regras do mundo e arco.</Deliverable>
<Deliverable icon={<CheckIcon size={16} />} title="Roteiro do ep01">Pronto para virar cena{kind === "interactive" ? ", com a escolha do público" : ""}.</Deliverable>
</>}
<Deliverable icon={<TerminalIcon size={16} />} title="Acompanhamento ao vivo">Cada passo da IA aparece no console.</Deliverable>
</ol>
<p className="mt-auto text-xs leading-relaxed text-fg-subtle">
Dica: quanto mais detalhes de tom, público e virada, melhor o primeiro rascunho. Envie com <Kbd>Ctrl</Kbd> + <Kbd>Enter</Kbd>.
</p>
</aside>
</form>
</section>
);
}
function Deliverable({ icon, title, children }: { icon: React.ReactNode; title: string; children: React.ReactNode }) {
return (
<li className="flex gap-3">
<span className="mt-0.5 grid size-8 shrink-0 place-items-center rounded-lg border border-line-strong bg-raised text-accent">{icon}</span>
<span className="grid gap-0.5">
<span className="text-sm font-semibold text-fg">{title}</span>
<span className="text-xs leading-relaxed text-fg-subtle">{children}</span>
</span>
</li>
);
}
+562
View File
@@ -0,0 +1,562 @@
"use client";
// Fluxo da história (estilo n8n): cada episódio é um nó, cada opção da votação é uma aresta.
// Só leitura: o layout é calculado aqui (árvore da esquerda para a direita), sem arrastar nem ligar nós.
// Clicar num nó abre o painel ao lado com arquivos, opções da decisão e ações (abrir, preparar vertentes).
//
// Dados: GET /api/stories/{id}/flow (o primeiro vem do servidor, para não piscar). Enquanto algum nó
// estiver com as vertentes na fila ou em preparo, refaz o GET a cada 4 s.
import "@xyflow/react/dist/style.css";
import {
Background, BackgroundVariant, BaseEdge, Controls, EdgeLabelRenderer, Handle, MarkerType, MiniMap, Position, ReactFlow,
ReactFlowProvider, getBezierPath, useReactFlow, type Edge, type EdgeProps, type Node, type NodeProps,
} from "@xyflow/react";
import Link from "next/link";
import { useCallback, useEffect, useMemo, useRef, useState, type FocusEvent, type ReactNode, type UIEvent } from "react";
import type { FlowEdge, FlowNode, StoryFlow } from "@/lib/flow";
import type { Choice, StoryKind } from "@/lib/types";
import { BranchesStatusBadge } from "./forms";
import { CheckIcon, FilmIcon, FlowIcon, RefreshIcon, SparkIcon, TerminalIcon, XIcon } from "./icons";
import {
Badge, Button, CHOICE_STYLE, ChoiceChip, EmptyState, Feedback, LinkButton, Spinner, StagePipeline, cx,
} from "./ui";
import { askConfirm } from "./confirm-dialog";
/* ---------- Geometria ---------- */
const NODE_W = 252;
const NODE_H = 136;
/** Espaço entre colunas: cabe o rótulo da opção (letra + texto) antes do nó de destino. */
const COL_GAP = 210;
const LINEAR_GAP = 72;
const ROW_GAP = 32;
const ROOT_GAP = 72;
type Point = { x: number; y: number };
/**
* Árvore da esquerda para a direita: cada nível numa coluna, vertentes empilhadas. As folhas ocupam
* linhas em sequência e cada pai fica centrado entre o primeiro e o último filho.
*/
function treeLayout(nodes: FlowNode[], edges: FlowEdge[]): Map<string, Point> {
const children = new Map<string, string[]>();
const order = new Map(edges.map((e) => [e.target, e.choice]));
for (const e of edges) children.set(e.source, [...(children.get(e.source) ?? []), e.target]);
for (const list of children.values()) list.sort((a, b) => (order.get(a) ?? "").localeCompare(order.get(b) ?? ""));
const targets = new Set(edges.map((e) => e.target));
const roots = nodes.filter((n) => !targets.has(n.id)).sort((a, b) => a.number - b.number);
const positions = new Map<string, Point>();
let nextY = 0;
const place = (id: string, depth: number): number => {
if (positions.has(id)) return positions.get(id)!.y; // proteção contra ciclo
positions.set(id, { x: depth * (NODE_W + COL_GAP), y: 0 });
const kids = (children.get(id) ?? []).filter((k) => !positions.has(k));
let y: number;
if (kids.length === 0) {
y = nextY;
nextY += NODE_H + ROW_GAP;
} else {
const ys = kids.map((k) => place(k, depth + 1));
y = (ys[0] + ys[ys.length - 1]) / 2;
}
positions.get(id)!.y = y;
return y;
};
roots.forEach((r, i) => {
if (i > 0) nextY += ROOT_GAP;
place(r.id, 0);
});
// Nós soltos (não deveria haver): numa linha abaixo.
for (const n of nodes) {
if (!positions.has(n.id)) {
positions.set(n.id, { x: (n.number - 1) * (NODE_W + COL_GAP), y: nextY });
nextY += NODE_H + ROW_GAP;
}
}
return positions;
}
/** História linear: a sequência simples, em linha, ligada em ordem. */
function linearLayout(nodes: FlowNode[]): { positions: Map<string, Point>; edges: ChoiceFlowEdge[] } {
const sorted = [...nodes].sort((a, b) => a.number - b.number);
const positions = new Map(sorted.map((n, i) => [n.id, { x: i * (NODE_W + LINEAR_GAP), y: 0 }]));
const edges = sorted.slice(1).map((n, i): ChoiceFlowEdge => ({
id: `seq-${sorted[i].id}-${n.id}`, source: sorted[i].id, target: n.id, type: "choice",
data: { choice: null, label: "", state: "open" },
markerEnd: { type: MarkerType.ArrowClosed, color: EDGE_COLOR.open, width: 16, height: 16 },
}));
return { positions, edges };
}
/* ---------- Nós e arestas ---------- */
type EpisodeNodeData = { node: FlowNode; selected: boolean };
type EpisodeFlowNode = Node<EpisodeNodeData, "episode">;
type ChoiceEdgeData = { choice: Choice | null; label: string; state: FlowEdge["state"] };
type ChoiceFlowEdge = Edge<ChoiceEdgeData, "choice">;
const EDGE_COLOR: Record<FlowEdge["state"], string> = {
winner: "var(--color-accent)",
open: "var(--color-fg-subtle)",
lost: "var(--color-fg-subtle)",
};
const STATUS_LABEL: Record<FlowNode["status"], string> = { main: "principal", candidate: "candidata", discarded: "descartada" };
function nodeCode(n: FlowNode): string {
return n.fileKey.toUpperCase();
}
function EpisodeNodeView({ data }: NodeProps<EpisodeFlowNode>) {
const { node: n, selected } = data;
const votes = n.decision ? Object.values(n.decision.votes).reduce((sum, v) => sum + (v ?? 0), 0) : 0;
return (
<>
<Handle type="target" position={Position.Left} isConnectable={false} />
{/* O clique (mouse ou Enter/Espaço no botão) sobe até o nó e chega ao onNodeClick do canvas. */}
<button type="button" aria-pressed={selected}
aria-label={`${nodeCode(n)}: ${n.title || "sem título"}, ${STATUS_LABEL[n.status]}, etapa ${n.stage}${n.isStart ? ", início" : ""}`}
style={{ width: NODE_W, height: NODE_H }}
className={cx(
"nodrag nopan relative grid cursor-pointer grid-rows-[auto_auto_1fr_auto] gap-2 rounded-card border px-4 py-3.5 text-left transition-[border-color,background-color,opacity,box-shadow]",
n.status === "main" && "border-line-strong bg-surface shadow-card hover:border-fg-subtle/60",
n.status === "candidate" && "border-dashed border-fg-subtle/60 bg-canvas/90 hover:border-fg-muted",
n.status === "discarded" && "border-dashed border-line-strong bg-surface/60 opacity-50 hover:opacity-80",
n.isStart && n.status === "main" && "border-accent/60 shadow-glow",
selected && "outline-2 outline-offset-3 outline-accent",
)}>
{n.isStart && (
<span className="absolute -top-2.5 left-4 rounded-full border border-accent/40 bg-accent px-2 py-0.5 text-[0.625rem] font-bold tracking-[0.12em] text-accent-fg uppercase">
Início
</span>
)}
<span className="flex items-center gap-2">
{n.choice && <ChoiceChip letter={n.choice} size="sm" />}
<span className="font-mono text-[0.8125rem] font-semibold text-fg-muted">{nodeCode(n)}</span>
<span className="ml-auto text-[0.6875rem] text-fg-subtle">{STATUS_LABEL[n.status]}</span>
</span>
<span className="truncate font-display text-[0.9375rem] leading-tight font-semibold text-fg" title={n.title || undefined}>
{n.title || <span className="text-fg-subtle">Sem título</span>}
</span>
<StagePipeline stage={n.stage} className="self-start [&>div>span]:w-4" />
<span className="flex min-w-0 items-center gap-1.5">
{n.decision ? (
<Badge tone={CHOICE_STYLE[n.decision.winner].tone} className="h-5 px-2 text-[0.6875rem]">
venceu {n.decision.winner}{n.decision.method === "manual" ? " (manual)" : ` · ${votes} voto${votes === 1 ? "" : "s"}`}
</Badge>
) : n.branchesStatus !== "none" ? (
<BranchesStatusBadge status={n.branchesStatus} className="h-5 px-2 text-[0.6875rem]" />
) : (
<span className="text-[0.6875rem] text-fg-subtle">{n.choices.length ? `${n.choices.length} opções` : " "}</span>
)}
</span>
</button>
<Handle type="source" position={Position.Right} isConnectable={false} />
</>
);
}
function ChoiceEdgeView({ id, sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition, data, markerEnd }: EdgeProps<ChoiceFlowEdge>) {
const [path] = getBezierPath({ sourceX, sourceY, sourcePosition, targetX, targetY, targetPosition });
const state = data?.state ?? "open";
return (
<>
<BaseEdge id={id} path={path} markerEnd={markerEnd}
style={{
stroke: EDGE_COLOR[state],
strokeWidth: state === "winner" ? 2.5 : 1.5,
strokeDasharray: state === "lost" ? "6 5" : undefined,
opacity: state === "lost" ? 0.5 : 1,
}} />
{data?.choice && (
<EdgeLabelRenderer>
{/* Rótulo na entrada do nó de destino, acima da linha: cada vertente tem o seu, sem sobrepor. */}
<div title={data.label ? `${data.choice}: ${data.label}` : `Opção ${data.choice}`}
style={{ position: "absolute", transform: `translate(-100%, -100%) translate(${targetX - 14}px, ${targetY - 5}px)`, pointerEvents: "all" }}
className={cx("nodrag nopan flex max-w-[11.5rem] items-center gap-1.5 rounded-lg border px-1.5 py-1 text-[0.6875rem] leading-tight",
state === "winner" ? "border-accent/50 bg-accent-soft text-fg" : "border-line-strong bg-raised text-fg-muted",
state === "lost" && "opacity-55")}>
<ChoiceChip letter={data.choice} size="sm" solid={state === "winner"} />
<span className="truncate">{data.label || `Opção ${data.choice}`}</span>
</div>
</EdgeLabelRenderer>
)}
</>
);
}
const NODE_TYPES = { episode: EpisodeNodeView };
const EDGE_TYPES = { choice: ChoiceEdgeView };
/** Rótulos dos controles da biblioteca em pt-BR. */
const ARIA_LABELS = {
"controls.ariaLabel": "Controles do fluxo",
"controls.zoomIn.ariaLabel": "Aproximar",
"controls.zoomOut.ariaLabel": "Afastar",
"controls.fitView.ariaLabel": "Encaixar na tela",
"controls.interactive.ariaLabel": "Travar ou destravar",
"minimap.ariaLabel": "Minimapa do fluxo",
};
/* ---------- Componente ---------- */
export function StoryFlowView({ initial }: { initial: StoryFlow }) {
const [flow, setFlow] = useState(initial);
const [selectedId, setSelectedId] = useState<string | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [refreshing, setRefreshing] = useState(false);
const busy = flow.nodes.some((n) => n.branchesStatus === "queued" || n.branchesStatus === "running");
const refresh = useCallback(async () => {
setRefreshing(true);
try {
const res = await fetch(`/api/stories/${encodeURIComponent(initial.storyId)}/flow`, { cache: "no-store" });
const body = (await res.json()) as StoryFlow | { error: string };
if ("error" in body) throw new Error(body.error);
setFlow(body);
setLoadError(null);
} catch (error) {
setLoadError(error instanceof Error ? error.message : "Não foi possível atualizar o fluxo.");
} finally {
setRefreshing(false);
}
}, [initial.storyId]);
// Vertentes na fila ou em preparo: acompanha a cada 4 s até terminar.
useEffect(() => {
if (!busy) return;
const timer = window.setTimeout(refresh, 4000);
return () => window.clearTimeout(timer);
}, [busy, flow, refresh]);
const selected = flow.nodes.find((n) => n.id === selectedId) ?? null;
if (flow.nodes.length === 0) {
return (
<EmptyState icon={<FlowIcon />} title="Crie o primeiro episódio"
action={<LinkButton variant="primary" href={`/stories/${flow.storyId}`}><FilmIcon size={16} />Ir para Episódios</LinkButton>}>
O fluxo nasce do ep01. Na aba Episódios, crie o primeiro episódio; depois cada decisão do público abre as vertentes aqui.
</EmptyState>
);
}
return (
<section aria-label="Fluxo da história" className="grid gap-4">
<div className="flex flex-wrap items-center justify-between gap-x-6 gap-y-3">
<Legend kind={flow.kind} />
<div className="flex items-center gap-3 text-xs text-fg-subtle">
{busy && <span className="inline-flex items-center gap-1.5 text-info" role="status"><Spinner className="size-3" />Vertentes em preparo · atualiza a cada 4 s</span>}
<span>{flow.nodes.length} {flow.nodes.length === 1 ? "nó" : "nós"}{flow.kind === "interactive" ? ` · ${flow.branchCount} vertentes por decisão` : ""}</span>
<Button variant="ghost" size="sm" onClick={refresh} disabled={refreshing} aria-label="Atualizar o fluxo">
{refreshing ? <Spinner className="size-3.5" /> : <RefreshIcon size={15} />}Atualizar
</Button>
</div>
</div>
{loadError && <Feedback ok={false}>{loadError}</Feedback>}
{/* Canvas em largura total; o painel do nó abre por cima, à direita (abaixo, em tela estreita). */}
<ReactFlowProvider>
<div className="relative grid gap-4">
<FlowCanvas flow={flow} selectedId={selectedId} onSelect={setSelectedId} />
{selected ? (
<aside aria-label="Detalhes do episódio"
className="z-10 rounded-card border border-line-strong bg-surface shadow-pop md:absolute md:top-3 md:right-3 md:bottom-3 md:w-[22rem] md:overflow-y-auto">
<NodeInspector key={selected.id} node={selected} flow={flow} onClose={() => setSelectedId(null)} onChanged={refresh} />
</aside>
) : (
<p className="text-xs text-fg-subtle">
Clique num episódio para ver roteiro, cena, opções da decisão e ações. Arraste o fundo para mover; role ou use os controles para aproximar.
</p>
)}
</div>
</ReactFlowProvider>
</section>
);
}
function FlowCanvas({ flow, selectedId, onSelect }: { flow: StoryFlow; selectedId: string | null; onSelect: (id: string | null) => void }) {
const wrapperRef = useRef<HTMLDivElement>(null);
const { getNode, getViewport, setCenter } = useReactFlow();
// Foco por teclado num nó fora da vista: o navegador "rolaria" o contêiner overflow:hidden e
// desalinharia o canvas. Desfaz a rolagem e, em vez dela, centraliza o nó mantendo o zoom.
function onScrollCapture(e: UIEvent<HTMLDivElement>) {
const target = e.target as HTMLElement;
if (target.scrollTop || target.scrollLeft) {
target.scrollTop = 0;
target.scrollLeft = 0;
}
}
function onFocusCapture(e: FocusEvent<HTMLDivElement>) {
const id = (e.target as HTMLElement).closest(".react-flow__node")?.getAttribute("data-id");
const node = id ? getNode(id) : undefined;
const box = wrapperRef.current?.getBoundingClientRect();
if (!node || !box) return;
const { x, y, zoom } = getViewport();
const left = node.position.x * zoom + x;
const top = node.position.y * zoom + y;
const inside = left >= 0 && top >= 0 && left + NODE_W * zoom <= box.width && top + NODE_H * zoom <= box.height;
if (!inside) void setCenter(node.position.x + NODE_W / 2, node.position.y + NODE_H / 2, { zoom, duration: 200 });
}
// A aba Fluxo pode montar escondida (as abas ficam montadas): só desenha quando o canvas tem tamanho,
// senão o "encaixar na tela" inicial calcula com 0 px.
const [visible, setVisible] = useState(false);
useEffect(() => {
const el = wrapperRef.current;
if (!el) return;
const check = () => { if (el.offsetWidth > 0) setVisible(true); };
check();
const observer = new ResizeObserver(check);
observer.observe(el);
return () => observer.disconnect();
}, []);
const { nodes, edges } = useMemo(() => {
const linear = flow.kind !== "interactive" || flow.edges.length === 0;
const built = linear ? linearLayout(flow.nodes) : { positions: treeLayout(flow.nodes, flow.edges), edges: null };
const nodes: EpisodeFlowNode[] = flow.nodes.map((n) => ({
id: n.id, type: "episode", position: built.positions.get(n.id) ?? { x: 0, y: 0 },
width: NODE_W, height: NODE_H, draggable: false, connectable: false,
data: { node: n, selected: n.id === selectedId },
}));
const edges: ChoiceFlowEdge[] = built.edges ?? flow.edges.map((e) => ({
id: e.id, source: e.source, target: e.target, type: "choice",
data: { choice: e.choice, label: e.label, state: e.state },
markerEnd: { type: MarkerType.ArrowClosed, color: EDGE_COLOR[e.state], width: 16, height: 16 },
}));
return { nodes, edges };
}, [flow, selectedId]);
return (
<div ref={wrapperRef} onKeyDown={(e) => { if (e.key === "Escape") onSelect(null); }}
onScrollCapture={onScrollCapture} onFocusCapture={onFocusCapture}
className="relative h-[min(72vh,46rem)] min-h-[26rem] overflow-hidden rounded-card border border-line bg-sunken/50 shadow-card max-md:h-[62vh]">
{visible && (
<ReactFlow<EpisodeFlowNode, ChoiceFlowEdge>
className="cf-flow"
nodes={nodes} edges={edges} nodeTypes={NODE_TYPES} edgeTypes={EDGE_TYPES}
forceColorMode="dark"
nodesDraggable={false} nodesConnectable={false} nodesFocusable={false} edgesFocusable={false} elementsSelectable={false}
fitView fitViewOptions={{ padding: 0.18, maxZoom: 1 }} minZoom={0.2} maxZoom={1.6}
onNodeClick={(_, node) => onSelect(node.id === selectedId ? null : node.id)}
onPaneClick={() => onSelect(null)}
attributionPosition="top-right"
ariaLabelConfig={ARIA_LABELS}>
<Background variant={BackgroundVariant.Dots} gap={22} size={1.2} />
<Controls showInteractive={false} position="bottom-left" fitViewOptions={{ padding: 0.18, maxZoom: 1 }} />
{!selectedId && <MiniMap<EpisodeFlowNode> pannable zoomable position="bottom-right" className="max-md:hidden"
style={{ width: 168, height: 112 }}
nodeBorderRadius={10}
nodeColor={(n) => n.data.node.isStart ? "var(--color-accent)"
: n.data.node.status === "main" ? "var(--color-fg-subtle)"
: n.data.node.status === "candidate" ? "var(--color-line-strong)" : "var(--color-raised)"} />}
<RefitOnGrowth count={nodes.length} />
</ReactFlow>
)}
</div>
);
}
/** Quando nós novos chegam (vertentes preparadas), reencaixa a vista para mostrá-los. */
function RefitOnGrowth({ count }: { count: number }) {
const { fitView } = useReactFlow();
const previous = useRef(count);
useEffect(() => {
// Espera os nós novos entrarem no estado interno antes de medir a vista.
if (count > previous.current) window.setTimeout(() => void fitView({ padding: 0.18, maxZoom: 1, duration: 300 }), 150);
previous.current = count;
}, [count, fitView]);
return null;
}
/* ---------- Painel lateral ---------- */
function NodeInspector({ node: n, flow, onClose, onChanged }: { node: FlowNode; flow: StoryFlow; onClose: () => void; onChanged: () => void }) {
const [pending, setPending] = useState(false);
const [result, setResult] = useState<{ ok: boolean; text: string; runId?: number | null } | null>(null);
const interactive = flow.kind === "interactive";
const scriptPath = `stories/${flow.storyId}/${n.fileKey}.md`;
const configPath = `config/${flow.storyId}-${n.fileKey}.json`;
const canPrepare = interactive && n.status === "main" && !n.decision;
const busy = n.branchesStatus === "queued" || n.branchesStatus === "running";
const regenerate = n.branchesStatus === "ready";
const runId = result?.runId ?? n.branchesRunId;
async function prepare() {
if (regenerate && !(await askConfirm({ title: "Gerar as vertentes de novo?",
message: "A IA reescreve opções, roteiros e cenas das vertentes deste episódio.", confirmLabel: "Gerar de novo" }))) return;
setPending(true);
setResult(null);
try {
const res = await fetch(`/api/episodes/${n.episodeId}/branches`, {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify(regenerate ? { regenerate: true } : {}),
});
const body = (await res.json()) as { error?: string; branchesStatus?: string; runId?: number | null };
if (!res.ok || body.error) {
setResult({ ok: false, text: body.error ?? "Não foi possível preparar as vertentes." });
} else {
setResult({
ok: true, runId: body.runId,
text: body.branchesStatus === "queued"
? "Vertentes na fila: a IA começa assim que terminar o trabalho atual."
: "A IA está preparando as vertentes (opções, roteiro e cena de cada uma).",
});
}
onChanged();
} catch {
setResult({ ok: false, text: "Sem resposta do painel. Ele está no ar?" });
} finally {
setPending(false);
}
}
return (
<div className="grid gap-6 p-6">
<header className="grid gap-2">
<div className="flex items-center gap-2">
{n.choice && <ChoiceChip letter={n.choice} size="sm" />}
<span className="font-mono text-sm font-semibold text-fg-muted">{nodeCode(n)}</span>
<Badge tone={n.status === "main" ? "accent" : "neutral"} dot={false}>{STATUS_LABEL[n.status]}</Badge>
{n.isStart && <Badge tone="accent" dot={false}>início</Badge>}
<button type="button" onClick={onClose} aria-label="Fechar detalhes"
className="ml-auto grid size-8 place-items-center rounded-control text-fg-subtle transition-colors hover:bg-raised hover:text-fg">
<XIcon size={16} />
</button>
</div>
<h3 className="font-display text-[1.125rem] leading-snug font-semibold text-fg">{n.title || <span className="text-fg-subtle">Sem título</span>}</h3>
<StagePipeline stage={n.stage} />
</header>
{n.choice && (
<InspectorSection title="Leva até aqui">
<p className="text-sm text-fg-muted">Opção {n.choice} do episódio anterior{n.choiceLabel ? <>: <span className="text-fg">{n.choiceLabel}</span></> : "."}</p>
</InspectorSection>
)}
<InspectorSection title="Arquivos">
<ul className="grid gap-2 text-sm">
<FileRow ok={n.hasScript} label="Roteiro" path={scriptPath} />
<FileRow ok={n.hasConfig} label="Cena" path={configPath} />
<FileRow ok={n.rendered} label="Vídeo renderizado" />
</ul>
</InspectorSection>
{interactive && (
<InspectorSection title="Decisão deste episódio">
{n.choices.length === 0 ? (
<p className="text-sm text-fg-subtle">Opções ainda não definidas. Elas saem do roteiro ou do preparo das vertentes.</p>
) : (
<ul className="grid gap-2">
{n.choices.map((c) => {
const won = n.decision?.winner === c.letter;
return (
<li key={c.letter} className={cx("flex items-start gap-2.5 rounded-control border px-3 py-2 text-sm",
won ? "border-accent/40 bg-accent-soft" : "border-line bg-raised/40", n.decision && !won && "opacity-60")}>
<ChoiceChip letter={c.letter} size="sm" solid={won} className="mt-0.5" />
<span className="min-w-0 flex-1 leading-snug text-fg">{c.label || `Opção ${c.letter}`}</span>
{n.decision && <span className="shrink-0 text-xs tabular-nums text-fg-subtle">{n.decision.votes[c.letter] ?? 0} voto(s)</span>}
</li>
);
})}
</ul>
)}
{n.decision && (
<p className="text-xs text-fg-subtle">Venceu {n.decision.winner} {n.decision.method === "manual" ? "por decisão manual" : "por votos"}.</p>
)}
</InspectorSection>
)}
{canPrepare && (
<InspectorSection title="Vertentes do próximo nível">
<div className="flex flex-wrap items-center gap-2.5">
<BranchesStatusBadge status={n.branchesStatus} />
{runId && n.branchesStatus !== "none" && (
<Link href={`/agent?run=${runId}`} className="inline-flex items-center gap-1.5 rounded text-xs font-medium text-fg-muted hover:text-fg hover:underline">
<TerminalIcon size={14} />ver no console
</Link>
)}
</div>
<Button variant={regenerate ? "secondary" : "primary"} disabled={pending || busy || !n.hasScript} onClick={prepare} className="justify-self-start">
{pending || busy ? <><Spinner />{n.branchesStatus === "queued" ? "Na fila…" : "Preparando…"}</>
: regenerate ? <><RefreshIcon size={16} />Gerar de novo</>
: <><SparkIcon size={16} />Preparar vertentes</>}
</Button>
{!n.hasScript && <p className="text-xs text-fg-subtle">Escreva o roteiro deste episódio antes de preparar as vertentes.</p>}
{result && (
<Feedback ok={result.ok}>
{result.text}
{result.ok && result.runId && <> <Link className="font-semibold underline" href={`/agent?run=${result.runId}`}>Acompanhar no console</Link></>}
</Feedback>
)}
</InspectorSection>
)}
<div className="grid gap-2 border-t border-line pt-5">
{n.status === "main" ? (
<LinkButton variant="primary" href={`/stories/${flow.storyId}/episodes/${n.number}`} className="justify-self-start">
<FilmIcon size={16} />Abrir episódio
</LinkButton>
) : (
<p className="text-xs leading-relaxed text-fg-subtle">
Vertente {n.status === "discarded" ? "descartada" : "ainda em votação"}: não tem página própria. Roteiro em <code>{scriptPath}</code>.
</p>
)}
</div>
</div>
);
}
function InspectorSection({ title, children }: { title: string; children: ReactNode }) {
return (
<section className="grid gap-3">
<h4 className="text-eyebrow font-semibold text-fg-subtle uppercase">{title}</h4>
{children}
</section>
);
}
function FileRow({ ok, label, path }: { ok: boolean; label: string; path?: string }) {
return (
<li className="flex items-start gap-2.5">
<span className={cx("mt-0.5 grid size-5 shrink-0 place-items-center rounded-full", ok ? "bg-success-soft text-success" : "bg-raised text-fg-subtle")}>
{ok ? <CheckIcon size={12} /> : <span aria-hidden="true" className="size-1.5 rounded-full bg-current" />}
</span>
<span className="grid min-w-0 gap-0.5">
<span className="text-fg">{label} <span className="text-xs text-fg-subtle">{ok ? "existe" : "ainda não"}</span></span>
{path && <code className="truncate text-[0.6875rem] text-fg-muted" title={path}>{path}</code>}
</span>
</li>
);
}
/* ---------- Legenda ---------- */
function Legend({ kind }: { kind: StoryKind }) {
return (
<ul aria-label="Legenda" className="flex flex-wrap items-center gap-x-5 gap-y-2 text-xs text-fg-muted">
<LegendItem swatch={<span className="h-3.5 w-5 rounded border border-accent/60 bg-surface shadow-[0_0_0_1px_rgb(255_122_26/0.35)]" />}>início</LegendItem>
<LegendItem swatch={<span className="h-3.5 w-5 rounded border border-line-strong bg-overlay" />}>principal</LegendItem>
{kind === "interactive" && <>
<LegendItem swatch={<span className="h-3.5 w-5 rounded border border-dashed border-fg-subtle" />}>candidata</LegendItem>
<LegendItem swatch={<span className="h-3.5 w-5 rounded border border-dashed border-line-strong bg-surface opacity-50" />}>descartada</LegendItem>
<span aria-hidden="true" className="h-4 w-px bg-line-strong" />
<LegendItem swatch={<EdgeSwatch color="var(--color-accent)" width={2.5} />}>vencedora</LegendItem>
<LegendItem swatch={<EdgeSwatch color="var(--color-fg-subtle)" width={1.5} />}>em votação</LegendItem>
<LegendItem swatch={<EdgeSwatch color="var(--color-fg-subtle)" width={1.5} dashed faded />}>perdeu</LegendItem>
</>}
</ul>
);
}
function LegendItem({ swatch, children }: { swatch: ReactNode; children: ReactNode }) {
return <li className="flex items-center gap-2">{swatch}<span>{children}</span></li>;
}
function EdgeSwatch({ color, width, dashed, faded }: { color: string; width: number; dashed?: boolean; faded?: boolean }) {
return (
<svg width="24" height="8" aria-hidden="true" className="shrink-0" style={{ opacity: faded ? 0.5 : 1 }}>
<line x1="1" y1="4" x2="23" y2="4" stroke={color} strokeWidth={width} strokeDasharray={dashed ? "4 3" : undefined} strokeLinecap="round" />
</svg>
);
}
+37
View File
@@ -0,0 +1,37 @@
// Lista central dos formatos de história. Para um formato novo, acrescente aqui (e o id no tipo
// StoryKind do servidor): os formulários de criação leem desta lista, sem mexer nos componentes.
import type { StoryKind } from "@/lib/types";
export type StoryFormat = { id: StoryKind; label: string; shortLabel: string; description: string };
export const STORY_FORMATS: StoryFormat[] = [
{ id: "interactive", label: "Interativa (votação)", shortLabel: "interativa", description: "O público vota nos comentários, entre 2 e 4 opções, e decide o rumo do próximo episódio." },
{ id: "linear", label: "Linear", shortLabel: "linear", description: "Episódios de ficção em sequência, sem votação." },
{ id: "documentary", label: "Documental (fatos reais)", shortLabel: "documental", description: "Vídeo único sobre um tema real: cita cidades, lugares e instituições pelo nome, com fatos conferidos em fontes." },
];
export const DEFAULT_STORY_FORMAT: StoryKind = "interactive";
/**
* Como a interface chama a unidade da história. Série (interativa, linear): episódio, ep01, ep02.
* Documental: é um vídeo só, então "vídeo" (e "vídeo 2" se um dia houver uma parte 2).
*/
export type UnitTerms = { one: string; One: string; many: string; Many: string; code: (n: number) => string };
const EPISODE_TERMS: UnitTerms = {
one: "episódio", One: "Episódio", many: "episódios", Many: "Episódios",
code: (n) => `ep${String(n).padStart(2, "0")}`,
};
const VIDEO_TERMS: UnitTerms = {
one: "vídeo", One: "Vídeo", many: "vídeos", Many: "Vídeos",
code: (n) => (n === 1 ? "vídeo" : `vídeo ${n}`),
};
export function unitTerms(kind: StoryKind | undefined): UnitTerms {
return kind === "documentary" ? VIDEO_TERMS : EPISODE_TERMS;
}
/** Rótulo curto do formato ("interativa", "linear", "documental") para badges e listas. */
export function storyFormatLabel(kind: StoryKind): string {
return STORY_FORMATS.find((f) => f.id === kind)?.shortLabel ?? kind;
}
+185
View File
@@ -0,0 +1,185 @@
"use client";
// Abas do design system: ícone + rótulo (+ contador opcional), sublinhado que desliza até a aba ativa,
// teclado no padrão WAI-ARIA (←/→, Home/End, roving tabindex) e aba ativa na URL (?tab=…).
//
// Uso:
// <Tabs label="Seções de vozes" items={[{ id: "geral", label: "Geral", icon: <GaugeIcon /> }, …]}
// panels={{ geral: <…/>, catalogo: <…/> }} />
//
// - URL: clique e Enter gravam com pushState (o "voltar" do navegador volta de aba, sem recarregar);
// setas/Home/End usam replaceState, para não encher o histórico ao percorrer as abas.
// A aba padrão não aparece na URL. Passe `param={null}` para abas só locais (sem URL).
// - Painéis ficam montados e só os inativos levam `hidden`: áudio tocando, formulário preenchido e
// envio em andamento continuam vivos ao trocar de aba.
// - `useSearchParams` exige um <Suspense> acima: o próprio componente cria um, com a aba padrão de
// fallback, então quem usa não precisa se preocupar.
import { Suspense, useCallback, useId, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { useSearchParams } from "next/navigation";
import { cx } from "./ui";
export type TabItem<T extends string> = {
id: T;
label: string;
icon?: ReactNode;
/** Contador ao lado do rótulo (ex.: número de vozes). */
count?: number;
};
type TabsProps<T extends string> = {
/** Nome acessível da lista de abas (lido por leitores de tela). */
label: string;
items: TabItem<T>[];
panels: Record<T, ReactNode>;
/** Parâmetro da URL; `null` = abas só locais. Padrão: "tab". */
param?: string | null;
/** Aba sem parâmetro na URL. Padrão: a primeira. */
defaultTab?: T;
className?: string;
};
export function Tabs<T extends string>({ param = "tab", ...props }: TabsProps<T>) {
const fallback = props.defaultTab ?? props.items[0].id;
if (param === null) return <LocalTabs {...props} initial={fallback} />;
return (
<Suspense fallback={<TabsView {...props} active={fallback} onSelect={() => {}} />}>
<UrlTabs {...props} param={param} fallback={fallback} />
</Suspense>
);
}
function LocalTabs<T extends string>(props: Omit<TabsProps<T>, "param"> & { initial: T }) {
const [active, setActive] = useState<T>(props.initial);
return <TabsView {...props} active={active} onSelect={(id) => setActive(id)} />;
}
function UrlTabs<T extends string>({ param, fallback, ...props }: Omit<TabsProps<T>, "param"> & { param: string; fallback: T }) {
const searchParams = useSearchParams();
const value = searchParams.get(param);
const active = props.items.some((i) => i.id === value) ? (value as T) : fallback;
const select = useCallback((id: T, mode: "push" | "replace") => {
const params = new URLSearchParams(window.location.search);
if (id === fallback) params.delete(param);
else params.set(param, id);
const query = params.toString();
const url = `${window.location.pathname}${query ? `?${query}` : ""}${window.location.hash}`;
// O Next integra pushState/replaceState ao router: useSearchParams atualiza sem recarregar a página.
if (mode === "push") window.history.pushState(null, "", url);
else window.history.replaceState(null, "", url);
}, [fallback, param]);
return <TabsView {...props} active={active} onSelect={select} />;
}
function TabsView<T extends string>({ label, items, panels, className, active, onSelect }: Omit<TabsProps<T>, "param" | "defaultTab"> & {
active: T; onSelect: (id: T, mode: "push" | "replace") => void;
}) {
const baseId = useId();
const listRef = useRef<HTMLDivElement>(null);
const tabRefs = useRef(new Map<T, HTMLButtonElement>());
const pillRefs = useRef(new Map<T, HTMLSpanElement>());
const [indicator, setIndicator] = useState<{ left: number; width: number } | null>(null);
const tabId = (id: T) => `${baseId}-tab-${id}`;
const panelId = (id: T) => `${baseId}-panel-${id}`;
// Sublinhado: mede a "pílula" da aba ativa e desliza até ela. Remede quando a lista muda de tamanho
// (fonte carregada, janela redimensionada, contador que cresce).
useLayoutEffect(() => {
const list = listRef.current;
const measure = () => {
const pill = pillRefs.current.get(active);
if (!list || !pill) return;
const listBox = list.getBoundingClientRect();
const box = pill.getBoundingClientRect();
setIndicator({ left: box.left - listBox.left + list.scrollLeft, width: box.width });
};
measure();
if (!list || typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(measure);
observer.observe(list);
pillRefs.current.forEach((pill) => observer.observe(pill));
return () => observer.disconnect();
}, [active, items]);
// Aba ativa visível na fileira (telas estreitas): rola SÓ a fileira, na horizontal, e só quando a aba muda.
// Antes era scrollIntoView dentro do efeito acima, que roda a cada atualização dos dados (os contadores
// recriam `items`): o scrollIntoView também rolava a PÁGINA até as abas — quem estava lendo mais abaixo
// via a página pular para cima a cada atualização automática (página do Clipador, 5 s).
useLayoutEffect(() => {
const list = listRef.current;
const tab = tabRefs.current.get(active);
if (!list || !tab) return;
const left = tab.offsetLeft; // a fileira é `relative`: offsetLeft da aba já é medido a partir dela
const right = left + tab.offsetWidth;
if (left < list.scrollLeft) list.scrollLeft = left;
else if (right > list.scrollLeft + list.clientWidth) list.scrollLeft = right - list.clientWidth;
}, [active]);
function onKeyDown(e: KeyboardEvent<HTMLDivElement>) {
const index = items.findIndex((i) => i.id === active);
const target =
e.key === "ArrowRight" ? (index + 1) % items.length
: e.key === "ArrowLeft" ? (index - 1 + items.length) % items.length
: e.key === "Home" ? 0
: e.key === "End" ? items.length - 1
: -1;
if (target < 0) return;
e.preventDefault();
const next = items[target].id;
tabRefs.current.get(next)?.focus();
onSelect(next, "replace");
}
return (
<div className={cx("grid gap-8", className)}>
<div className="border-b border-line">
<div ref={listRef} role="tablist" aria-label={label} aria-orientation="horizontal" onKeyDown={onKeyDown}
className="relative -mb-px flex overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
{items.map((item) => {
const selected = item.id === active;
return (
<button key={item.id} type="button" role="tab" id={tabId(item.id)} aria-selected={selected}
aria-controls={panelId(item.id)} tabIndex={selected ? 0 : -1} title={item.label}
ref={(el) => { if (el) tabRefs.current.set(item.id, el); else tabRefs.current.delete(item.id); }}
onClick={() => onSelect(item.id, "push")}
className="group relative flex h-12 shrink-0 cursor-pointer items-center px-1 focus-visible:outline-none">
<span ref={(el) => { if (el) pillRefs.current.set(item.id, el); else pillRefs.current.delete(item.id); }}
className={cx(
"flex items-center gap-2 rounded-control px-3 py-1.5 text-sm font-medium whitespace-nowrap transition-colors",
"group-hover:bg-raised group-focus-visible:outline-2 group-focus-visible:outline-accent",
selected ? "text-fg" : "text-fg-muted group-hover:text-fg",
)}>
<span className={cx("flex transition-colors", selected ? "text-accent" : "text-fg-subtle group-hover:text-fg-muted")}>
{item.icon}
</span>
{/* Em tela estreita fica só o ícone; o rótulo continua para leitores de tela. */}
<span className="max-sm:sr-only">{item.label}</span>
{item.count !== undefined && (
<span className={cx("grid h-5 min-w-5 place-items-center rounded-full px-1.5 text-[0.6875rem] font-semibold tabular-nums transition-colors",
selected ? "bg-accent-soft text-accent" : "bg-overlay text-fg-subtle")}>
{item.count}
</span>
)}
</span>
{/* Antes da primeira medição (HTML do servidor), um sublinhado fixo marca a aba ativa. */}
{selected && !indicator && <span aria-hidden="true" className="absolute inset-x-4 bottom-0 h-0.5 rounded-full bg-accent" />}
</button>
);
})}
{indicator && (
<span aria-hidden="true"
className="pointer-events-none absolute bottom-0 left-0 h-0.5 rounded-full bg-accent shadow-[0_0_10px_rgb(255_122_26/0.65)] transition-[transform,width] duration-300 ease-[cubic-bezier(0.2,0.8,0.2,1)]"
style={{ width: indicator.width, transform: `translateX(${indicator.left}px)` }} />
)}
</div>
</div>
{items.map((item) => (
<div key={item.id} role="tabpanel" id={panelId(item.id)} aria-labelledby={tabId(item.id)} tabIndex={0}
hidden={item.id !== active} className="grid gap-8 rounded-card focus-visible:outline-offset-4">
{panels[item.id]}
</div>
))}
</div>
);
}
+502
View File
@@ -0,0 +1,502 @@
// Componentes base do design system (sem estado). Um jeito de fazer cada coisa.
import Link from "next/link";
import type {
ComponentProps, InputHTMLAttributes, ReactNode, SelectHTMLAttributes, TextareaHTMLAttributes,
} from "react";
import type { Choice, EpisodeStage } from "@/lib/types";
export function cx(...parts: (string | false | null | undefined)[]): string {
return parts.filter(Boolean).join(" ");
}
/* ---------- Botões ---------- */
export type ButtonVariant = "primary" | "flame" | "secondary" | "ghost" | "danger";
export type ButtonSize = "sm" | "md" | "lg";
const BUTTON_BASE =
"inline-flex items-center justify-center gap-2 rounded-control font-semibold whitespace-nowrap select-none transition-[background-color,border-color,color,box-shadow,transform] duration-150 active:translate-y-px disabled:pointer-events-none disabled:opacity-45";
const BUTTON_VARIANT: Record<ButtonVariant, string> = {
primary: "bg-accent text-accent-fg shadow-[0_1px_0_0_rgb(255_255_255/0.25)_inset] hover:bg-accent-hover",
// Ação de IA: o degradê da chama, usado com parcimônia (uma vez por tela).
flame: "bg-linear-to-r from-glow via-accent to-flame text-accent-fg shadow-glow hover:brightness-110",
secondary: "border border-line-strong bg-raised text-fg hover:border-fg-subtle/50 hover:bg-overlay",
ghost: "text-fg-muted hover:bg-raised hover:text-fg",
danger: "border border-danger/35 bg-danger-soft text-danger hover:border-danger hover:text-danger-hover",
};
const BUTTON_SIZE: Record<ButtonSize, string> = {
sm: "h-8 px-3 text-[0.8125rem]",
md: "h-10 px-4 text-sm",
lg: "h-12 px-5 text-[0.9375rem]",
};
export function buttonStyles(variant: ButtonVariant = "primary", size: ButtonSize = "md"): string {
return cx(BUTTON_BASE, BUTTON_VARIANT[variant], BUTTON_SIZE[size]);
}
export function Button({ variant = "primary", size = "md", className, ...props }:
ComponentProps<"button"> & { variant?: ButtonVariant; size?: ButtonSize }) {
return <button {...props} className={cx(buttonStyles(variant, size), className)} />;
}
export function LinkButton({ variant = "secondary", size = "md", className, ...props }:
ComponentProps<typeof Link> & { variant?: ButtonVariant; size?: ButtonSize }) {
return <Link {...props} className={cx(buttonStyles(variant, size), className)} />;
}
export function Spinner({ className }: { className?: string }) {
return (
<span aria-hidden="true"
className={cx("inline-block size-4 animate-spin rounded-full border-2 border-current border-r-transparent", className)} />
);
}
/* ---------- Campos ---------- */
const FIELD =
"w-full rounded-control border border-line-strong bg-sunken/60 px-3.5 text-sm text-fg placeholder:text-fg-subtle/80 transition-[border-color,box-shadow] hover:border-fg-subtle/40 focus:border-accent focus:shadow-[0_0_0_3px_rgb(255_122_26/0.18)] focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50";
export function Input({ className, ...props }: InputHTMLAttributes<HTMLInputElement>) {
return (
<input {...props}
className={cx(FIELD, "h-10", props.type === "file" && "h-auto py-2 file:mr-3 file:rounded-md file:border-0 file:bg-overlay file:px-2.5 file:py-1 file:text-xs file:font-semibold file:text-fg", className)} />
);
}
export function Select({ className, ...props }: SelectHTMLAttributes<HTMLSelectElement>) {
return <select {...props} className={cx(FIELD, "h-10 cursor-pointer", className)} />;
}
export function Textarea({ className, ...props }: TextareaHTMLAttributes<HTMLTextAreaElement>) {
return <textarea {...props} className={cx(FIELD, "resize-y py-3 leading-relaxed", className)} />;
}
/** Rótulo visível ligado ao campo (o campo vai como filho). */
export function Field({ label, hint, className, children }: { label: ReactNode; hint?: ReactNode; className?: string; children: ReactNode }) {
return (
<label className={cx("grid content-start gap-2", className)}>
<span className="text-[0.8125rem] font-medium text-fg-muted">{label}</span>
{children}
{hint && <span className="text-xs leading-relaxed text-fg-subtle">{hint}</span>}
</label>
);
}
/**
* Controle deslizante com o valor atual ao lado do rótulo. Controlado: o valor vem de quem usa.
* `compact`: numa linha só (para listas densas); o rótulo fica só para leitores de tela.
*/
export function RangeField({ label, hint, name, min, max, step, value, onChange, format, disabled, className, compact = false }: {
label: ReactNode; hint?: ReactNode; name?: string; min: number; max: number; step: number;
value: number; onChange: (value: number) => void; format?: (value: number) => string; disabled?: boolean; className?: string;
compact?: boolean;
}) {
const shown = format ? format(value) : String(value);
if (compact) {
return (
<label className={cx("flex shrink-0 items-center gap-2", disabled && "opacity-50", className)}>
<span className="sr-only">{label}</span>
<input type="range" name={name} min={min} max={max} step={step} value={value} disabled={disabled}
aria-valuetext={shown} onChange={(e) => onChange(Number(e.target.value))}
className="h-5 w-24 cursor-pointer accent-accent disabled:cursor-not-allowed" />
<output className="w-11 font-mono text-xs text-fg-muted tabular-nums">{shown}</output>
</label>
);
}
return (
<label className={cx("grid content-start gap-2", disabled && "opacity-50", className)}>
<span className="flex items-baseline justify-between gap-3 text-[0.8125rem] font-medium text-fg-muted">
{label}
<output className="font-mono text-xs text-fg tabular-nums">{shown}</output>
</span>
<input type="range" name={name} min={min} max={max} step={step} value={value} disabled={disabled}
aria-valuetext={shown} onChange={(e) => onChange(Number(e.target.value))}
className="h-5 w-full cursor-pointer accent-accent disabled:cursor-not-allowed" />
{hint && <span className="text-xs leading-relaxed text-fg-subtle">{hint}</span>}
</label>
);
}
/** Barra de progresso. Sem `value`, fica indeterminada (pulsando). */
export function ProgressBar({ value, label, className }: { value?: number; label: string; className?: string }) {
const percent = value === undefined ? undefined : Math.round(Math.min(1, Math.max(0, value)) * 100);
return (
<div role="progressbar" aria-label={label} aria-valuemin={0} aria-valuemax={100} aria-valuenow={percent}
className={cx("h-1.5 w-full overflow-hidden rounded-full bg-overlay", className)}>
<div className={cx("h-full rounded-full bg-linear-to-r from-glow via-accent to-flame transition-[width] duration-300",
percent === undefined && "w-1/3 animate-pulse")}
style={percent === undefined ? undefined : { width: `${percent}%` }} />
</div>
);
}
/**
* Grupo de opções exclusivas (rádio) com aparência de botões segmentados. Funciona sem estado
* (o rádio marcado é o do formulário), então serve tanto em formulário de server action quanto em cliente.
*/
export function ChoiceGroup<T extends string>({ name, legend, options, defaultValue, value, onChange, className }: {
name: string;
legend: ReactNode;
options: { value: T; label: ReactNode; hint?: ReactNode; disabled?: boolean }[];
defaultValue?: T;
value?: T;
onChange?: (value: T) => void;
className?: string;
}) {
return (
<fieldset className={cx("grid content-start gap-2", className)}>
<legend className="mb-2 text-[0.8125rem] font-medium text-fg-muted">{legend}</legend>
<div className="flex flex-wrap gap-1 rounded-control border border-line-strong bg-sunken/60 p-1">
{options.map((o) => (
<label key={o.value}
className={cx(
"flex min-w-0 flex-1 cursor-pointer items-center justify-center gap-2 rounded-[0.45rem] px-3 py-1.5 text-center text-[0.8125rem] font-medium text-fg-muted transition-colors",
"hover:text-fg has-checked:bg-overlay has-checked:text-fg has-checked:shadow-[0_1px_0_0_rgb(255_255_255/0.06)_inset,0_1px_3px_rgb(0_0_0/0.5)]",
"has-focus-visible:outline-2 has-focus-visible:outline-offset-1 has-focus-visible:outline-accent",
o.disabled && "pointer-events-none opacity-45",
)}>
<input type="radio" name={name} value={o.value} className="sr-only" disabled={o.disabled}
{...(value !== undefined
? { checked: value === o.value, onChange: () => onChange?.(o.value) }
: { defaultChecked: defaultValue === o.value })} />
<span className="grid">
<span>{o.label}</span>
{o.hint && <span className="text-[0.6875rem] font-normal text-fg-subtle">{o.hint}</span>}
</span>
</label>
))}
</div>
</fieldset>
);
}
/**
* Chave liga/desliga (checkbox com papel de switch). Controlada: muda na hora, sem botão de salvar.
* O rótulo fica visível; `hint` explica o efeito logo abaixo.
*/
export function Switch({ label, hint, checked, onChange, disabled, busy = false, className }: {
label: ReactNode; hint?: ReactNode; checked: boolean; onChange: (checked: boolean) => void;
disabled?: boolean; busy?: boolean; className?: string;
}) {
return (
<label className={cx("group flex cursor-pointer items-start gap-3 text-sm", (disabled || busy) && "cursor-not-allowed opacity-60", className)}>
<input type="checkbox" role="switch" className="peer sr-only" checked={checked} disabled={disabled || busy}
onChange={(e) => onChange(e.target.checked)} />
<span aria-hidden="true"
className={cx("relative mt-0.5 inline-flex h-5 w-9 shrink-0 rounded-full border transition-colors duration-150",
"peer-focus-visible:outline-2 peer-focus-visible:outline-offset-2 peer-focus-visible:outline-accent",
checked ? "border-accent bg-accent" : "border-line-strong bg-overlay group-hover:border-fg-subtle/50")}>
<span className={cx("absolute top-1/2 size-3.5 -translate-y-1/2 rounded-full shadow transition-[left,background-color] duration-150",
checked ? "left-[1.1rem] bg-accent-fg" : "left-0.5 bg-fg-muted")} />
</span>
<span className="grid min-w-0 gap-0.5">
<span className="font-medium text-fg">{label}</span>
{hint && <span className="text-xs leading-relaxed text-fg-subtle">{hint}</span>}
</span>
</label>
);
}
/** Mensagem de retorno de formulário (sucesso ou erro). */
export function Feedback({ ok, children }: { ok: boolean; children: ReactNode }) {
return (
<p role={ok ? "status" : "alert"}
className={cx("flex items-start gap-2 rounded-control border px-3 py-2 text-sm",
ok ? "border-success/25 bg-success-soft text-success" : "border-danger/30 bg-danger-soft text-danger")}>
<span aria-hidden="true" className="mt-1.5 size-1.5 shrink-0 rounded-full bg-current" />
<span>{children}</span>
</p>
);
}
/* ---------- Superfícies ---------- */
export function Card({ title, description, actions, children, className, padded = true, eyebrow }: {
title?: ReactNode; description?: ReactNode; actions?: ReactNode; children: ReactNode; className?: string; padded?: boolean; eyebrow?: ReactNode;
}) {
return (
<section className={cx("rounded-card border border-line bg-surface shadow-card", className)}>
{(title || actions) && (
<header className={cx("flex flex-wrap items-start justify-between gap-x-4 gap-y-3", padded ? "px-6 pt-5 pb-4" : "border-b border-line px-6 py-4")}>
<div className="min-w-0">
{eyebrow && <Eyebrow className="mb-2">{eyebrow}</Eyebrow>}
{title && <h2 className="text-[1.0625rem] font-semibold tracking-[-0.01em] text-fg">{title}</h2>}
{description && <p className="mt-1 text-[0.8125rem] leading-relaxed text-fg-subtle">{description}</p>}
</div>
{actions && <div className="flex flex-wrap items-center gap-2">{actions}</div>}
</header>
)}
<div className={cx(padded && (title || actions ? "px-6 pb-6" : "p-6"))}>{children}</div>
</section>
);
}
/** Rótulo curto em caixa alta acima de um título. */
export function Eyebrow({ children, className, tone = "accent" }: { children: ReactNode; className?: string; tone?: "accent" | "muted" }) {
return (
<div className={cx("flex items-center gap-2 text-eyebrow font-semibold uppercase",
tone === "accent" ? "text-accent" : "text-fg-subtle", className)}>
{children}
</div>
);
}
/** Cabeçalho de seção (fora de cartão): título, descrição e ações à direita. */
export function SectionHeader({ title, description, actions, eyebrow, id }:
{ title: ReactNode; description?: ReactNode; actions?: ReactNode; eyebrow?: ReactNode; id?: string }) {
return (
<div className="flex flex-wrap items-end justify-between gap-x-6 gap-y-3">
<div className="min-w-0">
{eyebrow && <Eyebrow tone="muted" className="mb-2.5">{eyebrow}</Eyebrow>}
<h2 id={id} className="text-title text-fg">{title}</h2>
{description && <p className="mt-1.5 max-w-[75ch] text-sm leading-relaxed text-fg-muted">{description}</p>}
</div>
{actions && <div className="flex flex-wrap items-center gap-2">{actions}</div>}
</div>
);
}
/* ---------- Badges e estágios ---------- */
export type Tone = "neutral" | "accent" | "info" | "violet" | "success" | "warning" | "danger" | "optionB" | "optionC" | "optionD";
const TONE: Record<Tone, string> = {
neutral: "bg-raised text-fg-muted border-line-strong",
accent: "bg-accent-soft text-accent border-accent/25",
info: "bg-info-soft text-info border-info/25",
violet: "bg-violet-soft text-violet border-violet/25",
success: "bg-success-soft text-success border-success/25",
warning: "bg-warning-soft text-warning border-warning/25",
danger: "bg-danger-soft text-danger border-danger/25",
optionB: "bg-option-b-soft text-option-b border-option-b/25",
optionC: "bg-option-c-soft text-option-c border-option-c/25",
optionD: "bg-option-d-soft text-option-d border-option-d/25",
};
/* ---------- Opções da votação (A–D) ---------- */
/** Cor de cada opção da decisão: A = brasa (destaque), B = ciano, C = violeta, D = lima. */
export const CHOICE_STYLE: Record<Choice, { tone: Tone; text: string; soft: string; fill: string; fillFg: string; border: string; stroke: string }> = {
A: { tone: "accent", text: "text-accent", soft: "bg-accent-soft", fill: "bg-accent", fillFg: "text-accent-fg", border: "border-accent/25", stroke: "var(--color-accent)" },
B: { tone: "optionB", text: "text-option-b", soft: "bg-option-b-soft", fill: "bg-option-b", fillFg: "text-sunken", border: "border-option-b/25", stroke: "var(--color-option-b)" },
C: { tone: "optionC", text: "text-option-c", soft: "bg-option-c-soft", fill: "bg-option-c", fillFg: "text-sunken", border: "border-option-c/25", stroke: "var(--color-option-c)" },
D: { tone: "optionD", text: "text-option-d", soft: "bg-option-d-soft", fill: "bg-option-d", fillFg: "text-sunken", border: "border-option-d/25", stroke: "var(--color-option-d)" },
};
/** Quadradinho com a letra da opção. `solid` = cheio (vencedora, cena); senão, suave. */
export function ChoiceChip({ letter, solid = false, size = "md", className }: { letter: Choice; solid?: boolean; size?: "sm" | "md"; className?: string }) {
const c = CHOICE_STYLE[letter];
return (
<span aria-hidden="true" className={cx("grid shrink-0 place-items-center rounded-md font-bold",
size === "sm" ? "size-5 text-[0.6875rem]" : "size-7 text-sm", solid ? cx(c.fill, c.fillFg) : cx(c.soft, c.text), className)}>
{letter}
</span>
);
}
export function Badge({ tone = "neutral", pulse = false, dot = true, children, className }:
{ tone?: Tone; pulse?: boolean; dot?: boolean; children: ReactNode; className?: string }) {
return (
<span className={cx("inline-flex h-6 items-center gap-1.5 rounded-full border px-2.5 text-xs font-medium whitespace-nowrap", TONE[tone], className)}>
{dot && (
<span className="relative flex size-1.5" aria-hidden="true">
{pulse && <span className="absolute inset-0 animate-ping rounded-full bg-current opacity-60" />}
<span className="relative size-1.5 rounded-full bg-current" />
</span>
)}
{children}
</span>
);
}
export const STAGES: EpisodeStage[] = ["rascunho", "roteiro", "cena", "renderizado", "decidido"];
const STAGE_TONE: Record<EpisodeStage, Tone> = {
rascunho: "neutral", roteiro: "info", cena: "violet", renderizado: "success", decidido: "accent",
};
const STAGE_BAR: Record<EpisodeStage, string> = {
rascunho: "bg-fg-subtle", roteiro: "bg-info", cena: "bg-violet", renderizado: "bg-success", decidido: "bg-accent",
};
export function StageBadge({ stage }: { stage: EpisodeStage }) {
return <Badge tone={STAGE_TONE[stage]}>{stage}</Badge>;
}
/** Progresso do episódio nas cinco etapas: rascunho → roteiro → cena → renderizado → decidido. */
export function StagePipeline({ stage, showLabel = true, className }: { stage: EpisodeStage; showLabel?: boolean; className?: string }) {
const index = STAGES.indexOf(stage);
return (
<div className={cx("flex items-center gap-3", className)}>
<div className="flex gap-1" role="img" aria-label={`Etapa ${index + 1} de ${STAGES.length}: ${stage}`}>
{STAGES.map((s, i) => (
<span key={s} title={s} className={cx("h-1.5 w-5 rounded-full", i <= index ? STAGE_BAR[stage] : "bg-overlay")} />
))}
</div>
{showLabel && <span className="text-xs font-medium text-fg-muted">{stage}</span>}
</div>
);
}
const STATUS_TONE: Record<string, Tone> = { success: "success", running: "info", failed: "danger", error: "danger", cancelled: "neutral", interrupted: "warning" };
const STATUS_LABEL: Record<string, string> = {
success: "sucesso", running: "rodando", failed: "falhou", error: "erro", cancelled: "cancelado", interrupted: "interrompido",
};
export function StatusBadge({ status }: { status: string }) {
return <Badge tone={STATUS_TONE[status] ?? "neutral"} pulse={status === "running"}>{STATUS_LABEL[status] ?? status}</Badge>;
}
/* ---------- Cabeçalho de página, navegação, vazio ---------- */
export function PageHeader({ title, description, actions, eyebrow, meta, breadcrumb }: {
title: ReactNode; description?: ReactNode; actions?: ReactNode; eyebrow?: ReactNode; meta?: ReactNode; breadcrumb?: ReactNode;
}) {
return (
<header className="grid gap-5 pt-2 pb-2">
{breadcrumb}
<div className="flex flex-wrap items-end justify-between gap-x-10 gap-y-6">
{/* Largura mínima do texto: em tela estreita as ações descem, em vez de espremer o título. */}
<div className="min-w-[min(100%,20rem)] flex-1">
{eyebrow && <Eyebrow className="mb-4">{eyebrow}</Eyebrow>}
<h1 className="max-w-[24ch] text-display text-fg max-md:text-[2.125rem]">{title}</h1>
{description && <div className="mt-4 max-w-[75ch] text-lead text-fg-muted">{description}</div>}
{meta && <div className="mt-5 flex flex-wrap items-center gap-x-5 gap-y-2 text-[0.8125rem] text-fg-subtle">{meta}</div>}
</div>
{actions && <div className="flex flex-wrap items-center gap-2.5">{actions}</div>}
</div>
</header>
);
}
/** Item de metadado com ícone, para a linha `meta` do cabeçalho. */
export function Meta({ icon, children }: { icon?: ReactNode; children: ReactNode }) {
return <span className="inline-flex items-center gap-1.5 [&_svg]:text-fg-subtle">{icon}{children}</span>;
}
export function Breadcrumb({ items }: { items: { href?: string; label: string }[] }) {
return (
<nav aria-label="Você está em">
<ol className="flex flex-wrap items-center gap-1.5 text-[0.8125rem] text-fg-subtle">
{items.map((item, i) => (
<li key={i} className="flex items-center gap-1.5">
{i > 0 && <span aria-hidden="true" className="text-line-strong">/</span>}
{item.href
? <Link className="rounded px-1 py-0.5 transition-colors hover:bg-raised hover:text-fg" href={item.href}>{item.label}</Link>
: <span className="px-1 font-medium text-fg-muted" aria-current="page">{item.label}</span>}
</li>
))}
</ol>
</nav>
);
}
/** Estado vazio: diz o que falta e qual é o próximo passo. */
export function EmptyState({ icon, title, children, action, compact = false, className }:
{ icon?: ReactNode; title: ReactNode; children?: ReactNode; action?: ReactNode; compact?: boolean; className?: string }) {
return (
<div className={cx("flex flex-col items-center rounded-card border border-dashed border-line-strong bg-sunken/30 text-center",
compact ? "gap-2.5 px-5 py-7" : "gap-3 px-6 py-12", className)}>
{icon && (
<span className={cx("grid place-items-center rounded-2xl border border-line-strong bg-raised text-accent", compact ? "size-10" : "size-12")}>
{icon}
</span>
)}
<p className="font-display text-[0.9375rem] font-semibold text-fg">{title}</p>
{children && <div className="max-w-md text-sm leading-relaxed text-fg-muted">{children}</div>}
{action && <div className="mt-2">{action}</div>}
</div>
);
}
/** Número grande com rótulo. */
export function Stat({ label, value, hint }: { label: ReactNode; value: ReactNode; hint?: ReactNode }) {
return (
<div className="grid gap-1">
<dt className="text-eyebrow font-semibold uppercase text-fg-subtle">{label}</dt>
<dd className="font-display text-[1.75rem] leading-none font-semibold tabular-nums tracking-tight text-fg">
{value}{hint && <span className="ml-1.5 text-sm font-normal text-fg-subtle">{hint}</span>}
</dd>
</div>
);
}
export function Kbd({ children }: { children: ReactNode }) {
return <kbd className="rounded border border-line-strong bg-raised px-1.5 py-0.5 font-mono text-[0.6875rem] text-fg-muted">{children}</kbd>;
}
/* ---------- Tabela ---------- */
export function Table({ children, className }: { children: ReactNode; className?: string }) {
return (
<div className={cx("overflow-x-auto rounded-control border border-line", className)}>
<table className="w-full text-left text-sm">{children}</table>
</div>
);
}
export function THead({ children }: { children: ReactNode }) {
return <thead className="bg-raised/60 text-[0.6875rem] uppercase tracking-[0.12em] text-fg-subtle"><tr>{children}</tr></thead>;
}
export function Th({ children, className }: { children?: ReactNode; className?: string }) {
return <th scope="col" className={cx("px-4 py-2.5 font-semibold", className)}>{children}</th>;
}
export function Tr({ children }: { children: ReactNode }) {
return <tr className="border-t border-line transition-colors first:border-t-0 hover:bg-raised/40">{children}</tr>;
}
export function Td({ children, className }: { children?: ReactNode; className?: string }) {
return <td className={cx("px-4 py-3 align-middle", className)}>{children}</td>;
}
/* ---------- Utilidades ---------- */
export function fileUrl(relPath: string): string {
return `/api/files?path=${encodeURIComponent(relPath)}`;
}
export function formatDate(iso: string | null): string {
if (!iso) return "—";
return new Date(iso).toLocaleString("pt-BR", { dateStyle: "short", timeStyle: "short" });
}
/** Data relativa curta ("há 3 h", "ontem"), para listas. */
export function formatRelative(iso: string | null): string {
if (!iso) return "—";
const diff = Date.now() - new Date(iso).getTime();
const min = Math.round(diff / 60_000);
if (min < 1) return "agora";
if (min < 60) return `há ${min} min`;
const h = Math.round(min / 60);
if (h < 24) return `há ${h} h`;
const d = Math.round(h / 24);
if (d === 1) return "ontem";
if (d < 30) return `há ${d} dias`;
return new Date(iso).toLocaleDateString("pt-BR", { dateStyle: "short" });
}
const COMPACT = new Intl.NumberFormat("pt-BR", { notation: "compact", maximumFractionDigits: 1 });
const INTEGER = new Intl.NumberFormat("pt-BR");
const PERCENT = new Intl.NumberFormat("pt-BR", { style: "percent", maximumFractionDigits: 1 });
/** Número curto em pt-BR: 950, 1,2 mil, 3,4 mi. */
export function formatCompact(n: number): string {
return Math.abs(n) < 1000 ? INTEGER.format(n) : COMPACT.format(n);
}
/** Número inteiro com separador de milhar (para leitores de tela e dicas). */
export function formatInteger(n: number): string {
return INTEGER.format(n);
}
/** Fração (0–1) como porcentagem em pt-BR: 3,4%. Sem dado: —. */
export function formatPercent(rate: number | null | undefined): string {
return rate === null || rate === undefined ? "—" : PERCENT.format(rate);
}
export function episodeCode(n: number): string {
return `ep${String(n).padStart(2, "0")}`;
}
/** Matiz estável (0–359) derivado de um texto: dá a cada história um "pôster" próprio. */
export function hueOf(text: string): number {
let h = 0;
for (const ch of text) h = (h * 31 + ch.charCodeAt(0)) % 360;
return h;
}
+165
View File
@@ -0,0 +1,165 @@
"use client";
// Cadastro de voz de personagem (RVC): voz base + modelo .pth (e .index opcional), com origem e licença.
// O .pth costuma ter 50–200 MB, então o envio usa XMLHttpRequest para mostrar o progresso e permitir cancelar.
import { useRef, useState } from "react";
import { AlertIcon, UploadIcon } from "./icons";
import { DescribedSelect } from "./forms";
import { Button, ChoiceGroup, Feedback, Field, Input, ProgressBar, RangeField } from "./ui";
import {
UploadAborted, formatBytes, uploadError, uploadWithProgress, voiceOptionLabel, type F0Method, type UploadProgress, type VoiceInfo,
} from "./voice-client";
const F0_OPTIONS: { value: F0Method; label: string; hint: string }[] = [
{ value: "rmvpe", label: "rmvpe", hint: "padrão, equilibrado" },
{ value: "fcpe", label: "fcpe", hint: "mais rápido" },
{ value: "crepe", label: "crepe", hint: "preciso, mais lento" },
];
type Phase = { kind: "idle" } | { kind: "uploading"; progress: UploadProgress | null } | { kind: "processing" };
export function AddVoiceForm({ baseVoices, applioInstalled, rvcEnabled, onAdded }: {
baseVoices: VoiceInfo[]; applioInstalled: boolean; rvcEnabled: boolean; onAdded: () => void;
}) {
const [pitch, setPitch] = useState(0);
const [indexRate, setIndexRate] = useState(0.5);
const [protect, setProtect] = useState(0.33);
const [f0Method, setF0Method] = useState<F0Method>("rmvpe");
const [baseVoice, setBaseVoice] = useState("");
const [phase, setPhase] = useState<Phase>({ kind: "idle" });
const [feedback, setFeedback] = useState<{ ok: boolean; text: string } | null>(null);
const abortRef = useRef<(() => void) | null>(null);
const noBase = baseVoices.length === 0;
const disabled = !applioInstalled || noBase;
const busy = phase.kind !== "idle";
async function submit(form: HTMLFormElement) {
const data = new FormData(form);
// Arquivo opcional vazio não vai no corpo: o servidor trataria como .index inválido.
const index = data.get("index");
if (index instanceof File && index.size === 0) data.delete("index");
if (!String(data.get("description") ?? "").trim()) data.delete("description");
data.set("pitch", String(pitch));
data.set("indexRate", String(indexRate));
data.set("protect", String(protect));
data.set("f0Method", f0Method);
setFeedback(null);
setPhase({ kind: "uploading", progress: null });
const upload = uploadWithProgress("/api/voice/voices", data,
(progress) => setPhase({ kind: "uploading", progress }),
() => setPhase({ kind: "processing" }));
abortRef.current = upload.abort;
try {
const result = await upload.promise;
if (result.status >= 400) throw new Error(uploadError(result));
const id = (result.body as { id?: string } | null)?.id;
setFeedback({ ok: true, text: `Voz "${data.get("name")}" adicionada${id ? ` (${id})` : ""}. Ela já aparece na lista acima.` });
form.reset();
setPitch(0); setIndexRate(0.5); setProtect(0.33); setF0Method("rmvpe"); setBaseVoice("");
onAdded();
} catch (e) {
setFeedback({ ok: false, text: e instanceof UploadAborted ? "Envio cancelado. Nada foi salvo." : e instanceof Error ? e.message : String(e) });
} finally {
abortRef.current = null;
setPhase({ kind: "idle" });
}
}
const progress = phase.kind === "uploading" && phase.progress ? phase.progress : null;
return (
<form className="grid gap-6" onSubmit={(e) => { e.preventDefault(); void submit(e.currentTarget); }}>
{!applioInstalled && (
<Feedback ok={false}>
O RVC (Applio) não está instalado, então não dá para adicionar vozes de personagem. Rode <code>setup.bat</code> sem a
opção <code>-NoRvc</code> (ocupa cerca de 4 GB) e volte aqui.
</Feedback>
)}
{applioInstalled && noBase && (
<Feedback ok={false}>Nenhuma voz base disponível. Ponha o serviço de voz no ar para escolher a voz que o modelo vai transformar.</Feedback>
)}
{applioInstalled && !rvcEnabled && (
<p className="flex items-start gap-2 rounded-control border border-warning/25 bg-warning-soft px-3 py-2 text-sm text-warning">
<AlertIcon size={16} className="mt-0.5" />
O RVC está desligado nas configurações (abaixo). A voz fica salva, mas só soa como o personagem com o RVC ligado.
</p>
)}
<fieldset disabled={disabled || busy} className="grid gap-6 disabled:opacity-60">
<legend className="sr-only">Dados da voz de personagem</legend>
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
<Field label="Nome">
<Input name="name" required maxLength={60} placeholder="Ex.: Herói (jovem)" />
</Field>
<DescribedSelect name="baseVoice" label="Voz base" required placeholder="Escolha a voz base"
value={baseVoice} onChange={setBaseVoice}
options={baseVoices.map((v) => ({
value: v.id,
label: voiceOptionLabel(v),
description: <>A fala é gerada nesta voz e depois convertida pelo modelo.{v.description ? ` ${v.description}` : ""}</>,
}))} />
<Field label="Descrição (opcional)">
<Input name="description" maxLength={200} placeholder="Ex.: voz do protagonista, tom animado" />
</Field>
<Field label="Modelo RVC (.pth)" hint="Obrigatório. Costuma ter de 50 a 200 MB.">
<Input name="model" type="file" required accept=".pth" />
</Field>
<Field label="Índice (.index, opcional)" hint="Melhora o timbre; sem ele a taxa do índice é ignorada.">
<Input name="index" type="file" accept=".index" />
</Field>
<ChoiceGroup name="f0Method" legend="Método de f0 (afinação)" value={f0Method} onChange={setF0Method} options={F0_OPTIONS} />
</div>
<div className="grid gap-5 md:grid-cols-3">
<RangeField label="Pitch (semitons)" min={-24} max={24} step={1} value={pitch} onChange={setPitch}
format={(v) => (v > 0 ? `+${v}` : String(v))} hint="+12 sobe uma oitava; −12 desce." />
<RangeField label="Taxa do índice" min={0} max={1} step={0.05} value={indexRate} onChange={setIndexRate}
format={(v) => v.toFixed(2)} hint="Quanto do timbre vem do .index." />
<RangeField label="Proteção de consoantes" min={0} max={0.5} step={0.01} value={protect} onChange={setProtect}
format={(v) => v.toFixed(2)} hint="Mais alto preserva respiração e consoantes." />
</div>
<div className="grid gap-4 md:grid-cols-2">
<Field label="Origem / fonte" hint="De onde veio o modelo (link, autor, ou “treinado por mim com …”).">
<Input name="source" required placeholder="Ex.: treinado por mim com gravações próprias" />
</Field>
<Field label="Licença / autorização" hint="Obrigatório: o projeto só aceita vozes com origem e licença informadas.">
<Input name="license" required placeholder="Ex.: própria; CC-BY 4.0; autorização por escrito de …" />
</Field>
</div>
<p className="flex items-start gap-2 text-[0.8125rem] text-warning">
<AlertIcon size={16} className="mt-0.5" />
Não use voz de pessoa real ou personagem protegido sem autorização.
</p>
</fieldset>
<div className="grid gap-3">
<div className="flex flex-wrap items-center gap-3">
<Button type="submit" disabled={disabled || busy}>
<UploadIcon size={16} />{busy ? "Enviando…" : "Adicionar voz"}
</Button>
{phase.kind === "uploading" && (
<Button type="button" variant="ghost" onClick={() => abortRef.current?.()}>Cancelar envio</Button>
)}
</div>
<div aria-live="polite" className="grid max-w-xl gap-2 empty:hidden">
{busy && (
<>
<ProgressBar label="Envio da voz" value={phase.kind === "processing" ? undefined : progress ? progress.loaded / progress.total : 0} />
<p className="text-xs text-fg-muted tabular-nums">
{phase.kind === "processing"
? "Arquivos enviados. Conferindo o modelo no servidor…"
: progress
? `Enviando ${Math.round((progress.loaded / progress.total) * 100)}% · ${formatBytes(progress.loaded)} de ${formatBytes(progress.total)}`
: "Preparando o envio…"}
</p>
</>
)}
{feedback && <Feedback ok={feedback.ok}>{feedback.text}</Feedback>}
</div>
</div>
</form>
);
}
+318
View File
@@ -0,0 +1,318 @@
"use client";
// Lista de vozes (densa, uma linha por voz): nome e selos à esquerda; na mesma linha, texto de teste,
// velocidade e "Ouvir" (→ /api/voice/synthesize). O player só aparece, na própria linha, quando há áudio.
// Vozes de personagem (RVC) mostram voz base e pitch e podem ser removidas.
// Com muitas vozes, o topo tem sub-abas por tipo (Personagem/Edge/Kokoro/Piper/Google), busca e filtros de
// gênero e conexão, numa barra que fica presa ao rolar; a lista mostra só o que passa no filtro.
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { MicIcon, PlayIcon, SearchIcon, TrashIcon, XIcon } from "./icons";
import { Badge, Button, EmptyState, Feedback, Input, RangeField, Select, Spinner, cx } from "./ui";
import { GENDER_LABEL, PROVIDER_LABEL, SAMPLE_TEXT, errorMessage, type VoiceInfo } from "./voice-client";
import { askConfirm } from "./confirm-dialog";
/** Gera a fala de uma voz e guarda o áudio (URL de blob) para tocar ali mesmo; libera o anterior. */
export function useSynthesis() {
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [audioUrl, setAudioUrl] = useState<string | null>(null);
const urlRef = useRef<string | null>(null);
// Libera o áudio gerado quando o componente sai da tela.
useEffect(() => () => { if (urlRef.current) URL.revokeObjectURL(urlRef.current); }, []);
const speak = useCallback(async (voiceId: string, text: string, speed: number) => {
setLoading(true);
setError(null);
try {
const r = await fetch("/api/voice/synthesize", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ voiceId, text: text.trim(), speed }),
});
if (!r.ok) throw new Error(await errorMessage(r));
const blob = await r.blob();
if (urlRef.current) URL.revokeObjectURL(urlRef.current);
urlRef.current = URL.createObjectURL(blob);
setAudioUrl(urlRef.current);
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setLoading(false);
}
}, []);
/** Fecha o player e o erro (o áudio é liberado da memória). */
const clear = useCallback(() => {
if (urlRef.current) URL.revokeObjectURL(urlRef.current);
urlRef.current = null;
setAudioUrl(null);
setError(null);
}, []);
return { loading, error, audioUrl, speak, clear };
}
type Group = "all" | "user" | VoiceInfo["provider"];
type Connection = "all" | "offline" | "online";
type GenderFilter = "all" | "female" | "male";
/** Ordem das sub-abas; motor sem nenhuma voz não aparece. */
const GROUPS: { id: Group; label: string }[] = [
{ id: "all", label: "Todas" },
{ id: "user", label: "Personagem" },
{ id: "edge", label: "Edge" },
{ id: "kokoro", label: "Kokoro" },
{ id: "piper", label: "Piper" },
{ id: "google", label: "Google" },
{ id: "fake", label: "Teste" },
];
const inGroup = (v: VoiceInfo, group: Group) =>
group === "all" || (group === "user" ? v.user : !v.user && v.provider === group);
/** Sem acento e em minúsculas: a busca acha "voz" em "Vóz" e "pt-br" em "PT-BR". */
const fold = (text: string) => text.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
const sectionTitle = (title: string, count: number) => (
<h3 className="flex items-center gap-2 text-sm font-semibold text-fg">
{title} <span className="font-normal text-fg-subtle">· {count}</span>
</h3>
);
export function VoiceList({ voices, online, onChanged }: { voices: VoiceInfo[]; online: boolean; onChanged: () => void }) {
const [group, setGroup] = useState<Group>("all");
const [query, setQuery] = useState("");
const [gender, setGender] = useState<GenderFilter>("all");
const [connection, setConnection] = useState<Connection>("all");
const names = useMemo(() => new Map(voices.map((v) => [v.id, v.name])), [voices]);
const groups = useMemo(
() => GROUPS.map((g) => ({ ...g, count: voices.filter((v) => inGroup(v, g.id)).length }))
.filter((g) => g.id === "all" || g.id === "user" || g.count > 0),
[voices],
);
const visible = useMemo(() => {
const needle = fold(query.trim());
return voices.filter((v) =>
inGroup(v, group)
&& (gender === "all" || v.gender === gender)
&& (connection === "all" || (connection === "offline") === v.offline)
&& (!needle || fold(`${v.name} ${v.id} ${v.description ?? ""}`).includes(needle)));
}, [voices, group, query, gender, connection]);
const filtered = query.trim() !== "" || gender !== "all" || connection !== "all";
const clearFilters = () => { setQuery(""); setGender("all"); setConnection("all"); };
// Offline, o serviço não informa nem as vozes base nem as de personagem.
if (!online && voices.length === 0) {
return (
<EmptyState icon={<MicIcon size={20} />} title="Vozes indisponíveis com o serviço offline">
A lista de vozes (base e de personagem) vem do serviço de voz. Ela aparece aqui assim que ele estiver no ar.
</EmptyState>
);
}
const userVoices = visible.filter((v) => v.user);
const baseVoices = visible.filter((v) => !v.user);
// Sem filtro, "Todas" e "Personagem" mostram a seção de personagem mesmo vazia (com o convite para adicionar).
const showUserSection = !filtered && (group === "all" || group === "user");
const noMatch = showUserSection ? group === "all" && visible.length === 0 : visible.length === 0;
return (
<div className="grid gap-5">
{/* Barra de filtros: fica presa no topo ao rolar a lista. */}
<div className="sticky top-0 z-10 grid gap-3 rounded-card border border-line bg-surface/95 p-3 shadow-card backdrop-blur">
<div role="group" aria-label="Filtrar vozes por tipo" className="flex flex-wrap gap-1.5">
{groups.map((g) => (
<button key={g.id} type="button" aria-pressed={group === g.id} onClick={() => setGroup(g.id)}
className={cx(
"inline-flex h-8 items-center gap-1.5 rounded-full border px-3 text-[0.8125rem] font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent",
group === g.id ? "border-accent bg-accent/15 text-fg" : "border-line text-fg-muted hover:border-line-strong hover:text-fg",
)}>
{g.label}
<span className={cx("text-xs tabular-nums", group === g.id ? "text-accent" : "text-fg-subtle")}>{g.count}</span>
</button>
))}
</div>
<div className="flex flex-wrap items-center gap-2">
<label className="relative min-w-[12rem] flex-1 basis-64">
<span className="sr-only">Buscar voz</span>
<SearchIcon size={16} className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-fg-subtle" />
<Input type="search" value={query} onChange={(e) => setQuery(e.target.value)}
placeholder="Buscar por nome, id ou descrição…" className="h-9 pl-9" />
</label>
{/* O Select tem w-full fixo; a largura vem do contêiner. */}
<div className="w-44 shrink-0">
<Select aria-label="Gênero" value={gender} onChange={(e) => setGender(e.target.value as GenderFilter)} className="h-9">
<option value="all">Todos os gêneros</option>
<option value="female">Feminina</option>
<option value="male">Masculina</option>
</Select>
</div>
<div className="w-48 shrink-0">
<Select aria-label="Conexão" value={connection} onChange={(e) => setConnection(e.target.value as Connection)} className="h-9">
<option value="all">Online e offline</option>
<option value="offline">Só offline (rápidas)</option>
<option value="online">Só online</option>
</Select>
</div>
</div>
<p aria-live="polite" className="flex flex-wrap items-center gap-x-2 text-xs text-fg-subtle">
<span>Mostrando <span className="font-semibold tabular-nums text-fg-muted">{visible.length}</span> de {voices.length} vozes</span>
{filtered && (
<button type="button" onClick={clearFilters} className="font-medium text-accent underline-offset-2 hover:underline">
Limpar filtros
</button>
)}
</p>
</div>
{showUserSection && (
<div className="grid gap-3">
{sectionTitle("Vozes de personagem", userVoices.length)}
{userVoices.length === 0 && group === "all" ? (
<p className="text-xs text-fg-subtle">
Nenhuma ainda. Uma voz de personagem é uma voz base transformada por um modelo RVC; adicione em{" "}
<a href="#adicionar-voz" className="font-medium text-accent underline-offset-2 hover:underline">Adicionar voz de personagem</a>.
</p>
) : userVoices.length === 0 ? (
<EmptyState compact icon={<MicIcon size={18} />} title="Nenhuma voz de personagem ainda">
Uma voz de personagem é uma voz base transformada por um modelo RVC. Adicione uma em{" "}
<a href="#adicionar-voz" className="font-medium text-accent underline-offset-2 hover:underline">Adicionar voz de personagem</a>.
</EmptyState>
) : (
<VoiceRows voices={userVoices} online={online} names={names} onChanged={onChanged} />
)}
</div>
)}
{noMatch ? (
<EmptyState compact icon={<SearchIcon size={18} />} title="Nenhuma voz com esses filtros"
action={<Button type="button" variant="secondary" size="sm" onClick={() => { clearFilters(); setGroup("all"); }}>Ver todas</Button>}>
Tente outro termo de busca ou tire algum filtro.
</EmptyState>
) : showUserSection ? (
group === "all" && baseVoices.length > 0 && (
<div className="grid gap-3">
{sectionTitle("Vozes base", baseVoices.length)}
<VoiceRows voices={baseVoices} online={online} names={names} onChanged={onChanged} />
</div>
)
) : (
<VoiceRows voices={visible} online={online} names={names} onChanged={onChanged} />
)}
</div>
);
}
function VoiceRows({ voices, online, names, onChanged }:
{ voices: VoiceInfo[]; online: boolean; names: Map<string, string>; onChanged: () => void }) {
return (
<ul className="divide-y divide-line overflow-hidden rounded-card border border-line bg-surface shadow-card">
{voices.map((v) => (
<VoiceRow key={v.id} voice={v} online={online} onChanged={onChanged}
baseName={v.baseVoice ? names.get(v.baseVoice) ?? v.baseVoice : null} />
))}
</ul>
);
}
const formatSpeed = (v: number) => `${v.toLocaleString("pt-BR", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}×`;
function VoiceRow({ voice, online, baseName, onChanged }: { voice: VoiceInfo; online: boolean; baseName: string | null; onChanged: () => void }) {
const [text, setText] = useState(SAMPLE_TEXT);
const [speed, setSpeed] = useState(1);
const [removing, setRemoving] = useState(false);
const [removeError, setRemoveError] = useState<string | null>(null);
const synth = useSynthesis();
const nameId = `voz-${voice.id}`;
const busy = removing || synth.loading;
const canListen = online && text.trim().length > 0 && !busy;
const error = synth.error ?? removeError;
async function remove() {
if (!(await askConfirm({ title: `Remover a voz de personagem “${voice.name}”?`,
message: "Os arquivos do modelo (.pth/.index) também são apagados. Esta ação não pode ser desfeita.",
confirmLabel: "Remover voz", tone: "danger" }))) return;
setRemoving(true);
setRemoveError(null);
try {
const r = await fetch(`/api/voice/voices/${encodeURIComponent(voice.id)}`, { method: "DELETE" });
if (!r.ok) throw new Error(await errorMessage(r));
onChanged();
} catch (e) {
setRemoveError(e instanceof Error ? e.message : String(e));
setRemoving(false);
}
}
return (
<li aria-labelledby={nameId}
className="grid items-center gap-x-6 gap-y-3 px-4 py-3.5 transition-colors hover:bg-raised/30 lg:grid-cols-[minmax(15rem,1fr)_minmax(0,2.2fr)]">
{/* Coluna 1: quem é a voz */}
<div className="grid min-w-0 gap-1.5">
<div className="flex min-w-0 items-baseline gap-2">
<span id={nameId} className="truncate font-display text-[0.9375rem] font-semibold text-fg">{voice.name}</span>
<span className="truncate font-mono text-[0.6875rem] text-fg-subtle">{voice.id}</span>
</div>
<div className="flex flex-wrap gap-1.5">
{voice.default && <Badge tone="accent">padrão</Badge>}
{voice.user && <Badge tone="violet">{voice.provider === "clone" ? "clonada" : "personagem (RVC)"}</Badge>}
<Badge tone={voice.offline ? "success" : "info"} dot={false}>
{PROVIDER_LABEL[voice.provider] ?? voice.provider} · {voice.offline ? "offline" : "online"}
</Badge>
{voice.gender && <Badge dot={false}>{GENDER_LABEL[voice.gender] ?? voice.gender}</Badge>}
</div>
{voice.user && voice.provider === "clone" ? (
<p className="truncate text-xs text-fg-subtle" title={voice.description ?? undefined}>
{voice.description ?? "Clonada de uma gravação (Chatterbox)."} A velocidade não muda nesta voz.
</p>
) : voice.user ? (
<p className="truncate text-xs text-fg-subtle">
base <span className="text-fg-muted">{baseName ?? "—"}</span>
{voice.rvc && <>
{" · "}pitch <span className="font-mono text-fg-muted">{voice.rvc.pitch > 0 ? `+${voice.rvc.pitch}` : voice.rvc.pitch}</span>
{" · "}f0 <span className="font-mono text-fg-muted">{voice.rvc.f0Method}</span>
{" · "}índice <span className="text-fg-muted">{voice.rvc.hasIndex ? voice.rvc.indexRate : "não"}</span>
</>}
</p>
) : voice.description && (
<p className="truncate text-xs text-fg-subtle" title={voice.description}>{voice.description}</p>
)}
</div>
{/* Coluna 2: teste na mesma linha */}
<form className="flex min-w-0 flex-wrap items-center gap-x-4 gap-y-2"
onSubmit={(e) => { e.preventDefault(); if (canListen) void synth.speak(voice.id, text, speed); }}>
<Input value={text} maxLength={2000} onChange={(e) => setText(e.target.value)}
aria-label={`Texto de teste da voz ${voice.name}`} className="h-9 min-w-[12rem] flex-1 basis-64" />
<RangeField compact label="Velocidade" min={0.5} max={2} step={0.05} value={speed} onChange={setSpeed} format={formatSpeed} />
<div className="flex items-center gap-2">
<Button type="submit" variant="secondary" size="sm" disabled={!canListen}
aria-label={`Ouvir a voz ${voice.name}`} title={online ? undefined : "O serviço de voz está offline"}>
{synth.loading ? <><Spinner className="size-3.5" />Gerando…</> : <><PlayIcon size={14} />Ouvir</>}
</Button>
{voice.user && (
<Button type="button" variant="danger" size="sm" onClick={() => void remove()} disabled={busy}
aria-label={`Remover a voz ${voice.name}`}>
{removing ? <Spinner className="size-3.5" /> : <TrashIcon size={14} />}Remover
</Button>
)}
</div>
</form>
{/* Player e erro: só aparecem quando há o que mostrar, ocupando a linha toda. */}
<div aria-live="polite" className="flex items-center gap-2 empty:hidden lg:col-span-2">
{error && <div className="min-w-0 flex-1"><Feedback ok={false}>{error}</Feedback></div>}
{synth.audioUrl && !error && (
<audio key={synth.audioUrl} src={synth.audioUrl} controls autoPlay className="h-9 min-w-0 flex-1"
aria-label={`Amostra da voz ${voice.name}`} />
)}
{(error || synth.audioUrl) && (
<Button type="button" variant="ghost" size="sm" onClick={() => { synth.clear(); setRemoveError(null); }} aria-label="Fechar o player" title="Fechar">
<XIcon size={14} />
</Button>
)}
</div>
</li>
);
}
+157
View File
@@ -0,0 +1,157 @@
// Cliente da API de voz do painel (/api/voice/*): tipos do contrato e utilitários do navegador.
// Os tipos espelham as respostas das rotas; não importa de lib/voice.ts, que roda só no servidor.
export type Device = "auto" | "cuda" | "cpu";
export type SttModel = "base" | "small" | "medium" | "large-v3-turbo";
export type F0Method = "rmvpe" | "fcpe" | "crepe";
export type TranscribeLanguage = "pt-BR" | "en" | "es";
export type TranscribeDetail = "text" | "segments" | "words";
export type VoiceInfo = {
id: string;
name: string;
languages: string[];
engine: "tts" | "tts+rvc";
default: boolean;
description?: string | null;
gender?: "female" | "male" | "neutral" | null;
ageRange?: string | null;
provider: "piper" | "edge" | "kokoro" | "google" | "azure" | "clone" | "fake";
baseVoice: string | null;
user: boolean;
offline: boolean;
rvc: null | { pitch: number; f0Method: string; indexRate: number; protect: number; hasIndex: boolean };
};
export type VoiceSettings = {
device: Device; sttModel: SttModel; enableRvc: boolean; sttModelsInstalled: string[];
/** Azure Speech: só diz se há chave; a chave nunca sai do servidor. */
azureConfigured: boolean; azureRegion: string;
};
export type VoiceJob = { kind: "download"; status: "running" | "done" | "error"; message: string };
export type VoiceStatus = {
online: boolean;
error?: string;
device?: { kind: "cuda" | "cpu"; name: string | null; reason: string };
rvc?: boolean;
applioInstalled: boolean;
cloneInstalled: boolean;
engines?: { tts: string; transcribe: string | null };
voices: VoiceInfo[];
settings: VoiceSettings;
job: VoiceJob | null;
};
export type TranscribeWord = { start: number; end: number; text: string; p: number };
export type TranscribeSegment = { start: number; end: number; text: string; words?: TranscribeWord[] };
export type TranscribeResult = {
text: string;
noSpeechProb: number;
durationS?: number;
segments?: TranscribeSegment[];
srt?: string;
};
/* ---------- Rótulos ---------- */
export const STT_MODELS: { id: SttModel; size: string; note: string }[] = [
{ id: "base", size: "145 MB", note: "rápido, menos preciso" },
{ id: "small", size: "480 MB", note: "bom na CPU" },
{ id: "medium", size: "1,5 GB", note: "preciso, mais lento" },
{ id: "large-v3-turbo", size: "1,6 GB", note: "o melhor com GPU" },
];
export const GENDER_LABEL: Record<string, string> = { female: "feminina", male: "masculina", neutral: "neutra" };
/** Faixa etária do catálogo (em inglês no serviço); o que não estiver aqui aparece como veio. */
export const AGE_LABEL: Record<string, string> = {
child: "criança", teen: "adolescente", young: "jovem", "young-adult": "jovem adulta", adult: "adulta", elderly: "idosa", senior: "idosa",
};
export const PROVIDER_LABEL: Record<VoiceInfo["provider"], string> = { edge: "Edge", piper: "Piper", kokoro: "Kokoro", google: "Google", azure: "Azure", clone: "Clonada", fake: "Teste" };
/** Nome da voz para listas de seleção: avisa se é online (Edge: depende da internet e costuma demorar mais). */
export function voiceOptionLabel(voice: VoiceInfo, extra = ""): string {
const where = voice.offline ? "offline" : "online · mais lenta";
return `${voice.name}${voice.default ? " (padrão)" : ""}${extra} — ${where}`;
}
export const SAMPLE_TEXT = "Olá! Esta é uma frase de teste do CenaForge, para ouvir como a voz soa em português do Brasil.";
/* ---------- Utilitários ---------- */
/** Mensagem de erro de uma resposta: o `{error}` do servidor ou o código HTTP. */
export async function errorMessage(response: Response): Promise<string> {
try {
const body = (await response.json()) as { error?: unknown };
if (typeof body.error === "string" && body.error) return body.error;
} catch {
// corpo não é JSON (ex.: página de erro do Next)
}
return `O servidor respondeu ${response.status}${response.statusText ? ` (${response.statusText})` : ""}.`;
}
export function formatBytes(bytes: number): string {
if (bytes < 1024 * 1024) return `${Math.max(1, Math.round(bytes / 1024))} KB`;
if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toLocaleString("pt-BR", { maximumFractionDigits: 1 })} MB`;
return `${(bytes / (1024 * 1024 * 1024)).toLocaleString("pt-BR", { maximumFractionDigits: 2 })} GB`;
}
/** Tempo de legenda curto: "1:02,45". */
export function formatTimestamp(seconds: number): string {
const total = Math.max(0, seconds);
const minutes = Math.floor(total / 60);
const rest = total - minutes * 60;
return `${minutes}:${rest.toLocaleString("pt-BR", { minimumIntegerDigits: 2, minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
}
/** Cronômetro "m:ss" para esperas longas. */
export function formatElapsed(seconds: number): string {
return `${Math.floor(seconds / 60)}:${String(Math.floor(seconds % 60)).padStart(2, "0")}`;
}
export type UploadProgress = { loaded: number; total: number };
export type UploadResult = { status: number; body: unknown };
/**
* Envio multipart com progresso. O fetch não informa o progresso do upload, por isso XMLHttpRequest.
* Rejeita com `UploadAborted` se `abort()` for chamado e com Error em falha de rede.
*/
export class UploadAborted extends Error {}
export function uploadWithProgress(url: string, data: FormData, onProgress: (p: UploadProgress) => void, onUploaded?: () => void) {
const xhr = new XMLHttpRequest();
const promise = new Promise<UploadResult>((resolve, reject) => {
xhr.open("POST", url);
xhr.responseType = "text";
xhr.upload.onprogress = (e) => { if (e.lengthComputable) onProgress({ loaded: e.loaded, total: e.total }); };
xhr.upload.onload = () => onUploaded?.();
xhr.onload = () => {
let body: unknown = null;
try { body = JSON.parse(xhr.responseText); } catch { body = null; }
resolve({ status: xhr.status, body });
};
xhr.onerror = () => reject(new Error("Falha de rede ao enviar. O painel ainda está rodando?"));
xhr.onabort = () => reject(new UploadAborted("Envio cancelado."));
xhr.send(data);
});
return { promise, abort: () => xhr.abort() };
}
/** Mensagem de erro do corpo de um envio por XHR. */
export function uploadError(result: UploadResult): string {
const body = result.body as { error?: unknown } | null;
if (body && typeof body.error === "string" && body.error) return body.error;
return `O servidor respondeu ${result.status}.`;
}
/** Baixa um texto como arquivo (ex.: a legenda .srt). */
export function downloadText(filename: string, text: string, type = "text/plain;charset=utf-8") {
const url = URL.createObjectURL(new Blob([text], { type }));
const a = document.createElement("a");
a.href = url;
a.download = filename;
document.body.append(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
+108
View File
@@ -0,0 +1,108 @@
"use client";
// Clonar voz (Chatterbox Multilingual, MIT): gravação de 10–30 s + consentimento da pessoa → voz nova no catálogo.
// O envio usa XMLHttpRequest (progresso e cancelar), igual ao cadastro de RVC.
import { useRef, useState } from "react";
import { AlertIcon, UploadIcon } from "./icons";
import { Button, ChoiceGroup, Feedback, Field, Input, ProgressBar, RangeField } from "./ui";
import { UploadAborted, formatBytes, uploadError, uploadWithProgress, type UploadProgress } from "./voice-client";
type Phase = { kind: "idle" } | { kind: "uploading"; progress: UploadProgress | null } | { kind: "processing" };
const fmt = (v: number) => v.toLocaleString("pt-BR", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
export function CloneVoiceForm({ cloneInstalled, onAdded }: { cloneInstalled: boolean; onAdded: () => void }) {
const [gender, setGender] = useState<"female" | "male">("female");
const [exaggeration, setExaggeration] = useState(0.5);
const [cfgWeight, setCfgWeight] = useState(0.5);
const [phase, setPhase] = useState<Phase>({ kind: "idle" });
const [feedback, setFeedback] = useState<{ ok: boolean; text: string } | null>(null);
const abortRef = useRef<(() => void) | null>(null);
const busy = phase.kind !== "idle";
async function submit(form: HTMLFormElement) {
const data = new FormData(form);
if (!String(data.get("description") ?? "").trim()) data.delete("description");
data.set("gender", gender);
data.set("exaggeration", String(exaggeration));
data.set("cfgWeight", String(cfgWeight));
setFeedback(null);
setPhase({ kind: "uploading", progress: null });
const upload = uploadWithProgress("/api/voice/clone", data,
(progress) => setPhase({ kind: "uploading", progress }),
() => setPhase({ kind: "processing" }));
abortRef.current = upload.abort;
try {
const result = await upload.promise;
if (result.status >= 400) throw new Error(uploadError(result));
const id = (result.body as { id?: string } | null)?.id;
setFeedback({ ok: true, text: `Voz "${data.get("name")}" clonada${id ? ` (${id})` : ""}. Ouça na aba Personagem do catálogo.` });
form.reset();
setExaggeration(0.5); setCfgWeight(0.5);
onAdded();
} catch (e) {
setFeedback({ ok: false, text: e instanceof UploadAborted ? "Envio cancelado. Nada foi salvo." : e instanceof Error ? e.message : String(e) });
} finally {
abortRef.current = null;
setPhase({ kind: "idle" });
}
}
const progress = phase.kind === "uploading" && phase.progress ? phase.progress : null;
return (
<form className="grid gap-6" onSubmit={(e) => { e.preventDefault(); void submit(e.currentTarget); }}>
{!cloneInstalled && (
<Feedback ok={false}>
A clonagem não está instalada. Rode <code>setup.bat -Clone</code> (baixa cerca de 4 GB: torch + Chatterbox) e reinicie o <code>start.bat</code>.
</Feedback>
)}
<ul className="grid gap-1 text-xs leading-relaxed text-fg-subtle">
<li>• Grave <span className="text-fg-muted">10 a 30 segundos</span> de fala natural, sem música nem eco, uma pessoa só.</li>
<li>• A voz clonada fala qualquer texto em português; a primeira fala demora mais (o modelo carrega na placa).</li>
</ul>
<fieldset disabled={!cloneInstalled || busy} className="grid gap-6 disabled:opacity-60">
<legend className="sr-only">Dados da voz clonada</legend>
<div className="grid gap-5 md:grid-cols-2">
<Field label="Nome">
<Input name="name" required maxLength={60} placeholder="Ex.: Narrador (minha voz)" />
</Field>
<ChoiceGroup name="cloneGender" legend="Voz" value={gender} onChange={setGender}
options={[{ value: "female", label: "Feminina" }, { value: "male", label: "Masculina" }]} />
<Field label="Gravação (10–30 s)" hint="WAV, MP3, OGG, M4A, FLAC ou WebM, até 30 MB.">
<Input type="file" name="audio" required accept=".wav,.mp3,.ogg,.m4a,.flac,.webm,.opus,audio/*" />
</Field>
<Field label="Descrição (opcional)">
<Input name="description" maxLength={200} placeholder="Ex.: tom calmo, para narração" />
</Field>
<RangeField label="Expressividade" hint="Mais alto = mais emoção e ênfase." min={0.25} max={1.5} step={0.05}
value={exaggeration} onChange={setExaggeration} format={fmt} />
<RangeField label="Fidelidade ao ritmo" hint="Mais baixo = fala mais solta e lenta." min={0} max={1} step={0.05}
value={cfgWeight} onChange={setCfgWeight} format={fmt} />
</div>
<Field label="De quem é a voz" hint="Ex.: minha própria voz; locutor Fulano, com autorização por escrito em 16/11/2026.">
<Input name="source" required maxLength={200} />
</Field>
<label className="flex items-start gap-3 rounded-control border border-warning/25 bg-warning-soft px-3 py-2.5 text-sm">
<input type="checkbox" name="consent" required className="mt-0.5 size-4 accent-accent" />
<span className="grid gap-0.5">
<span className="font-medium text-fg">A pessoa desta gravação autorizou clonar e usar a voz dela.</span>
<span className="flex items-start gap-1.5 text-xs text-warning">
<AlertIcon size={14} className="mt-0.5" />
Não clone voz de famoso, dublador ou personagem sem autorização. Todo áudio gerado leva marca d’água inaudível (Chatterbox).
</span>
</span>
</label>
</fieldset>
<div className="flex flex-wrap items-center gap-3">
<Button type="submit" disabled={!cloneInstalled || busy}>
<UploadIcon size={16} />{phase.kind === "processing" ? "Salvando…" : busy ? "Enviando…" : "Clonar voz"}
</Button>
{busy && abortRef.current && <Button type="button" variant="ghost" onClick={() => abortRef.current?.()}>Cancelar</Button>}
{progress && (
<div className="min-w-[12rem] flex-1">
<ProgressBar value={progress.loaded / progress.total} label={`${formatBytes(progress.loaded)} de ${formatBytes(progress.total)}`} />
</div>
)}
<div aria-live="polite" className="empty:hidden">{feedback && <Feedback ok={feedback.ok}>{feedback.text}</Feedback>}</div>
</div>
</form>
);
}
+537
View File
@@ -0,0 +1,537 @@
"use client";
// Página de vozes: lê /api/voice/status e distribui em abas — Geral (resumo, teste rápido, legenda),
// Catálogo (vozes e voz de personagem) e Serviço (estado detalhado e configurações). Os avisos de
// serviço offline/reinício ficam acima das abas, porque valem para todas.
// Depois de salvar as configurações, o serviço reinicia sozinho: consultamos o estado a cada 3 s até
// ele voltar (e enquanto houver download de modelo em andamento).
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import {
AlertIcon, CheckIcon, CpuIcon, DownloadIcon, GaugeIcon, ListIcon, MicIcon, PlayIcon, RefreshIcon, ServerIcon, SettingsIcon,
UploadIcon, WaveIcon,
} from "./icons";
import { DescribedSelect } from "./forms";
import { Tabs } from "./tabs";
import { Badge, Button, Card, ChoiceGroup, EmptyState, Feedback, Field, Input, RangeField, SectionHeader, Spinner, Textarea, cx } from "./ui";
import { VoiceList, useSynthesis } from "./voice-cards";
import { AddVoiceForm } from "./voice-add-form";
import { CloneVoiceForm } from "./voice-clone-form";
import { TranscribeTester } from "./voice-transcribe";
import {
PROVIDER_LABEL, SAMPLE_TEXT, STT_MODELS, errorMessage, voiceOptionLabel,
type Device, type SttModel, type VoiceInfo, type VoiceSettings, type VoiceStatus,
} from "./voice-client";
import { askConfirm } from "./confirm-dialog";
const POLL_MS = 3000;
/** Sem ver o serviço cair, consideramos o reinício feito depois deste tempo com ele no ar. */
const RESTART_GRACE_MS = 15_000;
/** Desiste de esperar o serviço voltar (o terminal do `pnpm dev` mostra o motivo). */
const RESTART_TIMEOUT_MS = 5 * 60_000;
type Restart = { since: number; sawOffline: boolean; download: boolean; timedOut: boolean };
type Notice = { ok: boolean; text: string };
/** initialText: texto que chega pelo link ?text= (ex.: a narração do roteiro) e preenche o teste de voz. */
export function VoiceStudio({ initialText }: { initialText?: string } = {}) {
const [status, setStatus] = useState<VoiceStatus | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [refreshing, setRefreshing] = useState(false);
const [restart, setRestart] = useState<Restart | null>(null);
// Espelho do reinício para o refresh (chamado pelo intervalo) ler o valor atual sem recriar a função.
const restartRef = useRef<Restart | null>(null);
const updateRestart = useCallback((value: Restart | null) => { restartRef.current = value; setRestart(value); }, []);
const [notice, setNotice] = useState<Notice | null>(null);
const refresh = useCallback(async () => {
setRefreshing(true);
try {
const r = await fetch("/api/voice/status", { cache: "no-store" });
if (!r.ok) throw new Error(await errorMessage(r));
const next = (await r.json()) as VoiceStatus;
setStatus(next);
setLoadError(null);
const prev = restartRef.current;
if (prev && !prev.timedOut) {
const elapsed = Date.now() - prev.since;
const sawOffline = prev.sawOffline || !next.online;
const downloading = next.job?.status === "running";
if (next.online && !downloading && (sawOffline || elapsed > RESTART_GRACE_MS)) {
updateRestart(null);
setNotice({ ok: true, text: "O serviço de voz voltou com as novas configurações." });
} else {
updateRestart({ ...prev, sawOffline, timedOut: !downloading && elapsed > RESTART_TIMEOUT_MS });
}
}
} catch (e) {
setLoadError(e instanceof Error ? e.message : String(e));
} finally {
setRefreshing(false);
}
}, [updateRestart]);
useEffect(() => { void refresh(); }, [refresh]);
const polling = status?.job?.status === "running" || (restart !== null && !restart.timedOut);
useEffect(() => {
if (!polling) return;
const timer = setInterval(() => void refresh(), POLL_MS);
return () => clearInterval(timer);
}, [polling, refresh]);
function onSettingsSaved(download: boolean, model: string) {
setNotice({
ok: true,
text: download
? `Configurações salvas. O Whisper ${model} será baixado antes; depois o serviço de voz reinicia sozinho.`
: "Configurações salvas. O serviço de voz reinicia sozinho em alguns segundos.",
});
updateRestart({ since: Date.now(), sawOffline: false, download, timedOut: false });
void refresh();
}
if (!status) {
return loadError ? (
<Card>
<div className="grid justify-items-start gap-4">
<Feedback ok={false}>Não foi possível ler o estado do serviço de voz: {loadError}</Feedback>
<Button variant="secondary" onClick={() => void refresh()} disabled={refreshing}>
{refreshing ? <Spinner /> : <RefreshIcon size={16} />}Tentar de novo
</Button>
</div>
</Card>
) : (
<div role="status" className="flex items-center gap-3 text-sm text-fg-muted"><Spinner />Consultando o serviço de voz…</div>
);
}
const baseVoices = status.voices.filter((v) => !v.user);
const userCount = status.voices.length - baseVoices.length;
const restarting = restart !== null && !restart.timedOut;
const refreshButton = (
<Button variant="ghost" size="sm" onClick={() => void refresh()} disabled={refreshing} aria-label="Atualizar o estado do serviço">
{refreshing ? <Spinner className="size-3.5" /> : <RefreshIcon size={15} />}Atualizar
</Button>
);
return (
<div className="grid gap-6">
<StatusAlerts status={status} loadError={loadError} restart={restart} notice={notice} />
<Tabs label="Seções da página de vozes"
items={[
{ id: "geral", label: "Geral", icon: <GaugeIcon size={16} /> },
{ id: "catalogo", label: "Catálogo", icon: <ListIcon size={16} />, count: status.voices.length },
{ id: "servico", label: "Serviço", icon: <ServerIcon size={16} /> },
]}
panels={{
geral: <>
<Overview status={status} baseCount={baseVoices.length} userCount={userCount} action={refreshButton} />
<Card eyebrow={<><PlayIcon size={13} />Teste rápido</>} title="Ouvir uma voz"
description="Escolha a voz, escreva a frase e ouça. Cada voz também tem o próprio teste na lista da aba Catálogo.">
<QuickTest voices={status.voices} online={status.online} initialText={initialText} />
</Card>
<Card eyebrow={<><WaveIcon size={13} />Legenda</>} title="Testar legenda"
description="Envie um áudio e veja a transcrição com os tempos de cada frase ou palavra. Com tempos, sai também o arquivo .srt.">
<TranscribeTester online={status.online} model={status.settings.sttModel} />
</Card>
</>,
catalogo: <>
<section aria-labelledby="vozes" className="grid gap-5">
<SectionHeader id="vozes" title="Vozes"
description="Filtre por tipo, gênero ou conexão, ou busque pelo nome; escreva uma frase e ouça na própria linha. Vozes online (Edge, Google) precisam de internet e demoram mais; Kokoro e Piper funcionam offline." />
<VoiceList voices={status.voices} online={status.online} onChanged={() => void refresh()} />
</section>
<Card eyebrow={<><UploadIcon size={13} />Personagem</>}
title={<span id="adicionar-voz" className="scroll-mt-8">Adicionar voz de personagem</span>}
description="Uma voz base transformada por um modelo RVC (.pth). O modelo fica em data/voice/models/rvc/ com a origem e a licença registradas.">
<AddVoiceForm baseVoices={baseVoices} applioInstalled={status.applioInstalled} rvcEnabled={status.settings.enableRvc}
onAdded={() => void refresh()} />
</Card>
<Card eyebrow={<><MicIcon size={13} />Clonagem</>}
title={<span id="clonar-voz" className="scroll-mt-8">Clonar voz</span>}
description="Cria uma voz nova a partir de 10–30 s de gravação (Chatterbox Multilingual, licença MIT). Roda no seu computador, na placa de vídeo.">
<CloneVoiceForm cloneInstalled={status.cloneInstalled} onAdded={() => void refresh()} />
</Card>
</>,
servico: <>
<ServiceDetails status={status} action={refreshButton} />
<Card eyebrow={<><SettingsIcon size={13} />Configurações</>} title="Dispositivo, transcrição e RVC"
description="Ficam em voice/.env. Ao salvar, o serviço de voz reinicia sozinho.">
<SettingsForm key={JSON.stringify(status.settings)} settings={status.settings} applioInstalled={status.applioInstalled}
restarting={restarting} onSaved={onSettingsSaved} />
</Card>
<Card eyebrow={<><ServerIcon size={13} />Azure Speech</>} title="Vozes neurais do Azure"
description="Opcional. Libera 14 vozes pt-BR muito naturais (Brenda, Fabio, Giovanna, Macerio…). A franquia grátis (F0) dá 0,5 milhão de caracteres por mês.">
<AzureForm key={`${status.settings.azureConfigured}-${status.settings.azureRegion}`} settings={status.settings}
restarting={restarting} onSaved={() => onSettingsSaved(false, "")} />
</Card>
</>,
}} />
</div>
);
}
/* ---------- Avisos acima das abas (valem para todas) ---------- */
function StatusAlerts({ status, loadError, restart, notice }: {
status: VoiceStatus; loadError: string | null; restart: Restart | null; notice: Notice | null;
}) {
const job = status.job;
const restarting = restart !== null && !restart.timedOut;
return (
<div aria-live="polite" className="grid gap-3 empty:hidden">
{!status.online && (
<div role="alert" className="grid gap-1.5 rounded-card border border-danger/30 bg-danger-soft px-5 py-4 text-sm">
<p className="flex items-start gap-2 font-semibold text-danger">
<AlertIcon size={16} className="mt-0.5" />
{restarting ? "Reiniciando o serviço de voz…" : "O serviço de voz está offline."}
</p>
{status.error && !restarting && <p className="font-mono text-xs break-words text-danger/90">{status.error}</p>}
<p className="text-fg-muted">
Rode <code>start.bat</code> (ou <code>pnpm dev</code>) para subir o painel com o serviço de voz. Se ainda não
instalou, rode <code>setup.bat</code> antes.
</p>
</div>
)}
{job && <JobLine job={job} />}
{restarting && (
<p role="status" className="flex flex-wrap items-center gap-2 text-sm text-info">
<Spinner className="size-3.5" />
{restart.download && job?.status === "running" ? "Baixando o modelo; o serviço reinicia em seguida." : "Aguardando o serviço de voz voltar…"}
<span className="text-fg-subtle">(consultando a cada 3 s)</span>
</p>
)}
{restart?.timedOut && (
<Feedback ok={false}>O serviço não voltou em 5 minutos. Confira o terminal do <code>pnpm dev</code> e clique em Atualizar.</Feedback>
)}
{notice && !restarting && <Feedback ok={notice.ok}>{notice.text}</Feedback>}
{loadError && <Feedback ok={false}>Falha ao atualizar o estado: {loadError}</Feedback>}
</div>
);
}
function JobLine({ job }: { job: NonNullable<VoiceStatus["job"]> }) {
const tone = job.status === "running" ? "info" : job.status === "done" ? "success" : "danger";
const label = job.status === "running" ? "baixando" : job.status === "done" ? "download concluído" : "download falhou";
return (
<p className={cx("flex flex-wrap items-center gap-2 text-sm", job.status === "error" ? "text-danger" : "text-fg-muted")}>
<Badge tone={tone} pulse={job.status === "running"}>{label}</Badge>
<span className="min-w-0 break-words">{job.message}</span>
</p>
);
}
/* ---------- Peças comuns ---------- */
const DEVICE_LABEL: Record<Device, string> = { auto: "automático", cuda: "GPU", cpu: "CPU" };
function deviceLabel(status: VoiceStatus): string | null {
const d = status.device;
if (!d) return null;
return d.kind === "cuda" ? `GPU${d.name ? ` · ${d.name}` : ""}` : "CPU";
}
function StatusItem({ icon, label, children }: { icon: ReactNode; label: string; children: ReactNode }) {
return (
<div className="grid content-start gap-1.5 rounded-control border border-line bg-surface px-4 py-3 shadow-card">
<dt className="flex items-center gap-1.5 text-eyebrow font-semibold uppercase text-fg-subtle">{icon}{label}</dt>
<dd className="text-sm">{children}</dd>
</div>
);
}
function Unknown() {
return <span className="text-fg-subtle">— (serviço offline)</span>;
}
function RvcState({ status }: { status: VoiceStatus }) {
return (
<>
{status.rvc === undefined
? <span className="text-fg">{status.settings.enableRvc ? "ligado nas configurações" : "desligado"}</span>
: <span className={status.rvc ? "text-success" : "text-fg"}>{status.rvc ? "ligado" : "desligado"}</span>}
{!status.applioInstalled && <span className="block text-xs text-fg-subtle">Applio não instalado</span>}
</>
);
}
/* ---------- Geral ---------- */
function Overview({ status, baseCount, userCount, action }: { status: VoiceStatus; baseCount: number; userCount: number; action: ReactNode }) {
const device = deviceLabel(status);
return (
<section aria-labelledby="resumo" className="grid gap-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<h2 id="resumo" className="text-title text-fg">Resumo</h2>
{action}
</div>
<dl className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
<StatusItem icon={<ServerIcon size={15} />} label="Serviço">
<span className="flex">{status.online ? <Badge tone="success">online</Badge> : <Badge tone="danger">offline</Badge>}</span>
<span className="mt-1.5 block text-xs text-fg-subtle">127.0.0.1 · no seu computador</span>
</StatusItem>
<StatusItem icon={<CpuIcon size={15} />} label="Dispositivo">
{device ? <span className="text-fg">{device}</span> : <Unknown />}
{status.device?.reason && <span className="block text-xs text-fg-subtle">{status.device.reason}</span>}
</StatusItem>
<StatusItem icon={<SettingsIcon size={15} />} label="RVC (personagens)">
<RvcState status={status} />
</StatusItem>
<StatusItem icon={<MicIcon size={15} />} label="Vozes">
{status.online || status.voices.length > 0 ? (
<span className="flex items-baseline gap-4">
<span><span className="font-display text-xl font-semibold text-fg tabular-nums">{baseCount}</span> <span className="text-xs text-fg-subtle">base</span></span>
<span><span className="font-display text-xl font-semibold text-fg tabular-nums">{userCount}</span> <span className="text-xs text-fg-subtle">personagem</span></span>
</span>
) : <Unknown />}
</StatusItem>
</dl>
</section>
);
}
function QuickTest({ voices, online, initialText }: { voices: VoiceInfo[]; online: boolean; initialText?: string }) {
const fallback = voices.find((v) => v.default)?.id ?? voices[0]?.id ?? "";
const [voiceId, setVoiceId] = useState(fallback);
const [text, setText] = useState(initialText || SAMPLE_TEXT);
const [speed, setSpeed] = useState(1);
const synth = useSynthesis();
// Se a voz escolhida sumir (removida, serviço caiu), volta para a padrão.
const current = voices.some((v) => v.id === voiceId) ? voiceId : fallback;
const voice = voices.find((v) => v.id === current);
if (voices.length === 0) {
return (
<EmptyState compact icon={<MicIcon size={18} />} title="Nenhuma voz para testar">
{online ? "O serviço não informou vozes." : "As vozes aparecem quando o serviço de voz estiver no ar."}
</EmptyState>
);
}
const canListen = online && text.trim().length > 0 && !synth.loading && Boolean(voice);
return (
<form className="grid gap-5 lg:grid-cols-[minmax(0,1fr)_minmax(0,2fr)]"
onSubmit={(e) => { e.preventDefault(); if (canListen) void synth.speak(current, text, speed); }}>
<div className="grid content-start gap-5">
<DescribedSelect name="quickVoice" label="Voz" value={current} onChange={setVoiceId}
options={voices.map((v) => ({
value: v.id,
label: voiceOptionLabel(v, v.user ? " · personagem" : ""),
description: v.description ?? `${PROVIDER_LABEL[v.provider] ?? v.provider} · ${v.offline ? "funciona offline" : "precisa de internet"}`,
}))} />
<RangeField label="Velocidade" min={0.5} max={2} step={0.05} value={speed} onChange={setSpeed}
format={(v) => `${v.toLocaleString("pt-BR", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}×`} />
</div>
<div className="grid content-start gap-3">
<label className="grid gap-2">
<span className="text-[0.8125rem] font-medium text-fg-muted">Texto</span>
<Textarea rows={initialText ? 10 : 3} value={text} maxLength={2000} onChange={(e) => setText(e.target.value)} />
</label>
<div className="flex flex-wrap items-center gap-3">
<Button type="submit" disabled={!canListen}>
{synth.loading ? <><Spinner />Gerando…</> : <><PlayIcon size={16} />Ouvir</>}
</Button>
{!online && <span className="text-xs text-fg-subtle">Para ouvir, o serviço de voz precisa estar no ar.</span>}
</div>
<div aria-live="polite" className="grid gap-2 empty:hidden">
{synth.error && <Feedback ok={false}>{synth.error}</Feedback>}
{synth.audioUrl && !synth.error && (
<audio key={synth.audioUrl} src={synth.audioUrl} controls autoPlay className="h-10 w-full"
aria-label={voice ? `Amostra da voz ${voice.name}` : "Amostra de voz"} />
)}
</div>
</div>
</form>
);
}
/* ---------- Serviço ---------- */
function ServiceDetails({ status, action }: { status: VoiceStatus; action: ReactNode }) {
const installed = status.settings.sttModelsInstalled;
const device = deviceLabel(status);
return (
<Card eyebrow={<><ServerIcon size={13} />Serviço de voz</>}
title={<span className="flex flex-wrap items-center gap-3">
Estado detalhado
{status.online ? <Badge tone="success">online</Badge> : <Badge tone="danger">offline</Badge>}
</span>}
description="Narração (TTS), vozes de personagem (RVC) e transcrição, rodando no seu computador em 127.0.0.1."
actions={action}>
<dl className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
<StatusItem icon={<CpuIcon size={15} />} label="Dispositivo">
{device ? <span className="text-fg">{device}</span> : <Unknown />}
{status.device?.reason && <span className="block text-xs text-fg-subtle">Motivo: {status.device.reason}</span>}
<span className="block text-xs text-fg-subtle">Configurado: {DEVICE_LABEL[status.settings.device]}</span>
</StatusItem>
<StatusItem icon={<MicIcon size={15} />} label="Síntese (TTS)">
{status.engines ? <span className="font-mono text-[0.8125rem] break-all text-fg">{status.engines.tts}</span> : <Unknown />}
</StatusItem>
<StatusItem icon={<WaveIcon size={15} />} label="Transcrição">
{status.engines
? status.engines.transcribe
? <span className="font-mono text-[0.8125rem] break-all text-fg">{status.engines.transcribe}</span>
: <span className="text-fg-subtle">indisponível</span>
: <Unknown />}
<span className="block text-xs text-fg-subtle">Whisper configurado: {status.settings.sttModel}</span>
</StatusItem>
<StatusItem icon={<DownloadIcon size={15} />} label="Whisper instalado">
{installed.length > 0
? <span className="flex flex-wrap gap-1.5">{installed.map((m) => <Badge key={m} dot={false}>{m}</Badge>)}</span>
: <span className="text-fg-subtle">nenhum modelo</span>}
</StatusItem>
<StatusItem icon={<SettingsIcon size={15} />} label="RVC (personagens)">
<RvcState status={status} />
</StatusItem>
<StatusItem icon={<CheckIcon size={15} />} label="Applio">
{status.applioInstalled
? <span className="text-success">instalado</span>
: <><span className="text-fg">não instalado</span><span className="block text-xs text-fg-subtle">Rode <code>setup.bat</code> sem <code>-NoRvc</code>.</span></>}
</StatusItem>
</dl>
</Card>
);
}
function AzureForm({ settings, restarting, onSaved }: { settings: VoiceSettings; restarting: boolean; onSaved: () => void }) {
const [region, setRegion] = useState(settings.azureRegion);
const [key, setKey] = useState("");
const [pending, setPending] = useState(false);
const [error, setError] = useState<string | null>(null);
const dirty = key.trim() !== "" || region.trim().toLowerCase() !== settings.azureRegion;
async function send(body: Record<string, unknown>) {
setPending(true);
setError(null);
try {
const r = await fetch("/api/voice/azure", {
method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body),
});
if (!r.ok) throw new Error(await errorMessage(r));
setKey("");
onSaved();
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setPending(false);
}
}
return (
<form className="grid gap-5" onSubmit={(e) => { e.preventDefault(); void send({ region, key }); }}>
<ol className="grid list-decimal gap-1 pl-5 text-xs leading-relaxed text-fg-subtle">
<li>No portal do Azure, crie um recurso <span className="text-fg-muted">Fala (Speech)</span> no plano <span className="text-fg-muted">F0 (gratuito)</span>.</li>
<li>Em <span className="text-fg-muted">Chaves e ponto de extremidade</span>, copie a <span className="text-fg-muted">KEY 1</span> e a <span className="text-fg-muted">Localização/Região</span>.</li>
<li>Cole aqui e salve: o serviço reinicia e as vozes <span className="text-fg-muted">Azure</span> aparecem no Catálogo.</li>
</ol>
<div className="grid gap-4 md:grid-cols-[minmax(0,14rem)_minmax(0,1fr)]">
<Field label="Região" hint="Ex.: eastus, brazilsouth, westeurope.">
<Input value={region} onChange={(e) => setRegion(e.target.value)} autoComplete="off" spellCheck={false} required />
</Field>
<Field label="Chave (KEY 1)"
hint={settings.azureConfigured ? "Já há uma chave salva. Deixe vazio para mantê-la." : "Fica só no voice/.env deste computador."}>
<Input type="password" value={key} onChange={(e) => setKey(e.target.value)} autoComplete="off" spellCheck={false}
placeholder={settings.azureConfigured ? "•••••••• (salva)" : "Cole a chave"} />
</Field>
</div>
<div className="flex flex-wrap items-center gap-3">
<Button type="submit" disabled={pending || !dirty || restarting}>
{pending ? <><Spinner />Salvando…</> : "Salvar e reiniciar o serviço"}
</Button>
{settings.azureConfigured && (
<Button type="button" variant="ghost" disabled={pending || restarting}
onClick={async () => {
if (await askConfirm({ title: "Apagar a chave do Azure?", message: "As vozes Azure saem da lista.",
confirmLabel: "Remover chave", tone: "danger" })) void send({ region, clear: true });
}}>
Remover chave
</Button>
)}
<span className="text-xs">
{settings.azureConfigured
? <span className="text-success">Configurado · {settings.azureRegion}</span>
: <span className="text-fg-subtle">Não configurado: as vozes Azure ficam escondidas.</span>}
</span>
<div aria-live="polite" className="empty:hidden">{error && <Feedback ok={false}>{error}</Feedback>}</div>
</div>
</form>
);
}
function SettingsForm({ settings, applioInstalled, restarting, onSaved }: {
settings: VoiceSettings; applioInstalled: boolean; restarting: boolean; onSaved: (download: boolean, model: string) => void;
}) {
const [device, setDevice] = useState<Device>(settings.device);
const [sttModel, setSttModel] = useState<SttModel>(settings.sttModel);
const [enableRvc, setEnableRvc] = useState(settings.enableRvc);
const [pending, setPending] = useState(false);
const [error, setError] = useState<string | null>(null);
const installed = new Set(settings.sttModelsInstalled);
const dirty = device !== settings.device || sttModel !== settings.sttModel || enableRvc !== settings.enableRvc;
async function save() {
setPending(true);
setError(null);
try {
const r = await fetch("/api/voice/settings", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ device, sttModel, enableRvc }),
});
if (!r.ok) throw new Error(await errorMessage(r));
const body = (await r.json()) as { download?: boolean };
onSaved(Boolean(body.download), sttModel);
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setPending(false);
}
}
return (
<form className="grid gap-6" onSubmit={(e) => { e.preventDefault(); void save(); }}>
<div className="grid gap-6 md:grid-cols-2">
<div className="grid content-start gap-2">
<ChoiceGroup name="device" legend="Dispositivo" value={device} onChange={setDevice}
options={[{ value: "auto", label: "Automático" }, { value: "cuda", label: "GPU" }, { value: "cpu", label: "CPU" }]} />
<p className="text-xs leading-relaxed text-fg-subtle">Se a placa estiver ocupada com um jogo, a CPU fica mais rápida.</p>
</div>
<DescribedSelect name="sttModel" label="Modelo do Whisper (transcrição)" value={sttModel} onChange={setSttModel}
options={STT_MODELS.map((m) => ({
value: m.id,
label: `${m.id} · ${m.size}${installed.has(m.id) ? " · instalado" : ""}`,
description: installed.has(m.id)
? <>{m.size}, <span className="text-success">instalado</span>: {m.note}.</>
: <span className="text-warning">{m.size}, ainda não instalado: ao salvar, ele é baixado antes de o serviço reiniciar ({m.note}).</span>,
}))} />
</div>
<label className={cx("flex items-start gap-3 text-sm", !applioInstalled && "opacity-60")}>
<input type="checkbox" checked={enableRvc} onChange={(e) => setEnableRvc(e.target.checked)}
disabled={!applioInstalled && !enableRvc} className="mt-0.5 size-4 accent-accent" />
<span className="grid gap-0.5">
<span className="font-medium text-fg">Ligar o RVC (vozes de personagem)</span>
<span className="text-xs text-fg-subtle">
{applioInstalled
? "Converte a voz base no timbre do personagem. Usa mais memória da placa."
: <>O Applio não está instalado: rode <code>setup.bat</code> sem <code>-NoRvc</code> para poder ligar.</>}
</span>
</span>
</label>
<div className="flex flex-wrap items-center gap-3">
<Button type="submit" disabled={pending || !dirty || restarting}>
{pending ? <><Spinner />Salvando…</> : "Salvar e reiniciar o serviço"}
</Button>
{!dirty && !restarting && <span className="text-xs text-fg-subtle">Nada mudou.</span>}
{restarting && (
<span role="status" className="flex items-center gap-2 text-xs text-info">
<Spinner className="size-3" />Reiniciando o serviço de voz (consultando a cada 3 s)…
</span>
)}
<div aria-live="polite" className="empty:hidden">{error && <Feedback ok={false}>{error}</Feedback>}</div>
</div>
</form>
);
}
+178
View File
@@ -0,0 +1,178 @@
"use client";
// Teste de legenda: envia um áudio para /api/voice/transcribe e mostra texto, segmentos com tempo e o .srt.
// O servidor espera o job terminar, então a resposta pode levar minutos: mostramos o envio e um cronômetro.
import { useEffect, useRef, useState } from "react";
import { DownloadIcon, UploadIcon } from "./icons";
import { Badge, Button, ChoiceGroup, Feedback, Field, Input, ProgressBar, Spinner, THead, Table, Td, Th, Tr } from "./ui";
import {
UploadAborted, downloadText, formatBytes, formatElapsed, formatTimestamp, uploadError, uploadWithProgress,
type TranscribeDetail, type TranscribeLanguage, type TranscribeResult, type UploadProgress,
} from "./voice-client";
const LANGUAGE_OPTIONS: { value: TranscribeLanguage; label: string }[] = [
{ value: "pt-BR", label: "Português" },
{ value: "en", label: "Inglês" },
{ value: "es", label: "Espanhol" },
];
const DETAIL_OPTIONS: { value: TranscribeDetail; label: string; hint: string }[] = [
{ value: "text", label: "Texto", hint: "só a transcrição" },
{ value: "segments", label: "Frases", hint: "com tempos (.srt)" },
{ value: "words", label: "Palavras", hint: "tempo de cada palavra" },
];
type Phase = { kind: "idle" } | { kind: "uploading"; progress: UploadProgress | null } | { kind: "transcribing"; since: number };
export function TranscribeTester({ online, model }: { online: boolean; model: string }) {
const [language, setLanguage] = useState<TranscribeLanguage>("pt-BR");
const [detail, setDetail] = useState<TranscribeDetail>("segments");
const [phase, setPhase] = useState<Phase>({ kind: "idle" });
const [elapsed, setElapsed] = useState(0);
const [result, setResult] = useState<{ data: TranscribeResult; fileName: string } | null>(null);
const [error, setError] = useState<string | null>(null);
const abortRef = useRef<(() => void) | null>(null);
// Cronômetro enquanto o serviço transcreve.
useEffect(() => {
if (phase.kind !== "transcribing") return;
const tick = () => setElapsed(Math.round((Date.now() - phase.since) / 1000));
tick();
const timer = setInterval(tick, 1000);
return () => clearInterval(timer);
}, [phase]);
async function submit(form: HTMLFormElement) {
const data = new FormData(form);
const file = data.get("file");
if (!(file instanceof File) || file.size === 0) return setError("Escolha um arquivo de áudio.");
data.set("language", language);
data.set("detail", detail);
setError(null);
setResult(null);
setPhase({ kind: "uploading", progress: null });
const upload = uploadWithProgress("/api/voice/transcribe", data,
(progress) => setPhase({ kind: "uploading", progress }),
() => setPhase({ kind: "transcribing", since: Date.now() }));
abortRef.current = upload.abort;
try {
const response = await upload.promise;
if (response.status >= 400) throw new Error(uploadError(response));
setResult({ data: response.body as TranscribeResult, fileName: file.name });
} catch (e) {
setError(e instanceof UploadAborted ? "Transcrição cancelada." : e instanceof Error ? e.message : String(e));
} finally {
abortRef.current = null;
setPhase({ kind: "idle" });
}
}
const busy = phase.kind !== "idle";
const progress = phase.kind === "uploading" ? phase.progress : null;
return (
<div className="grid gap-6">
<form className="grid gap-5" onSubmit={(e) => { e.preventDefault(); void submit(e.currentTarget); }}>
<fieldset disabled={busy || !online} className="grid gap-5 disabled:opacity-60 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_minmax(0,1.2fr)]">
<legend className="sr-only">Áudio para transcrever</legend>
<Field label="Arquivo de áudio" hint="WAV, MP3, OGG, M4A, FLAC…">
<Input name="file" type="file" required accept="audio/*,.wav,.mp3,.ogg,.opus,.m4a,.flac,.webm" />
</Field>
<ChoiceGroup name="language" legend="Idioma" value={language} onChange={setLanguage} options={LANGUAGE_OPTIONS} />
<ChoiceGroup name="detail" legend="Detalhe" value={detail} onChange={setDetail} options={DETAIL_OPTIONS} />
</fieldset>
<div className="flex flex-wrap items-center gap-3">
<Button type="submit" variant="secondary" disabled={busy || !online}>
{busy ? <><Spinner />Transcrevendo…</> : <><UploadIcon size={16} />Transcrever</>}
</Button>
{busy && <Button type="button" variant="ghost" onClick={() => abortRef.current?.()}>Cancelar</Button>}
<p className="text-xs text-fg-subtle">
{online
? <>Pode levar alguns minutos: roda no seu computador, com o Whisper <code>{model}</code>.</>
: "O serviço de voz está offline."}
</p>
</div>
</form>
<div aria-live="polite" className="grid gap-4 empty:hidden">
{phase.kind === "uploading" && (
<div className="grid max-w-xl gap-2">
<ProgressBar label="Envio do áudio" value={progress ? progress.loaded / progress.total : 0} />
<p className="text-xs text-fg-muted tabular-nums">
{progress ? `Enviando ${formatBytes(progress.loaded)} de ${formatBytes(progress.total)}` : "Preparando o envio…"}
</p>
</div>
)}
{phase.kind === "transcribing" && (
<div className="grid max-w-xl gap-2">
<ProgressBar label="Transcrição em andamento" />
<p className="text-xs text-fg-muted tabular-nums">Transcrevendo há {formatElapsed(elapsed)}. Pode deixar a página aberta.</p>
</div>
)}
{error && <Feedback ok={false}>{error}</Feedback>}
{result && <TranscribeOutput result={result.data} fileName={result.fileName} />}
</div>
</div>
);
}
function TranscribeOutput({ result, fileName }: { result: TranscribeResult; fileName: string }) {
const segments = result.segments ?? [];
const srtName = `${fileName.replace(/\.[^.]+$/, "") || "legenda"}.srt`;
const noSpeech = result.noSpeechProb >= 0.5;
return (
<section aria-label="Resultado da transcrição" className="grid gap-4 rounded-card border border-line bg-sunken/40 p-5">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex flex-wrap items-center gap-2">
<Badge tone="success">pronto</Badge>
{result.durationS !== undefined && <Badge dot={false}>{formatTimestamp(result.durationS)} de áudio</Badge>}
{segments.length > 0 && <Badge dot={false}>{segments.length} {segments.length === 1 ? "frase" : "frases"}</Badge>}
{noSpeech && <Badge tone="warning">pode não haver fala ({Math.round(result.noSpeechProb * 100)}%)</Badge>}
</div>
{result.srt && (
<Button type="button" variant="primary" size="sm" onClick={() => downloadText(srtName, result.srt!, "application/x-subrip;charset=utf-8")}>
<DownloadIcon size={15} />Baixar {srtName}
</Button>
)}
</div>
<div className="grid gap-1.5">
<h3 className="text-eyebrow font-semibold uppercase text-fg-subtle">Texto</h3>
<p className="text-[0.9375rem] leading-relaxed whitespace-pre-wrap text-fg">{result.text || <span className="text-fg-subtle">(sem texto reconhecido)</span>}</p>
</div>
{segments.length > 0 && (
<Table className="max-h-[28rem] overflow-y-auto">
<THead>
<Th className="w-12">#</Th>
<Th className="w-28">Início</Th>
<Th className="w-28">Fim</Th>
<Th>Texto</Th>
</THead>
<tbody>
{segments.map((seg, i) => (
<Tr key={i}>
<Td className="font-mono text-xs text-fg-subtle tabular-nums">{i + 1}</Td>
<Td className="font-mono text-xs tabular-nums">{formatTimestamp(seg.start)}</Td>
<Td className="font-mono text-xs tabular-nums">{formatTimestamp(seg.end)}</Td>
<Td>
{seg.words && seg.words.length > 0 ? (
<span className="flex flex-wrap gap-x-1 gap-y-1">
{seg.words.map((w, j) => (
<span key={j} title={`${formatTimestamp(w.start)} → ${formatTimestamp(w.end)} · confiança ${Math.round(w.p * 100)}%`}
className={w.p < 0.5 ? "rounded bg-warning-soft px-0.5 text-warning" : "text-fg"}>
{w.text.trim()}
</span>
))}
</span>
) : <span className="text-fg">{seg.text.trim()}</span>}
</Td>
</Tr>
))}
</tbody>
</Table>
)}
{segments.some((s) => s.words?.length) && (
<p className="text-xs text-fg-subtle">Palavras com fundo amarelo têm confiança abaixo de 50%. Passe o mouse para ver o tempo de cada uma.</p>
)}
</section>
);
}